1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/SaveAndRestore.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <bitset> 92 #include <cassert> 93 #include <cstddef> 94 #include <cstdint> 95 #include <functional> 96 #include <limits> 97 #include <string> 98 #include <tuple> 99 #include <utility> 100 101 using namespace clang; 102 using namespace sema; 103 104 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 105 unsigned ByteNo) const { 106 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 107 Context.getTargetInfo()); 108 } 109 110 /// Checks that a call expression's argument count is the desired number. 111 /// This is useful when doing custom type-checking. Returns true on error. 112 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 113 unsigned argCount = call->getNumArgs(); 114 if (argCount == desiredArgCount) return false; 115 116 if (argCount < desiredArgCount) 117 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 118 << 0 /*function call*/ << desiredArgCount << argCount 119 << call->getSourceRange(); 120 121 // Highlight all the excess arguments. 122 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 123 call->getArg(argCount - 1)->getEndLoc()); 124 125 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 126 << 0 /*function call*/ << desiredArgCount << argCount 127 << call->getArg(1)->getSourceRange(); 128 } 129 130 /// Check that the first argument to __builtin_annotation is an integer 131 /// and the second argument is a non-wide string literal. 132 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 133 if (checkArgCount(S, TheCall, 2)) 134 return true; 135 136 // First argument should be an integer. 137 Expr *ValArg = TheCall->getArg(0); 138 QualType Ty = ValArg->getType(); 139 if (!Ty->isIntegerType()) { 140 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 141 << ValArg->getSourceRange(); 142 return true; 143 } 144 145 // Second argument should be a constant string. 146 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 147 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 148 if (!Literal || !Literal->isAscii()) { 149 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 150 << StrArg->getSourceRange(); 151 return true; 152 } 153 154 TheCall->setType(Ty); 155 return false; 156 } 157 158 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 159 // We need at least one argument. 160 if (TheCall->getNumArgs() < 1) { 161 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 162 << 0 << 1 << TheCall->getNumArgs() 163 << TheCall->getCallee()->getSourceRange(); 164 return true; 165 } 166 167 // All arguments should be wide string literals. 168 for (Expr *Arg : TheCall->arguments()) { 169 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 170 if (!Literal || !Literal->isWide()) { 171 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 172 << Arg->getSourceRange(); 173 return true; 174 } 175 } 176 177 return false; 178 } 179 180 /// Check that the argument to __builtin_addressof is a glvalue, and set the 181 /// result type to the corresponding pointer type. 182 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 183 if (checkArgCount(S, TheCall, 1)) 184 return true; 185 186 ExprResult Arg(TheCall->getArg(0)); 187 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 188 if (ResultType.isNull()) 189 return true; 190 191 TheCall->setArg(0, Arg.get()); 192 TheCall->setType(ResultType); 193 return false; 194 } 195 196 /// Check the number of arguments and set the result type to 197 /// the argument type. 198 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 199 if (checkArgCount(S, TheCall, 1)) 200 return true; 201 202 TheCall->setType(TheCall->getArg(0)->getType()); 203 return false; 204 } 205 206 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 207 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 208 /// type (but not a function pointer) and that the alignment is a power-of-two. 209 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 210 if (checkArgCount(S, TheCall, 2)) 211 return true; 212 213 clang::Expr *Source = TheCall->getArg(0); 214 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 215 216 auto IsValidIntegerType = [](QualType Ty) { 217 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 218 }; 219 QualType SrcTy = Source->getType(); 220 // We should also be able to use it with arrays (but not functions!). 221 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 222 SrcTy = S.Context.getDecayedType(SrcTy); 223 } 224 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 225 SrcTy->isFunctionPointerType()) { 226 // FIXME: this is not quite the right error message since we don't allow 227 // floating point types, or member pointers. 228 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 229 << SrcTy; 230 return true; 231 } 232 233 clang::Expr *AlignOp = TheCall->getArg(1); 234 if (!IsValidIntegerType(AlignOp->getType())) { 235 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 236 << AlignOp->getType(); 237 return true; 238 } 239 Expr::EvalResult AlignResult; 240 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 241 // We can't check validity of alignment if it is value dependent. 242 if (!AlignOp->isValueDependent() && 243 AlignOp->EvaluateAsInt(AlignResult, S.Context, 244 Expr::SE_AllowSideEffects)) { 245 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 246 llvm::APSInt MaxValue( 247 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 248 if (AlignValue < 1) { 249 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 250 return true; 251 } 252 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 253 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 254 << MaxValue.toString(10); 255 return true; 256 } 257 if (!AlignValue.isPowerOf2()) { 258 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 259 return true; 260 } 261 if (AlignValue == 1) { 262 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 263 << IsBooleanAlignBuiltin; 264 } 265 } 266 267 ExprResult SrcArg = S.PerformCopyInitialization( 268 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 269 SourceLocation(), Source); 270 if (SrcArg.isInvalid()) 271 return true; 272 TheCall->setArg(0, SrcArg.get()); 273 ExprResult AlignArg = 274 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 275 S.Context, AlignOp->getType(), false), 276 SourceLocation(), AlignOp); 277 if (AlignArg.isInvalid()) 278 return true; 279 TheCall->setArg(1, AlignArg.get()); 280 // For align_up/align_down, the return type is the same as the (potentially 281 // decayed) argument type including qualifiers. For is_aligned(), the result 282 // is always bool. 283 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 284 return false; 285 } 286 287 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 288 unsigned BuiltinID) { 289 if (checkArgCount(S, TheCall, 3)) 290 return true; 291 292 // First two arguments should be integers. 293 for (unsigned I = 0; I < 2; ++I) { 294 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 295 if (Arg.isInvalid()) return true; 296 TheCall->setArg(I, Arg.get()); 297 298 QualType Ty = Arg.get()->getType(); 299 if (!Ty->isIntegerType()) { 300 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 301 << Ty << Arg.get()->getSourceRange(); 302 return true; 303 } 304 } 305 306 // Third argument should be a pointer to a non-const integer. 307 // IRGen correctly handles volatile, restrict, and address spaces, and 308 // the other qualifiers aren't possible. 309 { 310 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 311 if (Arg.isInvalid()) return true; 312 TheCall->setArg(2, Arg.get()); 313 314 QualType Ty = Arg.get()->getType(); 315 const auto *PtrTy = Ty->getAs<PointerType>(); 316 if (!PtrTy || 317 !PtrTy->getPointeeType()->isIntegerType() || 318 PtrTy->getPointeeType().isConstQualified()) { 319 S.Diag(Arg.get()->getBeginLoc(), 320 diag::err_overflow_builtin_must_be_ptr_int) 321 << Ty << Arg.get()->getSourceRange(); 322 return true; 323 } 324 } 325 326 // Disallow signed ExtIntType args larger than 128 bits to mul function until 327 // we improve backend support. 328 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 329 for (unsigned I = 0; I < 3; ++I) { 330 const auto Arg = TheCall->getArg(I); 331 // Third argument will be a pointer. 332 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 333 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 334 S.getASTContext().getIntWidth(Ty) > 128) 335 return S.Diag(Arg->getBeginLoc(), 336 diag::err_overflow_builtin_ext_int_max_size) 337 << 128; 338 } 339 } 340 341 return false; 342 } 343 344 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 345 if (checkArgCount(S, BuiltinCall, 2)) 346 return true; 347 348 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 349 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 350 Expr *Call = BuiltinCall->getArg(0); 351 Expr *Chain = BuiltinCall->getArg(1); 352 353 if (Call->getStmtClass() != Stmt::CallExprClass) { 354 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 355 << Call->getSourceRange(); 356 return true; 357 } 358 359 auto CE = cast<CallExpr>(Call); 360 if (CE->getCallee()->getType()->isBlockPointerType()) { 361 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 362 << Call->getSourceRange(); 363 return true; 364 } 365 366 const Decl *TargetDecl = CE->getCalleeDecl(); 367 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 368 if (FD->getBuiltinID()) { 369 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 370 << Call->getSourceRange(); 371 return true; 372 } 373 374 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 375 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 376 << Call->getSourceRange(); 377 return true; 378 } 379 380 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 381 if (ChainResult.isInvalid()) 382 return true; 383 if (!ChainResult.get()->getType()->isPointerType()) { 384 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 385 << Chain->getSourceRange(); 386 return true; 387 } 388 389 QualType ReturnTy = CE->getCallReturnType(S.Context); 390 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 391 QualType BuiltinTy = S.Context.getFunctionType( 392 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 393 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 394 395 Builtin = 396 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 397 398 BuiltinCall->setType(CE->getType()); 399 BuiltinCall->setValueKind(CE->getValueKind()); 400 BuiltinCall->setObjectKind(CE->getObjectKind()); 401 BuiltinCall->setCallee(Builtin); 402 BuiltinCall->setArg(1, ChainResult.get()); 403 404 return false; 405 } 406 407 namespace { 408 409 class EstimateSizeFormatHandler 410 : public analyze_format_string::FormatStringHandler { 411 size_t Size; 412 413 public: 414 EstimateSizeFormatHandler(StringRef Format) 415 : Size(std::min(Format.find(0), Format.size()) + 416 1 /* null byte always written by sprintf */) {} 417 418 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 419 const char *, unsigned SpecifierLen) override { 420 421 const size_t FieldWidth = computeFieldWidth(FS); 422 const size_t Precision = computePrecision(FS); 423 424 // The actual format. 425 switch (FS.getConversionSpecifier().getKind()) { 426 // Just a char. 427 case analyze_format_string::ConversionSpecifier::cArg: 428 case analyze_format_string::ConversionSpecifier::CArg: 429 Size += std::max(FieldWidth, (size_t)1); 430 break; 431 // Just an integer. 432 case analyze_format_string::ConversionSpecifier::dArg: 433 case analyze_format_string::ConversionSpecifier::DArg: 434 case analyze_format_string::ConversionSpecifier::iArg: 435 case analyze_format_string::ConversionSpecifier::oArg: 436 case analyze_format_string::ConversionSpecifier::OArg: 437 case analyze_format_string::ConversionSpecifier::uArg: 438 case analyze_format_string::ConversionSpecifier::UArg: 439 case analyze_format_string::ConversionSpecifier::xArg: 440 case analyze_format_string::ConversionSpecifier::XArg: 441 Size += std::max(FieldWidth, Precision); 442 break; 443 444 // %g style conversion switches between %f or %e style dynamically. 445 // %f always takes less space, so default to it. 446 case analyze_format_string::ConversionSpecifier::gArg: 447 case analyze_format_string::ConversionSpecifier::GArg: 448 449 // Floating point number in the form '[+]ddd.ddd'. 450 case analyze_format_string::ConversionSpecifier::fArg: 451 case analyze_format_string::ConversionSpecifier::FArg: 452 Size += std::max(FieldWidth, 1 /* integer part */ + 453 (Precision ? 1 + Precision 454 : 0) /* period + decimal */); 455 break; 456 457 // Floating point number in the form '[-]d.ddde[+-]dd'. 458 case analyze_format_string::ConversionSpecifier::eArg: 459 case analyze_format_string::ConversionSpecifier::EArg: 460 Size += 461 std::max(FieldWidth, 462 1 /* integer part */ + 463 (Precision ? 1 + Precision : 0) /* period + decimal */ + 464 1 /* e or E letter */ + 2 /* exponent */); 465 break; 466 467 // Floating point number in the form '[-]0xh.hhhhp±dd'. 468 case analyze_format_string::ConversionSpecifier::aArg: 469 case analyze_format_string::ConversionSpecifier::AArg: 470 Size += 471 std::max(FieldWidth, 472 2 /* 0x */ + 1 /* integer part */ + 473 (Precision ? 1 + Precision : 0) /* period + decimal */ + 474 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 475 break; 476 477 // Just a string. 478 case analyze_format_string::ConversionSpecifier::sArg: 479 case analyze_format_string::ConversionSpecifier::SArg: 480 Size += FieldWidth; 481 break; 482 483 // Just a pointer in the form '0xddd'. 484 case analyze_format_string::ConversionSpecifier::pArg: 485 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 486 break; 487 488 // A plain percent. 489 case analyze_format_string::ConversionSpecifier::PercentArg: 490 Size += 1; 491 break; 492 493 default: 494 break; 495 } 496 497 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 498 499 if (FS.hasAlternativeForm()) { 500 switch (FS.getConversionSpecifier().getKind()) { 501 default: 502 break; 503 // Force a leading '0'. 504 case analyze_format_string::ConversionSpecifier::oArg: 505 Size += 1; 506 break; 507 // Force a leading '0x'. 508 case analyze_format_string::ConversionSpecifier::xArg: 509 case analyze_format_string::ConversionSpecifier::XArg: 510 Size += 2; 511 break; 512 // Force a period '.' before decimal, even if precision is 0. 513 case analyze_format_string::ConversionSpecifier::aArg: 514 case analyze_format_string::ConversionSpecifier::AArg: 515 case analyze_format_string::ConversionSpecifier::eArg: 516 case analyze_format_string::ConversionSpecifier::EArg: 517 case analyze_format_string::ConversionSpecifier::fArg: 518 case analyze_format_string::ConversionSpecifier::FArg: 519 case analyze_format_string::ConversionSpecifier::gArg: 520 case analyze_format_string::ConversionSpecifier::GArg: 521 Size += (Precision ? 0 : 1); 522 break; 523 } 524 } 525 assert(SpecifierLen <= Size && "no underflow"); 526 Size -= SpecifierLen; 527 return true; 528 } 529 530 size_t getSizeLowerBound() const { return Size; } 531 532 private: 533 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 534 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 535 size_t FieldWidth = 0; 536 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 537 FieldWidth = FW.getConstantAmount(); 538 return FieldWidth; 539 } 540 541 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 542 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 543 size_t Precision = 0; 544 545 // See man 3 printf for default precision value based on the specifier. 546 switch (FW.getHowSpecified()) { 547 case analyze_format_string::OptionalAmount::NotSpecified: 548 switch (FS.getConversionSpecifier().getKind()) { 549 default: 550 break; 551 case analyze_format_string::ConversionSpecifier::dArg: // %d 552 case analyze_format_string::ConversionSpecifier::DArg: // %D 553 case analyze_format_string::ConversionSpecifier::iArg: // %i 554 Precision = 1; 555 break; 556 case analyze_format_string::ConversionSpecifier::oArg: // %d 557 case analyze_format_string::ConversionSpecifier::OArg: // %D 558 case analyze_format_string::ConversionSpecifier::uArg: // %d 559 case analyze_format_string::ConversionSpecifier::UArg: // %D 560 case analyze_format_string::ConversionSpecifier::xArg: // %d 561 case analyze_format_string::ConversionSpecifier::XArg: // %D 562 Precision = 1; 563 break; 564 case analyze_format_string::ConversionSpecifier::fArg: // %f 565 case analyze_format_string::ConversionSpecifier::FArg: // %F 566 case analyze_format_string::ConversionSpecifier::eArg: // %e 567 case analyze_format_string::ConversionSpecifier::EArg: // %E 568 case analyze_format_string::ConversionSpecifier::gArg: // %g 569 case analyze_format_string::ConversionSpecifier::GArg: // %G 570 Precision = 6; 571 break; 572 case analyze_format_string::ConversionSpecifier::pArg: // %d 573 Precision = 1; 574 break; 575 } 576 break; 577 case analyze_format_string::OptionalAmount::Constant: 578 Precision = FW.getConstantAmount(); 579 break; 580 default: 581 break; 582 } 583 return Precision; 584 } 585 }; 586 587 } // namespace 588 589 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 590 /// __builtin_*_chk function, then use the object size argument specified in the 591 /// source. Otherwise, infer the object size using __builtin_object_size. 592 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 593 CallExpr *TheCall) { 594 // FIXME: There are some more useful checks we could be doing here: 595 // - Evaluate strlen of strcpy arguments, use as object size. 596 597 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 598 isConstantEvaluated()) 599 return; 600 601 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 602 if (!BuiltinID) 603 return; 604 605 const TargetInfo &TI = getASTContext().getTargetInfo(); 606 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 607 608 unsigned DiagID = 0; 609 bool IsChkVariant = false; 610 Optional<llvm::APSInt> UsedSize; 611 unsigned SizeIndex, ObjectIndex; 612 switch (BuiltinID) { 613 default: 614 return; 615 case Builtin::BIsprintf: 616 case Builtin::BI__builtin___sprintf_chk: { 617 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 618 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 619 620 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 621 622 if (!Format->isAscii() && !Format->isUTF8()) 623 return; 624 625 StringRef FormatStrRef = Format->getString(); 626 EstimateSizeFormatHandler H(FormatStrRef); 627 const char *FormatBytes = FormatStrRef.data(); 628 const ConstantArrayType *T = 629 Context.getAsConstantArrayType(Format->getType()); 630 assert(T && "String literal not of constant array type!"); 631 size_t TypeSize = T->getSize().getZExtValue(); 632 633 // In case there's a null byte somewhere. 634 size_t StrLen = 635 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 636 if (!analyze_format_string::ParsePrintfString( 637 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 638 Context.getTargetInfo(), false)) { 639 DiagID = diag::warn_fortify_source_format_overflow; 640 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 641 .extOrTrunc(SizeTypeWidth); 642 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 643 IsChkVariant = true; 644 ObjectIndex = 2; 645 } else { 646 IsChkVariant = false; 647 ObjectIndex = 0; 648 } 649 break; 650 } 651 } 652 return; 653 } 654 case Builtin::BI__builtin___memcpy_chk: 655 case Builtin::BI__builtin___memmove_chk: 656 case Builtin::BI__builtin___memset_chk: 657 case Builtin::BI__builtin___strlcat_chk: 658 case Builtin::BI__builtin___strlcpy_chk: 659 case Builtin::BI__builtin___strncat_chk: 660 case Builtin::BI__builtin___strncpy_chk: 661 case Builtin::BI__builtin___stpncpy_chk: 662 case Builtin::BI__builtin___memccpy_chk: 663 case Builtin::BI__builtin___mempcpy_chk: { 664 DiagID = diag::warn_builtin_chk_overflow; 665 IsChkVariant = true; 666 SizeIndex = TheCall->getNumArgs() - 2; 667 ObjectIndex = TheCall->getNumArgs() - 1; 668 break; 669 } 670 671 case Builtin::BI__builtin___snprintf_chk: 672 case Builtin::BI__builtin___vsnprintf_chk: { 673 DiagID = diag::warn_builtin_chk_overflow; 674 IsChkVariant = true; 675 SizeIndex = 1; 676 ObjectIndex = 3; 677 break; 678 } 679 680 case Builtin::BIstrncat: 681 case Builtin::BI__builtin_strncat: 682 case Builtin::BIstrncpy: 683 case Builtin::BI__builtin_strncpy: 684 case Builtin::BIstpncpy: 685 case Builtin::BI__builtin_stpncpy: { 686 // Whether these functions overflow depends on the runtime strlen of the 687 // string, not just the buffer size, so emitting the "always overflow" 688 // diagnostic isn't quite right. We should still diagnose passing a buffer 689 // size larger than the destination buffer though; this is a runtime abort 690 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 691 DiagID = diag::warn_fortify_source_size_mismatch; 692 SizeIndex = TheCall->getNumArgs() - 1; 693 ObjectIndex = 0; 694 break; 695 } 696 697 case Builtin::BImemcpy: 698 case Builtin::BI__builtin_memcpy: 699 case Builtin::BImemmove: 700 case Builtin::BI__builtin_memmove: 701 case Builtin::BImemset: 702 case Builtin::BI__builtin_memset: 703 case Builtin::BImempcpy: 704 case Builtin::BI__builtin_mempcpy: { 705 DiagID = diag::warn_fortify_source_overflow; 706 SizeIndex = TheCall->getNumArgs() - 1; 707 ObjectIndex = 0; 708 break; 709 } 710 case Builtin::BIsnprintf: 711 case Builtin::BI__builtin_snprintf: 712 case Builtin::BIvsnprintf: 713 case Builtin::BI__builtin_vsnprintf: { 714 DiagID = diag::warn_fortify_source_size_mismatch; 715 SizeIndex = 1; 716 ObjectIndex = 0; 717 break; 718 } 719 } 720 721 llvm::APSInt ObjectSize; 722 // For __builtin___*_chk, the object size is explicitly provided by the caller 723 // (usually using __builtin_object_size). Use that value to check this call. 724 if (IsChkVariant) { 725 Expr::EvalResult Result; 726 Expr *SizeArg = TheCall->getArg(ObjectIndex); 727 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 728 return; 729 ObjectSize = Result.Val.getInt(); 730 731 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 732 } else { 733 // If the parameter has a pass_object_size attribute, then we should use its 734 // (potentially) more strict checking mode. Otherwise, conservatively assume 735 // type 0. 736 int BOSType = 0; 737 if (const auto *POS = 738 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 739 BOSType = POS->getType(); 740 741 Expr *ObjArg = TheCall->getArg(ObjectIndex); 742 uint64_t Result; 743 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 744 return; 745 // Get the object size in the target's size_t width. 746 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 747 } 748 749 // Evaluate the number of bytes of the object that this call will use. 750 if (!UsedSize) { 751 Expr::EvalResult Result; 752 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 753 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 754 return; 755 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 756 } 757 758 if (UsedSize.getValue().ule(ObjectSize)) 759 return; 760 761 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 762 // Skim off the details of whichever builtin was called to produce a better 763 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 764 if (IsChkVariant) { 765 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 766 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 767 } else if (FunctionName.startswith("__builtin_")) { 768 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 769 } 770 771 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 772 PDiag(DiagID) 773 << FunctionName << ObjectSize.toString(/*Radix=*/10) 774 << UsedSize.getValue().toString(/*Radix=*/10)); 775 } 776 777 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 778 Scope::ScopeFlags NeededScopeFlags, 779 unsigned DiagID) { 780 // Scopes aren't available during instantiation. Fortunately, builtin 781 // functions cannot be template args so they cannot be formed through template 782 // instantiation. Therefore checking once during the parse is sufficient. 783 if (SemaRef.inTemplateInstantiation()) 784 return false; 785 786 Scope *S = SemaRef.getCurScope(); 787 while (S && !S->isSEHExceptScope()) 788 S = S->getParent(); 789 if (!S || !(S->getFlags() & NeededScopeFlags)) { 790 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 791 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 792 << DRE->getDecl()->getIdentifier(); 793 return true; 794 } 795 796 return false; 797 } 798 799 static inline bool isBlockPointer(Expr *Arg) { 800 return Arg->getType()->isBlockPointerType(); 801 } 802 803 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 804 /// void*, which is a requirement of device side enqueue. 805 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 806 const BlockPointerType *BPT = 807 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 808 ArrayRef<QualType> Params = 809 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 810 unsigned ArgCounter = 0; 811 bool IllegalParams = false; 812 // Iterate through the block parameters until either one is found that is not 813 // a local void*, or the block is valid. 814 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 815 I != E; ++I, ++ArgCounter) { 816 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 817 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 818 LangAS::opencl_local) { 819 // Get the location of the error. If a block literal has been passed 820 // (BlockExpr) then we can point straight to the offending argument, 821 // else we just point to the variable reference. 822 SourceLocation ErrorLoc; 823 if (isa<BlockExpr>(BlockArg)) { 824 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 825 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 826 } else if (isa<DeclRefExpr>(BlockArg)) { 827 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 828 } 829 S.Diag(ErrorLoc, 830 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 831 IllegalParams = true; 832 } 833 } 834 835 return IllegalParams; 836 } 837 838 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 839 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 840 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 841 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 842 return true; 843 } 844 return false; 845 } 846 847 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 848 if (checkArgCount(S, TheCall, 2)) 849 return true; 850 851 if (checkOpenCLSubgroupExt(S, TheCall)) 852 return true; 853 854 // First argument is an ndrange_t type. 855 Expr *NDRangeArg = TheCall->getArg(0); 856 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 857 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 858 << TheCall->getDirectCallee() << "'ndrange_t'"; 859 return true; 860 } 861 862 Expr *BlockArg = TheCall->getArg(1); 863 if (!isBlockPointer(BlockArg)) { 864 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 865 << TheCall->getDirectCallee() << "block"; 866 return true; 867 } 868 return checkOpenCLBlockArgs(S, BlockArg); 869 } 870 871 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 872 /// get_kernel_work_group_size 873 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 874 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 875 if (checkArgCount(S, TheCall, 1)) 876 return true; 877 878 Expr *BlockArg = TheCall->getArg(0); 879 if (!isBlockPointer(BlockArg)) { 880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 881 << TheCall->getDirectCallee() << "block"; 882 return true; 883 } 884 return checkOpenCLBlockArgs(S, BlockArg); 885 } 886 887 /// Diagnose integer type and any valid implicit conversion to it. 888 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 889 const QualType &IntType); 890 891 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 892 unsigned Start, unsigned End) { 893 bool IllegalParams = false; 894 for (unsigned I = Start; I <= End; ++I) 895 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 896 S.Context.getSizeType()); 897 return IllegalParams; 898 } 899 900 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 901 /// 'local void*' parameter of passed block. 902 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 903 Expr *BlockArg, 904 unsigned NumNonVarArgs) { 905 const BlockPointerType *BPT = 906 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 907 unsigned NumBlockParams = 908 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 909 unsigned TotalNumArgs = TheCall->getNumArgs(); 910 911 // For each argument passed to the block, a corresponding uint needs to 912 // be passed to describe the size of the local memory. 913 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 914 S.Diag(TheCall->getBeginLoc(), 915 diag::err_opencl_enqueue_kernel_local_size_args); 916 return true; 917 } 918 919 // Check that the sizes of the local memory are specified by integers. 920 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 921 TotalNumArgs - 1); 922 } 923 924 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 925 /// overload formats specified in Table 6.13.17.1. 926 /// int enqueue_kernel(queue_t queue, 927 /// kernel_enqueue_flags_t flags, 928 /// const ndrange_t ndrange, 929 /// void (^block)(void)) 930 /// int enqueue_kernel(queue_t queue, 931 /// kernel_enqueue_flags_t flags, 932 /// const ndrange_t ndrange, 933 /// uint num_events_in_wait_list, 934 /// clk_event_t *event_wait_list, 935 /// clk_event_t *event_ret, 936 /// void (^block)(void)) 937 /// int enqueue_kernel(queue_t queue, 938 /// kernel_enqueue_flags_t flags, 939 /// const ndrange_t ndrange, 940 /// void (^block)(local void*, ...), 941 /// uint size0, ...) 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// uint num_events_in_wait_list, 946 /// clk_event_t *event_wait_list, 947 /// clk_event_t *event_ret, 948 /// void (^block)(local void*, ...), 949 /// uint size0, ...) 950 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 951 unsigned NumArgs = TheCall->getNumArgs(); 952 953 if (NumArgs < 4) { 954 S.Diag(TheCall->getBeginLoc(), 955 diag::err_typecheck_call_too_few_args_at_least) 956 << 0 << 4 << NumArgs; 957 return true; 958 } 959 960 Expr *Arg0 = TheCall->getArg(0); 961 Expr *Arg1 = TheCall->getArg(1); 962 Expr *Arg2 = TheCall->getArg(2); 963 Expr *Arg3 = TheCall->getArg(3); 964 965 // First argument always needs to be a queue_t type. 966 if (!Arg0->getType()->isQueueT()) { 967 S.Diag(TheCall->getArg(0)->getBeginLoc(), 968 diag::err_opencl_builtin_expected_type) 969 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 970 return true; 971 } 972 973 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 974 if (!Arg1->getType()->isIntegerType()) { 975 S.Diag(TheCall->getArg(1)->getBeginLoc(), 976 diag::err_opencl_builtin_expected_type) 977 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 978 return true; 979 } 980 981 // Third argument is always an ndrange_t type. 982 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 983 S.Diag(TheCall->getArg(2)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << "'ndrange_t'"; 986 return true; 987 } 988 989 // With four arguments, there is only one form that the function could be 990 // called in: no events and no variable arguments. 991 if (NumArgs == 4) { 992 // check that the last argument is the right block type. 993 if (!isBlockPointer(Arg3)) { 994 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 995 << TheCall->getDirectCallee() << "block"; 996 return true; 997 } 998 // we have a block type, check the prototype 999 const BlockPointerType *BPT = 1000 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1001 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1002 S.Diag(Arg3->getBeginLoc(), 1003 diag::err_opencl_enqueue_kernel_blocks_no_args); 1004 return true; 1005 } 1006 return false; 1007 } 1008 // we can have block + varargs. 1009 if (isBlockPointer(Arg3)) 1010 return (checkOpenCLBlockArgs(S, Arg3) || 1011 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1012 // last two cases with either exactly 7 args or 7 args and varargs. 1013 if (NumArgs >= 7) { 1014 // check common block argument. 1015 Expr *Arg6 = TheCall->getArg(6); 1016 if (!isBlockPointer(Arg6)) { 1017 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1018 << TheCall->getDirectCallee() << "block"; 1019 return true; 1020 } 1021 if (checkOpenCLBlockArgs(S, Arg6)) 1022 return true; 1023 1024 // Forth argument has to be any integer type. 1025 if (!Arg3->getType()->isIntegerType()) { 1026 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1027 diag::err_opencl_builtin_expected_type) 1028 << TheCall->getDirectCallee() << "integer"; 1029 return true; 1030 } 1031 // check remaining common arguments. 1032 Expr *Arg4 = TheCall->getArg(4); 1033 Expr *Arg5 = TheCall->getArg(5); 1034 1035 // Fifth argument is always passed as a pointer to clk_event_t. 1036 if (!Arg4->isNullPointerConstant(S.Context, 1037 Expr::NPC_ValueDependentIsNotNull) && 1038 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1039 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1040 diag::err_opencl_builtin_expected_type) 1041 << TheCall->getDirectCallee() 1042 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1043 return true; 1044 } 1045 1046 // Sixth argument is always passed as a pointer to clk_event_t. 1047 if (!Arg5->isNullPointerConstant(S.Context, 1048 Expr::NPC_ValueDependentIsNotNull) && 1049 !(Arg5->getType()->isPointerType() && 1050 Arg5->getType()->getPointeeType()->isClkEventT())) { 1051 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1052 diag::err_opencl_builtin_expected_type) 1053 << TheCall->getDirectCallee() 1054 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1055 return true; 1056 } 1057 1058 if (NumArgs == 7) 1059 return false; 1060 1061 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1062 } 1063 1064 // None of the specific case has been detected, give generic error 1065 S.Diag(TheCall->getBeginLoc(), 1066 diag::err_opencl_enqueue_kernel_incorrect_args); 1067 return true; 1068 } 1069 1070 /// Returns OpenCL access qual. 1071 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1072 return D->getAttr<OpenCLAccessAttr>(); 1073 } 1074 1075 /// Returns true if pipe element type is different from the pointer. 1076 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1077 const Expr *Arg0 = Call->getArg(0); 1078 // First argument type should always be pipe. 1079 if (!Arg0->getType()->isPipeType()) { 1080 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1081 << Call->getDirectCallee() << Arg0->getSourceRange(); 1082 return true; 1083 } 1084 OpenCLAccessAttr *AccessQual = 1085 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1086 // Validates the access qualifier is compatible with the call. 1087 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1088 // read_only and write_only, and assumed to be read_only if no qualifier is 1089 // specified. 1090 switch (Call->getDirectCallee()->getBuiltinID()) { 1091 case Builtin::BIread_pipe: 1092 case Builtin::BIreserve_read_pipe: 1093 case Builtin::BIcommit_read_pipe: 1094 case Builtin::BIwork_group_reserve_read_pipe: 1095 case Builtin::BIsub_group_reserve_read_pipe: 1096 case Builtin::BIwork_group_commit_read_pipe: 1097 case Builtin::BIsub_group_commit_read_pipe: 1098 if (!(!AccessQual || AccessQual->isReadOnly())) { 1099 S.Diag(Arg0->getBeginLoc(), 1100 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1101 << "read_only" << Arg0->getSourceRange(); 1102 return true; 1103 } 1104 break; 1105 case Builtin::BIwrite_pipe: 1106 case Builtin::BIreserve_write_pipe: 1107 case Builtin::BIcommit_write_pipe: 1108 case Builtin::BIwork_group_reserve_write_pipe: 1109 case Builtin::BIsub_group_reserve_write_pipe: 1110 case Builtin::BIwork_group_commit_write_pipe: 1111 case Builtin::BIsub_group_commit_write_pipe: 1112 if (!(AccessQual && AccessQual->isWriteOnly())) { 1113 S.Diag(Arg0->getBeginLoc(), 1114 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1115 << "write_only" << Arg0->getSourceRange(); 1116 return true; 1117 } 1118 break; 1119 default: 1120 break; 1121 } 1122 return false; 1123 } 1124 1125 /// Returns true if pipe element type is different from the pointer. 1126 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1127 const Expr *Arg0 = Call->getArg(0); 1128 const Expr *ArgIdx = Call->getArg(Idx); 1129 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1130 const QualType EltTy = PipeTy->getElementType(); 1131 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1132 // The Idx argument should be a pointer and the type of the pointer and 1133 // the type of pipe element should also be the same. 1134 if (!ArgTy || 1135 !S.Context.hasSameType( 1136 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1137 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1138 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1139 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1140 return true; 1141 } 1142 return false; 1143 } 1144 1145 // Performs semantic analysis for the read/write_pipe call. 1146 // \param S Reference to the semantic analyzer. 1147 // \param Call A pointer to the builtin call. 1148 // \return True if a semantic error has been found, false otherwise. 1149 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1150 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1151 // functions have two forms. 1152 switch (Call->getNumArgs()) { 1153 case 2: 1154 if (checkOpenCLPipeArg(S, Call)) 1155 return true; 1156 // The call with 2 arguments should be 1157 // read/write_pipe(pipe T, T*). 1158 // Check packet type T. 1159 if (checkOpenCLPipePacketType(S, Call, 1)) 1160 return true; 1161 break; 1162 1163 case 4: { 1164 if (checkOpenCLPipeArg(S, Call)) 1165 return true; 1166 // The call with 4 arguments should be 1167 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1168 // Check reserve_id_t. 1169 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1170 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1171 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1172 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1173 return true; 1174 } 1175 1176 // Check the index. 1177 const Expr *Arg2 = Call->getArg(2); 1178 if (!Arg2->getType()->isIntegerType() && 1179 !Arg2->getType()->isUnsignedIntegerType()) { 1180 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1181 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1182 << Arg2->getType() << Arg2->getSourceRange(); 1183 return true; 1184 } 1185 1186 // Check packet type T. 1187 if (checkOpenCLPipePacketType(S, Call, 3)) 1188 return true; 1189 } break; 1190 default: 1191 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1192 << Call->getDirectCallee() << Call->getSourceRange(); 1193 return true; 1194 } 1195 1196 return false; 1197 } 1198 1199 // Performs a semantic analysis on the {work_group_/sub_group_ 1200 // /_}reserve_{read/write}_pipe 1201 // \param S Reference to the semantic analyzer. 1202 // \param Call The call to the builtin function to be analyzed. 1203 // \return True if a semantic error was found, false otherwise. 1204 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1205 if (checkArgCount(S, Call, 2)) 1206 return true; 1207 1208 if (checkOpenCLPipeArg(S, Call)) 1209 return true; 1210 1211 // Check the reserve size. 1212 if (!Call->getArg(1)->getType()->isIntegerType() && 1213 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1214 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1215 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1216 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1217 return true; 1218 } 1219 1220 // Since return type of reserve_read/write_pipe built-in function is 1221 // reserve_id_t, which is not defined in the builtin def file , we used int 1222 // as return type and need to override the return type of these functions. 1223 Call->setType(S.Context.OCLReserveIDTy); 1224 1225 return false; 1226 } 1227 1228 // Performs a semantic analysis on {work_group_/sub_group_ 1229 // /_}commit_{read/write}_pipe 1230 // \param S Reference to the semantic analyzer. 1231 // \param Call The call to the builtin function to be analyzed. 1232 // \return True if a semantic error was found, false otherwise. 1233 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1234 if (checkArgCount(S, Call, 2)) 1235 return true; 1236 1237 if (checkOpenCLPipeArg(S, Call)) 1238 return true; 1239 1240 // Check reserve_id_t. 1241 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1242 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1243 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1244 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1245 return true; 1246 } 1247 1248 return false; 1249 } 1250 1251 // Performs a semantic analysis on the call to built-in Pipe 1252 // Query Functions. 1253 // \param S Reference to the semantic analyzer. 1254 // \param Call The call to the builtin function to be analyzed. 1255 // \return True if a semantic error was found, false otherwise. 1256 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1257 if (checkArgCount(S, Call, 1)) 1258 return true; 1259 1260 if (!Call->getArg(0)->getType()->isPipeType()) { 1261 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1262 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1263 return true; 1264 } 1265 1266 return false; 1267 } 1268 1269 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1270 // Performs semantic analysis for the to_global/local/private call. 1271 // \param S Reference to the semantic analyzer. 1272 // \param BuiltinID ID of the builtin function. 1273 // \param Call A pointer to the builtin call. 1274 // \return True if a semantic error has been found, false otherwise. 1275 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1276 CallExpr *Call) { 1277 if (checkArgCount(S, Call, 1)) 1278 return true; 1279 1280 auto RT = Call->getArg(0)->getType(); 1281 if (!RT->isPointerType() || RT->getPointeeType() 1282 .getAddressSpace() == LangAS::opencl_constant) { 1283 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1284 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1285 return true; 1286 } 1287 1288 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1289 S.Diag(Call->getArg(0)->getBeginLoc(), 1290 diag::warn_opencl_generic_address_space_arg) 1291 << Call->getDirectCallee()->getNameInfo().getAsString() 1292 << Call->getArg(0)->getSourceRange(); 1293 } 1294 1295 RT = RT->getPointeeType(); 1296 auto Qual = RT.getQualifiers(); 1297 switch (BuiltinID) { 1298 case Builtin::BIto_global: 1299 Qual.setAddressSpace(LangAS::opencl_global); 1300 break; 1301 case Builtin::BIto_local: 1302 Qual.setAddressSpace(LangAS::opencl_local); 1303 break; 1304 case Builtin::BIto_private: 1305 Qual.setAddressSpace(LangAS::opencl_private); 1306 break; 1307 default: 1308 llvm_unreachable("Invalid builtin function"); 1309 } 1310 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1311 RT.getUnqualifiedType(), Qual))); 1312 1313 return false; 1314 } 1315 1316 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1317 if (checkArgCount(S, TheCall, 1)) 1318 return ExprError(); 1319 1320 // Compute __builtin_launder's parameter type from the argument. 1321 // The parameter type is: 1322 // * The type of the argument if it's not an array or function type, 1323 // Otherwise, 1324 // * The decayed argument type. 1325 QualType ParamTy = [&]() { 1326 QualType ArgTy = TheCall->getArg(0)->getType(); 1327 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1328 return S.Context.getPointerType(Ty->getElementType()); 1329 if (ArgTy->isFunctionType()) { 1330 return S.Context.getPointerType(ArgTy); 1331 } 1332 return ArgTy; 1333 }(); 1334 1335 TheCall->setType(ParamTy); 1336 1337 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1338 if (!ParamTy->isPointerType()) 1339 return 0; 1340 if (ParamTy->isFunctionPointerType()) 1341 return 1; 1342 if (ParamTy->isVoidPointerType()) 1343 return 2; 1344 return llvm::Optional<unsigned>{}; 1345 }(); 1346 if (DiagSelect.hasValue()) { 1347 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1348 << DiagSelect.getValue() << TheCall->getSourceRange(); 1349 return ExprError(); 1350 } 1351 1352 // We either have an incomplete class type, or we have a class template 1353 // whose instantiation has not been forced. Example: 1354 // 1355 // template <class T> struct Foo { T value; }; 1356 // Foo<int> *p = nullptr; 1357 // auto *d = __builtin_launder(p); 1358 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1359 diag::err_incomplete_type)) 1360 return ExprError(); 1361 1362 assert(ParamTy->getPointeeType()->isObjectType() && 1363 "Unhandled non-object pointer case"); 1364 1365 InitializedEntity Entity = 1366 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1367 ExprResult Arg = 1368 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1369 if (Arg.isInvalid()) 1370 return ExprError(); 1371 TheCall->setArg(0, Arg.get()); 1372 1373 return TheCall; 1374 } 1375 1376 // Emit an error and return true if the current architecture is not in the list 1377 // of supported architectures. 1378 static bool 1379 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1380 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1381 llvm::Triple::ArchType CurArch = 1382 S.getASTContext().getTargetInfo().getTriple().getArch(); 1383 if (llvm::is_contained(SupportedArchs, CurArch)) 1384 return false; 1385 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1386 << TheCall->getSourceRange(); 1387 return true; 1388 } 1389 1390 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1391 SourceLocation CallSiteLoc); 1392 1393 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1394 CallExpr *TheCall) { 1395 switch (TI.getTriple().getArch()) { 1396 default: 1397 // Some builtins don't require additional checking, so just consider these 1398 // acceptable. 1399 return false; 1400 case llvm::Triple::arm: 1401 case llvm::Triple::armeb: 1402 case llvm::Triple::thumb: 1403 case llvm::Triple::thumbeb: 1404 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1405 case llvm::Triple::aarch64: 1406 case llvm::Triple::aarch64_32: 1407 case llvm::Triple::aarch64_be: 1408 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1409 case llvm::Triple::bpfeb: 1410 case llvm::Triple::bpfel: 1411 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1412 case llvm::Triple::hexagon: 1413 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::mips: 1415 case llvm::Triple::mipsel: 1416 case llvm::Triple::mips64: 1417 case llvm::Triple::mips64el: 1418 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1419 case llvm::Triple::systemz: 1420 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1421 case llvm::Triple::x86: 1422 case llvm::Triple::x86_64: 1423 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1424 case llvm::Triple::ppc: 1425 case llvm::Triple::ppc64: 1426 case llvm::Triple::ppc64le: 1427 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1428 case llvm::Triple::amdgcn: 1429 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1430 } 1431 } 1432 1433 ExprResult 1434 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1435 CallExpr *TheCall) { 1436 ExprResult TheCallResult(TheCall); 1437 1438 // Find out if any arguments are required to be integer constant expressions. 1439 unsigned ICEArguments = 0; 1440 ASTContext::GetBuiltinTypeError Error; 1441 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1442 if (Error != ASTContext::GE_None) 1443 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1444 1445 // If any arguments are required to be ICE's, check and diagnose. 1446 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1447 // Skip arguments not required to be ICE's. 1448 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1449 1450 llvm::APSInt Result; 1451 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1452 return true; 1453 ICEArguments &= ~(1 << ArgNo); 1454 } 1455 1456 switch (BuiltinID) { 1457 case Builtin::BI__builtin___CFStringMakeConstantString: 1458 assert(TheCall->getNumArgs() == 1 && 1459 "Wrong # arguments to builtin CFStringMakeConstantString"); 1460 if (CheckObjCString(TheCall->getArg(0))) 1461 return ExprError(); 1462 break; 1463 case Builtin::BI__builtin_ms_va_start: 1464 case Builtin::BI__builtin_stdarg_start: 1465 case Builtin::BI__builtin_va_start: 1466 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__va_start: { 1470 switch (Context.getTargetInfo().getTriple().getArch()) { 1471 case llvm::Triple::aarch64: 1472 case llvm::Triple::arm: 1473 case llvm::Triple::thumb: 1474 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1475 return ExprError(); 1476 break; 1477 default: 1478 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1479 return ExprError(); 1480 break; 1481 } 1482 break; 1483 } 1484 1485 // The acquire, release, and no fence variants are ARM and AArch64 only. 1486 case Builtin::BI_interlockedbittestandset_acq: 1487 case Builtin::BI_interlockedbittestandset_rel: 1488 case Builtin::BI_interlockedbittestandset_nf: 1489 case Builtin::BI_interlockedbittestandreset_acq: 1490 case Builtin::BI_interlockedbittestandreset_rel: 1491 case Builtin::BI_interlockedbittestandreset_nf: 1492 if (CheckBuiltinTargetSupport( 1493 *this, BuiltinID, TheCall, 1494 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1495 return ExprError(); 1496 break; 1497 1498 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1499 case Builtin::BI_bittest64: 1500 case Builtin::BI_bittestandcomplement64: 1501 case Builtin::BI_bittestandreset64: 1502 case Builtin::BI_bittestandset64: 1503 case Builtin::BI_interlockedbittestandreset64: 1504 case Builtin::BI_interlockedbittestandset64: 1505 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1506 {llvm::Triple::x86_64, llvm::Triple::arm, 1507 llvm::Triple::thumb, llvm::Triple::aarch64})) 1508 return ExprError(); 1509 break; 1510 1511 case Builtin::BI__builtin_isgreater: 1512 case Builtin::BI__builtin_isgreaterequal: 1513 case Builtin::BI__builtin_isless: 1514 case Builtin::BI__builtin_islessequal: 1515 case Builtin::BI__builtin_islessgreater: 1516 case Builtin::BI__builtin_isunordered: 1517 if (SemaBuiltinUnorderedCompare(TheCall)) 1518 return ExprError(); 1519 break; 1520 case Builtin::BI__builtin_fpclassify: 1521 if (SemaBuiltinFPClassification(TheCall, 6)) 1522 return ExprError(); 1523 break; 1524 case Builtin::BI__builtin_isfinite: 1525 case Builtin::BI__builtin_isinf: 1526 case Builtin::BI__builtin_isinf_sign: 1527 case Builtin::BI__builtin_isnan: 1528 case Builtin::BI__builtin_isnormal: 1529 case Builtin::BI__builtin_signbit: 1530 case Builtin::BI__builtin_signbitf: 1531 case Builtin::BI__builtin_signbitl: 1532 if (SemaBuiltinFPClassification(TheCall, 1)) 1533 return ExprError(); 1534 break; 1535 case Builtin::BI__builtin_shufflevector: 1536 return SemaBuiltinShuffleVector(TheCall); 1537 // TheCall will be freed by the smart pointer here, but that's fine, since 1538 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1539 case Builtin::BI__builtin_prefetch: 1540 if (SemaBuiltinPrefetch(TheCall)) 1541 return ExprError(); 1542 break; 1543 case Builtin::BI__builtin_alloca_with_align: 1544 if (SemaBuiltinAllocaWithAlign(TheCall)) 1545 return ExprError(); 1546 LLVM_FALLTHROUGH; 1547 case Builtin::BI__builtin_alloca: 1548 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1549 << TheCall->getDirectCallee(); 1550 break; 1551 case Builtin::BI__assume: 1552 case Builtin::BI__builtin_assume: 1553 if (SemaBuiltinAssume(TheCall)) 1554 return ExprError(); 1555 break; 1556 case Builtin::BI__builtin_assume_aligned: 1557 if (SemaBuiltinAssumeAligned(TheCall)) 1558 return ExprError(); 1559 break; 1560 case Builtin::BI__builtin_dynamic_object_size: 1561 case Builtin::BI__builtin_object_size: 1562 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1563 return ExprError(); 1564 break; 1565 case Builtin::BI__builtin_longjmp: 1566 if (SemaBuiltinLongjmp(TheCall)) 1567 return ExprError(); 1568 break; 1569 case Builtin::BI__builtin_setjmp: 1570 if (SemaBuiltinSetjmp(TheCall)) 1571 return ExprError(); 1572 break; 1573 case Builtin::BI__builtin_classify_type: 1574 if (checkArgCount(*this, TheCall, 1)) return true; 1575 TheCall->setType(Context.IntTy); 1576 break; 1577 case Builtin::BI__builtin_complex: 1578 if (SemaBuiltinComplex(TheCall)) 1579 return ExprError(); 1580 break; 1581 case Builtin::BI__builtin_constant_p: { 1582 if (checkArgCount(*this, TheCall, 1)) return true; 1583 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1584 if (Arg.isInvalid()) return true; 1585 TheCall->setArg(0, Arg.get()); 1586 TheCall->setType(Context.IntTy); 1587 break; 1588 } 1589 case Builtin::BI__builtin_launder: 1590 return SemaBuiltinLaunder(*this, TheCall); 1591 case Builtin::BI__sync_fetch_and_add: 1592 case Builtin::BI__sync_fetch_and_add_1: 1593 case Builtin::BI__sync_fetch_and_add_2: 1594 case Builtin::BI__sync_fetch_and_add_4: 1595 case Builtin::BI__sync_fetch_and_add_8: 1596 case Builtin::BI__sync_fetch_and_add_16: 1597 case Builtin::BI__sync_fetch_and_sub: 1598 case Builtin::BI__sync_fetch_and_sub_1: 1599 case Builtin::BI__sync_fetch_and_sub_2: 1600 case Builtin::BI__sync_fetch_and_sub_4: 1601 case Builtin::BI__sync_fetch_and_sub_8: 1602 case Builtin::BI__sync_fetch_and_sub_16: 1603 case Builtin::BI__sync_fetch_and_or: 1604 case Builtin::BI__sync_fetch_and_or_1: 1605 case Builtin::BI__sync_fetch_and_or_2: 1606 case Builtin::BI__sync_fetch_and_or_4: 1607 case Builtin::BI__sync_fetch_and_or_8: 1608 case Builtin::BI__sync_fetch_and_or_16: 1609 case Builtin::BI__sync_fetch_and_and: 1610 case Builtin::BI__sync_fetch_and_and_1: 1611 case Builtin::BI__sync_fetch_and_and_2: 1612 case Builtin::BI__sync_fetch_and_and_4: 1613 case Builtin::BI__sync_fetch_and_and_8: 1614 case Builtin::BI__sync_fetch_and_and_16: 1615 case Builtin::BI__sync_fetch_and_xor: 1616 case Builtin::BI__sync_fetch_and_xor_1: 1617 case Builtin::BI__sync_fetch_and_xor_2: 1618 case Builtin::BI__sync_fetch_and_xor_4: 1619 case Builtin::BI__sync_fetch_and_xor_8: 1620 case Builtin::BI__sync_fetch_and_xor_16: 1621 case Builtin::BI__sync_fetch_and_nand: 1622 case Builtin::BI__sync_fetch_and_nand_1: 1623 case Builtin::BI__sync_fetch_and_nand_2: 1624 case Builtin::BI__sync_fetch_and_nand_4: 1625 case Builtin::BI__sync_fetch_and_nand_8: 1626 case Builtin::BI__sync_fetch_and_nand_16: 1627 case Builtin::BI__sync_add_and_fetch: 1628 case Builtin::BI__sync_add_and_fetch_1: 1629 case Builtin::BI__sync_add_and_fetch_2: 1630 case Builtin::BI__sync_add_and_fetch_4: 1631 case Builtin::BI__sync_add_and_fetch_8: 1632 case Builtin::BI__sync_add_and_fetch_16: 1633 case Builtin::BI__sync_sub_and_fetch: 1634 case Builtin::BI__sync_sub_and_fetch_1: 1635 case Builtin::BI__sync_sub_and_fetch_2: 1636 case Builtin::BI__sync_sub_and_fetch_4: 1637 case Builtin::BI__sync_sub_and_fetch_8: 1638 case Builtin::BI__sync_sub_and_fetch_16: 1639 case Builtin::BI__sync_and_and_fetch: 1640 case Builtin::BI__sync_and_and_fetch_1: 1641 case Builtin::BI__sync_and_and_fetch_2: 1642 case Builtin::BI__sync_and_and_fetch_4: 1643 case Builtin::BI__sync_and_and_fetch_8: 1644 case Builtin::BI__sync_and_and_fetch_16: 1645 case Builtin::BI__sync_or_and_fetch: 1646 case Builtin::BI__sync_or_and_fetch_1: 1647 case Builtin::BI__sync_or_and_fetch_2: 1648 case Builtin::BI__sync_or_and_fetch_4: 1649 case Builtin::BI__sync_or_and_fetch_8: 1650 case Builtin::BI__sync_or_and_fetch_16: 1651 case Builtin::BI__sync_xor_and_fetch: 1652 case Builtin::BI__sync_xor_and_fetch_1: 1653 case Builtin::BI__sync_xor_and_fetch_2: 1654 case Builtin::BI__sync_xor_and_fetch_4: 1655 case Builtin::BI__sync_xor_and_fetch_8: 1656 case Builtin::BI__sync_xor_and_fetch_16: 1657 case Builtin::BI__sync_nand_and_fetch: 1658 case Builtin::BI__sync_nand_and_fetch_1: 1659 case Builtin::BI__sync_nand_and_fetch_2: 1660 case Builtin::BI__sync_nand_and_fetch_4: 1661 case Builtin::BI__sync_nand_and_fetch_8: 1662 case Builtin::BI__sync_nand_and_fetch_16: 1663 case Builtin::BI__sync_val_compare_and_swap: 1664 case Builtin::BI__sync_val_compare_and_swap_1: 1665 case Builtin::BI__sync_val_compare_and_swap_2: 1666 case Builtin::BI__sync_val_compare_and_swap_4: 1667 case Builtin::BI__sync_val_compare_and_swap_8: 1668 case Builtin::BI__sync_val_compare_and_swap_16: 1669 case Builtin::BI__sync_bool_compare_and_swap: 1670 case Builtin::BI__sync_bool_compare_and_swap_1: 1671 case Builtin::BI__sync_bool_compare_and_swap_2: 1672 case Builtin::BI__sync_bool_compare_and_swap_4: 1673 case Builtin::BI__sync_bool_compare_and_swap_8: 1674 case Builtin::BI__sync_bool_compare_and_swap_16: 1675 case Builtin::BI__sync_lock_test_and_set: 1676 case Builtin::BI__sync_lock_test_and_set_1: 1677 case Builtin::BI__sync_lock_test_and_set_2: 1678 case Builtin::BI__sync_lock_test_and_set_4: 1679 case Builtin::BI__sync_lock_test_and_set_8: 1680 case Builtin::BI__sync_lock_test_and_set_16: 1681 case Builtin::BI__sync_lock_release: 1682 case Builtin::BI__sync_lock_release_1: 1683 case Builtin::BI__sync_lock_release_2: 1684 case Builtin::BI__sync_lock_release_4: 1685 case Builtin::BI__sync_lock_release_8: 1686 case Builtin::BI__sync_lock_release_16: 1687 case Builtin::BI__sync_swap: 1688 case Builtin::BI__sync_swap_1: 1689 case Builtin::BI__sync_swap_2: 1690 case Builtin::BI__sync_swap_4: 1691 case Builtin::BI__sync_swap_8: 1692 case Builtin::BI__sync_swap_16: 1693 return SemaBuiltinAtomicOverloaded(TheCallResult); 1694 case Builtin::BI__sync_synchronize: 1695 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1696 << TheCall->getCallee()->getSourceRange(); 1697 break; 1698 case Builtin::BI__builtin_nontemporal_load: 1699 case Builtin::BI__builtin_nontemporal_store: 1700 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1701 case Builtin::BI__builtin_memcpy_inline: { 1702 clang::Expr *SizeOp = TheCall->getArg(2); 1703 // We warn about copying to or from `nullptr` pointers when `size` is 1704 // greater than 0. When `size` is value dependent we cannot evaluate its 1705 // value so we bail out. 1706 if (SizeOp->isValueDependent()) 1707 break; 1708 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1709 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1710 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1711 } 1712 break; 1713 } 1714 #define BUILTIN(ID, TYPE, ATTRS) 1715 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1716 case Builtin::BI##ID: \ 1717 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1718 #include "clang/Basic/Builtins.def" 1719 case Builtin::BI__annotation: 1720 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1721 return ExprError(); 1722 break; 1723 case Builtin::BI__builtin_annotation: 1724 if (SemaBuiltinAnnotation(*this, TheCall)) 1725 return ExprError(); 1726 break; 1727 case Builtin::BI__builtin_addressof: 1728 if (SemaBuiltinAddressof(*this, TheCall)) 1729 return ExprError(); 1730 break; 1731 case Builtin::BI__builtin_is_aligned: 1732 case Builtin::BI__builtin_align_up: 1733 case Builtin::BI__builtin_align_down: 1734 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1735 return ExprError(); 1736 break; 1737 case Builtin::BI__builtin_add_overflow: 1738 case Builtin::BI__builtin_sub_overflow: 1739 case Builtin::BI__builtin_mul_overflow: 1740 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1741 return ExprError(); 1742 break; 1743 case Builtin::BI__builtin_operator_new: 1744 case Builtin::BI__builtin_operator_delete: { 1745 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1746 ExprResult Res = 1747 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1748 if (Res.isInvalid()) 1749 CorrectDelayedTyposInExpr(TheCallResult.get()); 1750 return Res; 1751 } 1752 case Builtin::BI__builtin_dump_struct: { 1753 // We first want to ensure we are called with 2 arguments 1754 if (checkArgCount(*this, TheCall, 2)) 1755 return ExprError(); 1756 // Ensure that the first argument is of type 'struct XX *' 1757 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1758 const QualType PtrArgType = PtrArg->getType(); 1759 if (!PtrArgType->isPointerType() || 1760 !PtrArgType->getPointeeType()->isRecordType()) { 1761 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1762 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1763 << "structure pointer"; 1764 return ExprError(); 1765 } 1766 1767 // Ensure that the second argument is of type 'FunctionType' 1768 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1769 const QualType FnPtrArgType = FnPtrArg->getType(); 1770 if (!FnPtrArgType->isPointerType()) { 1771 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1772 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1773 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1774 return ExprError(); 1775 } 1776 1777 const auto *FuncType = 1778 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1779 1780 if (!FuncType) { 1781 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1782 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1783 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1784 return ExprError(); 1785 } 1786 1787 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1788 if (!FT->getNumParams()) { 1789 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1790 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1791 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1792 return ExprError(); 1793 } 1794 QualType PT = FT->getParamType(0); 1795 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1796 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1797 !PT->getPointeeType().isConstQualified()) { 1798 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1799 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1800 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1801 return ExprError(); 1802 } 1803 } 1804 1805 TheCall->setType(Context.IntTy); 1806 break; 1807 } 1808 case Builtin::BI__builtin_expect_with_probability: { 1809 // We first want to ensure we are called with 3 arguments 1810 if (checkArgCount(*this, TheCall, 3)) 1811 return ExprError(); 1812 // then check probability is constant float in range [0.0, 1.0] 1813 const Expr *ProbArg = TheCall->getArg(2); 1814 SmallVector<PartialDiagnosticAt, 8> Notes; 1815 Expr::EvalResult Eval; 1816 Eval.Diag = &Notes; 1817 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1818 !Eval.Val.isFloat()) { 1819 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1820 << ProbArg->getSourceRange(); 1821 for (const PartialDiagnosticAt &PDiag : Notes) 1822 Diag(PDiag.first, PDiag.second); 1823 return ExprError(); 1824 } 1825 llvm::APFloat Probability = Eval.Val.getFloat(); 1826 bool LoseInfo = false; 1827 Probability.convert(llvm::APFloat::IEEEdouble(), 1828 llvm::RoundingMode::Dynamic, &LoseInfo); 1829 if (!(Probability >= llvm::APFloat(0.0) && 1830 Probability <= llvm::APFloat(1.0))) { 1831 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1832 << ProbArg->getSourceRange(); 1833 return ExprError(); 1834 } 1835 break; 1836 } 1837 case Builtin::BI__builtin_preserve_access_index: 1838 if (SemaBuiltinPreserveAI(*this, TheCall)) 1839 return ExprError(); 1840 break; 1841 case Builtin::BI__builtin_call_with_static_chain: 1842 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1843 return ExprError(); 1844 break; 1845 case Builtin::BI__exception_code: 1846 case Builtin::BI_exception_code: 1847 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1848 diag::err_seh___except_block)) 1849 return ExprError(); 1850 break; 1851 case Builtin::BI__exception_info: 1852 case Builtin::BI_exception_info: 1853 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1854 diag::err_seh___except_filter)) 1855 return ExprError(); 1856 break; 1857 case Builtin::BI__GetExceptionInfo: 1858 if (checkArgCount(*this, TheCall, 1)) 1859 return ExprError(); 1860 1861 if (CheckCXXThrowOperand( 1862 TheCall->getBeginLoc(), 1863 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1864 TheCall)) 1865 return ExprError(); 1866 1867 TheCall->setType(Context.VoidPtrTy); 1868 break; 1869 // OpenCL v2.0, s6.13.16 - Pipe functions 1870 case Builtin::BIread_pipe: 1871 case Builtin::BIwrite_pipe: 1872 // Since those two functions are declared with var args, we need a semantic 1873 // check for the argument. 1874 if (SemaBuiltinRWPipe(*this, TheCall)) 1875 return ExprError(); 1876 break; 1877 case Builtin::BIreserve_read_pipe: 1878 case Builtin::BIreserve_write_pipe: 1879 case Builtin::BIwork_group_reserve_read_pipe: 1880 case Builtin::BIwork_group_reserve_write_pipe: 1881 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1882 return ExprError(); 1883 break; 1884 case Builtin::BIsub_group_reserve_read_pipe: 1885 case Builtin::BIsub_group_reserve_write_pipe: 1886 if (checkOpenCLSubgroupExt(*this, TheCall) || 1887 SemaBuiltinReserveRWPipe(*this, TheCall)) 1888 return ExprError(); 1889 break; 1890 case Builtin::BIcommit_read_pipe: 1891 case Builtin::BIcommit_write_pipe: 1892 case Builtin::BIwork_group_commit_read_pipe: 1893 case Builtin::BIwork_group_commit_write_pipe: 1894 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1895 return ExprError(); 1896 break; 1897 case Builtin::BIsub_group_commit_read_pipe: 1898 case Builtin::BIsub_group_commit_write_pipe: 1899 if (checkOpenCLSubgroupExt(*this, TheCall) || 1900 SemaBuiltinCommitRWPipe(*this, TheCall)) 1901 return ExprError(); 1902 break; 1903 case Builtin::BIget_pipe_num_packets: 1904 case Builtin::BIget_pipe_max_packets: 1905 if (SemaBuiltinPipePackets(*this, TheCall)) 1906 return ExprError(); 1907 break; 1908 case Builtin::BIto_global: 1909 case Builtin::BIto_local: 1910 case Builtin::BIto_private: 1911 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1912 return ExprError(); 1913 break; 1914 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1915 case Builtin::BIenqueue_kernel: 1916 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1917 return ExprError(); 1918 break; 1919 case Builtin::BIget_kernel_work_group_size: 1920 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1921 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1922 return ExprError(); 1923 break; 1924 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1925 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1926 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1927 return ExprError(); 1928 break; 1929 case Builtin::BI__builtin_os_log_format: 1930 Cleanup.setExprNeedsCleanups(true); 1931 LLVM_FALLTHROUGH; 1932 case Builtin::BI__builtin_os_log_format_buffer_size: 1933 if (SemaBuiltinOSLogFormat(TheCall)) 1934 return ExprError(); 1935 break; 1936 case Builtin::BI__builtin_frame_address: 1937 case Builtin::BI__builtin_return_address: { 1938 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1939 return ExprError(); 1940 1941 // -Wframe-address warning if non-zero passed to builtin 1942 // return/frame address. 1943 Expr::EvalResult Result; 1944 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1945 Result.Val.getInt() != 0) 1946 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1947 << ((BuiltinID == Builtin::BI__builtin_return_address) 1948 ? "__builtin_return_address" 1949 : "__builtin_frame_address") 1950 << TheCall->getSourceRange(); 1951 break; 1952 } 1953 1954 case Builtin::BI__builtin_matrix_transpose: 1955 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1956 1957 case Builtin::BI__builtin_matrix_column_major_load: 1958 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1959 1960 case Builtin::BI__builtin_matrix_column_major_store: 1961 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1962 } 1963 1964 // Since the target specific builtins for each arch overlap, only check those 1965 // of the arch we are compiling for. 1966 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1967 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1968 assert(Context.getAuxTargetInfo() && 1969 "Aux Target Builtin, but not an aux target?"); 1970 1971 if (CheckTSBuiltinFunctionCall( 1972 *Context.getAuxTargetInfo(), 1973 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1974 return ExprError(); 1975 } else { 1976 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 1977 TheCall)) 1978 return ExprError(); 1979 } 1980 } 1981 1982 return TheCallResult; 1983 } 1984 1985 // Get the valid immediate range for the specified NEON type code. 1986 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1987 NeonTypeFlags Type(t); 1988 int IsQuad = ForceQuad ? true : Type.isQuad(); 1989 switch (Type.getEltType()) { 1990 case NeonTypeFlags::Int8: 1991 case NeonTypeFlags::Poly8: 1992 return shift ? 7 : (8 << IsQuad) - 1; 1993 case NeonTypeFlags::Int16: 1994 case NeonTypeFlags::Poly16: 1995 return shift ? 15 : (4 << IsQuad) - 1; 1996 case NeonTypeFlags::Int32: 1997 return shift ? 31 : (2 << IsQuad) - 1; 1998 case NeonTypeFlags::Int64: 1999 case NeonTypeFlags::Poly64: 2000 return shift ? 63 : (1 << IsQuad) - 1; 2001 case NeonTypeFlags::Poly128: 2002 return shift ? 127 : (1 << IsQuad) - 1; 2003 case NeonTypeFlags::Float16: 2004 assert(!shift && "cannot shift float types!"); 2005 return (4 << IsQuad) - 1; 2006 case NeonTypeFlags::Float32: 2007 assert(!shift && "cannot shift float types!"); 2008 return (2 << IsQuad) - 1; 2009 case NeonTypeFlags::Float64: 2010 assert(!shift && "cannot shift float types!"); 2011 return (1 << IsQuad) - 1; 2012 case NeonTypeFlags::BFloat16: 2013 assert(!shift && "cannot shift float types!"); 2014 return (4 << IsQuad) - 1; 2015 } 2016 llvm_unreachable("Invalid NeonTypeFlag!"); 2017 } 2018 2019 /// getNeonEltType - Return the QualType corresponding to the elements of 2020 /// the vector type specified by the NeonTypeFlags. This is used to check 2021 /// the pointer arguments for Neon load/store intrinsics. 2022 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2023 bool IsPolyUnsigned, bool IsInt64Long) { 2024 switch (Flags.getEltType()) { 2025 case NeonTypeFlags::Int8: 2026 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2027 case NeonTypeFlags::Int16: 2028 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2029 case NeonTypeFlags::Int32: 2030 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2031 case NeonTypeFlags::Int64: 2032 if (IsInt64Long) 2033 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2034 else 2035 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2036 : Context.LongLongTy; 2037 case NeonTypeFlags::Poly8: 2038 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2039 case NeonTypeFlags::Poly16: 2040 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2041 case NeonTypeFlags::Poly64: 2042 if (IsInt64Long) 2043 return Context.UnsignedLongTy; 2044 else 2045 return Context.UnsignedLongLongTy; 2046 case NeonTypeFlags::Poly128: 2047 break; 2048 case NeonTypeFlags::Float16: 2049 return Context.HalfTy; 2050 case NeonTypeFlags::Float32: 2051 return Context.FloatTy; 2052 case NeonTypeFlags::Float64: 2053 return Context.DoubleTy; 2054 case NeonTypeFlags::BFloat16: 2055 return Context.BFloat16Ty; 2056 } 2057 llvm_unreachable("Invalid NeonTypeFlag!"); 2058 } 2059 2060 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2061 // Range check SVE intrinsics that take immediate values. 2062 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2063 2064 switch (BuiltinID) { 2065 default: 2066 return false; 2067 #define GET_SVE_IMMEDIATE_CHECK 2068 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2069 #undef GET_SVE_IMMEDIATE_CHECK 2070 } 2071 2072 // Perform all the immediate checks for this builtin call. 2073 bool HasError = false; 2074 for (auto &I : ImmChecks) { 2075 int ArgNum, CheckTy, ElementSizeInBits; 2076 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2077 2078 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2079 2080 // Function that checks whether the operand (ArgNum) is an immediate 2081 // that is one of the predefined values. 2082 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2083 int ErrDiag) -> bool { 2084 // We can't check the value of a dependent argument. 2085 Expr *Arg = TheCall->getArg(ArgNum); 2086 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2087 return false; 2088 2089 // Check constant-ness first. 2090 llvm::APSInt Imm; 2091 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2092 return true; 2093 2094 if (!CheckImm(Imm.getSExtValue())) 2095 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2096 return false; 2097 }; 2098 2099 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2100 case SVETypeFlags::ImmCheck0_31: 2101 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2102 HasError = true; 2103 break; 2104 case SVETypeFlags::ImmCheck0_13: 2105 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2106 HasError = true; 2107 break; 2108 case SVETypeFlags::ImmCheck1_16: 2109 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2110 HasError = true; 2111 break; 2112 case SVETypeFlags::ImmCheck0_7: 2113 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2114 HasError = true; 2115 break; 2116 case SVETypeFlags::ImmCheckExtract: 2117 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2118 (2048 / ElementSizeInBits) - 1)) 2119 HasError = true; 2120 break; 2121 case SVETypeFlags::ImmCheckShiftRight: 2122 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2123 HasError = true; 2124 break; 2125 case SVETypeFlags::ImmCheckShiftRightNarrow: 2126 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2127 ElementSizeInBits / 2)) 2128 HasError = true; 2129 break; 2130 case SVETypeFlags::ImmCheckShiftLeft: 2131 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2132 ElementSizeInBits - 1)) 2133 HasError = true; 2134 break; 2135 case SVETypeFlags::ImmCheckLaneIndex: 2136 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2137 (128 / (1 * ElementSizeInBits)) - 1)) 2138 HasError = true; 2139 break; 2140 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2141 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2142 (128 / (2 * ElementSizeInBits)) - 1)) 2143 HasError = true; 2144 break; 2145 case SVETypeFlags::ImmCheckLaneIndexDot: 2146 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2147 (128 / (4 * ElementSizeInBits)) - 1)) 2148 HasError = true; 2149 break; 2150 case SVETypeFlags::ImmCheckComplexRot90_270: 2151 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2152 diag::err_rotation_argument_to_cadd)) 2153 HasError = true; 2154 break; 2155 case SVETypeFlags::ImmCheckComplexRotAll90: 2156 if (CheckImmediateInSet( 2157 [](int64_t V) { 2158 return V == 0 || V == 90 || V == 180 || V == 270; 2159 }, 2160 diag::err_rotation_argument_to_cmla)) 2161 HasError = true; 2162 break; 2163 case SVETypeFlags::ImmCheck0_1: 2164 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2165 HasError = true; 2166 break; 2167 case SVETypeFlags::ImmCheck0_2: 2168 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2169 HasError = true; 2170 break; 2171 case SVETypeFlags::ImmCheck0_3: 2172 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2173 HasError = true; 2174 break; 2175 } 2176 } 2177 2178 return HasError; 2179 } 2180 2181 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2182 unsigned BuiltinID, CallExpr *TheCall) { 2183 llvm::APSInt Result; 2184 uint64_t mask = 0; 2185 unsigned TV = 0; 2186 int PtrArgNum = -1; 2187 bool HasConstPtr = false; 2188 switch (BuiltinID) { 2189 #define GET_NEON_OVERLOAD_CHECK 2190 #include "clang/Basic/arm_neon.inc" 2191 #include "clang/Basic/arm_fp16.inc" 2192 #undef GET_NEON_OVERLOAD_CHECK 2193 } 2194 2195 // For NEON intrinsics which are overloaded on vector element type, validate 2196 // the immediate which specifies which variant to emit. 2197 unsigned ImmArg = TheCall->getNumArgs()-1; 2198 if (mask) { 2199 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2200 return true; 2201 2202 TV = Result.getLimitedValue(64); 2203 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2204 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2205 << TheCall->getArg(ImmArg)->getSourceRange(); 2206 } 2207 2208 if (PtrArgNum >= 0) { 2209 // Check that pointer arguments have the specified type. 2210 Expr *Arg = TheCall->getArg(PtrArgNum); 2211 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2212 Arg = ICE->getSubExpr(); 2213 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2214 QualType RHSTy = RHS.get()->getType(); 2215 2216 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2217 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2218 Arch == llvm::Triple::aarch64_32 || 2219 Arch == llvm::Triple::aarch64_be; 2220 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2221 QualType EltTy = 2222 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2223 if (HasConstPtr) 2224 EltTy = EltTy.withConst(); 2225 QualType LHSTy = Context.getPointerType(EltTy); 2226 AssignConvertType ConvTy; 2227 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2228 if (RHS.isInvalid()) 2229 return true; 2230 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2231 RHS.get(), AA_Assigning)) 2232 return true; 2233 } 2234 2235 // For NEON intrinsics which take an immediate value as part of the 2236 // instruction, range check them here. 2237 unsigned i = 0, l = 0, u = 0; 2238 switch (BuiltinID) { 2239 default: 2240 return false; 2241 #define GET_NEON_IMMEDIATE_CHECK 2242 #include "clang/Basic/arm_neon.inc" 2243 #include "clang/Basic/arm_fp16.inc" 2244 #undef GET_NEON_IMMEDIATE_CHECK 2245 } 2246 2247 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2248 } 2249 2250 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2251 switch (BuiltinID) { 2252 default: 2253 return false; 2254 #include "clang/Basic/arm_mve_builtin_sema.inc" 2255 } 2256 } 2257 2258 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2259 CallExpr *TheCall) { 2260 bool Err = false; 2261 switch (BuiltinID) { 2262 default: 2263 return false; 2264 #include "clang/Basic/arm_cde_builtin_sema.inc" 2265 } 2266 2267 if (Err) 2268 return true; 2269 2270 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2271 } 2272 2273 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2274 const Expr *CoprocArg, bool WantCDE) { 2275 if (isConstantEvaluated()) 2276 return false; 2277 2278 // We can't check the value of a dependent argument. 2279 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2280 return false; 2281 2282 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2283 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2284 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2285 2286 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2287 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2288 2289 if (IsCDECoproc != WantCDE) 2290 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2291 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2292 2293 return false; 2294 } 2295 2296 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2297 unsigned MaxWidth) { 2298 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2299 BuiltinID == ARM::BI__builtin_arm_ldaex || 2300 BuiltinID == ARM::BI__builtin_arm_strex || 2301 BuiltinID == ARM::BI__builtin_arm_stlex || 2302 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2303 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2304 BuiltinID == AArch64::BI__builtin_arm_strex || 2305 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2306 "unexpected ARM builtin"); 2307 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2308 BuiltinID == ARM::BI__builtin_arm_ldaex || 2309 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2310 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2311 2312 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2313 2314 // Ensure that we have the proper number of arguments. 2315 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2316 return true; 2317 2318 // Inspect the pointer argument of the atomic builtin. This should always be 2319 // a pointer type, whose element is an integral scalar or pointer type. 2320 // Because it is a pointer type, we don't have to worry about any implicit 2321 // casts here. 2322 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2323 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2324 if (PointerArgRes.isInvalid()) 2325 return true; 2326 PointerArg = PointerArgRes.get(); 2327 2328 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2329 if (!pointerType) { 2330 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2331 << PointerArg->getType() << PointerArg->getSourceRange(); 2332 return true; 2333 } 2334 2335 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2336 // task is to insert the appropriate casts into the AST. First work out just 2337 // what the appropriate type is. 2338 QualType ValType = pointerType->getPointeeType(); 2339 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2340 if (IsLdrex) 2341 AddrType.addConst(); 2342 2343 // Issue a warning if the cast is dodgy. 2344 CastKind CastNeeded = CK_NoOp; 2345 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2346 CastNeeded = CK_BitCast; 2347 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2348 << PointerArg->getType() << Context.getPointerType(AddrType) 2349 << AA_Passing << PointerArg->getSourceRange(); 2350 } 2351 2352 // Finally, do the cast and replace the argument with the corrected version. 2353 AddrType = Context.getPointerType(AddrType); 2354 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2355 if (PointerArgRes.isInvalid()) 2356 return true; 2357 PointerArg = PointerArgRes.get(); 2358 2359 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2360 2361 // In general, we allow ints, floats and pointers to be loaded and stored. 2362 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2363 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2364 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2365 << PointerArg->getType() << PointerArg->getSourceRange(); 2366 return true; 2367 } 2368 2369 // But ARM doesn't have instructions to deal with 128-bit versions. 2370 if (Context.getTypeSize(ValType) > MaxWidth) { 2371 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2372 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2373 << PointerArg->getType() << PointerArg->getSourceRange(); 2374 return true; 2375 } 2376 2377 switch (ValType.getObjCLifetime()) { 2378 case Qualifiers::OCL_None: 2379 case Qualifiers::OCL_ExplicitNone: 2380 // okay 2381 break; 2382 2383 case Qualifiers::OCL_Weak: 2384 case Qualifiers::OCL_Strong: 2385 case Qualifiers::OCL_Autoreleasing: 2386 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2387 << ValType << PointerArg->getSourceRange(); 2388 return true; 2389 } 2390 2391 if (IsLdrex) { 2392 TheCall->setType(ValType); 2393 return false; 2394 } 2395 2396 // Initialize the argument to be stored. 2397 ExprResult ValArg = TheCall->getArg(0); 2398 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2399 Context, ValType, /*consume*/ false); 2400 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2401 if (ValArg.isInvalid()) 2402 return true; 2403 TheCall->setArg(0, ValArg.get()); 2404 2405 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2406 // but the custom checker bypasses all default analysis. 2407 TheCall->setType(Context.IntTy); 2408 return false; 2409 } 2410 2411 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2412 CallExpr *TheCall) { 2413 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2414 BuiltinID == ARM::BI__builtin_arm_ldaex || 2415 BuiltinID == ARM::BI__builtin_arm_strex || 2416 BuiltinID == ARM::BI__builtin_arm_stlex) { 2417 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2418 } 2419 2420 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2421 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2422 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2423 } 2424 2425 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2426 BuiltinID == ARM::BI__builtin_arm_wsr64) 2427 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2428 2429 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2430 BuiltinID == ARM::BI__builtin_arm_rsrp || 2431 BuiltinID == ARM::BI__builtin_arm_wsr || 2432 BuiltinID == ARM::BI__builtin_arm_wsrp) 2433 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2434 2435 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2436 return true; 2437 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2438 return true; 2439 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2440 return true; 2441 2442 // For intrinsics which take an immediate value as part of the instruction, 2443 // range check them here. 2444 // FIXME: VFP Intrinsics should error if VFP not present. 2445 switch (BuiltinID) { 2446 default: return false; 2447 case ARM::BI__builtin_arm_ssat: 2448 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2449 case ARM::BI__builtin_arm_usat: 2450 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2451 case ARM::BI__builtin_arm_ssat16: 2452 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2453 case ARM::BI__builtin_arm_usat16: 2454 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2455 case ARM::BI__builtin_arm_vcvtr_f: 2456 case ARM::BI__builtin_arm_vcvtr_d: 2457 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2458 case ARM::BI__builtin_arm_dmb: 2459 case ARM::BI__builtin_arm_dsb: 2460 case ARM::BI__builtin_arm_isb: 2461 case ARM::BI__builtin_arm_dbg: 2462 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2463 case ARM::BI__builtin_arm_cdp: 2464 case ARM::BI__builtin_arm_cdp2: 2465 case ARM::BI__builtin_arm_mcr: 2466 case ARM::BI__builtin_arm_mcr2: 2467 case ARM::BI__builtin_arm_mrc: 2468 case ARM::BI__builtin_arm_mrc2: 2469 case ARM::BI__builtin_arm_mcrr: 2470 case ARM::BI__builtin_arm_mcrr2: 2471 case ARM::BI__builtin_arm_mrrc: 2472 case ARM::BI__builtin_arm_mrrc2: 2473 case ARM::BI__builtin_arm_ldc: 2474 case ARM::BI__builtin_arm_ldcl: 2475 case ARM::BI__builtin_arm_ldc2: 2476 case ARM::BI__builtin_arm_ldc2l: 2477 case ARM::BI__builtin_arm_stc: 2478 case ARM::BI__builtin_arm_stcl: 2479 case ARM::BI__builtin_arm_stc2: 2480 case ARM::BI__builtin_arm_stc2l: 2481 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2482 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2483 /*WantCDE*/ false); 2484 } 2485 } 2486 2487 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2488 unsigned BuiltinID, 2489 CallExpr *TheCall) { 2490 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2491 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2492 BuiltinID == AArch64::BI__builtin_arm_strex || 2493 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2494 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2495 } 2496 2497 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2498 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2499 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2500 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2501 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2502 } 2503 2504 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2505 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2506 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2507 2508 // Memory Tagging Extensions (MTE) Intrinsics 2509 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2510 BuiltinID == AArch64::BI__builtin_arm_addg || 2511 BuiltinID == AArch64::BI__builtin_arm_gmi || 2512 BuiltinID == AArch64::BI__builtin_arm_ldg || 2513 BuiltinID == AArch64::BI__builtin_arm_stg || 2514 BuiltinID == AArch64::BI__builtin_arm_subp) { 2515 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2516 } 2517 2518 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2519 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2520 BuiltinID == AArch64::BI__builtin_arm_wsr || 2521 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2522 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2523 2524 // Only check the valid encoding range. Any constant in this range would be 2525 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2526 // an exception for incorrect registers. This matches MSVC behavior. 2527 if (BuiltinID == AArch64::BI_ReadStatusReg || 2528 BuiltinID == AArch64::BI_WriteStatusReg) 2529 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2530 2531 if (BuiltinID == AArch64::BI__getReg) 2532 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2533 2534 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2535 return true; 2536 2537 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2538 return true; 2539 2540 // For intrinsics which take an immediate value as part of the instruction, 2541 // range check them here. 2542 unsigned i = 0, l = 0, u = 0; 2543 switch (BuiltinID) { 2544 default: return false; 2545 case AArch64::BI__builtin_arm_dmb: 2546 case AArch64::BI__builtin_arm_dsb: 2547 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2548 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2549 } 2550 2551 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2552 } 2553 2554 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2555 if (Arg->getType()->getAsPlaceholderType()) 2556 return false; 2557 2558 // The first argument needs to be a record field access. 2559 // If it is an array element access, we delay decision 2560 // to BPF backend to check whether the access is a 2561 // field access or not. 2562 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2563 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2564 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2565 } 2566 2567 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2568 QualType VectorTy, QualType EltTy) { 2569 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2570 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2571 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2572 << Call->getSourceRange() << VectorEltTy << EltTy; 2573 return false; 2574 } 2575 return true; 2576 } 2577 2578 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2579 QualType ArgType = Arg->getType(); 2580 if (ArgType->getAsPlaceholderType()) 2581 return false; 2582 2583 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2584 // format: 2585 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2586 // 2. <type> var; 2587 // __builtin_preserve_type_info(var, flag); 2588 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2589 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2590 return false; 2591 2592 // Typedef type. 2593 if (ArgType->getAs<TypedefType>()) 2594 return true; 2595 2596 // Record type or Enum type. 2597 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2598 if (const auto *RT = Ty->getAs<RecordType>()) { 2599 if (!RT->getDecl()->getDeclName().isEmpty()) 2600 return true; 2601 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2602 if (!ET->getDecl()->getDeclName().isEmpty()) 2603 return true; 2604 } 2605 2606 return false; 2607 } 2608 2609 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2610 QualType ArgType = Arg->getType(); 2611 if (ArgType->getAsPlaceholderType()) 2612 return false; 2613 2614 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2615 // format: 2616 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2617 // flag); 2618 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2619 if (!UO) 2620 return false; 2621 2622 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2623 if (!CE || CE->getCastKind() != CK_IntegralToPointer) 2624 return false; 2625 2626 // The integer must be from an EnumConstantDecl. 2627 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2628 if (!DR) 2629 return false; 2630 2631 const EnumConstantDecl *Enumerator = 2632 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2633 if (!Enumerator) 2634 return false; 2635 2636 // The type must be EnumType. 2637 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2638 const auto *ET = Ty->getAs<EnumType>(); 2639 if (!ET) 2640 return false; 2641 2642 // The enum value must be supported. 2643 for (auto *EDI : ET->getDecl()->enumerators()) { 2644 if (EDI == Enumerator) 2645 return true; 2646 } 2647 2648 return false; 2649 } 2650 2651 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2652 CallExpr *TheCall) { 2653 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2654 BuiltinID == BPF::BI__builtin_btf_type_id || 2655 BuiltinID == BPF::BI__builtin_preserve_type_info || 2656 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2657 "unexpected BPF builtin"); 2658 2659 if (checkArgCount(*this, TheCall, 2)) 2660 return true; 2661 2662 // The second argument needs to be a constant int 2663 Expr *Arg = TheCall->getArg(1); 2664 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2665 diag::kind kind; 2666 if (!Value) { 2667 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2668 kind = diag::err_preserve_field_info_not_const; 2669 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2670 kind = diag::err_btf_type_id_not_const; 2671 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2672 kind = diag::err_preserve_type_info_not_const; 2673 else 2674 kind = diag::err_preserve_enum_value_not_const; 2675 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2676 return true; 2677 } 2678 2679 // The first argument 2680 Arg = TheCall->getArg(0); 2681 bool InvalidArg = false; 2682 bool ReturnUnsignedInt = true; 2683 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2684 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2685 InvalidArg = true; 2686 kind = diag::err_preserve_field_info_not_field; 2687 } 2688 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2689 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2690 InvalidArg = true; 2691 kind = diag::err_preserve_type_info_invalid; 2692 } 2693 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2694 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2695 InvalidArg = true; 2696 kind = diag::err_preserve_enum_value_invalid; 2697 } 2698 ReturnUnsignedInt = false; 2699 } 2700 2701 if (InvalidArg) { 2702 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2703 return true; 2704 } 2705 2706 if (ReturnUnsignedInt) 2707 TheCall->setType(Context.UnsignedIntTy); 2708 else 2709 TheCall->setType(Context.UnsignedLongTy); 2710 return false; 2711 } 2712 2713 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2714 struct ArgInfo { 2715 uint8_t OpNum; 2716 bool IsSigned; 2717 uint8_t BitWidth; 2718 uint8_t Align; 2719 }; 2720 struct BuiltinInfo { 2721 unsigned BuiltinID; 2722 ArgInfo Infos[2]; 2723 }; 2724 2725 static BuiltinInfo Infos[] = { 2726 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2727 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2728 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2729 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2730 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2731 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2732 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2733 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2734 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2735 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2736 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2737 2738 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2739 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2745 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2749 2750 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2802 {{ 1, false, 6, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2810 {{ 1, false, 5, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2817 { 2, false, 5, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2819 { 2, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2821 { 3, false, 5, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2823 { 3, false, 6, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2840 {{ 2, false, 4, 0 }, 2841 { 3, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2843 {{ 2, false, 4, 0 }, 2844 { 3, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2846 {{ 2, false, 4, 0 }, 2847 { 3, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2849 {{ 2, false, 4, 0 }, 2850 { 3, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2862 { 2, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2864 { 2, false, 6, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2874 {{ 1, false, 4, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2877 {{ 1, false, 4, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2898 {{ 3, false, 1, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2903 {{ 3, false, 1, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2908 {{ 3, false, 1, 0 }} }, 2909 }; 2910 2911 // Use a dynamically initialized static to sort the table exactly once on 2912 // first run. 2913 static const bool SortOnce = 2914 (llvm::sort(Infos, 2915 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2916 return LHS.BuiltinID < RHS.BuiltinID; 2917 }), 2918 true); 2919 (void)SortOnce; 2920 2921 const BuiltinInfo *F = llvm::partition_point( 2922 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2923 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2924 return false; 2925 2926 bool Error = false; 2927 2928 for (const ArgInfo &A : F->Infos) { 2929 // Ignore empty ArgInfo elements. 2930 if (A.BitWidth == 0) 2931 continue; 2932 2933 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2934 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2935 if (!A.Align) { 2936 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2937 } else { 2938 unsigned M = 1 << A.Align; 2939 Min *= M; 2940 Max *= M; 2941 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2942 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2943 } 2944 } 2945 return Error; 2946 } 2947 2948 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2949 CallExpr *TheCall) { 2950 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2951 } 2952 2953 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2954 unsigned BuiltinID, CallExpr *TheCall) { 2955 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2956 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2957 } 2958 2959 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2960 CallExpr *TheCall) { 2961 2962 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2963 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2964 if (!TI.hasFeature("dsp")) 2965 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2966 } 2967 2968 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2969 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2970 if (!TI.hasFeature("dspr2")) 2971 return Diag(TheCall->getBeginLoc(), 2972 diag::err_mips_builtin_requires_dspr2); 2973 } 2974 2975 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2976 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2977 if (!TI.hasFeature("msa")) 2978 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2979 } 2980 2981 return false; 2982 } 2983 2984 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2985 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2986 // ordering for DSP is unspecified. MSA is ordered by the data format used 2987 // by the underlying instruction i.e., df/m, df/n and then by size. 2988 // 2989 // FIXME: The size tests here should instead be tablegen'd along with the 2990 // definitions from include/clang/Basic/BuiltinsMips.def. 2991 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2992 // be too. 2993 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2994 unsigned i = 0, l = 0, u = 0, m = 0; 2995 switch (BuiltinID) { 2996 default: return false; 2997 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2998 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2999 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3000 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3001 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3002 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3003 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3004 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3005 // df/m field. 3006 // These intrinsics take an unsigned 3 bit immediate. 3007 case Mips::BI__builtin_msa_bclri_b: 3008 case Mips::BI__builtin_msa_bnegi_b: 3009 case Mips::BI__builtin_msa_bseti_b: 3010 case Mips::BI__builtin_msa_sat_s_b: 3011 case Mips::BI__builtin_msa_sat_u_b: 3012 case Mips::BI__builtin_msa_slli_b: 3013 case Mips::BI__builtin_msa_srai_b: 3014 case Mips::BI__builtin_msa_srari_b: 3015 case Mips::BI__builtin_msa_srli_b: 3016 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3017 case Mips::BI__builtin_msa_binsli_b: 3018 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3019 // These intrinsics take an unsigned 4 bit immediate. 3020 case Mips::BI__builtin_msa_bclri_h: 3021 case Mips::BI__builtin_msa_bnegi_h: 3022 case Mips::BI__builtin_msa_bseti_h: 3023 case Mips::BI__builtin_msa_sat_s_h: 3024 case Mips::BI__builtin_msa_sat_u_h: 3025 case Mips::BI__builtin_msa_slli_h: 3026 case Mips::BI__builtin_msa_srai_h: 3027 case Mips::BI__builtin_msa_srari_h: 3028 case Mips::BI__builtin_msa_srli_h: 3029 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3030 case Mips::BI__builtin_msa_binsli_h: 3031 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3032 // These intrinsics take an unsigned 5 bit immediate. 3033 // The first block of intrinsics actually have an unsigned 5 bit field, 3034 // not a df/n field. 3035 case Mips::BI__builtin_msa_cfcmsa: 3036 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3037 case Mips::BI__builtin_msa_clei_u_b: 3038 case Mips::BI__builtin_msa_clei_u_h: 3039 case Mips::BI__builtin_msa_clei_u_w: 3040 case Mips::BI__builtin_msa_clei_u_d: 3041 case Mips::BI__builtin_msa_clti_u_b: 3042 case Mips::BI__builtin_msa_clti_u_h: 3043 case Mips::BI__builtin_msa_clti_u_w: 3044 case Mips::BI__builtin_msa_clti_u_d: 3045 case Mips::BI__builtin_msa_maxi_u_b: 3046 case Mips::BI__builtin_msa_maxi_u_h: 3047 case Mips::BI__builtin_msa_maxi_u_w: 3048 case Mips::BI__builtin_msa_maxi_u_d: 3049 case Mips::BI__builtin_msa_mini_u_b: 3050 case Mips::BI__builtin_msa_mini_u_h: 3051 case Mips::BI__builtin_msa_mini_u_w: 3052 case Mips::BI__builtin_msa_mini_u_d: 3053 case Mips::BI__builtin_msa_addvi_b: 3054 case Mips::BI__builtin_msa_addvi_h: 3055 case Mips::BI__builtin_msa_addvi_w: 3056 case Mips::BI__builtin_msa_addvi_d: 3057 case Mips::BI__builtin_msa_bclri_w: 3058 case Mips::BI__builtin_msa_bnegi_w: 3059 case Mips::BI__builtin_msa_bseti_w: 3060 case Mips::BI__builtin_msa_sat_s_w: 3061 case Mips::BI__builtin_msa_sat_u_w: 3062 case Mips::BI__builtin_msa_slli_w: 3063 case Mips::BI__builtin_msa_srai_w: 3064 case Mips::BI__builtin_msa_srari_w: 3065 case Mips::BI__builtin_msa_srli_w: 3066 case Mips::BI__builtin_msa_srlri_w: 3067 case Mips::BI__builtin_msa_subvi_b: 3068 case Mips::BI__builtin_msa_subvi_h: 3069 case Mips::BI__builtin_msa_subvi_w: 3070 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3071 case Mips::BI__builtin_msa_binsli_w: 3072 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3073 // These intrinsics take an unsigned 6 bit immediate. 3074 case Mips::BI__builtin_msa_bclri_d: 3075 case Mips::BI__builtin_msa_bnegi_d: 3076 case Mips::BI__builtin_msa_bseti_d: 3077 case Mips::BI__builtin_msa_sat_s_d: 3078 case Mips::BI__builtin_msa_sat_u_d: 3079 case Mips::BI__builtin_msa_slli_d: 3080 case Mips::BI__builtin_msa_srai_d: 3081 case Mips::BI__builtin_msa_srari_d: 3082 case Mips::BI__builtin_msa_srli_d: 3083 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3084 case Mips::BI__builtin_msa_binsli_d: 3085 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3086 // These intrinsics take a signed 5 bit immediate. 3087 case Mips::BI__builtin_msa_ceqi_b: 3088 case Mips::BI__builtin_msa_ceqi_h: 3089 case Mips::BI__builtin_msa_ceqi_w: 3090 case Mips::BI__builtin_msa_ceqi_d: 3091 case Mips::BI__builtin_msa_clti_s_b: 3092 case Mips::BI__builtin_msa_clti_s_h: 3093 case Mips::BI__builtin_msa_clti_s_w: 3094 case Mips::BI__builtin_msa_clti_s_d: 3095 case Mips::BI__builtin_msa_clei_s_b: 3096 case Mips::BI__builtin_msa_clei_s_h: 3097 case Mips::BI__builtin_msa_clei_s_w: 3098 case Mips::BI__builtin_msa_clei_s_d: 3099 case Mips::BI__builtin_msa_maxi_s_b: 3100 case Mips::BI__builtin_msa_maxi_s_h: 3101 case Mips::BI__builtin_msa_maxi_s_w: 3102 case Mips::BI__builtin_msa_maxi_s_d: 3103 case Mips::BI__builtin_msa_mini_s_b: 3104 case Mips::BI__builtin_msa_mini_s_h: 3105 case Mips::BI__builtin_msa_mini_s_w: 3106 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3107 // These intrinsics take an unsigned 8 bit immediate. 3108 case Mips::BI__builtin_msa_andi_b: 3109 case Mips::BI__builtin_msa_nori_b: 3110 case Mips::BI__builtin_msa_ori_b: 3111 case Mips::BI__builtin_msa_shf_b: 3112 case Mips::BI__builtin_msa_shf_h: 3113 case Mips::BI__builtin_msa_shf_w: 3114 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3115 case Mips::BI__builtin_msa_bseli_b: 3116 case Mips::BI__builtin_msa_bmnzi_b: 3117 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3118 // df/n format 3119 // These intrinsics take an unsigned 4 bit immediate. 3120 case Mips::BI__builtin_msa_copy_s_b: 3121 case Mips::BI__builtin_msa_copy_u_b: 3122 case Mips::BI__builtin_msa_insve_b: 3123 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3124 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3125 // These intrinsics take an unsigned 3 bit immediate. 3126 case Mips::BI__builtin_msa_copy_s_h: 3127 case Mips::BI__builtin_msa_copy_u_h: 3128 case Mips::BI__builtin_msa_insve_h: 3129 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3130 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3131 // These intrinsics take an unsigned 2 bit immediate. 3132 case Mips::BI__builtin_msa_copy_s_w: 3133 case Mips::BI__builtin_msa_copy_u_w: 3134 case Mips::BI__builtin_msa_insve_w: 3135 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3136 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3137 // These intrinsics take an unsigned 1 bit immediate. 3138 case Mips::BI__builtin_msa_copy_s_d: 3139 case Mips::BI__builtin_msa_copy_u_d: 3140 case Mips::BI__builtin_msa_insve_d: 3141 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3142 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3143 // Memory offsets and immediate loads. 3144 // These intrinsics take a signed 10 bit immediate. 3145 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3146 case Mips::BI__builtin_msa_ldi_h: 3147 case Mips::BI__builtin_msa_ldi_w: 3148 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3149 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3150 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3151 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3152 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3153 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3154 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3155 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3156 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3157 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3158 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3159 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3160 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3161 } 3162 3163 if (!m) 3164 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3165 3166 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3167 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3168 } 3169 3170 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3171 CallExpr *TheCall) { 3172 unsigned i = 0, l = 0, u = 0; 3173 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3174 BuiltinID == PPC::BI__builtin_divdeu || 3175 BuiltinID == PPC::BI__builtin_bpermd; 3176 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3177 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3178 BuiltinID == PPC::BI__builtin_divweu || 3179 BuiltinID == PPC::BI__builtin_divde || 3180 BuiltinID == PPC::BI__builtin_divdeu; 3181 3182 if (Is64BitBltin && !IsTarget64Bit) 3183 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3184 << TheCall->getSourceRange(); 3185 3186 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3187 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3188 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3189 << TheCall->getSourceRange(); 3190 3191 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3192 if (!TI.hasFeature("vsx")) 3193 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3194 << TheCall->getSourceRange(); 3195 return false; 3196 }; 3197 3198 switch (BuiltinID) { 3199 default: return false; 3200 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3201 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3202 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3203 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3204 case PPC::BI__builtin_altivec_dss: 3205 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3206 case PPC::BI__builtin_tbegin: 3207 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3208 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3209 case PPC::BI__builtin_tabortwc: 3210 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3211 case PPC::BI__builtin_tabortwci: 3212 case PPC::BI__builtin_tabortdci: 3213 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3214 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3215 case PPC::BI__builtin_altivec_dst: 3216 case PPC::BI__builtin_altivec_dstt: 3217 case PPC::BI__builtin_altivec_dstst: 3218 case PPC::BI__builtin_altivec_dststt: 3219 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3220 case PPC::BI__builtin_vsx_xxpermdi: 3221 case PPC::BI__builtin_vsx_xxsldwi: 3222 return SemaBuiltinVSX(TheCall); 3223 case PPC::BI__builtin_unpack_vector_int128: 3224 return SemaVSXCheck(TheCall) || 3225 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3226 case PPC::BI__builtin_pack_vector_int128: 3227 return SemaVSXCheck(TheCall); 3228 case PPC::BI__builtin_altivec_vgnb: 3229 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3230 case PPC::BI__builtin_altivec_vec_replace_elt: 3231 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3232 QualType VecTy = TheCall->getArg(0)->getType(); 3233 QualType EltTy = TheCall->getArg(1)->getType(); 3234 unsigned Width = Context.getIntWidth(EltTy); 3235 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3236 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3237 } 3238 case PPC::BI__builtin_vsx_xxeval: 3239 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3240 case PPC::BI__builtin_altivec_vsldbi: 3241 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3242 case PPC::BI__builtin_altivec_vsrdbi: 3243 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3244 case PPC::BI__builtin_vsx_xxpermx: 3245 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3246 } 3247 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3248 } 3249 3250 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3251 CallExpr *TheCall) { 3252 // position of memory order and scope arguments in the builtin 3253 unsigned OrderIndex, ScopeIndex; 3254 switch (BuiltinID) { 3255 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3256 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3257 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3258 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3259 OrderIndex = 2; 3260 ScopeIndex = 3; 3261 break; 3262 case AMDGPU::BI__builtin_amdgcn_fence: 3263 OrderIndex = 0; 3264 ScopeIndex = 1; 3265 break; 3266 default: 3267 return false; 3268 } 3269 3270 ExprResult Arg = TheCall->getArg(OrderIndex); 3271 auto ArgExpr = Arg.get(); 3272 Expr::EvalResult ArgResult; 3273 3274 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3275 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3276 << ArgExpr->getType(); 3277 int ord = ArgResult.Val.getInt().getZExtValue(); 3278 3279 // Check valididty of memory ordering as per C11 / C++11's memody model. 3280 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3281 case llvm::AtomicOrderingCABI::acquire: 3282 case llvm::AtomicOrderingCABI::release: 3283 case llvm::AtomicOrderingCABI::acq_rel: 3284 case llvm::AtomicOrderingCABI::seq_cst: 3285 break; 3286 default: { 3287 return Diag(ArgExpr->getBeginLoc(), 3288 diag::warn_atomic_op_has_invalid_memory_order) 3289 << ArgExpr->getSourceRange(); 3290 } 3291 } 3292 3293 Arg = TheCall->getArg(ScopeIndex); 3294 ArgExpr = Arg.get(); 3295 Expr::EvalResult ArgResult1; 3296 // Check that sync scope is a constant literal 3297 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3298 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3299 << ArgExpr->getType(); 3300 3301 return false; 3302 } 3303 3304 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3305 CallExpr *TheCall) { 3306 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3307 Expr *Arg = TheCall->getArg(0); 3308 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3309 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3310 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3311 << Arg->getSourceRange(); 3312 } 3313 3314 // For intrinsics which take an immediate value as part of the instruction, 3315 // range check them here. 3316 unsigned i = 0, l = 0, u = 0; 3317 switch (BuiltinID) { 3318 default: return false; 3319 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3320 case SystemZ::BI__builtin_s390_verimb: 3321 case SystemZ::BI__builtin_s390_verimh: 3322 case SystemZ::BI__builtin_s390_verimf: 3323 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3324 case SystemZ::BI__builtin_s390_vfaeb: 3325 case SystemZ::BI__builtin_s390_vfaeh: 3326 case SystemZ::BI__builtin_s390_vfaef: 3327 case SystemZ::BI__builtin_s390_vfaebs: 3328 case SystemZ::BI__builtin_s390_vfaehs: 3329 case SystemZ::BI__builtin_s390_vfaefs: 3330 case SystemZ::BI__builtin_s390_vfaezb: 3331 case SystemZ::BI__builtin_s390_vfaezh: 3332 case SystemZ::BI__builtin_s390_vfaezf: 3333 case SystemZ::BI__builtin_s390_vfaezbs: 3334 case SystemZ::BI__builtin_s390_vfaezhs: 3335 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3336 case SystemZ::BI__builtin_s390_vfisb: 3337 case SystemZ::BI__builtin_s390_vfidb: 3338 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3339 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3340 case SystemZ::BI__builtin_s390_vftcisb: 3341 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3342 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3343 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3344 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3345 case SystemZ::BI__builtin_s390_vstrcb: 3346 case SystemZ::BI__builtin_s390_vstrch: 3347 case SystemZ::BI__builtin_s390_vstrcf: 3348 case SystemZ::BI__builtin_s390_vstrczb: 3349 case SystemZ::BI__builtin_s390_vstrczh: 3350 case SystemZ::BI__builtin_s390_vstrczf: 3351 case SystemZ::BI__builtin_s390_vstrcbs: 3352 case SystemZ::BI__builtin_s390_vstrchs: 3353 case SystemZ::BI__builtin_s390_vstrcfs: 3354 case SystemZ::BI__builtin_s390_vstrczbs: 3355 case SystemZ::BI__builtin_s390_vstrczhs: 3356 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3357 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3358 case SystemZ::BI__builtin_s390_vfminsb: 3359 case SystemZ::BI__builtin_s390_vfmaxsb: 3360 case SystemZ::BI__builtin_s390_vfmindb: 3361 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3362 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3363 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3364 } 3365 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3366 } 3367 3368 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3369 /// This checks that the target supports __builtin_cpu_supports and 3370 /// that the string argument is constant and valid. 3371 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3372 CallExpr *TheCall) { 3373 Expr *Arg = TheCall->getArg(0); 3374 3375 // Check if the argument is a string literal. 3376 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3377 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3378 << Arg->getSourceRange(); 3379 3380 // Check the contents of the string. 3381 StringRef Feature = 3382 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3383 if (!TI.validateCpuSupports(Feature)) 3384 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3385 << Arg->getSourceRange(); 3386 return false; 3387 } 3388 3389 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3390 /// This checks that the target supports __builtin_cpu_is and 3391 /// that the string argument is constant and valid. 3392 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3393 Expr *Arg = TheCall->getArg(0); 3394 3395 // Check if the argument is a string literal. 3396 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3397 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3398 << Arg->getSourceRange(); 3399 3400 // Check the contents of the string. 3401 StringRef Feature = 3402 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3403 if (!TI.validateCpuIs(Feature)) 3404 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3405 << Arg->getSourceRange(); 3406 return false; 3407 } 3408 3409 // Check if the rounding mode is legal. 3410 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3411 // Indicates if this instruction has rounding control or just SAE. 3412 bool HasRC = false; 3413 3414 unsigned ArgNum = 0; 3415 switch (BuiltinID) { 3416 default: 3417 return false; 3418 case X86::BI__builtin_ia32_vcvttsd2si32: 3419 case X86::BI__builtin_ia32_vcvttsd2si64: 3420 case X86::BI__builtin_ia32_vcvttsd2usi32: 3421 case X86::BI__builtin_ia32_vcvttsd2usi64: 3422 case X86::BI__builtin_ia32_vcvttss2si32: 3423 case X86::BI__builtin_ia32_vcvttss2si64: 3424 case X86::BI__builtin_ia32_vcvttss2usi32: 3425 case X86::BI__builtin_ia32_vcvttss2usi64: 3426 ArgNum = 1; 3427 break; 3428 case X86::BI__builtin_ia32_maxpd512: 3429 case X86::BI__builtin_ia32_maxps512: 3430 case X86::BI__builtin_ia32_minpd512: 3431 case X86::BI__builtin_ia32_minps512: 3432 ArgNum = 2; 3433 break; 3434 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3435 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3436 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3437 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3438 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3439 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3440 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3441 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3442 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3443 case X86::BI__builtin_ia32_exp2pd_mask: 3444 case X86::BI__builtin_ia32_exp2ps_mask: 3445 case X86::BI__builtin_ia32_getexppd512_mask: 3446 case X86::BI__builtin_ia32_getexpps512_mask: 3447 case X86::BI__builtin_ia32_rcp28pd_mask: 3448 case X86::BI__builtin_ia32_rcp28ps_mask: 3449 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3450 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3451 case X86::BI__builtin_ia32_vcomisd: 3452 case X86::BI__builtin_ia32_vcomiss: 3453 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3454 ArgNum = 3; 3455 break; 3456 case X86::BI__builtin_ia32_cmppd512_mask: 3457 case X86::BI__builtin_ia32_cmpps512_mask: 3458 case X86::BI__builtin_ia32_cmpsd_mask: 3459 case X86::BI__builtin_ia32_cmpss_mask: 3460 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3461 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3462 case X86::BI__builtin_ia32_getexpss128_round_mask: 3463 case X86::BI__builtin_ia32_getmantpd512_mask: 3464 case X86::BI__builtin_ia32_getmantps512_mask: 3465 case X86::BI__builtin_ia32_maxsd_round_mask: 3466 case X86::BI__builtin_ia32_maxss_round_mask: 3467 case X86::BI__builtin_ia32_minsd_round_mask: 3468 case X86::BI__builtin_ia32_minss_round_mask: 3469 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3470 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3471 case X86::BI__builtin_ia32_reducepd512_mask: 3472 case X86::BI__builtin_ia32_reduceps512_mask: 3473 case X86::BI__builtin_ia32_rndscalepd_mask: 3474 case X86::BI__builtin_ia32_rndscaleps_mask: 3475 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3476 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3477 ArgNum = 4; 3478 break; 3479 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3480 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3481 case X86::BI__builtin_ia32_fixupimmps512_mask: 3482 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3483 case X86::BI__builtin_ia32_fixupimmsd_mask: 3484 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3485 case X86::BI__builtin_ia32_fixupimmss_mask: 3486 case X86::BI__builtin_ia32_fixupimmss_maskz: 3487 case X86::BI__builtin_ia32_getmantsd_round_mask: 3488 case X86::BI__builtin_ia32_getmantss_round_mask: 3489 case X86::BI__builtin_ia32_rangepd512_mask: 3490 case X86::BI__builtin_ia32_rangeps512_mask: 3491 case X86::BI__builtin_ia32_rangesd128_round_mask: 3492 case X86::BI__builtin_ia32_rangess128_round_mask: 3493 case X86::BI__builtin_ia32_reducesd_mask: 3494 case X86::BI__builtin_ia32_reducess_mask: 3495 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3496 case X86::BI__builtin_ia32_rndscaless_round_mask: 3497 ArgNum = 5; 3498 break; 3499 case X86::BI__builtin_ia32_vcvtsd2si64: 3500 case X86::BI__builtin_ia32_vcvtsd2si32: 3501 case X86::BI__builtin_ia32_vcvtsd2usi32: 3502 case X86::BI__builtin_ia32_vcvtsd2usi64: 3503 case X86::BI__builtin_ia32_vcvtss2si32: 3504 case X86::BI__builtin_ia32_vcvtss2si64: 3505 case X86::BI__builtin_ia32_vcvtss2usi32: 3506 case X86::BI__builtin_ia32_vcvtss2usi64: 3507 case X86::BI__builtin_ia32_sqrtpd512: 3508 case X86::BI__builtin_ia32_sqrtps512: 3509 ArgNum = 1; 3510 HasRC = true; 3511 break; 3512 case X86::BI__builtin_ia32_addpd512: 3513 case X86::BI__builtin_ia32_addps512: 3514 case X86::BI__builtin_ia32_divpd512: 3515 case X86::BI__builtin_ia32_divps512: 3516 case X86::BI__builtin_ia32_mulpd512: 3517 case X86::BI__builtin_ia32_mulps512: 3518 case X86::BI__builtin_ia32_subpd512: 3519 case X86::BI__builtin_ia32_subps512: 3520 case X86::BI__builtin_ia32_cvtsi2sd64: 3521 case X86::BI__builtin_ia32_cvtsi2ss32: 3522 case X86::BI__builtin_ia32_cvtsi2ss64: 3523 case X86::BI__builtin_ia32_cvtusi2sd64: 3524 case X86::BI__builtin_ia32_cvtusi2ss32: 3525 case X86::BI__builtin_ia32_cvtusi2ss64: 3526 ArgNum = 2; 3527 HasRC = true; 3528 break; 3529 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3530 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3531 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3532 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3533 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3534 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3535 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3536 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3537 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3538 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3539 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3540 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3541 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3542 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3543 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3544 ArgNum = 3; 3545 HasRC = true; 3546 break; 3547 case X86::BI__builtin_ia32_addss_round_mask: 3548 case X86::BI__builtin_ia32_addsd_round_mask: 3549 case X86::BI__builtin_ia32_divss_round_mask: 3550 case X86::BI__builtin_ia32_divsd_round_mask: 3551 case X86::BI__builtin_ia32_mulss_round_mask: 3552 case X86::BI__builtin_ia32_mulsd_round_mask: 3553 case X86::BI__builtin_ia32_subss_round_mask: 3554 case X86::BI__builtin_ia32_subsd_round_mask: 3555 case X86::BI__builtin_ia32_scalefpd512_mask: 3556 case X86::BI__builtin_ia32_scalefps512_mask: 3557 case X86::BI__builtin_ia32_scalefsd_round_mask: 3558 case X86::BI__builtin_ia32_scalefss_round_mask: 3559 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3560 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3561 case X86::BI__builtin_ia32_sqrtss_round_mask: 3562 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3563 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3564 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3565 case X86::BI__builtin_ia32_vfmaddss3_mask: 3566 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3567 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3568 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3569 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3570 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3571 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3572 case X86::BI__builtin_ia32_vfmaddps512_mask: 3573 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3574 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3575 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3576 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3577 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3578 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3579 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3580 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3581 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3582 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3583 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3584 ArgNum = 4; 3585 HasRC = true; 3586 break; 3587 } 3588 3589 llvm::APSInt Result; 3590 3591 // We can't check the value of a dependent argument. 3592 Expr *Arg = TheCall->getArg(ArgNum); 3593 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3594 return false; 3595 3596 // Check constant-ness first. 3597 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3598 return true; 3599 3600 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3601 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3602 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3603 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3604 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3605 Result == 8/*ROUND_NO_EXC*/ || 3606 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3607 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3608 return false; 3609 3610 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3611 << Arg->getSourceRange(); 3612 } 3613 3614 // Check if the gather/scatter scale is legal. 3615 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3616 CallExpr *TheCall) { 3617 unsigned ArgNum = 0; 3618 switch (BuiltinID) { 3619 default: 3620 return false; 3621 case X86::BI__builtin_ia32_gatherpfdpd: 3622 case X86::BI__builtin_ia32_gatherpfdps: 3623 case X86::BI__builtin_ia32_gatherpfqpd: 3624 case X86::BI__builtin_ia32_gatherpfqps: 3625 case X86::BI__builtin_ia32_scatterpfdpd: 3626 case X86::BI__builtin_ia32_scatterpfdps: 3627 case X86::BI__builtin_ia32_scatterpfqpd: 3628 case X86::BI__builtin_ia32_scatterpfqps: 3629 ArgNum = 3; 3630 break; 3631 case X86::BI__builtin_ia32_gatherd_pd: 3632 case X86::BI__builtin_ia32_gatherd_pd256: 3633 case X86::BI__builtin_ia32_gatherq_pd: 3634 case X86::BI__builtin_ia32_gatherq_pd256: 3635 case X86::BI__builtin_ia32_gatherd_ps: 3636 case X86::BI__builtin_ia32_gatherd_ps256: 3637 case X86::BI__builtin_ia32_gatherq_ps: 3638 case X86::BI__builtin_ia32_gatherq_ps256: 3639 case X86::BI__builtin_ia32_gatherd_q: 3640 case X86::BI__builtin_ia32_gatherd_q256: 3641 case X86::BI__builtin_ia32_gatherq_q: 3642 case X86::BI__builtin_ia32_gatherq_q256: 3643 case X86::BI__builtin_ia32_gatherd_d: 3644 case X86::BI__builtin_ia32_gatherd_d256: 3645 case X86::BI__builtin_ia32_gatherq_d: 3646 case X86::BI__builtin_ia32_gatherq_d256: 3647 case X86::BI__builtin_ia32_gather3div2df: 3648 case X86::BI__builtin_ia32_gather3div2di: 3649 case X86::BI__builtin_ia32_gather3div4df: 3650 case X86::BI__builtin_ia32_gather3div4di: 3651 case X86::BI__builtin_ia32_gather3div4sf: 3652 case X86::BI__builtin_ia32_gather3div4si: 3653 case X86::BI__builtin_ia32_gather3div8sf: 3654 case X86::BI__builtin_ia32_gather3div8si: 3655 case X86::BI__builtin_ia32_gather3siv2df: 3656 case X86::BI__builtin_ia32_gather3siv2di: 3657 case X86::BI__builtin_ia32_gather3siv4df: 3658 case X86::BI__builtin_ia32_gather3siv4di: 3659 case X86::BI__builtin_ia32_gather3siv4sf: 3660 case X86::BI__builtin_ia32_gather3siv4si: 3661 case X86::BI__builtin_ia32_gather3siv8sf: 3662 case X86::BI__builtin_ia32_gather3siv8si: 3663 case X86::BI__builtin_ia32_gathersiv8df: 3664 case X86::BI__builtin_ia32_gathersiv16sf: 3665 case X86::BI__builtin_ia32_gatherdiv8df: 3666 case X86::BI__builtin_ia32_gatherdiv16sf: 3667 case X86::BI__builtin_ia32_gathersiv8di: 3668 case X86::BI__builtin_ia32_gathersiv16si: 3669 case X86::BI__builtin_ia32_gatherdiv8di: 3670 case X86::BI__builtin_ia32_gatherdiv16si: 3671 case X86::BI__builtin_ia32_scatterdiv2df: 3672 case X86::BI__builtin_ia32_scatterdiv2di: 3673 case X86::BI__builtin_ia32_scatterdiv4df: 3674 case X86::BI__builtin_ia32_scatterdiv4di: 3675 case X86::BI__builtin_ia32_scatterdiv4sf: 3676 case X86::BI__builtin_ia32_scatterdiv4si: 3677 case X86::BI__builtin_ia32_scatterdiv8sf: 3678 case X86::BI__builtin_ia32_scatterdiv8si: 3679 case X86::BI__builtin_ia32_scattersiv2df: 3680 case X86::BI__builtin_ia32_scattersiv2di: 3681 case X86::BI__builtin_ia32_scattersiv4df: 3682 case X86::BI__builtin_ia32_scattersiv4di: 3683 case X86::BI__builtin_ia32_scattersiv4sf: 3684 case X86::BI__builtin_ia32_scattersiv4si: 3685 case X86::BI__builtin_ia32_scattersiv8sf: 3686 case X86::BI__builtin_ia32_scattersiv8si: 3687 case X86::BI__builtin_ia32_scattersiv8df: 3688 case X86::BI__builtin_ia32_scattersiv16sf: 3689 case X86::BI__builtin_ia32_scatterdiv8df: 3690 case X86::BI__builtin_ia32_scatterdiv16sf: 3691 case X86::BI__builtin_ia32_scattersiv8di: 3692 case X86::BI__builtin_ia32_scattersiv16si: 3693 case X86::BI__builtin_ia32_scatterdiv8di: 3694 case X86::BI__builtin_ia32_scatterdiv16si: 3695 ArgNum = 4; 3696 break; 3697 } 3698 3699 llvm::APSInt Result; 3700 3701 // We can't check the value of a dependent argument. 3702 Expr *Arg = TheCall->getArg(ArgNum); 3703 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3704 return false; 3705 3706 // Check constant-ness first. 3707 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3708 return true; 3709 3710 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3711 return false; 3712 3713 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3714 << Arg->getSourceRange(); 3715 } 3716 3717 enum { TileRegLow = 0, TileRegHigh = 7 }; 3718 3719 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3720 ArrayRef<int> ArgNums) { 3721 for (int ArgNum : ArgNums) { 3722 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3723 return true; 3724 } 3725 return false; 3726 } 3727 3728 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3729 ArrayRef<int> ArgNums) { 3730 // Because the max number of tile register is TileRegHigh + 1, so here we use 3731 // each bit to represent the usage of them in bitset. 3732 std::bitset<TileRegHigh + 1> ArgValues; 3733 for (int ArgNum : ArgNums) { 3734 Expr *Arg = TheCall->getArg(ArgNum); 3735 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3736 continue; 3737 3738 llvm::APSInt Result; 3739 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3740 return true; 3741 int ArgExtValue = Result.getExtValue(); 3742 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3743 "Incorrect tile register num."); 3744 if (ArgValues.test(ArgExtValue)) 3745 return Diag(TheCall->getBeginLoc(), 3746 diag::err_x86_builtin_tile_arg_duplicate) 3747 << TheCall->getArg(ArgNum)->getSourceRange(); 3748 ArgValues.set(ArgExtValue); 3749 } 3750 return false; 3751 } 3752 3753 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3754 ArrayRef<int> ArgNums) { 3755 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3756 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3757 } 3758 3759 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3760 switch (BuiltinID) { 3761 default: 3762 return false; 3763 case X86::BI__builtin_ia32_tileloadd64: 3764 case X86::BI__builtin_ia32_tileloaddt164: 3765 case X86::BI__builtin_ia32_tilestored64: 3766 case X86::BI__builtin_ia32_tilezero: 3767 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3768 case X86::BI__builtin_ia32_tdpbssd: 3769 case X86::BI__builtin_ia32_tdpbsud: 3770 case X86::BI__builtin_ia32_tdpbusd: 3771 case X86::BI__builtin_ia32_tdpbuud: 3772 case X86::BI__builtin_ia32_tdpbf16ps: 3773 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3774 } 3775 } 3776 static bool isX86_32Builtin(unsigned BuiltinID) { 3777 // These builtins only work on x86-32 targets. 3778 switch (BuiltinID) { 3779 case X86::BI__builtin_ia32_readeflags_u32: 3780 case X86::BI__builtin_ia32_writeeflags_u32: 3781 return true; 3782 } 3783 3784 return false; 3785 } 3786 3787 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3788 CallExpr *TheCall) { 3789 if (BuiltinID == X86::BI__builtin_cpu_supports) 3790 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3791 3792 if (BuiltinID == X86::BI__builtin_cpu_is) 3793 return SemaBuiltinCpuIs(*this, TI, TheCall); 3794 3795 // Check for 32-bit only builtins on a 64-bit target. 3796 const llvm::Triple &TT = TI.getTriple(); 3797 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3798 return Diag(TheCall->getCallee()->getBeginLoc(), 3799 diag::err_32_bit_builtin_64_bit_tgt); 3800 3801 // If the intrinsic has rounding or SAE make sure its valid. 3802 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3803 return true; 3804 3805 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3806 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3807 return true; 3808 3809 // If the intrinsic has a tile arguments, make sure they are valid. 3810 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3811 return true; 3812 3813 // For intrinsics which take an immediate value as part of the instruction, 3814 // range check them here. 3815 int i = 0, l = 0, u = 0; 3816 switch (BuiltinID) { 3817 default: 3818 return false; 3819 case X86::BI__builtin_ia32_vec_ext_v2si: 3820 case X86::BI__builtin_ia32_vec_ext_v2di: 3821 case X86::BI__builtin_ia32_vextractf128_pd256: 3822 case X86::BI__builtin_ia32_vextractf128_ps256: 3823 case X86::BI__builtin_ia32_vextractf128_si256: 3824 case X86::BI__builtin_ia32_extract128i256: 3825 case X86::BI__builtin_ia32_extractf64x4_mask: 3826 case X86::BI__builtin_ia32_extracti64x4_mask: 3827 case X86::BI__builtin_ia32_extractf32x8_mask: 3828 case X86::BI__builtin_ia32_extracti32x8_mask: 3829 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3830 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3831 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3832 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3833 i = 1; l = 0; u = 1; 3834 break; 3835 case X86::BI__builtin_ia32_vec_set_v2di: 3836 case X86::BI__builtin_ia32_vinsertf128_pd256: 3837 case X86::BI__builtin_ia32_vinsertf128_ps256: 3838 case X86::BI__builtin_ia32_vinsertf128_si256: 3839 case X86::BI__builtin_ia32_insert128i256: 3840 case X86::BI__builtin_ia32_insertf32x8: 3841 case X86::BI__builtin_ia32_inserti32x8: 3842 case X86::BI__builtin_ia32_insertf64x4: 3843 case X86::BI__builtin_ia32_inserti64x4: 3844 case X86::BI__builtin_ia32_insertf64x2_256: 3845 case X86::BI__builtin_ia32_inserti64x2_256: 3846 case X86::BI__builtin_ia32_insertf32x4_256: 3847 case X86::BI__builtin_ia32_inserti32x4_256: 3848 i = 2; l = 0; u = 1; 3849 break; 3850 case X86::BI__builtin_ia32_vpermilpd: 3851 case X86::BI__builtin_ia32_vec_ext_v4hi: 3852 case X86::BI__builtin_ia32_vec_ext_v4si: 3853 case X86::BI__builtin_ia32_vec_ext_v4sf: 3854 case X86::BI__builtin_ia32_vec_ext_v4di: 3855 case X86::BI__builtin_ia32_extractf32x4_mask: 3856 case X86::BI__builtin_ia32_extracti32x4_mask: 3857 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3858 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3859 i = 1; l = 0; u = 3; 3860 break; 3861 case X86::BI_mm_prefetch: 3862 case X86::BI__builtin_ia32_vec_ext_v8hi: 3863 case X86::BI__builtin_ia32_vec_ext_v8si: 3864 i = 1; l = 0; u = 7; 3865 break; 3866 case X86::BI__builtin_ia32_sha1rnds4: 3867 case X86::BI__builtin_ia32_blendpd: 3868 case X86::BI__builtin_ia32_shufpd: 3869 case X86::BI__builtin_ia32_vec_set_v4hi: 3870 case X86::BI__builtin_ia32_vec_set_v4si: 3871 case X86::BI__builtin_ia32_vec_set_v4di: 3872 case X86::BI__builtin_ia32_shuf_f32x4_256: 3873 case X86::BI__builtin_ia32_shuf_f64x2_256: 3874 case X86::BI__builtin_ia32_shuf_i32x4_256: 3875 case X86::BI__builtin_ia32_shuf_i64x2_256: 3876 case X86::BI__builtin_ia32_insertf64x2_512: 3877 case X86::BI__builtin_ia32_inserti64x2_512: 3878 case X86::BI__builtin_ia32_insertf32x4: 3879 case X86::BI__builtin_ia32_inserti32x4: 3880 i = 2; l = 0; u = 3; 3881 break; 3882 case X86::BI__builtin_ia32_vpermil2pd: 3883 case X86::BI__builtin_ia32_vpermil2pd256: 3884 case X86::BI__builtin_ia32_vpermil2ps: 3885 case X86::BI__builtin_ia32_vpermil2ps256: 3886 i = 3; l = 0; u = 3; 3887 break; 3888 case X86::BI__builtin_ia32_cmpb128_mask: 3889 case X86::BI__builtin_ia32_cmpw128_mask: 3890 case X86::BI__builtin_ia32_cmpd128_mask: 3891 case X86::BI__builtin_ia32_cmpq128_mask: 3892 case X86::BI__builtin_ia32_cmpb256_mask: 3893 case X86::BI__builtin_ia32_cmpw256_mask: 3894 case X86::BI__builtin_ia32_cmpd256_mask: 3895 case X86::BI__builtin_ia32_cmpq256_mask: 3896 case X86::BI__builtin_ia32_cmpb512_mask: 3897 case X86::BI__builtin_ia32_cmpw512_mask: 3898 case X86::BI__builtin_ia32_cmpd512_mask: 3899 case X86::BI__builtin_ia32_cmpq512_mask: 3900 case X86::BI__builtin_ia32_ucmpb128_mask: 3901 case X86::BI__builtin_ia32_ucmpw128_mask: 3902 case X86::BI__builtin_ia32_ucmpd128_mask: 3903 case X86::BI__builtin_ia32_ucmpq128_mask: 3904 case X86::BI__builtin_ia32_ucmpb256_mask: 3905 case X86::BI__builtin_ia32_ucmpw256_mask: 3906 case X86::BI__builtin_ia32_ucmpd256_mask: 3907 case X86::BI__builtin_ia32_ucmpq256_mask: 3908 case X86::BI__builtin_ia32_ucmpb512_mask: 3909 case X86::BI__builtin_ia32_ucmpw512_mask: 3910 case X86::BI__builtin_ia32_ucmpd512_mask: 3911 case X86::BI__builtin_ia32_ucmpq512_mask: 3912 case X86::BI__builtin_ia32_vpcomub: 3913 case X86::BI__builtin_ia32_vpcomuw: 3914 case X86::BI__builtin_ia32_vpcomud: 3915 case X86::BI__builtin_ia32_vpcomuq: 3916 case X86::BI__builtin_ia32_vpcomb: 3917 case X86::BI__builtin_ia32_vpcomw: 3918 case X86::BI__builtin_ia32_vpcomd: 3919 case X86::BI__builtin_ia32_vpcomq: 3920 case X86::BI__builtin_ia32_vec_set_v8hi: 3921 case X86::BI__builtin_ia32_vec_set_v8si: 3922 i = 2; l = 0; u = 7; 3923 break; 3924 case X86::BI__builtin_ia32_vpermilpd256: 3925 case X86::BI__builtin_ia32_roundps: 3926 case X86::BI__builtin_ia32_roundpd: 3927 case X86::BI__builtin_ia32_roundps256: 3928 case X86::BI__builtin_ia32_roundpd256: 3929 case X86::BI__builtin_ia32_getmantpd128_mask: 3930 case X86::BI__builtin_ia32_getmantpd256_mask: 3931 case X86::BI__builtin_ia32_getmantps128_mask: 3932 case X86::BI__builtin_ia32_getmantps256_mask: 3933 case X86::BI__builtin_ia32_getmantpd512_mask: 3934 case X86::BI__builtin_ia32_getmantps512_mask: 3935 case X86::BI__builtin_ia32_vec_ext_v16qi: 3936 case X86::BI__builtin_ia32_vec_ext_v16hi: 3937 i = 1; l = 0; u = 15; 3938 break; 3939 case X86::BI__builtin_ia32_pblendd128: 3940 case X86::BI__builtin_ia32_blendps: 3941 case X86::BI__builtin_ia32_blendpd256: 3942 case X86::BI__builtin_ia32_shufpd256: 3943 case X86::BI__builtin_ia32_roundss: 3944 case X86::BI__builtin_ia32_roundsd: 3945 case X86::BI__builtin_ia32_rangepd128_mask: 3946 case X86::BI__builtin_ia32_rangepd256_mask: 3947 case X86::BI__builtin_ia32_rangepd512_mask: 3948 case X86::BI__builtin_ia32_rangeps128_mask: 3949 case X86::BI__builtin_ia32_rangeps256_mask: 3950 case X86::BI__builtin_ia32_rangeps512_mask: 3951 case X86::BI__builtin_ia32_getmantsd_round_mask: 3952 case X86::BI__builtin_ia32_getmantss_round_mask: 3953 case X86::BI__builtin_ia32_vec_set_v16qi: 3954 case X86::BI__builtin_ia32_vec_set_v16hi: 3955 i = 2; l = 0; u = 15; 3956 break; 3957 case X86::BI__builtin_ia32_vec_ext_v32qi: 3958 i = 1; l = 0; u = 31; 3959 break; 3960 case X86::BI__builtin_ia32_cmpps: 3961 case X86::BI__builtin_ia32_cmpss: 3962 case X86::BI__builtin_ia32_cmppd: 3963 case X86::BI__builtin_ia32_cmpsd: 3964 case X86::BI__builtin_ia32_cmpps256: 3965 case X86::BI__builtin_ia32_cmppd256: 3966 case X86::BI__builtin_ia32_cmpps128_mask: 3967 case X86::BI__builtin_ia32_cmppd128_mask: 3968 case X86::BI__builtin_ia32_cmpps256_mask: 3969 case X86::BI__builtin_ia32_cmppd256_mask: 3970 case X86::BI__builtin_ia32_cmpps512_mask: 3971 case X86::BI__builtin_ia32_cmppd512_mask: 3972 case X86::BI__builtin_ia32_cmpsd_mask: 3973 case X86::BI__builtin_ia32_cmpss_mask: 3974 case X86::BI__builtin_ia32_vec_set_v32qi: 3975 i = 2; l = 0; u = 31; 3976 break; 3977 case X86::BI__builtin_ia32_permdf256: 3978 case X86::BI__builtin_ia32_permdi256: 3979 case X86::BI__builtin_ia32_permdf512: 3980 case X86::BI__builtin_ia32_permdi512: 3981 case X86::BI__builtin_ia32_vpermilps: 3982 case X86::BI__builtin_ia32_vpermilps256: 3983 case X86::BI__builtin_ia32_vpermilpd512: 3984 case X86::BI__builtin_ia32_vpermilps512: 3985 case X86::BI__builtin_ia32_pshufd: 3986 case X86::BI__builtin_ia32_pshufd256: 3987 case X86::BI__builtin_ia32_pshufd512: 3988 case X86::BI__builtin_ia32_pshufhw: 3989 case X86::BI__builtin_ia32_pshufhw256: 3990 case X86::BI__builtin_ia32_pshufhw512: 3991 case X86::BI__builtin_ia32_pshuflw: 3992 case X86::BI__builtin_ia32_pshuflw256: 3993 case X86::BI__builtin_ia32_pshuflw512: 3994 case X86::BI__builtin_ia32_vcvtps2ph: 3995 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3996 case X86::BI__builtin_ia32_vcvtps2ph256: 3997 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3998 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3999 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4000 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4001 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4002 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4003 case X86::BI__builtin_ia32_rndscaleps_mask: 4004 case X86::BI__builtin_ia32_rndscalepd_mask: 4005 case X86::BI__builtin_ia32_reducepd128_mask: 4006 case X86::BI__builtin_ia32_reducepd256_mask: 4007 case X86::BI__builtin_ia32_reducepd512_mask: 4008 case X86::BI__builtin_ia32_reduceps128_mask: 4009 case X86::BI__builtin_ia32_reduceps256_mask: 4010 case X86::BI__builtin_ia32_reduceps512_mask: 4011 case X86::BI__builtin_ia32_prold512: 4012 case X86::BI__builtin_ia32_prolq512: 4013 case X86::BI__builtin_ia32_prold128: 4014 case X86::BI__builtin_ia32_prold256: 4015 case X86::BI__builtin_ia32_prolq128: 4016 case X86::BI__builtin_ia32_prolq256: 4017 case X86::BI__builtin_ia32_prord512: 4018 case X86::BI__builtin_ia32_prorq512: 4019 case X86::BI__builtin_ia32_prord128: 4020 case X86::BI__builtin_ia32_prord256: 4021 case X86::BI__builtin_ia32_prorq128: 4022 case X86::BI__builtin_ia32_prorq256: 4023 case X86::BI__builtin_ia32_fpclasspd128_mask: 4024 case X86::BI__builtin_ia32_fpclasspd256_mask: 4025 case X86::BI__builtin_ia32_fpclassps128_mask: 4026 case X86::BI__builtin_ia32_fpclassps256_mask: 4027 case X86::BI__builtin_ia32_fpclassps512_mask: 4028 case X86::BI__builtin_ia32_fpclasspd512_mask: 4029 case X86::BI__builtin_ia32_fpclasssd_mask: 4030 case X86::BI__builtin_ia32_fpclassss_mask: 4031 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4032 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4033 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4034 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4035 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4036 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4037 case X86::BI__builtin_ia32_kshiftliqi: 4038 case X86::BI__builtin_ia32_kshiftlihi: 4039 case X86::BI__builtin_ia32_kshiftlisi: 4040 case X86::BI__builtin_ia32_kshiftlidi: 4041 case X86::BI__builtin_ia32_kshiftriqi: 4042 case X86::BI__builtin_ia32_kshiftrihi: 4043 case X86::BI__builtin_ia32_kshiftrisi: 4044 case X86::BI__builtin_ia32_kshiftridi: 4045 i = 1; l = 0; u = 255; 4046 break; 4047 case X86::BI__builtin_ia32_vperm2f128_pd256: 4048 case X86::BI__builtin_ia32_vperm2f128_ps256: 4049 case X86::BI__builtin_ia32_vperm2f128_si256: 4050 case X86::BI__builtin_ia32_permti256: 4051 case X86::BI__builtin_ia32_pblendw128: 4052 case X86::BI__builtin_ia32_pblendw256: 4053 case X86::BI__builtin_ia32_blendps256: 4054 case X86::BI__builtin_ia32_pblendd256: 4055 case X86::BI__builtin_ia32_palignr128: 4056 case X86::BI__builtin_ia32_palignr256: 4057 case X86::BI__builtin_ia32_palignr512: 4058 case X86::BI__builtin_ia32_alignq512: 4059 case X86::BI__builtin_ia32_alignd512: 4060 case X86::BI__builtin_ia32_alignd128: 4061 case X86::BI__builtin_ia32_alignd256: 4062 case X86::BI__builtin_ia32_alignq128: 4063 case X86::BI__builtin_ia32_alignq256: 4064 case X86::BI__builtin_ia32_vcomisd: 4065 case X86::BI__builtin_ia32_vcomiss: 4066 case X86::BI__builtin_ia32_shuf_f32x4: 4067 case X86::BI__builtin_ia32_shuf_f64x2: 4068 case X86::BI__builtin_ia32_shuf_i32x4: 4069 case X86::BI__builtin_ia32_shuf_i64x2: 4070 case X86::BI__builtin_ia32_shufpd512: 4071 case X86::BI__builtin_ia32_shufps: 4072 case X86::BI__builtin_ia32_shufps256: 4073 case X86::BI__builtin_ia32_shufps512: 4074 case X86::BI__builtin_ia32_dbpsadbw128: 4075 case X86::BI__builtin_ia32_dbpsadbw256: 4076 case X86::BI__builtin_ia32_dbpsadbw512: 4077 case X86::BI__builtin_ia32_vpshldd128: 4078 case X86::BI__builtin_ia32_vpshldd256: 4079 case X86::BI__builtin_ia32_vpshldd512: 4080 case X86::BI__builtin_ia32_vpshldq128: 4081 case X86::BI__builtin_ia32_vpshldq256: 4082 case X86::BI__builtin_ia32_vpshldq512: 4083 case X86::BI__builtin_ia32_vpshldw128: 4084 case X86::BI__builtin_ia32_vpshldw256: 4085 case X86::BI__builtin_ia32_vpshldw512: 4086 case X86::BI__builtin_ia32_vpshrdd128: 4087 case X86::BI__builtin_ia32_vpshrdd256: 4088 case X86::BI__builtin_ia32_vpshrdd512: 4089 case X86::BI__builtin_ia32_vpshrdq128: 4090 case X86::BI__builtin_ia32_vpshrdq256: 4091 case X86::BI__builtin_ia32_vpshrdq512: 4092 case X86::BI__builtin_ia32_vpshrdw128: 4093 case X86::BI__builtin_ia32_vpshrdw256: 4094 case X86::BI__builtin_ia32_vpshrdw512: 4095 i = 2; l = 0; u = 255; 4096 break; 4097 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4098 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4099 case X86::BI__builtin_ia32_fixupimmps512_mask: 4100 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4101 case X86::BI__builtin_ia32_fixupimmsd_mask: 4102 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4103 case X86::BI__builtin_ia32_fixupimmss_mask: 4104 case X86::BI__builtin_ia32_fixupimmss_maskz: 4105 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4106 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4107 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4108 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4109 case X86::BI__builtin_ia32_fixupimmps128_mask: 4110 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4111 case X86::BI__builtin_ia32_fixupimmps256_mask: 4112 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4113 case X86::BI__builtin_ia32_pternlogd512_mask: 4114 case X86::BI__builtin_ia32_pternlogd512_maskz: 4115 case X86::BI__builtin_ia32_pternlogq512_mask: 4116 case X86::BI__builtin_ia32_pternlogq512_maskz: 4117 case X86::BI__builtin_ia32_pternlogd128_mask: 4118 case X86::BI__builtin_ia32_pternlogd128_maskz: 4119 case X86::BI__builtin_ia32_pternlogd256_mask: 4120 case X86::BI__builtin_ia32_pternlogd256_maskz: 4121 case X86::BI__builtin_ia32_pternlogq128_mask: 4122 case X86::BI__builtin_ia32_pternlogq128_maskz: 4123 case X86::BI__builtin_ia32_pternlogq256_mask: 4124 case X86::BI__builtin_ia32_pternlogq256_maskz: 4125 i = 3; l = 0; u = 255; 4126 break; 4127 case X86::BI__builtin_ia32_gatherpfdpd: 4128 case X86::BI__builtin_ia32_gatherpfdps: 4129 case X86::BI__builtin_ia32_gatherpfqpd: 4130 case X86::BI__builtin_ia32_gatherpfqps: 4131 case X86::BI__builtin_ia32_scatterpfdpd: 4132 case X86::BI__builtin_ia32_scatterpfdps: 4133 case X86::BI__builtin_ia32_scatterpfqpd: 4134 case X86::BI__builtin_ia32_scatterpfqps: 4135 i = 4; l = 2; u = 3; 4136 break; 4137 case X86::BI__builtin_ia32_reducesd_mask: 4138 case X86::BI__builtin_ia32_reducess_mask: 4139 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4140 case X86::BI__builtin_ia32_rndscaless_round_mask: 4141 i = 4; l = 0; u = 255; 4142 break; 4143 } 4144 4145 // Note that we don't force a hard error on the range check here, allowing 4146 // template-generated or macro-generated dead code to potentially have out-of- 4147 // range values. These need to code generate, but don't need to necessarily 4148 // make any sense. We use a warning that defaults to an error. 4149 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4150 } 4151 4152 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4153 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4154 /// Returns true when the format fits the function and the FormatStringInfo has 4155 /// been populated. 4156 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4157 FormatStringInfo *FSI) { 4158 FSI->HasVAListArg = Format->getFirstArg() == 0; 4159 FSI->FormatIdx = Format->getFormatIdx() - 1; 4160 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4161 4162 // The way the format attribute works in GCC, the implicit this argument 4163 // of member functions is counted. However, it doesn't appear in our own 4164 // lists, so decrement format_idx in that case. 4165 if (IsCXXMember) { 4166 if(FSI->FormatIdx == 0) 4167 return false; 4168 --FSI->FormatIdx; 4169 if (FSI->FirstDataArg != 0) 4170 --FSI->FirstDataArg; 4171 } 4172 return true; 4173 } 4174 4175 /// Checks if a the given expression evaluates to null. 4176 /// 4177 /// Returns true if the value evaluates to null. 4178 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4179 // If the expression has non-null type, it doesn't evaluate to null. 4180 if (auto nullability 4181 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4182 if (*nullability == NullabilityKind::NonNull) 4183 return false; 4184 } 4185 4186 // As a special case, transparent unions initialized with zero are 4187 // considered null for the purposes of the nonnull attribute. 4188 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4189 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4190 if (const CompoundLiteralExpr *CLE = 4191 dyn_cast<CompoundLiteralExpr>(Expr)) 4192 if (const InitListExpr *ILE = 4193 dyn_cast<InitListExpr>(CLE->getInitializer())) 4194 Expr = ILE->getInit(0); 4195 } 4196 4197 bool Result; 4198 return (!Expr->isValueDependent() && 4199 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4200 !Result); 4201 } 4202 4203 static void CheckNonNullArgument(Sema &S, 4204 const Expr *ArgExpr, 4205 SourceLocation CallSiteLoc) { 4206 if (CheckNonNullExpr(S, ArgExpr)) 4207 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4208 S.PDiag(diag::warn_null_arg) 4209 << ArgExpr->getSourceRange()); 4210 } 4211 4212 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4213 FormatStringInfo FSI; 4214 if ((GetFormatStringType(Format) == FST_NSString) && 4215 getFormatStringInfo(Format, false, &FSI)) { 4216 Idx = FSI.FormatIdx; 4217 return true; 4218 } 4219 return false; 4220 } 4221 4222 /// Diagnose use of %s directive in an NSString which is being passed 4223 /// as formatting string to formatting method. 4224 static void 4225 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4226 const NamedDecl *FDecl, 4227 Expr **Args, 4228 unsigned NumArgs) { 4229 unsigned Idx = 0; 4230 bool Format = false; 4231 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4232 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4233 Idx = 2; 4234 Format = true; 4235 } 4236 else 4237 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4238 if (S.GetFormatNSStringIdx(I, Idx)) { 4239 Format = true; 4240 break; 4241 } 4242 } 4243 if (!Format || NumArgs <= Idx) 4244 return; 4245 const Expr *FormatExpr = Args[Idx]; 4246 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4247 FormatExpr = CSCE->getSubExpr(); 4248 const StringLiteral *FormatString; 4249 if (const ObjCStringLiteral *OSL = 4250 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4251 FormatString = OSL->getString(); 4252 else 4253 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4254 if (!FormatString) 4255 return; 4256 if (S.FormatStringHasSArg(FormatString)) { 4257 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4258 << "%s" << 1 << 1; 4259 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4260 << FDecl->getDeclName(); 4261 } 4262 } 4263 4264 /// Determine whether the given type has a non-null nullability annotation. 4265 static bool isNonNullType(ASTContext &ctx, QualType type) { 4266 if (auto nullability = type->getNullability(ctx)) 4267 return *nullability == NullabilityKind::NonNull; 4268 4269 return false; 4270 } 4271 4272 static void CheckNonNullArguments(Sema &S, 4273 const NamedDecl *FDecl, 4274 const FunctionProtoType *Proto, 4275 ArrayRef<const Expr *> Args, 4276 SourceLocation CallSiteLoc) { 4277 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4278 4279 // Already checked by by constant evaluator. 4280 if (S.isConstantEvaluated()) 4281 return; 4282 // Check the attributes attached to the method/function itself. 4283 llvm::SmallBitVector NonNullArgs; 4284 if (FDecl) { 4285 // Handle the nonnull attribute on the function/method declaration itself. 4286 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4287 if (!NonNull->args_size()) { 4288 // Easy case: all pointer arguments are nonnull. 4289 for (const auto *Arg : Args) 4290 if (S.isValidPointerAttrType(Arg->getType())) 4291 CheckNonNullArgument(S, Arg, CallSiteLoc); 4292 return; 4293 } 4294 4295 for (const ParamIdx &Idx : NonNull->args()) { 4296 unsigned IdxAST = Idx.getASTIndex(); 4297 if (IdxAST >= Args.size()) 4298 continue; 4299 if (NonNullArgs.empty()) 4300 NonNullArgs.resize(Args.size()); 4301 NonNullArgs.set(IdxAST); 4302 } 4303 } 4304 } 4305 4306 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4307 // Handle the nonnull attribute on the parameters of the 4308 // function/method. 4309 ArrayRef<ParmVarDecl*> parms; 4310 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4311 parms = FD->parameters(); 4312 else 4313 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4314 4315 unsigned ParamIndex = 0; 4316 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4317 I != E; ++I, ++ParamIndex) { 4318 const ParmVarDecl *PVD = *I; 4319 if (PVD->hasAttr<NonNullAttr>() || 4320 isNonNullType(S.Context, PVD->getType())) { 4321 if (NonNullArgs.empty()) 4322 NonNullArgs.resize(Args.size()); 4323 4324 NonNullArgs.set(ParamIndex); 4325 } 4326 } 4327 } else { 4328 // If we have a non-function, non-method declaration but no 4329 // function prototype, try to dig out the function prototype. 4330 if (!Proto) { 4331 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4332 QualType type = VD->getType().getNonReferenceType(); 4333 if (auto pointerType = type->getAs<PointerType>()) 4334 type = pointerType->getPointeeType(); 4335 else if (auto blockType = type->getAs<BlockPointerType>()) 4336 type = blockType->getPointeeType(); 4337 // FIXME: data member pointers? 4338 4339 // Dig out the function prototype, if there is one. 4340 Proto = type->getAs<FunctionProtoType>(); 4341 } 4342 } 4343 4344 // Fill in non-null argument information from the nullability 4345 // information on the parameter types (if we have them). 4346 if (Proto) { 4347 unsigned Index = 0; 4348 for (auto paramType : Proto->getParamTypes()) { 4349 if (isNonNullType(S.Context, paramType)) { 4350 if (NonNullArgs.empty()) 4351 NonNullArgs.resize(Args.size()); 4352 4353 NonNullArgs.set(Index); 4354 } 4355 4356 ++Index; 4357 } 4358 } 4359 } 4360 4361 // Check for non-null arguments. 4362 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4363 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4364 if (NonNullArgs[ArgIndex]) 4365 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4366 } 4367 } 4368 4369 /// Handles the checks for format strings, non-POD arguments to vararg 4370 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4371 /// attributes. 4372 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4373 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4374 bool IsMemberFunction, SourceLocation Loc, 4375 SourceRange Range, VariadicCallType CallType) { 4376 // FIXME: We should check as much as we can in the template definition. 4377 if (CurContext->isDependentContext()) 4378 return; 4379 4380 // Printf and scanf checking. 4381 llvm::SmallBitVector CheckedVarArgs; 4382 if (FDecl) { 4383 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4384 // Only create vector if there are format attributes. 4385 CheckedVarArgs.resize(Args.size()); 4386 4387 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4388 CheckedVarArgs); 4389 } 4390 } 4391 4392 // Refuse POD arguments that weren't caught by the format string 4393 // checks above. 4394 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4395 if (CallType != VariadicDoesNotApply && 4396 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4397 unsigned NumParams = Proto ? Proto->getNumParams() 4398 : FDecl && isa<FunctionDecl>(FDecl) 4399 ? cast<FunctionDecl>(FDecl)->getNumParams() 4400 : FDecl && isa<ObjCMethodDecl>(FDecl) 4401 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4402 : 0; 4403 4404 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4405 // Args[ArgIdx] can be null in malformed code. 4406 if (const Expr *Arg = Args[ArgIdx]) { 4407 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4408 checkVariadicArgument(Arg, CallType); 4409 } 4410 } 4411 } 4412 4413 if (FDecl || Proto) { 4414 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4415 4416 // Type safety checking. 4417 if (FDecl) { 4418 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4419 CheckArgumentWithTypeTag(I, Args, Loc); 4420 } 4421 } 4422 4423 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4424 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4425 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4426 if (!Arg->isValueDependent()) { 4427 Expr::EvalResult Align; 4428 if (Arg->EvaluateAsInt(Align, Context)) { 4429 const llvm::APSInt &I = Align.Val.getInt(); 4430 if (!I.isPowerOf2()) 4431 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4432 << Arg->getSourceRange(); 4433 4434 if (I > Sema::MaximumAlignment) 4435 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4436 << Arg->getSourceRange() << Sema::MaximumAlignment; 4437 } 4438 } 4439 } 4440 4441 if (FD) 4442 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4443 } 4444 4445 /// CheckConstructorCall - Check a constructor call for correctness and safety 4446 /// properties not enforced by the C type system. 4447 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4448 ArrayRef<const Expr *> Args, 4449 const FunctionProtoType *Proto, 4450 SourceLocation Loc) { 4451 VariadicCallType CallType = 4452 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4453 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4454 Loc, SourceRange(), CallType); 4455 } 4456 4457 /// CheckFunctionCall - Check a direct function call for various correctness 4458 /// and safety properties not strictly enforced by the C type system. 4459 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4460 const FunctionProtoType *Proto) { 4461 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4462 isa<CXXMethodDecl>(FDecl); 4463 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4464 IsMemberOperatorCall; 4465 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4466 TheCall->getCallee()); 4467 Expr** Args = TheCall->getArgs(); 4468 unsigned NumArgs = TheCall->getNumArgs(); 4469 4470 Expr *ImplicitThis = nullptr; 4471 if (IsMemberOperatorCall) { 4472 // If this is a call to a member operator, hide the first argument 4473 // from checkCall. 4474 // FIXME: Our choice of AST representation here is less than ideal. 4475 ImplicitThis = Args[0]; 4476 ++Args; 4477 --NumArgs; 4478 } else if (IsMemberFunction) 4479 ImplicitThis = 4480 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4481 4482 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4483 IsMemberFunction, TheCall->getRParenLoc(), 4484 TheCall->getCallee()->getSourceRange(), CallType); 4485 4486 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4487 // None of the checks below are needed for functions that don't have 4488 // simple names (e.g., C++ conversion functions). 4489 if (!FnInfo) 4490 return false; 4491 4492 CheckAbsoluteValueFunction(TheCall, FDecl); 4493 CheckMaxUnsignedZero(TheCall, FDecl); 4494 4495 if (getLangOpts().ObjC) 4496 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4497 4498 unsigned CMId = FDecl->getMemoryFunctionKind(); 4499 if (CMId == 0) 4500 return false; 4501 4502 // Handle memory setting and copying functions. 4503 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4504 CheckStrlcpycatArguments(TheCall, FnInfo); 4505 else if (CMId == Builtin::BIstrncat) 4506 CheckStrncatArguments(TheCall, FnInfo); 4507 else 4508 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4509 4510 return false; 4511 } 4512 4513 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4514 ArrayRef<const Expr *> Args) { 4515 VariadicCallType CallType = 4516 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4517 4518 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4519 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4520 CallType); 4521 4522 return false; 4523 } 4524 4525 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4526 const FunctionProtoType *Proto) { 4527 QualType Ty; 4528 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4529 Ty = V->getType().getNonReferenceType(); 4530 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4531 Ty = F->getType().getNonReferenceType(); 4532 else 4533 return false; 4534 4535 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4536 !Ty->isFunctionProtoType()) 4537 return false; 4538 4539 VariadicCallType CallType; 4540 if (!Proto || !Proto->isVariadic()) { 4541 CallType = VariadicDoesNotApply; 4542 } else if (Ty->isBlockPointerType()) { 4543 CallType = VariadicBlock; 4544 } else { // Ty->isFunctionPointerType() 4545 CallType = VariadicFunction; 4546 } 4547 4548 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4549 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4550 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4551 TheCall->getCallee()->getSourceRange(), CallType); 4552 4553 return false; 4554 } 4555 4556 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4557 /// such as function pointers returned from functions. 4558 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4559 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4560 TheCall->getCallee()); 4561 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4562 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4563 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4564 TheCall->getCallee()->getSourceRange(), CallType); 4565 4566 return false; 4567 } 4568 4569 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4570 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4571 return false; 4572 4573 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4574 switch (Op) { 4575 case AtomicExpr::AO__c11_atomic_init: 4576 case AtomicExpr::AO__opencl_atomic_init: 4577 llvm_unreachable("There is no ordering argument for an init"); 4578 4579 case AtomicExpr::AO__c11_atomic_load: 4580 case AtomicExpr::AO__opencl_atomic_load: 4581 case AtomicExpr::AO__atomic_load_n: 4582 case AtomicExpr::AO__atomic_load: 4583 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4584 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4585 4586 case AtomicExpr::AO__c11_atomic_store: 4587 case AtomicExpr::AO__opencl_atomic_store: 4588 case AtomicExpr::AO__atomic_store: 4589 case AtomicExpr::AO__atomic_store_n: 4590 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4591 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4592 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4593 4594 default: 4595 return true; 4596 } 4597 } 4598 4599 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4600 AtomicExpr::AtomicOp Op) { 4601 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4602 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4603 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4604 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4605 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4606 Op); 4607 } 4608 4609 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4610 SourceLocation RParenLoc, MultiExprArg Args, 4611 AtomicExpr::AtomicOp Op, 4612 AtomicArgumentOrder ArgOrder) { 4613 // All the non-OpenCL operations take one of the following forms. 4614 // The OpenCL operations take the __c11 forms with one extra argument for 4615 // synchronization scope. 4616 enum { 4617 // C __c11_atomic_init(A *, C) 4618 Init, 4619 4620 // C __c11_atomic_load(A *, int) 4621 Load, 4622 4623 // void __atomic_load(A *, CP, int) 4624 LoadCopy, 4625 4626 // void __atomic_store(A *, CP, int) 4627 Copy, 4628 4629 // C __c11_atomic_add(A *, M, int) 4630 Arithmetic, 4631 4632 // C __atomic_exchange_n(A *, CP, int) 4633 Xchg, 4634 4635 // void __atomic_exchange(A *, C *, CP, int) 4636 GNUXchg, 4637 4638 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4639 C11CmpXchg, 4640 4641 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4642 GNUCmpXchg 4643 } Form = Init; 4644 4645 const unsigned NumForm = GNUCmpXchg + 1; 4646 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4647 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4648 // where: 4649 // C is an appropriate type, 4650 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4651 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4652 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4653 // the int parameters are for orderings. 4654 4655 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4656 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4657 "need to update code for modified forms"); 4658 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4659 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4660 AtomicExpr::AO__atomic_load, 4661 "need to update code for modified C11 atomics"); 4662 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4663 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4664 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4665 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4666 IsOpenCL; 4667 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4668 Op == AtomicExpr::AO__atomic_store_n || 4669 Op == AtomicExpr::AO__atomic_exchange_n || 4670 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4671 bool IsAddSub = false; 4672 4673 switch (Op) { 4674 case AtomicExpr::AO__c11_atomic_init: 4675 case AtomicExpr::AO__opencl_atomic_init: 4676 Form = Init; 4677 break; 4678 4679 case AtomicExpr::AO__c11_atomic_load: 4680 case AtomicExpr::AO__opencl_atomic_load: 4681 case AtomicExpr::AO__atomic_load_n: 4682 Form = Load; 4683 break; 4684 4685 case AtomicExpr::AO__atomic_load: 4686 Form = LoadCopy; 4687 break; 4688 4689 case AtomicExpr::AO__c11_atomic_store: 4690 case AtomicExpr::AO__opencl_atomic_store: 4691 case AtomicExpr::AO__atomic_store: 4692 case AtomicExpr::AO__atomic_store_n: 4693 Form = Copy; 4694 break; 4695 4696 case AtomicExpr::AO__c11_atomic_fetch_add: 4697 case AtomicExpr::AO__c11_atomic_fetch_sub: 4698 case AtomicExpr::AO__opencl_atomic_fetch_add: 4699 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4700 case AtomicExpr::AO__atomic_fetch_add: 4701 case AtomicExpr::AO__atomic_fetch_sub: 4702 case AtomicExpr::AO__atomic_add_fetch: 4703 case AtomicExpr::AO__atomic_sub_fetch: 4704 IsAddSub = true; 4705 LLVM_FALLTHROUGH; 4706 case AtomicExpr::AO__c11_atomic_fetch_and: 4707 case AtomicExpr::AO__c11_atomic_fetch_or: 4708 case AtomicExpr::AO__c11_atomic_fetch_xor: 4709 case AtomicExpr::AO__opencl_atomic_fetch_and: 4710 case AtomicExpr::AO__opencl_atomic_fetch_or: 4711 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4712 case AtomicExpr::AO__atomic_fetch_and: 4713 case AtomicExpr::AO__atomic_fetch_or: 4714 case AtomicExpr::AO__atomic_fetch_xor: 4715 case AtomicExpr::AO__atomic_fetch_nand: 4716 case AtomicExpr::AO__atomic_and_fetch: 4717 case AtomicExpr::AO__atomic_or_fetch: 4718 case AtomicExpr::AO__atomic_xor_fetch: 4719 case AtomicExpr::AO__atomic_nand_fetch: 4720 case AtomicExpr::AO__c11_atomic_fetch_min: 4721 case AtomicExpr::AO__c11_atomic_fetch_max: 4722 case AtomicExpr::AO__opencl_atomic_fetch_min: 4723 case AtomicExpr::AO__opencl_atomic_fetch_max: 4724 case AtomicExpr::AO__atomic_min_fetch: 4725 case AtomicExpr::AO__atomic_max_fetch: 4726 case AtomicExpr::AO__atomic_fetch_min: 4727 case AtomicExpr::AO__atomic_fetch_max: 4728 Form = Arithmetic; 4729 break; 4730 4731 case AtomicExpr::AO__c11_atomic_exchange: 4732 case AtomicExpr::AO__opencl_atomic_exchange: 4733 case AtomicExpr::AO__atomic_exchange_n: 4734 Form = Xchg; 4735 break; 4736 4737 case AtomicExpr::AO__atomic_exchange: 4738 Form = GNUXchg; 4739 break; 4740 4741 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4742 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4743 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4744 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4745 Form = C11CmpXchg; 4746 break; 4747 4748 case AtomicExpr::AO__atomic_compare_exchange: 4749 case AtomicExpr::AO__atomic_compare_exchange_n: 4750 Form = GNUCmpXchg; 4751 break; 4752 } 4753 4754 unsigned AdjustedNumArgs = NumArgs[Form]; 4755 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4756 ++AdjustedNumArgs; 4757 // Check we have the right number of arguments. 4758 if (Args.size() < AdjustedNumArgs) { 4759 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4760 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4761 << ExprRange; 4762 return ExprError(); 4763 } else if (Args.size() > AdjustedNumArgs) { 4764 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4765 diag::err_typecheck_call_too_many_args) 4766 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4767 << ExprRange; 4768 return ExprError(); 4769 } 4770 4771 // Inspect the first argument of the atomic operation. 4772 Expr *Ptr = Args[0]; 4773 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4774 if (ConvertedPtr.isInvalid()) 4775 return ExprError(); 4776 4777 Ptr = ConvertedPtr.get(); 4778 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4779 if (!pointerType) { 4780 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4781 << Ptr->getType() << Ptr->getSourceRange(); 4782 return ExprError(); 4783 } 4784 4785 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4786 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4787 QualType ValType = AtomTy; // 'C' 4788 if (IsC11) { 4789 if (!AtomTy->isAtomicType()) { 4790 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4791 << Ptr->getType() << Ptr->getSourceRange(); 4792 return ExprError(); 4793 } 4794 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4795 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4796 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4797 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4798 << Ptr->getSourceRange(); 4799 return ExprError(); 4800 } 4801 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4802 } else if (Form != Load && Form != LoadCopy) { 4803 if (ValType.isConstQualified()) { 4804 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4805 << Ptr->getType() << Ptr->getSourceRange(); 4806 return ExprError(); 4807 } 4808 } 4809 4810 // For an arithmetic operation, the implied arithmetic must be well-formed. 4811 if (Form == Arithmetic) { 4812 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4813 if (IsAddSub && !ValType->isIntegerType() 4814 && !ValType->isPointerType()) { 4815 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4816 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4817 return ExprError(); 4818 } 4819 if (!IsAddSub && !ValType->isIntegerType()) { 4820 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4821 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4822 return ExprError(); 4823 } 4824 if (IsC11 && ValType->isPointerType() && 4825 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4826 diag::err_incomplete_type)) { 4827 return ExprError(); 4828 } 4829 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4830 // For __atomic_*_n operations, the value type must be a scalar integral or 4831 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4832 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4833 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4834 return ExprError(); 4835 } 4836 4837 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4838 !AtomTy->isScalarType()) { 4839 // For GNU atomics, require a trivially-copyable type. This is not part of 4840 // the GNU atomics specification, but we enforce it for sanity. 4841 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4842 << Ptr->getType() << Ptr->getSourceRange(); 4843 return ExprError(); 4844 } 4845 4846 switch (ValType.getObjCLifetime()) { 4847 case Qualifiers::OCL_None: 4848 case Qualifiers::OCL_ExplicitNone: 4849 // okay 4850 break; 4851 4852 case Qualifiers::OCL_Weak: 4853 case Qualifiers::OCL_Strong: 4854 case Qualifiers::OCL_Autoreleasing: 4855 // FIXME: Can this happen? By this point, ValType should be known 4856 // to be trivially copyable. 4857 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4858 << ValType << Ptr->getSourceRange(); 4859 return ExprError(); 4860 } 4861 4862 // All atomic operations have an overload which takes a pointer to a volatile 4863 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4864 // into the result or the other operands. Similarly atomic_load takes a 4865 // pointer to a const 'A'. 4866 ValType.removeLocalVolatile(); 4867 ValType.removeLocalConst(); 4868 QualType ResultType = ValType; 4869 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4870 Form == Init) 4871 ResultType = Context.VoidTy; 4872 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4873 ResultType = Context.BoolTy; 4874 4875 // The type of a parameter passed 'by value'. In the GNU atomics, such 4876 // arguments are actually passed as pointers. 4877 QualType ByValType = ValType; // 'CP' 4878 bool IsPassedByAddress = false; 4879 if (!IsC11 && !IsN) { 4880 ByValType = Ptr->getType(); 4881 IsPassedByAddress = true; 4882 } 4883 4884 SmallVector<Expr *, 5> APIOrderedArgs; 4885 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4886 APIOrderedArgs.push_back(Args[0]); 4887 switch (Form) { 4888 case Init: 4889 case Load: 4890 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4891 break; 4892 case LoadCopy: 4893 case Copy: 4894 case Arithmetic: 4895 case Xchg: 4896 APIOrderedArgs.push_back(Args[2]); // Val1 4897 APIOrderedArgs.push_back(Args[1]); // Order 4898 break; 4899 case GNUXchg: 4900 APIOrderedArgs.push_back(Args[2]); // Val1 4901 APIOrderedArgs.push_back(Args[3]); // Val2 4902 APIOrderedArgs.push_back(Args[1]); // Order 4903 break; 4904 case C11CmpXchg: 4905 APIOrderedArgs.push_back(Args[2]); // Val1 4906 APIOrderedArgs.push_back(Args[4]); // Val2 4907 APIOrderedArgs.push_back(Args[1]); // Order 4908 APIOrderedArgs.push_back(Args[3]); // OrderFail 4909 break; 4910 case GNUCmpXchg: 4911 APIOrderedArgs.push_back(Args[2]); // Val1 4912 APIOrderedArgs.push_back(Args[4]); // Val2 4913 APIOrderedArgs.push_back(Args[5]); // Weak 4914 APIOrderedArgs.push_back(Args[1]); // Order 4915 APIOrderedArgs.push_back(Args[3]); // OrderFail 4916 break; 4917 } 4918 } else 4919 APIOrderedArgs.append(Args.begin(), Args.end()); 4920 4921 // The first argument's non-CV pointer type is used to deduce the type of 4922 // subsequent arguments, except for: 4923 // - weak flag (always converted to bool) 4924 // - memory order (always converted to int) 4925 // - scope (always converted to int) 4926 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4927 QualType Ty; 4928 if (i < NumVals[Form] + 1) { 4929 switch (i) { 4930 case 0: 4931 // The first argument is always a pointer. It has a fixed type. 4932 // It is always dereferenced, a nullptr is undefined. 4933 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4934 // Nothing else to do: we already know all we want about this pointer. 4935 continue; 4936 case 1: 4937 // The second argument is the non-atomic operand. For arithmetic, this 4938 // is always passed by value, and for a compare_exchange it is always 4939 // passed by address. For the rest, GNU uses by-address and C11 uses 4940 // by-value. 4941 assert(Form != Load); 4942 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4943 Ty = ValType; 4944 else if (Form == Copy || Form == Xchg) { 4945 if (IsPassedByAddress) { 4946 // The value pointer is always dereferenced, a nullptr is undefined. 4947 CheckNonNullArgument(*this, APIOrderedArgs[i], 4948 ExprRange.getBegin()); 4949 } 4950 Ty = ByValType; 4951 } else if (Form == Arithmetic) 4952 Ty = Context.getPointerDiffType(); 4953 else { 4954 Expr *ValArg = APIOrderedArgs[i]; 4955 // The value pointer is always dereferenced, a nullptr is undefined. 4956 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4957 LangAS AS = LangAS::Default; 4958 // Keep address space of non-atomic pointer type. 4959 if (const PointerType *PtrTy = 4960 ValArg->getType()->getAs<PointerType>()) { 4961 AS = PtrTy->getPointeeType().getAddressSpace(); 4962 } 4963 Ty = Context.getPointerType( 4964 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4965 } 4966 break; 4967 case 2: 4968 // The third argument to compare_exchange / GNU exchange is the desired 4969 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4970 if (IsPassedByAddress) 4971 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4972 Ty = ByValType; 4973 break; 4974 case 3: 4975 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4976 Ty = Context.BoolTy; 4977 break; 4978 } 4979 } else { 4980 // The order(s) and scope are always converted to int. 4981 Ty = Context.IntTy; 4982 } 4983 4984 InitializedEntity Entity = 4985 InitializedEntity::InitializeParameter(Context, Ty, false); 4986 ExprResult Arg = APIOrderedArgs[i]; 4987 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4988 if (Arg.isInvalid()) 4989 return true; 4990 APIOrderedArgs[i] = Arg.get(); 4991 } 4992 4993 // Permute the arguments into a 'consistent' order. 4994 SmallVector<Expr*, 5> SubExprs; 4995 SubExprs.push_back(Ptr); 4996 switch (Form) { 4997 case Init: 4998 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4999 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5000 break; 5001 case Load: 5002 SubExprs.push_back(APIOrderedArgs[1]); // Order 5003 break; 5004 case LoadCopy: 5005 case Copy: 5006 case Arithmetic: 5007 case Xchg: 5008 SubExprs.push_back(APIOrderedArgs[2]); // Order 5009 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5010 break; 5011 case GNUXchg: 5012 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5013 SubExprs.push_back(APIOrderedArgs[3]); // Order 5014 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5015 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5016 break; 5017 case C11CmpXchg: 5018 SubExprs.push_back(APIOrderedArgs[3]); // Order 5019 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5020 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5021 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5022 break; 5023 case GNUCmpXchg: 5024 SubExprs.push_back(APIOrderedArgs[4]); // Order 5025 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5026 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5027 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5028 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5029 break; 5030 } 5031 5032 if (SubExprs.size() >= 2 && Form != Init) { 5033 if (Optional<llvm::APSInt> Result = 5034 SubExprs[1]->getIntegerConstantExpr(Context)) 5035 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5036 Diag(SubExprs[1]->getBeginLoc(), 5037 diag::warn_atomic_op_has_invalid_memory_order) 5038 << SubExprs[1]->getSourceRange(); 5039 } 5040 5041 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5042 auto *Scope = Args[Args.size() - 1]; 5043 if (Optional<llvm::APSInt> Result = 5044 Scope->getIntegerConstantExpr(Context)) { 5045 if (!ScopeModel->isValid(Result->getZExtValue())) 5046 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5047 << Scope->getSourceRange(); 5048 } 5049 SubExprs.push_back(Scope); 5050 } 5051 5052 AtomicExpr *AE = new (Context) 5053 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5054 5055 if ((Op == AtomicExpr::AO__c11_atomic_load || 5056 Op == AtomicExpr::AO__c11_atomic_store || 5057 Op == AtomicExpr::AO__opencl_atomic_load || 5058 Op == AtomicExpr::AO__opencl_atomic_store ) && 5059 Context.AtomicUsesUnsupportedLibcall(AE)) 5060 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5061 << ((Op == AtomicExpr::AO__c11_atomic_load || 5062 Op == AtomicExpr::AO__opencl_atomic_load) 5063 ? 0 5064 : 1); 5065 5066 if (ValType->isExtIntType()) { 5067 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5068 return ExprError(); 5069 } 5070 5071 return AE; 5072 } 5073 5074 /// checkBuiltinArgument - Given a call to a builtin function, perform 5075 /// normal type-checking on the given argument, updating the call in 5076 /// place. This is useful when a builtin function requires custom 5077 /// type-checking for some of its arguments but not necessarily all of 5078 /// them. 5079 /// 5080 /// Returns true on error. 5081 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5082 FunctionDecl *Fn = E->getDirectCallee(); 5083 assert(Fn && "builtin call without direct callee!"); 5084 5085 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5086 InitializedEntity Entity = 5087 InitializedEntity::InitializeParameter(S.Context, Param); 5088 5089 ExprResult Arg = E->getArg(0); 5090 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5091 if (Arg.isInvalid()) 5092 return true; 5093 5094 E->setArg(ArgIndex, Arg.get()); 5095 return false; 5096 } 5097 5098 /// We have a call to a function like __sync_fetch_and_add, which is an 5099 /// overloaded function based on the pointer type of its first argument. 5100 /// The main BuildCallExpr routines have already promoted the types of 5101 /// arguments because all of these calls are prototyped as void(...). 5102 /// 5103 /// This function goes through and does final semantic checking for these 5104 /// builtins, as well as generating any warnings. 5105 ExprResult 5106 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5107 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5108 Expr *Callee = TheCall->getCallee(); 5109 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5110 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5111 5112 // Ensure that we have at least one argument to do type inference from. 5113 if (TheCall->getNumArgs() < 1) { 5114 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5115 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5116 return ExprError(); 5117 } 5118 5119 // Inspect the first argument of the atomic builtin. This should always be 5120 // a pointer type, whose element is an integral scalar or pointer type. 5121 // Because it is a pointer type, we don't have to worry about any implicit 5122 // casts here. 5123 // FIXME: We don't allow floating point scalars as input. 5124 Expr *FirstArg = TheCall->getArg(0); 5125 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5126 if (FirstArgResult.isInvalid()) 5127 return ExprError(); 5128 FirstArg = FirstArgResult.get(); 5129 TheCall->setArg(0, FirstArg); 5130 5131 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5132 if (!pointerType) { 5133 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5134 << FirstArg->getType() << FirstArg->getSourceRange(); 5135 return ExprError(); 5136 } 5137 5138 QualType ValType = pointerType->getPointeeType(); 5139 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5140 !ValType->isBlockPointerType()) { 5141 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5142 << FirstArg->getType() << FirstArg->getSourceRange(); 5143 return ExprError(); 5144 } 5145 5146 if (ValType.isConstQualified()) { 5147 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5148 << FirstArg->getType() << FirstArg->getSourceRange(); 5149 return ExprError(); 5150 } 5151 5152 switch (ValType.getObjCLifetime()) { 5153 case Qualifiers::OCL_None: 5154 case Qualifiers::OCL_ExplicitNone: 5155 // okay 5156 break; 5157 5158 case Qualifiers::OCL_Weak: 5159 case Qualifiers::OCL_Strong: 5160 case Qualifiers::OCL_Autoreleasing: 5161 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5162 << ValType << FirstArg->getSourceRange(); 5163 return ExprError(); 5164 } 5165 5166 // Strip any qualifiers off ValType. 5167 ValType = ValType.getUnqualifiedType(); 5168 5169 // The majority of builtins return a value, but a few have special return 5170 // types, so allow them to override appropriately below. 5171 QualType ResultType = ValType; 5172 5173 // We need to figure out which concrete builtin this maps onto. For example, 5174 // __sync_fetch_and_add with a 2 byte object turns into 5175 // __sync_fetch_and_add_2. 5176 #define BUILTIN_ROW(x) \ 5177 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5178 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5179 5180 static const unsigned BuiltinIndices[][5] = { 5181 BUILTIN_ROW(__sync_fetch_and_add), 5182 BUILTIN_ROW(__sync_fetch_and_sub), 5183 BUILTIN_ROW(__sync_fetch_and_or), 5184 BUILTIN_ROW(__sync_fetch_and_and), 5185 BUILTIN_ROW(__sync_fetch_and_xor), 5186 BUILTIN_ROW(__sync_fetch_and_nand), 5187 5188 BUILTIN_ROW(__sync_add_and_fetch), 5189 BUILTIN_ROW(__sync_sub_and_fetch), 5190 BUILTIN_ROW(__sync_and_and_fetch), 5191 BUILTIN_ROW(__sync_or_and_fetch), 5192 BUILTIN_ROW(__sync_xor_and_fetch), 5193 BUILTIN_ROW(__sync_nand_and_fetch), 5194 5195 BUILTIN_ROW(__sync_val_compare_and_swap), 5196 BUILTIN_ROW(__sync_bool_compare_and_swap), 5197 BUILTIN_ROW(__sync_lock_test_and_set), 5198 BUILTIN_ROW(__sync_lock_release), 5199 BUILTIN_ROW(__sync_swap) 5200 }; 5201 #undef BUILTIN_ROW 5202 5203 // Determine the index of the size. 5204 unsigned SizeIndex; 5205 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5206 case 1: SizeIndex = 0; break; 5207 case 2: SizeIndex = 1; break; 5208 case 4: SizeIndex = 2; break; 5209 case 8: SizeIndex = 3; break; 5210 case 16: SizeIndex = 4; break; 5211 default: 5212 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5213 << FirstArg->getType() << FirstArg->getSourceRange(); 5214 return ExprError(); 5215 } 5216 5217 // Each of these builtins has one pointer argument, followed by some number of 5218 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5219 // that we ignore. Find out which row of BuiltinIndices to read from as well 5220 // as the number of fixed args. 5221 unsigned BuiltinID = FDecl->getBuiltinID(); 5222 unsigned BuiltinIndex, NumFixed = 1; 5223 bool WarnAboutSemanticsChange = false; 5224 switch (BuiltinID) { 5225 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5226 case Builtin::BI__sync_fetch_and_add: 5227 case Builtin::BI__sync_fetch_and_add_1: 5228 case Builtin::BI__sync_fetch_and_add_2: 5229 case Builtin::BI__sync_fetch_and_add_4: 5230 case Builtin::BI__sync_fetch_and_add_8: 5231 case Builtin::BI__sync_fetch_and_add_16: 5232 BuiltinIndex = 0; 5233 break; 5234 5235 case Builtin::BI__sync_fetch_and_sub: 5236 case Builtin::BI__sync_fetch_and_sub_1: 5237 case Builtin::BI__sync_fetch_and_sub_2: 5238 case Builtin::BI__sync_fetch_and_sub_4: 5239 case Builtin::BI__sync_fetch_and_sub_8: 5240 case Builtin::BI__sync_fetch_and_sub_16: 5241 BuiltinIndex = 1; 5242 break; 5243 5244 case Builtin::BI__sync_fetch_and_or: 5245 case Builtin::BI__sync_fetch_and_or_1: 5246 case Builtin::BI__sync_fetch_and_or_2: 5247 case Builtin::BI__sync_fetch_and_or_4: 5248 case Builtin::BI__sync_fetch_and_or_8: 5249 case Builtin::BI__sync_fetch_and_or_16: 5250 BuiltinIndex = 2; 5251 break; 5252 5253 case Builtin::BI__sync_fetch_and_and: 5254 case Builtin::BI__sync_fetch_and_and_1: 5255 case Builtin::BI__sync_fetch_and_and_2: 5256 case Builtin::BI__sync_fetch_and_and_4: 5257 case Builtin::BI__sync_fetch_and_and_8: 5258 case Builtin::BI__sync_fetch_and_and_16: 5259 BuiltinIndex = 3; 5260 break; 5261 5262 case Builtin::BI__sync_fetch_and_xor: 5263 case Builtin::BI__sync_fetch_and_xor_1: 5264 case Builtin::BI__sync_fetch_and_xor_2: 5265 case Builtin::BI__sync_fetch_and_xor_4: 5266 case Builtin::BI__sync_fetch_and_xor_8: 5267 case Builtin::BI__sync_fetch_and_xor_16: 5268 BuiltinIndex = 4; 5269 break; 5270 5271 case Builtin::BI__sync_fetch_and_nand: 5272 case Builtin::BI__sync_fetch_and_nand_1: 5273 case Builtin::BI__sync_fetch_and_nand_2: 5274 case Builtin::BI__sync_fetch_and_nand_4: 5275 case Builtin::BI__sync_fetch_and_nand_8: 5276 case Builtin::BI__sync_fetch_and_nand_16: 5277 BuiltinIndex = 5; 5278 WarnAboutSemanticsChange = true; 5279 break; 5280 5281 case Builtin::BI__sync_add_and_fetch: 5282 case Builtin::BI__sync_add_and_fetch_1: 5283 case Builtin::BI__sync_add_and_fetch_2: 5284 case Builtin::BI__sync_add_and_fetch_4: 5285 case Builtin::BI__sync_add_and_fetch_8: 5286 case Builtin::BI__sync_add_and_fetch_16: 5287 BuiltinIndex = 6; 5288 break; 5289 5290 case Builtin::BI__sync_sub_and_fetch: 5291 case Builtin::BI__sync_sub_and_fetch_1: 5292 case Builtin::BI__sync_sub_and_fetch_2: 5293 case Builtin::BI__sync_sub_and_fetch_4: 5294 case Builtin::BI__sync_sub_and_fetch_8: 5295 case Builtin::BI__sync_sub_and_fetch_16: 5296 BuiltinIndex = 7; 5297 break; 5298 5299 case Builtin::BI__sync_and_and_fetch: 5300 case Builtin::BI__sync_and_and_fetch_1: 5301 case Builtin::BI__sync_and_and_fetch_2: 5302 case Builtin::BI__sync_and_and_fetch_4: 5303 case Builtin::BI__sync_and_and_fetch_8: 5304 case Builtin::BI__sync_and_and_fetch_16: 5305 BuiltinIndex = 8; 5306 break; 5307 5308 case Builtin::BI__sync_or_and_fetch: 5309 case Builtin::BI__sync_or_and_fetch_1: 5310 case Builtin::BI__sync_or_and_fetch_2: 5311 case Builtin::BI__sync_or_and_fetch_4: 5312 case Builtin::BI__sync_or_and_fetch_8: 5313 case Builtin::BI__sync_or_and_fetch_16: 5314 BuiltinIndex = 9; 5315 break; 5316 5317 case Builtin::BI__sync_xor_and_fetch: 5318 case Builtin::BI__sync_xor_and_fetch_1: 5319 case Builtin::BI__sync_xor_and_fetch_2: 5320 case Builtin::BI__sync_xor_and_fetch_4: 5321 case Builtin::BI__sync_xor_and_fetch_8: 5322 case Builtin::BI__sync_xor_and_fetch_16: 5323 BuiltinIndex = 10; 5324 break; 5325 5326 case Builtin::BI__sync_nand_and_fetch: 5327 case Builtin::BI__sync_nand_and_fetch_1: 5328 case Builtin::BI__sync_nand_and_fetch_2: 5329 case Builtin::BI__sync_nand_and_fetch_4: 5330 case Builtin::BI__sync_nand_and_fetch_8: 5331 case Builtin::BI__sync_nand_and_fetch_16: 5332 BuiltinIndex = 11; 5333 WarnAboutSemanticsChange = true; 5334 break; 5335 5336 case Builtin::BI__sync_val_compare_and_swap: 5337 case Builtin::BI__sync_val_compare_and_swap_1: 5338 case Builtin::BI__sync_val_compare_and_swap_2: 5339 case Builtin::BI__sync_val_compare_and_swap_4: 5340 case Builtin::BI__sync_val_compare_and_swap_8: 5341 case Builtin::BI__sync_val_compare_and_swap_16: 5342 BuiltinIndex = 12; 5343 NumFixed = 2; 5344 break; 5345 5346 case Builtin::BI__sync_bool_compare_and_swap: 5347 case Builtin::BI__sync_bool_compare_and_swap_1: 5348 case Builtin::BI__sync_bool_compare_and_swap_2: 5349 case Builtin::BI__sync_bool_compare_and_swap_4: 5350 case Builtin::BI__sync_bool_compare_and_swap_8: 5351 case Builtin::BI__sync_bool_compare_and_swap_16: 5352 BuiltinIndex = 13; 5353 NumFixed = 2; 5354 ResultType = Context.BoolTy; 5355 break; 5356 5357 case Builtin::BI__sync_lock_test_and_set: 5358 case Builtin::BI__sync_lock_test_and_set_1: 5359 case Builtin::BI__sync_lock_test_and_set_2: 5360 case Builtin::BI__sync_lock_test_and_set_4: 5361 case Builtin::BI__sync_lock_test_and_set_8: 5362 case Builtin::BI__sync_lock_test_and_set_16: 5363 BuiltinIndex = 14; 5364 break; 5365 5366 case Builtin::BI__sync_lock_release: 5367 case Builtin::BI__sync_lock_release_1: 5368 case Builtin::BI__sync_lock_release_2: 5369 case Builtin::BI__sync_lock_release_4: 5370 case Builtin::BI__sync_lock_release_8: 5371 case Builtin::BI__sync_lock_release_16: 5372 BuiltinIndex = 15; 5373 NumFixed = 0; 5374 ResultType = Context.VoidTy; 5375 break; 5376 5377 case Builtin::BI__sync_swap: 5378 case Builtin::BI__sync_swap_1: 5379 case Builtin::BI__sync_swap_2: 5380 case Builtin::BI__sync_swap_4: 5381 case Builtin::BI__sync_swap_8: 5382 case Builtin::BI__sync_swap_16: 5383 BuiltinIndex = 16; 5384 break; 5385 } 5386 5387 // Now that we know how many fixed arguments we expect, first check that we 5388 // have at least that many. 5389 if (TheCall->getNumArgs() < 1+NumFixed) { 5390 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5391 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5392 << Callee->getSourceRange(); 5393 return ExprError(); 5394 } 5395 5396 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5397 << Callee->getSourceRange(); 5398 5399 if (WarnAboutSemanticsChange) { 5400 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5401 << Callee->getSourceRange(); 5402 } 5403 5404 // Get the decl for the concrete builtin from this, we can tell what the 5405 // concrete integer type we should convert to is. 5406 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5407 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5408 FunctionDecl *NewBuiltinDecl; 5409 if (NewBuiltinID == BuiltinID) 5410 NewBuiltinDecl = FDecl; 5411 else { 5412 // Perform builtin lookup to avoid redeclaring it. 5413 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5414 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5415 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5416 assert(Res.getFoundDecl()); 5417 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5418 if (!NewBuiltinDecl) 5419 return ExprError(); 5420 } 5421 5422 // The first argument --- the pointer --- has a fixed type; we 5423 // deduce the types of the rest of the arguments accordingly. Walk 5424 // the remaining arguments, converting them to the deduced value type. 5425 for (unsigned i = 0; i != NumFixed; ++i) { 5426 ExprResult Arg = TheCall->getArg(i+1); 5427 5428 // GCC does an implicit conversion to the pointer or integer ValType. This 5429 // can fail in some cases (1i -> int**), check for this error case now. 5430 // Initialize the argument. 5431 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5432 ValType, /*consume*/ false); 5433 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5434 if (Arg.isInvalid()) 5435 return ExprError(); 5436 5437 // Okay, we have something that *can* be converted to the right type. Check 5438 // to see if there is a potentially weird extension going on here. This can 5439 // happen when you do an atomic operation on something like an char* and 5440 // pass in 42. The 42 gets converted to char. This is even more strange 5441 // for things like 45.123 -> char, etc. 5442 // FIXME: Do this check. 5443 TheCall->setArg(i+1, Arg.get()); 5444 } 5445 5446 // Create a new DeclRefExpr to refer to the new decl. 5447 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5448 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5449 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5450 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5451 5452 // Set the callee in the CallExpr. 5453 // FIXME: This loses syntactic information. 5454 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5455 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5456 CK_BuiltinFnToFnPtr); 5457 TheCall->setCallee(PromotedCall.get()); 5458 5459 // Change the result type of the call to match the original value type. This 5460 // is arbitrary, but the codegen for these builtins ins design to handle it 5461 // gracefully. 5462 TheCall->setType(ResultType); 5463 5464 // Prohibit use of _ExtInt with atomic builtins. 5465 // The arguments would have already been converted to the first argument's 5466 // type, so only need to check the first argument. 5467 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5468 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5469 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5470 return ExprError(); 5471 } 5472 5473 return TheCallResult; 5474 } 5475 5476 /// SemaBuiltinNontemporalOverloaded - We have a call to 5477 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5478 /// overloaded function based on the pointer type of its last argument. 5479 /// 5480 /// This function goes through and does final semantic checking for these 5481 /// builtins. 5482 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5483 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5484 DeclRefExpr *DRE = 5485 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5486 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5487 unsigned BuiltinID = FDecl->getBuiltinID(); 5488 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5489 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5490 "Unexpected nontemporal load/store builtin!"); 5491 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5492 unsigned numArgs = isStore ? 2 : 1; 5493 5494 // Ensure that we have the proper number of arguments. 5495 if (checkArgCount(*this, TheCall, numArgs)) 5496 return ExprError(); 5497 5498 // Inspect the last argument of the nontemporal builtin. This should always 5499 // be a pointer type, from which we imply the type of the memory access. 5500 // Because it is a pointer type, we don't have to worry about any implicit 5501 // casts here. 5502 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5503 ExprResult PointerArgResult = 5504 DefaultFunctionArrayLvalueConversion(PointerArg); 5505 5506 if (PointerArgResult.isInvalid()) 5507 return ExprError(); 5508 PointerArg = PointerArgResult.get(); 5509 TheCall->setArg(numArgs - 1, PointerArg); 5510 5511 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5512 if (!pointerType) { 5513 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5514 << PointerArg->getType() << PointerArg->getSourceRange(); 5515 return ExprError(); 5516 } 5517 5518 QualType ValType = pointerType->getPointeeType(); 5519 5520 // Strip any qualifiers off ValType. 5521 ValType = ValType.getUnqualifiedType(); 5522 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5523 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5524 !ValType->isVectorType()) { 5525 Diag(DRE->getBeginLoc(), 5526 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5527 << PointerArg->getType() << PointerArg->getSourceRange(); 5528 return ExprError(); 5529 } 5530 5531 if (!isStore) { 5532 TheCall->setType(ValType); 5533 return TheCallResult; 5534 } 5535 5536 ExprResult ValArg = TheCall->getArg(0); 5537 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5538 Context, ValType, /*consume*/ false); 5539 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5540 if (ValArg.isInvalid()) 5541 return ExprError(); 5542 5543 TheCall->setArg(0, ValArg.get()); 5544 TheCall->setType(Context.VoidTy); 5545 return TheCallResult; 5546 } 5547 5548 /// CheckObjCString - Checks that the argument to the builtin 5549 /// CFString constructor is correct 5550 /// Note: It might also make sense to do the UTF-16 conversion here (would 5551 /// simplify the backend). 5552 bool Sema::CheckObjCString(Expr *Arg) { 5553 Arg = Arg->IgnoreParenCasts(); 5554 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5555 5556 if (!Literal || !Literal->isAscii()) { 5557 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5558 << Arg->getSourceRange(); 5559 return true; 5560 } 5561 5562 if (Literal->containsNonAsciiOrNull()) { 5563 StringRef String = Literal->getString(); 5564 unsigned NumBytes = String.size(); 5565 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5566 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5567 llvm::UTF16 *ToPtr = &ToBuf[0]; 5568 5569 llvm::ConversionResult Result = 5570 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5571 ToPtr + NumBytes, llvm::strictConversion); 5572 // Check for conversion failure. 5573 if (Result != llvm::conversionOK) 5574 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5575 << Arg->getSourceRange(); 5576 } 5577 return false; 5578 } 5579 5580 /// CheckObjCString - Checks that the format string argument to the os_log() 5581 /// and os_trace() functions is correct, and converts it to const char *. 5582 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5583 Arg = Arg->IgnoreParenCasts(); 5584 auto *Literal = dyn_cast<StringLiteral>(Arg); 5585 if (!Literal) { 5586 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5587 Literal = ObjcLiteral->getString(); 5588 } 5589 } 5590 5591 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5592 return ExprError( 5593 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5594 << Arg->getSourceRange()); 5595 } 5596 5597 ExprResult Result(Literal); 5598 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5599 InitializedEntity Entity = 5600 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5601 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5602 return Result; 5603 } 5604 5605 /// Check that the user is calling the appropriate va_start builtin for the 5606 /// target and calling convention. 5607 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5608 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5609 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5610 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5611 TT.getArch() == llvm::Triple::aarch64_32); 5612 bool IsWindows = TT.isOSWindows(); 5613 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5614 if (IsX64 || IsAArch64) { 5615 CallingConv CC = CC_C; 5616 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5617 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5618 if (IsMSVAStart) { 5619 // Don't allow this in System V ABI functions. 5620 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5621 return S.Diag(Fn->getBeginLoc(), 5622 diag::err_ms_va_start_used_in_sysv_function); 5623 } else { 5624 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5625 // On x64 Windows, don't allow this in System V ABI functions. 5626 // (Yes, that means there's no corresponding way to support variadic 5627 // System V ABI functions on Windows.) 5628 if ((IsWindows && CC == CC_X86_64SysV) || 5629 (!IsWindows && CC == CC_Win64)) 5630 return S.Diag(Fn->getBeginLoc(), 5631 diag::err_va_start_used_in_wrong_abi_function) 5632 << !IsWindows; 5633 } 5634 return false; 5635 } 5636 5637 if (IsMSVAStart) 5638 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5639 return false; 5640 } 5641 5642 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5643 ParmVarDecl **LastParam = nullptr) { 5644 // Determine whether the current function, block, or obj-c method is variadic 5645 // and get its parameter list. 5646 bool IsVariadic = false; 5647 ArrayRef<ParmVarDecl *> Params; 5648 DeclContext *Caller = S.CurContext; 5649 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5650 IsVariadic = Block->isVariadic(); 5651 Params = Block->parameters(); 5652 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5653 IsVariadic = FD->isVariadic(); 5654 Params = FD->parameters(); 5655 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5656 IsVariadic = MD->isVariadic(); 5657 // FIXME: This isn't correct for methods (results in bogus warning). 5658 Params = MD->parameters(); 5659 } else if (isa<CapturedDecl>(Caller)) { 5660 // We don't support va_start in a CapturedDecl. 5661 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5662 return true; 5663 } else { 5664 // This must be some other declcontext that parses exprs. 5665 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5666 return true; 5667 } 5668 5669 if (!IsVariadic) { 5670 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5671 return true; 5672 } 5673 5674 if (LastParam) 5675 *LastParam = Params.empty() ? nullptr : Params.back(); 5676 5677 return false; 5678 } 5679 5680 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5681 /// for validity. Emit an error and return true on failure; return false 5682 /// on success. 5683 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5684 Expr *Fn = TheCall->getCallee(); 5685 5686 if (checkVAStartABI(*this, BuiltinID, Fn)) 5687 return true; 5688 5689 if (checkArgCount(*this, TheCall, 2)) 5690 return true; 5691 5692 // Type-check the first argument normally. 5693 if (checkBuiltinArgument(*this, TheCall, 0)) 5694 return true; 5695 5696 // Check that the current function is variadic, and get its last parameter. 5697 ParmVarDecl *LastParam; 5698 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5699 return true; 5700 5701 // Verify that the second argument to the builtin is the last argument of the 5702 // current function or method. 5703 bool SecondArgIsLastNamedArgument = false; 5704 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5705 5706 // These are valid if SecondArgIsLastNamedArgument is false after the next 5707 // block. 5708 QualType Type; 5709 SourceLocation ParamLoc; 5710 bool IsCRegister = false; 5711 5712 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5713 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5714 SecondArgIsLastNamedArgument = PV == LastParam; 5715 5716 Type = PV->getType(); 5717 ParamLoc = PV->getLocation(); 5718 IsCRegister = 5719 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5720 } 5721 } 5722 5723 if (!SecondArgIsLastNamedArgument) 5724 Diag(TheCall->getArg(1)->getBeginLoc(), 5725 diag::warn_second_arg_of_va_start_not_last_named_param); 5726 else if (IsCRegister || Type->isReferenceType() || 5727 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5728 // Promotable integers are UB, but enumerations need a bit of 5729 // extra checking to see what their promotable type actually is. 5730 if (!Type->isPromotableIntegerType()) 5731 return false; 5732 if (!Type->isEnumeralType()) 5733 return true; 5734 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5735 return !(ED && 5736 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5737 }()) { 5738 unsigned Reason = 0; 5739 if (Type->isReferenceType()) Reason = 1; 5740 else if (IsCRegister) Reason = 2; 5741 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5742 Diag(ParamLoc, diag::note_parameter_type) << Type; 5743 } 5744 5745 TheCall->setType(Context.VoidTy); 5746 return false; 5747 } 5748 5749 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5750 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5751 // const char *named_addr); 5752 5753 Expr *Func = Call->getCallee(); 5754 5755 if (Call->getNumArgs() < 3) 5756 return Diag(Call->getEndLoc(), 5757 diag::err_typecheck_call_too_few_args_at_least) 5758 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5759 5760 // Type-check the first argument normally. 5761 if (checkBuiltinArgument(*this, Call, 0)) 5762 return true; 5763 5764 // Check that the current function is variadic. 5765 if (checkVAStartIsInVariadicFunction(*this, Func)) 5766 return true; 5767 5768 // __va_start on Windows does not validate the parameter qualifiers 5769 5770 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5771 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5772 5773 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5774 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5775 5776 const QualType &ConstCharPtrTy = 5777 Context.getPointerType(Context.CharTy.withConst()); 5778 if (!Arg1Ty->isPointerType() || 5779 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5780 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5781 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5782 << 0 /* qualifier difference */ 5783 << 3 /* parameter mismatch */ 5784 << 2 << Arg1->getType() << ConstCharPtrTy; 5785 5786 const QualType SizeTy = Context.getSizeType(); 5787 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5788 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5789 << Arg2->getType() << SizeTy << 1 /* different class */ 5790 << 0 /* qualifier difference */ 5791 << 3 /* parameter mismatch */ 5792 << 3 << Arg2->getType() << SizeTy; 5793 5794 return false; 5795 } 5796 5797 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5798 /// friends. This is declared to take (...), so we have to check everything. 5799 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5800 if (checkArgCount(*this, TheCall, 2)) 5801 return true; 5802 5803 ExprResult OrigArg0 = TheCall->getArg(0); 5804 ExprResult OrigArg1 = TheCall->getArg(1); 5805 5806 // Do standard promotions between the two arguments, returning their common 5807 // type. 5808 QualType Res = UsualArithmeticConversions( 5809 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5810 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5811 return true; 5812 5813 // Make sure any conversions are pushed back into the call; this is 5814 // type safe since unordered compare builtins are declared as "_Bool 5815 // foo(...)". 5816 TheCall->setArg(0, OrigArg0.get()); 5817 TheCall->setArg(1, OrigArg1.get()); 5818 5819 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5820 return false; 5821 5822 // If the common type isn't a real floating type, then the arguments were 5823 // invalid for this operation. 5824 if (Res.isNull() || !Res->isRealFloatingType()) 5825 return Diag(OrigArg0.get()->getBeginLoc(), 5826 diag::err_typecheck_call_invalid_ordered_compare) 5827 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5828 << SourceRange(OrigArg0.get()->getBeginLoc(), 5829 OrigArg1.get()->getEndLoc()); 5830 5831 return false; 5832 } 5833 5834 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5835 /// __builtin_isnan and friends. This is declared to take (...), so we have 5836 /// to check everything. We expect the last argument to be a floating point 5837 /// value. 5838 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5839 if (checkArgCount(*this, TheCall, NumArgs)) 5840 return true; 5841 5842 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5843 // on all preceding parameters just being int. Try all of those. 5844 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5845 Expr *Arg = TheCall->getArg(i); 5846 5847 if (Arg->isTypeDependent()) 5848 return false; 5849 5850 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5851 5852 if (Res.isInvalid()) 5853 return true; 5854 TheCall->setArg(i, Res.get()); 5855 } 5856 5857 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5858 5859 if (OrigArg->isTypeDependent()) 5860 return false; 5861 5862 // Usual Unary Conversions will convert half to float, which we want for 5863 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5864 // type how it is, but do normal L->Rvalue conversions. 5865 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5866 OrigArg = UsualUnaryConversions(OrigArg).get(); 5867 else 5868 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5869 TheCall->setArg(NumArgs - 1, OrigArg); 5870 5871 // This operation requires a non-_Complex floating-point number. 5872 if (!OrigArg->getType()->isRealFloatingType()) 5873 return Diag(OrigArg->getBeginLoc(), 5874 diag::err_typecheck_call_invalid_unary_fp) 5875 << OrigArg->getType() << OrigArg->getSourceRange(); 5876 5877 return false; 5878 } 5879 5880 /// Perform semantic analysis for a call to __builtin_complex. 5881 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 5882 if (checkArgCount(*this, TheCall, 2)) 5883 return true; 5884 5885 bool Dependent = false; 5886 for (unsigned I = 0; I != 2; ++I) { 5887 Expr *Arg = TheCall->getArg(I); 5888 QualType T = Arg->getType(); 5889 if (T->isDependentType()) { 5890 Dependent = true; 5891 continue; 5892 } 5893 5894 // Despite supporting _Complex int, GCC requires a real floating point type 5895 // for the operands of __builtin_complex. 5896 if (!T->isRealFloatingType()) { 5897 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 5898 << Arg->getType() << Arg->getSourceRange(); 5899 } 5900 5901 ExprResult Converted = DefaultLvalueConversion(Arg); 5902 if (Converted.isInvalid()) 5903 return true; 5904 TheCall->setArg(I, Converted.get()); 5905 } 5906 5907 if (Dependent) { 5908 TheCall->setType(Context.DependentTy); 5909 return false; 5910 } 5911 5912 Expr *Real = TheCall->getArg(0); 5913 Expr *Imag = TheCall->getArg(1); 5914 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 5915 return Diag(Real->getBeginLoc(), 5916 diag::err_typecheck_call_different_arg_types) 5917 << Real->getType() << Imag->getType() 5918 << Real->getSourceRange() << Imag->getSourceRange(); 5919 } 5920 5921 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 5922 // don't allow this builtin to form those types either. 5923 // FIXME: Should we allow these types? 5924 if (Real->getType()->isFloat16Type()) 5925 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5926 << "_Float16"; 5927 if (Real->getType()->isHalfType()) 5928 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5929 << "half"; 5930 5931 TheCall->setType(Context.getComplexType(Real->getType())); 5932 return false; 5933 } 5934 5935 // Customized Sema Checking for VSX builtins that have the following signature: 5936 // vector [...] builtinName(vector [...], vector [...], const int); 5937 // Which takes the same type of vectors (any legal vector type) for the first 5938 // two arguments and takes compile time constant for the third argument. 5939 // Example builtins are : 5940 // vector double vec_xxpermdi(vector double, vector double, int); 5941 // vector short vec_xxsldwi(vector short, vector short, int); 5942 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5943 unsigned ExpectedNumArgs = 3; 5944 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 5945 return true; 5946 5947 // Check the third argument is a compile time constant 5948 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 5949 return Diag(TheCall->getBeginLoc(), 5950 diag::err_vsx_builtin_nonconstant_argument) 5951 << 3 /* argument index */ << TheCall->getDirectCallee() 5952 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5953 TheCall->getArg(2)->getEndLoc()); 5954 5955 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5956 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5957 5958 // Check the type of argument 1 and argument 2 are vectors. 5959 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5960 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5961 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5962 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5963 << TheCall->getDirectCallee() 5964 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5965 TheCall->getArg(1)->getEndLoc()); 5966 } 5967 5968 // Check the first two arguments are the same type. 5969 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5970 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5971 << TheCall->getDirectCallee() 5972 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5973 TheCall->getArg(1)->getEndLoc()); 5974 } 5975 5976 // When default clang type checking is turned off and the customized type 5977 // checking is used, the returning type of the function must be explicitly 5978 // set. Otherwise it is _Bool by default. 5979 TheCall->setType(Arg1Ty); 5980 5981 return false; 5982 } 5983 5984 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5985 // This is declared to take (...), so we have to check everything. 5986 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5987 if (TheCall->getNumArgs() < 2) 5988 return ExprError(Diag(TheCall->getEndLoc(), 5989 diag::err_typecheck_call_too_few_args_at_least) 5990 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5991 << TheCall->getSourceRange()); 5992 5993 // Determine which of the following types of shufflevector we're checking: 5994 // 1) unary, vector mask: (lhs, mask) 5995 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5996 QualType resType = TheCall->getArg(0)->getType(); 5997 unsigned numElements = 0; 5998 5999 if (!TheCall->getArg(0)->isTypeDependent() && 6000 !TheCall->getArg(1)->isTypeDependent()) { 6001 QualType LHSType = TheCall->getArg(0)->getType(); 6002 QualType RHSType = TheCall->getArg(1)->getType(); 6003 6004 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6005 return ExprError( 6006 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6007 << TheCall->getDirectCallee() 6008 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6009 TheCall->getArg(1)->getEndLoc())); 6010 6011 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6012 unsigned numResElements = TheCall->getNumArgs() - 2; 6013 6014 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6015 // with mask. If so, verify that RHS is an integer vector type with the 6016 // same number of elts as lhs. 6017 if (TheCall->getNumArgs() == 2) { 6018 if (!RHSType->hasIntegerRepresentation() || 6019 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6020 return ExprError(Diag(TheCall->getBeginLoc(), 6021 diag::err_vec_builtin_incompatible_vector) 6022 << TheCall->getDirectCallee() 6023 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6024 TheCall->getArg(1)->getEndLoc())); 6025 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6026 return ExprError(Diag(TheCall->getBeginLoc(), 6027 diag::err_vec_builtin_incompatible_vector) 6028 << TheCall->getDirectCallee() 6029 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6030 TheCall->getArg(1)->getEndLoc())); 6031 } else if (numElements != numResElements) { 6032 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6033 resType = Context.getVectorType(eltType, numResElements, 6034 VectorType::GenericVector); 6035 } 6036 } 6037 6038 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6039 if (TheCall->getArg(i)->isTypeDependent() || 6040 TheCall->getArg(i)->isValueDependent()) 6041 continue; 6042 6043 Optional<llvm::APSInt> Result; 6044 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6045 return ExprError(Diag(TheCall->getBeginLoc(), 6046 diag::err_shufflevector_nonconstant_argument) 6047 << TheCall->getArg(i)->getSourceRange()); 6048 6049 // Allow -1 which will be translated to undef in the IR. 6050 if (Result->isSigned() && Result->isAllOnesValue()) 6051 continue; 6052 6053 if (Result->getActiveBits() > 64 || 6054 Result->getZExtValue() >= numElements * 2) 6055 return ExprError(Diag(TheCall->getBeginLoc(), 6056 diag::err_shufflevector_argument_too_large) 6057 << TheCall->getArg(i)->getSourceRange()); 6058 } 6059 6060 SmallVector<Expr*, 32> exprs; 6061 6062 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6063 exprs.push_back(TheCall->getArg(i)); 6064 TheCall->setArg(i, nullptr); 6065 } 6066 6067 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6068 TheCall->getCallee()->getBeginLoc(), 6069 TheCall->getRParenLoc()); 6070 } 6071 6072 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6073 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6074 SourceLocation BuiltinLoc, 6075 SourceLocation RParenLoc) { 6076 ExprValueKind VK = VK_RValue; 6077 ExprObjectKind OK = OK_Ordinary; 6078 QualType DstTy = TInfo->getType(); 6079 QualType SrcTy = E->getType(); 6080 6081 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6082 return ExprError(Diag(BuiltinLoc, 6083 diag::err_convertvector_non_vector) 6084 << E->getSourceRange()); 6085 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6086 return ExprError(Diag(BuiltinLoc, 6087 diag::err_convertvector_non_vector_type)); 6088 6089 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6090 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6091 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6092 if (SrcElts != DstElts) 6093 return ExprError(Diag(BuiltinLoc, 6094 diag::err_convertvector_incompatible_vector) 6095 << E->getSourceRange()); 6096 } 6097 6098 return new (Context) 6099 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6100 } 6101 6102 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6103 // This is declared to take (const void*, ...) and can take two 6104 // optional constant int args. 6105 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6106 unsigned NumArgs = TheCall->getNumArgs(); 6107 6108 if (NumArgs > 3) 6109 return Diag(TheCall->getEndLoc(), 6110 diag::err_typecheck_call_too_many_args_at_most) 6111 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6112 6113 // Argument 0 is checked for us and the remaining arguments must be 6114 // constant integers. 6115 for (unsigned i = 1; i != NumArgs; ++i) 6116 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6117 return true; 6118 6119 return false; 6120 } 6121 6122 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6123 // __assume does not evaluate its arguments, and should warn if its argument 6124 // has side effects. 6125 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6126 Expr *Arg = TheCall->getArg(0); 6127 if (Arg->isInstantiationDependent()) return false; 6128 6129 if (Arg->HasSideEffects(Context)) 6130 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6131 << Arg->getSourceRange() 6132 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6133 6134 return false; 6135 } 6136 6137 /// Handle __builtin_alloca_with_align. This is declared 6138 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6139 /// than 8. 6140 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6141 // The alignment must be a constant integer. 6142 Expr *Arg = TheCall->getArg(1); 6143 6144 // We can't check the value of a dependent argument. 6145 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6146 if (const auto *UE = 6147 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6148 if (UE->getKind() == UETT_AlignOf || 6149 UE->getKind() == UETT_PreferredAlignOf) 6150 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6151 << Arg->getSourceRange(); 6152 6153 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6154 6155 if (!Result.isPowerOf2()) 6156 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6157 << Arg->getSourceRange(); 6158 6159 if (Result < Context.getCharWidth()) 6160 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6161 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6162 6163 if (Result > std::numeric_limits<int32_t>::max()) 6164 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6165 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6166 } 6167 6168 return false; 6169 } 6170 6171 /// Handle __builtin_assume_aligned. This is declared 6172 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6173 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6174 unsigned NumArgs = TheCall->getNumArgs(); 6175 6176 if (NumArgs > 3) 6177 return Diag(TheCall->getEndLoc(), 6178 diag::err_typecheck_call_too_many_args_at_most) 6179 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6180 6181 // The alignment must be a constant integer. 6182 Expr *Arg = TheCall->getArg(1); 6183 6184 // We can't check the value of a dependent argument. 6185 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6186 llvm::APSInt Result; 6187 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6188 return true; 6189 6190 if (!Result.isPowerOf2()) 6191 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6192 << Arg->getSourceRange(); 6193 6194 if (Result > Sema::MaximumAlignment) 6195 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6196 << Arg->getSourceRange() << Sema::MaximumAlignment; 6197 } 6198 6199 if (NumArgs > 2) { 6200 ExprResult Arg(TheCall->getArg(2)); 6201 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6202 Context.getSizeType(), false); 6203 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6204 if (Arg.isInvalid()) return true; 6205 TheCall->setArg(2, Arg.get()); 6206 } 6207 6208 return false; 6209 } 6210 6211 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6212 unsigned BuiltinID = 6213 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6214 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6215 6216 unsigned NumArgs = TheCall->getNumArgs(); 6217 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6218 if (NumArgs < NumRequiredArgs) { 6219 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6220 << 0 /* function call */ << NumRequiredArgs << NumArgs 6221 << TheCall->getSourceRange(); 6222 } 6223 if (NumArgs >= NumRequiredArgs + 0x100) { 6224 return Diag(TheCall->getEndLoc(), 6225 diag::err_typecheck_call_too_many_args_at_most) 6226 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6227 << TheCall->getSourceRange(); 6228 } 6229 unsigned i = 0; 6230 6231 // For formatting call, check buffer arg. 6232 if (!IsSizeCall) { 6233 ExprResult Arg(TheCall->getArg(i)); 6234 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6235 Context, Context.VoidPtrTy, false); 6236 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6237 if (Arg.isInvalid()) 6238 return true; 6239 TheCall->setArg(i, Arg.get()); 6240 i++; 6241 } 6242 6243 // Check string literal arg. 6244 unsigned FormatIdx = i; 6245 { 6246 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6247 if (Arg.isInvalid()) 6248 return true; 6249 TheCall->setArg(i, Arg.get()); 6250 i++; 6251 } 6252 6253 // Make sure variadic args are scalar. 6254 unsigned FirstDataArg = i; 6255 while (i < NumArgs) { 6256 ExprResult Arg = DefaultVariadicArgumentPromotion( 6257 TheCall->getArg(i), VariadicFunction, nullptr); 6258 if (Arg.isInvalid()) 6259 return true; 6260 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6261 if (ArgSize.getQuantity() >= 0x100) { 6262 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6263 << i << (int)ArgSize.getQuantity() << 0xff 6264 << TheCall->getSourceRange(); 6265 } 6266 TheCall->setArg(i, Arg.get()); 6267 i++; 6268 } 6269 6270 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6271 // call to avoid duplicate diagnostics. 6272 if (!IsSizeCall) { 6273 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6274 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6275 bool Success = CheckFormatArguments( 6276 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6277 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6278 CheckedVarArgs); 6279 if (!Success) 6280 return true; 6281 } 6282 6283 if (IsSizeCall) { 6284 TheCall->setType(Context.getSizeType()); 6285 } else { 6286 TheCall->setType(Context.VoidPtrTy); 6287 } 6288 return false; 6289 } 6290 6291 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6292 /// TheCall is a constant expression. 6293 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6294 llvm::APSInt &Result) { 6295 Expr *Arg = TheCall->getArg(ArgNum); 6296 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6297 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6298 6299 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6300 6301 Optional<llvm::APSInt> R; 6302 if (!(R = Arg->getIntegerConstantExpr(Context))) 6303 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6304 << FDecl->getDeclName() << Arg->getSourceRange(); 6305 Result = *R; 6306 return false; 6307 } 6308 6309 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6310 /// TheCall is a constant expression in the range [Low, High]. 6311 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6312 int Low, int High, bool RangeIsError) { 6313 if (isConstantEvaluated()) 6314 return false; 6315 llvm::APSInt Result; 6316 6317 // We can't check the value of a dependent argument. 6318 Expr *Arg = TheCall->getArg(ArgNum); 6319 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6320 return false; 6321 6322 // Check constant-ness first. 6323 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6324 return true; 6325 6326 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6327 if (RangeIsError) 6328 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6329 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6330 else 6331 // Defer the warning until we know if the code will be emitted so that 6332 // dead code can ignore this. 6333 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6334 PDiag(diag::warn_argument_invalid_range) 6335 << Result.toString(10) << Low << High 6336 << Arg->getSourceRange()); 6337 } 6338 6339 return false; 6340 } 6341 6342 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6343 /// TheCall is a constant expression is a multiple of Num.. 6344 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6345 unsigned Num) { 6346 llvm::APSInt Result; 6347 6348 // We can't check the value of a dependent argument. 6349 Expr *Arg = TheCall->getArg(ArgNum); 6350 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6351 return false; 6352 6353 // Check constant-ness first. 6354 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6355 return true; 6356 6357 if (Result.getSExtValue() % Num != 0) 6358 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6359 << Num << Arg->getSourceRange(); 6360 6361 return false; 6362 } 6363 6364 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6365 /// constant expression representing a power of 2. 6366 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6367 llvm::APSInt Result; 6368 6369 // We can't check the value of a dependent argument. 6370 Expr *Arg = TheCall->getArg(ArgNum); 6371 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6372 return false; 6373 6374 // Check constant-ness first. 6375 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6376 return true; 6377 6378 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6379 // and only if x is a power of 2. 6380 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6381 return false; 6382 6383 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6384 << Arg->getSourceRange(); 6385 } 6386 6387 static bool IsShiftedByte(llvm::APSInt Value) { 6388 if (Value.isNegative()) 6389 return false; 6390 6391 // Check if it's a shifted byte, by shifting it down 6392 while (true) { 6393 // If the value fits in the bottom byte, the check passes. 6394 if (Value < 0x100) 6395 return true; 6396 6397 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6398 // fails. 6399 if ((Value & 0xFF) != 0) 6400 return false; 6401 6402 // If the bottom 8 bits are all 0, but something above that is nonzero, 6403 // then shifting the value right by 8 bits won't affect whether it's a 6404 // shifted byte or not. So do that, and go round again. 6405 Value >>= 8; 6406 } 6407 } 6408 6409 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6410 /// a constant expression representing an arbitrary byte value shifted left by 6411 /// a multiple of 8 bits. 6412 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6413 unsigned ArgBits) { 6414 llvm::APSInt Result; 6415 6416 // We can't check the value of a dependent argument. 6417 Expr *Arg = TheCall->getArg(ArgNum); 6418 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6419 return false; 6420 6421 // Check constant-ness first. 6422 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6423 return true; 6424 6425 // Truncate to the given size. 6426 Result = Result.getLoBits(ArgBits); 6427 Result.setIsUnsigned(true); 6428 6429 if (IsShiftedByte(Result)) 6430 return false; 6431 6432 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6433 << Arg->getSourceRange(); 6434 } 6435 6436 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6437 /// TheCall is a constant expression representing either a shifted byte value, 6438 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6439 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6440 /// Arm MVE intrinsics. 6441 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6442 int ArgNum, 6443 unsigned ArgBits) { 6444 llvm::APSInt Result; 6445 6446 // We can't check the value of a dependent argument. 6447 Expr *Arg = TheCall->getArg(ArgNum); 6448 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6449 return false; 6450 6451 // Check constant-ness first. 6452 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6453 return true; 6454 6455 // Truncate to the given size. 6456 Result = Result.getLoBits(ArgBits); 6457 Result.setIsUnsigned(true); 6458 6459 // Check to see if it's in either of the required forms. 6460 if (IsShiftedByte(Result) || 6461 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6462 return false; 6463 6464 return Diag(TheCall->getBeginLoc(), 6465 diag::err_argument_not_shifted_byte_or_xxff) 6466 << Arg->getSourceRange(); 6467 } 6468 6469 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6470 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6471 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6472 if (checkArgCount(*this, TheCall, 2)) 6473 return true; 6474 Expr *Arg0 = TheCall->getArg(0); 6475 Expr *Arg1 = TheCall->getArg(1); 6476 6477 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6478 if (FirstArg.isInvalid()) 6479 return true; 6480 QualType FirstArgType = FirstArg.get()->getType(); 6481 if (!FirstArgType->isAnyPointerType()) 6482 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6483 << "first" << FirstArgType << Arg0->getSourceRange(); 6484 TheCall->setArg(0, FirstArg.get()); 6485 6486 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6487 if (SecArg.isInvalid()) 6488 return true; 6489 QualType SecArgType = SecArg.get()->getType(); 6490 if (!SecArgType->isIntegerType()) 6491 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6492 << "second" << SecArgType << Arg1->getSourceRange(); 6493 6494 // Derive the return type from the pointer argument. 6495 TheCall->setType(FirstArgType); 6496 return false; 6497 } 6498 6499 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6500 if (checkArgCount(*this, TheCall, 2)) 6501 return true; 6502 6503 Expr *Arg0 = TheCall->getArg(0); 6504 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6505 if (FirstArg.isInvalid()) 6506 return true; 6507 QualType FirstArgType = FirstArg.get()->getType(); 6508 if (!FirstArgType->isAnyPointerType()) 6509 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6510 << "first" << FirstArgType << Arg0->getSourceRange(); 6511 TheCall->setArg(0, FirstArg.get()); 6512 6513 // Derive the return type from the pointer argument. 6514 TheCall->setType(FirstArgType); 6515 6516 // Second arg must be an constant in range [0,15] 6517 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6518 } 6519 6520 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6521 if (checkArgCount(*this, TheCall, 2)) 6522 return true; 6523 Expr *Arg0 = TheCall->getArg(0); 6524 Expr *Arg1 = TheCall->getArg(1); 6525 6526 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6527 if (FirstArg.isInvalid()) 6528 return true; 6529 QualType FirstArgType = FirstArg.get()->getType(); 6530 if (!FirstArgType->isAnyPointerType()) 6531 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6532 << "first" << FirstArgType << Arg0->getSourceRange(); 6533 6534 QualType SecArgType = Arg1->getType(); 6535 if (!SecArgType->isIntegerType()) 6536 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6537 << "second" << SecArgType << Arg1->getSourceRange(); 6538 TheCall->setType(Context.IntTy); 6539 return false; 6540 } 6541 6542 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6543 BuiltinID == AArch64::BI__builtin_arm_stg) { 6544 if (checkArgCount(*this, TheCall, 1)) 6545 return true; 6546 Expr *Arg0 = TheCall->getArg(0); 6547 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6548 if (FirstArg.isInvalid()) 6549 return true; 6550 6551 QualType FirstArgType = FirstArg.get()->getType(); 6552 if (!FirstArgType->isAnyPointerType()) 6553 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6554 << "first" << FirstArgType << Arg0->getSourceRange(); 6555 TheCall->setArg(0, FirstArg.get()); 6556 6557 // Derive the return type from the pointer argument. 6558 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6559 TheCall->setType(FirstArgType); 6560 return false; 6561 } 6562 6563 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6564 Expr *ArgA = TheCall->getArg(0); 6565 Expr *ArgB = TheCall->getArg(1); 6566 6567 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6568 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6569 6570 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6571 return true; 6572 6573 QualType ArgTypeA = ArgExprA.get()->getType(); 6574 QualType ArgTypeB = ArgExprB.get()->getType(); 6575 6576 auto isNull = [&] (Expr *E) -> bool { 6577 return E->isNullPointerConstant( 6578 Context, Expr::NPC_ValueDependentIsNotNull); }; 6579 6580 // argument should be either a pointer or null 6581 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6582 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6583 << "first" << ArgTypeA << ArgA->getSourceRange(); 6584 6585 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6586 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6587 << "second" << ArgTypeB << ArgB->getSourceRange(); 6588 6589 // Ensure Pointee types are compatible 6590 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6591 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6592 QualType pointeeA = ArgTypeA->getPointeeType(); 6593 QualType pointeeB = ArgTypeB->getPointeeType(); 6594 if (!Context.typesAreCompatible( 6595 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6596 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6597 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6598 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6599 << ArgB->getSourceRange(); 6600 } 6601 } 6602 6603 // at least one argument should be pointer type 6604 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6605 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6606 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6607 6608 if (isNull(ArgA)) // adopt type of the other pointer 6609 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6610 6611 if (isNull(ArgB)) 6612 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6613 6614 TheCall->setArg(0, ArgExprA.get()); 6615 TheCall->setArg(1, ArgExprB.get()); 6616 TheCall->setType(Context.LongLongTy); 6617 return false; 6618 } 6619 assert(false && "Unhandled ARM MTE intrinsic"); 6620 return true; 6621 } 6622 6623 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6624 /// TheCall is an ARM/AArch64 special register string literal. 6625 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6626 int ArgNum, unsigned ExpectedFieldNum, 6627 bool AllowName) { 6628 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6629 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6630 BuiltinID == ARM::BI__builtin_arm_rsr || 6631 BuiltinID == ARM::BI__builtin_arm_rsrp || 6632 BuiltinID == ARM::BI__builtin_arm_wsr || 6633 BuiltinID == ARM::BI__builtin_arm_wsrp; 6634 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6635 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6636 BuiltinID == AArch64::BI__builtin_arm_rsr || 6637 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6638 BuiltinID == AArch64::BI__builtin_arm_wsr || 6639 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6640 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6641 6642 // We can't check the value of a dependent argument. 6643 Expr *Arg = TheCall->getArg(ArgNum); 6644 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6645 return false; 6646 6647 // Check if the argument is a string literal. 6648 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6649 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6650 << Arg->getSourceRange(); 6651 6652 // Check the type of special register given. 6653 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6654 SmallVector<StringRef, 6> Fields; 6655 Reg.split(Fields, ":"); 6656 6657 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6658 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6659 << Arg->getSourceRange(); 6660 6661 // If the string is the name of a register then we cannot check that it is 6662 // valid here but if the string is of one the forms described in ACLE then we 6663 // can check that the supplied fields are integers and within the valid 6664 // ranges. 6665 if (Fields.size() > 1) { 6666 bool FiveFields = Fields.size() == 5; 6667 6668 bool ValidString = true; 6669 if (IsARMBuiltin) { 6670 ValidString &= Fields[0].startswith_lower("cp") || 6671 Fields[0].startswith_lower("p"); 6672 if (ValidString) 6673 Fields[0] = 6674 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6675 6676 ValidString &= Fields[2].startswith_lower("c"); 6677 if (ValidString) 6678 Fields[2] = Fields[2].drop_front(1); 6679 6680 if (FiveFields) { 6681 ValidString &= Fields[3].startswith_lower("c"); 6682 if (ValidString) 6683 Fields[3] = Fields[3].drop_front(1); 6684 } 6685 } 6686 6687 SmallVector<int, 5> Ranges; 6688 if (FiveFields) 6689 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6690 else 6691 Ranges.append({15, 7, 15}); 6692 6693 for (unsigned i=0; i<Fields.size(); ++i) { 6694 int IntField; 6695 ValidString &= !Fields[i].getAsInteger(10, IntField); 6696 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6697 } 6698 6699 if (!ValidString) 6700 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6701 << Arg->getSourceRange(); 6702 } else if (IsAArch64Builtin && Fields.size() == 1) { 6703 // If the register name is one of those that appear in the condition below 6704 // and the special register builtin being used is one of the write builtins, 6705 // then we require that the argument provided for writing to the register 6706 // is an integer constant expression. This is because it will be lowered to 6707 // an MSR (immediate) instruction, so we need to know the immediate at 6708 // compile time. 6709 if (TheCall->getNumArgs() != 2) 6710 return false; 6711 6712 std::string RegLower = Reg.lower(); 6713 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6714 RegLower != "pan" && RegLower != "uao") 6715 return false; 6716 6717 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6718 } 6719 6720 return false; 6721 } 6722 6723 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6724 /// This checks that the target supports __builtin_longjmp and 6725 /// that val is a constant 1. 6726 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6727 if (!Context.getTargetInfo().hasSjLjLowering()) 6728 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6729 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6730 6731 Expr *Arg = TheCall->getArg(1); 6732 llvm::APSInt Result; 6733 6734 // TODO: This is less than ideal. Overload this to take a value. 6735 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6736 return true; 6737 6738 if (Result != 1) 6739 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6740 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6741 6742 return false; 6743 } 6744 6745 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6746 /// This checks that the target supports __builtin_setjmp. 6747 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6748 if (!Context.getTargetInfo().hasSjLjLowering()) 6749 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6750 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6751 return false; 6752 } 6753 6754 namespace { 6755 6756 class UncoveredArgHandler { 6757 enum { Unknown = -1, AllCovered = -2 }; 6758 6759 signed FirstUncoveredArg = Unknown; 6760 SmallVector<const Expr *, 4> DiagnosticExprs; 6761 6762 public: 6763 UncoveredArgHandler() = default; 6764 6765 bool hasUncoveredArg() const { 6766 return (FirstUncoveredArg >= 0); 6767 } 6768 6769 unsigned getUncoveredArg() const { 6770 assert(hasUncoveredArg() && "no uncovered argument"); 6771 return FirstUncoveredArg; 6772 } 6773 6774 void setAllCovered() { 6775 // A string has been found with all arguments covered, so clear out 6776 // the diagnostics. 6777 DiagnosticExprs.clear(); 6778 FirstUncoveredArg = AllCovered; 6779 } 6780 6781 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6782 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6783 6784 // Don't update if a previous string covers all arguments. 6785 if (FirstUncoveredArg == AllCovered) 6786 return; 6787 6788 // UncoveredArgHandler tracks the highest uncovered argument index 6789 // and with it all the strings that match this index. 6790 if (NewFirstUncoveredArg == FirstUncoveredArg) 6791 DiagnosticExprs.push_back(StrExpr); 6792 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6793 DiagnosticExprs.clear(); 6794 DiagnosticExprs.push_back(StrExpr); 6795 FirstUncoveredArg = NewFirstUncoveredArg; 6796 } 6797 } 6798 6799 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6800 }; 6801 6802 enum StringLiteralCheckType { 6803 SLCT_NotALiteral, 6804 SLCT_UncheckedLiteral, 6805 SLCT_CheckedLiteral 6806 }; 6807 6808 } // namespace 6809 6810 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6811 BinaryOperatorKind BinOpKind, 6812 bool AddendIsRight) { 6813 unsigned BitWidth = Offset.getBitWidth(); 6814 unsigned AddendBitWidth = Addend.getBitWidth(); 6815 // There might be negative interim results. 6816 if (Addend.isUnsigned()) { 6817 Addend = Addend.zext(++AddendBitWidth); 6818 Addend.setIsSigned(true); 6819 } 6820 // Adjust the bit width of the APSInts. 6821 if (AddendBitWidth > BitWidth) { 6822 Offset = Offset.sext(AddendBitWidth); 6823 BitWidth = AddendBitWidth; 6824 } else if (BitWidth > AddendBitWidth) { 6825 Addend = Addend.sext(BitWidth); 6826 } 6827 6828 bool Ov = false; 6829 llvm::APSInt ResOffset = Offset; 6830 if (BinOpKind == BO_Add) 6831 ResOffset = Offset.sadd_ov(Addend, Ov); 6832 else { 6833 assert(AddendIsRight && BinOpKind == BO_Sub && 6834 "operator must be add or sub with addend on the right"); 6835 ResOffset = Offset.ssub_ov(Addend, Ov); 6836 } 6837 6838 // We add an offset to a pointer here so we should support an offset as big as 6839 // possible. 6840 if (Ov) { 6841 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6842 "index (intermediate) result too big"); 6843 Offset = Offset.sext(2 * BitWidth); 6844 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6845 return; 6846 } 6847 6848 Offset = ResOffset; 6849 } 6850 6851 namespace { 6852 6853 // This is a wrapper class around StringLiteral to support offsetted string 6854 // literals as format strings. It takes the offset into account when returning 6855 // the string and its length or the source locations to display notes correctly. 6856 class FormatStringLiteral { 6857 const StringLiteral *FExpr; 6858 int64_t Offset; 6859 6860 public: 6861 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6862 : FExpr(fexpr), Offset(Offset) {} 6863 6864 StringRef getString() const { 6865 return FExpr->getString().drop_front(Offset); 6866 } 6867 6868 unsigned getByteLength() const { 6869 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6870 } 6871 6872 unsigned getLength() const { return FExpr->getLength() - Offset; } 6873 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6874 6875 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6876 6877 QualType getType() const { return FExpr->getType(); } 6878 6879 bool isAscii() const { return FExpr->isAscii(); } 6880 bool isWide() const { return FExpr->isWide(); } 6881 bool isUTF8() const { return FExpr->isUTF8(); } 6882 bool isUTF16() const { return FExpr->isUTF16(); } 6883 bool isUTF32() const { return FExpr->isUTF32(); } 6884 bool isPascal() const { return FExpr->isPascal(); } 6885 6886 SourceLocation getLocationOfByte( 6887 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6888 const TargetInfo &Target, unsigned *StartToken = nullptr, 6889 unsigned *StartTokenByteOffset = nullptr) const { 6890 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6891 StartToken, StartTokenByteOffset); 6892 } 6893 6894 SourceLocation getBeginLoc() const LLVM_READONLY { 6895 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6896 } 6897 6898 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6899 }; 6900 6901 } // namespace 6902 6903 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6904 const Expr *OrigFormatExpr, 6905 ArrayRef<const Expr *> Args, 6906 bool HasVAListArg, unsigned format_idx, 6907 unsigned firstDataArg, 6908 Sema::FormatStringType Type, 6909 bool inFunctionCall, 6910 Sema::VariadicCallType CallType, 6911 llvm::SmallBitVector &CheckedVarArgs, 6912 UncoveredArgHandler &UncoveredArg, 6913 bool IgnoreStringsWithoutSpecifiers); 6914 6915 // Determine if an expression is a string literal or constant string. 6916 // If this function returns false on the arguments to a function expecting a 6917 // format string, we will usually need to emit a warning. 6918 // True string literals are then checked by CheckFormatString. 6919 static StringLiteralCheckType 6920 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6921 bool HasVAListArg, unsigned format_idx, 6922 unsigned firstDataArg, Sema::FormatStringType Type, 6923 Sema::VariadicCallType CallType, bool InFunctionCall, 6924 llvm::SmallBitVector &CheckedVarArgs, 6925 UncoveredArgHandler &UncoveredArg, 6926 llvm::APSInt Offset, 6927 bool IgnoreStringsWithoutSpecifiers = false) { 6928 if (S.isConstantEvaluated()) 6929 return SLCT_NotALiteral; 6930 tryAgain: 6931 assert(Offset.isSigned() && "invalid offset"); 6932 6933 if (E->isTypeDependent() || E->isValueDependent()) 6934 return SLCT_NotALiteral; 6935 6936 E = E->IgnoreParenCasts(); 6937 6938 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6939 // Technically -Wformat-nonliteral does not warn about this case. 6940 // The behavior of printf and friends in this case is implementation 6941 // dependent. Ideally if the format string cannot be null then 6942 // it should have a 'nonnull' attribute in the function prototype. 6943 return SLCT_UncheckedLiteral; 6944 6945 switch (E->getStmtClass()) { 6946 case Stmt::BinaryConditionalOperatorClass: 6947 case Stmt::ConditionalOperatorClass: { 6948 // The expression is a literal if both sub-expressions were, and it was 6949 // completely checked only if both sub-expressions were checked. 6950 const AbstractConditionalOperator *C = 6951 cast<AbstractConditionalOperator>(E); 6952 6953 // Determine whether it is necessary to check both sub-expressions, for 6954 // example, because the condition expression is a constant that can be 6955 // evaluated at compile time. 6956 bool CheckLeft = true, CheckRight = true; 6957 6958 bool Cond; 6959 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6960 S.isConstantEvaluated())) { 6961 if (Cond) 6962 CheckRight = false; 6963 else 6964 CheckLeft = false; 6965 } 6966 6967 // We need to maintain the offsets for the right and the left hand side 6968 // separately to check if every possible indexed expression is a valid 6969 // string literal. They might have different offsets for different string 6970 // literals in the end. 6971 StringLiteralCheckType Left; 6972 if (!CheckLeft) 6973 Left = SLCT_UncheckedLiteral; 6974 else { 6975 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6976 HasVAListArg, format_idx, firstDataArg, 6977 Type, CallType, InFunctionCall, 6978 CheckedVarArgs, UncoveredArg, Offset, 6979 IgnoreStringsWithoutSpecifiers); 6980 if (Left == SLCT_NotALiteral || !CheckRight) { 6981 return Left; 6982 } 6983 } 6984 6985 StringLiteralCheckType Right = checkFormatStringExpr( 6986 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6987 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6988 IgnoreStringsWithoutSpecifiers); 6989 6990 return (CheckLeft && Left < Right) ? Left : Right; 6991 } 6992 6993 case Stmt::ImplicitCastExprClass: 6994 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6995 goto tryAgain; 6996 6997 case Stmt::OpaqueValueExprClass: 6998 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6999 E = src; 7000 goto tryAgain; 7001 } 7002 return SLCT_NotALiteral; 7003 7004 case Stmt::PredefinedExprClass: 7005 // While __func__, etc., are technically not string literals, they 7006 // cannot contain format specifiers and thus are not a security 7007 // liability. 7008 return SLCT_UncheckedLiteral; 7009 7010 case Stmt::DeclRefExprClass: { 7011 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7012 7013 // As an exception, do not flag errors for variables binding to 7014 // const string literals. 7015 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7016 bool isConstant = false; 7017 QualType T = DR->getType(); 7018 7019 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7020 isConstant = AT->getElementType().isConstant(S.Context); 7021 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7022 isConstant = T.isConstant(S.Context) && 7023 PT->getPointeeType().isConstant(S.Context); 7024 } else if (T->isObjCObjectPointerType()) { 7025 // In ObjC, there is usually no "const ObjectPointer" type, 7026 // so don't check if the pointee type is constant. 7027 isConstant = T.isConstant(S.Context); 7028 } 7029 7030 if (isConstant) { 7031 if (const Expr *Init = VD->getAnyInitializer()) { 7032 // Look through initializers like const char c[] = { "foo" } 7033 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7034 if (InitList->isStringLiteralInit()) 7035 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7036 } 7037 return checkFormatStringExpr(S, Init, Args, 7038 HasVAListArg, format_idx, 7039 firstDataArg, Type, CallType, 7040 /*InFunctionCall*/ false, CheckedVarArgs, 7041 UncoveredArg, Offset); 7042 } 7043 } 7044 7045 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7046 // special check to see if the format string is a function parameter 7047 // of the function calling the printf function. If the function 7048 // has an attribute indicating it is a printf-like function, then we 7049 // should suppress warnings concerning non-literals being used in a call 7050 // to a vprintf function. For example: 7051 // 7052 // void 7053 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7054 // va_list ap; 7055 // va_start(ap, fmt); 7056 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7057 // ... 7058 // } 7059 if (HasVAListArg) { 7060 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7061 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7062 int PVIndex = PV->getFunctionScopeIndex() + 1; 7063 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7064 // adjust for implicit parameter 7065 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7066 if (MD->isInstance()) 7067 ++PVIndex; 7068 // We also check if the formats are compatible. 7069 // We can't pass a 'scanf' string to a 'printf' function. 7070 if (PVIndex == PVFormat->getFormatIdx() && 7071 Type == S.GetFormatStringType(PVFormat)) 7072 return SLCT_UncheckedLiteral; 7073 } 7074 } 7075 } 7076 } 7077 } 7078 7079 return SLCT_NotALiteral; 7080 } 7081 7082 case Stmt::CallExprClass: 7083 case Stmt::CXXMemberCallExprClass: { 7084 const CallExpr *CE = cast<CallExpr>(E); 7085 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7086 bool IsFirst = true; 7087 StringLiteralCheckType CommonResult; 7088 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7089 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7090 StringLiteralCheckType Result = checkFormatStringExpr( 7091 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7092 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7093 IgnoreStringsWithoutSpecifiers); 7094 if (IsFirst) { 7095 CommonResult = Result; 7096 IsFirst = false; 7097 } 7098 } 7099 if (!IsFirst) 7100 return CommonResult; 7101 7102 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7103 unsigned BuiltinID = FD->getBuiltinID(); 7104 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7105 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7106 const Expr *Arg = CE->getArg(0); 7107 return checkFormatStringExpr(S, Arg, Args, 7108 HasVAListArg, format_idx, 7109 firstDataArg, Type, CallType, 7110 InFunctionCall, CheckedVarArgs, 7111 UncoveredArg, Offset, 7112 IgnoreStringsWithoutSpecifiers); 7113 } 7114 } 7115 } 7116 7117 return SLCT_NotALiteral; 7118 } 7119 case Stmt::ObjCMessageExprClass: { 7120 const auto *ME = cast<ObjCMessageExpr>(E); 7121 if (const auto *MD = ME->getMethodDecl()) { 7122 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7123 // As a special case heuristic, if we're using the method -[NSBundle 7124 // localizedStringForKey:value:table:], ignore any key strings that lack 7125 // format specifiers. The idea is that if the key doesn't have any 7126 // format specifiers then its probably just a key to map to the 7127 // localized strings. If it does have format specifiers though, then its 7128 // likely that the text of the key is the format string in the 7129 // programmer's language, and should be checked. 7130 const ObjCInterfaceDecl *IFace; 7131 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7132 IFace->getIdentifier()->isStr("NSBundle") && 7133 MD->getSelector().isKeywordSelector( 7134 {"localizedStringForKey", "value", "table"})) { 7135 IgnoreStringsWithoutSpecifiers = true; 7136 } 7137 7138 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7139 return checkFormatStringExpr( 7140 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7141 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7142 IgnoreStringsWithoutSpecifiers); 7143 } 7144 } 7145 7146 return SLCT_NotALiteral; 7147 } 7148 case Stmt::ObjCStringLiteralClass: 7149 case Stmt::StringLiteralClass: { 7150 const StringLiteral *StrE = nullptr; 7151 7152 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7153 StrE = ObjCFExpr->getString(); 7154 else 7155 StrE = cast<StringLiteral>(E); 7156 7157 if (StrE) { 7158 if (Offset.isNegative() || Offset > StrE->getLength()) { 7159 // TODO: It would be better to have an explicit warning for out of 7160 // bounds literals. 7161 return SLCT_NotALiteral; 7162 } 7163 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7164 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7165 firstDataArg, Type, InFunctionCall, CallType, 7166 CheckedVarArgs, UncoveredArg, 7167 IgnoreStringsWithoutSpecifiers); 7168 return SLCT_CheckedLiteral; 7169 } 7170 7171 return SLCT_NotALiteral; 7172 } 7173 case Stmt::BinaryOperatorClass: { 7174 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7175 7176 // A string literal + an int offset is still a string literal. 7177 if (BinOp->isAdditiveOp()) { 7178 Expr::EvalResult LResult, RResult; 7179 7180 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7181 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7182 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7183 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7184 7185 if (LIsInt != RIsInt) { 7186 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7187 7188 if (LIsInt) { 7189 if (BinOpKind == BO_Add) { 7190 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7191 E = BinOp->getRHS(); 7192 goto tryAgain; 7193 } 7194 } else { 7195 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7196 E = BinOp->getLHS(); 7197 goto tryAgain; 7198 } 7199 } 7200 } 7201 7202 return SLCT_NotALiteral; 7203 } 7204 case Stmt::UnaryOperatorClass: { 7205 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7206 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7207 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7208 Expr::EvalResult IndexResult; 7209 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7210 Expr::SE_NoSideEffects, 7211 S.isConstantEvaluated())) { 7212 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7213 /*RHS is int*/ true); 7214 E = ASE->getBase(); 7215 goto tryAgain; 7216 } 7217 } 7218 7219 return SLCT_NotALiteral; 7220 } 7221 7222 default: 7223 return SLCT_NotALiteral; 7224 } 7225 } 7226 7227 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7228 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7229 .Case("scanf", FST_Scanf) 7230 .Cases("printf", "printf0", FST_Printf) 7231 .Cases("NSString", "CFString", FST_NSString) 7232 .Case("strftime", FST_Strftime) 7233 .Case("strfmon", FST_Strfmon) 7234 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7235 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7236 .Case("os_trace", FST_OSLog) 7237 .Case("os_log", FST_OSLog) 7238 .Default(FST_Unknown); 7239 } 7240 7241 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7242 /// functions) for correct use of format strings. 7243 /// Returns true if a format string has been fully checked. 7244 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7245 ArrayRef<const Expr *> Args, 7246 bool IsCXXMember, 7247 VariadicCallType CallType, 7248 SourceLocation Loc, SourceRange Range, 7249 llvm::SmallBitVector &CheckedVarArgs) { 7250 FormatStringInfo FSI; 7251 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7252 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7253 FSI.FirstDataArg, GetFormatStringType(Format), 7254 CallType, Loc, Range, CheckedVarArgs); 7255 return false; 7256 } 7257 7258 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7259 bool HasVAListArg, unsigned format_idx, 7260 unsigned firstDataArg, FormatStringType Type, 7261 VariadicCallType CallType, 7262 SourceLocation Loc, SourceRange Range, 7263 llvm::SmallBitVector &CheckedVarArgs) { 7264 // CHECK: printf/scanf-like function is called with no format string. 7265 if (format_idx >= Args.size()) { 7266 Diag(Loc, diag::warn_missing_format_string) << Range; 7267 return false; 7268 } 7269 7270 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7271 7272 // CHECK: format string is not a string literal. 7273 // 7274 // Dynamically generated format strings are difficult to 7275 // automatically vet at compile time. Requiring that format strings 7276 // are string literals: (1) permits the checking of format strings by 7277 // the compiler and thereby (2) can practically remove the source of 7278 // many format string exploits. 7279 7280 // Format string can be either ObjC string (e.g. @"%d") or 7281 // C string (e.g. "%d") 7282 // ObjC string uses the same format specifiers as C string, so we can use 7283 // the same format string checking logic for both ObjC and C strings. 7284 UncoveredArgHandler UncoveredArg; 7285 StringLiteralCheckType CT = 7286 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7287 format_idx, firstDataArg, Type, CallType, 7288 /*IsFunctionCall*/ true, CheckedVarArgs, 7289 UncoveredArg, 7290 /*no string offset*/ llvm::APSInt(64, false) = 0); 7291 7292 // Generate a diagnostic where an uncovered argument is detected. 7293 if (UncoveredArg.hasUncoveredArg()) { 7294 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7295 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7296 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7297 } 7298 7299 if (CT != SLCT_NotALiteral) 7300 // Literal format string found, check done! 7301 return CT == SLCT_CheckedLiteral; 7302 7303 // Strftime is particular as it always uses a single 'time' argument, 7304 // so it is safe to pass a non-literal string. 7305 if (Type == FST_Strftime) 7306 return false; 7307 7308 // Do not emit diag when the string param is a macro expansion and the 7309 // format is either NSString or CFString. This is a hack to prevent 7310 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7311 // which are usually used in place of NS and CF string literals. 7312 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7313 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7314 return false; 7315 7316 // If there are no arguments specified, warn with -Wformat-security, otherwise 7317 // warn only with -Wformat-nonliteral. 7318 if (Args.size() == firstDataArg) { 7319 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7320 << OrigFormatExpr->getSourceRange(); 7321 switch (Type) { 7322 default: 7323 break; 7324 case FST_Kprintf: 7325 case FST_FreeBSDKPrintf: 7326 case FST_Printf: 7327 Diag(FormatLoc, diag::note_format_security_fixit) 7328 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7329 break; 7330 case FST_NSString: 7331 Diag(FormatLoc, diag::note_format_security_fixit) 7332 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7333 break; 7334 } 7335 } else { 7336 Diag(FormatLoc, diag::warn_format_nonliteral) 7337 << OrigFormatExpr->getSourceRange(); 7338 } 7339 return false; 7340 } 7341 7342 namespace { 7343 7344 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7345 protected: 7346 Sema &S; 7347 const FormatStringLiteral *FExpr; 7348 const Expr *OrigFormatExpr; 7349 const Sema::FormatStringType FSType; 7350 const unsigned FirstDataArg; 7351 const unsigned NumDataArgs; 7352 const char *Beg; // Start of format string. 7353 const bool HasVAListArg; 7354 ArrayRef<const Expr *> Args; 7355 unsigned FormatIdx; 7356 llvm::SmallBitVector CoveredArgs; 7357 bool usesPositionalArgs = false; 7358 bool atFirstArg = true; 7359 bool inFunctionCall; 7360 Sema::VariadicCallType CallType; 7361 llvm::SmallBitVector &CheckedVarArgs; 7362 UncoveredArgHandler &UncoveredArg; 7363 7364 public: 7365 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7366 const Expr *origFormatExpr, 7367 const Sema::FormatStringType type, unsigned firstDataArg, 7368 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7369 ArrayRef<const Expr *> Args, unsigned formatIdx, 7370 bool inFunctionCall, Sema::VariadicCallType callType, 7371 llvm::SmallBitVector &CheckedVarArgs, 7372 UncoveredArgHandler &UncoveredArg) 7373 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7374 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7375 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7376 inFunctionCall(inFunctionCall), CallType(callType), 7377 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7378 CoveredArgs.resize(numDataArgs); 7379 CoveredArgs.reset(); 7380 } 7381 7382 void DoneProcessing(); 7383 7384 void HandleIncompleteSpecifier(const char *startSpecifier, 7385 unsigned specifierLen) override; 7386 7387 void HandleInvalidLengthModifier( 7388 const analyze_format_string::FormatSpecifier &FS, 7389 const analyze_format_string::ConversionSpecifier &CS, 7390 const char *startSpecifier, unsigned specifierLen, 7391 unsigned DiagID); 7392 7393 void HandleNonStandardLengthModifier( 7394 const analyze_format_string::FormatSpecifier &FS, 7395 const char *startSpecifier, unsigned specifierLen); 7396 7397 void HandleNonStandardConversionSpecifier( 7398 const analyze_format_string::ConversionSpecifier &CS, 7399 const char *startSpecifier, unsigned specifierLen); 7400 7401 void HandlePosition(const char *startPos, unsigned posLen) override; 7402 7403 void HandleInvalidPosition(const char *startSpecifier, 7404 unsigned specifierLen, 7405 analyze_format_string::PositionContext p) override; 7406 7407 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7408 7409 void HandleNullChar(const char *nullCharacter) override; 7410 7411 template <typename Range> 7412 static void 7413 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7414 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7415 bool IsStringLocation, Range StringRange, 7416 ArrayRef<FixItHint> Fixit = None); 7417 7418 protected: 7419 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7420 const char *startSpec, 7421 unsigned specifierLen, 7422 const char *csStart, unsigned csLen); 7423 7424 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7425 const char *startSpec, 7426 unsigned specifierLen); 7427 7428 SourceRange getFormatStringRange(); 7429 CharSourceRange getSpecifierRange(const char *startSpecifier, 7430 unsigned specifierLen); 7431 SourceLocation getLocationOfByte(const char *x); 7432 7433 const Expr *getDataArg(unsigned i) const; 7434 7435 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7436 const analyze_format_string::ConversionSpecifier &CS, 7437 const char *startSpecifier, unsigned specifierLen, 7438 unsigned argIndex); 7439 7440 template <typename Range> 7441 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7442 bool IsStringLocation, Range StringRange, 7443 ArrayRef<FixItHint> Fixit = None); 7444 }; 7445 7446 } // namespace 7447 7448 SourceRange CheckFormatHandler::getFormatStringRange() { 7449 return OrigFormatExpr->getSourceRange(); 7450 } 7451 7452 CharSourceRange CheckFormatHandler:: 7453 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7454 SourceLocation Start = getLocationOfByte(startSpecifier); 7455 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7456 7457 // Advance the end SourceLocation by one due to half-open ranges. 7458 End = End.getLocWithOffset(1); 7459 7460 return CharSourceRange::getCharRange(Start, End); 7461 } 7462 7463 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7464 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7465 S.getLangOpts(), S.Context.getTargetInfo()); 7466 } 7467 7468 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7469 unsigned specifierLen){ 7470 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7471 getLocationOfByte(startSpecifier), 7472 /*IsStringLocation*/true, 7473 getSpecifierRange(startSpecifier, specifierLen)); 7474 } 7475 7476 void CheckFormatHandler::HandleInvalidLengthModifier( 7477 const analyze_format_string::FormatSpecifier &FS, 7478 const analyze_format_string::ConversionSpecifier &CS, 7479 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7480 using namespace analyze_format_string; 7481 7482 const LengthModifier &LM = FS.getLengthModifier(); 7483 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7484 7485 // See if we know how to fix this length modifier. 7486 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7487 if (FixedLM) { 7488 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7489 getLocationOfByte(LM.getStart()), 7490 /*IsStringLocation*/true, 7491 getSpecifierRange(startSpecifier, specifierLen)); 7492 7493 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7494 << FixedLM->toString() 7495 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7496 7497 } else { 7498 FixItHint Hint; 7499 if (DiagID == diag::warn_format_nonsensical_length) 7500 Hint = FixItHint::CreateRemoval(LMRange); 7501 7502 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7503 getLocationOfByte(LM.getStart()), 7504 /*IsStringLocation*/true, 7505 getSpecifierRange(startSpecifier, specifierLen), 7506 Hint); 7507 } 7508 } 7509 7510 void CheckFormatHandler::HandleNonStandardLengthModifier( 7511 const analyze_format_string::FormatSpecifier &FS, 7512 const char *startSpecifier, unsigned specifierLen) { 7513 using namespace analyze_format_string; 7514 7515 const LengthModifier &LM = FS.getLengthModifier(); 7516 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7517 7518 // See if we know how to fix this length modifier. 7519 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7520 if (FixedLM) { 7521 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7522 << LM.toString() << 0, 7523 getLocationOfByte(LM.getStart()), 7524 /*IsStringLocation*/true, 7525 getSpecifierRange(startSpecifier, specifierLen)); 7526 7527 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7528 << FixedLM->toString() 7529 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7530 7531 } else { 7532 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7533 << LM.toString() << 0, 7534 getLocationOfByte(LM.getStart()), 7535 /*IsStringLocation*/true, 7536 getSpecifierRange(startSpecifier, specifierLen)); 7537 } 7538 } 7539 7540 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7541 const analyze_format_string::ConversionSpecifier &CS, 7542 const char *startSpecifier, unsigned specifierLen) { 7543 using namespace analyze_format_string; 7544 7545 // See if we know how to fix this conversion specifier. 7546 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7547 if (FixedCS) { 7548 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7549 << CS.toString() << /*conversion specifier*/1, 7550 getLocationOfByte(CS.getStart()), 7551 /*IsStringLocation*/true, 7552 getSpecifierRange(startSpecifier, specifierLen)); 7553 7554 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7555 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7556 << FixedCS->toString() 7557 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7558 } else { 7559 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7560 << CS.toString() << /*conversion specifier*/1, 7561 getLocationOfByte(CS.getStart()), 7562 /*IsStringLocation*/true, 7563 getSpecifierRange(startSpecifier, specifierLen)); 7564 } 7565 } 7566 7567 void CheckFormatHandler::HandlePosition(const char *startPos, 7568 unsigned posLen) { 7569 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7570 getLocationOfByte(startPos), 7571 /*IsStringLocation*/true, 7572 getSpecifierRange(startPos, posLen)); 7573 } 7574 7575 void 7576 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7577 analyze_format_string::PositionContext p) { 7578 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7579 << (unsigned) p, 7580 getLocationOfByte(startPos), /*IsStringLocation*/true, 7581 getSpecifierRange(startPos, posLen)); 7582 } 7583 7584 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7585 unsigned posLen) { 7586 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7587 getLocationOfByte(startPos), 7588 /*IsStringLocation*/true, 7589 getSpecifierRange(startPos, posLen)); 7590 } 7591 7592 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7593 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7594 // The presence of a null character is likely an error. 7595 EmitFormatDiagnostic( 7596 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7597 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7598 getFormatStringRange()); 7599 } 7600 } 7601 7602 // Note that this may return NULL if there was an error parsing or building 7603 // one of the argument expressions. 7604 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7605 return Args[FirstDataArg + i]; 7606 } 7607 7608 void CheckFormatHandler::DoneProcessing() { 7609 // Does the number of data arguments exceed the number of 7610 // format conversions in the format string? 7611 if (!HasVAListArg) { 7612 // Find any arguments that weren't covered. 7613 CoveredArgs.flip(); 7614 signed notCoveredArg = CoveredArgs.find_first(); 7615 if (notCoveredArg >= 0) { 7616 assert((unsigned)notCoveredArg < NumDataArgs); 7617 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7618 } else { 7619 UncoveredArg.setAllCovered(); 7620 } 7621 } 7622 } 7623 7624 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7625 const Expr *ArgExpr) { 7626 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7627 "Invalid state"); 7628 7629 if (!ArgExpr) 7630 return; 7631 7632 SourceLocation Loc = ArgExpr->getBeginLoc(); 7633 7634 if (S.getSourceManager().isInSystemMacro(Loc)) 7635 return; 7636 7637 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7638 for (auto E : DiagnosticExprs) 7639 PDiag << E->getSourceRange(); 7640 7641 CheckFormatHandler::EmitFormatDiagnostic( 7642 S, IsFunctionCall, DiagnosticExprs[0], 7643 PDiag, Loc, /*IsStringLocation*/false, 7644 DiagnosticExprs[0]->getSourceRange()); 7645 } 7646 7647 bool 7648 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7649 SourceLocation Loc, 7650 const char *startSpec, 7651 unsigned specifierLen, 7652 const char *csStart, 7653 unsigned csLen) { 7654 bool keepGoing = true; 7655 if (argIndex < NumDataArgs) { 7656 // Consider the argument coverered, even though the specifier doesn't 7657 // make sense. 7658 CoveredArgs.set(argIndex); 7659 } 7660 else { 7661 // If argIndex exceeds the number of data arguments we 7662 // don't issue a warning because that is just a cascade of warnings (and 7663 // they may have intended '%%' anyway). We don't want to continue processing 7664 // the format string after this point, however, as we will like just get 7665 // gibberish when trying to match arguments. 7666 keepGoing = false; 7667 } 7668 7669 StringRef Specifier(csStart, csLen); 7670 7671 // If the specifier in non-printable, it could be the first byte of a UTF-8 7672 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7673 // hex value. 7674 std::string CodePointStr; 7675 if (!llvm::sys::locale::isPrint(*csStart)) { 7676 llvm::UTF32 CodePoint; 7677 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7678 const llvm::UTF8 *E = 7679 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7680 llvm::ConversionResult Result = 7681 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7682 7683 if (Result != llvm::conversionOK) { 7684 unsigned char FirstChar = *csStart; 7685 CodePoint = (llvm::UTF32)FirstChar; 7686 } 7687 7688 llvm::raw_string_ostream OS(CodePointStr); 7689 if (CodePoint < 256) 7690 OS << "\\x" << llvm::format("%02x", CodePoint); 7691 else if (CodePoint <= 0xFFFF) 7692 OS << "\\u" << llvm::format("%04x", CodePoint); 7693 else 7694 OS << "\\U" << llvm::format("%08x", CodePoint); 7695 OS.flush(); 7696 Specifier = CodePointStr; 7697 } 7698 7699 EmitFormatDiagnostic( 7700 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7701 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7702 7703 return keepGoing; 7704 } 7705 7706 void 7707 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7708 const char *startSpec, 7709 unsigned specifierLen) { 7710 EmitFormatDiagnostic( 7711 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7712 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7713 } 7714 7715 bool 7716 CheckFormatHandler::CheckNumArgs( 7717 const analyze_format_string::FormatSpecifier &FS, 7718 const analyze_format_string::ConversionSpecifier &CS, 7719 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7720 7721 if (argIndex >= NumDataArgs) { 7722 PartialDiagnostic PDiag = FS.usesPositionalArg() 7723 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7724 << (argIndex+1) << NumDataArgs) 7725 : S.PDiag(diag::warn_printf_insufficient_data_args); 7726 EmitFormatDiagnostic( 7727 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7728 getSpecifierRange(startSpecifier, specifierLen)); 7729 7730 // Since more arguments than conversion tokens are given, by extension 7731 // all arguments are covered, so mark this as so. 7732 UncoveredArg.setAllCovered(); 7733 return false; 7734 } 7735 return true; 7736 } 7737 7738 template<typename Range> 7739 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7740 SourceLocation Loc, 7741 bool IsStringLocation, 7742 Range StringRange, 7743 ArrayRef<FixItHint> FixIt) { 7744 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7745 Loc, IsStringLocation, StringRange, FixIt); 7746 } 7747 7748 /// If the format string is not within the function call, emit a note 7749 /// so that the function call and string are in diagnostic messages. 7750 /// 7751 /// \param InFunctionCall if true, the format string is within the function 7752 /// call and only one diagnostic message will be produced. Otherwise, an 7753 /// extra note will be emitted pointing to location of the format string. 7754 /// 7755 /// \param ArgumentExpr the expression that is passed as the format string 7756 /// argument in the function call. Used for getting locations when two 7757 /// diagnostics are emitted. 7758 /// 7759 /// \param PDiag the callee should already have provided any strings for the 7760 /// diagnostic message. This function only adds locations and fixits 7761 /// to diagnostics. 7762 /// 7763 /// \param Loc primary location for diagnostic. If two diagnostics are 7764 /// required, one will be at Loc and a new SourceLocation will be created for 7765 /// the other one. 7766 /// 7767 /// \param IsStringLocation if true, Loc points to the format string should be 7768 /// used for the note. Otherwise, Loc points to the argument list and will 7769 /// be used with PDiag. 7770 /// 7771 /// \param StringRange some or all of the string to highlight. This is 7772 /// templated so it can accept either a CharSourceRange or a SourceRange. 7773 /// 7774 /// \param FixIt optional fix it hint for the format string. 7775 template <typename Range> 7776 void CheckFormatHandler::EmitFormatDiagnostic( 7777 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7778 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7779 Range StringRange, ArrayRef<FixItHint> FixIt) { 7780 if (InFunctionCall) { 7781 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7782 D << StringRange; 7783 D << FixIt; 7784 } else { 7785 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7786 << ArgumentExpr->getSourceRange(); 7787 7788 const Sema::SemaDiagnosticBuilder &Note = 7789 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7790 diag::note_format_string_defined); 7791 7792 Note << StringRange; 7793 Note << FixIt; 7794 } 7795 } 7796 7797 //===--- CHECK: Printf format string checking ------------------------------===// 7798 7799 namespace { 7800 7801 class CheckPrintfHandler : public CheckFormatHandler { 7802 public: 7803 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7804 const Expr *origFormatExpr, 7805 const Sema::FormatStringType type, unsigned firstDataArg, 7806 unsigned numDataArgs, bool isObjC, const char *beg, 7807 bool hasVAListArg, ArrayRef<const Expr *> Args, 7808 unsigned formatIdx, bool inFunctionCall, 7809 Sema::VariadicCallType CallType, 7810 llvm::SmallBitVector &CheckedVarArgs, 7811 UncoveredArgHandler &UncoveredArg) 7812 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7813 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7814 inFunctionCall, CallType, CheckedVarArgs, 7815 UncoveredArg) {} 7816 7817 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7818 7819 /// Returns true if '%@' specifiers are allowed in the format string. 7820 bool allowsObjCArg() const { 7821 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7822 FSType == Sema::FST_OSTrace; 7823 } 7824 7825 bool HandleInvalidPrintfConversionSpecifier( 7826 const analyze_printf::PrintfSpecifier &FS, 7827 const char *startSpecifier, 7828 unsigned specifierLen) override; 7829 7830 void handleInvalidMaskType(StringRef MaskType) override; 7831 7832 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7833 const char *startSpecifier, 7834 unsigned specifierLen) override; 7835 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7836 const char *StartSpecifier, 7837 unsigned SpecifierLen, 7838 const Expr *E); 7839 7840 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7841 const char *startSpecifier, unsigned specifierLen); 7842 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7843 const analyze_printf::OptionalAmount &Amt, 7844 unsigned type, 7845 const char *startSpecifier, unsigned specifierLen); 7846 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7847 const analyze_printf::OptionalFlag &flag, 7848 const char *startSpecifier, unsigned specifierLen); 7849 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7850 const analyze_printf::OptionalFlag &ignoredFlag, 7851 const analyze_printf::OptionalFlag &flag, 7852 const char *startSpecifier, unsigned specifierLen); 7853 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7854 const Expr *E); 7855 7856 void HandleEmptyObjCModifierFlag(const char *startFlag, 7857 unsigned flagLen) override; 7858 7859 void HandleInvalidObjCModifierFlag(const char *startFlag, 7860 unsigned flagLen) override; 7861 7862 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7863 const char *flagsEnd, 7864 const char *conversionPosition) 7865 override; 7866 }; 7867 7868 } // namespace 7869 7870 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7871 const analyze_printf::PrintfSpecifier &FS, 7872 const char *startSpecifier, 7873 unsigned specifierLen) { 7874 const analyze_printf::PrintfConversionSpecifier &CS = 7875 FS.getConversionSpecifier(); 7876 7877 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7878 getLocationOfByte(CS.getStart()), 7879 startSpecifier, specifierLen, 7880 CS.getStart(), CS.getLength()); 7881 } 7882 7883 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7884 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7885 } 7886 7887 bool CheckPrintfHandler::HandleAmount( 7888 const analyze_format_string::OptionalAmount &Amt, 7889 unsigned k, const char *startSpecifier, 7890 unsigned specifierLen) { 7891 if (Amt.hasDataArgument()) { 7892 if (!HasVAListArg) { 7893 unsigned argIndex = Amt.getArgIndex(); 7894 if (argIndex >= NumDataArgs) { 7895 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7896 << k, 7897 getLocationOfByte(Amt.getStart()), 7898 /*IsStringLocation*/true, 7899 getSpecifierRange(startSpecifier, specifierLen)); 7900 // Don't do any more checking. We will just emit 7901 // spurious errors. 7902 return false; 7903 } 7904 7905 // Type check the data argument. It should be an 'int'. 7906 // Although not in conformance with C99, we also allow the argument to be 7907 // an 'unsigned int' as that is a reasonably safe case. GCC also 7908 // doesn't emit a warning for that case. 7909 CoveredArgs.set(argIndex); 7910 const Expr *Arg = getDataArg(argIndex); 7911 if (!Arg) 7912 return false; 7913 7914 QualType T = Arg->getType(); 7915 7916 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7917 assert(AT.isValid()); 7918 7919 if (!AT.matchesType(S.Context, T)) { 7920 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7921 << k << AT.getRepresentativeTypeName(S.Context) 7922 << T << Arg->getSourceRange(), 7923 getLocationOfByte(Amt.getStart()), 7924 /*IsStringLocation*/true, 7925 getSpecifierRange(startSpecifier, specifierLen)); 7926 // Don't do any more checking. We will just emit 7927 // spurious errors. 7928 return false; 7929 } 7930 } 7931 } 7932 return true; 7933 } 7934 7935 void CheckPrintfHandler::HandleInvalidAmount( 7936 const analyze_printf::PrintfSpecifier &FS, 7937 const analyze_printf::OptionalAmount &Amt, 7938 unsigned type, 7939 const char *startSpecifier, 7940 unsigned specifierLen) { 7941 const analyze_printf::PrintfConversionSpecifier &CS = 7942 FS.getConversionSpecifier(); 7943 7944 FixItHint fixit = 7945 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7946 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7947 Amt.getConstantLength())) 7948 : FixItHint(); 7949 7950 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7951 << type << CS.toString(), 7952 getLocationOfByte(Amt.getStart()), 7953 /*IsStringLocation*/true, 7954 getSpecifierRange(startSpecifier, specifierLen), 7955 fixit); 7956 } 7957 7958 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7959 const analyze_printf::OptionalFlag &flag, 7960 const char *startSpecifier, 7961 unsigned specifierLen) { 7962 // Warn about pointless flag with a fixit removal. 7963 const analyze_printf::PrintfConversionSpecifier &CS = 7964 FS.getConversionSpecifier(); 7965 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7966 << flag.toString() << CS.toString(), 7967 getLocationOfByte(flag.getPosition()), 7968 /*IsStringLocation*/true, 7969 getSpecifierRange(startSpecifier, specifierLen), 7970 FixItHint::CreateRemoval( 7971 getSpecifierRange(flag.getPosition(), 1))); 7972 } 7973 7974 void CheckPrintfHandler::HandleIgnoredFlag( 7975 const analyze_printf::PrintfSpecifier &FS, 7976 const analyze_printf::OptionalFlag &ignoredFlag, 7977 const analyze_printf::OptionalFlag &flag, 7978 const char *startSpecifier, 7979 unsigned specifierLen) { 7980 // Warn about ignored flag with a fixit removal. 7981 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7982 << ignoredFlag.toString() << flag.toString(), 7983 getLocationOfByte(ignoredFlag.getPosition()), 7984 /*IsStringLocation*/true, 7985 getSpecifierRange(startSpecifier, specifierLen), 7986 FixItHint::CreateRemoval( 7987 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7988 } 7989 7990 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7991 unsigned flagLen) { 7992 // Warn about an empty flag. 7993 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7994 getLocationOfByte(startFlag), 7995 /*IsStringLocation*/true, 7996 getSpecifierRange(startFlag, flagLen)); 7997 } 7998 7999 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8000 unsigned flagLen) { 8001 // Warn about an invalid flag. 8002 auto Range = getSpecifierRange(startFlag, flagLen); 8003 StringRef flag(startFlag, flagLen); 8004 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8005 getLocationOfByte(startFlag), 8006 /*IsStringLocation*/true, 8007 Range, FixItHint::CreateRemoval(Range)); 8008 } 8009 8010 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8011 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8012 // Warn about using '[...]' without a '@' conversion. 8013 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8014 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8015 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8016 getLocationOfByte(conversionPosition), 8017 /*IsStringLocation*/true, 8018 Range, FixItHint::CreateRemoval(Range)); 8019 } 8020 8021 // Determines if the specified is a C++ class or struct containing 8022 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8023 // "c_str()"). 8024 template<typename MemberKind> 8025 static llvm::SmallPtrSet<MemberKind*, 1> 8026 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8027 const RecordType *RT = Ty->getAs<RecordType>(); 8028 llvm::SmallPtrSet<MemberKind*, 1> Results; 8029 8030 if (!RT) 8031 return Results; 8032 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8033 if (!RD || !RD->getDefinition()) 8034 return Results; 8035 8036 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8037 Sema::LookupMemberName); 8038 R.suppressDiagnostics(); 8039 8040 // We just need to include all members of the right kind turned up by the 8041 // filter, at this point. 8042 if (S.LookupQualifiedName(R, RT->getDecl())) 8043 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8044 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8045 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8046 Results.insert(FK); 8047 } 8048 return Results; 8049 } 8050 8051 /// Check if we could call '.c_str()' on an object. 8052 /// 8053 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8054 /// allow the call, or if it would be ambiguous). 8055 bool Sema::hasCStrMethod(const Expr *E) { 8056 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8057 8058 MethodSet Results = 8059 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8060 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8061 MI != ME; ++MI) 8062 if ((*MI)->getMinRequiredArguments() == 0) 8063 return true; 8064 return false; 8065 } 8066 8067 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8068 // better diagnostic if so. AT is assumed to be valid. 8069 // Returns true when a c_str() conversion method is found. 8070 bool CheckPrintfHandler::checkForCStrMembers( 8071 const analyze_printf::ArgType &AT, const Expr *E) { 8072 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8073 8074 MethodSet Results = 8075 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8076 8077 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8078 MI != ME; ++MI) { 8079 const CXXMethodDecl *Method = *MI; 8080 if (Method->getMinRequiredArguments() == 0 && 8081 AT.matchesType(S.Context, Method->getReturnType())) { 8082 // FIXME: Suggest parens if the expression needs them. 8083 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8084 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8085 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8086 return true; 8087 } 8088 } 8089 8090 return false; 8091 } 8092 8093 bool 8094 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8095 &FS, 8096 const char *startSpecifier, 8097 unsigned specifierLen) { 8098 using namespace analyze_format_string; 8099 using namespace analyze_printf; 8100 8101 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8102 8103 if (FS.consumesDataArgument()) { 8104 if (atFirstArg) { 8105 atFirstArg = false; 8106 usesPositionalArgs = FS.usesPositionalArg(); 8107 } 8108 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8109 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8110 startSpecifier, specifierLen); 8111 return false; 8112 } 8113 } 8114 8115 // First check if the field width, precision, and conversion specifier 8116 // have matching data arguments. 8117 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8118 startSpecifier, specifierLen)) { 8119 return false; 8120 } 8121 8122 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8123 startSpecifier, specifierLen)) { 8124 return false; 8125 } 8126 8127 if (!CS.consumesDataArgument()) { 8128 // FIXME: Technically specifying a precision or field width here 8129 // makes no sense. Worth issuing a warning at some point. 8130 return true; 8131 } 8132 8133 // Consume the argument. 8134 unsigned argIndex = FS.getArgIndex(); 8135 if (argIndex < NumDataArgs) { 8136 // The check to see if the argIndex is valid will come later. 8137 // We set the bit here because we may exit early from this 8138 // function if we encounter some other error. 8139 CoveredArgs.set(argIndex); 8140 } 8141 8142 // FreeBSD kernel extensions. 8143 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8144 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8145 // We need at least two arguments. 8146 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8147 return false; 8148 8149 // Claim the second argument. 8150 CoveredArgs.set(argIndex + 1); 8151 8152 // Type check the first argument (int for %b, pointer for %D) 8153 const Expr *Ex = getDataArg(argIndex); 8154 const analyze_printf::ArgType &AT = 8155 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8156 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8157 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8158 EmitFormatDiagnostic( 8159 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8160 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8161 << false << Ex->getSourceRange(), 8162 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8163 getSpecifierRange(startSpecifier, specifierLen)); 8164 8165 // Type check the second argument (char * for both %b and %D) 8166 Ex = getDataArg(argIndex + 1); 8167 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8168 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8169 EmitFormatDiagnostic( 8170 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8171 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8172 << false << Ex->getSourceRange(), 8173 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8174 getSpecifierRange(startSpecifier, specifierLen)); 8175 8176 return true; 8177 } 8178 8179 // Check for using an Objective-C specific conversion specifier 8180 // in a non-ObjC literal. 8181 if (!allowsObjCArg() && CS.isObjCArg()) { 8182 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8183 specifierLen); 8184 } 8185 8186 // %P can only be used with os_log. 8187 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8188 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8189 specifierLen); 8190 } 8191 8192 // %n is not allowed with os_log. 8193 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8194 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8195 getLocationOfByte(CS.getStart()), 8196 /*IsStringLocation*/ false, 8197 getSpecifierRange(startSpecifier, specifierLen)); 8198 8199 return true; 8200 } 8201 8202 // Only scalars are allowed for os_trace. 8203 if (FSType == Sema::FST_OSTrace && 8204 (CS.getKind() == ConversionSpecifier::PArg || 8205 CS.getKind() == ConversionSpecifier::sArg || 8206 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8207 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8208 specifierLen); 8209 } 8210 8211 // Check for use of public/private annotation outside of os_log(). 8212 if (FSType != Sema::FST_OSLog) { 8213 if (FS.isPublic().isSet()) { 8214 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8215 << "public", 8216 getLocationOfByte(FS.isPublic().getPosition()), 8217 /*IsStringLocation*/ false, 8218 getSpecifierRange(startSpecifier, specifierLen)); 8219 } 8220 if (FS.isPrivate().isSet()) { 8221 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8222 << "private", 8223 getLocationOfByte(FS.isPrivate().getPosition()), 8224 /*IsStringLocation*/ false, 8225 getSpecifierRange(startSpecifier, specifierLen)); 8226 } 8227 } 8228 8229 // Check for invalid use of field width 8230 if (!FS.hasValidFieldWidth()) { 8231 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8232 startSpecifier, specifierLen); 8233 } 8234 8235 // Check for invalid use of precision 8236 if (!FS.hasValidPrecision()) { 8237 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8238 startSpecifier, specifierLen); 8239 } 8240 8241 // Precision is mandatory for %P specifier. 8242 if (CS.getKind() == ConversionSpecifier::PArg && 8243 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8244 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8245 getLocationOfByte(startSpecifier), 8246 /*IsStringLocation*/ false, 8247 getSpecifierRange(startSpecifier, specifierLen)); 8248 } 8249 8250 // Check each flag does not conflict with any other component. 8251 if (!FS.hasValidThousandsGroupingPrefix()) 8252 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8253 if (!FS.hasValidLeadingZeros()) 8254 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8255 if (!FS.hasValidPlusPrefix()) 8256 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8257 if (!FS.hasValidSpacePrefix()) 8258 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8259 if (!FS.hasValidAlternativeForm()) 8260 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8261 if (!FS.hasValidLeftJustified()) 8262 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8263 8264 // Check that flags are not ignored by another flag 8265 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8266 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8267 startSpecifier, specifierLen); 8268 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8269 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8270 startSpecifier, specifierLen); 8271 8272 // Check the length modifier is valid with the given conversion specifier. 8273 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8274 S.getLangOpts())) 8275 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8276 diag::warn_format_nonsensical_length); 8277 else if (!FS.hasStandardLengthModifier()) 8278 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8279 else if (!FS.hasStandardLengthConversionCombination()) 8280 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8281 diag::warn_format_non_standard_conversion_spec); 8282 8283 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8284 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8285 8286 // The remaining checks depend on the data arguments. 8287 if (HasVAListArg) 8288 return true; 8289 8290 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8291 return false; 8292 8293 const Expr *Arg = getDataArg(argIndex); 8294 if (!Arg) 8295 return true; 8296 8297 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8298 } 8299 8300 static bool requiresParensToAddCast(const Expr *E) { 8301 // FIXME: We should have a general way to reason about operator 8302 // precedence and whether parens are actually needed here. 8303 // Take care of a few common cases where they aren't. 8304 const Expr *Inside = E->IgnoreImpCasts(); 8305 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8306 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8307 8308 switch (Inside->getStmtClass()) { 8309 case Stmt::ArraySubscriptExprClass: 8310 case Stmt::CallExprClass: 8311 case Stmt::CharacterLiteralClass: 8312 case Stmt::CXXBoolLiteralExprClass: 8313 case Stmt::DeclRefExprClass: 8314 case Stmt::FloatingLiteralClass: 8315 case Stmt::IntegerLiteralClass: 8316 case Stmt::MemberExprClass: 8317 case Stmt::ObjCArrayLiteralClass: 8318 case Stmt::ObjCBoolLiteralExprClass: 8319 case Stmt::ObjCBoxedExprClass: 8320 case Stmt::ObjCDictionaryLiteralClass: 8321 case Stmt::ObjCEncodeExprClass: 8322 case Stmt::ObjCIvarRefExprClass: 8323 case Stmt::ObjCMessageExprClass: 8324 case Stmt::ObjCPropertyRefExprClass: 8325 case Stmt::ObjCStringLiteralClass: 8326 case Stmt::ObjCSubscriptRefExprClass: 8327 case Stmt::ParenExprClass: 8328 case Stmt::StringLiteralClass: 8329 case Stmt::UnaryOperatorClass: 8330 return false; 8331 default: 8332 return true; 8333 } 8334 } 8335 8336 static std::pair<QualType, StringRef> 8337 shouldNotPrintDirectly(const ASTContext &Context, 8338 QualType IntendedTy, 8339 const Expr *E) { 8340 // Use a 'while' to peel off layers of typedefs. 8341 QualType TyTy = IntendedTy; 8342 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8343 StringRef Name = UserTy->getDecl()->getName(); 8344 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8345 .Case("CFIndex", Context.getNSIntegerType()) 8346 .Case("NSInteger", Context.getNSIntegerType()) 8347 .Case("NSUInteger", Context.getNSUIntegerType()) 8348 .Case("SInt32", Context.IntTy) 8349 .Case("UInt32", Context.UnsignedIntTy) 8350 .Default(QualType()); 8351 8352 if (!CastTy.isNull()) 8353 return std::make_pair(CastTy, Name); 8354 8355 TyTy = UserTy->desugar(); 8356 } 8357 8358 // Strip parens if necessary. 8359 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8360 return shouldNotPrintDirectly(Context, 8361 PE->getSubExpr()->getType(), 8362 PE->getSubExpr()); 8363 8364 // If this is a conditional expression, then its result type is constructed 8365 // via usual arithmetic conversions and thus there might be no necessary 8366 // typedef sugar there. Recurse to operands to check for NSInteger & 8367 // Co. usage condition. 8368 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8369 QualType TrueTy, FalseTy; 8370 StringRef TrueName, FalseName; 8371 8372 std::tie(TrueTy, TrueName) = 8373 shouldNotPrintDirectly(Context, 8374 CO->getTrueExpr()->getType(), 8375 CO->getTrueExpr()); 8376 std::tie(FalseTy, FalseName) = 8377 shouldNotPrintDirectly(Context, 8378 CO->getFalseExpr()->getType(), 8379 CO->getFalseExpr()); 8380 8381 if (TrueTy == FalseTy) 8382 return std::make_pair(TrueTy, TrueName); 8383 else if (TrueTy.isNull()) 8384 return std::make_pair(FalseTy, FalseName); 8385 else if (FalseTy.isNull()) 8386 return std::make_pair(TrueTy, TrueName); 8387 } 8388 8389 return std::make_pair(QualType(), StringRef()); 8390 } 8391 8392 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8393 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8394 /// type do not count. 8395 static bool 8396 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8397 QualType From = ICE->getSubExpr()->getType(); 8398 QualType To = ICE->getType(); 8399 // It's an integer promotion if the destination type is the promoted 8400 // source type. 8401 if (ICE->getCastKind() == CK_IntegralCast && 8402 From->isPromotableIntegerType() && 8403 S.Context.getPromotedIntegerType(From) == To) 8404 return true; 8405 // Look through vector types, since we do default argument promotion for 8406 // those in OpenCL. 8407 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8408 From = VecTy->getElementType(); 8409 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8410 To = VecTy->getElementType(); 8411 // It's a floating promotion if the source type is a lower rank. 8412 return ICE->getCastKind() == CK_FloatingCast && 8413 S.Context.getFloatingTypeOrder(From, To) < 0; 8414 } 8415 8416 bool 8417 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8418 const char *StartSpecifier, 8419 unsigned SpecifierLen, 8420 const Expr *E) { 8421 using namespace analyze_format_string; 8422 using namespace analyze_printf; 8423 8424 // Now type check the data expression that matches the 8425 // format specifier. 8426 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8427 if (!AT.isValid()) 8428 return true; 8429 8430 QualType ExprTy = E->getType(); 8431 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8432 ExprTy = TET->getUnderlyingExpr()->getType(); 8433 } 8434 8435 // Diagnose attempts to print a boolean value as a character. Unlike other 8436 // -Wformat diagnostics, this is fine from a type perspective, but it still 8437 // doesn't make sense. 8438 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8439 E->isKnownToHaveBooleanValue()) { 8440 const CharSourceRange &CSR = 8441 getSpecifierRange(StartSpecifier, SpecifierLen); 8442 SmallString<4> FSString; 8443 llvm::raw_svector_ostream os(FSString); 8444 FS.toString(os); 8445 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8446 << FSString, 8447 E->getExprLoc(), false, CSR); 8448 return true; 8449 } 8450 8451 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8452 if (Match == analyze_printf::ArgType::Match) 8453 return true; 8454 8455 // Look through argument promotions for our error message's reported type. 8456 // This includes the integral and floating promotions, but excludes array 8457 // and function pointer decay (seeing that an argument intended to be a 8458 // string has type 'char [6]' is probably more confusing than 'char *') and 8459 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8460 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8461 if (isArithmeticArgumentPromotion(S, ICE)) { 8462 E = ICE->getSubExpr(); 8463 ExprTy = E->getType(); 8464 8465 // Check if we didn't match because of an implicit cast from a 'char' 8466 // or 'short' to an 'int'. This is done because printf is a varargs 8467 // function. 8468 if (ICE->getType() == S.Context.IntTy || 8469 ICE->getType() == S.Context.UnsignedIntTy) { 8470 // All further checking is done on the subexpression 8471 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8472 AT.matchesType(S.Context, ExprTy); 8473 if (ImplicitMatch == analyze_printf::ArgType::Match) 8474 return true; 8475 if (ImplicitMatch == ArgType::NoMatchPedantic || 8476 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8477 Match = ImplicitMatch; 8478 } 8479 } 8480 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8481 // Special case for 'a', which has type 'int' in C. 8482 // Note, however, that we do /not/ want to treat multibyte constants like 8483 // 'MooV' as characters! This form is deprecated but still exists. 8484 if (ExprTy == S.Context.IntTy) 8485 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8486 ExprTy = S.Context.CharTy; 8487 } 8488 8489 // Look through enums to their underlying type. 8490 bool IsEnum = false; 8491 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8492 ExprTy = EnumTy->getDecl()->getIntegerType(); 8493 IsEnum = true; 8494 } 8495 8496 // %C in an Objective-C context prints a unichar, not a wchar_t. 8497 // If the argument is an integer of some kind, believe the %C and suggest 8498 // a cast instead of changing the conversion specifier. 8499 QualType IntendedTy = ExprTy; 8500 if (isObjCContext() && 8501 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8502 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8503 !ExprTy->isCharType()) { 8504 // 'unichar' is defined as a typedef of unsigned short, but we should 8505 // prefer using the typedef if it is visible. 8506 IntendedTy = S.Context.UnsignedShortTy; 8507 8508 // While we are here, check if the value is an IntegerLiteral that happens 8509 // to be within the valid range. 8510 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8511 const llvm::APInt &V = IL->getValue(); 8512 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8513 return true; 8514 } 8515 8516 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8517 Sema::LookupOrdinaryName); 8518 if (S.LookupName(Result, S.getCurScope())) { 8519 NamedDecl *ND = Result.getFoundDecl(); 8520 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8521 if (TD->getUnderlyingType() == IntendedTy) 8522 IntendedTy = S.Context.getTypedefType(TD); 8523 } 8524 } 8525 } 8526 8527 // Special-case some of Darwin's platform-independence types by suggesting 8528 // casts to primitive types that are known to be large enough. 8529 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8530 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8531 QualType CastTy; 8532 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8533 if (!CastTy.isNull()) { 8534 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8535 // (long in ASTContext). Only complain to pedants. 8536 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8537 (AT.isSizeT() || AT.isPtrdiffT()) && 8538 AT.matchesType(S.Context, CastTy)) 8539 Match = ArgType::NoMatchPedantic; 8540 IntendedTy = CastTy; 8541 ShouldNotPrintDirectly = true; 8542 } 8543 } 8544 8545 // We may be able to offer a FixItHint if it is a supported type. 8546 PrintfSpecifier fixedFS = FS; 8547 bool Success = 8548 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8549 8550 if (Success) { 8551 // Get the fix string from the fixed format specifier 8552 SmallString<16> buf; 8553 llvm::raw_svector_ostream os(buf); 8554 fixedFS.toString(os); 8555 8556 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8557 8558 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8559 unsigned Diag; 8560 switch (Match) { 8561 case ArgType::Match: llvm_unreachable("expected non-matching"); 8562 case ArgType::NoMatchPedantic: 8563 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8564 break; 8565 case ArgType::NoMatchTypeConfusion: 8566 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8567 break; 8568 case ArgType::NoMatch: 8569 Diag = diag::warn_format_conversion_argument_type_mismatch; 8570 break; 8571 } 8572 8573 // In this case, the specifier is wrong and should be changed to match 8574 // the argument. 8575 EmitFormatDiagnostic(S.PDiag(Diag) 8576 << AT.getRepresentativeTypeName(S.Context) 8577 << IntendedTy << IsEnum << E->getSourceRange(), 8578 E->getBeginLoc(), 8579 /*IsStringLocation*/ false, SpecRange, 8580 FixItHint::CreateReplacement(SpecRange, os.str())); 8581 } else { 8582 // The canonical type for formatting this value is different from the 8583 // actual type of the expression. (This occurs, for example, with Darwin's 8584 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8585 // should be printed as 'long' for 64-bit compatibility.) 8586 // Rather than emitting a normal format/argument mismatch, we want to 8587 // add a cast to the recommended type (and correct the format string 8588 // if necessary). 8589 SmallString<16> CastBuf; 8590 llvm::raw_svector_ostream CastFix(CastBuf); 8591 CastFix << "("; 8592 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8593 CastFix << ")"; 8594 8595 SmallVector<FixItHint,4> Hints; 8596 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8597 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8598 8599 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8600 // If there's already a cast present, just replace it. 8601 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8602 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8603 8604 } else if (!requiresParensToAddCast(E)) { 8605 // If the expression has high enough precedence, 8606 // just write the C-style cast. 8607 Hints.push_back( 8608 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8609 } else { 8610 // Otherwise, add parens around the expression as well as the cast. 8611 CastFix << "("; 8612 Hints.push_back( 8613 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8614 8615 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8616 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8617 } 8618 8619 if (ShouldNotPrintDirectly) { 8620 // The expression has a type that should not be printed directly. 8621 // We extract the name from the typedef because we don't want to show 8622 // the underlying type in the diagnostic. 8623 StringRef Name; 8624 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8625 Name = TypedefTy->getDecl()->getName(); 8626 else 8627 Name = CastTyName; 8628 unsigned Diag = Match == ArgType::NoMatchPedantic 8629 ? diag::warn_format_argument_needs_cast_pedantic 8630 : diag::warn_format_argument_needs_cast; 8631 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8632 << E->getSourceRange(), 8633 E->getBeginLoc(), /*IsStringLocation=*/false, 8634 SpecRange, Hints); 8635 } else { 8636 // In this case, the expression could be printed using a different 8637 // specifier, but we've decided that the specifier is probably correct 8638 // and we should cast instead. Just use the normal warning message. 8639 EmitFormatDiagnostic( 8640 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8641 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8642 << E->getSourceRange(), 8643 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8644 } 8645 } 8646 } else { 8647 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8648 SpecifierLen); 8649 // Since the warning for passing non-POD types to variadic functions 8650 // was deferred until now, we emit a warning for non-POD 8651 // arguments here. 8652 switch (S.isValidVarArgType(ExprTy)) { 8653 case Sema::VAK_Valid: 8654 case Sema::VAK_ValidInCXX11: { 8655 unsigned Diag; 8656 switch (Match) { 8657 case ArgType::Match: llvm_unreachable("expected non-matching"); 8658 case ArgType::NoMatchPedantic: 8659 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8660 break; 8661 case ArgType::NoMatchTypeConfusion: 8662 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8663 break; 8664 case ArgType::NoMatch: 8665 Diag = diag::warn_format_conversion_argument_type_mismatch; 8666 break; 8667 } 8668 8669 EmitFormatDiagnostic( 8670 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8671 << IsEnum << CSR << E->getSourceRange(), 8672 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8673 break; 8674 } 8675 case Sema::VAK_Undefined: 8676 case Sema::VAK_MSVCUndefined: 8677 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8678 << S.getLangOpts().CPlusPlus11 << ExprTy 8679 << CallType 8680 << AT.getRepresentativeTypeName(S.Context) << CSR 8681 << E->getSourceRange(), 8682 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8683 checkForCStrMembers(AT, E); 8684 break; 8685 8686 case Sema::VAK_Invalid: 8687 if (ExprTy->isObjCObjectType()) 8688 EmitFormatDiagnostic( 8689 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8690 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8691 << AT.getRepresentativeTypeName(S.Context) << CSR 8692 << E->getSourceRange(), 8693 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8694 else 8695 // FIXME: If this is an initializer list, suggest removing the braces 8696 // or inserting a cast to the target type. 8697 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8698 << isa<InitListExpr>(E) << ExprTy << CallType 8699 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8700 break; 8701 } 8702 8703 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8704 "format string specifier index out of range"); 8705 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8706 } 8707 8708 return true; 8709 } 8710 8711 //===--- CHECK: Scanf format string checking ------------------------------===// 8712 8713 namespace { 8714 8715 class CheckScanfHandler : public CheckFormatHandler { 8716 public: 8717 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8718 const Expr *origFormatExpr, Sema::FormatStringType type, 8719 unsigned firstDataArg, unsigned numDataArgs, 8720 const char *beg, bool hasVAListArg, 8721 ArrayRef<const Expr *> Args, unsigned formatIdx, 8722 bool inFunctionCall, Sema::VariadicCallType CallType, 8723 llvm::SmallBitVector &CheckedVarArgs, 8724 UncoveredArgHandler &UncoveredArg) 8725 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8726 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8727 inFunctionCall, CallType, CheckedVarArgs, 8728 UncoveredArg) {} 8729 8730 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8731 const char *startSpecifier, 8732 unsigned specifierLen) override; 8733 8734 bool HandleInvalidScanfConversionSpecifier( 8735 const analyze_scanf::ScanfSpecifier &FS, 8736 const char *startSpecifier, 8737 unsigned specifierLen) override; 8738 8739 void HandleIncompleteScanList(const char *start, const char *end) override; 8740 }; 8741 8742 } // namespace 8743 8744 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8745 const char *end) { 8746 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8747 getLocationOfByte(end), /*IsStringLocation*/true, 8748 getSpecifierRange(start, end - start)); 8749 } 8750 8751 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8752 const analyze_scanf::ScanfSpecifier &FS, 8753 const char *startSpecifier, 8754 unsigned specifierLen) { 8755 const analyze_scanf::ScanfConversionSpecifier &CS = 8756 FS.getConversionSpecifier(); 8757 8758 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8759 getLocationOfByte(CS.getStart()), 8760 startSpecifier, specifierLen, 8761 CS.getStart(), CS.getLength()); 8762 } 8763 8764 bool CheckScanfHandler::HandleScanfSpecifier( 8765 const analyze_scanf::ScanfSpecifier &FS, 8766 const char *startSpecifier, 8767 unsigned specifierLen) { 8768 using namespace analyze_scanf; 8769 using namespace analyze_format_string; 8770 8771 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8772 8773 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8774 // be used to decide if we are using positional arguments consistently. 8775 if (FS.consumesDataArgument()) { 8776 if (atFirstArg) { 8777 atFirstArg = false; 8778 usesPositionalArgs = FS.usesPositionalArg(); 8779 } 8780 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8781 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8782 startSpecifier, specifierLen); 8783 return false; 8784 } 8785 } 8786 8787 // Check if the field with is non-zero. 8788 const OptionalAmount &Amt = FS.getFieldWidth(); 8789 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8790 if (Amt.getConstantAmount() == 0) { 8791 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8792 Amt.getConstantLength()); 8793 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8794 getLocationOfByte(Amt.getStart()), 8795 /*IsStringLocation*/true, R, 8796 FixItHint::CreateRemoval(R)); 8797 } 8798 } 8799 8800 if (!FS.consumesDataArgument()) { 8801 // FIXME: Technically specifying a precision or field width here 8802 // makes no sense. Worth issuing a warning at some point. 8803 return true; 8804 } 8805 8806 // Consume the argument. 8807 unsigned argIndex = FS.getArgIndex(); 8808 if (argIndex < NumDataArgs) { 8809 // The check to see if the argIndex is valid will come later. 8810 // We set the bit here because we may exit early from this 8811 // function if we encounter some other error. 8812 CoveredArgs.set(argIndex); 8813 } 8814 8815 // Check the length modifier is valid with the given conversion specifier. 8816 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8817 S.getLangOpts())) 8818 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8819 diag::warn_format_nonsensical_length); 8820 else if (!FS.hasStandardLengthModifier()) 8821 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8822 else if (!FS.hasStandardLengthConversionCombination()) 8823 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8824 diag::warn_format_non_standard_conversion_spec); 8825 8826 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8827 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8828 8829 // The remaining checks depend on the data arguments. 8830 if (HasVAListArg) 8831 return true; 8832 8833 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8834 return false; 8835 8836 // Check that the argument type matches the format specifier. 8837 const Expr *Ex = getDataArg(argIndex); 8838 if (!Ex) 8839 return true; 8840 8841 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8842 8843 if (!AT.isValid()) { 8844 return true; 8845 } 8846 8847 analyze_format_string::ArgType::MatchKind Match = 8848 AT.matchesType(S.Context, Ex->getType()); 8849 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8850 if (Match == analyze_format_string::ArgType::Match) 8851 return true; 8852 8853 ScanfSpecifier fixedFS = FS; 8854 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8855 S.getLangOpts(), S.Context); 8856 8857 unsigned Diag = 8858 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8859 : diag::warn_format_conversion_argument_type_mismatch; 8860 8861 if (Success) { 8862 // Get the fix string from the fixed format specifier. 8863 SmallString<128> buf; 8864 llvm::raw_svector_ostream os(buf); 8865 fixedFS.toString(os); 8866 8867 EmitFormatDiagnostic( 8868 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8869 << Ex->getType() << false << Ex->getSourceRange(), 8870 Ex->getBeginLoc(), 8871 /*IsStringLocation*/ false, 8872 getSpecifierRange(startSpecifier, specifierLen), 8873 FixItHint::CreateReplacement( 8874 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8875 } else { 8876 EmitFormatDiagnostic(S.PDiag(Diag) 8877 << AT.getRepresentativeTypeName(S.Context) 8878 << Ex->getType() << false << Ex->getSourceRange(), 8879 Ex->getBeginLoc(), 8880 /*IsStringLocation*/ false, 8881 getSpecifierRange(startSpecifier, specifierLen)); 8882 } 8883 8884 return true; 8885 } 8886 8887 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8888 const Expr *OrigFormatExpr, 8889 ArrayRef<const Expr *> Args, 8890 bool HasVAListArg, unsigned format_idx, 8891 unsigned firstDataArg, 8892 Sema::FormatStringType Type, 8893 bool inFunctionCall, 8894 Sema::VariadicCallType CallType, 8895 llvm::SmallBitVector &CheckedVarArgs, 8896 UncoveredArgHandler &UncoveredArg, 8897 bool IgnoreStringsWithoutSpecifiers) { 8898 // CHECK: is the format string a wide literal? 8899 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8900 CheckFormatHandler::EmitFormatDiagnostic( 8901 S, inFunctionCall, Args[format_idx], 8902 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8903 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8904 return; 8905 } 8906 8907 // Str - The format string. NOTE: this is NOT null-terminated! 8908 StringRef StrRef = FExpr->getString(); 8909 const char *Str = StrRef.data(); 8910 // Account for cases where the string literal is truncated in a declaration. 8911 const ConstantArrayType *T = 8912 S.Context.getAsConstantArrayType(FExpr->getType()); 8913 assert(T && "String literal not of constant array type!"); 8914 size_t TypeSize = T->getSize().getZExtValue(); 8915 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8916 const unsigned numDataArgs = Args.size() - firstDataArg; 8917 8918 if (IgnoreStringsWithoutSpecifiers && 8919 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8920 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8921 return; 8922 8923 // Emit a warning if the string literal is truncated and does not contain an 8924 // embedded null character. 8925 if (TypeSize <= StrRef.size() && 8926 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8927 CheckFormatHandler::EmitFormatDiagnostic( 8928 S, inFunctionCall, Args[format_idx], 8929 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8930 FExpr->getBeginLoc(), 8931 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8932 return; 8933 } 8934 8935 // CHECK: empty format string? 8936 if (StrLen == 0 && numDataArgs > 0) { 8937 CheckFormatHandler::EmitFormatDiagnostic( 8938 S, inFunctionCall, Args[format_idx], 8939 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8940 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8941 return; 8942 } 8943 8944 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8945 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8946 Type == Sema::FST_OSTrace) { 8947 CheckPrintfHandler H( 8948 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8949 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8950 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8951 CheckedVarArgs, UncoveredArg); 8952 8953 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8954 S.getLangOpts(), 8955 S.Context.getTargetInfo(), 8956 Type == Sema::FST_FreeBSDKPrintf)) 8957 H.DoneProcessing(); 8958 } else if (Type == Sema::FST_Scanf) { 8959 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8960 numDataArgs, Str, HasVAListArg, Args, format_idx, 8961 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8962 8963 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8964 S.getLangOpts(), 8965 S.Context.getTargetInfo())) 8966 H.DoneProcessing(); 8967 } // TODO: handle other formats 8968 } 8969 8970 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8971 // Str - The format string. NOTE: this is NOT null-terminated! 8972 StringRef StrRef = FExpr->getString(); 8973 const char *Str = StrRef.data(); 8974 // Account for cases where the string literal is truncated in a declaration. 8975 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8976 assert(T && "String literal not of constant array type!"); 8977 size_t TypeSize = T->getSize().getZExtValue(); 8978 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8979 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8980 getLangOpts(), 8981 Context.getTargetInfo()); 8982 } 8983 8984 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8985 8986 // Returns the related absolute value function that is larger, of 0 if one 8987 // does not exist. 8988 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8989 switch (AbsFunction) { 8990 default: 8991 return 0; 8992 8993 case Builtin::BI__builtin_abs: 8994 return Builtin::BI__builtin_labs; 8995 case Builtin::BI__builtin_labs: 8996 return Builtin::BI__builtin_llabs; 8997 case Builtin::BI__builtin_llabs: 8998 return 0; 8999 9000 case Builtin::BI__builtin_fabsf: 9001 return Builtin::BI__builtin_fabs; 9002 case Builtin::BI__builtin_fabs: 9003 return Builtin::BI__builtin_fabsl; 9004 case Builtin::BI__builtin_fabsl: 9005 return 0; 9006 9007 case Builtin::BI__builtin_cabsf: 9008 return Builtin::BI__builtin_cabs; 9009 case Builtin::BI__builtin_cabs: 9010 return Builtin::BI__builtin_cabsl; 9011 case Builtin::BI__builtin_cabsl: 9012 return 0; 9013 9014 case Builtin::BIabs: 9015 return Builtin::BIlabs; 9016 case Builtin::BIlabs: 9017 return Builtin::BIllabs; 9018 case Builtin::BIllabs: 9019 return 0; 9020 9021 case Builtin::BIfabsf: 9022 return Builtin::BIfabs; 9023 case Builtin::BIfabs: 9024 return Builtin::BIfabsl; 9025 case Builtin::BIfabsl: 9026 return 0; 9027 9028 case Builtin::BIcabsf: 9029 return Builtin::BIcabs; 9030 case Builtin::BIcabs: 9031 return Builtin::BIcabsl; 9032 case Builtin::BIcabsl: 9033 return 0; 9034 } 9035 } 9036 9037 // Returns the argument type of the absolute value function. 9038 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9039 unsigned AbsType) { 9040 if (AbsType == 0) 9041 return QualType(); 9042 9043 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9044 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9045 if (Error != ASTContext::GE_None) 9046 return QualType(); 9047 9048 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9049 if (!FT) 9050 return QualType(); 9051 9052 if (FT->getNumParams() != 1) 9053 return QualType(); 9054 9055 return FT->getParamType(0); 9056 } 9057 9058 // Returns the best absolute value function, or zero, based on type and 9059 // current absolute value function. 9060 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9061 unsigned AbsFunctionKind) { 9062 unsigned BestKind = 0; 9063 uint64_t ArgSize = Context.getTypeSize(ArgType); 9064 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9065 Kind = getLargerAbsoluteValueFunction(Kind)) { 9066 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9067 if (Context.getTypeSize(ParamType) >= ArgSize) { 9068 if (BestKind == 0) 9069 BestKind = Kind; 9070 else if (Context.hasSameType(ParamType, ArgType)) { 9071 BestKind = Kind; 9072 break; 9073 } 9074 } 9075 } 9076 return BestKind; 9077 } 9078 9079 enum AbsoluteValueKind { 9080 AVK_Integer, 9081 AVK_Floating, 9082 AVK_Complex 9083 }; 9084 9085 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9086 if (T->isIntegralOrEnumerationType()) 9087 return AVK_Integer; 9088 if (T->isRealFloatingType()) 9089 return AVK_Floating; 9090 if (T->isAnyComplexType()) 9091 return AVK_Complex; 9092 9093 llvm_unreachable("Type not integer, floating, or complex"); 9094 } 9095 9096 // Changes the absolute value function to a different type. Preserves whether 9097 // the function is a builtin. 9098 static unsigned changeAbsFunction(unsigned AbsKind, 9099 AbsoluteValueKind ValueKind) { 9100 switch (ValueKind) { 9101 case AVK_Integer: 9102 switch (AbsKind) { 9103 default: 9104 return 0; 9105 case Builtin::BI__builtin_fabsf: 9106 case Builtin::BI__builtin_fabs: 9107 case Builtin::BI__builtin_fabsl: 9108 case Builtin::BI__builtin_cabsf: 9109 case Builtin::BI__builtin_cabs: 9110 case Builtin::BI__builtin_cabsl: 9111 return Builtin::BI__builtin_abs; 9112 case Builtin::BIfabsf: 9113 case Builtin::BIfabs: 9114 case Builtin::BIfabsl: 9115 case Builtin::BIcabsf: 9116 case Builtin::BIcabs: 9117 case Builtin::BIcabsl: 9118 return Builtin::BIabs; 9119 } 9120 case AVK_Floating: 9121 switch (AbsKind) { 9122 default: 9123 return 0; 9124 case Builtin::BI__builtin_abs: 9125 case Builtin::BI__builtin_labs: 9126 case Builtin::BI__builtin_llabs: 9127 case Builtin::BI__builtin_cabsf: 9128 case Builtin::BI__builtin_cabs: 9129 case Builtin::BI__builtin_cabsl: 9130 return Builtin::BI__builtin_fabsf; 9131 case Builtin::BIabs: 9132 case Builtin::BIlabs: 9133 case Builtin::BIllabs: 9134 case Builtin::BIcabsf: 9135 case Builtin::BIcabs: 9136 case Builtin::BIcabsl: 9137 return Builtin::BIfabsf; 9138 } 9139 case AVK_Complex: 9140 switch (AbsKind) { 9141 default: 9142 return 0; 9143 case Builtin::BI__builtin_abs: 9144 case Builtin::BI__builtin_labs: 9145 case Builtin::BI__builtin_llabs: 9146 case Builtin::BI__builtin_fabsf: 9147 case Builtin::BI__builtin_fabs: 9148 case Builtin::BI__builtin_fabsl: 9149 return Builtin::BI__builtin_cabsf; 9150 case Builtin::BIabs: 9151 case Builtin::BIlabs: 9152 case Builtin::BIllabs: 9153 case Builtin::BIfabsf: 9154 case Builtin::BIfabs: 9155 case Builtin::BIfabsl: 9156 return Builtin::BIcabsf; 9157 } 9158 } 9159 llvm_unreachable("Unable to convert function"); 9160 } 9161 9162 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9163 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9164 if (!FnInfo) 9165 return 0; 9166 9167 switch (FDecl->getBuiltinID()) { 9168 default: 9169 return 0; 9170 case Builtin::BI__builtin_abs: 9171 case Builtin::BI__builtin_fabs: 9172 case Builtin::BI__builtin_fabsf: 9173 case Builtin::BI__builtin_fabsl: 9174 case Builtin::BI__builtin_labs: 9175 case Builtin::BI__builtin_llabs: 9176 case Builtin::BI__builtin_cabs: 9177 case Builtin::BI__builtin_cabsf: 9178 case Builtin::BI__builtin_cabsl: 9179 case Builtin::BIabs: 9180 case Builtin::BIlabs: 9181 case Builtin::BIllabs: 9182 case Builtin::BIfabs: 9183 case Builtin::BIfabsf: 9184 case Builtin::BIfabsl: 9185 case Builtin::BIcabs: 9186 case Builtin::BIcabsf: 9187 case Builtin::BIcabsl: 9188 return FDecl->getBuiltinID(); 9189 } 9190 llvm_unreachable("Unknown Builtin type"); 9191 } 9192 9193 // If the replacement is valid, emit a note with replacement function. 9194 // Additionally, suggest including the proper header if not already included. 9195 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9196 unsigned AbsKind, QualType ArgType) { 9197 bool EmitHeaderHint = true; 9198 const char *HeaderName = nullptr; 9199 const char *FunctionName = nullptr; 9200 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9201 FunctionName = "std::abs"; 9202 if (ArgType->isIntegralOrEnumerationType()) { 9203 HeaderName = "cstdlib"; 9204 } else if (ArgType->isRealFloatingType()) { 9205 HeaderName = "cmath"; 9206 } else { 9207 llvm_unreachable("Invalid Type"); 9208 } 9209 9210 // Lookup all std::abs 9211 if (NamespaceDecl *Std = S.getStdNamespace()) { 9212 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9213 R.suppressDiagnostics(); 9214 S.LookupQualifiedName(R, Std); 9215 9216 for (const auto *I : R) { 9217 const FunctionDecl *FDecl = nullptr; 9218 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9219 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9220 } else { 9221 FDecl = dyn_cast<FunctionDecl>(I); 9222 } 9223 if (!FDecl) 9224 continue; 9225 9226 // Found std::abs(), check that they are the right ones. 9227 if (FDecl->getNumParams() != 1) 9228 continue; 9229 9230 // Check that the parameter type can handle the argument. 9231 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9232 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9233 S.Context.getTypeSize(ArgType) <= 9234 S.Context.getTypeSize(ParamType)) { 9235 // Found a function, don't need the header hint. 9236 EmitHeaderHint = false; 9237 break; 9238 } 9239 } 9240 } 9241 } else { 9242 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9243 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9244 9245 if (HeaderName) { 9246 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9247 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9248 R.suppressDiagnostics(); 9249 S.LookupName(R, S.getCurScope()); 9250 9251 if (R.isSingleResult()) { 9252 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9253 if (FD && FD->getBuiltinID() == AbsKind) { 9254 EmitHeaderHint = false; 9255 } else { 9256 return; 9257 } 9258 } else if (!R.empty()) { 9259 return; 9260 } 9261 } 9262 } 9263 9264 S.Diag(Loc, diag::note_replace_abs_function) 9265 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9266 9267 if (!HeaderName) 9268 return; 9269 9270 if (!EmitHeaderHint) 9271 return; 9272 9273 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9274 << FunctionName; 9275 } 9276 9277 template <std::size_t StrLen> 9278 static bool IsStdFunction(const FunctionDecl *FDecl, 9279 const char (&Str)[StrLen]) { 9280 if (!FDecl) 9281 return false; 9282 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9283 return false; 9284 if (!FDecl->isInStdNamespace()) 9285 return false; 9286 9287 return true; 9288 } 9289 9290 // Warn when using the wrong abs() function. 9291 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9292 const FunctionDecl *FDecl) { 9293 if (Call->getNumArgs() != 1) 9294 return; 9295 9296 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9297 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9298 if (AbsKind == 0 && !IsStdAbs) 9299 return; 9300 9301 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9302 QualType ParamType = Call->getArg(0)->getType(); 9303 9304 // Unsigned types cannot be negative. Suggest removing the absolute value 9305 // function call. 9306 if (ArgType->isUnsignedIntegerType()) { 9307 const char *FunctionName = 9308 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9309 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9310 Diag(Call->getExprLoc(), diag::note_remove_abs) 9311 << FunctionName 9312 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9313 return; 9314 } 9315 9316 // Taking the absolute value of a pointer is very suspicious, they probably 9317 // wanted to index into an array, dereference a pointer, call a function, etc. 9318 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9319 unsigned DiagType = 0; 9320 if (ArgType->isFunctionType()) 9321 DiagType = 1; 9322 else if (ArgType->isArrayType()) 9323 DiagType = 2; 9324 9325 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9326 return; 9327 } 9328 9329 // std::abs has overloads which prevent most of the absolute value problems 9330 // from occurring. 9331 if (IsStdAbs) 9332 return; 9333 9334 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9335 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9336 9337 // The argument and parameter are the same kind. Check if they are the right 9338 // size. 9339 if (ArgValueKind == ParamValueKind) { 9340 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9341 return; 9342 9343 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9344 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9345 << FDecl << ArgType << ParamType; 9346 9347 if (NewAbsKind == 0) 9348 return; 9349 9350 emitReplacement(*this, Call->getExprLoc(), 9351 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9352 return; 9353 } 9354 9355 // ArgValueKind != ParamValueKind 9356 // The wrong type of absolute value function was used. Attempt to find the 9357 // proper one. 9358 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9359 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9360 if (NewAbsKind == 0) 9361 return; 9362 9363 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9364 << FDecl << ParamValueKind << ArgValueKind; 9365 9366 emitReplacement(*this, Call->getExprLoc(), 9367 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9368 } 9369 9370 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9371 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9372 const FunctionDecl *FDecl) { 9373 if (!Call || !FDecl) return; 9374 9375 // Ignore template specializations and macros. 9376 if (inTemplateInstantiation()) return; 9377 if (Call->getExprLoc().isMacroID()) return; 9378 9379 // Only care about the one template argument, two function parameter std::max 9380 if (Call->getNumArgs() != 2) return; 9381 if (!IsStdFunction(FDecl, "max")) return; 9382 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9383 if (!ArgList) return; 9384 if (ArgList->size() != 1) return; 9385 9386 // Check that template type argument is unsigned integer. 9387 const auto& TA = ArgList->get(0); 9388 if (TA.getKind() != TemplateArgument::Type) return; 9389 QualType ArgType = TA.getAsType(); 9390 if (!ArgType->isUnsignedIntegerType()) return; 9391 9392 // See if either argument is a literal zero. 9393 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9394 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9395 if (!MTE) return false; 9396 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9397 if (!Num) return false; 9398 if (Num->getValue() != 0) return false; 9399 return true; 9400 }; 9401 9402 const Expr *FirstArg = Call->getArg(0); 9403 const Expr *SecondArg = Call->getArg(1); 9404 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9405 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9406 9407 // Only warn when exactly one argument is zero. 9408 if (IsFirstArgZero == IsSecondArgZero) return; 9409 9410 SourceRange FirstRange = FirstArg->getSourceRange(); 9411 SourceRange SecondRange = SecondArg->getSourceRange(); 9412 9413 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9414 9415 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9416 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9417 9418 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9419 SourceRange RemovalRange; 9420 if (IsFirstArgZero) { 9421 RemovalRange = SourceRange(FirstRange.getBegin(), 9422 SecondRange.getBegin().getLocWithOffset(-1)); 9423 } else { 9424 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9425 SecondRange.getEnd()); 9426 } 9427 9428 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9429 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9430 << FixItHint::CreateRemoval(RemovalRange); 9431 } 9432 9433 //===--- CHECK: Standard memory functions ---------------------------------===// 9434 9435 /// Takes the expression passed to the size_t parameter of functions 9436 /// such as memcmp, strncat, etc and warns if it's a comparison. 9437 /// 9438 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9439 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9440 IdentifierInfo *FnName, 9441 SourceLocation FnLoc, 9442 SourceLocation RParenLoc) { 9443 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9444 if (!Size) 9445 return false; 9446 9447 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9448 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9449 return false; 9450 9451 SourceRange SizeRange = Size->getSourceRange(); 9452 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9453 << SizeRange << FnName; 9454 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9455 << FnName 9456 << FixItHint::CreateInsertion( 9457 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9458 << FixItHint::CreateRemoval(RParenLoc); 9459 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9460 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9461 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9462 ")"); 9463 9464 return true; 9465 } 9466 9467 /// Determine whether the given type is or contains a dynamic class type 9468 /// (e.g., whether it has a vtable). 9469 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9470 bool &IsContained) { 9471 // Look through array types while ignoring qualifiers. 9472 const Type *Ty = T->getBaseElementTypeUnsafe(); 9473 IsContained = false; 9474 9475 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9476 RD = RD ? RD->getDefinition() : nullptr; 9477 if (!RD || RD->isInvalidDecl()) 9478 return nullptr; 9479 9480 if (RD->isDynamicClass()) 9481 return RD; 9482 9483 // Check all the fields. If any bases were dynamic, the class is dynamic. 9484 // It's impossible for a class to transitively contain itself by value, so 9485 // infinite recursion is impossible. 9486 for (auto *FD : RD->fields()) { 9487 bool SubContained; 9488 if (const CXXRecordDecl *ContainedRD = 9489 getContainedDynamicClass(FD->getType(), SubContained)) { 9490 IsContained = true; 9491 return ContainedRD; 9492 } 9493 } 9494 9495 return nullptr; 9496 } 9497 9498 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9499 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9500 if (Unary->getKind() == UETT_SizeOf) 9501 return Unary; 9502 return nullptr; 9503 } 9504 9505 /// If E is a sizeof expression, returns its argument expression, 9506 /// otherwise returns NULL. 9507 static const Expr *getSizeOfExprArg(const Expr *E) { 9508 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9509 if (!SizeOf->isArgumentType()) 9510 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9511 return nullptr; 9512 } 9513 9514 /// If E is a sizeof expression, returns its argument type. 9515 static QualType getSizeOfArgType(const Expr *E) { 9516 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9517 return SizeOf->getTypeOfArgument(); 9518 return QualType(); 9519 } 9520 9521 namespace { 9522 9523 struct SearchNonTrivialToInitializeField 9524 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9525 using Super = 9526 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9527 9528 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9529 9530 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9531 SourceLocation SL) { 9532 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9533 asDerived().visitArray(PDIK, AT, SL); 9534 return; 9535 } 9536 9537 Super::visitWithKind(PDIK, FT, SL); 9538 } 9539 9540 void visitARCStrong(QualType FT, SourceLocation SL) { 9541 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9542 } 9543 void visitARCWeak(QualType FT, SourceLocation SL) { 9544 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9545 } 9546 void visitStruct(QualType FT, SourceLocation SL) { 9547 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9548 visit(FD->getType(), FD->getLocation()); 9549 } 9550 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9551 const ArrayType *AT, SourceLocation SL) { 9552 visit(getContext().getBaseElementType(AT), SL); 9553 } 9554 void visitTrivial(QualType FT, SourceLocation SL) {} 9555 9556 static void diag(QualType RT, const Expr *E, Sema &S) { 9557 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9558 } 9559 9560 ASTContext &getContext() { return S.getASTContext(); } 9561 9562 const Expr *E; 9563 Sema &S; 9564 }; 9565 9566 struct SearchNonTrivialToCopyField 9567 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9568 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9569 9570 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9571 9572 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9573 SourceLocation SL) { 9574 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9575 asDerived().visitArray(PCK, AT, SL); 9576 return; 9577 } 9578 9579 Super::visitWithKind(PCK, FT, SL); 9580 } 9581 9582 void visitARCStrong(QualType FT, SourceLocation SL) { 9583 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9584 } 9585 void visitARCWeak(QualType FT, SourceLocation SL) { 9586 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9587 } 9588 void visitStruct(QualType FT, SourceLocation SL) { 9589 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9590 visit(FD->getType(), FD->getLocation()); 9591 } 9592 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9593 SourceLocation SL) { 9594 visit(getContext().getBaseElementType(AT), SL); 9595 } 9596 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9597 SourceLocation SL) {} 9598 void visitTrivial(QualType FT, SourceLocation SL) {} 9599 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9600 9601 static void diag(QualType RT, const Expr *E, Sema &S) { 9602 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9603 } 9604 9605 ASTContext &getContext() { return S.getASTContext(); } 9606 9607 const Expr *E; 9608 Sema &S; 9609 }; 9610 9611 } 9612 9613 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9614 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9615 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9616 9617 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9618 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9619 return false; 9620 9621 return doesExprLikelyComputeSize(BO->getLHS()) || 9622 doesExprLikelyComputeSize(BO->getRHS()); 9623 } 9624 9625 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9626 } 9627 9628 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9629 /// 9630 /// \code 9631 /// #define MACRO 0 9632 /// foo(MACRO); 9633 /// foo(0); 9634 /// \endcode 9635 /// 9636 /// This should return true for the first call to foo, but not for the second 9637 /// (regardless of whether foo is a macro or function). 9638 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9639 SourceLocation CallLoc, 9640 SourceLocation ArgLoc) { 9641 if (!CallLoc.isMacroID()) 9642 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9643 9644 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9645 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9646 } 9647 9648 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9649 /// last two arguments transposed. 9650 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9651 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9652 return; 9653 9654 const Expr *SizeArg = 9655 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9656 9657 auto isLiteralZero = [](const Expr *E) { 9658 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9659 }; 9660 9661 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9662 SourceLocation CallLoc = Call->getRParenLoc(); 9663 SourceManager &SM = S.getSourceManager(); 9664 if (isLiteralZero(SizeArg) && 9665 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9666 9667 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9668 9669 // Some platforms #define bzero to __builtin_memset. See if this is the 9670 // case, and if so, emit a better diagnostic. 9671 if (BId == Builtin::BIbzero || 9672 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9673 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9674 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9675 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9676 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9677 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9678 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9679 } 9680 return; 9681 } 9682 9683 // If the second argument to a memset is a sizeof expression and the third 9684 // isn't, this is also likely an error. This should catch 9685 // 'memset(buf, sizeof(buf), 0xff)'. 9686 if (BId == Builtin::BImemset && 9687 doesExprLikelyComputeSize(Call->getArg(1)) && 9688 !doesExprLikelyComputeSize(Call->getArg(2))) { 9689 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9690 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9691 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9692 return; 9693 } 9694 } 9695 9696 /// Check for dangerous or invalid arguments to memset(). 9697 /// 9698 /// This issues warnings on known problematic, dangerous or unspecified 9699 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9700 /// function calls. 9701 /// 9702 /// \param Call The call expression to diagnose. 9703 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9704 unsigned BId, 9705 IdentifierInfo *FnName) { 9706 assert(BId != 0); 9707 9708 // It is possible to have a non-standard definition of memset. Validate 9709 // we have enough arguments, and if not, abort further checking. 9710 unsigned ExpectedNumArgs = 9711 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9712 if (Call->getNumArgs() < ExpectedNumArgs) 9713 return; 9714 9715 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9716 BId == Builtin::BIstrndup ? 1 : 2); 9717 unsigned LenArg = 9718 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9719 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9720 9721 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9722 Call->getBeginLoc(), Call->getRParenLoc())) 9723 return; 9724 9725 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9726 CheckMemaccessSize(*this, BId, Call); 9727 9728 // We have special checking when the length is a sizeof expression. 9729 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9730 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9731 llvm::FoldingSetNodeID SizeOfArgID; 9732 9733 // Although widely used, 'bzero' is not a standard function. Be more strict 9734 // with the argument types before allowing diagnostics and only allow the 9735 // form bzero(ptr, sizeof(...)). 9736 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9737 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9738 return; 9739 9740 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9741 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9742 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9743 9744 QualType DestTy = Dest->getType(); 9745 QualType PointeeTy; 9746 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9747 PointeeTy = DestPtrTy->getPointeeType(); 9748 9749 // Never warn about void type pointers. This can be used to suppress 9750 // false positives. 9751 if (PointeeTy->isVoidType()) 9752 continue; 9753 9754 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9755 // actually comparing the expressions for equality. Because computing the 9756 // expression IDs can be expensive, we only do this if the diagnostic is 9757 // enabled. 9758 if (SizeOfArg && 9759 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9760 SizeOfArg->getExprLoc())) { 9761 // We only compute IDs for expressions if the warning is enabled, and 9762 // cache the sizeof arg's ID. 9763 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9764 SizeOfArg->Profile(SizeOfArgID, Context, true); 9765 llvm::FoldingSetNodeID DestID; 9766 Dest->Profile(DestID, Context, true); 9767 if (DestID == SizeOfArgID) { 9768 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9769 // over sizeof(src) as well. 9770 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9771 StringRef ReadableName = FnName->getName(); 9772 9773 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9774 if (UnaryOp->getOpcode() == UO_AddrOf) 9775 ActionIdx = 1; // If its an address-of operator, just remove it. 9776 if (!PointeeTy->isIncompleteType() && 9777 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9778 ActionIdx = 2; // If the pointee's size is sizeof(char), 9779 // suggest an explicit length. 9780 9781 // If the function is defined as a builtin macro, do not show macro 9782 // expansion. 9783 SourceLocation SL = SizeOfArg->getExprLoc(); 9784 SourceRange DSR = Dest->getSourceRange(); 9785 SourceRange SSR = SizeOfArg->getSourceRange(); 9786 SourceManager &SM = getSourceManager(); 9787 9788 if (SM.isMacroArgExpansion(SL)) { 9789 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9790 SL = SM.getSpellingLoc(SL); 9791 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9792 SM.getSpellingLoc(DSR.getEnd())); 9793 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9794 SM.getSpellingLoc(SSR.getEnd())); 9795 } 9796 9797 DiagRuntimeBehavior(SL, SizeOfArg, 9798 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9799 << ReadableName 9800 << PointeeTy 9801 << DestTy 9802 << DSR 9803 << SSR); 9804 DiagRuntimeBehavior(SL, SizeOfArg, 9805 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9806 << ActionIdx 9807 << SSR); 9808 9809 break; 9810 } 9811 } 9812 9813 // Also check for cases where the sizeof argument is the exact same 9814 // type as the memory argument, and where it points to a user-defined 9815 // record type. 9816 if (SizeOfArgTy != QualType()) { 9817 if (PointeeTy->isRecordType() && 9818 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9819 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9820 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9821 << FnName << SizeOfArgTy << ArgIdx 9822 << PointeeTy << Dest->getSourceRange() 9823 << LenExpr->getSourceRange()); 9824 break; 9825 } 9826 } 9827 } else if (DestTy->isArrayType()) { 9828 PointeeTy = DestTy; 9829 } 9830 9831 if (PointeeTy == QualType()) 9832 continue; 9833 9834 // Always complain about dynamic classes. 9835 bool IsContained; 9836 if (const CXXRecordDecl *ContainedRD = 9837 getContainedDynamicClass(PointeeTy, IsContained)) { 9838 9839 unsigned OperationType = 0; 9840 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9841 // "overwritten" if we're warning about the destination for any call 9842 // but memcmp; otherwise a verb appropriate to the call. 9843 if (ArgIdx != 0 || IsCmp) { 9844 if (BId == Builtin::BImemcpy) 9845 OperationType = 1; 9846 else if(BId == Builtin::BImemmove) 9847 OperationType = 2; 9848 else if (IsCmp) 9849 OperationType = 3; 9850 } 9851 9852 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9853 PDiag(diag::warn_dyn_class_memaccess) 9854 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9855 << IsContained << ContainedRD << OperationType 9856 << Call->getCallee()->getSourceRange()); 9857 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9858 BId != Builtin::BImemset) 9859 DiagRuntimeBehavior( 9860 Dest->getExprLoc(), Dest, 9861 PDiag(diag::warn_arc_object_memaccess) 9862 << ArgIdx << FnName << PointeeTy 9863 << Call->getCallee()->getSourceRange()); 9864 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9865 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9866 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9867 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9868 PDiag(diag::warn_cstruct_memaccess) 9869 << ArgIdx << FnName << PointeeTy << 0); 9870 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9871 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9872 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9873 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9874 PDiag(diag::warn_cstruct_memaccess) 9875 << ArgIdx << FnName << PointeeTy << 1); 9876 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9877 } else { 9878 continue; 9879 } 9880 } else 9881 continue; 9882 9883 DiagRuntimeBehavior( 9884 Dest->getExprLoc(), Dest, 9885 PDiag(diag::note_bad_memaccess_silence) 9886 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9887 break; 9888 } 9889 } 9890 9891 // A little helper routine: ignore addition and subtraction of integer literals. 9892 // This intentionally does not ignore all integer constant expressions because 9893 // we don't want to remove sizeof(). 9894 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9895 Ex = Ex->IgnoreParenCasts(); 9896 9897 while (true) { 9898 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9899 if (!BO || !BO->isAdditiveOp()) 9900 break; 9901 9902 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9903 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9904 9905 if (isa<IntegerLiteral>(RHS)) 9906 Ex = LHS; 9907 else if (isa<IntegerLiteral>(LHS)) 9908 Ex = RHS; 9909 else 9910 break; 9911 } 9912 9913 return Ex; 9914 } 9915 9916 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9917 ASTContext &Context) { 9918 // Only handle constant-sized or VLAs, but not flexible members. 9919 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9920 // Only issue the FIXIT for arrays of size > 1. 9921 if (CAT->getSize().getSExtValue() <= 1) 9922 return false; 9923 } else if (!Ty->isVariableArrayType()) { 9924 return false; 9925 } 9926 return true; 9927 } 9928 9929 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9930 // be the size of the source, instead of the destination. 9931 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9932 IdentifierInfo *FnName) { 9933 9934 // Don't crash if the user has the wrong number of arguments 9935 unsigned NumArgs = Call->getNumArgs(); 9936 if ((NumArgs != 3) && (NumArgs != 4)) 9937 return; 9938 9939 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9940 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9941 const Expr *CompareWithSrc = nullptr; 9942 9943 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9944 Call->getBeginLoc(), Call->getRParenLoc())) 9945 return; 9946 9947 // Look for 'strlcpy(dst, x, sizeof(x))' 9948 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9949 CompareWithSrc = Ex; 9950 else { 9951 // Look for 'strlcpy(dst, x, strlen(x))' 9952 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9953 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9954 SizeCall->getNumArgs() == 1) 9955 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9956 } 9957 } 9958 9959 if (!CompareWithSrc) 9960 return; 9961 9962 // Determine if the argument to sizeof/strlen is equal to the source 9963 // argument. In principle there's all kinds of things you could do 9964 // here, for instance creating an == expression and evaluating it with 9965 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9966 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9967 if (!SrcArgDRE) 9968 return; 9969 9970 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9971 if (!CompareWithSrcDRE || 9972 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9973 return; 9974 9975 const Expr *OriginalSizeArg = Call->getArg(2); 9976 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9977 << OriginalSizeArg->getSourceRange() << FnName; 9978 9979 // Output a FIXIT hint if the destination is an array (rather than a 9980 // pointer to an array). This could be enhanced to handle some 9981 // pointers if we know the actual size, like if DstArg is 'array+2' 9982 // we could say 'sizeof(array)-2'. 9983 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9984 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9985 return; 9986 9987 SmallString<128> sizeString; 9988 llvm::raw_svector_ostream OS(sizeString); 9989 OS << "sizeof("; 9990 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9991 OS << ")"; 9992 9993 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9994 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9995 OS.str()); 9996 } 9997 9998 /// Check if two expressions refer to the same declaration. 9999 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10000 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10001 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10002 return D1->getDecl() == D2->getDecl(); 10003 return false; 10004 } 10005 10006 static const Expr *getStrlenExprArg(const Expr *E) { 10007 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10008 const FunctionDecl *FD = CE->getDirectCallee(); 10009 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10010 return nullptr; 10011 return CE->getArg(0)->IgnoreParenCasts(); 10012 } 10013 return nullptr; 10014 } 10015 10016 // Warn on anti-patterns as the 'size' argument to strncat. 10017 // The correct size argument should look like following: 10018 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10019 void Sema::CheckStrncatArguments(const CallExpr *CE, 10020 IdentifierInfo *FnName) { 10021 // Don't crash if the user has the wrong number of arguments. 10022 if (CE->getNumArgs() < 3) 10023 return; 10024 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10025 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10026 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10027 10028 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10029 CE->getRParenLoc())) 10030 return; 10031 10032 // Identify common expressions, which are wrongly used as the size argument 10033 // to strncat and may lead to buffer overflows. 10034 unsigned PatternType = 0; 10035 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10036 // - sizeof(dst) 10037 if (referToTheSameDecl(SizeOfArg, DstArg)) 10038 PatternType = 1; 10039 // - sizeof(src) 10040 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10041 PatternType = 2; 10042 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10043 if (BE->getOpcode() == BO_Sub) { 10044 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10045 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10046 // - sizeof(dst) - strlen(dst) 10047 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10048 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10049 PatternType = 1; 10050 // - sizeof(src) - (anything) 10051 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10052 PatternType = 2; 10053 } 10054 } 10055 10056 if (PatternType == 0) 10057 return; 10058 10059 // Generate the diagnostic. 10060 SourceLocation SL = LenArg->getBeginLoc(); 10061 SourceRange SR = LenArg->getSourceRange(); 10062 SourceManager &SM = getSourceManager(); 10063 10064 // If the function is defined as a builtin macro, do not show macro expansion. 10065 if (SM.isMacroArgExpansion(SL)) { 10066 SL = SM.getSpellingLoc(SL); 10067 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10068 SM.getSpellingLoc(SR.getEnd())); 10069 } 10070 10071 // Check if the destination is an array (rather than a pointer to an array). 10072 QualType DstTy = DstArg->getType(); 10073 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10074 Context); 10075 if (!isKnownSizeArray) { 10076 if (PatternType == 1) 10077 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10078 else 10079 Diag(SL, diag::warn_strncat_src_size) << SR; 10080 return; 10081 } 10082 10083 if (PatternType == 1) 10084 Diag(SL, diag::warn_strncat_large_size) << SR; 10085 else 10086 Diag(SL, diag::warn_strncat_src_size) << SR; 10087 10088 SmallString<128> sizeString; 10089 llvm::raw_svector_ostream OS(sizeString); 10090 OS << "sizeof("; 10091 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10092 OS << ") - "; 10093 OS << "strlen("; 10094 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10095 OS << ") - 1"; 10096 10097 Diag(SL, diag::note_strncat_wrong_size) 10098 << FixItHint::CreateReplacement(SR, OS.str()); 10099 } 10100 10101 void 10102 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10103 SourceLocation ReturnLoc, 10104 bool isObjCMethod, 10105 const AttrVec *Attrs, 10106 const FunctionDecl *FD) { 10107 // Check if the return value is null but should not be. 10108 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10109 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10110 CheckNonNullExpr(*this, RetValExp)) 10111 Diag(ReturnLoc, diag::warn_null_ret) 10112 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10113 10114 // C++11 [basic.stc.dynamic.allocation]p4: 10115 // If an allocation function declared with a non-throwing 10116 // exception-specification fails to allocate storage, it shall return 10117 // a null pointer. Any other allocation function that fails to allocate 10118 // storage shall indicate failure only by throwing an exception [...] 10119 if (FD) { 10120 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10121 if (Op == OO_New || Op == OO_Array_New) { 10122 const FunctionProtoType *Proto 10123 = FD->getType()->castAs<FunctionProtoType>(); 10124 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10125 CheckNonNullExpr(*this, RetValExp)) 10126 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10127 << FD << getLangOpts().CPlusPlus11; 10128 } 10129 } 10130 } 10131 10132 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10133 10134 /// Check for comparisons of floating point operands using != and ==. 10135 /// Issue a warning if these are no self-comparisons, as they are not likely 10136 /// to do what the programmer intended. 10137 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10138 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10139 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10140 10141 // Special case: check for x == x (which is OK). 10142 // Do not emit warnings for such cases. 10143 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10144 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10145 if (DRL->getDecl() == DRR->getDecl()) 10146 return; 10147 10148 // Special case: check for comparisons against literals that can be exactly 10149 // represented by APFloat. In such cases, do not emit a warning. This 10150 // is a heuristic: often comparison against such literals are used to 10151 // detect if a value in a variable has not changed. This clearly can 10152 // lead to false negatives. 10153 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10154 if (FLL->isExact()) 10155 return; 10156 } else 10157 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10158 if (FLR->isExact()) 10159 return; 10160 10161 // Check for comparisons with builtin types. 10162 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10163 if (CL->getBuiltinCallee()) 10164 return; 10165 10166 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10167 if (CR->getBuiltinCallee()) 10168 return; 10169 10170 // Emit the diagnostic. 10171 Diag(Loc, diag::warn_floatingpoint_eq) 10172 << LHS->getSourceRange() << RHS->getSourceRange(); 10173 } 10174 10175 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10176 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10177 10178 namespace { 10179 10180 /// Structure recording the 'active' range of an integer-valued 10181 /// expression. 10182 struct IntRange { 10183 /// The number of bits active in the int. Note that this includes exactly one 10184 /// sign bit if !NonNegative. 10185 unsigned Width; 10186 10187 /// True if the int is known not to have negative values. If so, all leading 10188 /// bits before Width are known zero, otherwise they are known to be the 10189 /// same as the MSB within Width. 10190 bool NonNegative; 10191 10192 IntRange(unsigned Width, bool NonNegative) 10193 : Width(Width), NonNegative(NonNegative) {} 10194 10195 /// Number of bits excluding the sign bit. 10196 unsigned valueBits() const { 10197 return NonNegative ? Width : Width - 1; 10198 } 10199 10200 /// Returns the range of the bool type. 10201 static IntRange forBoolType() { 10202 return IntRange(1, true); 10203 } 10204 10205 /// Returns the range of an opaque value of the given integral type. 10206 static IntRange forValueOfType(ASTContext &C, QualType T) { 10207 return forValueOfCanonicalType(C, 10208 T->getCanonicalTypeInternal().getTypePtr()); 10209 } 10210 10211 /// Returns the range of an opaque value of a canonical integral type. 10212 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10213 assert(T->isCanonicalUnqualified()); 10214 10215 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10216 T = VT->getElementType().getTypePtr(); 10217 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10218 T = CT->getElementType().getTypePtr(); 10219 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10220 T = AT->getValueType().getTypePtr(); 10221 10222 if (!C.getLangOpts().CPlusPlus) { 10223 // For enum types in C code, use the underlying datatype. 10224 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10225 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10226 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10227 // For enum types in C++, use the known bit width of the enumerators. 10228 EnumDecl *Enum = ET->getDecl(); 10229 // In C++11, enums can have a fixed underlying type. Use this type to 10230 // compute the range. 10231 if (Enum->isFixed()) { 10232 return IntRange(C.getIntWidth(QualType(T, 0)), 10233 !ET->isSignedIntegerOrEnumerationType()); 10234 } 10235 10236 unsigned NumPositive = Enum->getNumPositiveBits(); 10237 unsigned NumNegative = Enum->getNumNegativeBits(); 10238 10239 if (NumNegative == 0) 10240 return IntRange(NumPositive, true/*NonNegative*/); 10241 else 10242 return IntRange(std::max(NumPositive + 1, NumNegative), 10243 false/*NonNegative*/); 10244 } 10245 10246 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10247 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10248 10249 const BuiltinType *BT = cast<BuiltinType>(T); 10250 assert(BT->isInteger()); 10251 10252 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10253 } 10254 10255 /// Returns the "target" range of a canonical integral type, i.e. 10256 /// the range of values expressible in the type. 10257 /// 10258 /// This matches forValueOfCanonicalType except that enums have the 10259 /// full range of their type, not the range of their enumerators. 10260 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10261 assert(T->isCanonicalUnqualified()); 10262 10263 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10264 T = VT->getElementType().getTypePtr(); 10265 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10266 T = CT->getElementType().getTypePtr(); 10267 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10268 T = AT->getValueType().getTypePtr(); 10269 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10270 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10271 10272 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10273 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10274 10275 const BuiltinType *BT = cast<BuiltinType>(T); 10276 assert(BT->isInteger()); 10277 10278 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10279 } 10280 10281 /// Returns the supremum of two ranges: i.e. their conservative merge. 10282 static IntRange join(IntRange L, IntRange R) { 10283 bool Unsigned = L.NonNegative && R.NonNegative; 10284 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10285 L.NonNegative && R.NonNegative); 10286 } 10287 10288 /// Return the range of a bitwise-AND of the two ranges. 10289 static IntRange bit_and(IntRange L, IntRange R) { 10290 unsigned Bits = std::max(L.Width, R.Width); 10291 bool NonNegative = false; 10292 if (L.NonNegative) { 10293 Bits = std::min(Bits, L.Width); 10294 NonNegative = true; 10295 } 10296 if (R.NonNegative) { 10297 Bits = std::min(Bits, R.Width); 10298 NonNegative = true; 10299 } 10300 return IntRange(Bits, NonNegative); 10301 } 10302 10303 /// Return the range of a sum of the two ranges. 10304 static IntRange sum(IntRange L, IntRange R) { 10305 bool Unsigned = L.NonNegative && R.NonNegative; 10306 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10307 Unsigned); 10308 } 10309 10310 /// Return the range of a difference of the two ranges. 10311 static IntRange difference(IntRange L, IntRange R) { 10312 // We need a 1-bit-wider range if: 10313 // 1) LHS can be negative: least value can be reduced. 10314 // 2) RHS can be negative: greatest value can be increased. 10315 bool CanWiden = !L.NonNegative || !R.NonNegative; 10316 bool Unsigned = L.NonNegative && R.Width == 0; 10317 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10318 !Unsigned, 10319 Unsigned); 10320 } 10321 10322 /// Return the range of a product of the two ranges. 10323 static IntRange product(IntRange L, IntRange R) { 10324 // If both LHS and RHS can be negative, we can form 10325 // -2^L * -2^R = 2^(L + R) 10326 // which requires L + R + 1 value bits to represent. 10327 bool CanWiden = !L.NonNegative && !R.NonNegative; 10328 bool Unsigned = L.NonNegative && R.NonNegative; 10329 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10330 Unsigned); 10331 } 10332 10333 /// Return the range of a remainder operation between the two ranges. 10334 static IntRange rem(IntRange L, IntRange R) { 10335 // The result of a remainder can't be larger than the result of 10336 // either side. The sign of the result is the sign of the LHS. 10337 bool Unsigned = L.NonNegative; 10338 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10339 Unsigned); 10340 } 10341 }; 10342 10343 } // namespace 10344 10345 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10346 unsigned MaxWidth) { 10347 if (value.isSigned() && value.isNegative()) 10348 return IntRange(value.getMinSignedBits(), false); 10349 10350 if (value.getBitWidth() > MaxWidth) 10351 value = value.trunc(MaxWidth); 10352 10353 // isNonNegative() just checks the sign bit without considering 10354 // signedness. 10355 return IntRange(value.getActiveBits(), true); 10356 } 10357 10358 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10359 unsigned MaxWidth) { 10360 if (result.isInt()) 10361 return GetValueRange(C, result.getInt(), MaxWidth); 10362 10363 if (result.isVector()) { 10364 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10365 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10366 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10367 R = IntRange::join(R, El); 10368 } 10369 return R; 10370 } 10371 10372 if (result.isComplexInt()) { 10373 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10374 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10375 return IntRange::join(R, I); 10376 } 10377 10378 // This can happen with lossless casts to intptr_t of "based" lvalues. 10379 // Assume it might use arbitrary bits. 10380 // FIXME: The only reason we need to pass the type in here is to get 10381 // the sign right on this one case. It would be nice if APValue 10382 // preserved this. 10383 assert(result.isLValue() || result.isAddrLabelDiff()); 10384 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10385 } 10386 10387 static QualType GetExprType(const Expr *E) { 10388 QualType Ty = E->getType(); 10389 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10390 Ty = AtomicRHS->getValueType(); 10391 return Ty; 10392 } 10393 10394 /// Pseudo-evaluate the given integer expression, estimating the 10395 /// range of values it might take. 10396 /// 10397 /// \param MaxWidth The width to which the value will be truncated. 10398 /// \param Approximate If \c true, return a likely range for the result: in 10399 /// particular, assume that aritmetic on narrower types doesn't leave 10400 /// those types. If \c false, return a range including all possible 10401 /// result values. 10402 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10403 bool InConstantContext, bool Approximate) { 10404 E = E->IgnoreParens(); 10405 10406 // Try a full evaluation first. 10407 Expr::EvalResult result; 10408 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10409 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10410 10411 // I think we only want to look through implicit casts here; if the 10412 // user has an explicit widening cast, we should treat the value as 10413 // being of the new, wider type. 10414 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10415 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10416 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 10417 Approximate); 10418 10419 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10420 10421 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10422 CE->getCastKind() == CK_BooleanToSignedIntegral; 10423 10424 // Assume that non-integer casts can span the full range of the type. 10425 if (!isIntegerCast) 10426 return OutputTypeRange; 10427 10428 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10429 std::min(MaxWidth, OutputTypeRange.Width), 10430 InConstantContext, Approximate); 10431 10432 // Bail out if the subexpr's range is as wide as the cast type. 10433 if (SubRange.Width >= OutputTypeRange.Width) 10434 return OutputTypeRange; 10435 10436 // Otherwise, we take the smaller width, and we're non-negative if 10437 // either the output type or the subexpr is. 10438 return IntRange(SubRange.Width, 10439 SubRange.NonNegative || OutputTypeRange.NonNegative); 10440 } 10441 10442 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10443 // If we can fold the condition, just take that operand. 10444 bool CondResult; 10445 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10446 return GetExprRange(C, 10447 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10448 MaxWidth, InConstantContext, Approximate); 10449 10450 // Otherwise, conservatively merge. 10451 // GetExprRange requires an integer expression, but a throw expression 10452 // results in a void type. 10453 Expr *E = CO->getTrueExpr(); 10454 IntRange L = E->getType()->isVoidType() 10455 ? IntRange{0, true} 10456 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10457 E = CO->getFalseExpr(); 10458 IntRange R = E->getType()->isVoidType() 10459 ? IntRange{0, true} 10460 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10461 return IntRange::join(L, R); 10462 } 10463 10464 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10465 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 10466 10467 switch (BO->getOpcode()) { 10468 case BO_Cmp: 10469 llvm_unreachable("builtin <=> should have class type"); 10470 10471 // Boolean-valued operations are single-bit and positive. 10472 case BO_LAnd: 10473 case BO_LOr: 10474 case BO_LT: 10475 case BO_GT: 10476 case BO_LE: 10477 case BO_GE: 10478 case BO_EQ: 10479 case BO_NE: 10480 return IntRange::forBoolType(); 10481 10482 // The type of the assignments is the type of the LHS, so the RHS 10483 // is not necessarily the same type. 10484 case BO_MulAssign: 10485 case BO_DivAssign: 10486 case BO_RemAssign: 10487 case BO_AddAssign: 10488 case BO_SubAssign: 10489 case BO_XorAssign: 10490 case BO_OrAssign: 10491 // TODO: bitfields? 10492 return IntRange::forValueOfType(C, GetExprType(E)); 10493 10494 // Simple assignments just pass through the RHS, which will have 10495 // been coerced to the LHS type. 10496 case BO_Assign: 10497 // TODO: bitfields? 10498 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10499 Approximate); 10500 10501 // Operations with opaque sources are black-listed. 10502 case BO_PtrMemD: 10503 case BO_PtrMemI: 10504 return IntRange::forValueOfType(C, GetExprType(E)); 10505 10506 // Bitwise-and uses the *infinum* of the two source ranges. 10507 case BO_And: 10508 case BO_AndAssign: 10509 Combine = IntRange::bit_and; 10510 break; 10511 10512 // Left shift gets black-listed based on a judgement call. 10513 case BO_Shl: 10514 // ...except that we want to treat '1 << (blah)' as logically 10515 // positive. It's an important idiom. 10516 if (IntegerLiteral *I 10517 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10518 if (I->getValue() == 1) { 10519 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10520 return IntRange(R.Width, /*NonNegative*/ true); 10521 } 10522 } 10523 LLVM_FALLTHROUGH; 10524 10525 case BO_ShlAssign: 10526 return IntRange::forValueOfType(C, GetExprType(E)); 10527 10528 // Right shift by a constant can narrow its left argument. 10529 case BO_Shr: 10530 case BO_ShrAssign: { 10531 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 10532 Approximate); 10533 10534 // If the shift amount is a positive constant, drop the width by 10535 // that much. 10536 if (Optional<llvm::APSInt> shift = 10537 BO->getRHS()->getIntegerConstantExpr(C)) { 10538 if (shift->isNonNegative()) { 10539 unsigned zext = shift->getZExtValue(); 10540 if (zext >= L.Width) 10541 L.Width = (L.NonNegative ? 0 : 1); 10542 else 10543 L.Width -= zext; 10544 } 10545 } 10546 10547 return L; 10548 } 10549 10550 // Comma acts as its right operand. 10551 case BO_Comma: 10552 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10553 Approximate); 10554 10555 case BO_Add: 10556 if (!Approximate) 10557 Combine = IntRange::sum; 10558 break; 10559 10560 case BO_Sub: 10561 if (BO->getLHS()->getType()->isPointerType()) 10562 return IntRange::forValueOfType(C, GetExprType(E)); 10563 if (!Approximate) 10564 Combine = IntRange::difference; 10565 break; 10566 10567 case BO_Mul: 10568 if (!Approximate) 10569 Combine = IntRange::product; 10570 break; 10571 10572 // The width of a division result is mostly determined by the size 10573 // of the LHS. 10574 case BO_Div: { 10575 // Don't 'pre-truncate' the operands. 10576 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10577 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 10578 Approximate); 10579 10580 // If the divisor is constant, use that. 10581 if (Optional<llvm::APSInt> divisor = 10582 BO->getRHS()->getIntegerConstantExpr(C)) { 10583 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10584 if (log2 >= L.Width) 10585 L.Width = (L.NonNegative ? 0 : 1); 10586 else 10587 L.Width = std::min(L.Width - log2, MaxWidth); 10588 return L; 10589 } 10590 10591 // Otherwise, just use the LHS's width. 10592 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 10593 // could be -1. 10594 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 10595 Approximate); 10596 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10597 } 10598 10599 case BO_Rem: 10600 Combine = IntRange::rem; 10601 break; 10602 10603 // The default behavior is okay for these. 10604 case BO_Xor: 10605 case BO_Or: 10606 break; 10607 } 10608 10609 // Combine the two ranges, but limit the result to the type in which we 10610 // performed the computation. 10611 QualType T = GetExprType(E); 10612 unsigned opWidth = C.getIntWidth(T); 10613 IntRange L = 10614 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 10615 IntRange R = 10616 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 10617 IntRange C = Combine(L, R); 10618 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 10619 C.Width = std::min(C.Width, MaxWidth); 10620 return C; 10621 } 10622 10623 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10624 switch (UO->getOpcode()) { 10625 // Boolean-valued operations are white-listed. 10626 case UO_LNot: 10627 return IntRange::forBoolType(); 10628 10629 // Operations with opaque sources are black-listed. 10630 case UO_Deref: 10631 case UO_AddrOf: // should be impossible 10632 return IntRange::forValueOfType(C, GetExprType(E)); 10633 10634 default: 10635 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 10636 Approximate); 10637 } 10638 } 10639 10640 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10641 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 10642 Approximate); 10643 10644 if (const auto *BitField = E->getSourceBitField()) 10645 return IntRange(BitField->getBitWidthValue(C), 10646 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10647 10648 return IntRange::forValueOfType(C, GetExprType(E)); 10649 } 10650 10651 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10652 bool InConstantContext, bool Approximate) { 10653 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 10654 Approximate); 10655 } 10656 10657 /// Checks whether the given value, which currently has the given 10658 /// source semantics, has the same value when coerced through the 10659 /// target semantics. 10660 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10661 const llvm::fltSemantics &Src, 10662 const llvm::fltSemantics &Tgt) { 10663 llvm::APFloat truncated = value; 10664 10665 bool ignored; 10666 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10667 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10668 10669 return truncated.bitwiseIsEqual(value); 10670 } 10671 10672 /// Checks whether the given value, which currently has the given 10673 /// source semantics, has the same value when coerced through the 10674 /// target semantics. 10675 /// 10676 /// The value might be a vector of floats (or a complex number). 10677 static bool IsSameFloatAfterCast(const APValue &value, 10678 const llvm::fltSemantics &Src, 10679 const llvm::fltSemantics &Tgt) { 10680 if (value.isFloat()) 10681 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10682 10683 if (value.isVector()) { 10684 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10685 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10686 return false; 10687 return true; 10688 } 10689 10690 assert(value.isComplexFloat()); 10691 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10692 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10693 } 10694 10695 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10696 bool IsListInit = false); 10697 10698 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10699 // Suppress cases where we are comparing against an enum constant. 10700 if (const DeclRefExpr *DR = 10701 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10702 if (isa<EnumConstantDecl>(DR->getDecl())) 10703 return true; 10704 10705 // Suppress cases where the value is expanded from a macro, unless that macro 10706 // is how a language represents a boolean literal. This is the case in both C 10707 // and Objective-C. 10708 SourceLocation BeginLoc = E->getBeginLoc(); 10709 if (BeginLoc.isMacroID()) { 10710 StringRef MacroName = Lexer::getImmediateMacroName( 10711 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10712 return MacroName != "YES" && MacroName != "NO" && 10713 MacroName != "true" && MacroName != "false"; 10714 } 10715 10716 return false; 10717 } 10718 10719 static bool isKnownToHaveUnsignedValue(Expr *E) { 10720 return E->getType()->isIntegerType() && 10721 (!E->getType()->isSignedIntegerType() || 10722 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10723 } 10724 10725 namespace { 10726 /// The promoted range of values of a type. In general this has the 10727 /// following structure: 10728 /// 10729 /// |-----------| . . . |-----------| 10730 /// ^ ^ ^ ^ 10731 /// Min HoleMin HoleMax Max 10732 /// 10733 /// ... where there is only a hole if a signed type is promoted to unsigned 10734 /// (in which case Min and Max are the smallest and largest representable 10735 /// values). 10736 struct PromotedRange { 10737 // Min, or HoleMax if there is a hole. 10738 llvm::APSInt PromotedMin; 10739 // Max, or HoleMin if there is a hole. 10740 llvm::APSInt PromotedMax; 10741 10742 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10743 if (R.Width == 0) 10744 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10745 else if (R.Width >= BitWidth && !Unsigned) { 10746 // Promotion made the type *narrower*. This happens when promoting 10747 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10748 // Treat all values of 'signed int' as being in range for now. 10749 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10750 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10751 } else { 10752 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10753 .extOrTrunc(BitWidth); 10754 PromotedMin.setIsUnsigned(Unsigned); 10755 10756 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10757 .extOrTrunc(BitWidth); 10758 PromotedMax.setIsUnsigned(Unsigned); 10759 } 10760 } 10761 10762 // Determine whether this range is contiguous (has no hole). 10763 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10764 10765 // Where a constant value is within the range. 10766 enum ComparisonResult { 10767 LT = 0x1, 10768 LE = 0x2, 10769 GT = 0x4, 10770 GE = 0x8, 10771 EQ = 0x10, 10772 NE = 0x20, 10773 InRangeFlag = 0x40, 10774 10775 Less = LE | LT | NE, 10776 Min = LE | InRangeFlag, 10777 InRange = InRangeFlag, 10778 Max = GE | InRangeFlag, 10779 Greater = GE | GT | NE, 10780 10781 OnlyValue = LE | GE | EQ | InRangeFlag, 10782 InHole = NE 10783 }; 10784 10785 ComparisonResult compare(const llvm::APSInt &Value) const { 10786 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10787 Value.isUnsigned() == PromotedMin.isUnsigned()); 10788 if (!isContiguous()) { 10789 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10790 if (Value.isMinValue()) return Min; 10791 if (Value.isMaxValue()) return Max; 10792 if (Value >= PromotedMin) return InRange; 10793 if (Value <= PromotedMax) return InRange; 10794 return InHole; 10795 } 10796 10797 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10798 case -1: return Less; 10799 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10800 case 1: 10801 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10802 case -1: return InRange; 10803 case 0: return Max; 10804 case 1: return Greater; 10805 } 10806 } 10807 10808 llvm_unreachable("impossible compare result"); 10809 } 10810 10811 static llvm::Optional<StringRef> 10812 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10813 if (Op == BO_Cmp) { 10814 ComparisonResult LTFlag = LT, GTFlag = GT; 10815 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10816 10817 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10818 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10819 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10820 return llvm::None; 10821 } 10822 10823 ComparisonResult TrueFlag, FalseFlag; 10824 if (Op == BO_EQ) { 10825 TrueFlag = EQ; 10826 FalseFlag = NE; 10827 } else if (Op == BO_NE) { 10828 TrueFlag = NE; 10829 FalseFlag = EQ; 10830 } else { 10831 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10832 TrueFlag = LT; 10833 FalseFlag = GE; 10834 } else { 10835 TrueFlag = GT; 10836 FalseFlag = LE; 10837 } 10838 if (Op == BO_GE || Op == BO_LE) 10839 std::swap(TrueFlag, FalseFlag); 10840 } 10841 if (R & TrueFlag) 10842 return StringRef("true"); 10843 if (R & FalseFlag) 10844 return StringRef("false"); 10845 return llvm::None; 10846 } 10847 }; 10848 } 10849 10850 static bool HasEnumType(Expr *E) { 10851 // Strip off implicit integral promotions. 10852 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10853 if (ICE->getCastKind() != CK_IntegralCast && 10854 ICE->getCastKind() != CK_NoOp) 10855 break; 10856 E = ICE->getSubExpr(); 10857 } 10858 10859 return E->getType()->isEnumeralType(); 10860 } 10861 10862 static int classifyConstantValue(Expr *Constant) { 10863 // The values of this enumeration are used in the diagnostics 10864 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10865 enum ConstantValueKind { 10866 Miscellaneous = 0, 10867 LiteralTrue, 10868 LiteralFalse 10869 }; 10870 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10871 return BL->getValue() ? ConstantValueKind::LiteralTrue 10872 : ConstantValueKind::LiteralFalse; 10873 return ConstantValueKind::Miscellaneous; 10874 } 10875 10876 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10877 Expr *Constant, Expr *Other, 10878 const llvm::APSInt &Value, 10879 bool RhsConstant) { 10880 if (S.inTemplateInstantiation()) 10881 return false; 10882 10883 Expr *OriginalOther = Other; 10884 10885 Constant = Constant->IgnoreParenImpCasts(); 10886 Other = Other->IgnoreParenImpCasts(); 10887 10888 // Suppress warnings on tautological comparisons between values of the same 10889 // enumeration type. There are only two ways we could warn on this: 10890 // - If the constant is outside the range of representable values of 10891 // the enumeration. In such a case, we should warn about the cast 10892 // to enumeration type, not about the comparison. 10893 // - If the constant is the maximum / minimum in-range value. For an 10894 // enumeratin type, such comparisons can be meaningful and useful. 10895 if (Constant->getType()->isEnumeralType() && 10896 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10897 return false; 10898 10899 IntRange OtherValueRange = GetExprRange( 10900 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 10901 10902 QualType OtherT = Other->getType(); 10903 if (const auto *AT = OtherT->getAs<AtomicType>()) 10904 OtherT = AT->getValueType(); 10905 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 10906 10907 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10908 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 10909 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10910 S.NSAPIObj->isObjCBOOLType(OtherT) && 10911 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10912 10913 // Whether we're treating Other as being a bool because of the form of 10914 // expression despite it having another type (typically 'int' in C). 10915 bool OtherIsBooleanDespiteType = 10916 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10917 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10918 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 10919 10920 // Check if all values in the range of possible values of this expression 10921 // lead to the same comparison outcome. 10922 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 10923 Value.isUnsigned()); 10924 auto Cmp = OtherPromotedValueRange.compare(Value); 10925 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10926 if (!Result) 10927 return false; 10928 10929 // Also consider the range determined by the type alone. This allows us to 10930 // classify the warning under the proper diagnostic group. 10931 bool TautologicalTypeCompare = false; 10932 { 10933 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 10934 Value.isUnsigned()); 10935 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 10936 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 10937 RhsConstant)) { 10938 TautologicalTypeCompare = true; 10939 Cmp = TypeCmp; 10940 Result = TypeResult; 10941 } 10942 } 10943 10944 // Don't warn if the non-constant operand actually always evaluates to the 10945 // same value. 10946 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 10947 return false; 10948 10949 // Suppress the diagnostic for an in-range comparison if the constant comes 10950 // from a macro or enumerator. We don't want to diagnose 10951 // 10952 // some_long_value <= INT_MAX 10953 // 10954 // when sizeof(int) == sizeof(long). 10955 bool InRange = Cmp & PromotedRange::InRangeFlag; 10956 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10957 return false; 10958 10959 // A comparison of an unsigned bit-field against 0 is really a type problem, 10960 // even though at the type level the bit-field might promote to 'signed int'. 10961 if (Other->refersToBitField() && InRange && Value == 0 && 10962 Other->getType()->isUnsignedIntegerOrEnumerationType()) 10963 TautologicalTypeCompare = true; 10964 10965 // If this is a comparison to an enum constant, include that 10966 // constant in the diagnostic. 10967 const EnumConstantDecl *ED = nullptr; 10968 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10969 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10970 10971 // Should be enough for uint128 (39 decimal digits) 10972 SmallString<64> PrettySourceValue; 10973 llvm::raw_svector_ostream OS(PrettySourceValue); 10974 if (ED) { 10975 OS << '\'' << *ED << "' (" << Value << ")"; 10976 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10977 Constant->IgnoreParenImpCasts())) { 10978 OS << (BL->getValue() ? "YES" : "NO"); 10979 } else { 10980 OS << Value; 10981 } 10982 10983 if (!TautologicalTypeCompare) { 10984 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 10985 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 10986 << E->getOpcodeStr() << OS.str() << *Result 10987 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10988 return true; 10989 } 10990 10991 if (IsObjCSignedCharBool) { 10992 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10993 S.PDiag(diag::warn_tautological_compare_objc_bool) 10994 << OS.str() << *Result); 10995 return true; 10996 } 10997 10998 // FIXME: We use a somewhat different formatting for the in-range cases and 10999 // cases involving boolean values for historical reasons. We should pick a 11000 // consistent way of presenting these diagnostics. 11001 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11002 11003 S.DiagRuntimeBehavior( 11004 E->getOperatorLoc(), E, 11005 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11006 : diag::warn_tautological_bool_compare) 11007 << OS.str() << classifyConstantValue(Constant) << OtherT 11008 << OtherIsBooleanDespiteType << *Result 11009 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11010 } else { 11011 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11012 ? (HasEnumType(OriginalOther) 11013 ? diag::warn_unsigned_enum_always_true_comparison 11014 : diag::warn_unsigned_always_true_comparison) 11015 : diag::warn_tautological_constant_compare; 11016 11017 S.Diag(E->getOperatorLoc(), Diag) 11018 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11019 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11020 } 11021 11022 return true; 11023 } 11024 11025 /// Analyze the operands of the given comparison. Implements the 11026 /// fallback case from AnalyzeComparison. 11027 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11028 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11029 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11030 } 11031 11032 /// Implements -Wsign-compare. 11033 /// 11034 /// \param E the binary operator to check for warnings 11035 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11036 // The type the comparison is being performed in. 11037 QualType T = E->getLHS()->getType(); 11038 11039 // Only analyze comparison operators where both sides have been converted to 11040 // the same type. 11041 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11042 return AnalyzeImpConvsInComparison(S, E); 11043 11044 // Don't analyze value-dependent comparisons directly. 11045 if (E->isValueDependent()) 11046 return AnalyzeImpConvsInComparison(S, E); 11047 11048 Expr *LHS = E->getLHS(); 11049 Expr *RHS = E->getRHS(); 11050 11051 if (T->isIntegralType(S.Context)) { 11052 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11053 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11054 11055 // We don't care about expressions whose result is a constant. 11056 if (RHSValue && LHSValue) 11057 return AnalyzeImpConvsInComparison(S, E); 11058 11059 // We only care about expressions where just one side is literal 11060 if ((bool)RHSValue ^ (bool)LHSValue) { 11061 // Is the constant on the RHS or LHS? 11062 const bool RhsConstant = (bool)RHSValue; 11063 Expr *Const = RhsConstant ? RHS : LHS; 11064 Expr *Other = RhsConstant ? LHS : RHS; 11065 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11066 11067 // Check whether an integer constant comparison results in a value 11068 // of 'true' or 'false'. 11069 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11070 return AnalyzeImpConvsInComparison(S, E); 11071 } 11072 } 11073 11074 if (!T->hasUnsignedIntegerRepresentation()) { 11075 // We don't do anything special if this isn't an unsigned integral 11076 // comparison: we're only interested in integral comparisons, and 11077 // signed comparisons only happen in cases we don't care to warn about. 11078 return AnalyzeImpConvsInComparison(S, E); 11079 } 11080 11081 LHS = LHS->IgnoreParenImpCasts(); 11082 RHS = RHS->IgnoreParenImpCasts(); 11083 11084 if (!S.getLangOpts().CPlusPlus) { 11085 // Avoid warning about comparison of integers with different signs when 11086 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11087 // the type of `E`. 11088 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11089 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11090 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11091 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11092 } 11093 11094 // Check to see if one of the (unmodified) operands is of different 11095 // signedness. 11096 Expr *signedOperand, *unsignedOperand; 11097 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11098 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11099 "unsigned comparison between two signed integer expressions?"); 11100 signedOperand = LHS; 11101 unsignedOperand = RHS; 11102 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11103 signedOperand = RHS; 11104 unsignedOperand = LHS; 11105 } else { 11106 return AnalyzeImpConvsInComparison(S, E); 11107 } 11108 11109 // Otherwise, calculate the effective range of the signed operand. 11110 IntRange signedRange = GetExprRange( 11111 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11112 11113 // Go ahead and analyze implicit conversions in the operands. Note 11114 // that we skip the implicit conversions on both sides. 11115 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11116 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11117 11118 // If the signed range is non-negative, -Wsign-compare won't fire. 11119 if (signedRange.NonNegative) 11120 return; 11121 11122 // For (in)equality comparisons, if the unsigned operand is a 11123 // constant which cannot collide with a overflowed signed operand, 11124 // then reinterpreting the signed operand as unsigned will not 11125 // change the result of the comparison. 11126 if (E->isEqualityOp()) { 11127 unsigned comparisonWidth = S.Context.getIntWidth(T); 11128 IntRange unsignedRange = 11129 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11130 /*Approximate*/ true); 11131 11132 // We should never be unable to prove that the unsigned operand is 11133 // non-negative. 11134 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11135 11136 if (unsignedRange.Width < comparisonWidth) 11137 return; 11138 } 11139 11140 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11141 S.PDiag(diag::warn_mixed_sign_comparison) 11142 << LHS->getType() << RHS->getType() 11143 << LHS->getSourceRange() << RHS->getSourceRange()); 11144 } 11145 11146 /// Analyzes an attempt to assign the given value to a bitfield. 11147 /// 11148 /// Returns true if there was something fishy about the attempt. 11149 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11150 SourceLocation InitLoc) { 11151 assert(Bitfield->isBitField()); 11152 if (Bitfield->isInvalidDecl()) 11153 return false; 11154 11155 // White-list bool bitfields. 11156 QualType BitfieldType = Bitfield->getType(); 11157 if (BitfieldType->isBooleanType()) 11158 return false; 11159 11160 if (BitfieldType->isEnumeralType()) { 11161 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11162 // If the underlying enum type was not explicitly specified as an unsigned 11163 // type and the enum contain only positive values, MSVC++ will cause an 11164 // inconsistency by storing this as a signed type. 11165 if (S.getLangOpts().CPlusPlus11 && 11166 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11167 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11168 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11169 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11170 << BitfieldEnumDecl; 11171 } 11172 } 11173 11174 if (Bitfield->getType()->isBooleanType()) 11175 return false; 11176 11177 // Ignore value- or type-dependent expressions. 11178 if (Bitfield->getBitWidth()->isValueDependent() || 11179 Bitfield->getBitWidth()->isTypeDependent() || 11180 Init->isValueDependent() || 11181 Init->isTypeDependent()) 11182 return false; 11183 11184 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11185 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11186 11187 Expr::EvalResult Result; 11188 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11189 Expr::SE_AllowSideEffects)) { 11190 // The RHS is not constant. If the RHS has an enum type, make sure the 11191 // bitfield is wide enough to hold all the values of the enum without 11192 // truncation. 11193 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11194 EnumDecl *ED = EnumTy->getDecl(); 11195 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11196 11197 // Enum types are implicitly signed on Windows, so check if there are any 11198 // negative enumerators to see if the enum was intended to be signed or 11199 // not. 11200 bool SignedEnum = ED->getNumNegativeBits() > 0; 11201 11202 // Check for surprising sign changes when assigning enum values to a 11203 // bitfield of different signedness. If the bitfield is signed and we 11204 // have exactly the right number of bits to store this unsigned enum, 11205 // suggest changing the enum to an unsigned type. This typically happens 11206 // on Windows where unfixed enums always use an underlying type of 'int'. 11207 unsigned DiagID = 0; 11208 if (SignedEnum && !SignedBitfield) { 11209 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11210 } else if (SignedBitfield && !SignedEnum && 11211 ED->getNumPositiveBits() == FieldWidth) { 11212 DiagID = diag::warn_signed_bitfield_enum_conversion; 11213 } 11214 11215 if (DiagID) { 11216 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11217 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11218 SourceRange TypeRange = 11219 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11220 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11221 << SignedEnum << TypeRange; 11222 } 11223 11224 // Compute the required bitwidth. If the enum has negative values, we need 11225 // one more bit than the normal number of positive bits to represent the 11226 // sign bit. 11227 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11228 ED->getNumNegativeBits()) 11229 : ED->getNumPositiveBits(); 11230 11231 // Check the bitwidth. 11232 if (BitsNeeded > FieldWidth) { 11233 Expr *WidthExpr = Bitfield->getBitWidth(); 11234 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11235 << Bitfield << ED; 11236 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11237 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11238 } 11239 } 11240 11241 return false; 11242 } 11243 11244 llvm::APSInt Value = Result.Val.getInt(); 11245 11246 unsigned OriginalWidth = Value.getBitWidth(); 11247 11248 if (!Value.isSigned() || Value.isNegative()) 11249 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11250 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11251 OriginalWidth = Value.getMinSignedBits(); 11252 11253 if (OriginalWidth <= FieldWidth) 11254 return false; 11255 11256 // Compute the value which the bitfield will contain. 11257 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11258 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11259 11260 // Check whether the stored value is equal to the original value. 11261 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11262 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11263 return false; 11264 11265 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11266 // therefore don't strictly fit into a signed bitfield of width 1. 11267 if (FieldWidth == 1 && Value == 1) 11268 return false; 11269 11270 std::string PrettyValue = Value.toString(10); 11271 std::string PrettyTrunc = TruncatedValue.toString(10); 11272 11273 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11274 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11275 << Init->getSourceRange(); 11276 11277 return true; 11278 } 11279 11280 /// Analyze the given simple or compound assignment for warning-worthy 11281 /// operations. 11282 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11283 // Just recurse on the LHS. 11284 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11285 11286 // We want to recurse on the RHS as normal unless we're assigning to 11287 // a bitfield. 11288 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11289 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11290 E->getOperatorLoc())) { 11291 // Recurse, ignoring any implicit conversions on the RHS. 11292 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11293 E->getOperatorLoc()); 11294 } 11295 } 11296 11297 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11298 11299 // Diagnose implicitly sequentially-consistent atomic assignment. 11300 if (E->getLHS()->getType()->isAtomicType()) 11301 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11302 } 11303 11304 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11305 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11306 SourceLocation CContext, unsigned diag, 11307 bool pruneControlFlow = false) { 11308 if (pruneControlFlow) { 11309 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11310 S.PDiag(diag) 11311 << SourceType << T << E->getSourceRange() 11312 << SourceRange(CContext)); 11313 return; 11314 } 11315 S.Diag(E->getExprLoc(), diag) 11316 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11317 } 11318 11319 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11320 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11321 SourceLocation CContext, 11322 unsigned diag, bool pruneControlFlow = false) { 11323 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11324 } 11325 11326 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11327 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11328 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11329 } 11330 11331 static void adornObjCBoolConversionDiagWithTernaryFixit( 11332 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11333 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11334 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11335 Ignored = OVE->getSourceExpr(); 11336 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11337 isa<BinaryOperator>(Ignored) || 11338 isa<CXXOperatorCallExpr>(Ignored); 11339 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11340 if (NeedsParens) 11341 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11342 << FixItHint::CreateInsertion(EndLoc, ")"); 11343 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11344 } 11345 11346 /// Diagnose an implicit cast from a floating point value to an integer value. 11347 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11348 SourceLocation CContext) { 11349 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11350 const bool PruneWarnings = S.inTemplateInstantiation(); 11351 11352 Expr *InnerE = E->IgnoreParenImpCasts(); 11353 // We also want to warn on, e.g., "int i = -1.234" 11354 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11355 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11356 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11357 11358 const bool IsLiteral = 11359 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11360 11361 llvm::APFloat Value(0.0); 11362 bool IsConstant = 11363 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11364 if (!IsConstant) { 11365 if (isObjCSignedCharBool(S, T)) { 11366 return adornObjCBoolConversionDiagWithTernaryFixit( 11367 S, E, 11368 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11369 << E->getType()); 11370 } 11371 11372 return DiagnoseImpCast(S, E, T, CContext, 11373 diag::warn_impcast_float_integer, PruneWarnings); 11374 } 11375 11376 bool isExact = false; 11377 11378 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11379 T->hasUnsignedIntegerRepresentation()); 11380 llvm::APFloat::opStatus Result = Value.convertToInteger( 11381 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11382 11383 // FIXME: Force the precision of the source value down so we don't print 11384 // digits which are usually useless (we don't really care here if we 11385 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11386 // would automatically print the shortest representation, but it's a bit 11387 // tricky to implement. 11388 SmallString<16> PrettySourceValue; 11389 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11390 precision = (precision * 59 + 195) / 196; 11391 Value.toString(PrettySourceValue, precision); 11392 11393 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11394 return adornObjCBoolConversionDiagWithTernaryFixit( 11395 S, E, 11396 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11397 << PrettySourceValue); 11398 } 11399 11400 if (Result == llvm::APFloat::opOK && isExact) { 11401 if (IsLiteral) return; 11402 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11403 PruneWarnings); 11404 } 11405 11406 // Conversion of a floating-point value to a non-bool integer where the 11407 // integral part cannot be represented by the integer type is undefined. 11408 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11409 return DiagnoseImpCast( 11410 S, E, T, CContext, 11411 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11412 : diag::warn_impcast_float_to_integer_out_of_range, 11413 PruneWarnings); 11414 11415 unsigned DiagID = 0; 11416 if (IsLiteral) { 11417 // Warn on floating point literal to integer. 11418 DiagID = diag::warn_impcast_literal_float_to_integer; 11419 } else if (IntegerValue == 0) { 11420 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11421 return DiagnoseImpCast(S, E, T, CContext, 11422 diag::warn_impcast_float_integer, PruneWarnings); 11423 } 11424 // Warn on non-zero to zero conversion. 11425 DiagID = diag::warn_impcast_float_to_integer_zero; 11426 } else { 11427 if (IntegerValue.isUnsigned()) { 11428 if (!IntegerValue.isMaxValue()) { 11429 return DiagnoseImpCast(S, E, T, CContext, 11430 diag::warn_impcast_float_integer, PruneWarnings); 11431 } 11432 } else { // IntegerValue.isSigned() 11433 if (!IntegerValue.isMaxSignedValue() && 11434 !IntegerValue.isMinSignedValue()) { 11435 return DiagnoseImpCast(S, E, T, CContext, 11436 diag::warn_impcast_float_integer, PruneWarnings); 11437 } 11438 } 11439 // Warn on evaluatable floating point expression to integer conversion. 11440 DiagID = diag::warn_impcast_float_to_integer; 11441 } 11442 11443 SmallString<16> PrettyTargetValue; 11444 if (IsBool) 11445 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11446 else 11447 IntegerValue.toString(PrettyTargetValue); 11448 11449 if (PruneWarnings) { 11450 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11451 S.PDiag(DiagID) 11452 << E->getType() << T.getUnqualifiedType() 11453 << PrettySourceValue << PrettyTargetValue 11454 << E->getSourceRange() << SourceRange(CContext)); 11455 } else { 11456 S.Diag(E->getExprLoc(), DiagID) 11457 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11458 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11459 } 11460 } 11461 11462 /// Analyze the given compound assignment for the possible losing of 11463 /// floating-point precision. 11464 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11465 assert(isa<CompoundAssignOperator>(E) && 11466 "Must be compound assignment operation"); 11467 // Recurse on the LHS and RHS in here 11468 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11469 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11470 11471 if (E->getLHS()->getType()->isAtomicType()) 11472 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11473 11474 // Now check the outermost expression 11475 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11476 const auto *RBT = cast<CompoundAssignOperator>(E) 11477 ->getComputationResultType() 11478 ->getAs<BuiltinType>(); 11479 11480 // The below checks assume source is floating point. 11481 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11482 11483 // If source is floating point but target is an integer. 11484 if (ResultBT->isInteger()) 11485 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11486 E->getExprLoc(), diag::warn_impcast_float_integer); 11487 11488 if (!ResultBT->isFloatingPoint()) 11489 return; 11490 11491 // If both source and target are floating points, warn about losing precision. 11492 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11493 QualType(ResultBT, 0), QualType(RBT, 0)); 11494 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11495 // warn about dropping FP rank. 11496 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11497 diag::warn_impcast_float_result_precision); 11498 } 11499 11500 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11501 IntRange Range) { 11502 if (!Range.Width) return "0"; 11503 11504 llvm::APSInt ValueInRange = Value; 11505 ValueInRange.setIsSigned(!Range.NonNegative); 11506 ValueInRange = ValueInRange.trunc(Range.Width); 11507 return ValueInRange.toString(10); 11508 } 11509 11510 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11511 if (!isa<ImplicitCastExpr>(Ex)) 11512 return false; 11513 11514 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11515 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11516 const Type *Source = 11517 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11518 if (Target->isDependentType()) 11519 return false; 11520 11521 const BuiltinType *FloatCandidateBT = 11522 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11523 const Type *BoolCandidateType = ToBool ? Target : Source; 11524 11525 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11526 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11527 } 11528 11529 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11530 SourceLocation CC) { 11531 unsigned NumArgs = TheCall->getNumArgs(); 11532 for (unsigned i = 0; i < NumArgs; ++i) { 11533 Expr *CurrA = TheCall->getArg(i); 11534 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11535 continue; 11536 11537 bool IsSwapped = ((i > 0) && 11538 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11539 IsSwapped |= ((i < (NumArgs - 1)) && 11540 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11541 if (IsSwapped) { 11542 // Warn on this floating-point to bool conversion. 11543 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11544 CurrA->getType(), CC, 11545 diag::warn_impcast_floating_point_to_bool); 11546 } 11547 } 11548 } 11549 11550 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11551 SourceLocation CC) { 11552 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11553 E->getExprLoc())) 11554 return; 11555 11556 // Don't warn on functions which have return type nullptr_t. 11557 if (isa<CallExpr>(E)) 11558 return; 11559 11560 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11561 const Expr::NullPointerConstantKind NullKind = 11562 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11563 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11564 return; 11565 11566 // Return if target type is a safe conversion. 11567 if (T->isAnyPointerType() || T->isBlockPointerType() || 11568 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11569 return; 11570 11571 SourceLocation Loc = E->getSourceRange().getBegin(); 11572 11573 // Venture through the macro stacks to get to the source of macro arguments. 11574 // The new location is a better location than the complete location that was 11575 // passed in. 11576 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11577 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11578 11579 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11580 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11581 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11582 Loc, S.SourceMgr, S.getLangOpts()); 11583 if (MacroName == "NULL") 11584 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11585 } 11586 11587 // Only warn if the null and context location are in the same macro expansion. 11588 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11589 return; 11590 11591 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11592 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11593 << FixItHint::CreateReplacement(Loc, 11594 S.getFixItZeroLiteralForType(T, Loc)); 11595 } 11596 11597 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11598 ObjCArrayLiteral *ArrayLiteral); 11599 11600 static void 11601 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11602 ObjCDictionaryLiteral *DictionaryLiteral); 11603 11604 /// Check a single element within a collection literal against the 11605 /// target element type. 11606 static void checkObjCCollectionLiteralElement(Sema &S, 11607 QualType TargetElementType, 11608 Expr *Element, 11609 unsigned ElementKind) { 11610 // Skip a bitcast to 'id' or qualified 'id'. 11611 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11612 if (ICE->getCastKind() == CK_BitCast && 11613 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11614 Element = ICE->getSubExpr(); 11615 } 11616 11617 QualType ElementType = Element->getType(); 11618 ExprResult ElementResult(Element); 11619 if (ElementType->getAs<ObjCObjectPointerType>() && 11620 S.CheckSingleAssignmentConstraints(TargetElementType, 11621 ElementResult, 11622 false, false) 11623 != Sema::Compatible) { 11624 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11625 << ElementType << ElementKind << TargetElementType 11626 << Element->getSourceRange(); 11627 } 11628 11629 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11630 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11631 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11632 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11633 } 11634 11635 /// Check an Objective-C array literal being converted to the given 11636 /// target type. 11637 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11638 ObjCArrayLiteral *ArrayLiteral) { 11639 if (!S.NSArrayDecl) 11640 return; 11641 11642 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11643 if (!TargetObjCPtr) 11644 return; 11645 11646 if (TargetObjCPtr->isUnspecialized() || 11647 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11648 != S.NSArrayDecl->getCanonicalDecl()) 11649 return; 11650 11651 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11652 if (TypeArgs.size() != 1) 11653 return; 11654 11655 QualType TargetElementType = TypeArgs[0]; 11656 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11657 checkObjCCollectionLiteralElement(S, TargetElementType, 11658 ArrayLiteral->getElement(I), 11659 0); 11660 } 11661 } 11662 11663 /// Check an Objective-C dictionary literal being converted to the given 11664 /// target type. 11665 static void 11666 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11667 ObjCDictionaryLiteral *DictionaryLiteral) { 11668 if (!S.NSDictionaryDecl) 11669 return; 11670 11671 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11672 if (!TargetObjCPtr) 11673 return; 11674 11675 if (TargetObjCPtr->isUnspecialized() || 11676 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11677 != S.NSDictionaryDecl->getCanonicalDecl()) 11678 return; 11679 11680 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11681 if (TypeArgs.size() != 2) 11682 return; 11683 11684 QualType TargetKeyType = TypeArgs[0]; 11685 QualType TargetObjectType = TypeArgs[1]; 11686 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11687 auto Element = DictionaryLiteral->getKeyValueElement(I); 11688 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11689 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11690 } 11691 } 11692 11693 // Helper function to filter out cases for constant width constant conversion. 11694 // Don't warn on char array initialization or for non-decimal values. 11695 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11696 SourceLocation CC) { 11697 // If initializing from a constant, and the constant starts with '0', 11698 // then it is a binary, octal, or hexadecimal. Allow these constants 11699 // to fill all the bits, even if there is a sign change. 11700 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11701 const char FirstLiteralCharacter = 11702 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11703 if (FirstLiteralCharacter == '0') 11704 return false; 11705 } 11706 11707 // If the CC location points to a '{', and the type is char, then assume 11708 // assume it is an array initialization. 11709 if (CC.isValid() && T->isCharType()) { 11710 const char FirstContextCharacter = 11711 S.getSourceManager().getCharacterData(CC)[0]; 11712 if (FirstContextCharacter == '{') 11713 return false; 11714 } 11715 11716 return true; 11717 } 11718 11719 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11720 const auto *IL = dyn_cast<IntegerLiteral>(E); 11721 if (!IL) { 11722 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11723 if (UO->getOpcode() == UO_Minus) 11724 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11725 } 11726 } 11727 11728 return IL; 11729 } 11730 11731 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11732 E = E->IgnoreParenImpCasts(); 11733 SourceLocation ExprLoc = E->getExprLoc(); 11734 11735 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11736 BinaryOperator::Opcode Opc = BO->getOpcode(); 11737 Expr::EvalResult Result; 11738 // Do not diagnose unsigned shifts. 11739 if (Opc == BO_Shl) { 11740 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11741 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11742 if (LHS && LHS->getValue() == 0) 11743 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11744 else if (!E->isValueDependent() && LHS && RHS && 11745 RHS->getValue().isNonNegative() && 11746 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11747 S.Diag(ExprLoc, diag::warn_left_shift_always) 11748 << (Result.Val.getInt() != 0); 11749 else if (E->getType()->isSignedIntegerType()) 11750 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11751 } 11752 } 11753 11754 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11755 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11756 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11757 if (!LHS || !RHS) 11758 return; 11759 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11760 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11761 // Do not diagnose common idioms. 11762 return; 11763 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11764 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11765 } 11766 } 11767 11768 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11769 SourceLocation CC, 11770 bool *ICContext = nullptr, 11771 bool IsListInit = false) { 11772 if (E->isTypeDependent() || E->isValueDependent()) return; 11773 11774 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11775 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11776 if (Source == Target) return; 11777 if (Target->isDependentType()) return; 11778 11779 // If the conversion context location is invalid don't complain. We also 11780 // don't want to emit a warning if the issue occurs from the expansion of 11781 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11782 // delay this check as long as possible. Once we detect we are in that 11783 // scenario, we just return. 11784 if (CC.isInvalid()) 11785 return; 11786 11787 if (Source->isAtomicType()) 11788 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11789 11790 // Diagnose implicit casts to bool. 11791 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11792 if (isa<StringLiteral>(E)) 11793 // Warn on string literal to bool. Checks for string literals in logical 11794 // and expressions, for instance, assert(0 && "error here"), are 11795 // prevented by a check in AnalyzeImplicitConversions(). 11796 return DiagnoseImpCast(S, E, T, CC, 11797 diag::warn_impcast_string_literal_to_bool); 11798 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11799 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11800 // This covers the literal expressions that evaluate to Objective-C 11801 // objects. 11802 return DiagnoseImpCast(S, E, T, CC, 11803 diag::warn_impcast_objective_c_literal_to_bool); 11804 } 11805 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11806 // Warn on pointer to bool conversion that is always true. 11807 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11808 SourceRange(CC)); 11809 } 11810 } 11811 11812 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11813 // is a typedef for signed char (macOS), then that constant value has to be 1 11814 // or 0. 11815 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11816 Expr::EvalResult Result; 11817 if (E->EvaluateAsInt(Result, S.getASTContext(), 11818 Expr::SE_AllowSideEffects)) { 11819 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11820 adornObjCBoolConversionDiagWithTernaryFixit( 11821 S, E, 11822 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11823 << Result.Val.getInt().toString(10)); 11824 } 11825 return; 11826 } 11827 } 11828 11829 // Check implicit casts from Objective-C collection literals to specialized 11830 // collection types, e.g., NSArray<NSString *> *. 11831 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11832 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11833 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11834 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11835 11836 // Strip vector types. 11837 if (isa<VectorType>(Source)) { 11838 if (!isa<VectorType>(Target)) { 11839 if (S.SourceMgr.isInSystemMacro(CC)) 11840 return; 11841 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11842 } 11843 11844 // If the vector cast is cast between two vectors of the same size, it is 11845 // a bitcast, not a conversion. 11846 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11847 return; 11848 11849 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11850 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11851 } 11852 if (auto VecTy = dyn_cast<VectorType>(Target)) 11853 Target = VecTy->getElementType().getTypePtr(); 11854 11855 // Strip complex types. 11856 if (isa<ComplexType>(Source)) { 11857 if (!isa<ComplexType>(Target)) { 11858 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11859 return; 11860 11861 return DiagnoseImpCast(S, E, T, CC, 11862 S.getLangOpts().CPlusPlus 11863 ? diag::err_impcast_complex_scalar 11864 : diag::warn_impcast_complex_scalar); 11865 } 11866 11867 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11868 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11869 } 11870 11871 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11872 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11873 11874 // If the source is floating point... 11875 if (SourceBT && SourceBT->isFloatingPoint()) { 11876 // ...and the target is floating point... 11877 if (TargetBT && TargetBT->isFloatingPoint()) { 11878 // ...then warn if we're dropping FP rank. 11879 11880 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11881 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11882 if (Order > 0) { 11883 // Don't warn about float constants that are precisely 11884 // representable in the target type. 11885 Expr::EvalResult result; 11886 if (E->EvaluateAsRValue(result, S.Context)) { 11887 // Value might be a float, a float vector, or a float complex. 11888 if (IsSameFloatAfterCast(result.Val, 11889 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11890 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11891 return; 11892 } 11893 11894 if (S.SourceMgr.isInSystemMacro(CC)) 11895 return; 11896 11897 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11898 } 11899 // ... or possibly if we're increasing rank, too 11900 else if (Order < 0) { 11901 if (S.SourceMgr.isInSystemMacro(CC)) 11902 return; 11903 11904 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11905 } 11906 return; 11907 } 11908 11909 // If the target is integral, always warn. 11910 if (TargetBT && TargetBT->isInteger()) { 11911 if (S.SourceMgr.isInSystemMacro(CC)) 11912 return; 11913 11914 DiagnoseFloatingImpCast(S, E, T, CC); 11915 } 11916 11917 // Detect the case where a call result is converted from floating-point to 11918 // to bool, and the final argument to the call is converted from bool, to 11919 // discover this typo: 11920 // 11921 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11922 // 11923 // FIXME: This is an incredibly special case; is there some more general 11924 // way to detect this class of misplaced-parentheses bug? 11925 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11926 // Check last argument of function call to see if it is an 11927 // implicit cast from a type matching the type the result 11928 // is being cast to. 11929 CallExpr *CEx = cast<CallExpr>(E); 11930 if (unsigned NumArgs = CEx->getNumArgs()) { 11931 Expr *LastA = CEx->getArg(NumArgs - 1); 11932 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11933 if (isa<ImplicitCastExpr>(LastA) && 11934 InnerE->getType()->isBooleanType()) { 11935 // Warn on this floating-point to bool conversion 11936 DiagnoseImpCast(S, E, T, CC, 11937 diag::warn_impcast_floating_point_to_bool); 11938 } 11939 } 11940 } 11941 return; 11942 } 11943 11944 // Valid casts involving fixed point types should be accounted for here. 11945 if (Source->isFixedPointType()) { 11946 if (Target->isUnsaturatedFixedPointType()) { 11947 Expr::EvalResult Result; 11948 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11949 S.isConstantEvaluated())) { 11950 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 11951 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11952 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11953 if (Value > MaxVal || Value < MinVal) { 11954 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11955 S.PDiag(diag::warn_impcast_fixed_point_range) 11956 << Value.toString() << T 11957 << E->getSourceRange() 11958 << clang::SourceRange(CC)); 11959 return; 11960 } 11961 } 11962 } else if (Target->isIntegerType()) { 11963 Expr::EvalResult Result; 11964 if (!S.isConstantEvaluated() && 11965 E->EvaluateAsFixedPoint(Result, S.Context, 11966 Expr::SE_AllowSideEffects)) { 11967 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 11968 11969 bool Overflowed; 11970 llvm::APSInt IntResult = FXResult.convertToInt( 11971 S.Context.getIntWidth(T), 11972 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11973 11974 if (Overflowed) { 11975 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11976 S.PDiag(diag::warn_impcast_fixed_point_range) 11977 << FXResult.toString() << T 11978 << E->getSourceRange() 11979 << clang::SourceRange(CC)); 11980 return; 11981 } 11982 } 11983 } 11984 } else if (Target->isUnsaturatedFixedPointType()) { 11985 if (Source->isIntegerType()) { 11986 Expr::EvalResult Result; 11987 if (!S.isConstantEvaluated() && 11988 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11989 llvm::APSInt Value = Result.Val.getInt(); 11990 11991 bool Overflowed; 11992 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 11993 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11994 11995 if (Overflowed) { 11996 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11997 S.PDiag(diag::warn_impcast_fixed_point_range) 11998 << Value.toString(/*Radix=*/10) << T 11999 << E->getSourceRange() 12000 << clang::SourceRange(CC)); 12001 return; 12002 } 12003 } 12004 } 12005 } 12006 12007 // If we are casting an integer type to a floating point type without 12008 // initialization-list syntax, we might lose accuracy if the floating 12009 // point type has a narrower significand than the integer type. 12010 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12011 TargetBT->isFloatingType() && !IsListInit) { 12012 // Determine the number of precision bits in the source integer type. 12013 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12014 /*Approximate*/ true); 12015 unsigned int SourcePrecision = SourceRange.Width; 12016 12017 // Determine the number of precision bits in the 12018 // target floating point type. 12019 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12020 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12021 12022 if (SourcePrecision > 0 && TargetPrecision > 0 && 12023 SourcePrecision > TargetPrecision) { 12024 12025 if (Optional<llvm::APSInt> SourceInt = 12026 E->getIntegerConstantExpr(S.Context)) { 12027 // If the source integer is a constant, convert it to the target 12028 // floating point type. Issue a warning if the value changes 12029 // during the whole conversion. 12030 llvm::APFloat TargetFloatValue( 12031 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12032 llvm::APFloat::opStatus ConversionStatus = 12033 TargetFloatValue.convertFromAPInt( 12034 *SourceInt, SourceBT->isSignedInteger(), 12035 llvm::APFloat::rmNearestTiesToEven); 12036 12037 if (ConversionStatus != llvm::APFloat::opOK) { 12038 std::string PrettySourceValue = SourceInt->toString(10); 12039 SmallString<32> PrettyTargetValue; 12040 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12041 12042 S.DiagRuntimeBehavior( 12043 E->getExprLoc(), E, 12044 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12045 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12046 << E->getSourceRange() << clang::SourceRange(CC)); 12047 } 12048 } else { 12049 // Otherwise, the implicit conversion may lose precision. 12050 DiagnoseImpCast(S, E, T, CC, 12051 diag::warn_impcast_integer_float_precision); 12052 } 12053 } 12054 } 12055 12056 DiagnoseNullConversion(S, E, T, CC); 12057 12058 S.DiscardMisalignedMemberAddress(Target, E); 12059 12060 if (Target->isBooleanType()) 12061 DiagnoseIntInBoolContext(S, E); 12062 12063 if (!Source->isIntegerType() || !Target->isIntegerType()) 12064 return; 12065 12066 // TODO: remove this early return once the false positives for constant->bool 12067 // in templates, macros, etc, are reduced or removed. 12068 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12069 return; 12070 12071 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12072 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12073 return adornObjCBoolConversionDiagWithTernaryFixit( 12074 S, E, 12075 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12076 << E->getType()); 12077 } 12078 12079 IntRange SourceTypeRange = 12080 IntRange::forTargetOfCanonicalType(S.Context, Source); 12081 IntRange LikelySourceRange = 12082 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12083 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12084 12085 if (LikelySourceRange.Width > TargetRange.Width) { 12086 // If the source is a constant, use a default-on diagnostic. 12087 // TODO: this should happen for bitfield stores, too. 12088 Expr::EvalResult Result; 12089 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12090 S.isConstantEvaluated())) { 12091 llvm::APSInt Value(32); 12092 Value = Result.Val.getInt(); 12093 12094 if (S.SourceMgr.isInSystemMacro(CC)) 12095 return; 12096 12097 std::string PrettySourceValue = Value.toString(10); 12098 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12099 12100 S.DiagRuntimeBehavior( 12101 E->getExprLoc(), E, 12102 S.PDiag(diag::warn_impcast_integer_precision_constant) 12103 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12104 << E->getSourceRange() << SourceRange(CC)); 12105 return; 12106 } 12107 12108 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12109 if (S.SourceMgr.isInSystemMacro(CC)) 12110 return; 12111 12112 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12113 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12114 /* pruneControlFlow */ true); 12115 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12116 } 12117 12118 if (TargetRange.Width > SourceTypeRange.Width) { 12119 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12120 if (UO->getOpcode() == UO_Minus) 12121 if (Source->isUnsignedIntegerType()) { 12122 if (Target->isUnsignedIntegerType()) 12123 return DiagnoseImpCast(S, E, T, CC, 12124 diag::warn_impcast_high_order_zero_bits); 12125 if (Target->isSignedIntegerType()) 12126 return DiagnoseImpCast(S, E, T, CC, 12127 diag::warn_impcast_nonnegative_result); 12128 } 12129 } 12130 12131 if (TargetRange.Width == LikelySourceRange.Width && 12132 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12133 Source->isSignedIntegerType()) { 12134 // Warn when doing a signed to signed conversion, warn if the positive 12135 // source value is exactly the width of the target type, which will 12136 // cause a negative value to be stored. 12137 12138 Expr::EvalResult Result; 12139 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12140 !S.SourceMgr.isInSystemMacro(CC)) { 12141 llvm::APSInt Value = Result.Val.getInt(); 12142 if (isSameWidthConstantConversion(S, E, T, CC)) { 12143 std::string PrettySourceValue = Value.toString(10); 12144 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12145 12146 S.DiagRuntimeBehavior( 12147 E->getExprLoc(), E, 12148 S.PDiag(diag::warn_impcast_integer_precision_constant) 12149 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12150 << E->getSourceRange() << SourceRange(CC)); 12151 return; 12152 } 12153 } 12154 12155 // Fall through for non-constants to give a sign conversion warning. 12156 } 12157 12158 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12159 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12160 LikelySourceRange.Width == TargetRange.Width)) { 12161 if (S.SourceMgr.isInSystemMacro(CC)) 12162 return; 12163 12164 unsigned DiagID = diag::warn_impcast_integer_sign; 12165 12166 // Traditionally, gcc has warned about this under -Wsign-compare. 12167 // We also want to warn about it in -Wconversion. 12168 // So if -Wconversion is off, use a completely identical diagnostic 12169 // in the sign-compare group. 12170 // The conditional-checking code will 12171 if (ICContext) { 12172 DiagID = diag::warn_impcast_integer_sign_conditional; 12173 *ICContext = true; 12174 } 12175 12176 return DiagnoseImpCast(S, E, T, CC, DiagID); 12177 } 12178 12179 // Diagnose conversions between different enumeration types. 12180 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12181 // type, to give us better diagnostics. 12182 QualType SourceType = E->getType(); 12183 if (!S.getLangOpts().CPlusPlus) { 12184 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12185 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12186 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12187 SourceType = S.Context.getTypeDeclType(Enum); 12188 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12189 } 12190 } 12191 12192 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12193 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12194 if (SourceEnum->getDecl()->hasNameForLinkage() && 12195 TargetEnum->getDecl()->hasNameForLinkage() && 12196 SourceEnum != TargetEnum) { 12197 if (S.SourceMgr.isInSystemMacro(CC)) 12198 return; 12199 12200 return DiagnoseImpCast(S, E, SourceType, T, CC, 12201 diag::warn_impcast_different_enum_types); 12202 } 12203 } 12204 12205 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12206 SourceLocation CC, QualType T); 12207 12208 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12209 SourceLocation CC, bool &ICContext) { 12210 E = E->IgnoreParenImpCasts(); 12211 12212 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12213 return CheckConditionalOperator(S, CO, CC, T); 12214 12215 AnalyzeImplicitConversions(S, E, CC); 12216 if (E->getType() != T) 12217 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12218 } 12219 12220 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12221 SourceLocation CC, QualType T) { 12222 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12223 12224 Expr *TrueExpr = E->getTrueExpr(); 12225 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12226 TrueExpr = BCO->getCommon(); 12227 12228 bool Suspicious = false; 12229 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12230 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12231 12232 if (T->isBooleanType()) 12233 DiagnoseIntInBoolContext(S, E); 12234 12235 // If -Wconversion would have warned about either of the candidates 12236 // for a signedness conversion to the context type... 12237 if (!Suspicious) return; 12238 12239 // ...but it's currently ignored... 12240 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12241 return; 12242 12243 // ...then check whether it would have warned about either of the 12244 // candidates for a signedness conversion to the condition type. 12245 if (E->getType() == T) return; 12246 12247 Suspicious = false; 12248 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12249 E->getType(), CC, &Suspicious); 12250 if (!Suspicious) 12251 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12252 E->getType(), CC, &Suspicious); 12253 } 12254 12255 /// Check conversion of given expression to boolean. 12256 /// Input argument E is a logical expression. 12257 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12258 if (S.getLangOpts().Bool) 12259 return; 12260 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12261 return; 12262 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12263 } 12264 12265 namespace { 12266 struct AnalyzeImplicitConversionsWorkItem { 12267 Expr *E; 12268 SourceLocation CC; 12269 bool IsListInit; 12270 }; 12271 } 12272 12273 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12274 /// that should be visited are added to WorkList. 12275 static void AnalyzeImplicitConversions( 12276 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12277 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12278 Expr *OrigE = Item.E; 12279 SourceLocation CC = Item.CC; 12280 12281 QualType T = OrigE->getType(); 12282 Expr *E = OrigE->IgnoreParenImpCasts(); 12283 12284 // Propagate whether we are in a C++ list initialization expression. 12285 // If so, we do not issue warnings for implicit int-float conversion 12286 // precision loss, because C++11 narrowing already handles it. 12287 bool IsListInit = Item.IsListInit || 12288 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12289 12290 if (E->isTypeDependent() || E->isValueDependent()) 12291 return; 12292 12293 Expr *SourceExpr = E; 12294 // Examine, but don't traverse into the source expression of an 12295 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12296 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12297 // evaluate it in the context of checking the specific conversion to T though. 12298 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12299 if (auto *Src = OVE->getSourceExpr()) 12300 SourceExpr = Src; 12301 12302 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12303 if (UO->getOpcode() == UO_Not && 12304 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12305 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12306 << OrigE->getSourceRange() << T->isBooleanType() 12307 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12308 12309 // For conditional operators, we analyze the arguments as if they 12310 // were being fed directly into the output. 12311 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12312 CheckConditionalOperator(S, CO, CC, T); 12313 return; 12314 } 12315 12316 // Check implicit argument conversions for function calls. 12317 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12318 CheckImplicitArgumentConversions(S, Call, CC); 12319 12320 // Go ahead and check any implicit conversions we might have skipped. 12321 // The non-canonical typecheck is just an optimization; 12322 // CheckImplicitConversion will filter out dead implicit conversions. 12323 if (SourceExpr->getType() != T) 12324 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12325 12326 // Now continue drilling into this expression. 12327 12328 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12329 // The bound subexpressions in a PseudoObjectExpr are not reachable 12330 // as transitive children. 12331 // FIXME: Use a more uniform representation for this. 12332 for (auto *SE : POE->semantics()) 12333 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12334 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12335 } 12336 12337 // Skip past explicit casts. 12338 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12339 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12340 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12341 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12342 WorkList.push_back({E, CC, IsListInit}); 12343 return; 12344 } 12345 12346 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12347 // Do a somewhat different check with comparison operators. 12348 if (BO->isComparisonOp()) 12349 return AnalyzeComparison(S, BO); 12350 12351 // And with simple assignments. 12352 if (BO->getOpcode() == BO_Assign) 12353 return AnalyzeAssignment(S, BO); 12354 // And with compound assignments. 12355 if (BO->isAssignmentOp()) 12356 return AnalyzeCompoundAssignment(S, BO); 12357 } 12358 12359 // These break the otherwise-useful invariant below. Fortunately, 12360 // we don't really need to recurse into them, because any internal 12361 // expressions should have been analyzed already when they were 12362 // built into statements. 12363 if (isa<StmtExpr>(E)) return; 12364 12365 // Don't descend into unevaluated contexts. 12366 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12367 12368 // Now just recurse over the expression's children. 12369 CC = E->getExprLoc(); 12370 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12371 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12372 for (Stmt *SubStmt : E->children()) { 12373 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12374 if (!ChildExpr) 12375 continue; 12376 12377 if (IsLogicalAndOperator && 12378 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12379 // Ignore checking string literals that are in logical and operators. 12380 // This is a common pattern for asserts. 12381 continue; 12382 WorkList.push_back({ChildExpr, CC, IsListInit}); 12383 } 12384 12385 if (BO && BO->isLogicalOp()) { 12386 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12387 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12388 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12389 12390 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12391 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12392 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12393 } 12394 12395 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12396 if (U->getOpcode() == UO_LNot) { 12397 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12398 } else if (U->getOpcode() != UO_AddrOf) { 12399 if (U->getSubExpr()->getType()->isAtomicType()) 12400 S.Diag(U->getSubExpr()->getBeginLoc(), 12401 diag::warn_atomic_implicit_seq_cst); 12402 } 12403 } 12404 } 12405 12406 /// AnalyzeImplicitConversions - Find and report any interesting 12407 /// implicit conversions in the given expression. There are a couple 12408 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12409 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12410 bool IsListInit/*= false*/) { 12411 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12412 WorkList.push_back({OrigE, CC, IsListInit}); 12413 while (!WorkList.empty()) 12414 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12415 } 12416 12417 /// Diagnose integer type and any valid implicit conversion to it. 12418 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12419 // Taking into account implicit conversions, 12420 // allow any integer. 12421 if (!E->getType()->isIntegerType()) { 12422 S.Diag(E->getBeginLoc(), 12423 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12424 return true; 12425 } 12426 // Potentially emit standard warnings for implicit conversions if enabled 12427 // using -Wconversion. 12428 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12429 return false; 12430 } 12431 12432 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12433 // Returns true when emitting a warning about taking the address of a reference. 12434 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12435 const PartialDiagnostic &PD) { 12436 E = E->IgnoreParenImpCasts(); 12437 12438 const FunctionDecl *FD = nullptr; 12439 12440 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12441 if (!DRE->getDecl()->getType()->isReferenceType()) 12442 return false; 12443 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12444 if (!M->getMemberDecl()->getType()->isReferenceType()) 12445 return false; 12446 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12447 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12448 return false; 12449 FD = Call->getDirectCallee(); 12450 } else { 12451 return false; 12452 } 12453 12454 SemaRef.Diag(E->getExprLoc(), PD); 12455 12456 // If possible, point to location of function. 12457 if (FD) { 12458 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12459 } 12460 12461 return true; 12462 } 12463 12464 // Returns true if the SourceLocation is expanded from any macro body. 12465 // Returns false if the SourceLocation is invalid, is from not in a macro 12466 // expansion, or is from expanded from a top-level macro argument. 12467 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12468 if (Loc.isInvalid()) 12469 return false; 12470 12471 while (Loc.isMacroID()) { 12472 if (SM.isMacroBodyExpansion(Loc)) 12473 return true; 12474 Loc = SM.getImmediateMacroCallerLoc(Loc); 12475 } 12476 12477 return false; 12478 } 12479 12480 /// Diagnose pointers that are always non-null. 12481 /// \param E the expression containing the pointer 12482 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12483 /// compared to a null pointer 12484 /// \param IsEqual True when the comparison is equal to a null pointer 12485 /// \param Range Extra SourceRange to highlight in the diagnostic 12486 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12487 Expr::NullPointerConstantKind NullKind, 12488 bool IsEqual, SourceRange Range) { 12489 if (!E) 12490 return; 12491 12492 // Don't warn inside macros. 12493 if (E->getExprLoc().isMacroID()) { 12494 const SourceManager &SM = getSourceManager(); 12495 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12496 IsInAnyMacroBody(SM, Range.getBegin())) 12497 return; 12498 } 12499 E = E->IgnoreImpCasts(); 12500 12501 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12502 12503 if (isa<CXXThisExpr>(E)) { 12504 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12505 : diag::warn_this_bool_conversion; 12506 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12507 return; 12508 } 12509 12510 bool IsAddressOf = false; 12511 12512 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12513 if (UO->getOpcode() != UO_AddrOf) 12514 return; 12515 IsAddressOf = true; 12516 E = UO->getSubExpr(); 12517 } 12518 12519 if (IsAddressOf) { 12520 unsigned DiagID = IsCompare 12521 ? diag::warn_address_of_reference_null_compare 12522 : diag::warn_address_of_reference_bool_conversion; 12523 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12524 << IsEqual; 12525 if (CheckForReference(*this, E, PD)) { 12526 return; 12527 } 12528 } 12529 12530 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12531 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12532 std::string Str; 12533 llvm::raw_string_ostream S(Str); 12534 E->printPretty(S, nullptr, getPrintingPolicy()); 12535 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12536 : diag::warn_cast_nonnull_to_bool; 12537 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12538 << E->getSourceRange() << Range << IsEqual; 12539 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12540 }; 12541 12542 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12543 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12544 if (auto *Callee = Call->getDirectCallee()) { 12545 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12546 ComplainAboutNonnullParamOrCall(A); 12547 return; 12548 } 12549 } 12550 } 12551 12552 // Expect to find a single Decl. Skip anything more complicated. 12553 ValueDecl *D = nullptr; 12554 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12555 D = R->getDecl(); 12556 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12557 D = M->getMemberDecl(); 12558 } 12559 12560 // Weak Decls can be null. 12561 if (!D || D->isWeak()) 12562 return; 12563 12564 // Check for parameter decl with nonnull attribute 12565 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12566 if (getCurFunction() && 12567 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12568 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12569 ComplainAboutNonnullParamOrCall(A); 12570 return; 12571 } 12572 12573 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12574 // Skip function template not specialized yet. 12575 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12576 return; 12577 auto ParamIter = llvm::find(FD->parameters(), PV); 12578 assert(ParamIter != FD->param_end()); 12579 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12580 12581 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12582 if (!NonNull->args_size()) { 12583 ComplainAboutNonnullParamOrCall(NonNull); 12584 return; 12585 } 12586 12587 for (const ParamIdx &ArgNo : NonNull->args()) { 12588 if (ArgNo.getASTIndex() == ParamNo) { 12589 ComplainAboutNonnullParamOrCall(NonNull); 12590 return; 12591 } 12592 } 12593 } 12594 } 12595 } 12596 } 12597 12598 QualType T = D->getType(); 12599 const bool IsArray = T->isArrayType(); 12600 const bool IsFunction = T->isFunctionType(); 12601 12602 // Address of function is used to silence the function warning. 12603 if (IsAddressOf && IsFunction) { 12604 return; 12605 } 12606 12607 // Found nothing. 12608 if (!IsAddressOf && !IsFunction && !IsArray) 12609 return; 12610 12611 // Pretty print the expression for the diagnostic. 12612 std::string Str; 12613 llvm::raw_string_ostream S(Str); 12614 E->printPretty(S, nullptr, getPrintingPolicy()); 12615 12616 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12617 : diag::warn_impcast_pointer_to_bool; 12618 enum { 12619 AddressOf, 12620 FunctionPointer, 12621 ArrayPointer 12622 } DiagType; 12623 if (IsAddressOf) 12624 DiagType = AddressOf; 12625 else if (IsFunction) 12626 DiagType = FunctionPointer; 12627 else if (IsArray) 12628 DiagType = ArrayPointer; 12629 else 12630 llvm_unreachable("Could not determine diagnostic."); 12631 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12632 << Range << IsEqual; 12633 12634 if (!IsFunction) 12635 return; 12636 12637 // Suggest '&' to silence the function warning. 12638 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12639 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12640 12641 // Check to see if '()' fixit should be emitted. 12642 QualType ReturnType; 12643 UnresolvedSet<4> NonTemplateOverloads; 12644 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12645 if (ReturnType.isNull()) 12646 return; 12647 12648 if (IsCompare) { 12649 // There are two cases here. If there is null constant, the only suggest 12650 // for a pointer return type. If the null is 0, then suggest if the return 12651 // type is a pointer or an integer type. 12652 if (!ReturnType->isPointerType()) { 12653 if (NullKind == Expr::NPCK_ZeroExpression || 12654 NullKind == Expr::NPCK_ZeroLiteral) { 12655 if (!ReturnType->isIntegerType()) 12656 return; 12657 } else { 12658 return; 12659 } 12660 } 12661 } else { // !IsCompare 12662 // For function to bool, only suggest if the function pointer has bool 12663 // return type. 12664 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12665 return; 12666 } 12667 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12668 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12669 } 12670 12671 /// Diagnoses "dangerous" implicit conversions within the given 12672 /// expression (which is a full expression). Implements -Wconversion 12673 /// and -Wsign-compare. 12674 /// 12675 /// \param CC the "context" location of the implicit conversion, i.e. 12676 /// the most location of the syntactic entity requiring the implicit 12677 /// conversion 12678 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12679 // Don't diagnose in unevaluated contexts. 12680 if (isUnevaluatedContext()) 12681 return; 12682 12683 // Don't diagnose for value- or type-dependent expressions. 12684 if (E->isTypeDependent() || E->isValueDependent()) 12685 return; 12686 12687 // Check for array bounds violations in cases where the check isn't triggered 12688 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12689 // ArraySubscriptExpr is on the RHS of a variable initialization. 12690 CheckArrayAccess(E); 12691 12692 // This is not the right CC for (e.g.) a variable initialization. 12693 AnalyzeImplicitConversions(*this, E, CC); 12694 } 12695 12696 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12697 /// Input argument E is a logical expression. 12698 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12699 ::CheckBoolLikeConversion(*this, E, CC); 12700 } 12701 12702 /// Diagnose when expression is an integer constant expression and its evaluation 12703 /// results in integer overflow 12704 void Sema::CheckForIntOverflow (Expr *E) { 12705 // Use a work list to deal with nested struct initializers. 12706 SmallVector<Expr *, 2> Exprs(1, E); 12707 12708 do { 12709 Expr *OriginalE = Exprs.pop_back_val(); 12710 Expr *E = OriginalE->IgnoreParenCasts(); 12711 12712 if (isa<BinaryOperator>(E)) { 12713 E->EvaluateForOverflow(Context); 12714 continue; 12715 } 12716 12717 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12718 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12719 else if (isa<ObjCBoxedExpr>(OriginalE)) 12720 E->EvaluateForOverflow(Context); 12721 else if (auto Call = dyn_cast<CallExpr>(E)) 12722 Exprs.append(Call->arg_begin(), Call->arg_end()); 12723 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12724 Exprs.append(Message->arg_begin(), Message->arg_end()); 12725 } while (!Exprs.empty()); 12726 } 12727 12728 namespace { 12729 12730 /// Visitor for expressions which looks for unsequenced operations on the 12731 /// same object. 12732 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12733 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12734 12735 /// A tree of sequenced regions within an expression. Two regions are 12736 /// unsequenced if one is an ancestor or a descendent of the other. When we 12737 /// finish processing an expression with sequencing, such as a comma 12738 /// expression, we fold its tree nodes into its parent, since they are 12739 /// unsequenced with respect to nodes we will visit later. 12740 class SequenceTree { 12741 struct Value { 12742 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12743 unsigned Parent : 31; 12744 unsigned Merged : 1; 12745 }; 12746 SmallVector<Value, 8> Values; 12747 12748 public: 12749 /// A region within an expression which may be sequenced with respect 12750 /// to some other region. 12751 class Seq { 12752 friend class SequenceTree; 12753 12754 unsigned Index; 12755 12756 explicit Seq(unsigned N) : Index(N) {} 12757 12758 public: 12759 Seq() : Index(0) {} 12760 }; 12761 12762 SequenceTree() { Values.push_back(Value(0)); } 12763 Seq root() const { return Seq(0); } 12764 12765 /// Create a new sequence of operations, which is an unsequenced 12766 /// subset of \p Parent. This sequence of operations is sequenced with 12767 /// respect to other children of \p Parent. 12768 Seq allocate(Seq Parent) { 12769 Values.push_back(Value(Parent.Index)); 12770 return Seq(Values.size() - 1); 12771 } 12772 12773 /// Merge a sequence of operations into its parent. 12774 void merge(Seq S) { 12775 Values[S.Index].Merged = true; 12776 } 12777 12778 /// Determine whether two operations are unsequenced. This operation 12779 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12780 /// should have been merged into its parent as appropriate. 12781 bool isUnsequenced(Seq Cur, Seq Old) { 12782 unsigned C = representative(Cur.Index); 12783 unsigned Target = representative(Old.Index); 12784 while (C >= Target) { 12785 if (C == Target) 12786 return true; 12787 C = Values[C].Parent; 12788 } 12789 return false; 12790 } 12791 12792 private: 12793 /// Pick a representative for a sequence. 12794 unsigned representative(unsigned K) { 12795 if (Values[K].Merged) 12796 // Perform path compression as we go. 12797 return Values[K].Parent = representative(Values[K].Parent); 12798 return K; 12799 } 12800 }; 12801 12802 /// An object for which we can track unsequenced uses. 12803 using Object = const NamedDecl *; 12804 12805 /// Different flavors of object usage which we track. We only track the 12806 /// least-sequenced usage of each kind. 12807 enum UsageKind { 12808 /// A read of an object. Multiple unsequenced reads are OK. 12809 UK_Use, 12810 12811 /// A modification of an object which is sequenced before the value 12812 /// computation of the expression, such as ++n in C++. 12813 UK_ModAsValue, 12814 12815 /// A modification of an object which is not sequenced before the value 12816 /// computation of the expression, such as n++. 12817 UK_ModAsSideEffect, 12818 12819 UK_Count = UK_ModAsSideEffect + 1 12820 }; 12821 12822 /// Bundle together a sequencing region and the expression corresponding 12823 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12824 struct Usage { 12825 const Expr *UsageExpr; 12826 SequenceTree::Seq Seq; 12827 12828 Usage() : UsageExpr(nullptr), Seq() {} 12829 }; 12830 12831 struct UsageInfo { 12832 Usage Uses[UK_Count]; 12833 12834 /// Have we issued a diagnostic for this object already? 12835 bool Diagnosed; 12836 12837 UsageInfo() : Uses(), Diagnosed(false) {} 12838 }; 12839 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12840 12841 Sema &SemaRef; 12842 12843 /// Sequenced regions within the expression. 12844 SequenceTree Tree; 12845 12846 /// Declaration modifications and references which we have seen. 12847 UsageInfoMap UsageMap; 12848 12849 /// The region we are currently within. 12850 SequenceTree::Seq Region; 12851 12852 /// Filled in with declarations which were modified as a side-effect 12853 /// (that is, post-increment operations). 12854 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12855 12856 /// Expressions to check later. We defer checking these to reduce 12857 /// stack usage. 12858 SmallVectorImpl<const Expr *> &WorkList; 12859 12860 /// RAII object wrapping the visitation of a sequenced subexpression of an 12861 /// expression. At the end of this process, the side-effects of the evaluation 12862 /// become sequenced with respect to the value computation of the result, so 12863 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12864 /// UK_ModAsValue. 12865 struct SequencedSubexpression { 12866 SequencedSubexpression(SequenceChecker &Self) 12867 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12868 Self.ModAsSideEffect = &ModAsSideEffect; 12869 } 12870 12871 ~SequencedSubexpression() { 12872 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12873 // Add a new usage with usage kind UK_ModAsValue, and then restore 12874 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12875 // the previous one was empty). 12876 UsageInfo &UI = Self.UsageMap[M.first]; 12877 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12878 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12879 SideEffectUsage = M.second; 12880 } 12881 Self.ModAsSideEffect = OldModAsSideEffect; 12882 } 12883 12884 SequenceChecker &Self; 12885 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12886 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12887 }; 12888 12889 /// RAII object wrapping the visitation of a subexpression which we might 12890 /// choose to evaluate as a constant. If any subexpression is evaluated and 12891 /// found to be non-constant, this allows us to suppress the evaluation of 12892 /// the outer expression. 12893 class EvaluationTracker { 12894 public: 12895 EvaluationTracker(SequenceChecker &Self) 12896 : Self(Self), Prev(Self.EvalTracker) { 12897 Self.EvalTracker = this; 12898 } 12899 12900 ~EvaluationTracker() { 12901 Self.EvalTracker = Prev; 12902 if (Prev) 12903 Prev->EvalOK &= EvalOK; 12904 } 12905 12906 bool evaluate(const Expr *E, bool &Result) { 12907 if (!EvalOK || E->isValueDependent()) 12908 return false; 12909 EvalOK = E->EvaluateAsBooleanCondition( 12910 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12911 return EvalOK; 12912 } 12913 12914 private: 12915 SequenceChecker &Self; 12916 EvaluationTracker *Prev; 12917 bool EvalOK = true; 12918 } *EvalTracker = nullptr; 12919 12920 /// Find the object which is produced by the specified expression, 12921 /// if any. 12922 Object getObject(const Expr *E, bool Mod) const { 12923 E = E->IgnoreParenCasts(); 12924 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12925 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12926 return getObject(UO->getSubExpr(), Mod); 12927 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12928 if (BO->getOpcode() == BO_Comma) 12929 return getObject(BO->getRHS(), Mod); 12930 if (Mod && BO->isAssignmentOp()) 12931 return getObject(BO->getLHS(), Mod); 12932 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12933 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12934 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12935 return ME->getMemberDecl(); 12936 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12937 // FIXME: If this is a reference, map through to its value. 12938 return DRE->getDecl(); 12939 return nullptr; 12940 } 12941 12942 /// Note that an object \p O was modified or used by an expression 12943 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12944 /// the object \p O as obtained via the \p UsageMap. 12945 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12946 // Get the old usage for the given object and usage kind. 12947 Usage &U = UI.Uses[UK]; 12948 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12949 // If we have a modification as side effect and are in a sequenced 12950 // subexpression, save the old Usage so that we can restore it later 12951 // in SequencedSubexpression::~SequencedSubexpression. 12952 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12953 ModAsSideEffect->push_back(std::make_pair(O, U)); 12954 // Then record the new usage with the current sequencing region. 12955 U.UsageExpr = UsageExpr; 12956 U.Seq = Region; 12957 } 12958 } 12959 12960 /// Check whether a modification or use of an object \p O in an expression 12961 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12962 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12963 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12964 /// usage and false we are checking for a mod-use unsequenced usage. 12965 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12966 UsageKind OtherKind, bool IsModMod) { 12967 if (UI.Diagnosed) 12968 return; 12969 12970 const Usage &U = UI.Uses[OtherKind]; 12971 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12972 return; 12973 12974 const Expr *Mod = U.UsageExpr; 12975 const Expr *ModOrUse = UsageExpr; 12976 if (OtherKind == UK_Use) 12977 std::swap(Mod, ModOrUse); 12978 12979 SemaRef.DiagRuntimeBehavior( 12980 Mod->getExprLoc(), {Mod, ModOrUse}, 12981 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12982 : diag::warn_unsequenced_mod_use) 12983 << O << SourceRange(ModOrUse->getExprLoc())); 12984 UI.Diagnosed = true; 12985 } 12986 12987 // A note on note{Pre, Post}{Use, Mod}: 12988 // 12989 // (It helps to follow the algorithm with an expression such as 12990 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12991 // operations before C++17 and both are well-defined in C++17). 12992 // 12993 // When visiting a node which uses/modify an object we first call notePreUse 12994 // or notePreMod before visiting its sub-expression(s). At this point the 12995 // children of the current node have not yet been visited and so the eventual 12996 // uses/modifications resulting from the children of the current node have not 12997 // been recorded yet. 12998 // 12999 // We then visit the children of the current node. After that notePostUse or 13000 // notePostMod is called. These will 1) detect an unsequenced modification 13001 // as side effect (as in "k++ + k") and 2) add a new usage with the 13002 // appropriate usage kind. 13003 // 13004 // We also have to be careful that some operation sequences modification as 13005 // side effect as well (for example: || or ,). To account for this we wrap 13006 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13007 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13008 // which record usages which are modifications as side effect, and then 13009 // downgrade them (or more accurately restore the previous usage which was a 13010 // modification as side effect) when exiting the scope of the sequenced 13011 // subexpression. 13012 13013 void notePreUse(Object O, const Expr *UseExpr) { 13014 UsageInfo &UI = UsageMap[O]; 13015 // Uses conflict with other modifications. 13016 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13017 } 13018 13019 void notePostUse(Object O, const Expr *UseExpr) { 13020 UsageInfo &UI = UsageMap[O]; 13021 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13022 /*IsModMod=*/false); 13023 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13024 } 13025 13026 void notePreMod(Object O, const Expr *ModExpr) { 13027 UsageInfo &UI = UsageMap[O]; 13028 // Modifications conflict with other modifications and with uses. 13029 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13030 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13031 } 13032 13033 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13034 UsageInfo &UI = UsageMap[O]; 13035 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13036 /*IsModMod=*/true); 13037 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13038 } 13039 13040 public: 13041 SequenceChecker(Sema &S, const Expr *E, 13042 SmallVectorImpl<const Expr *> &WorkList) 13043 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13044 Visit(E); 13045 // Silence a -Wunused-private-field since WorkList is now unused. 13046 // TODO: Evaluate if it can be used, and if not remove it. 13047 (void)this->WorkList; 13048 } 13049 13050 void VisitStmt(const Stmt *S) { 13051 // Skip all statements which aren't expressions for now. 13052 } 13053 13054 void VisitExpr(const Expr *E) { 13055 // By default, just recurse to evaluated subexpressions. 13056 Base::VisitStmt(E); 13057 } 13058 13059 void VisitCastExpr(const CastExpr *E) { 13060 Object O = Object(); 13061 if (E->getCastKind() == CK_LValueToRValue) 13062 O = getObject(E->getSubExpr(), false); 13063 13064 if (O) 13065 notePreUse(O, E); 13066 VisitExpr(E); 13067 if (O) 13068 notePostUse(O, E); 13069 } 13070 13071 void VisitSequencedExpressions(const Expr *SequencedBefore, 13072 const Expr *SequencedAfter) { 13073 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13074 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13075 SequenceTree::Seq OldRegion = Region; 13076 13077 { 13078 SequencedSubexpression SeqBefore(*this); 13079 Region = BeforeRegion; 13080 Visit(SequencedBefore); 13081 } 13082 13083 Region = AfterRegion; 13084 Visit(SequencedAfter); 13085 13086 Region = OldRegion; 13087 13088 Tree.merge(BeforeRegion); 13089 Tree.merge(AfterRegion); 13090 } 13091 13092 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13093 // C++17 [expr.sub]p1: 13094 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13095 // expression E1 is sequenced before the expression E2. 13096 if (SemaRef.getLangOpts().CPlusPlus17) 13097 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13098 else { 13099 Visit(ASE->getLHS()); 13100 Visit(ASE->getRHS()); 13101 } 13102 } 13103 13104 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13105 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13106 void VisitBinPtrMem(const BinaryOperator *BO) { 13107 // C++17 [expr.mptr.oper]p4: 13108 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13109 // the expression E1 is sequenced before the expression E2. 13110 if (SemaRef.getLangOpts().CPlusPlus17) 13111 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13112 else { 13113 Visit(BO->getLHS()); 13114 Visit(BO->getRHS()); 13115 } 13116 } 13117 13118 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13119 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13120 void VisitBinShlShr(const BinaryOperator *BO) { 13121 // C++17 [expr.shift]p4: 13122 // The expression E1 is sequenced before the expression E2. 13123 if (SemaRef.getLangOpts().CPlusPlus17) 13124 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13125 else { 13126 Visit(BO->getLHS()); 13127 Visit(BO->getRHS()); 13128 } 13129 } 13130 13131 void VisitBinComma(const BinaryOperator *BO) { 13132 // C++11 [expr.comma]p1: 13133 // Every value computation and side effect associated with the left 13134 // expression is sequenced before every value computation and side 13135 // effect associated with the right expression. 13136 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13137 } 13138 13139 void VisitBinAssign(const BinaryOperator *BO) { 13140 SequenceTree::Seq RHSRegion; 13141 SequenceTree::Seq LHSRegion; 13142 if (SemaRef.getLangOpts().CPlusPlus17) { 13143 RHSRegion = Tree.allocate(Region); 13144 LHSRegion = Tree.allocate(Region); 13145 } else { 13146 RHSRegion = Region; 13147 LHSRegion = Region; 13148 } 13149 SequenceTree::Seq OldRegion = Region; 13150 13151 // C++11 [expr.ass]p1: 13152 // [...] the assignment is sequenced after the value computation 13153 // of the right and left operands, [...] 13154 // 13155 // so check it before inspecting the operands and update the 13156 // map afterwards. 13157 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13158 if (O) 13159 notePreMod(O, BO); 13160 13161 if (SemaRef.getLangOpts().CPlusPlus17) { 13162 // C++17 [expr.ass]p1: 13163 // [...] The right operand is sequenced before the left operand. [...] 13164 { 13165 SequencedSubexpression SeqBefore(*this); 13166 Region = RHSRegion; 13167 Visit(BO->getRHS()); 13168 } 13169 13170 Region = LHSRegion; 13171 Visit(BO->getLHS()); 13172 13173 if (O && isa<CompoundAssignOperator>(BO)) 13174 notePostUse(O, BO); 13175 13176 } else { 13177 // C++11 does not specify any sequencing between the LHS and RHS. 13178 Region = LHSRegion; 13179 Visit(BO->getLHS()); 13180 13181 if (O && isa<CompoundAssignOperator>(BO)) 13182 notePostUse(O, BO); 13183 13184 Region = RHSRegion; 13185 Visit(BO->getRHS()); 13186 } 13187 13188 // C++11 [expr.ass]p1: 13189 // the assignment is sequenced [...] before the value computation of the 13190 // assignment expression. 13191 // C11 6.5.16/3 has no such rule. 13192 Region = OldRegion; 13193 if (O) 13194 notePostMod(O, BO, 13195 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13196 : UK_ModAsSideEffect); 13197 if (SemaRef.getLangOpts().CPlusPlus17) { 13198 Tree.merge(RHSRegion); 13199 Tree.merge(LHSRegion); 13200 } 13201 } 13202 13203 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13204 VisitBinAssign(CAO); 13205 } 13206 13207 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13208 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13209 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13210 Object O = getObject(UO->getSubExpr(), true); 13211 if (!O) 13212 return VisitExpr(UO); 13213 13214 notePreMod(O, UO); 13215 Visit(UO->getSubExpr()); 13216 // C++11 [expr.pre.incr]p1: 13217 // the expression ++x is equivalent to x+=1 13218 notePostMod(O, UO, 13219 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13220 : UK_ModAsSideEffect); 13221 } 13222 13223 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13224 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13225 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13226 Object O = getObject(UO->getSubExpr(), true); 13227 if (!O) 13228 return VisitExpr(UO); 13229 13230 notePreMod(O, UO); 13231 Visit(UO->getSubExpr()); 13232 notePostMod(O, UO, UK_ModAsSideEffect); 13233 } 13234 13235 void VisitBinLOr(const BinaryOperator *BO) { 13236 // C++11 [expr.log.or]p2: 13237 // If the second expression is evaluated, every value computation and 13238 // side effect associated with the first expression is sequenced before 13239 // every value computation and side effect associated with the 13240 // second expression. 13241 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13242 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13243 SequenceTree::Seq OldRegion = Region; 13244 13245 EvaluationTracker Eval(*this); 13246 { 13247 SequencedSubexpression Sequenced(*this); 13248 Region = LHSRegion; 13249 Visit(BO->getLHS()); 13250 } 13251 13252 // C++11 [expr.log.or]p1: 13253 // [...] the second operand is not evaluated if the first operand 13254 // evaluates to true. 13255 bool EvalResult = false; 13256 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13257 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13258 if (ShouldVisitRHS) { 13259 Region = RHSRegion; 13260 Visit(BO->getRHS()); 13261 } 13262 13263 Region = OldRegion; 13264 Tree.merge(LHSRegion); 13265 Tree.merge(RHSRegion); 13266 } 13267 13268 void VisitBinLAnd(const BinaryOperator *BO) { 13269 // C++11 [expr.log.and]p2: 13270 // If the second expression is evaluated, every value computation and 13271 // side effect associated with the first expression is sequenced before 13272 // every value computation and side effect associated with the 13273 // second expression. 13274 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13275 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13276 SequenceTree::Seq OldRegion = Region; 13277 13278 EvaluationTracker Eval(*this); 13279 { 13280 SequencedSubexpression Sequenced(*this); 13281 Region = LHSRegion; 13282 Visit(BO->getLHS()); 13283 } 13284 13285 // C++11 [expr.log.and]p1: 13286 // [...] the second operand is not evaluated if the first operand is false. 13287 bool EvalResult = false; 13288 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13289 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13290 if (ShouldVisitRHS) { 13291 Region = RHSRegion; 13292 Visit(BO->getRHS()); 13293 } 13294 13295 Region = OldRegion; 13296 Tree.merge(LHSRegion); 13297 Tree.merge(RHSRegion); 13298 } 13299 13300 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13301 // C++11 [expr.cond]p1: 13302 // [...] Every value computation and side effect associated with the first 13303 // expression is sequenced before every value computation and side effect 13304 // associated with the second or third expression. 13305 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13306 13307 // No sequencing is specified between the true and false expression. 13308 // However since exactly one of both is going to be evaluated we can 13309 // consider them to be sequenced. This is needed to avoid warning on 13310 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13311 // both the true and false expressions because we can't evaluate x. 13312 // This will still allow us to detect an expression like (pre C++17) 13313 // "(x ? y += 1 : y += 2) = y". 13314 // 13315 // We don't wrap the visitation of the true and false expression with 13316 // SequencedSubexpression because we don't want to downgrade modifications 13317 // as side effect in the true and false expressions after the visition 13318 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13319 // not warn between the two "y++", but we should warn between the "y++" 13320 // and the "y". 13321 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13322 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13323 SequenceTree::Seq OldRegion = Region; 13324 13325 EvaluationTracker Eval(*this); 13326 { 13327 SequencedSubexpression Sequenced(*this); 13328 Region = ConditionRegion; 13329 Visit(CO->getCond()); 13330 } 13331 13332 // C++11 [expr.cond]p1: 13333 // [...] The first expression is contextually converted to bool (Clause 4). 13334 // It is evaluated and if it is true, the result of the conditional 13335 // expression is the value of the second expression, otherwise that of the 13336 // third expression. Only one of the second and third expressions is 13337 // evaluated. [...] 13338 bool EvalResult = false; 13339 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13340 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13341 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13342 if (ShouldVisitTrueExpr) { 13343 Region = TrueRegion; 13344 Visit(CO->getTrueExpr()); 13345 } 13346 if (ShouldVisitFalseExpr) { 13347 Region = FalseRegion; 13348 Visit(CO->getFalseExpr()); 13349 } 13350 13351 Region = OldRegion; 13352 Tree.merge(ConditionRegion); 13353 Tree.merge(TrueRegion); 13354 Tree.merge(FalseRegion); 13355 } 13356 13357 void VisitCallExpr(const CallExpr *CE) { 13358 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13359 13360 if (CE->isUnevaluatedBuiltinCall(Context)) 13361 return; 13362 13363 // C++11 [intro.execution]p15: 13364 // When calling a function [...], every value computation and side effect 13365 // associated with any argument expression, or with the postfix expression 13366 // designating the called function, is sequenced before execution of every 13367 // expression or statement in the body of the function [and thus before 13368 // the value computation of its result]. 13369 SequencedSubexpression Sequenced(*this); 13370 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13371 // C++17 [expr.call]p5 13372 // The postfix-expression is sequenced before each expression in the 13373 // expression-list and any default argument. [...] 13374 SequenceTree::Seq CalleeRegion; 13375 SequenceTree::Seq OtherRegion; 13376 if (SemaRef.getLangOpts().CPlusPlus17) { 13377 CalleeRegion = Tree.allocate(Region); 13378 OtherRegion = Tree.allocate(Region); 13379 } else { 13380 CalleeRegion = Region; 13381 OtherRegion = Region; 13382 } 13383 SequenceTree::Seq OldRegion = Region; 13384 13385 // Visit the callee expression first. 13386 Region = CalleeRegion; 13387 if (SemaRef.getLangOpts().CPlusPlus17) { 13388 SequencedSubexpression Sequenced(*this); 13389 Visit(CE->getCallee()); 13390 } else { 13391 Visit(CE->getCallee()); 13392 } 13393 13394 // Then visit the argument expressions. 13395 Region = OtherRegion; 13396 for (const Expr *Argument : CE->arguments()) 13397 Visit(Argument); 13398 13399 Region = OldRegion; 13400 if (SemaRef.getLangOpts().CPlusPlus17) { 13401 Tree.merge(CalleeRegion); 13402 Tree.merge(OtherRegion); 13403 } 13404 }); 13405 } 13406 13407 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13408 // C++17 [over.match.oper]p2: 13409 // [...] the operator notation is first transformed to the equivalent 13410 // function-call notation as summarized in Table 12 (where @ denotes one 13411 // of the operators covered in the specified subclause). However, the 13412 // operands are sequenced in the order prescribed for the built-in 13413 // operator (Clause 8). 13414 // 13415 // From the above only overloaded binary operators and overloaded call 13416 // operators have sequencing rules in C++17 that we need to handle 13417 // separately. 13418 if (!SemaRef.getLangOpts().CPlusPlus17 || 13419 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13420 return VisitCallExpr(CXXOCE); 13421 13422 enum { 13423 NoSequencing, 13424 LHSBeforeRHS, 13425 RHSBeforeLHS, 13426 LHSBeforeRest 13427 } SequencingKind; 13428 switch (CXXOCE->getOperator()) { 13429 case OO_Equal: 13430 case OO_PlusEqual: 13431 case OO_MinusEqual: 13432 case OO_StarEqual: 13433 case OO_SlashEqual: 13434 case OO_PercentEqual: 13435 case OO_CaretEqual: 13436 case OO_AmpEqual: 13437 case OO_PipeEqual: 13438 case OO_LessLessEqual: 13439 case OO_GreaterGreaterEqual: 13440 SequencingKind = RHSBeforeLHS; 13441 break; 13442 13443 case OO_LessLess: 13444 case OO_GreaterGreater: 13445 case OO_AmpAmp: 13446 case OO_PipePipe: 13447 case OO_Comma: 13448 case OO_ArrowStar: 13449 case OO_Subscript: 13450 SequencingKind = LHSBeforeRHS; 13451 break; 13452 13453 case OO_Call: 13454 SequencingKind = LHSBeforeRest; 13455 break; 13456 13457 default: 13458 SequencingKind = NoSequencing; 13459 break; 13460 } 13461 13462 if (SequencingKind == NoSequencing) 13463 return VisitCallExpr(CXXOCE); 13464 13465 // This is a call, so all subexpressions are sequenced before the result. 13466 SequencedSubexpression Sequenced(*this); 13467 13468 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13469 assert(SemaRef.getLangOpts().CPlusPlus17 && 13470 "Should only get there with C++17 and above!"); 13471 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13472 "Should only get there with an overloaded binary operator" 13473 " or an overloaded call operator!"); 13474 13475 if (SequencingKind == LHSBeforeRest) { 13476 assert(CXXOCE->getOperator() == OO_Call && 13477 "We should only have an overloaded call operator here!"); 13478 13479 // This is very similar to VisitCallExpr, except that we only have the 13480 // C++17 case. The postfix-expression is the first argument of the 13481 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13482 // are in the following arguments. 13483 // 13484 // Note that we intentionally do not visit the callee expression since 13485 // it is just a decayed reference to a function. 13486 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13487 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13488 SequenceTree::Seq OldRegion = Region; 13489 13490 assert(CXXOCE->getNumArgs() >= 1 && 13491 "An overloaded call operator must have at least one argument" 13492 " for the postfix-expression!"); 13493 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13494 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13495 CXXOCE->getNumArgs() - 1); 13496 13497 // Visit the postfix-expression first. 13498 { 13499 Region = PostfixExprRegion; 13500 SequencedSubexpression Sequenced(*this); 13501 Visit(PostfixExpr); 13502 } 13503 13504 // Then visit the argument expressions. 13505 Region = ArgsRegion; 13506 for (const Expr *Arg : Args) 13507 Visit(Arg); 13508 13509 Region = OldRegion; 13510 Tree.merge(PostfixExprRegion); 13511 Tree.merge(ArgsRegion); 13512 } else { 13513 assert(CXXOCE->getNumArgs() == 2 && 13514 "Should only have two arguments here!"); 13515 assert((SequencingKind == LHSBeforeRHS || 13516 SequencingKind == RHSBeforeLHS) && 13517 "Unexpected sequencing kind!"); 13518 13519 // We do not visit the callee expression since it is just a decayed 13520 // reference to a function. 13521 const Expr *E1 = CXXOCE->getArg(0); 13522 const Expr *E2 = CXXOCE->getArg(1); 13523 if (SequencingKind == RHSBeforeLHS) 13524 std::swap(E1, E2); 13525 13526 return VisitSequencedExpressions(E1, E2); 13527 } 13528 }); 13529 } 13530 13531 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13532 // This is a call, so all subexpressions are sequenced before the result. 13533 SequencedSubexpression Sequenced(*this); 13534 13535 if (!CCE->isListInitialization()) 13536 return VisitExpr(CCE); 13537 13538 // In C++11, list initializations are sequenced. 13539 SmallVector<SequenceTree::Seq, 32> Elts; 13540 SequenceTree::Seq Parent = Region; 13541 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13542 E = CCE->arg_end(); 13543 I != E; ++I) { 13544 Region = Tree.allocate(Parent); 13545 Elts.push_back(Region); 13546 Visit(*I); 13547 } 13548 13549 // Forget that the initializers are sequenced. 13550 Region = Parent; 13551 for (unsigned I = 0; I < Elts.size(); ++I) 13552 Tree.merge(Elts[I]); 13553 } 13554 13555 void VisitInitListExpr(const InitListExpr *ILE) { 13556 if (!SemaRef.getLangOpts().CPlusPlus11) 13557 return VisitExpr(ILE); 13558 13559 // In C++11, list initializations are sequenced. 13560 SmallVector<SequenceTree::Seq, 32> Elts; 13561 SequenceTree::Seq Parent = Region; 13562 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13563 const Expr *E = ILE->getInit(I); 13564 if (!E) 13565 continue; 13566 Region = Tree.allocate(Parent); 13567 Elts.push_back(Region); 13568 Visit(E); 13569 } 13570 13571 // Forget that the initializers are sequenced. 13572 Region = Parent; 13573 for (unsigned I = 0; I < Elts.size(); ++I) 13574 Tree.merge(Elts[I]); 13575 } 13576 }; 13577 13578 } // namespace 13579 13580 void Sema::CheckUnsequencedOperations(const Expr *E) { 13581 SmallVector<const Expr *, 8> WorkList; 13582 WorkList.push_back(E); 13583 while (!WorkList.empty()) { 13584 const Expr *Item = WorkList.pop_back_val(); 13585 SequenceChecker(*this, Item, WorkList); 13586 } 13587 } 13588 13589 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13590 bool IsConstexpr) { 13591 llvm::SaveAndRestore<bool> ConstantContext( 13592 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13593 CheckImplicitConversions(E, CheckLoc); 13594 if (!E->isInstantiationDependent()) 13595 CheckUnsequencedOperations(E); 13596 if (!IsConstexpr && !E->isValueDependent()) 13597 CheckForIntOverflow(E); 13598 DiagnoseMisalignedMembers(); 13599 } 13600 13601 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13602 FieldDecl *BitField, 13603 Expr *Init) { 13604 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13605 } 13606 13607 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13608 SourceLocation Loc) { 13609 if (!PType->isVariablyModifiedType()) 13610 return; 13611 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13612 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13613 return; 13614 } 13615 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13616 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13617 return; 13618 } 13619 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13620 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13621 return; 13622 } 13623 13624 const ArrayType *AT = S.Context.getAsArrayType(PType); 13625 if (!AT) 13626 return; 13627 13628 if (AT->getSizeModifier() != ArrayType::Star) { 13629 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13630 return; 13631 } 13632 13633 S.Diag(Loc, diag::err_array_star_in_function_definition); 13634 } 13635 13636 /// CheckParmsForFunctionDef - Check that the parameters of the given 13637 /// function are appropriate for the definition of a function. This 13638 /// takes care of any checks that cannot be performed on the 13639 /// declaration itself, e.g., that the types of each of the function 13640 /// parameters are complete. 13641 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13642 bool CheckParameterNames) { 13643 bool HasInvalidParm = false; 13644 for (ParmVarDecl *Param : Parameters) { 13645 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13646 // function declarator that is part of a function definition of 13647 // that function shall not have incomplete type. 13648 // 13649 // This is also C++ [dcl.fct]p6. 13650 if (!Param->isInvalidDecl() && 13651 RequireCompleteType(Param->getLocation(), Param->getType(), 13652 diag::err_typecheck_decl_incomplete_type)) { 13653 Param->setInvalidDecl(); 13654 HasInvalidParm = true; 13655 } 13656 13657 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13658 // declaration of each parameter shall include an identifier. 13659 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13660 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13661 // Diagnose this as an extension in C17 and earlier. 13662 if (!getLangOpts().C2x) 13663 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13664 } 13665 13666 // C99 6.7.5.3p12: 13667 // If the function declarator is not part of a definition of that 13668 // function, parameters may have incomplete type and may use the [*] 13669 // notation in their sequences of declarator specifiers to specify 13670 // variable length array types. 13671 QualType PType = Param->getOriginalType(); 13672 // FIXME: This diagnostic should point the '[*]' if source-location 13673 // information is added for it. 13674 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13675 13676 // If the parameter is a c++ class type and it has to be destructed in the 13677 // callee function, declare the destructor so that it can be called by the 13678 // callee function. Do not perform any direct access check on the dtor here. 13679 if (!Param->isInvalidDecl()) { 13680 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13681 if (!ClassDecl->isInvalidDecl() && 13682 !ClassDecl->hasIrrelevantDestructor() && 13683 !ClassDecl->isDependentContext() && 13684 ClassDecl->isParamDestroyedInCallee()) { 13685 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13686 MarkFunctionReferenced(Param->getLocation(), Destructor); 13687 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13688 } 13689 } 13690 } 13691 13692 // Parameters with the pass_object_size attribute only need to be marked 13693 // constant at function definitions. Because we lack information about 13694 // whether we're on a declaration or definition when we're instantiating the 13695 // attribute, we need to check for constness here. 13696 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13697 if (!Param->getType().isConstQualified()) 13698 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13699 << Attr->getSpelling() << 1; 13700 13701 // Check for parameter names shadowing fields from the class. 13702 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13703 // The owning context for the parameter should be the function, but we 13704 // want to see if this function's declaration context is a record. 13705 DeclContext *DC = Param->getDeclContext(); 13706 if (DC && DC->isFunctionOrMethod()) { 13707 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13708 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13709 RD, /*DeclIsField*/ false); 13710 } 13711 } 13712 } 13713 13714 return HasInvalidParm; 13715 } 13716 13717 Optional<std::pair<CharUnits, CharUnits>> 13718 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13719 13720 /// Compute the alignment and offset of the base class object given the 13721 /// derived-to-base cast expression and the alignment and offset of the derived 13722 /// class object. 13723 static std::pair<CharUnits, CharUnits> 13724 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13725 CharUnits BaseAlignment, CharUnits Offset, 13726 ASTContext &Ctx) { 13727 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13728 ++PathI) { 13729 const CXXBaseSpecifier *Base = *PathI; 13730 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13731 if (Base->isVirtual()) { 13732 // The complete object may have a lower alignment than the non-virtual 13733 // alignment of the base, in which case the base may be misaligned. Choose 13734 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13735 // conservative lower bound of the complete object alignment. 13736 CharUnits NonVirtualAlignment = 13737 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13738 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13739 Offset = CharUnits::Zero(); 13740 } else { 13741 const ASTRecordLayout &RL = 13742 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13743 Offset += RL.getBaseClassOffset(BaseDecl); 13744 } 13745 DerivedType = Base->getType(); 13746 } 13747 13748 return std::make_pair(BaseAlignment, Offset); 13749 } 13750 13751 /// Compute the alignment and offset of a binary additive operator. 13752 static Optional<std::pair<CharUnits, CharUnits>> 13753 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13754 bool IsSub, ASTContext &Ctx) { 13755 QualType PointeeType = PtrE->getType()->getPointeeType(); 13756 13757 if (!PointeeType->isConstantSizeType()) 13758 return llvm::None; 13759 13760 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13761 13762 if (!P) 13763 return llvm::None; 13764 13765 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13766 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 13767 CharUnits Offset = EltSize * IdxRes->getExtValue(); 13768 if (IsSub) 13769 Offset = -Offset; 13770 return std::make_pair(P->first, P->second + Offset); 13771 } 13772 13773 // If the integer expression isn't a constant expression, compute the lower 13774 // bound of the alignment using the alignment and offset of the pointer 13775 // expression and the element size. 13776 return std::make_pair( 13777 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13778 CharUnits::Zero()); 13779 } 13780 13781 /// This helper function takes an lvalue expression and returns the alignment of 13782 /// a VarDecl and a constant offset from the VarDecl. 13783 Optional<std::pair<CharUnits, CharUnits>> 13784 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13785 E = E->IgnoreParens(); 13786 switch (E->getStmtClass()) { 13787 default: 13788 break; 13789 case Stmt::CStyleCastExprClass: 13790 case Stmt::CXXStaticCastExprClass: 13791 case Stmt::ImplicitCastExprClass: { 13792 auto *CE = cast<CastExpr>(E); 13793 const Expr *From = CE->getSubExpr(); 13794 switch (CE->getCastKind()) { 13795 default: 13796 break; 13797 case CK_NoOp: 13798 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13799 case CK_UncheckedDerivedToBase: 13800 case CK_DerivedToBase: { 13801 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13802 if (!P) 13803 break; 13804 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13805 P->second, Ctx); 13806 } 13807 } 13808 break; 13809 } 13810 case Stmt::ArraySubscriptExprClass: { 13811 auto *ASE = cast<ArraySubscriptExpr>(E); 13812 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13813 false, Ctx); 13814 } 13815 case Stmt::DeclRefExprClass: { 13816 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13817 // FIXME: If VD is captured by copy or is an escaping __block variable, 13818 // use the alignment of VD's type. 13819 if (!VD->getType()->isReferenceType()) 13820 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13821 if (VD->hasInit()) 13822 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13823 } 13824 break; 13825 } 13826 case Stmt::MemberExprClass: { 13827 auto *ME = cast<MemberExpr>(E); 13828 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13829 if (!FD || FD->getType()->isReferenceType()) 13830 break; 13831 Optional<std::pair<CharUnits, CharUnits>> P; 13832 if (ME->isArrow()) 13833 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 13834 else 13835 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13836 if (!P) 13837 break; 13838 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13839 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13840 return std::make_pair(P->first, 13841 P->second + CharUnits::fromQuantity(Offset)); 13842 } 13843 case Stmt::UnaryOperatorClass: { 13844 auto *UO = cast<UnaryOperator>(E); 13845 switch (UO->getOpcode()) { 13846 default: 13847 break; 13848 case UO_Deref: 13849 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13850 } 13851 break; 13852 } 13853 case Stmt::BinaryOperatorClass: { 13854 auto *BO = cast<BinaryOperator>(E); 13855 auto Opcode = BO->getOpcode(); 13856 switch (Opcode) { 13857 default: 13858 break; 13859 case BO_Comma: 13860 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13861 } 13862 break; 13863 } 13864 } 13865 return llvm::None; 13866 } 13867 13868 /// This helper function takes a pointer expression and returns the alignment of 13869 /// a VarDecl and a constant offset from the VarDecl. 13870 Optional<std::pair<CharUnits, CharUnits>> 13871 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 13872 E = E->IgnoreParens(); 13873 switch (E->getStmtClass()) { 13874 default: 13875 break; 13876 case Stmt::CStyleCastExprClass: 13877 case Stmt::CXXStaticCastExprClass: 13878 case Stmt::ImplicitCastExprClass: { 13879 auto *CE = cast<CastExpr>(E); 13880 const Expr *From = CE->getSubExpr(); 13881 switch (CE->getCastKind()) { 13882 default: 13883 break; 13884 case CK_NoOp: 13885 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13886 case CK_ArrayToPointerDecay: 13887 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13888 case CK_UncheckedDerivedToBase: 13889 case CK_DerivedToBase: { 13890 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13891 if (!P) 13892 break; 13893 return getDerivedToBaseAlignmentAndOffset( 13894 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13895 } 13896 } 13897 break; 13898 } 13899 case Stmt::CXXThisExprClass: { 13900 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 13901 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 13902 return std::make_pair(Alignment, CharUnits::Zero()); 13903 } 13904 case Stmt::UnaryOperatorClass: { 13905 auto *UO = cast<UnaryOperator>(E); 13906 if (UO->getOpcode() == UO_AddrOf) 13907 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13908 break; 13909 } 13910 case Stmt::BinaryOperatorClass: { 13911 auto *BO = cast<BinaryOperator>(E); 13912 auto Opcode = BO->getOpcode(); 13913 switch (Opcode) { 13914 default: 13915 break; 13916 case BO_Add: 13917 case BO_Sub: { 13918 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13919 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13920 std::swap(LHS, RHS); 13921 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13922 Ctx); 13923 } 13924 case BO_Comma: 13925 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13926 } 13927 break; 13928 } 13929 } 13930 return llvm::None; 13931 } 13932 13933 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13934 // See if we can compute the alignment of a VarDecl and an offset from it. 13935 Optional<std::pair<CharUnits, CharUnits>> P = 13936 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13937 13938 if (P) 13939 return P->first.alignmentAtOffset(P->second); 13940 13941 // If that failed, return the type's alignment. 13942 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13943 } 13944 13945 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13946 /// pointer cast increases the alignment requirements. 13947 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13948 // This is actually a lot of work to potentially be doing on every 13949 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13950 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13951 return; 13952 13953 // Ignore dependent types. 13954 if (T->isDependentType() || Op->getType()->isDependentType()) 13955 return; 13956 13957 // Require that the destination be a pointer type. 13958 const PointerType *DestPtr = T->getAs<PointerType>(); 13959 if (!DestPtr) return; 13960 13961 // If the destination has alignment 1, we're done. 13962 QualType DestPointee = DestPtr->getPointeeType(); 13963 if (DestPointee->isIncompleteType()) return; 13964 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13965 if (DestAlign.isOne()) return; 13966 13967 // Require that the source be a pointer type. 13968 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13969 if (!SrcPtr) return; 13970 QualType SrcPointee = SrcPtr->getPointeeType(); 13971 13972 // Explicitly allow casts from cv void*. We already implicitly 13973 // allowed casts to cv void*, since they have alignment 1. 13974 // Also allow casts involving incomplete types, which implicitly 13975 // includes 'void'. 13976 if (SrcPointee->isIncompleteType()) return; 13977 13978 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13979 13980 if (SrcAlign >= DestAlign) return; 13981 13982 Diag(TRange.getBegin(), diag::warn_cast_align) 13983 << Op->getType() << T 13984 << static_cast<unsigned>(SrcAlign.getQuantity()) 13985 << static_cast<unsigned>(DestAlign.getQuantity()) 13986 << TRange << Op->getSourceRange(); 13987 } 13988 13989 /// Check whether this array fits the idiom of a size-one tail padded 13990 /// array member of a struct. 13991 /// 13992 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13993 /// commonly used to emulate flexible arrays in C89 code. 13994 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13995 const NamedDecl *ND) { 13996 if (Size != 1 || !ND) return false; 13997 13998 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13999 if (!FD) return false; 14000 14001 // Don't consider sizes resulting from macro expansions or template argument 14002 // substitution to form C89 tail-padded arrays. 14003 14004 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14005 while (TInfo) { 14006 TypeLoc TL = TInfo->getTypeLoc(); 14007 // Look through typedefs. 14008 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14009 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14010 TInfo = TDL->getTypeSourceInfo(); 14011 continue; 14012 } 14013 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14014 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14015 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14016 return false; 14017 } 14018 break; 14019 } 14020 14021 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14022 if (!RD) return false; 14023 if (RD->isUnion()) return false; 14024 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14025 if (!CRD->isStandardLayout()) return false; 14026 } 14027 14028 // See if this is the last field decl in the record. 14029 const Decl *D = FD; 14030 while ((D = D->getNextDeclInContext())) 14031 if (isa<FieldDecl>(D)) 14032 return false; 14033 return true; 14034 } 14035 14036 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14037 const ArraySubscriptExpr *ASE, 14038 bool AllowOnePastEnd, bool IndexNegated) { 14039 // Already diagnosed by the constant evaluator. 14040 if (isConstantEvaluated()) 14041 return; 14042 14043 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14044 if (IndexExpr->isValueDependent()) 14045 return; 14046 14047 const Type *EffectiveType = 14048 BaseExpr->getType()->getPointeeOrArrayElementType(); 14049 BaseExpr = BaseExpr->IgnoreParenCasts(); 14050 const ConstantArrayType *ArrayTy = 14051 Context.getAsConstantArrayType(BaseExpr->getType()); 14052 14053 if (!ArrayTy) 14054 return; 14055 14056 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 14057 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 14058 return; 14059 14060 Expr::EvalResult Result; 14061 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14062 return; 14063 14064 llvm::APSInt index = Result.Val.getInt(); 14065 if (IndexNegated) 14066 index = -index; 14067 14068 const NamedDecl *ND = nullptr; 14069 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14070 ND = DRE->getDecl(); 14071 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14072 ND = ME->getMemberDecl(); 14073 14074 if (index.isUnsigned() || !index.isNegative()) { 14075 // It is possible that the type of the base expression after 14076 // IgnoreParenCasts is incomplete, even though the type of the base 14077 // expression before IgnoreParenCasts is complete (see PR39746 for an 14078 // example). In this case we have no information about whether the array 14079 // access exceeds the array bounds. However we can still diagnose an array 14080 // access which precedes the array bounds. 14081 if (BaseType->isIncompleteType()) 14082 return; 14083 14084 llvm::APInt size = ArrayTy->getSize(); 14085 if (!size.isStrictlyPositive()) 14086 return; 14087 14088 if (BaseType != EffectiveType) { 14089 // Make sure we're comparing apples to apples when comparing index to size 14090 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14091 uint64_t array_typesize = Context.getTypeSize(BaseType); 14092 // Handle ptrarith_typesize being zero, such as when casting to void* 14093 if (!ptrarith_typesize) ptrarith_typesize = 1; 14094 if (ptrarith_typesize != array_typesize) { 14095 // There's a cast to a different size type involved 14096 uint64_t ratio = array_typesize / ptrarith_typesize; 14097 // TODO: Be smarter about handling cases where array_typesize is not a 14098 // multiple of ptrarith_typesize 14099 if (ptrarith_typesize * ratio == array_typesize) 14100 size *= llvm::APInt(size.getBitWidth(), ratio); 14101 } 14102 } 14103 14104 if (size.getBitWidth() > index.getBitWidth()) 14105 index = index.zext(size.getBitWidth()); 14106 else if (size.getBitWidth() < index.getBitWidth()) 14107 size = size.zext(index.getBitWidth()); 14108 14109 // For array subscripting the index must be less than size, but for pointer 14110 // arithmetic also allow the index (offset) to be equal to size since 14111 // computing the next address after the end of the array is legal and 14112 // commonly done e.g. in C++ iterators and range-based for loops. 14113 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14114 return; 14115 14116 // Also don't warn for arrays of size 1 which are members of some 14117 // structure. These are often used to approximate flexible arrays in C89 14118 // code. 14119 if (IsTailPaddedMemberArray(*this, size, ND)) 14120 return; 14121 14122 // Suppress the warning if the subscript expression (as identified by the 14123 // ']' location) and the index expression are both from macro expansions 14124 // within a system header. 14125 if (ASE) { 14126 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14127 ASE->getRBracketLoc()); 14128 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14129 SourceLocation IndexLoc = 14130 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14131 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14132 return; 14133 } 14134 } 14135 14136 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 14137 if (ASE) 14138 DiagID = diag::warn_array_index_exceeds_bounds; 14139 14140 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14141 PDiag(DiagID) << index.toString(10, true) 14142 << size.toString(10, true) 14143 << (unsigned)size.getLimitedValue(~0U) 14144 << IndexExpr->getSourceRange()); 14145 } else { 14146 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14147 if (!ASE) { 14148 DiagID = diag::warn_ptr_arith_precedes_bounds; 14149 if (index.isNegative()) index = -index; 14150 } 14151 14152 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14153 PDiag(DiagID) << index.toString(10, true) 14154 << IndexExpr->getSourceRange()); 14155 } 14156 14157 if (!ND) { 14158 // Try harder to find a NamedDecl to point at in the note. 14159 while (const ArraySubscriptExpr *ASE = 14160 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14161 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14162 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14163 ND = DRE->getDecl(); 14164 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14165 ND = ME->getMemberDecl(); 14166 } 14167 14168 if (ND) 14169 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14170 PDiag(diag::note_array_declared_here) << ND); 14171 } 14172 14173 void Sema::CheckArrayAccess(const Expr *expr) { 14174 int AllowOnePastEnd = 0; 14175 while (expr) { 14176 expr = expr->IgnoreParenImpCasts(); 14177 switch (expr->getStmtClass()) { 14178 case Stmt::ArraySubscriptExprClass: { 14179 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14180 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14181 AllowOnePastEnd > 0); 14182 expr = ASE->getBase(); 14183 break; 14184 } 14185 case Stmt::MemberExprClass: { 14186 expr = cast<MemberExpr>(expr)->getBase(); 14187 break; 14188 } 14189 case Stmt::OMPArraySectionExprClass: { 14190 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14191 if (ASE->getLowerBound()) 14192 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14193 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14194 return; 14195 } 14196 case Stmt::UnaryOperatorClass: { 14197 // Only unwrap the * and & unary operators 14198 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14199 expr = UO->getSubExpr(); 14200 switch (UO->getOpcode()) { 14201 case UO_AddrOf: 14202 AllowOnePastEnd++; 14203 break; 14204 case UO_Deref: 14205 AllowOnePastEnd--; 14206 break; 14207 default: 14208 return; 14209 } 14210 break; 14211 } 14212 case Stmt::ConditionalOperatorClass: { 14213 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14214 if (const Expr *lhs = cond->getLHS()) 14215 CheckArrayAccess(lhs); 14216 if (const Expr *rhs = cond->getRHS()) 14217 CheckArrayAccess(rhs); 14218 return; 14219 } 14220 case Stmt::CXXOperatorCallExprClass: { 14221 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14222 for (const auto *Arg : OCE->arguments()) 14223 CheckArrayAccess(Arg); 14224 return; 14225 } 14226 default: 14227 return; 14228 } 14229 } 14230 } 14231 14232 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14233 14234 namespace { 14235 14236 struct RetainCycleOwner { 14237 VarDecl *Variable = nullptr; 14238 SourceRange Range; 14239 SourceLocation Loc; 14240 bool Indirect = false; 14241 14242 RetainCycleOwner() = default; 14243 14244 void setLocsFrom(Expr *e) { 14245 Loc = e->getExprLoc(); 14246 Range = e->getSourceRange(); 14247 } 14248 }; 14249 14250 } // namespace 14251 14252 /// Consider whether capturing the given variable can possibly lead to 14253 /// a retain cycle. 14254 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14255 // In ARC, it's captured strongly iff the variable has __strong 14256 // lifetime. In MRR, it's captured strongly if the variable is 14257 // __block and has an appropriate type. 14258 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14259 return false; 14260 14261 owner.Variable = var; 14262 if (ref) 14263 owner.setLocsFrom(ref); 14264 return true; 14265 } 14266 14267 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14268 while (true) { 14269 e = e->IgnoreParens(); 14270 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14271 switch (cast->getCastKind()) { 14272 case CK_BitCast: 14273 case CK_LValueBitCast: 14274 case CK_LValueToRValue: 14275 case CK_ARCReclaimReturnedObject: 14276 e = cast->getSubExpr(); 14277 continue; 14278 14279 default: 14280 return false; 14281 } 14282 } 14283 14284 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14285 ObjCIvarDecl *ivar = ref->getDecl(); 14286 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14287 return false; 14288 14289 // Try to find a retain cycle in the base. 14290 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14291 return false; 14292 14293 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14294 owner.Indirect = true; 14295 return true; 14296 } 14297 14298 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14299 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14300 if (!var) return false; 14301 return considerVariable(var, ref, owner); 14302 } 14303 14304 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14305 if (member->isArrow()) return false; 14306 14307 // Don't count this as an indirect ownership. 14308 e = member->getBase(); 14309 continue; 14310 } 14311 14312 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14313 // Only pay attention to pseudo-objects on property references. 14314 ObjCPropertyRefExpr *pre 14315 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14316 ->IgnoreParens()); 14317 if (!pre) return false; 14318 if (pre->isImplicitProperty()) return false; 14319 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14320 if (!property->isRetaining() && 14321 !(property->getPropertyIvarDecl() && 14322 property->getPropertyIvarDecl()->getType() 14323 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14324 return false; 14325 14326 owner.Indirect = true; 14327 if (pre->isSuperReceiver()) { 14328 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14329 if (!owner.Variable) 14330 return false; 14331 owner.Loc = pre->getLocation(); 14332 owner.Range = pre->getSourceRange(); 14333 return true; 14334 } 14335 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14336 ->getSourceExpr()); 14337 continue; 14338 } 14339 14340 // Array ivars? 14341 14342 return false; 14343 } 14344 } 14345 14346 namespace { 14347 14348 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14349 ASTContext &Context; 14350 VarDecl *Variable; 14351 Expr *Capturer = nullptr; 14352 bool VarWillBeReased = false; 14353 14354 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14355 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14356 Context(Context), Variable(variable) {} 14357 14358 void VisitDeclRefExpr(DeclRefExpr *ref) { 14359 if (ref->getDecl() == Variable && !Capturer) 14360 Capturer = ref; 14361 } 14362 14363 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14364 if (Capturer) return; 14365 Visit(ref->getBase()); 14366 if (Capturer && ref->isFreeIvar()) 14367 Capturer = ref; 14368 } 14369 14370 void VisitBlockExpr(BlockExpr *block) { 14371 // Look inside nested blocks 14372 if (block->getBlockDecl()->capturesVariable(Variable)) 14373 Visit(block->getBlockDecl()->getBody()); 14374 } 14375 14376 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14377 if (Capturer) return; 14378 if (OVE->getSourceExpr()) 14379 Visit(OVE->getSourceExpr()); 14380 } 14381 14382 void VisitBinaryOperator(BinaryOperator *BinOp) { 14383 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14384 return; 14385 Expr *LHS = BinOp->getLHS(); 14386 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14387 if (DRE->getDecl() != Variable) 14388 return; 14389 if (Expr *RHS = BinOp->getRHS()) { 14390 RHS = RHS->IgnoreParenCasts(); 14391 Optional<llvm::APSInt> Value; 14392 VarWillBeReased = 14393 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14394 *Value == 0); 14395 } 14396 } 14397 } 14398 }; 14399 14400 } // namespace 14401 14402 /// Check whether the given argument is a block which captures a 14403 /// variable. 14404 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14405 assert(owner.Variable && owner.Loc.isValid()); 14406 14407 e = e->IgnoreParenCasts(); 14408 14409 // Look through [^{...} copy] and Block_copy(^{...}). 14410 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14411 Selector Cmd = ME->getSelector(); 14412 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14413 e = ME->getInstanceReceiver(); 14414 if (!e) 14415 return nullptr; 14416 e = e->IgnoreParenCasts(); 14417 } 14418 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14419 if (CE->getNumArgs() == 1) { 14420 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14421 if (Fn) { 14422 const IdentifierInfo *FnI = Fn->getIdentifier(); 14423 if (FnI && FnI->isStr("_Block_copy")) { 14424 e = CE->getArg(0)->IgnoreParenCasts(); 14425 } 14426 } 14427 } 14428 } 14429 14430 BlockExpr *block = dyn_cast<BlockExpr>(e); 14431 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14432 return nullptr; 14433 14434 FindCaptureVisitor visitor(S.Context, owner.Variable); 14435 visitor.Visit(block->getBlockDecl()->getBody()); 14436 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14437 } 14438 14439 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14440 RetainCycleOwner &owner) { 14441 assert(capturer); 14442 assert(owner.Variable && owner.Loc.isValid()); 14443 14444 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14445 << owner.Variable << capturer->getSourceRange(); 14446 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14447 << owner.Indirect << owner.Range; 14448 } 14449 14450 /// Check for a keyword selector that starts with the word 'add' or 14451 /// 'set'. 14452 static bool isSetterLikeSelector(Selector sel) { 14453 if (sel.isUnarySelector()) return false; 14454 14455 StringRef str = sel.getNameForSlot(0); 14456 while (!str.empty() && str.front() == '_') str = str.substr(1); 14457 if (str.startswith("set")) 14458 str = str.substr(3); 14459 else if (str.startswith("add")) { 14460 // Specially allow 'addOperationWithBlock:'. 14461 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14462 return false; 14463 str = str.substr(3); 14464 } 14465 else 14466 return false; 14467 14468 if (str.empty()) return true; 14469 return !isLowercase(str.front()); 14470 } 14471 14472 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14473 ObjCMessageExpr *Message) { 14474 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14475 Message->getReceiverInterface(), 14476 NSAPI::ClassId_NSMutableArray); 14477 if (!IsMutableArray) { 14478 return None; 14479 } 14480 14481 Selector Sel = Message->getSelector(); 14482 14483 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14484 S.NSAPIObj->getNSArrayMethodKind(Sel); 14485 if (!MKOpt) { 14486 return None; 14487 } 14488 14489 NSAPI::NSArrayMethodKind MK = *MKOpt; 14490 14491 switch (MK) { 14492 case NSAPI::NSMutableArr_addObject: 14493 case NSAPI::NSMutableArr_insertObjectAtIndex: 14494 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14495 return 0; 14496 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14497 return 1; 14498 14499 default: 14500 return None; 14501 } 14502 14503 return None; 14504 } 14505 14506 static 14507 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14508 ObjCMessageExpr *Message) { 14509 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14510 Message->getReceiverInterface(), 14511 NSAPI::ClassId_NSMutableDictionary); 14512 if (!IsMutableDictionary) { 14513 return None; 14514 } 14515 14516 Selector Sel = Message->getSelector(); 14517 14518 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14519 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14520 if (!MKOpt) { 14521 return None; 14522 } 14523 14524 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14525 14526 switch (MK) { 14527 case NSAPI::NSMutableDict_setObjectForKey: 14528 case NSAPI::NSMutableDict_setValueForKey: 14529 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14530 return 0; 14531 14532 default: 14533 return None; 14534 } 14535 14536 return None; 14537 } 14538 14539 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14540 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14541 Message->getReceiverInterface(), 14542 NSAPI::ClassId_NSMutableSet); 14543 14544 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14545 Message->getReceiverInterface(), 14546 NSAPI::ClassId_NSMutableOrderedSet); 14547 if (!IsMutableSet && !IsMutableOrderedSet) { 14548 return None; 14549 } 14550 14551 Selector Sel = Message->getSelector(); 14552 14553 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14554 if (!MKOpt) { 14555 return None; 14556 } 14557 14558 NSAPI::NSSetMethodKind MK = *MKOpt; 14559 14560 switch (MK) { 14561 case NSAPI::NSMutableSet_addObject: 14562 case NSAPI::NSOrderedSet_setObjectAtIndex: 14563 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14564 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14565 return 0; 14566 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14567 return 1; 14568 } 14569 14570 return None; 14571 } 14572 14573 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14574 if (!Message->isInstanceMessage()) { 14575 return; 14576 } 14577 14578 Optional<int> ArgOpt; 14579 14580 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14581 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14582 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14583 return; 14584 } 14585 14586 int ArgIndex = *ArgOpt; 14587 14588 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14589 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14590 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14591 } 14592 14593 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14594 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14595 if (ArgRE->isObjCSelfExpr()) { 14596 Diag(Message->getSourceRange().getBegin(), 14597 diag::warn_objc_circular_container) 14598 << ArgRE->getDecl() << StringRef("'super'"); 14599 } 14600 } 14601 } else { 14602 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14603 14604 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14605 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14606 } 14607 14608 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14609 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14610 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14611 ValueDecl *Decl = ReceiverRE->getDecl(); 14612 Diag(Message->getSourceRange().getBegin(), 14613 diag::warn_objc_circular_container) 14614 << Decl << Decl; 14615 if (!ArgRE->isObjCSelfExpr()) { 14616 Diag(Decl->getLocation(), 14617 diag::note_objc_circular_container_declared_here) 14618 << Decl; 14619 } 14620 } 14621 } 14622 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14623 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14624 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14625 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14626 Diag(Message->getSourceRange().getBegin(), 14627 diag::warn_objc_circular_container) 14628 << Decl << Decl; 14629 Diag(Decl->getLocation(), 14630 diag::note_objc_circular_container_declared_here) 14631 << Decl; 14632 } 14633 } 14634 } 14635 } 14636 } 14637 14638 /// Check a message send to see if it's likely to cause a retain cycle. 14639 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14640 // Only check instance methods whose selector looks like a setter. 14641 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14642 return; 14643 14644 // Try to find a variable that the receiver is strongly owned by. 14645 RetainCycleOwner owner; 14646 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14647 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14648 return; 14649 } else { 14650 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14651 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14652 owner.Loc = msg->getSuperLoc(); 14653 owner.Range = msg->getSuperLoc(); 14654 } 14655 14656 // Check whether the receiver is captured by any of the arguments. 14657 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14658 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14659 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14660 // noescape blocks should not be retained by the method. 14661 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14662 continue; 14663 return diagnoseRetainCycle(*this, capturer, owner); 14664 } 14665 } 14666 } 14667 14668 /// Check a property assign to see if it's likely to cause a retain cycle. 14669 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14670 RetainCycleOwner owner; 14671 if (!findRetainCycleOwner(*this, receiver, owner)) 14672 return; 14673 14674 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14675 diagnoseRetainCycle(*this, capturer, owner); 14676 } 14677 14678 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14679 RetainCycleOwner Owner; 14680 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14681 return; 14682 14683 // Because we don't have an expression for the variable, we have to set the 14684 // location explicitly here. 14685 Owner.Loc = Var->getLocation(); 14686 Owner.Range = Var->getSourceRange(); 14687 14688 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14689 diagnoseRetainCycle(*this, Capturer, Owner); 14690 } 14691 14692 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14693 Expr *RHS, bool isProperty) { 14694 // Check if RHS is an Objective-C object literal, which also can get 14695 // immediately zapped in a weak reference. Note that we explicitly 14696 // allow ObjCStringLiterals, since those are designed to never really die. 14697 RHS = RHS->IgnoreParenImpCasts(); 14698 14699 // This enum needs to match with the 'select' in 14700 // warn_objc_arc_literal_assign (off-by-1). 14701 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14702 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14703 return false; 14704 14705 S.Diag(Loc, diag::warn_arc_literal_assign) 14706 << (unsigned) Kind 14707 << (isProperty ? 0 : 1) 14708 << RHS->getSourceRange(); 14709 14710 return true; 14711 } 14712 14713 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14714 Qualifiers::ObjCLifetime LT, 14715 Expr *RHS, bool isProperty) { 14716 // Strip off any implicit cast added to get to the one ARC-specific. 14717 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14718 if (cast->getCastKind() == CK_ARCConsumeObject) { 14719 S.Diag(Loc, diag::warn_arc_retained_assign) 14720 << (LT == Qualifiers::OCL_ExplicitNone) 14721 << (isProperty ? 0 : 1) 14722 << RHS->getSourceRange(); 14723 return true; 14724 } 14725 RHS = cast->getSubExpr(); 14726 } 14727 14728 if (LT == Qualifiers::OCL_Weak && 14729 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14730 return true; 14731 14732 return false; 14733 } 14734 14735 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14736 QualType LHS, Expr *RHS) { 14737 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14738 14739 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14740 return false; 14741 14742 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14743 return true; 14744 14745 return false; 14746 } 14747 14748 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14749 Expr *LHS, Expr *RHS) { 14750 QualType LHSType; 14751 // PropertyRef on LHS type need be directly obtained from 14752 // its declaration as it has a PseudoType. 14753 ObjCPropertyRefExpr *PRE 14754 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14755 if (PRE && !PRE->isImplicitProperty()) { 14756 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14757 if (PD) 14758 LHSType = PD->getType(); 14759 } 14760 14761 if (LHSType.isNull()) 14762 LHSType = LHS->getType(); 14763 14764 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14765 14766 if (LT == Qualifiers::OCL_Weak) { 14767 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14768 getCurFunction()->markSafeWeakUse(LHS); 14769 } 14770 14771 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14772 return; 14773 14774 // FIXME. Check for other life times. 14775 if (LT != Qualifiers::OCL_None) 14776 return; 14777 14778 if (PRE) { 14779 if (PRE->isImplicitProperty()) 14780 return; 14781 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14782 if (!PD) 14783 return; 14784 14785 unsigned Attributes = PD->getPropertyAttributes(); 14786 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14787 // when 'assign' attribute was not explicitly specified 14788 // by user, ignore it and rely on property type itself 14789 // for lifetime info. 14790 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14791 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 14792 LHSType->isObjCRetainableType()) 14793 return; 14794 14795 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14796 if (cast->getCastKind() == CK_ARCConsumeObject) { 14797 Diag(Loc, diag::warn_arc_retained_property_assign) 14798 << RHS->getSourceRange(); 14799 return; 14800 } 14801 RHS = cast->getSubExpr(); 14802 } 14803 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 14804 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14805 return; 14806 } 14807 } 14808 } 14809 14810 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14811 14812 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14813 SourceLocation StmtLoc, 14814 const NullStmt *Body) { 14815 // Do not warn if the body is a macro that expands to nothing, e.g: 14816 // 14817 // #define CALL(x) 14818 // if (condition) 14819 // CALL(0); 14820 if (Body->hasLeadingEmptyMacro()) 14821 return false; 14822 14823 // Get line numbers of statement and body. 14824 bool StmtLineInvalid; 14825 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14826 &StmtLineInvalid); 14827 if (StmtLineInvalid) 14828 return false; 14829 14830 bool BodyLineInvalid; 14831 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14832 &BodyLineInvalid); 14833 if (BodyLineInvalid) 14834 return false; 14835 14836 // Warn if null statement and body are on the same line. 14837 if (StmtLine != BodyLine) 14838 return false; 14839 14840 return true; 14841 } 14842 14843 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14844 const Stmt *Body, 14845 unsigned DiagID) { 14846 // Since this is a syntactic check, don't emit diagnostic for template 14847 // instantiations, this just adds noise. 14848 if (CurrentInstantiationScope) 14849 return; 14850 14851 // The body should be a null statement. 14852 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14853 if (!NBody) 14854 return; 14855 14856 // Do the usual checks. 14857 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14858 return; 14859 14860 Diag(NBody->getSemiLoc(), DiagID); 14861 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14862 } 14863 14864 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14865 const Stmt *PossibleBody) { 14866 assert(!CurrentInstantiationScope); // Ensured by caller 14867 14868 SourceLocation StmtLoc; 14869 const Stmt *Body; 14870 unsigned DiagID; 14871 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14872 StmtLoc = FS->getRParenLoc(); 14873 Body = FS->getBody(); 14874 DiagID = diag::warn_empty_for_body; 14875 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14876 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14877 Body = WS->getBody(); 14878 DiagID = diag::warn_empty_while_body; 14879 } else 14880 return; // Neither `for' nor `while'. 14881 14882 // The body should be a null statement. 14883 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14884 if (!NBody) 14885 return; 14886 14887 // Skip expensive checks if diagnostic is disabled. 14888 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14889 return; 14890 14891 // Do the usual checks. 14892 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14893 return; 14894 14895 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14896 // noise level low, emit diagnostics only if for/while is followed by a 14897 // CompoundStmt, e.g.: 14898 // for (int i = 0; i < n; i++); 14899 // { 14900 // a(i); 14901 // } 14902 // or if for/while is followed by a statement with more indentation 14903 // than for/while itself: 14904 // for (int i = 0; i < n; i++); 14905 // a(i); 14906 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14907 if (!ProbableTypo) { 14908 bool BodyColInvalid; 14909 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14910 PossibleBody->getBeginLoc(), &BodyColInvalid); 14911 if (BodyColInvalid) 14912 return; 14913 14914 bool StmtColInvalid; 14915 unsigned StmtCol = 14916 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14917 if (StmtColInvalid) 14918 return; 14919 14920 if (BodyCol > StmtCol) 14921 ProbableTypo = true; 14922 } 14923 14924 if (ProbableTypo) { 14925 Diag(NBody->getSemiLoc(), DiagID); 14926 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14927 } 14928 } 14929 14930 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14931 14932 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14933 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14934 SourceLocation OpLoc) { 14935 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14936 return; 14937 14938 if (inTemplateInstantiation()) 14939 return; 14940 14941 // Strip parens and casts away. 14942 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14943 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14944 14945 // Check for a call expression 14946 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14947 if (!CE || CE->getNumArgs() != 1) 14948 return; 14949 14950 // Check for a call to std::move 14951 if (!CE->isCallToStdMove()) 14952 return; 14953 14954 // Get argument from std::move 14955 RHSExpr = CE->getArg(0); 14956 14957 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14958 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14959 14960 // Two DeclRefExpr's, check that the decls are the same. 14961 if (LHSDeclRef && RHSDeclRef) { 14962 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14963 return; 14964 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14965 RHSDeclRef->getDecl()->getCanonicalDecl()) 14966 return; 14967 14968 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14969 << LHSExpr->getSourceRange() 14970 << RHSExpr->getSourceRange(); 14971 return; 14972 } 14973 14974 // Member variables require a different approach to check for self moves. 14975 // MemberExpr's are the same if every nested MemberExpr refers to the same 14976 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14977 // the base Expr's are CXXThisExpr's. 14978 const Expr *LHSBase = LHSExpr; 14979 const Expr *RHSBase = RHSExpr; 14980 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14981 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14982 if (!LHSME || !RHSME) 14983 return; 14984 14985 while (LHSME && RHSME) { 14986 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14987 RHSME->getMemberDecl()->getCanonicalDecl()) 14988 return; 14989 14990 LHSBase = LHSME->getBase(); 14991 RHSBase = RHSME->getBase(); 14992 LHSME = dyn_cast<MemberExpr>(LHSBase); 14993 RHSME = dyn_cast<MemberExpr>(RHSBase); 14994 } 14995 14996 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14997 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14998 if (LHSDeclRef && RHSDeclRef) { 14999 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15000 return; 15001 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15002 RHSDeclRef->getDecl()->getCanonicalDecl()) 15003 return; 15004 15005 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15006 << LHSExpr->getSourceRange() 15007 << RHSExpr->getSourceRange(); 15008 return; 15009 } 15010 15011 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15012 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15013 << LHSExpr->getSourceRange() 15014 << RHSExpr->getSourceRange(); 15015 } 15016 15017 //===--- Layout compatibility ----------------------------------------------// 15018 15019 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15020 15021 /// Check if two enumeration types are layout-compatible. 15022 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15023 // C++11 [dcl.enum] p8: 15024 // Two enumeration types are layout-compatible if they have the same 15025 // underlying type. 15026 return ED1->isComplete() && ED2->isComplete() && 15027 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15028 } 15029 15030 /// Check if two fields are layout-compatible. 15031 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15032 FieldDecl *Field2) { 15033 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15034 return false; 15035 15036 if (Field1->isBitField() != Field2->isBitField()) 15037 return false; 15038 15039 if (Field1->isBitField()) { 15040 // Make sure that the bit-fields are the same length. 15041 unsigned Bits1 = Field1->getBitWidthValue(C); 15042 unsigned Bits2 = Field2->getBitWidthValue(C); 15043 15044 if (Bits1 != Bits2) 15045 return false; 15046 } 15047 15048 return true; 15049 } 15050 15051 /// Check if two standard-layout structs are layout-compatible. 15052 /// (C++11 [class.mem] p17) 15053 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15054 RecordDecl *RD2) { 15055 // If both records are C++ classes, check that base classes match. 15056 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15057 // If one of records is a CXXRecordDecl we are in C++ mode, 15058 // thus the other one is a CXXRecordDecl, too. 15059 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15060 // Check number of base classes. 15061 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15062 return false; 15063 15064 // Check the base classes. 15065 for (CXXRecordDecl::base_class_const_iterator 15066 Base1 = D1CXX->bases_begin(), 15067 BaseEnd1 = D1CXX->bases_end(), 15068 Base2 = D2CXX->bases_begin(); 15069 Base1 != BaseEnd1; 15070 ++Base1, ++Base2) { 15071 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15072 return false; 15073 } 15074 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15075 // If only RD2 is a C++ class, it should have zero base classes. 15076 if (D2CXX->getNumBases() > 0) 15077 return false; 15078 } 15079 15080 // Check the fields. 15081 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15082 Field2End = RD2->field_end(), 15083 Field1 = RD1->field_begin(), 15084 Field1End = RD1->field_end(); 15085 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15086 if (!isLayoutCompatible(C, *Field1, *Field2)) 15087 return false; 15088 } 15089 if (Field1 != Field1End || Field2 != Field2End) 15090 return false; 15091 15092 return true; 15093 } 15094 15095 /// Check if two standard-layout unions are layout-compatible. 15096 /// (C++11 [class.mem] p18) 15097 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15098 RecordDecl *RD2) { 15099 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15100 for (auto *Field2 : RD2->fields()) 15101 UnmatchedFields.insert(Field2); 15102 15103 for (auto *Field1 : RD1->fields()) { 15104 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15105 I = UnmatchedFields.begin(), 15106 E = UnmatchedFields.end(); 15107 15108 for ( ; I != E; ++I) { 15109 if (isLayoutCompatible(C, Field1, *I)) { 15110 bool Result = UnmatchedFields.erase(*I); 15111 (void) Result; 15112 assert(Result); 15113 break; 15114 } 15115 } 15116 if (I == E) 15117 return false; 15118 } 15119 15120 return UnmatchedFields.empty(); 15121 } 15122 15123 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15124 RecordDecl *RD2) { 15125 if (RD1->isUnion() != RD2->isUnion()) 15126 return false; 15127 15128 if (RD1->isUnion()) 15129 return isLayoutCompatibleUnion(C, RD1, RD2); 15130 else 15131 return isLayoutCompatibleStruct(C, RD1, RD2); 15132 } 15133 15134 /// Check if two types are layout-compatible in C++11 sense. 15135 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15136 if (T1.isNull() || T2.isNull()) 15137 return false; 15138 15139 // C++11 [basic.types] p11: 15140 // If two types T1 and T2 are the same type, then T1 and T2 are 15141 // layout-compatible types. 15142 if (C.hasSameType(T1, T2)) 15143 return true; 15144 15145 T1 = T1.getCanonicalType().getUnqualifiedType(); 15146 T2 = T2.getCanonicalType().getUnqualifiedType(); 15147 15148 const Type::TypeClass TC1 = T1->getTypeClass(); 15149 const Type::TypeClass TC2 = T2->getTypeClass(); 15150 15151 if (TC1 != TC2) 15152 return false; 15153 15154 if (TC1 == Type::Enum) { 15155 return isLayoutCompatible(C, 15156 cast<EnumType>(T1)->getDecl(), 15157 cast<EnumType>(T2)->getDecl()); 15158 } else if (TC1 == Type::Record) { 15159 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15160 return false; 15161 15162 return isLayoutCompatible(C, 15163 cast<RecordType>(T1)->getDecl(), 15164 cast<RecordType>(T2)->getDecl()); 15165 } 15166 15167 return false; 15168 } 15169 15170 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15171 15172 /// Given a type tag expression find the type tag itself. 15173 /// 15174 /// \param TypeExpr Type tag expression, as it appears in user's code. 15175 /// 15176 /// \param VD Declaration of an identifier that appears in a type tag. 15177 /// 15178 /// \param MagicValue Type tag magic value. 15179 /// 15180 /// \param isConstantEvaluated wether the evalaution should be performed in 15181 15182 /// constant context. 15183 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15184 const ValueDecl **VD, uint64_t *MagicValue, 15185 bool isConstantEvaluated) { 15186 while(true) { 15187 if (!TypeExpr) 15188 return false; 15189 15190 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15191 15192 switch (TypeExpr->getStmtClass()) { 15193 case Stmt::UnaryOperatorClass: { 15194 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15195 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15196 TypeExpr = UO->getSubExpr(); 15197 continue; 15198 } 15199 return false; 15200 } 15201 15202 case Stmt::DeclRefExprClass: { 15203 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15204 *VD = DRE->getDecl(); 15205 return true; 15206 } 15207 15208 case Stmt::IntegerLiteralClass: { 15209 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15210 llvm::APInt MagicValueAPInt = IL->getValue(); 15211 if (MagicValueAPInt.getActiveBits() <= 64) { 15212 *MagicValue = MagicValueAPInt.getZExtValue(); 15213 return true; 15214 } else 15215 return false; 15216 } 15217 15218 case Stmt::BinaryConditionalOperatorClass: 15219 case Stmt::ConditionalOperatorClass: { 15220 const AbstractConditionalOperator *ACO = 15221 cast<AbstractConditionalOperator>(TypeExpr); 15222 bool Result; 15223 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15224 isConstantEvaluated)) { 15225 if (Result) 15226 TypeExpr = ACO->getTrueExpr(); 15227 else 15228 TypeExpr = ACO->getFalseExpr(); 15229 continue; 15230 } 15231 return false; 15232 } 15233 15234 case Stmt::BinaryOperatorClass: { 15235 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15236 if (BO->getOpcode() == BO_Comma) { 15237 TypeExpr = BO->getRHS(); 15238 continue; 15239 } 15240 return false; 15241 } 15242 15243 default: 15244 return false; 15245 } 15246 } 15247 } 15248 15249 /// Retrieve the C type corresponding to type tag TypeExpr. 15250 /// 15251 /// \param TypeExpr Expression that specifies a type tag. 15252 /// 15253 /// \param MagicValues Registered magic values. 15254 /// 15255 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15256 /// kind. 15257 /// 15258 /// \param TypeInfo Information about the corresponding C type. 15259 /// 15260 /// \param isConstantEvaluated wether the evalaution should be performed in 15261 /// constant context. 15262 /// 15263 /// \returns true if the corresponding C type was found. 15264 static bool GetMatchingCType( 15265 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15266 const ASTContext &Ctx, 15267 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15268 *MagicValues, 15269 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15270 bool isConstantEvaluated) { 15271 FoundWrongKind = false; 15272 15273 // Variable declaration that has type_tag_for_datatype attribute. 15274 const ValueDecl *VD = nullptr; 15275 15276 uint64_t MagicValue; 15277 15278 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15279 return false; 15280 15281 if (VD) { 15282 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15283 if (I->getArgumentKind() != ArgumentKind) { 15284 FoundWrongKind = true; 15285 return false; 15286 } 15287 TypeInfo.Type = I->getMatchingCType(); 15288 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15289 TypeInfo.MustBeNull = I->getMustBeNull(); 15290 return true; 15291 } 15292 return false; 15293 } 15294 15295 if (!MagicValues) 15296 return false; 15297 15298 llvm::DenseMap<Sema::TypeTagMagicValue, 15299 Sema::TypeTagData>::const_iterator I = 15300 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15301 if (I == MagicValues->end()) 15302 return false; 15303 15304 TypeInfo = I->second; 15305 return true; 15306 } 15307 15308 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15309 uint64_t MagicValue, QualType Type, 15310 bool LayoutCompatible, 15311 bool MustBeNull) { 15312 if (!TypeTagForDatatypeMagicValues) 15313 TypeTagForDatatypeMagicValues.reset( 15314 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15315 15316 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15317 (*TypeTagForDatatypeMagicValues)[Magic] = 15318 TypeTagData(Type, LayoutCompatible, MustBeNull); 15319 } 15320 15321 static bool IsSameCharType(QualType T1, QualType T2) { 15322 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15323 if (!BT1) 15324 return false; 15325 15326 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15327 if (!BT2) 15328 return false; 15329 15330 BuiltinType::Kind T1Kind = BT1->getKind(); 15331 BuiltinType::Kind T2Kind = BT2->getKind(); 15332 15333 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15334 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15335 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15336 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15337 } 15338 15339 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15340 const ArrayRef<const Expr *> ExprArgs, 15341 SourceLocation CallSiteLoc) { 15342 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15343 bool IsPointerAttr = Attr->getIsPointer(); 15344 15345 // Retrieve the argument representing the 'type_tag'. 15346 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15347 if (TypeTagIdxAST >= ExprArgs.size()) { 15348 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15349 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15350 return; 15351 } 15352 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15353 bool FoundWrongKind; 15354 TypeTagData TypeInfo; 15355 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15356 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15357 TypeInfo, isConstantEvaluated())) { 15358 if (FoundWrongKind) 15359 Diag(TypeTagExpr->getExprLoc(), 15360 diag::warn_type_tag_for_datatype_wrong_kind) 15361 << TypeTagExpr->getSourceRange(); 15362 return; 15363 } 15364 15365 // Retrieve the argument representing the 'arg_idx'. 15366 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15367 if (ArgumentIdxAST >= ExprArgs.size()) { 15368 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15369 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15370 return; 15371 } 15372 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15373 if (IsPointerAttr) { 15374 // Skip implicit cast of pointer to `void *' (as a function argument). 15375 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15376 if (ICE->getType()->isVoidPointerType() && 15377 ICE->getCastKind() == CK_BitCast) 15378 ArgumentExpr = ICE->getSubExpr(); 15379 } 15380 QualType ArgumentType = ArgumentExpr->getType(); 15381 15382 // Passing a `void*' pointer shouldn't trigger a warning. 15383 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15384 return; 15385 15386 if (TypeInfo.MustBeNull) { 15387 // Type tag with matching void type requires a null pointer. 15388 if (!ArgumentExpr->isNullPointerConstant(Context, 15389 Expr::NPC_ValueDependentIsNotNull)) { 15390 Diag(ArgumentExpr->getExprLoc(), 15391 diag::warn_type_safety_null_pointer_required) 15392 << ArgumentKind->getName() 15393 << ArgumentExpr->getSourceRange() 15394 << TypeTagExpr->getSourceRange(); 15395 } 15396 return; 15397 } 15398 15399 QualType RequiredType = TypeInfo.Type; 15400 if (IsPointerAttr) 15401 RequiredType = Context.getPointerType(RequiredType); 15402 15403 bool mismatch = false; 15404 if (!TypeInfo.LayoutCompatible) { 15405 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15406 15407 // C++11 [basic.fundamental] p1: 15408 // Plain char, signed char, and unsigned char are three distinct types. 15409 // 15410 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15411 // char' depending on the current char signedness mode. 15412 if (mismatch) 15413 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15414 RequiredType->getPointeeType())) || 15415 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15416 mismatch = false; 15417 } else 15418 if (IsPointerAttr) 15419 mismatch = !isLayoutCompatible(Context, 15420 ArgumentType->getPointeeType(), 15421 RequiredType->getPointeeType()); 15422 else 15423 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15424 15425 if (mismatch) 15426 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15427 << ArgumentType << ArgumentKind 15428 << TypeInfo.LayoutCompatible << RequiredType 15429 << ArgumentExpr->getSourceRange() 15430 << TypeTagExpr->getSourceRange(); 15431 } 15432 15433 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15434 CharUnits Alignment) { 15435 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15436 } 15437 15438 void Sema::DiagnoseMisalignedMembers() { 15439 for (MisalignedMember &m : MisalignedMembers) { 15440 const NamedDecl *ND = m.RD; 15441 if (ND->getName().empty()) { 15442 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15443 ND = TD; 15444 } 15445 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15446 << m.MD << ND << m.E->getSourceRange(); 15447 } 15448 MisalignedMembers.clear(); 15449 } 15450 15451 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15452 E = E->IgnoreParens(); 15453 if (!T->isPointerType() && !T->isIntegerType()) 15454 return; 15455 if (isa<UnaryOperator>(E) && 15456 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15457 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15458 if (isa<MemberExpr>(Op)) { 15459 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15460 if (MA != MisalignedMembers.end() && 15461 (T->isIntegerType() || 15462 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15463 Context.getTypeAlignInChars( 15464 T->getPointeeType()) <= MA->Alignment)))) 15465 MisalignedMembers.erase(MA); 15466 } 15467 } 15468 } 15469 15470 void Sema::RefersToMemberWithReducedAlignment( 15471 Expr *E, 15472 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15473 Action) { 15474 const auto *ME = dyn_cast<MemberExpr>(E); 15475 if (!ME) 15476 return; 15477 15478 // No need to check expressions with an __unaligned-qualified type. 15479 if (E->getType().getQualifiers().hasUnaligned()) 15480 return; 15481 15482 // For a chain of MemberExpr like "a.b.c.d" this list 15483 // will keep FieldDecl's like [d, c, b]. 15484 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15485 const MemberExpr *TopME = nullptr; 15486 bool AnyIsPacked = false; 15487 do { 15488 QualType BaseType = ME->getBase()->getType(); 15489 if (BaseType->isDependentType()) 15490 return; 15491 if (ME->isArrow()) 15492 BaseType = BaseType->getPointeeType(); 15493 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15494 if (RD->isInvalidDecl()) 15495 return; 15496 15497 ValueDecl *MD = ME->getMemberDecl(); 15498 auto *FD = dyn_cast<FieldDecl>(MD); 15499 // We do not care about non-data members. 15500 if (!FD || FD->isInvalidDecl()) 15501 return; 15502 15503 AnyIsPacked = 15504 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15505 ReverseMemberChain.push_back(FD); 15506 15507 TopME = ME; 15508 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15509 } while (ME); 15510 assert(TopME && "We did not compute a topmost MemberExpr!"); 15511 15512 // Not the scope of this diagnostic. 15513 if (!AnyIsPacked) 15514 return; 15515 15516 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15517 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15518 // TODO: The innermost base of the member expression may be too complicated. 15519 // For now, just disregard these cases. This is left for future 15520 // improvement. 15521 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15522 return; 15523 15524 // Alignment expected by the whole expression. 15525 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15526 15527 // No need to do anything else with this case. 15528 if (ExpectedAlignment.isOne()) 15529 return; 15530 15531 // Synthesize offset of the whole access. 15532 CharUnits Offset; 15533 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15534 I++) { 15535 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15536 } 15537 15538 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15539 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15540 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15541 15542 // The base expression of the innermost MemberExpr may give 15543 // stronger guarantees than the class containing the member. 15544 if (DRE && !TopME->isArrow()) { 15545 const ValueDecl *VD = DRE->getDecl(); 15546 if (!VD->getType()->isReferenceType()) 15547 CompleteObjectAlignment = 15548 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15549 } 15550 15551 // Check if the synthesized offset fulfills the alignment. 15552 if (Offset % ExpectedAlignment != 0 || 15553 // It may fulfill the offset it but the effective alignment may still be 15554 // lower than the expected expression alignment. 15555 CompleteObjectAlignment < ExpectedAlignment) { 15556 // If this happens, we want to determine a sensible culprit of this. 15557 // Intuitively, watching the chain of member expressions from right to 15558 // left, we start with the required alignment (as required by the field 15559 // type) but some packed attribute in that chain has reduced the alignment. 15560 // It may happen that another packed structure increases it again. But if 15561 // we are here such increase has not been enough. So pointing the first 15562 // FieldDecl that either is packed or else its RecordDecl is, 15563 // seems reasonable. 15564 FieldDecl *FD = nullptr; 15565 CharUnits Alignment; 15566 for (FieldDecl *FDI : ReverseMemberChain) { 15567 if (FDI->hasAttr<PackedAttr>() || 15568 FDI->getParent()->hasAttr<PackedAttr>()) { 15569 FD = FDI; 15570 Alignment = std::min( 15571 Context.getTypeAlignInChars(FD->getType()), 15572 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15573 break; 15574 } 15575 } 15576 assert(FD && "We did not find a packed FieldDecl!"); 15577 Action(E, FD->getParent(), FD, Alignment); 15578 } 15579 } 15580 15581 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15582 using namespace std::placeholders; 15583 15584 RefersToMemberWithReducedAlignment( 15585 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15586 _2, _3, _4)); 15587 } 15588 15589 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15590 ExprResult CallResult) { 15591 if (checkArgCount(*this, TheCall, 1)) 15592 return ExprError(); 15593 15594 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15595 if (MatrixArg.isInvalid()) 15596 return MatrixArg; 15597 Expr *Matrix = MatrixArg.get(); 15598 15599 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15600 if (!MType) { 15601 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15602 return ExprError(); 15603 } 15604 15605 // Create returned matrix type by swapping rows and columns of the argument 15606 // matrix type. 15607 QualType ResultType = Context.getConstantMatrixType( 15608 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15609 15610 // Change the return type to the type of the returned matrix. 15611 TheCall->setType(ResultType); 15612 15613 // Update call argument to use the possibly converted matrix argument. 15614 TheCall->setArg(0, Matrix); 15615 return CallResult; 15616 } 15617 15618 // Get and verify the matrix dimensions. 15619 static llvm::Optional<unsigned> 15620 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15621 SourceLocation ErrorPos; 15622 Optional<llvm::APSInt> Value = 15623 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 15624 if (!Value) { 15625 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 15626 << Name; 15627 return {}; 15628 } 15629 uint64_t Dim = Value->getZExtValue(); 15630 if (!ConstantMatrixType::isDimensionValid(Dim)) { 15631 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 15632 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 15633 return {}; 15634 } 15635 return Dim; 15636 } 15637 15638 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 15639 ExprResult CallResult) { 15640 if (!getLangOpts().MatrixTypes) { 15641 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 15642 return ExprError(); 15643 } 15644 15645 if (checkArgCount(*this, TheCall, 4)) 15646 return ExprError(); 15647 15648 unsigned PtrArgIdx = 0; 15649 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15650 Expr *RowsExpr = TheCall->getArg(1); 15651 Expr *ColumnsExpr = TheCall->getArg(2); 15652 Expr *StrideExpr = TheCall->getArg(3); 15653 15654 bool ArgError = false; 15655 15656 // Check pointer argument. 15657 { 15658 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15659 if (PtrConv.isInvalid()) 15660 return PtrConv; 15661 PtrExpr = PtrConv.get(); 15662 TheCall->setArg(0, PtrExpr); 15663 if (PtrExpr->isTypeDependent()) { 15664 TheCall->setType(Context.DependentTy); 15665 return TheCall; 15666 } 15667 } 15668 15669 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15670 QualType ElementTy; 15671 if (!PtrTy) { 15672 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15673 << PtrArgIdx + 1; 15674 ArgError = true; 15675 } else { 15676 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 15677 15678 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 15679 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15680 << PtrArgIdx + 1; 15681 ArgError = true; 15682 } 15683 } 15684 15685 // Apply default Lvalue conversions and convert the expression to size_t. 15686 auto ApplyArgumentConversions = [this](Expr *E) { 15687 ExprResult Conv = DefaultLvalueConversion(E); 15688 if (Conv.isInvalid()) 15689 return Conv; 15690 15691 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 15692 }; 15693 15694 // Apply conversion to row and column expressions. 15695 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 15696 if (!RowsConv.isInvalid()) { 15697 RowsExpr = RowsConv.get(); 15698 TheCall->setArg(1, RowsExpr); 15699 } else 15700 RowsExpr = nullptr; 15701 15702 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 15703 if (!ColumnsConv.isInvalid()) { 15704 ColumnsExpr = ColumnsConv.get(); 15705 TheCall->setArg(2, ColumnsExpr); 15706 } else 15707 ColumnsExpr = nullptr; 15708 15709 // If any any part of the result matrix type is still pending, just use 15710 // Context.DependentTy, until all parts are resolved. 15711 if ((RowsExpr && RowsExpr->isTypeDependent()) || 15712 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 15713 TheCall->setType(Context.DependentTy); 15714 return CallResult; 15715 } 15716 15717 // Check row and column dimenions. 15718 llvm::Optional<unsigned> MaybeRows; 15719 if (RowsExpr) 15720 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 15721 15722 llvm::Optional<unsigned> MaybeColumns; 15723 if (ColumnsExpr) 15724 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 15725 15726 // Check stride argument. 15727 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 15728 if (StrideConv.isInvalid()) 15729 return ExprError(); 15730 StrideExpr = StrideConv.get(); 15731 TheCall->setArg(3, StrideExpr); 15732 15733 if (MaybeRows) { 15734 if (Optional<llvm::APSInt> Value = 15735 StrideExpr->getIntegerConstantExpr(Context)) { 15736 uint64_t Stride = Value->getZExtValue(); 15737 if (Stride < *MaybeRows) { 15738 Diag(StrideExpr->getBeginLoc(), 15739 diag::err_builtin_matrix_stride_too_small); 15740 ArgError = true; 15741 } 15742 } 15743 } 15744 15745 if (ArgError || !MaybeRows || !MaybeColumns) 15746 return ExprError(); 15747 15748 TheCall->setType( 15749 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 15750 return CallResult; 15751 } 15752 15753 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 15754 ExprResult CallResult) { 15755 if (checkArgCount(*this, TheCall, 3)) 15756 return ExprError(); 15757 15758 unsigned PtrArgIdx = 1; 15759 Expr *MatrixExpr = TheCall->getArg(0); 15760 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15761 Expr *StrideExpr = TheCall->getArg(2); 15762 15763 bool ArgError = false; 15764 15765 { 15766 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 15767 if (MatrixConv.isInvalid()) 15768 return MatrixConv; 15769 MatrixExpr = MatrixConv.get(); 15770 TheCall->setArg(0, MatrixExpr); 15771 } 15772 if (MatrixExpr->isTypeDependent()) { 15773 TheCall->setType(Context.DependentTy); 15774 return TheCall; 15775 } 15776 15777 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 15778 if (!MatrixTy) { 15779 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15780 ArgError = true; 15781 } 15782 15783 { 15784 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15785 if (PtrConv.isInvalid()) 15786 return PtrConv; 15787 PtrExpr = PtrConv.get(); 15788 TheCall->setArg(1, PtrExpr); 15789 if (PtrExpr->isTypeDependent()) { 15790 TheCall->setType(Context.DependentTy); 15791 return TheCall; 15792 } 15793 } 15794 15795 // Check pointer argument. 15796 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15797 if (!PtrTy) { 15798 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15799 << PtrArgIdx + 1; 15800 ArgError = true; 15801 } else { 15802 QualType ElementTy = PtrTy->getPointeeType(); 15803 if (ElementTy.isConstQualified()) { 15804 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 15805 ArgError = true; 15806 } 15807 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 15808 if (MatrixTy && 15809 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 15810 Diag(PtrExpr->getBeginLoc(), 15811 diag::err_builtin_matrix_pointer_arg_mismatch) 15812 << ElementTy << MatrixTy->getElementType(); 15813 ArgError = true; 15814 } 15815 } 15816 15817 // Apply default Lvalue conversions and convert the stride expression to 15818 // size_t. 15819 { 15820 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 15821 if (StrideConv.isInvalid()) 15822 return StrideConv; 15823 15824 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 15825 if (StrideConv.isInvalid()) 15826 return StrideConv; 15827 StrideExpr = StrideConv.get(); 15828 TheCall->setArg(2, StrideExpr); 15829 } 15830 15831 // Check stride argument. 15832 if (MatrixTy) { 15833 if (Optional<llvm::APSInt> Value = 15834 StrideExpr->getIntegerConstantExpr(Context)) { 15835 uint64_t Stride = Value->getZExtValue(); 15836 if (Stride < MatrixTy->getNumRows()) { 15837 Diag(StrideExpr->getBeginLoc(), 15838 diag::err_builtin_matrix_stride_too_small); 15839 ArgError = true; 15840 } 15841 } 15842 } 15843 15844 if (ArgError) 15845 return ExprError(); 15846 15847 return CallResult; 15848 } 15849