1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 592 /// __builtin_*_chk function, then use the object size argument specified in the 593 /// source. Otherwise, infer the object size using __builtin_object_size. 594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 595 CallExpr *TheCall) { 596 // FIXME: There are some more useful checks we could be doing here: 597 // - Evaluate strlen of strcpy arguments, use as object size. 598 599 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 600 isConstantEvaluated()) 601 return; 602 603 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 604 if (!BuiltinID) 605 return; 606 607 const TargetInfo &TI = getASTContext().getTargetInfo(); 608 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 609 610 unsigned DiagID = 0; 611 bool IsChkVariant = false; 612 Optional<llvm::APSInt> UsedSize; 613 unsigned SizeIndex, ObjectIndex; 614 switch (BuiltinID) { 615 default: 616 return; 617 case Builtin::BIsprintf: 618 case Builtin::BI__builtin___sprintf_chk: { 619 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 620 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 621 622 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 623 624 if (!Format->isAscii() && !Format->isUTF8()) 625 return; 626 627 StringRef FormatStrRef = Format->getString(); 628 EstimateSizeFormatHandler H(FormatStrRef); 629 const char *FormatBytes = FormatStrRef.data(); 630 const ConstantArrayType *T = 631 Context.getAsConstantArrayType(Format->getType()); 632 assert(T && "String literal not of constant array type!"); 633 size_t TypeSize = T->getSize().getZExtValue(); 634 635 // In case there's a null byte somewhere. 636 size_t StrLen = 637 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 638 if (!analyze_format_string::ParsePrintfString( 639 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 640 Context.getTargetInfo(), false)) { 641 DiagID = diag::warn_fortify_source_format_overflow; 642 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 643 .extOrTrunc(SizeTypeWidth); 644 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 645 IsChkVariant = true; 646 ObjectIndex = 2; 647 } else { 648 IsChkVariant = false; 649 ObjectIndex = 0; 650 } 651 break; 652 } 653 } 654 return; 655 } 656 case Builtin::BI__builtin___memcpy_chk: 657 case Builtin::BI__builtin___memmove_chk: 658 case Builtin::BI__builtin___memset_chk: 659 case Builtin::BI__builtin___strlcat_chk: 660 case Builtin::BI__builtin___strlcpy_chk: 661 case Builtin::BI__builtin___strncat_chk: 662 case Builtin::BI__builtin___strncpy_chk: 663 case Builtin::BI__builtin___stpncpy_chk: 664 case Builtin::BI__builtin___memccpy_chk: 665 case Builtin::BI__builtin___mempcpy_chk: { 666 DiagID = diag::warn_builtin_chk_overflow; 667 IsChkVariant = true; 668 SizeIndex = TheCall->getNumArgs() - 2; 669 ObjectIndex = TheCall->getNumArgs() - 1; 670 break; 671 } 672 673 case Builtin::BI__builtin___snprintf_chk: 674 case Builtin::BI__builtin___vsnprintf_chk: { 675 DiagID = diag::warn_builtin_chk_overflow; 676 IsChkVariant = true; 677 SizeIndex = 1; 678 ObjectIndex = 3; 679 break; 680 } 681 682 case Builtin::BIstrncat: 683 case Builtin::BI__builtin_strncat: 684 case Builtin::BIstrncpy: 685 case Builtin::BI__builtin_strncpy: 686 case Builtin::BIstpncpy: 687 case Builtin::BI__builtin_stpncpy: { 688 // Whether these functions overflow depends on the runtime strlen of the 689 // string, not just the buffer size, so emitting the "always overflow" 690 // diagnostic isn't quite right. We should still diagnose passing a buffer 691 // size larger than the destination buffer though; this is a runtime abort 692 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 693 DiagID = diag::warn_fortify_source_size_mismatch; 694 SizeIndex = TheCall->getNumArgs() - 1; 695 ObjectIndex = 0; 696 break; 697 } 698 699 case Builtin::BImemcpy: 700 case Builtin::BI__builtin_memcpy: 701 case Builtin::BImemmove: 702 case Builtin::BI__builtin_memmove: 703 case Builtin::BImemset: 704 case Builtin::BI__builtin_memset: 705 case Builtin::BImempcpy: 706 case Builtin::BI__builtin_mempcpy: { 707 DiagID = diag::warn_fortify_source_overflow; 708 SizeIndex = TheCall->getNumArgs() - 1; 709 ObjectIndex = 0; 710 break; 711 } 712 case Builtin::BIsnprintf: 713 case Builtin::BI__builtin_snprintf: 714 case Builtin::BIvsnprintf: 715 case Builtin::BI__builtin_vsnprintf: { 716 DiagID = diag::warn_fortify_source_size_mismatch; 717 SizeIndex = 1; 718 ObjectIndex = 0; 719 break; 720 } 721 } 722 723 llvm::APSInt ObjectSize; 724 // For __builtin___*_chk, the object size is explicitly provided by the caller 725 // (usually using __builtin_object_size). Use that value to check this call. 726 if (IsChkVariant) { 727 Expr::EvalResult Result; 728 Expr *SizeArg = TheCall->getArg(ObjectIndex); 729 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 730 return; 731 ObjectSize = Result.Val.getInt(); 732 733 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 734 } else { 735 // If the parameter has a pass_object_size attribute, then we should use its 736 // (potentially) more strict checking mode. Otherwise, conservatively assume 737 // type 0. 738 int BOSType = 0; 739 if (const auto *POS = 740 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 741 BOSType = POS->getType(); 742 743 Expr *ObjArg = TheCall->getArg(ObjectIndex); 744 uint64_t Result; 745 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 746 return; 747 // Get the object size in the target's size_t width. 748 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 749 } 750 751 // Evaluate the number of bytes of the object that this call will use. 752 if (!UsedSize) { 753 Expr::EvalResult Result; 754 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 755 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 756 return; 757 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 758 } 759 760 if (UsedSize.getValue().ule(ObjectSize)) 761 return; 762 763 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 764 // Skim off the details of whichever builtin was called to produce a better 765 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 766 if (IsChkVariant) { 767 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 768 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 769 } else if (FunctionName.startswith("__builtin_")) { 770 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 771 } 772 773 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 774 PDiag(DiagID) 775 << FunctionName << toString(ObjectSize, /*Radix=*/10) 776 << toString(UsedSize.getValue(), /*Radix=*/10)); 777 } 778 779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 780 Scope::ScopeFlags NeededScopeFlags, 781 unsigned DiagID) { 782 // Scopes aren't available during instantiation. Fortunately, builtin 783 // functions cannot be template args so they cannot be formed through template 784 // instantiation. Therefore checking once during the parse is sufficient. 785 if (SemaRef.inTemplateInstantiation()) 786 return false; 787 788 Scope *S = SemaRef.getCurScope(); 789 while (S && !S->isSEHExceptScope()) 790 S = S->getParent(); 791 if (!S || !(S->getFlags() & NeededScopeFlags)) { 792 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 793 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 794 << DRE->getDecl()->getIdentifier(); 795 return true; 796 } 797 798 return false; 799 } 800 801 static inline bool isBlockPointer(Expr *Arg) { 802 return Arg->getType()->isBlockPointerType(); 803 } 804 805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 806 /// void*, which is a requirement of device side enqueue. 807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 808 const BlockPointerType *BPT = 809 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 810 ArrayRef<QualType> Params = 811 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 812 unsigned ArgCounter = 0; 813 bool IllegalParams = false; 814 // Iterate through the block parameters until either one is found that is not 815 // a local void*, or the block is valid. 816 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 817 I != E; ++I, ++ArgCounter) { 818 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 819 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 820 LangAS::opencl_local) { 821 // Get the location of the error. If a block literal has been passed 822 // (BlockExpr) then we can point straight to the offending argument, 823 // else we just point to the variable reference. 824 SourceLocation ErrorLoc; 825 if (isa<BlockExpr>(BlockArg)) { 826 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 827 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 828 } else if (isa<DeclRefExpr>(BlockArg)) { 829 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 830 } 831 S.Diag(ErrorLoc, 832 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 833 IllegalParams = true; 834 } 835 } 836 837 return IllegalParams; 838 } 839 840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 841 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 842 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 843 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 844 return true; 845 } 846 return false; 847 } 848 849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 850 if (checkArgCount(S, TheCall, 2)) 851 return true; 852 853 if (checkOpenCLSubgroupExt(S, TheCall)) 854 return true; 855 856 // First argument is an ndrange_t type. 857 Expr *NDRangeArg = TheCall->getArg(0); 858 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 859 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 860 << TheCall->getDirectCallee() << "'ndrange_t'"; 861 return true; 862 } 863 864 Expr *BlockArg = TheCall->getArg(1); 865 if (!isBlockPointer(BlockArg)) { 866 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 867 << TheCall->getDirectCallee() << "block"; 868 return true; 869 } 870 return checkOpenCLBlockArgs(S, BlockArg); 871 } 872 873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 874 /// get_kernel_work_group_size 875 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 877 if (checkArgCount(S, TheCall, 1)) 878 return true; 879 880 Expr *BlockArg = TheCall->getArg(0); 881 if (!isBlockPointer(BlockArg)) { 882 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 883 << TheCall->getDirectCallee() << "block"; 884 return true; 885 } 886 return checkOpenCLBlockArgs(S, BlockArg); 887 } 888 889 /// Diagnose integer type and any valid implicit conversion to it. 890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 891 const QualType &IntType); 892 893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 894 unsigned Start, unsigned End) { 895 bool IllegalParams = false; 896 for (unsigned I = Start; I <= End; ++I) 897 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 898 S.Context.getSizeType()); 899 return IllegalParams; 900 } 901 902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 903 /// 'local void*' parameter of passed block. 904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 905 Expr *BlockArg, 906 unsigned NumNonVarArgs) { 907 const BlockPointerType *BPT = 908 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 909 unsigned NumBlockParams = 910 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 911 unsigned TotalNumArgs = TheCall->getNumArgs(); 912 913 // For each argument passed to the block, a corresponding uint needs to 914 // be passed to describe the size of the local memory. 915 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 916 S.Diag(TheCall->getBeginLoc(), 917 diag::err_opencl_enqueue_kernel_local_size_args); 918 return true; 919 } 920 921 // Check that the sizes of the local memory are specified by integers. 922 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 923 TotalNumArgs - 1); 924 } 925 926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 927 /// overload formats specified in Table 6.13.17.1. 928 /// int enqueue_kernel(queue_t queue, 929 /// kernel_enqueue_flags_t flags, 930 /// const ndrange_t ndrange, 931 /// void (^block)(void)) 932 /// int enqueue_kernel(queue_t queue, 933 /// kernel_enqueue_flags_t flags, 934 /// const ndrange_t ndrange, 935 /// uint num_events_in_wait_list, 936 /// clk_event_t *event_wait_list, 937 /// clk_event_t *event_ret, 938 /// void (^block)(void)) 939 /// int enqueue_kernel(queue_t queue, 940 /// kernel_enqueue_flags_t flags, 941 /// const ndrange_t ndrange, 942 /// void (^block)(local void*, ...), 943 /// uint size0, ...) 944 /// int enqueue_kernel(queue_t queue, 945 /// kernel_enqueue_flags_t flags, 946 /// const ndrange_t ndrange, 947 /// uint num_events_in_wait_list, 948 /// clk_event_t *event_wait_list, 949 /// clk_event_t *event_ret, 950 /// void (^block)(local void*, ...), 951 /// uint size0, ...) 952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 953 unsigned NumArgs = TheCall->getNumArgs(); 954 955 if (NumArgs < 4) { 956 S.Diag(TheCall->getBeginLoc(), 957 diag::err_typecheck_call_too_few_args_at_least) 958 << 0 << 4 << NumArgs; 959 return true; 960 } 961 962 Expr *Arg0 = TheCall->getArg(0); 963 Expr *Arg1 = TheCall->getArg(1); 964 Expr *Arg2 = TheCall->getArg(2); 965 Expr *Arg3 = TheCall->getArg(3); 966 967 // First argument always needs to be a queue_t type. 968 if (!Arg0->getType()->isQueueT()) { 969 S.Diag(TheCall->getArg(0)->getBeginLoc(), 970 diag::err_opencl_builtin_expected_type) 971 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 972 return true; 973 } 974 975 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 976 if (!Arg1->getType()->isIntegerType()) { 977 S.Diag(TheCall->getArg(1)->getBeginLoc(), 978 diag::err_opencl_builtin_expected_type) 979 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 980 return true; 981 } 982 983 // Third argument is always an ndrange_t type. 984 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 985 S.Diag(TheCall->getArg(2)->getBeginLoc(), 986 diag::err_opencl_builtin_expected_type) 987 << TheCall->getDirectCallee() << "'ndrange_t'"; 988 return true; 989 } 990 991 // With four arguments, there is only one form that the function could be 992 // called in: no events and no variable arguments. 993 if (NumArgs == 4) { 994 // check that the last argument is the right block type. 995 if (!isBlockPointer(Arg3)) { 996 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 997 << TheCall->getDirectCallee() << "block"; 998 return true; 999 } 1000 // we have a block type, check the prototype 1001 const BlockPointerType *BPT = 1002 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1003 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1004 S.Diag(Arg3->getBeginLoc(), 1005 diag::err_opencl_enqueue_kernel_blocks_no_args); 1006 return true; 1007 } 1008 return false; 1009 } 1010 // we can have block + varargs. 1011 if (isBlockPointer(Arg3)) 1012 return (checkOpenCLBlockArgs(S, Arg3) || 1013 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1014 // last two cases with either exactly 7 args or 7 args and varargs. 1015 if (NumArgs >= 7) { 1016 // check common block argument. 1017 Expr *Arg6 = TheCall->getArg(6); 1018 if (!isBlockPointer(Arg6)) { 1019 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1020 << TheCall->getDirectCallee() << "block"; 1021 return true; 1022 } 1023 if (checkOpenCLBlockArgs(S, Arg6)) 1024 return true; 1025 1026 // Forth argument has to be any integer type. 1027 if (!Arg3->getType()->isIntegerType()) { 1028 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1029 diag::err_opencl_builtin_expected_type) 1030 << TheCall->getDirectCallee() << "integer"; 1031 return true; 1032 } 1033 // check remaining common arguments. 1034 Expr *Arg4 = TheCall->getArg(4); 1035 Expr *Arg5 = TheCall->getArg(5); 1036 1037 // Fifth argument is always passed as a pointer to clk_event_t. 1038 if (!Arg4->isNullPointerConstant(S.Context, 1039 Expr::NPC_ValueDependentIsNotNull) && 1040 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1041 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1042 diag::err_opencl_builtin_expected_type) 1043 << TheCall->getDirectCallee() 1044 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1045 return true; 1046 } 1047 1048 // Sixth argument is always passed as a pointer to clk_event_t. 1049 if (!Arg5->isNullPointerConstant(S.Context, 1050 Expr::NPC_ValueDependentIsNotNull) && 1051 !(Arg5->getType()->isPointerType() && 1052 Arg5->getType()->getPointeeType()->isClkEventT())) { 1053 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1054 diag::err_opencl_builtin_expected_type) 1055 << TheCall->getDirectCallee() 1056 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1057 return true; 1058 } 1059 1060 if (NumArgs == 7) 1061 return false; 1062 1063 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1064 } 1065 1066 // None of the specific case has been detected, give generic error 1067 S.Diag(TheCall->getBeginLoc(), 1068 diag::err_opencl_enqueue_kernel_incorrect_args); 1069 return true; 1070 } 1071 1072 /// Returns OpenCL access qual. 1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1074 return D->getAttr<OpenCLAccessAttr>(); 1075 } 1076 1077 /// Returns true if pipe element type is different from the pointer. 1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1079 const Expr *Arg0 = Call->getArg(0); 1080 // First argument type should always be pipe. 1081 if (!Arg0->getType()->isPipeType()) { 1082 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1083 << Call->getDirectCallee() << Arg0->getSourceRange(); 1084 return true; 1085 } 1086 OpenCLAccessAttr *AccessQual = 1087 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1088 // Validates the access qualifier is compatible with the call. 1089 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1090 // read_only and write_only, and assumed to be read_only if no qualifier is 1091 // specified. 1092 switch (Call->getDirectCallee()->getBuiltinID()) { 1093 case Builtin::BIread_pipe: 1094 case Builtin::BIreserve_read_pipe: 1095 case Builtin::BIcommit_read_pipe: 1096 case Builtin::BIwork_group_reserve_read_pipe: 1097 case Builtin::BIsub_group_reserve_read_pipe: 1098 case Builtin::BIwork_group_commit_read_pipe: 1099 case Builtin::BIsub_group_commit_read_pipe: 1100 if (!(!AccessQual || AccessQual->isReadOnly())) { 1101 S.Diag(Arg0->getBeginLoc(), 1102 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1103 << "read_only" << Arg0->getSourceRange(); 1104 return true; 1105 } 1106 break; 1107 case Builtin::BIwrite_pipe: 1108 case Builtin::BIreserve_write_pipe: 1109 case Builtin::BIcommit_write_pipe: 1110 case Builtin::BIwork_group_reserve_write_pipe: 1111 case Builtin::BIsub_group_reserve_write_pipe: 1112 case Builtin::BIwork_group_commit_write_pipe: 1113 case Builtin::BIsub_group_commit_write_pipe: 1114 if (!(AccessQual && AccessQual->isWriteOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "write_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 default: 1122 break; 1123 } 1124 return false; 1125 } 1126 1127 /// Returns true if pipe element type is different from the pointer. 1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1129 const Expr *Arg0 = Call->getArg(0); 1130 const Expr *ArgIdx = Call->getArg(Idx); 1131 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1132 const QualType EltTy = PipeTy->getElementType(); 1133 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1134 // The Idx argument should be a pointer and the type of the pointer and 1135 // the type of pipe element should also be the same. 1136 if (!ArgTy || 1137 !S.Context.hasSameType( 1138 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1139 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1140 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1141 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1142 return true; 1143 } 1144 return false; 1145 } 1146 1147 // Performs semantic analysis for the read/write_pipe call. 1148 // \param S Reference to the semantic analyzer. 1149 // \param Call A pointer to the builtin call. 1150 // \return True if a semantic error has been found, false otherwise. 1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1152 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1153 // functions have two forms. 1154 switch (Call->getNumArgs()) { 1155 case 2: 1156 if (checkOpenCLPipeArg(S, Call)) 1157 return true; 1158 // The call with 2 arguments should be 1159 // read/write_pipe(pipe T, T*). 1160 // Check packet type T. 1161 if (checkOpenCLPipePacketType(S, Call, 1)) 1162 return true; 1163 break; 1164 1165 case 4: { 1166 if (checkOpenCLPipeArg(S, Call)) 1167 return true; 1168 // The call with 4 arguments should be 1169 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1170 // Check reserve_id_t. 1171 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1172 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1173 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1174 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1175 return true; 1176 } 1177 1178 // Check the index. 1179 const Expr *Arg2 = Call->getArg(2); 1180 if (!Arg2->getType()->isIntegerType() && 1181 !Arg2->getType()->isUnsignedIntegerType()) { 1182 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1183 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1184 << Arg2->getType() << Arg2->getSourceRange(); 1185 return true; 1186 } 1187 1188 // Check packet type T. 1189 if (checkOpenCLPipePacketType(S, Call, 3)) 1190 return true; 1191 } break; 1192 default: 1193 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1194 << Call->getDirectCallee() << Call->getSourceRange(); 1195 return true; 1196 } 1197 1198 return false; 1199 } 1200 1201 // Performs a semantic analysis on the {work_group_/sub_group_ 1202 // /_}reserve_{read/write}_pipe 1203 // \param S Reference to the semantic analyzer. 1204 // \param Call The call to the builtin function to be analyzed. 1205 // \return True if a semantic error was found, false otherwise. 1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1207 if (checkArgCount(S, Call, 2)) 1208 return true; 1209 1210 if (checkOpenCLPipeArg(S, Call)) 1211 return true; 1212 1213 // Check the reserve size. 1214 if (!Call->getArg(1)->getType()->isIntegerType() && 1215 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1216 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1217 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1218 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1219 return true; 1220 } 1221 1222 // Since return type of reserve_read/write_pipe built-in function is 1223 // reserve_id_t, which is not defined in the builtin def file , we used int 1224 // as return type and need to override the return type of these functions. 1225 Call->setType(S.Context.OCLReserveIDTy); 1226 1227 return false; 1228 } 1229 1230 // Performs a semantic analysis on {work_group_/sub_group_ 1231 // /_}commit_{read/write}_pipe 1232 // \param S Reference to the semantic analyzer. 1233 // \param Call The call to the builtin function to be analyzed. 1234 // \return True if a semantic error was found, false otherwise. 1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1236 if (checkArgCount(S, Call, 2)) 1237 return true; 1238 1239 if (checkOpenCLPipeArg(S, Call)) 1240 return true; 1241 1242 // Check reserve_id_t. 1243 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1244 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1245 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1246 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1247 return true; 1248 } 1249 1250 return false; 1251 } 1252 1253 // Performs a semantic analysis on the call to built-in Pipe 1254 // Query Functions. 1255 // \param S Reference to the semantic analyzer. 1256 // \param Call The call to the builtin function to be analyzed. 1257 // \return True if a semantic error was found, false otherwise. 1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1259 if (checkArgCount(S, Call, 1)) 1260 return true; 1261 1262 if (!Call->getArg(0)->getType()->isPipeType()) { 1263 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1264 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1265 return true; 1266 } 1267 1268 return false; 1269 } 1270 1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1272 // Performs semantic analysis for the to_global/local/private call. 1273 // \param S Reference to the semantic analyzer. 1274 // \param BuiltinID ID of the builtin function. 1275 // \param Call A pointer to the builtin call. 1276 // \return True if a semantic error has been found, false otherwise. 1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1278 CallExpr *Call) { 1279 if (checkArgCount(S, Call, 1)) 1280 return true; 1281 1282 auto RT = Call->getArg(0)->getType(); 1283 if (!RT->isPointerType() || RT->getPointeeType() 1284 .getAddressSpace() == LangAS::opencl_constant) { 1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1286 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1287 return true; 1288 } 1289 1290 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1291 S.Diag(Call->getArg(0)->getBeginLoc(), 1292 diag::warn_opencl_generic_address_space_arg) 1293 << Call->getDirectCallee()->getNameInfo().getAsString() 1294 << Call->getArg(0)->getSourceRange(); 1295 } 1296 1297 RT = RT->getPointeeType(); 1298 auto Qual = RT.getQualifiers(); 1299 switch (BuiltinID) { 1300 case Builtin::BIto_global: 1301 Qual.setAddressSpace(LangAS::opencl_global); 1302 break; 1303 case Builtin::BIto_local: 1304 Qual.setAddressSpace(LangAS::opencl_local); 1305 break; 1306 case Builtin::BIto_private: 1307 Qual.setAddressSpace(LangAS::opencl_private); 1308 break; 1309 default: 1310 llvm_unreachable("Invalid builtin function"); 1311 } 1312 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1313 RT.getUnqualifiedType(), Qual))); 1314 1315 return false; 1316 } 1317 1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1319 if (checkArgCount(S, TheCall, 1)) 1320 return ExprError(); 1321 1322 // Compute __builtin_launder's parameter type from the argument. 1323 // The parameter type is: 1324 // * The type of the argument if it's not an array or function type, 1325 // Otherwise, 1326 // * The decayed argument type. 1327 QualType ParamTy = [&]() { 1328 QualType ArgTy = TheCall->getArg(0)->getType(); 1329 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1330 return S.Context.getPointerType(Ty->getElementType()); 1331 if (ArgTy->isFunctionType()) { 1332 return S.Context.getPointerType(ArgTy); 1333 } 1334 return ArgTy; 1335 }(); 1336 1337 TheCall->setType(ParamTy); 1338 1339 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1340 if (!ParamTy->isPointerType()) 1341 return 0; 1342 if (ParamTy->isFunctionPointerType()) 1343 return 1; 1344 if (ParamTy->isVoidPointerType()) 1345 return 2; 1346 return llvm::Optional<unsigned>{}; 1347 }(); 1348 if (DiagSelect.hasValue()) { 1349 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1350 << DiagSelect.getValue() << TheCall->getSourceRange(); 1351 return ExprError(); 1352 } 1353 1354 // We either have an incomplete class type, or we have a class template 1355 // whose instantiation has not been forced. Example: 1356 // 1357 // template <class T> struct Foo { T value; }; 1358 // Foo<int> *p = nullptr; 1359 // auto *d = __builtin_launder(p); 1360 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1361 diag::err_incomplete_type)) 1362 return ExprError(); 1363 1364 assert(ParamTy->getPointeeType()->isObjectType() && 1365 "Unhandled non-object pointer case"); 1366 1367 InitializedEntity Entity = 1368 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1369 ExprResult Arg = 1370 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1371 if (Arg.isInvalid()) 1372 return ExprError(); 1373 TheCall->setArg(0, Arg.get()); 1374 1375 return TheCall; 1376 } 1377 1378 // Emit an error and return true if the current architecture is not in the list 1379 // of supported architectures. 1380 static bool 1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1382 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1383 llvm::Triple::ArchType CurArch = 1384 S.getASTContext().getTargetInfo().getTriple().getArch(); 1385 if (llvm::is_contained(SupportedArchs, CurArch)) 1386 return false; 1387 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1388 << TheCall->getSourceRange(); 1389 return true; 1390 } 1391 1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1393 SourceLocation CallSiteLoc); 1394 1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1396 CallExpr *TheCall) { 1397 switch (TI.getTriple().getArch()) { 1398 default: 1399 // Some builtins don't require additional checking, so just consider these 1400 // acceptable. 1401 return false; 1402 case llvm::Triple::arm: 1403 case llvm::Triple::armeb: 1404 case llvm::Triple::thumb: 1405 case llvm::Triple::thumbeb: 1406 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1407 case llvm::Triple::aarch64: 1408 case llvm::Triple::aarch64_32: 1409 case llvm::Triple::aarch64_be: 1410 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1411 case llvm::Triple::bpfeb: 1412 case llvm::Triple::bpfel: 1413 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::hexagon: 1415 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1416 case llvm::Triple::mips: 1417 case llvm::Triple::mipsel: 1418 case llvm::Triple::mips64: 1419 case llvm::Triple::mips64el: 1420 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::systemz: 1422 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1423 case llvm::Triple::x86: 1424 case llvm::Triple::x86_64: 1425 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1426 case llvm::Triple::ppc: 1427 case llvm::Triple::ppcle: 1428 case llvm::Triple::ppc64: 1429 case llvm::Triple::ppc64le: 1430 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1431 case llvm::Triple::amdgcn: 1432 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1433 case llvm::Triple::riscv32: 1434 case llvm::Triple::riscv64: 1435 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1436 } 1437 } 1438 1439 ExprResult 1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1441 CallExpr *TheCall) { 1442 ExprResult TheCallResult(TheCall); 1443 1444 // Find out if any arguments are required to be integer constant expressions. 1445 unsigned ICEArguments = 0; 1446 ASTContext::GetBuiltinTypeError Error; 1447 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1448 if (Error != ASTContext::GE_None) 1449 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1450 1451 // If any arguments are required to be ICE's, check and diagnose. 1452 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1453 // Skip arguments not required to be ICE's. 1454 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1455 1456 llvm::APSInt Result; 1457 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1458 return true; 1459 ICEArguments &= ~(1 << ArgNo); 1460 } 1461 1462 switch (BuiltinID) { 1463 case Builtin::BI__builtin___CFStringMakeConstantString: 1464 assert(TheCall->getNumArgs() == 1 && 1465 "Wrong # arguments to builtin CFStringMakeConstantString"); 1466 if (CheckObjCString(TheCall->getArg(0))) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__builtin_ms_va_start: 1470 case Builtin::BI__builtin_stdarg_start: 1471 case Builtin::BI__builtin_va_start: 1472 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1473 return ExprError(); 1474 break; 1475 case Builtin::BI__va_start: { 1476 switch (Context.getTargetInfo().getTriple().getArch()) { 1477 case llvm::Triple::aarch64: 1478 case llvm::Triple::arm: 1479 case llvm::Triple::thumb: 1480 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1481 return ExprError(); 1482 break; 1483 default: 1484 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1485 return ExprError(); 1486 break; 1487 } 1488 break; 1489 } 1490 1491 // The acquire, release, and no fence variants are ARM and AArch64 only. 1492 case Builtin::BI_interlockedbittestandset_acq: 1493 case Builtin::BI_interlockedbittestandset_rel: 1494 case Builtin::BI_interlockedbittestandset_nf: 1495 case Builtin::BI_interlockedbittestandreset_acq: 1496 case Builtin::BI_interlockedbittestandreset_rel: 1497 case Builtin::BI_interlockedbittestandreset_nf: 1498 if (CheckBuiltinTargetSupport( 1499 *this, BuiltinID, TheCall, 1500 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1501 return ExprError(); 1502 break; 1503 1504 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1505 case Builtin::BI_bittest64: 1506 case Builtin::BI_bittestandcomplement64: 1507 case Builtin::BI_bittestandreset64: 1508 case Builtin::BI_bittestandset64: 1509 case Builtin::BI_interlockedbittestandreset64: 1510 case Builtin::BI_interlockedbittestandset64: 1511 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1512 {llvm::Triple::x86_64, llvm::Triple::arm, 1513 llvm::Triple::thumb, llvm::Triple::aarch64})) 1514 return ExprError(); 1515 break; 1516 1517 case Builtin::BI__builtin_isgreater: 1518 case Builtin::BI__builtin_isgreaterequal: 1519 case Builtin::BI__builtin_isless: 1520 case Builtin::BI__builtin_islessequal: 1521 case Builtin::BI__builtin_islessgreater: 1522 case Builtin::BI__builtin_isunordered: 1523 if (SemaBuiltinUnorderedCompare(TheCall)) 1524 return ExprError(); 1525 break; 1526 case Builtin::BI__builtin_fpclassify: 1527 if (SemaBuiltinFPClassification(TheCall, 6)) 1528 return ExprError(); 1529 break; 1530 case Builtin::BI__builtin_isfinite: 1531 case Builtin::BI__builtin_isinf: 1532 case Builtin::BI__builtin_isinf_sign: 1533 case Builtin::BI__builtin_isnan: 1534 case Builtin::BI__builtin_isnormal: 1535 case Builtin::BI__builtin_signbit: 1536 case Builtin::BI__builtin_signbitf: 1537 case Builtin::BI__builtin_signbitl: 1538 if (SemaBuiltinFPClassification(TheCall, 1)) 1539 return ExprError(); 1540 break; 1541 case Builtin::BI__builtin_shufflevector: 1542 return SemaBuiltinShuffleVector(TheCall); 1543 // TheCall will be freed by the smart pointer here, but that's fine, since 1544 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1545 case Builtin::BI__builtin_prefetch: 1546 if (SemaBuiltinPrefetch(TheCall)) 1547 return ExprError(); 1548 break; 1549 case Builtin::BI__builtin_alloca_with_align: 1550 if (SemaBuiltinAllocaWithAlign(TheCall)) 1551 return ExprError(); 1552 LLVM_FALLTHROUGH; 1553 case Builtin::BI__builtin_alloca: 1554 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1555 << TheCall->getDirectCallee(); 1556 break; 1557 case Builtin::BI__arithmetic_fence: 1558 if (SemaBuiltinArithmeticFence(TheCall)) 1559 return ExprError(); 1560 break; 1561 case Builtin::BI__assume: 1562 case Builtin::BI__builtin_assume: 1563 if (SemaBuiltinAssume(TheCall)) 1564 return ExprError(); 1565 break; 1566 case Builtin::BI__builtin_assume_aligned: 1567 if (SemaBuiltinAssumeAligned(TheCall)) 1568 return ExprError(); 1569 break; 1570 case Builtin::BI__builtin_dynamic_object_size: 1571 case Builtin::BI__builtin_object_size: 1572 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__builtin_longjmp: 1576 if (SemaBuiltinLongjmp(TheCall)) 1577 return ExprError(); 1578 break; 1579 case Builtin::BI__builtin_setjmp: 1580 if (SemaBuiltinSetjmp(TheCall)) 1581 return ExprError(); 1582 break; 1583 case Builtin::BI__builtin_classify_type: 1584 if (checkArgCount(*this, TheCall, 1)) return true; 1585 TheCall->setType(Context.IntTy); 1586 break; 1587 case Builtin::BI__builtin_complex: 1588 if (SemaBuiltinComplex(TheCall)) 1589 return ExprError(); 1590 break; 1591 case Builtin::BI__builtin_constant_p: { 1592 if (checkArgCount(*this, TheCall, 1)) return true; 1593 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1594 if (Arg.isInvalid()) return true; 1595 TheCall->setArg(0, Arg.get()); 1596 TheCall->setType(Context.IntTy); 1597 break; 1598 } 1599 case Builtin::BI__builtin_launder: 1600 return SemaBuiltinLaunder(*this, TheCall); 1601 case Builtin::BI__sync_fetch_and_add: 1602 case Builtin::BI__sync_fetch_and_add_1: 1603 case Builtin::BI__sync_fetch_and_add_2: 1604 case Builtin::BI__sync_fetch_and_add_4: 1605 case Builtin::BI__sync_fetch_and_add_8: 1606 case Builtin::BI__sync_fetch_and_add_16: 1607 case Builtin::BI__sync_fetch_and_sub: 1608 case Builtin::BI__sync_fetch_and_sub_1: 1609 case Builtin::BI__sync_fetch_and_sub_2: 1610 case Builtin::BI__sync_fetch_and_sub_4: 1611 case Builtin::BI__sync_fetch_and_sub_8: 1612 case Builtin::BI__sync_fetch_and_sub_16: 1613 case Builtin::BI__sync_fetch_and_or: 1614 case Builtin::BI__sync_fetch_and_or_1: 1615 case Builtin::BI__sync_fetch_and_or_2: 1616 case Builtin::BI__sync_fetch_and_or_4: 1617 case Builtin::BI__sync_fetch_and_or_8: 1618 case Builtin::BI__sync_fetch_and_or_16: 1619 case Builtin::BI__sync_fetch_and_and: 1620 case Builtin::BI__sync_fetch_and_and_1: 1621 case Builtin::BI__sync_fetch_and_and_2: 1622 case Builtin::BI__sync_fetch_and_and_4: 1623 case Builtin::BI__sync_fetch_and_and_8: 1624 case Builtin::BI__sync_fetch_and_and_16: 1625 case Builtin::BI__sync_fetch_and_xor: 1626 case Builtin::BI__sync_fetch_and_xor_1: 1627 case Builtin::BI__sync_fetch_and_xor_2: 1628 case Builtin::BI__sync_fetch_and_xor_4: 1629 case Builtin::BI__sync_fetch_and_xor_8: 1630 case Builtin::BI__sync_fetch_and_xor_16: 1631 case Builtin::BI__sync_fetch_and_nand: 1632 case Builtin::BI__sync_fetch_and_nand_1: 1633 case Builtin::BI__sync_fetch_and_nand_2: 1634 case Builtin::BI__sync_fetch_and_nand_4: 1635 case Builtin::BI__sync_fetch_and_nand_8: 1636 case Builtin::BI__sync_fetch_and_nand_16: 1637 case Builtin::BI__sync_add_and_fetch: 1638 case Builtin::BI__sync_add_and_fetch_1: 1639 case Builtin::BI__sync_add_and_fetch_2: 1640 case Builtin::BI__sync_add_and_fetch_4: 1641 case Builtin::BI__sync_add_and_fetch_8: 1642 case Builtin::BI__sync_add_and_fetch_16: 1643 case Builtin::BI__sync_sub_and_fetch: 1644 case Builtin::BI__sync_sub_and_fetch_1: 1645 case Builtin::BI__sync_sub_and_fetch_2: 1646 case Builtin::BI__sync_sub_and_fetch_4: 1647 case Builtin::BI__sync_sub_and_fetch_8: 1648 case Builtin::BI__sync_sub_and_fetch_16: 1649 case Builtin::BI__sync_and_and_fetch: 1650 case Builtin::BI__sync_and_and_fetch_1: 1651 case Builtin::BI__sync_and_and_fetch_2: 1652 case Builtin::BI__sync_and_and_fetch_4: 1653 case Builtin::BI__sync_and_and_fetch_8: 1654 case Builtin::BI__sync_and_and_fetch_16: 1655 case Builtin::BI__sync_or_and_fetch: 1656 case Builtin::BI__sync_or_and_fetch_1: 1657 case Builtin::BI__sync_or_and_fetch_2: 1658 case Builtin::BI__sync_or_and_fetch_4: 1659 case Builtin::BI__sync_or_and_fetch_8: 1660 case Builtin::BI__sync_or_and_fetch_16: 1661 case Builtin::BI__sync_xor_and_fetch: 1662 case Builtin::BI__sync_xor_and_fetch_1: 1663 case Builtin::BI__sync_xor_and_fetch_2: 1664 case Builtin::BI__sync_xor_and_fetch_4: 1665 case Builtin::BI__sync_xor_and_fetch_8: 1666 case Builtin::BI__sync_xor_and_fetch_16: 1667 case Builtin::BI__sync_nand_and_fetch: 1668 case Builtin::BI__sync_nand_and_fetch_1: 1669 case Builtin::BI__sync_nand_and_fetch_2: 1670 case Builtin::BI__sync_nand_and_fetch_4: 1671 case Builtin::BI__sync_nand_and_fetch_8: 1672 case Builtin::BI__sync_nand_and_fetch_16: 1673 case Builtin::BI__sync_val_compare_and_swap: 1674 case Builtin::BI__sync_val_compare_and_swap_1: 1675 case Builtin::BI__sync_val_compare_and_swap_2: 1676 case Builtin::BI__sync_val_compare_and_swap_4: 1677 case Builtin::BI__sync_val_compare_and_swap_8: 1678 case Builtin::BI__sync_val_compare_and_swap_16: 1679 case Builtin::BI__sync_bool_compare_and_swap: 1680 case Builtin::BI__sync_bool_compare_and_swap_1: 1681 case Builtin::BI__sync_bool_compare_and_swap_2: 1682 case Builtin::BI__sync_bool_compare_and_swap_4: 1683 case Builtin::BI__sync_bool_compare_and_swap_8: 1684 case Builtin::BI__sync_bool_compare_and_swap_16: 1685 case Builtin::BI__sync_lock_test_and_set: 1686 case Builtin::BI__sync_lock_test_and_set_1: 1687 case Builtin::BI__sync_lock_test_and_set_2: 1688 case Builtin::BI__sync_lock_test_and_set_4: 1689 case Builtin::BI__sync_lock_test_and_set_8: 1690 case Builtin::BI__sync_lock_test_and_set_16: 1691 case Builtin::BI__sync_lock_release: 1692 case Builtin::BI__sync_lock_release_1: 1693 case Builtin::BI__sync_lock_release_2: 1694 case Builtin::BI__sync_lock_release_4: 1695 case Builtin::BI__sync_lock_release_8: 1696 case Builtin::BI__sync_lock_release_16: 1697 case Builtin::BI__sync_swap: 1698 case Builtin::BI__sync_swap_1: 1699 case Builtin::BI__sync_swap_2: 1700 case Builtin::BI__sync_swap_4: 1701 case Builtin::BI__sync_swap_8: 1702 case Builtin::BI__sync_swap_16: 1703 return SemaBuiltinAtomicOverloaded(TheCallResult); 1704 case Builtin::BI__sync_synchronize: 1705 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1706 << TheCall->getCallee()->getSourceRange(); 1707 break; 1708 case Builtin::BI__builtin_nontemporal_load: 1709 case Builtin::BI__builtin_nontemporal_store: 1710 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1711 case Builtin::BI__builtin_memcpy_inline: { 1712 clang::Expr *SizeOp = TheCall->getArg(2); 1713 // We warn about copying to or from `nullptr` pointers when `size` is 1714 // greater than 0. When `size` is value dependent we cannot evaluate its 1715 // value so we bail out. 1716 if (SizeOp->isValueDependent()) 1717 break; 1718 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1719 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1720 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1721 } 1722 break; 1723 } 1724 #define BUILTIN(ID, TYPE, ATTRS) 1725 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1726 case Builtin::BI##ID: \ 1727 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1728 #include "clang/Basic/Builtins.def" 1729 case Builtin::BI__annotation: 1730 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1731 return ExprError(); 1732 break; 1733 case Builtin::BI__builtin_annotation: 1734 if (SemaBuiltinAnnotation(*this, TheCall)) 1735 return ExprError(); 1736 break; 1737 case Builtin::BI__builtin_addressof: 1738 if (SemaBuiltinAddressof(*this, TheCall)) 1739 return ExprError(); 1740 break; 1741 case Builtin::BI__builtin_is_aligned: 1742 case Builtin::BI__builtin_align_up: 1743 case Builtin::BI__builtin_align_down: 1744 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1745 return ExprError(); 1746 break; 1747 case Builtin::BI__builtin_add_overflow: 1748 case Builtin::BI__builtin_sub_overflow: 1749 case Builtin::BI__builtin_mul_overflow: 1750 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1751 return ExprError(); 1752 break; 1753 case Builtin::BI__builtin_operator_new: 1754 case Builtin::BI__builtin_operator_delete: { 1755 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1756 ExprResult Res = 1757 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1758 if (Res.isInvalid()) 1759 CorrectDelayedTyposInExpr(TheCallResult.get()); 1760 return Res; 1761 } 1762 case Builtin::BI__builtin_dump_struct: { 1763 // We first want to ensure we are called with 2 arguments 1764 if (checkArgCount(*this, TheCall, 2)) 1765 return ExprError(); 1766 // Ensure that the first argument is of type 'struct XX *' 1767 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1768 const QualType PtrArgType = PtrArg->getType(); 1769 if (!PtrArgType->isPointerType() || 1770 !PtrArgType->getPointeeType()->isRecordType()) { 1771 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1772 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1773 << "structure pointer"; 1774 return ExprError(); 1775 } 1776 1777 // Ensure that the second argument is of type 'FunctionType' 1778 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1779 const QualType FnPtrArgType = FnPtrArg->getType(); 1780 if (!FnPtrArgType->isPointerType()) { 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 const auto *FuncType = 1788 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1789 1790 if (!FuncType) { 1791 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1792 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1793 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1794 return ExprError(); 1795 } 1796 1797 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1798 if (!FT->getNumParams()) { 1799 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1800 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1801 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1802 return ExprError(); 1803 } 1804 QualType PT = FT->getParamType(0); 1805 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1806 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1807 !PT->getPointeeType().isConstQualified()) { 1808 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1809 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1810 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1811 return ExprError(); 1812 } 1813 } 1814 1815 TheCall->setType(Context.IntTy); 1816 break; 1817 } 1818 case Builtin::BI__builtin_expect_with_probability: { 1819 // We first want to ensure we are called with 3 arguments 1820 if (checkArgCount(*this, TheCall, 3)) 1821 return ExprError(); 1822 // then check probability is constant float in range [0.0, 1.0] 1823 const Expr *ProbArg = TheCall->getArg(2); 1824 SmallVector<PartialDiagnosticAt, 8> Notes; 1825 Expr::EvalResult Eval; 1826 Eval.Diag = &Notes; 1827 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1828 !Eval.Val.isFloat()) { 1829 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1830 << ProbArg->getSourceRange(); 1831 for (const PartialDiagnosticAt &PDiag : Notes) 1832 Diag(PDiag.first, PDiag.second); 1833 return ExprError(); 1834 } 1835 llvm::APFloat Probability = Eval.Val.getFloat(); 1836 bool LoseInfo = false; 1837 Probability.convert(llvm::APFloat::IEEEdouble(), 1838 llvm::RoundingMode::Dynamic, &LoseInfo); 1839 if (!(Probability >= llvm::APFloat(0.0) && 1840 Probability <= llvm::APFloat(1.0))) { 1841 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1842 << ProbArg->getSourceRange(); 1843 return ExprError(); 1844 } 1845 break; 1846 } 1847 case Builtin::BI__builtin_preserve_access_index: 1848 if (SemaBuiltinPreserveAI(*this, TheCall)) 1849 return ExprError(); 1850 break; 1851 case Builtin::BI__builtin_call_with_static_chain: 1852 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1853 return ExprError(); 1854 break; 1855 case Builtin::BI__exception_code: 1856 case Builtin::BI_exception_code: 1857 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1858 diag::err_seh___except_block)) 1859 return ExprError(); 1860 break; 1861 case Builtin::BI__exception_info: 1862 case Builtin::BI_exception_info: 1863 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1864 diag::err_seh___except_filter)) 1865 return ExprError(); 1866 break; 1867 case Builtin::BI__GetExceptionInfo: 1868 if (checkArgCount(*this, TheCall, 1)) 1869 return ExprError(); 1870 1871 if (CheckCXXThrowOperand( 1872 TheCall->getBeginLoc(), 1873 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1874 TheCall)) 1875 return ExprError(); 1876 1877 TheCall->setType(Context.VoidPtrTy); 1878 break; 1879 // OpenCL v2.0, s6.13.16 - Pipe functions 1880 case Builtin::BIread_pipe: 1881 case Builtin::BIwrite_pipe: 1882 // Since those two functions are declared with var args, we need a semantic 1883 // check for the argument. 1884 if (SemaBuiltinRWPipe(*this, TheCall)) 1885 return ExprError(); 1886 break; 1887 case Builtin::BIreserve_read_pipe: 1888 case Builtin::BIreserve_write_pipe: 1889 case Builtin::BIwork_group_reserve_read_pipe: 1890 case Builtin::BIwork_group_reserve_write_pipe: 1891 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1892 return ExprError(); 1893 break; 1894 case Builtin::BIsub_group_reserve_read_pipe: 1895 case Builtin::BIsub_group_reserve_write_pipe: 1896 if (checkOpenCLSubgroupExt(*this, TheCall) || 1897 SemaBuiltinReserveRWPipe(*this, TheCall)) 1898 return ExprError(); 1899 break; 1900 case Builtin::BIcommit_read_pipe: 1901 case Builtin::BIcommit_write_pipe: 1902 case Builtin::BIwork_group_commit_read_pipe: 1903 case Builtin::BIwork_group_commit_write_pipe: 1904 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1905 return ExprError(); 1906 break; 1907 case Builtin::BIsub_group_commit_read_pipe: 1908 case Builtin::BIsub_group_commit_write_pipe: 1909 if (checkOpenCLSubgroupExt(*this, TheCall) || 1910 SemaBuiltinCommitRWPipe(*this, TheCall)) 1911 return ExprError(); 1912 break; 1913 case Builtin::BIget_pipe_num_packets: 1914 case Builtin::BIget_pipe_max_packets: 1915 if (SemaBuiltinPipePackets(*this, TheCall)) 1916 return ExprError(); 1917 break; 1918 case Builtin::BIto_global: 1919 case Builtin::BIto_local: 1920 case Builtin::BIto_private: 1921 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1922 return ExprError(); 1923 break; 1924 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1925 case Builtin::BIenqueue_kernel: 1926 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1927 return ExprError(); 1928 break; 1929 case Builtin::BIget_kernel_work_group_size: 1930 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1931 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1932 return ExprError(); 1933 break; 1934 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1935 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1936 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1937 return ExprError(); 1938 break; 1939 case Builtin::BI__builtin_os_log_format: 1940 Cleanup.setExprNeedsCleanups(true); 1941 LLVM_FALLTHROUGH; 1942 case Builtin::BI__builtin_os_log_format_buffer_size: 1943 if (SemaBuiltinOSLogFormat(TheCall)) 1944 return ExprError(); 1945 break; 1946 case Builtin::BI__builtin_frame_address: 1947 case Builtin::BI__builtin_return_address: { 1948 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1949 return ExprError(); 1950 1951 // -Wframe-address warning if non-zero passed to builtin 1952 // return/frame address. 1953 Expr::EvalResult Result; 1954 if (!TheCall->getArg(0)->isValueDependent() && 1955 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1956 Result.Val.getInt() != 0) 1957 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1958 << ((BuiltinID == Builtin::BI__builtin_return_address) 1959 ? "__builtin_return_address" 1960 : "__builtin_frame_address") 1961 << TheCall->getSourceRange(); 1962 break; 1963 } 1964 1965 case Builtin::BI__builtin_matrix_transpose: 1966 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1967 1968 case Builtin::BI__builtin_matrix_column_major_load: 1969 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1970 1971 case Builtin::BI__builtin_matrix_column_major_store: 1972 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1973 1974 case Builtin::BI__builtin_get_device_side_mangled_name: { 1975 auto Check = [](CallExpr *TheCall) { 1976 if (TheCall->getNumArgs() != 1) 1977 return false; 1978 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1979 if (!DRE) 1980 return false; 1981 auto *D = DRE->getDecl(); 1982 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1983 return false; 1984 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1985 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 1986 }; 1987 if (!Check(TheCall)) { 1988 Diag(TheCall->getBeginLoc(), 1989 diag::err_hip_invalid_args_builtin_mangled_name); 1990 return ExprError(); 1991 } 1992 } 1993 } 1994 1995 // Since the target specific builtins for each arch overlap, only check those 1996 // of the arch we are compiling for. 1997 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1998 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1999 assert(Context.getAuxTargetInfo() && 2000 "Aux Target Builtin, but not an aux target?"); 2001 2002 if (CheckTSBuiltinFunctionCall( 2003 *Context.getAuxTargetInfo(), 2004 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2005 return ExprError(); 2006 } else { 2007 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2008 TheCall)) 2009 return ExprError(); 2010 } 2011 } 2012 2013 return TheCallResult; 2014 } 2015 2016 // Get the valid immediate range for the specified NEON type code. 2017 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2018 NeonTypeFlags Type(t); 2019 int IsQuad = ForceQuad ? true : Type.isQuad(); 2020 switch (Type.getEltType()) { 2021 case NeonTypeFlags::Int8: 2022 case NeonTypeFlags::Poly8: 2023 return shift ? 7 : (8 << IsQuad) - 1; 2024 case NeonTypeFlags::Int16: 2025 case NeonTypeFlags::Poly16: 2026 return shift ? 15 : (4 << IsQuad) - 1; 2027 case NeonTypeFlags::Int32: 2028 return shift ? 31 : (2 << IsQuad) - 1; 2029 case NeonTypeFlags::Int64: 2030 case NeonTypeFlags::Poly64: 2031 return shift ? 63 : (1 << IsQuad) - 1; 2032 case NeonTypeFlags::Poly128: 2033 return shift ? 127 : (1 << IsQuad) - 1; 2034 case NeonTypeFlags::Float16: 2035 assert(!shift && "cannot shift float types!"); 2036 return (4 << IsQuad) - 1; 2037 case NeonTypeFlags::Float32: 2038 assert(!shift && "cannot shift float types!"); 2039 return (2 << IsQuad) - 1; 2040 case NeonTypeFlags::Float64: 2041 assert(!shift && "cannot shift float types!"); 2042 return (1 << IsQuad) - 1; 2043 case NeonTypeFlags::BFloat16: 2044 assert(!shift && "cannot shift float types!"); 2045 return (4 << IsQuad) - 1; 2046 } 2047 llvm_unreachable("Invalid NeonTypeFlag!"); 2048 } 2049 2050 /// getNeonEltType - Return the QualType corresponding to the elements of 2051 /// the vector type specified by the NeonTypeFlags. This is used to check 2052 /// the pointer arguments for Neon load/store intrinsics. 2053 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2054 bool IsPolyUnsigned, bool IsInt64Long) { 2055 switch (Flags.getEltType()) { 2056 case NeonTypeFlags::Int8: 2057 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2058 case NeonTypeFlags::Int16: 2059 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2060 case NeonTypeFlags::Int32: 2061 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2062 case NeonTypeFlags::Int64: 2063 if (IsInt64Long) 2064 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2065 else 2066 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2067 : Context.LongLongTy; 2068 case NeonTypeFlags::Poly8: 2069 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2070 case NeonTypeFlags::Poly16: 2071 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2072 case NeonTypeFlags::Poly64: 2073 if (IsInt64Long) 2074 return Context.UnsignedLongTy; 2075 else 2076 return Context.UnsignedLongLongTy; 2077 case NeonTypeFlags::Poly128: 2078 break; 2079 case NeonTypeFlags::Float16: 2080 return Context.HalfTy; 2081 case NeonTypeFlags::Float32: 2082 return Context.FloatTy; 2083 case NeonTypeFlags::Float64: 2084 return Context.DoubleTy; 2085 case NeonTypeFlags::BFloat16: 2086 return Context.BFloat16Ty; 2087 } 2088 llvm_unreachable("Invalid NeonTypeFlag!"); 2089 } 2090 2091 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2092 // Range check SVE intrinsics that take immediate values. 2093 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2094 2095 switch (BuiltinID) { 2096 default: 2097 return false; 2098 #define GET_SVE_IMMEDIATE_CHECK 2099 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2100 #undef GET_SVE_IMMEDIATE_CHECK 2101 } 2102 2103 // Perform all the immediate checks for this builtin call. 2104 bool HasError = false; 2105 for (auto &I : ImmChecks) { 2106 int ArgNum, CheckTy, ElementSizeInBits; 2107 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2108 2109 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2110 2111 // Function that checks whether the operand (ArgNum) is an immediate 2112 // that is one of the predefined values. 2113 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2114 int ErrDiag) -> bool { 2115 // We can't check the value of a dependent argument. 2116 Expr *Arg = TheCall->getArg(ArgNum); 2117 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2118 return false; 2119 2120 // Check constant-ness first. 2121 llvm::APSInt Imm; 2122 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2123 return true; 2124 2125 if (!CheckImm(Imm.getSExtValue())) 2126 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2127 return false; 2128 }; 2129 2130 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2131 case SVETypeFlags::ImmCheck0_31: 2132 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2133 HasError = true; 2134 break; 2135 case SVETypeFlags::ImmCheck0_13: 2136 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2137 HasError = true; 2138 break; 2139 case SVETypeFlags::ImmCheck1_16: 2140 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2141 HasError = true; 2142 break; 2143 case SVETypeFlags::ImmCheck0_7: 2144 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2145 HasError = true; 2146 break; 2147 case SVETypeFlags::ImmCheckExtract: 2148 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2149 (2048 / ElementSizeInBits) - 1)) 2150 HasError = true; 2151 break; 2152 case SVETypeFlags::ImmCheckShiftRight: 2153 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2154 HasError = true; 2155 break; 2156 case SVETypeFlags::ImmCheckShiftRightNarrow: 2157 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2158 ElementSizeInBits / 2)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckShiftLeft: 2162 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2163 ElementSizeInBits - 1)) 2164 HasError = true; 2165 break; 2166 case SVETypeFlags::ImmCheckLaneIndex: 2167 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2168 (128 / (1 * ElementSizeInBits)) - 1)) 2169 HasError = true; 2170 break; 2171 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2172 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2173 (128 / (2 * ElementSizeInBits)) - 1)) 2174 HasError = true; 2175 break; 2176 case SVETypeFlags::ImmCheckLaneIndexDot: 2177 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2178 (128 / (4 * ElementSizeInBits)) - 1)) 2179 HasError = true; 2180 break; 2181 case SVETypeFlags::ImmCheckComplexRot90_270: 2182 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2183 diag::err_rotation_argument_to_cadd)) 2184 HasError = true; 2185 break; 2186 case SVETypeFlags::ImmCheckComplexRotAll90: 2187 if (CheckImmediateInSet( 2188 [](int64_t V) { 2189 return V == 0 || V == 90 || V == 180 || V == 270; 2190 }, 2191 diag::err_rotation_argument_to_cmla)) 2192 HasError = true; 2193 break; 2194 case SVETypeFlags::ImmCheck0_1: 2195 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2196 HasError = true; 2197 break; 2198 case SVETypeFlags::ImmCheck0_2: 2199 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2200 HasError = true; 2201 break; 2202 case SVETypeFlags::ImmCheck0_3: 2203 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2204 HasError = true; 2205 break; 2206 } 2207 } 2208 2209 return HasError; 2210 } 2211 2212 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2213 unsigned BuiltinID, CallExpr *TheCall) { 2214 llvm::APSInt Result; 2215 uint64_t mask = 0; 2216 unsigned TV = 0; 2217 int PtrArgNum = -1; 2218 bool HasConstPtr = false; 2219 switch (BuiltinID) { 2220 #define GET_NEON_OVERLOAD_CHECK 2221 #include "clang/Basic/arm_neon.inc" 2222 #include "clang/Basic/arm_fp16.inc" 2223 #undef GET_NEON_OVERLOAD_CHECK 2224 } 2225 2226 // For NEON intrinsics which are overloaded on vector element type, validate 2227 // the immediate which specifies which variant to emit. 2228 unsigned ImmArg = TheCall->getNumArgs()-1; 2229 if (mask) { 2230 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2231 return true; 2232 2233 TV = Result.getLimitedValue(64); 2234 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2235 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2236 << TheCall->getArg(ImmArg)->getSourceRange(); 2237 } 2238 2239 if (PtrArgNum >= 0) { 2240 // Check that pointer arguments have the specified type. 2241 Expr *Arg = TheCall->getArg(PtrArgNum); 2242 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2243 Arg = ICE->getSubExpr(); 2244 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2245 QualType RHSTy = RHS.get()->getType(); 2246 2247 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2248 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2249 Arch == llvm::Triple::aarch64_32 || 2250 Arch == llvm::Triple::aarch64_be; 2251 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2252 QualType EltTy = 2253 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2254 if (HasConstPtr) 2255 EltTy = EltTy.withConst(); 2256 QualType LHSTy = Context.getPointerType(EltTy); 2257 AssignConvertType ConvTy; 2258 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2259 if (RHS.isInvalid()) 2260 return true; 2261 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2262 RHS.get(), AA_Assigning)) 2263 return true; 2264 } 2265 2266 // For NEON intrinsics which take an immediate value as part of the 2267 // instruction, range check them here. 2268 unsigned i = 0, l = 0, u = 0; 2269 switch (BuiltinID) { 2270 default: 2271 return false; 2272 #define GET_NEON_IMMEDIATE_CHECK 2273 #include "clang/Basic/arm_neon.inc" 2274 #include "clang/Basic/arm_fp16.inc" 2275 #undef GET_NEON_IMMEDIATE_CHECK 2276 } 2277 2278 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2279 } 2280 2281 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2282 switch (BuiltinID) { 2283 default: 2284 return false; 2285 #include "clang/Basic/arm_mve_builtin_sema.inc" 2286 } 2287 } 2288 2289 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2290 CallExpr *TheCall) { 2291 bool Err = false; 2292 switch (BuiltinID) { 2293 default: 2294 return false; 2295 #include "clang/Basic/arm_cde_builtin_sema.inc" 2296 } 2297 2298 if (Err) 2299 return true; 2300 2301 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2302 } 2303 2304 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2305 const Expr *CoprocArg, bool WantCDE) { 2306 if (isConstantEvaluated()) 2307 return false; 2308 2309 // We can't check the value of a dependent argument. 2310 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2311 return false; 2312 2313 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2314 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2315 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2316 2317 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2318 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2319 2320 if (IsCDECoproc != WantCDE) 2321 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2322 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2323 2324 return false; 2325 } 2326 2327 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2328 unsigned MaxWidth) { 2329 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2330 BuiltinID == ARM::BI__builtin_arm_ldaex || 2331 BuiltinID == ARM::BI__builtin_arm_strex || 2332 BuiltinID == ARM::BI__builtin_arm_stlex || 2333 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2334 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2335 BuiltinID == AArch64::BI__builtin_arm_strex || 2336 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2337 "unexpected ARM builtin"); 2338 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2339 BuiltinID == ARM::BI__builtin_arm_ldaex || 2340 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2341 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2342 2343 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2344 2345 // Ensure that we have the proper number of arguments. 2346 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2347 return true; 2348 2349 // Inspect the pointer argument of the atomic builtin. This should always be 2350 // a pointer type, whose element is an integral scalar or pointer type. 2351 // Because it is a pointer type, we don't have to worry about any implicit 2352 // casts here. 2353 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2354 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2355 if (PointerArgRes.isInvalid()) 2356 return true; 2357 PointerArg = PointerArgRes.get(); 2358 2359 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2360 if (!pointerType) { 2361 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2362 << PointerArg->getType() << PointerArg->getSourceRange(); 2363 return true; 2364 } 2365 2366 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2367 // task is to insert the appropriate casts into the AST. First work out just 2368 // what the appropriate type is. 2369 QualType ValType = pointerType->getPointeeType(); 2370 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2371 if (IsLdrex) 2372 AddrType.addConst(); 2373 2374 // Issue a warning if the cast is dodgy. 2375 CastKind CastNeeded = CK_NoOp; 2376 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2377 CastNeeded = CK_BitCast; 2378 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2379 << PointerArg->getType() << Context.getPointerType(AddrType) 2380 << AA_Passing << PointerArg->getSourceRange(); 2381 } 2382 2383 // Finally, do the cast and replace the argument with the corrected version. 2384 AddrType = Context.getPointerType(AddrType); 2385 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2386 if (PointerArgRes.isInvalid()) 2387 return true; 2388 PointerArg = PointerArgRes.get(); 2389 2390 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2391 2392 // In general, we allow ints, floats and pointers to be loaded and stored. 2393 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2394 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2395 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2396 << PointerArg->getType() << PointerArg->getSourceRange(); 2397 return true; 2398 } 2399 2400 // But ARM doesn't have instructions to deal with 128-bit versions. 2401 if (Context.getTypeSize(ValType) > MaxWidth) { 2402 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2403 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2404 << PointerArg->getType() << PointerArg->getSourceRange(); 2405 return true; 2406 } 2407 2408 switch (ValType.getObjCLifetime()) { 2409 case Qualifiers::OCL_None: 2410 case Qualifiers::OCL_ExplicitNone: 2411 // okay 2412 break; 2413 2414 case Qualifiers::OCL_Weak: 2415 case Qualifiers::OCL_Strong: 2416 case Qualifiers::OCL_Autoreleasing: 2417 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2418 << ValType << PointerArg->getSourceRange(); 2419 return true; 2420 } 2421 2422 if (IsLdrex) { 2423 TheCall->setType(ValType); 2424 return false; 2425 } 2426 2427 // Initialize the argument to be stored. 2428 ExprResult ValArg = TheCall->getArg(0); 2429 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2430 Context, ValType, /*consume*/ false); 2431 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2432 if (ValArg.isInvalid()) 2433 return true; 2434 TheCall->setArg(0, ValArg.get()); 2435 2436 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2437 // but the custom checker bypasses all default analysis. 2438 TheCall->setType(Context.IntTy); 2439 return false; 2440 } 2441 2442 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2443 CallExpr *TheCall) { 2444 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2445 BuiltinID == ARM::BI__builtin_arm_ldaex || 2446 BuiltinID == ARM::BI__builtin_arm_strex || 2447 BuiltinID == ARM::BI__builtin_arm_stlex) { 2448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2449 } 2450 2451 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2454 } 2455 2456 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2457 BuiltinID == ARM::BI__builtin_arm_wsr64) 2458 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2459 2460 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2461 BuiltinID == ARM::BI__builtin_arm_rsrp || 2462 BuiltinID == ARM::BI__builtin_arm_wsr || 2463 BuiltinID == ARM::BI__builtin_arm_wsrp) 2464 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2465 2466 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2467 return true; 2468 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2469 return true; 2470 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2471 return true; 2472 2473 // For intrinsics which take an immediate value as part of the instruction, 2474 // range check them here. 2475 // FIXME: VFP Intrinsics should error if VFP not present. 2476 switch (BuiltinID) { 2477 default: return false; 2478 case ARM::BI__builtin_arm_ssat: 2479 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2480 case ARM::BI__builtin_arm_usat: 2481 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2482 case ARM::BI__builtin_arm_ssat16: 2483 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2484 case ARM::BI__builtin_arm_usat16: 2485 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2486 case ARM::BI__builtin_arm_vcvtr_f: 2487 case ARM::BI__builtin_arm_vcvtr_d: 2488 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2489 case ARM::BI__builtin_arm_dmb: 2490 case ARM::BI__builtin_arm_dsb: 2491 case ARM::BI__builtin_arm_isb: 2492 case ARM::BI__builtin_arm_dbg: 2493 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2494 case ARM::BI__builtin_arm_cdp: 2495 case ARM::BI__builtin_arm_cdp2: 2496 case ARM::BI__builtin_arm_mcr: 2497 case ARM::BI__builtin_arm_mcr2: 2498 case ARM::BI__builtin_arm_mrc: 2499 case ARM::BI__builtin_arm_mrc2: 2500 case ARM::BI__builtin_arm_mcrr: 2501 case ARM::BI__builtin_arm_mcrr2: 2502 case ARM::BI__builtin_arm_mrrc: 2503 case ARM::BI__builtin_arm_mrrc2: 2504 case ARM::BI__builtin_arm_ldc: 2505 case ARM::BI__builtin_arm_ldcl: 2506 case ARM::BI__builtin_arm_ldc2: 2507 case ARM::BI__builtin_arm_ldc2l: 2508 case ARM::BI__builtin_arm_stc: 2509 case ARM::BI__builtin_arm_stcl: 2510 case ARM::BI__builtin_arm_stc2: 2511 case ARM::BI__builtin_arm_stc2l: 2512 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2513 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2514 /*WantCDE*/ false); 2515 } 2516 } 2517 2518 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2519 unsigned BuiltinID, 2520 CallExpr *TheCall) { 2521 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2522 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2523 BuiltinID == AArch64::BI__builtin_arm_strex || 2524 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2525 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2526 } 2527 2528 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2529 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2530 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2531 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2532 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2533 } 2534 2535 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2536 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2537 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2538 2539 // Memory Tagging Extensions (MTE) Intrinsics 2540 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2541 BuiltinID == AArch64::BI__builtin_arm_addg || 2542 BuiltinID == AArch64::BI__builtin_arm_gmi || 2543 BuiltinID == AArch64::BI__builtin_arm_ldg || 2544 BuiltinID == AArch64::BI__builtin_arm_stg || 2545 BuiltinID == AArch64::BI__builtin_arm_subp) { 2546 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2547 } 2548 2549 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2550 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2551 BuiltinID == AArch64::BI__builtin_arm_wsr || 2552 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2553 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2554 2555 // Only check the valid encoding range. Any constant in this range would be 2556 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2557 // an exception for incorrect registers. This matches MSVC behavior. 2558 if (BuiltinID == AArch64::BI_ReadStatusReg || 2559 BuiltinID == AArch64::BI_WriteStatusReg) 2560 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2561 2562 if (BuiltinID == AArch64::BI__getReg) 2563 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2564 2565 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2566 return true; 2567 2568 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2569 return true; 2570 2571 // For intrinsics which take an immediate value as part of the instruction, 2572 // range check them here. 2573 unsigned i = 0, l = 0, u = 0; 2574 switch (BuiltinID) { 2575 default: return false; 2576 case AArch64::BI__builtin_arm_dmb: 2577 case AArch64::BI__builtin_arm_dsb: 2578 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2579 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2580 } 2581 2582 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2583 } 2584 2585 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2586 if (Arg->getType()->getAsPlaceholderType()) 2587 return false; 2588 2589 // The first argument needs to be a record field access. 2590 // If it is an array element access, we delay decision 2591 // to BPF backend to check whether the access is a 2592 // field access or not. 2593 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2594 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2595 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2596 } 2597 2598 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2599 QualType VectorTy, QualType EltTy) { 2600 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2601 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2602 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2603 << Call->getSourceRange() << VectorEltTy << EltTy; 2604 return false; 2605 } 2606 return true; 2607 } 2608 2609 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2610 QualType ArgType = Arg->getType(); 2611 if (ArgType->getAsPlaceholderType()) 2612 return false; 2613 2614 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2615 // format: 2616 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2617 // 2. <type> var; 2618 // __builtin_preserve_type_info(var, flag); 2619 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2620 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2621 return false; 2622 2623 // Typedef type. 2624 if (ArgType->getAs<TypedefType>()) 2625 return true; 2626 2627 // Record type or Enum type. 2628 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2629 if (const auto *RT = Ty->getAs<RecordType>()) { 2630 if (!RT->getDecl()->getDeclName().isEmpty()) 2631 return true; 2632 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2633 if (!ET->getDecl()->getDeclName().isEmpty()) 2634 return true; 2635 } 2636 2637 return false; 2638 } 2639 2640 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2641 QualType ArgType = Arg->getType(); 2642 if (ArgType->getAsPlaceholderType()) 2643 return false; 2644 2645 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2646 // format: 2647 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2648 // flag); 2649 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2650 if (!UO) 2651 return false; 2652 2653 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2654 if (!CE) 2655 return false; 2656 if (CE->getCastKind() != CK_IntegralToPointer && 2657 CE->getCastKind() != CK_NullToPointer) 2658 return false; 2659 2660 // The integer must be from an EnumConstantDecl. 2661 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2662 if (!DR) 2663 return false; 2664 2665 const EnumConstantDecl *Enumerator = 2666 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2667 if (!Enumerator) 2668 return false; 2669 2670 // The type must be EnumType. 2671 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2672 const auto *ET = Ty->getAs<EnumType>(); 2673 if (!ET) 2674 return false; 2675 2676 // The enum value must be supported. 2677 for (auto *EDI : ET->getDecl()->enumerators()) { 2678 if (EDI == Enumerator) 2679 return true; 2680 } 2681 2682 return false; 2683 } 2684 2685 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2686 CallExpr *TheCall) { 2687 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2688 BuiltinID == BPF::BI__builtin_btf_type_id || 2689 BuiltinID == BPF::BI__builtin_preserve_type_info || 2690 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2691 "unexpected BPF builtin"); 2692 2693 if (checkArgCount(*this, TheCall, 2)) 2694 return true; 2695 2696 // The second argument needs to be a constant int 2697 Expr *Arg = TheCall->getArg(1); 2698 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2699 diag::kind kind; 2700 if (!Value) { 2701 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2702 kind = diag::err_preserve_field_info_not_const; 2703 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2704 kind = diag::err_btf_type_id_not_const; 2705 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2706 kind = diag::err_preserve_type_info_not_const; 2707 else 2708 kind = diag::err_preserve_enum_value_not_const; 2709 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2710 return true; 2711 } 2712 2713 // The first argument 2714 Arg = TheCall->getArg(0); 2715 bool InvalidArg = false; 2716 bool ReturnUnsignedInt = true; 2717 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2718 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2719 InvalidArg = true; 2720 kind = diag::err_preserve_field_info_not_field; 2721 } 2722 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2723 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2724 InvalidArg = true; 2725 kind = diag::err_preserve_type_info_invalid; 2726 } 2727 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2728 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2729 InvalidArg = true; 2730 kind = diag::err_preserve_enum_value_invalid; 2731 } 2732 ReturnUnsignedInt = false; 2733 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2734 ReturnUnsignedInt = false; 2735 } 2736 2737 if (InvalidArg) { 2738 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2739 return true; 2740 } 2741 2742 if (ReturnUnsignedInt) 2743 TheCall->setType(Context.UnsignedIntTy); 2744 else 2745 TheCall->setType(Context.UnsignedLongTy); 2746 return false; 2747 } 2748 2749 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2750 struct ArgInfo { 2751 uint8_t OpNum; 2752 bool IsSigned; 2753 uint8_t BitWidth; 2754 uint8_t Align; 2755 }; 2756 struct BuiltinInfo { 2757 unsigned BuiltinID; 2758 ArgInfo Infos[2]; 2759 }; 2760 2761 static BuiltinInfo Infos[] = { 2762 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2763 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2764 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2765 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2766 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2767 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2768 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2769 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2770 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2771 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2772 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2773 2774 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2785 2786 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2838 {{ 1, false, 6, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2846 {{ 1, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2853 { 2, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2855 { 2, false, 6, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2857 { 3, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2859 { 3, false, 6, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2876 {{ 2, false, 4, 0 }, 2877 { 3, false, 5, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2879 {{ 2, false, 4, 0 }, 2880 { 3, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2882 {{ 2, false, 4, 0 }, 2883 { 3, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2885 {{ 2, false, 4, 0 }, 2886 { 3, false, 5, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2898 { 2, false, 5, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2900 { 2, false, 6, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2910 {{ 1, false, 4, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2913 {{ 1, false, 4, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2934 {{ 3, false, 1, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2939 {{ 3, false, 1, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2944 {{ 3, false, 1, 0 }} }, 2945 }; 2946 2947 // Use a dynamically initialized static to sort the table exactly once on 2948 // first run. 2949 static const bool SortOnce = 2950 (llvm::sort(Infos, 2951 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2952 return LHS.BuiltinID < RHS.BuiltinID; 2953 }), 2954 true); 2955 (void)SortOnce; 2956 2957 const BuiltinInfo *F = llvm::partition_point( 2958 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2959 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2960 return false; 2961 2962 bool Error = false; 2963 2964 for (const ArgInfo &A : F->Infos) { 2965 // Ignore empty ArgInfo elements. 2966 if (A.BitWidth == 0) 2967 continue; 2968 2969 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2970 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2971 if (!A.Align) { 2972 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2973 } else { 2974 unsigned M = 1 << A.Align; 2975 Min *= M; 2976 Max *= M; 2977 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2978 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2979 } 2980 } 2981 return Error; 2982 } 2983 2984 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2985 CallExpr *TheCall) { 2986 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2987 } 2988 2989 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2990 unsigned BuiltinID, CallExpr *TheCall) { 2991 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2992 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2993 } 2994 2995 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2996 CallExpr *TheCall) { 2997 2998 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2999 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3000 if (!TI.hasFeature("dsp")) 3001 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3002 } 3003 3004 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3005 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3006 if (!TI.hasFeature("dspr2")) 3007 return Diag(TheCall->getBeginLoc(), 3008 diag::err_mips_builtin_requires_dspr2); 3009 } 3010 3011 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3012 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3013 if (!TI.hasFeature("msa")) 3014 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3015 } 3016 3017 return false; 3018 } 3019 3020 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3021 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3022 // ordering for DSP is unspecified. MSA is ordered by the data format used 3023 // by the underlying instruction i.e., df/m, df/n and then by size. 3024 // 3025 // FIXME: The size tests here should instead be tablegen'd along with the 3026 // definitions from include/clang/Basic/BuiltinsMips.def. 3027 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3028 // be too. 3029 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3030 unsigned i = 0, l = 0, u = 0, m = 0; 3031 switch (BuiltinID) { 3032 default: return false; 3033 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3034 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3035 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3036 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3037 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3038 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3039 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3040 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3041 // df/m field. 3042 // These intrinsics take an unsigned 3 bit immediate. 3043 case Mips::BI__builtin_msa_bclri_b: 3044 case Mips::BI__builtin_msa_bnegi_b: 3045 case Mips::BI__builtin_msa_bseti_b: 3046 case Mips::BI__builtin_msa_sat_s_b: 3047 case Mips::BI__builtin_msa_sat_u_b: 3048 case Mips::BI__builtin_msa_slli_b: 3049 case Mips::BI__builtin_msa_srai_b: 3050 case Mips::BI__builtin_msa_srari_b: 3051 case Mips::BI__builtin_msa_srli_b: 3052 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3053 case Mips::BI__builtin_msa_binsli_b: 3054 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3055 // These intrinsics take an unsigned 4 bit immediate. 3056 case Mips::BI__builtin_msa_bclri_h: 3057 case Mips::BI__builtin_msa_bnegi_h: 3058 case Mips::BI__builtin_msa_bseti_h: 3059 case Mips::BI__builtin_msa_sat_s_h: 3060 case Mips::BI__builtin_msa_sat_u_h: 3061 case Mips::BI__builtin_msa_slli_h: 3062 case Mips::BI__builtin_msa_srai_h: 3063 case Mips::BI__builtin_msa_srari_h: 3064 case Mips::BI__builtin_msa_srli_h: 3065 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3066 case Mips::BI__builtin_msa_binsli_h: 3067 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3068 // These intrinsics take an unsigned 5 bit immediate. 3069 // The first block of intrinsics actually have an unsigned 5 bit field, 3070 // not a df/n field. 3071 case Mips::BI__builtin_msa_cfcmsa: 3072 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3073 case Mips::BI__builtin_msa_clei_u_b: 3074 case Mips::BI__builtin_msa_clei_u_h: 3075 case Mips::BI__builtin_msa_clei_u_w: 3076 case Mips::BI__builtin_msa_clei_u_d: 3077 case Mips::BI__builtin_msa_clti_u_b: 3078 case Mips::BI__builtin_msa_clti_u_h: 3079 case Mips::BI__builtin_msa_clti_u_w: 3080 case Mips::BI__builtin_msa_clti_u_d: 3081 case Mips::BI__builtin_msa_maxi_u_b: 3082 case Mips::BI__builtin_msa_maxi_u_h: 3083 case Mips::BI__builtin_msa_maxi_u_w: 3084 case Mips::BI__builtin_msa_maxi_u_d: 3085 case Mips::BI__builtin_msa_mini_u_b: 3086 case Mips::BI__builtin_msa_mini_u_h: 3087 case Mips::BI__builtin_msa_mini_u_w: 3088 case Mips::BI__builtin_msa_mini_u_d: 3089 case Mips::BI__builtin_msa_addvi_b: 3090 case Mips::BI__builtin_msa_addvi_h: 3091 case Mips::BI__builtin_msa_addvi_w: 3092 case Mips::BI__builtin_msa_addvi_d: 3093 case Mips::BI__builtin_msa_bclri_w: 3094 case Mips::BI__builtin_msa_bnegi_w: 3095 case Mips::BI__builtin_msa_bseti_w: 3096 case Mips::BI__builtin_msa_sat_s_w: 3097 case Mips::BI__builtin_msa_sat_u_w: 3098 case Mips::BI__builtin_msa_slli_w: 3099 case Mips::BI__builtin_msa_srai_w: 3100 case Mips::BI__builtin_msa_srari_w: 3101 case Mips::BI__builtin_msa_srli_w: 3102 case Mips::BI__builtin_msa_srlri_w: 3103 case Mips::BI__builtin_msa_subvi_b: 3104 case Mips::BI__builtin_msa_subvi_h: 3105 case Mips::BI__builtin_msa_subvi_w: 3106 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3107 case Mips::BI__builtin_msa_binsli_w: 3108 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3109 // These intrinsics take an unsigned 6 bit immediate. 3110 case Mips::BI__builtin_msa_bclri_d: 3111 case Mips::BI__builtin_msa_bnegi_d: 3112 case Mips::BI__builtin_msa_bseti_d: 3113 case Mips::BI__builtin_msa_sat_s_d: 3114 case Mips::BI__builtin_msa_sat_u_d: 3115 case Mips::BI__builtin_msa_slli_d: 3116 case Mips::BI__builtin_msa_srai_d: 3117 case Mips::BI__builtin_msa_srari_d: 3118 case Mips::BI__builtin_msa_srli_d: 3119 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3120 case Mips::BI__builtin_msa_binsli_d: 3121 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3122 // These intrinsics take a signed 5 bit immediate. 3123 case Mips::BI__builtin_msa_ceqi_b: 3124 case Mips::BI__builtin_msa_ceqi_h: 3125 case Mips::BI__builtin_msa_ceqi_w: 3126 case Mips::BI__builtin_msa_ceqi_d: 3127 case Mips::BI__builtin_msa_clti_s_b: 3128 case Mips::BI__builtin_msa_clti_s_h: 3129 case Mips::BI__builtin_msa_clti_s_w: 3130 case Mips::BI__builtin_msa_clti_s_d: 3131 case Mips::BI__builtin_msa_clei_s_b: 3132 case Mips::BI__builtin_msa_clei_s_h: 3133 case Mips::BI__builtin_msa_clei_s_w: 3134 case Mips::BI__builtin_msa_clei_s_d: 3135 case Mips::BI__builtin_msa_maxi_s_b: 3136 case Mips::BI__builtin_msa_maxi_s_h: 3137 case Mips::BI__builtin_msa_maxi_s_w: 3138 case Mips::BI__builtin_msa_maxi_s_d: 3139 case Mips::BI__builtin_msa_mini_s_b: 3140 case Mips::BI__builtin_msa_mini_s_h: 3141 case Mips::BI__builtin_msa_mini_s_w: 3142 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3143 // These intrinsics take an unsigned 8 bit immediate. 3144 case Mips::BI__builtin_msa_andi_b: 3145 case Mips::BI__builtin_msa_nori_b: 3146 case Mips::BI__builtin_msa_ori_b: 3147 case Mips::BI__builtin_msa_shf_b: 3148 case Mips::BI__builtin_msa_shf_h: 3149 case Mips::BI__builtin_msa_shf_w: 3150 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3151 case Mips::BI__builtin_msa_bseli_b: 3152 case Mips::BI__builtin_msa_bmnzi_b: 3153 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3154 // df/n format 3155 // These intrinsics take an unsigned 4 bit immediate. 3156 case Mips::BI__builtin_msa_copy_s_b: 3157 case Mips::BI__builtin_msa_copy_u_b: 3158 case Mips::BI__builtin_msa_insve_b: 3159 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3160 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3161 // These intrinsics take an unsigned 3 bit immediate. 3162 case Mips::BI__builtin_msa_copy_s_h: 3163 case Mips::BI__builtin_msa_copy_u_h: 3164 case Mips::BI__builtin_msa_insve_h: 3165 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3166 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3167 // These intrinsics take an unsigned 2 bit immediate. 3168 case Mips::BI__builtin_msa_copy_s_w: 3169 case Mips::BI__builtin_msa_copy_u_w: 3170 case Mips::BI__builtin_msa_insve_w: 3171 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3172 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3173 // These intrinsics take an unsigned 1 bit immediate. 3174 case Mips::BI__builtin_msa_copy_s_d: 3175 case Mips::BI__builtin_msa_copy_u_d: 3176 case Mips::BI__builtin_msa_insve_d: 3177 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3178 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3179 // Memory offsets and immediate loads. 3180 // These intrinsics take a signed 10 bit immediate. 3181 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3182 case Mips::BI__builtin_msa_ldi_h: 3183 case Mips::BI__builtin_msa_ldi_w: 3184 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3185 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3186 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3187 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3188 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3189 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3190 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3191 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3192 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3193 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3194 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3195 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3196 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3197 } 3198 3199 if (!m) 3200 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3201 3202 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3203 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3204 } 3205 3206 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3207 /// advancing the pointer over the consumed characters. The decoded type is 3208 /// returned. If the decoded type represents a constant integer with a 3209 /// constraint on its value then Mask is set to that value. The type descriptors 3210 /// used in Str are specific to PPC MMA builtins and are documented in the file 3211 /// defining the PPC builtins. 3212 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3213 unsigned &Mask) { 3214 bool RequireICE = false; 3215 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3216 switch (*Str++) { 3217 case 'V': 3218 return Context.getVectorType(Context.UnsignedCharTy, 16, 3219 VectorType::VectorKind::AltiVecVector); 3220 case 'i': { 3221 char *End; 3222 unsigned size = strtoul(Str, &End, 10); 3223 assert(End != Str && "Missing constant parameter constraint"); 3224 Str = End; 3225 Mask = size; 3226 return Context.IntTy; 3227 } 3228 case 'W': { 3229 char *End; 3230 unsigned size = strtoul(Str, &End, 10); 3231 assert(End != Str && "Missing PowerPC MMA type size"); 3232 Str = End; 3233 QualType Type; 3234 switch (size) { 3235 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3236 case size: Type = Context.Id##Ty; break; 3237 #include "clang/Basic/PPCTypes.def" 3238 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3239 } 3240 bool CheckVectorArgs = false; 3241 while (!CheckVectorArgs) { 3242 switch (*Str++) { 3243 case '*': 3244 Type = Context.getPointerType(Type); 3245 break; 3246 case 'C': 3247 Type = Type.withConst(); 3248 break; 3249 default: 3250 CheckVectorArgs = true; 3251 --Str; 3252 break; 3253 } 3254 } 3255 return Type; 3256 } 3257 default: 3258 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3259 } 3260 } 3261 3262 static bool isPPC_64Builtin(unsigned BuiltinID) { 3263 // These builtins only work on PPC 64bit targets. 3264 switch (BuiltinID) { 3265 case PPC::BI__builtin_divde: 3266 case PPC::BI__builtin_divdeu: 3267 case PPC::BI__builtin_bpermd: 3268 case PPC::BI__builtin_ppc_ldarx: 3269 case PPC::BI__builtin_ppc_stdcx: 3270 case PPC::BI__builtin_ppc_tdw: 3271 case PPC::BI__builtin_ppc_trapd: 3272 case PPC::BI__builtin_ppc_cmpeqb: 3273 case PPC::BI__builtin_ppc_setb: 3274 case PPC::BI__builtin_ppc_mulhd: 3275 case PPC::BI__builtin_ppc_mulhdu: 3276 case PPC::BI__builtin_ppc_maddhd: 3277 case PPC::BI__builtin_ppc_maddhdu: 3278 case PPC::BI__builtin_ppc_maddld: 3279 case PPC::BI__builtin_ppc_load8r: 3280 case PPC::BI__builtin_ppc_store8r: 3281 case PPC::BI__builtin_ppc_insert_exp: 3282 case PPC::BI__builtin_ppc_extract_sig: 3283 return true; 3284 } 3285 return false; 3286 } 3287 3288 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3289 StringRef FeatureToCheck, unsigned DiagID, 3290 StringRef DiagArg = "") { 3291 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3292 return false; 3293 3294 if (DiagArg.empty()) 3295 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3296 else 3297 S.Diag(TheCall->getBeginLoc(), DiagID) 3298 << DiagArg << TheCall->getSourceRange(); 3299 3300 return true; 3301 } 3302 3303 /// Returns true if the argument consists of one contiguous run of 1s with any 3304 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3305 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3306 /// since all 1s are not contiguous. 3307 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3308 llvm::APSInt Result; 3309 // We can't check the value of a dependent argument. 3310 Expr *Arg = TheCall->getArg(ArgNum); 3311 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3312 return false; 3313 3314 // Check constant-ness first. 3315 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3316 return true; 3317 3318 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3319 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3320 return false; 3321 3322 return Diag(TheCall->getBeginLoc(), 3323 diag::err_argument_not_contiguous_bit_field) 3324 << ArgNum << Arg->getSourceRange(); 3325 } 3326 3327 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3328 CallExpr *TheCall) { 3329 unsigned i = 0, l = 0, u = 0; 3330 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3331 llvm::APSInt Result; 3332 3333 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3334 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3335 << TheCall->getSourceRange(); 3336 3337 switch (BuiltinID) { 3338 default: return false; 3339 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3340 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3341 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3342 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3343 case PPC::BI__builtin_altivec_dss: 3344 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3345 case PPC::BI__builtin_tbegin: 3346 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3347 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3348 case PPC::BI__builtin_tabortwc: 3349 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3350 case PPC::BI__builtin_tabortwci: 3351 case PPC::BI__builtin_tabortdci: 3352 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3353 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3354 case PPC::BI__builtin_altivec_dst: 3355 case PPC::BI__builtin_altivec_dstt: 3356 case PPC::BI__builtin_altivec_dstst: 3357 case PPC::BI__builtin_altivec_dststt: 3358 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3359 case PPC::BI__builtin_vsx_xxpermdi: 3360 case PPC::BI__builtin_vsx_xxsldwi: 3361 return SemaBuiltinVSX(TheCall); 3362 case PPC::BI__builtin_divwe: 3363 case PPC::BI__builtin_divweu: 3364 case PPC::BI__builtin_divde: 3365 case PPC::BI__builtin_divdeu: 3366 return SemaFeatureCheck(*this, TheCall, "extdiv", 3367 diag::err_ppc_builtin_only_on_arch, "7"); 3368 case PPC::BI__builtin_bpermd: 3369 return SemaFeatureCheck(*this, TheCall, "bpermd", 3370 diag::err_ppc_builtin_only_on_arch, "7"); 3371 case PPC::BI__builtin_unpack_vector_int128: 3372 return SemaFeatureCheck(*this, TheCall, "vsx", 3373 diag::err_ppc_builtin_only_on_arch, "7") || 3374 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3375 case PPC::BI__builtin_pack_vector_int128: 3376 return SemaFeatureCheck(*this, TheCall, "vsx", 3377 diag::err_ppc_builtin_only_on_arch, "7"); 3378 case PPC::BI__builtin_altivec_vgnb: 3379 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3380 case PPC::BI__builtin_altivec_vec_replace_elt: 3381 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3382 QualType VecTy = TheCall->getArg(0)->getType(); 3383 QualType EltTy = TheCall->getArg(1)->getType(); 3384 unsigned Width = Context.getIntWidth(EltTy); 3385 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3386 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3387 } 3388 case PPC::BI__builtin_vsx_xxeval: 3389 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3390 case PPC::BI__builtin_altivec_vsldbi: 3391 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3392 case PPC::BI__builtin_altivec_vsrdbi: 3393 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3394 case PPC::BI__builtin_vsx_xxpermx: 3395 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3396 case PPC::BI__builtin_ppc_tw: 3397 case PPC::BI__builtin_ppc_tdw: 3398 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3399 case PPC::BI__builtin_ppc_cmpeqb: 3400 case PPC::BI__builtin_ppc_setb: 3401 case PPC::BI__builtin_ppc_maddhd: 3402 case PPC::BI__builtin_ppc_maddhdu: 3403 case PPC::BI__builtin_ppc_maddld: 3404 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3405 diag::err_ppc_builtin_only_on_arch, "9"); 3406 case PPC::BI__builtin_ppc_cmprb: 3407 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3408 diag::err_ppc_builtin_only_on_arch, "9") || 3409 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3410 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3411 // be a constant that represents a contiguous bit field. 3412 case PPC::BI__builtin_ppc_rlwnm: 3413 return SemaBuiltinConstantArg(TheCall, 1, Result) || 3414 SemaValueIsRunOfOnes(TheCall, 2); 3415 case PPC::BI__builtin_ppc_rlwimi: 3416 case PPC::BI__builtin_ppc_rldimi: 3417 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3418 SemaValueIsRunOfOnes(TheCall, 3); 3419 case PPC::BI__builtin_ppc_extract_exp: 3420 case PPC::BI__builtin_ppc_extract_sig: 3421 case PPC::BI__builtin_ppc_insert_exp: 3422 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3423 diag::err_ppc_builtin_only_on_arch, "9"); 3424 case PPC::BI__builtin_ppc_mtfsb0: 3425 case PPC::BI__builtin_ppc_mtfsb1: 3426 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3427 case PPC::BI__builtin_ppc_mtfsf: 3428 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3429 case PPC::BI__builtin_ppc_mtfsfi: 3430 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3431 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3432 case PPC::BI__builtin_ppc_alignx: 3433 return SemaBuiltinConstantArgPower2(TheCall, 0); 3434 case PPC::BI__builtin_ppc_rdlam: 3435 return SemaValueIsRunOfOnes(TheCall, 2); 3436 case PPC::BI__builtin_ppc_icbt: 3437 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3438 diag::err_ppc_builtin_only_on_arch, "8"); 3439 case PPC::BI__builtin_ppc_sthcx: 3440 case PPC::BI__builtin_ppc_lharx: 3441 case PPC::BI__builtin_ppc_lbarx: 3442 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3443 diag::err_ppc_builtin_only_on_arch, "8"); 3444 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3445 case PPC::BI__builtin_##Name: \ 3446 return SemaBuiltinPPCMMACall(TheCall, Types); 3447 #include "clang/Basic/BuiltinsPPC.def" 3448 } 3449 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3450 } 3451 3452 // Check if the given type is a non-pointer PPC MMA type. This function is used 3453 // in Sema to prevent invalid uses of restricted PPC MMA types. 3454 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3455 if (Type->isPointerType() || Type->isArrayType()) 3456 return false; 3457 3458 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3459 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3460 if (false 3461 #include "clang/Basic/PPCTypes.def" 3462 ) { 3463 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3464 return true; 3465 } 3466 return false; 3467 } 3468 3469 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3470 CallExpr *TheCall) { 3471 // position of memory order and scope arguments in the builtin 3472 unsigned OrderIndex, ScopeIndex; 3473 switch (BuiltinID) { 3474 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3475 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3476 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3477 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3478 OrderIndex = 2; 3479 ScopeIndex = 3; 3480 break; 3481 case AMDGPU::BI__builtin_amdgcn_fence: 3482 OrderIndex = 0; 3483 ScopeIndex = 1; 3484 break; 3485 default: 3486 return false; 3487 } 3488 3489 ExprResult Arg = TheCall->getArg(OrderIndex); 3490 auto ArgExpr = Arg.get(); 3491 Expr::EvalResult ArgResult; 3492 3493 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3494 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3495 << ArgExpr->getType(); 3496 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3497 3498 // Check valididty of memory ordering as per C11 / C++11's memody model. 3499 // Only fence needs check. Atomic dec/inc allow all memory orders. 3500 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3501 return Diag(ArgExpr->getBeginLoc(), 3502 diag::warn_atomic_op_has_invalid_memory_order) 3503 << ArgExpr->getSourceRange(); 3504 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3505 case llvm::AtomicOrderingCABI::relaxed: 3506 case llvm::AtomicOrderingCABI::consume: 3507 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3508 return Diag(ArgExpr->getBeginLoc(), 3509 diag::warn_atomic_op_has_invalid_memory_order) 3510 << ArgExpr->getSourceRange(); 3511 break; 3512 case llvm::AtomicOrderingCABI::acquire: 3513 case llvm::AtomicOrderingCABI::release: 3514 case llvm::AtomicOrderingCABI::acq_rel: 3515 case llvm::AtomicOrderingCABI::seq_cst: 3516 break; 3517 } 3518 3519 Arg = TheCall->getArg(ScopeIndex); 3520 ArgExpr = Arg.get(); 3521 Expr::EvalResult ArgResult1; 3522 // Check that sync scope is a constant literal 3523 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3524 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3525 << ArgExpr->getType(); 3526 3527 return false; 3528 } 3529 3530 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3531 llvm::APSInt Result; 3532 3533 // We can't check the value of a dependent argument. 3534 Expr *Arg = TheCall->getArg(ArgNum); 3535 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3536 return false; 3537 3538 // Check constant-ness first. 3539 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3540 return true; 3541 3542 int64_t Val = Result.getSExtValue(); 3543 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3544 return false; 3545 3546 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3547 << Arg->getSourceRange(); 3548 } 3549 3550 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3551 unsigned BuiltinID, 3552 CallExpr *TheCall) { 3553 // CodeGenFunction can also detect this, but this gives a better error 3554 // message. 3555 bool FeatureMissing = false; 3556 SmallVector<StringRef> ReqFeatures; 3557 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3558 Features.split(ReqFeatures, ','); 3559 3560 // Check if each required feature is included 3561 for (StringRef F : ReqFeatures) { 3562 if (TI.hasFeature(F)) 3563 continue; 3564 3565 // If the feature is 64bit, alter the string so it will print better in 3566 // the diagnostic. 3567 if (F == "64bit") 3568 F = "RV64"; 3569 3570 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3571 F.consume_front("experimental-"); 3572 std::string FeatureStr = F.str(); 3573 FeatureStr[0] = std::toupper(FeatureStr[0]); 3574 3575 // Error message 3576 FeatureMissing = true; 3577 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3578 << TheCall->getSourceRange() << StringRef(FeatureStr); 3579 } 3580 3581 if (FeatureMissing) 3582 return true; 3583 3584 switch (BuiltinID) { 3585 case RISCV::BI__builtin_rvv_vsetvli: 3586 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3587 CheckRISCVLMUL(TheCall, 2); 3588 case RISCV::BI__builtin_rvv_vsetvlimax: 3589 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3590 CheckRISCVLMUL(TheCall, 1); 3591 case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1: 3592 case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1: 3593 case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1: 3594 case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1: 3595 case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1: 3596 case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1: 3597 case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1: 3598 case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1: 3599 case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1: 3600 case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1: 3601 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2: 3602 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2: 3603 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2: 3604 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2: 3605 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2: 3606 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2: 3607 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2: 3608 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2: 3609 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2: 3610 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2: 3611 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4: 3612 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4: 3613 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4: 3614 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4: 3615 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4: 3616 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4: 3617 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4: 3618 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4: 3619 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4: 3620 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4: 3621 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3622 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1: 3623 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1: 3624 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1: 3625 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1: 3626 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1: 3627 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1: 3628 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1: 3629 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1: 3630 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1: 3631 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1: 3632 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2: 3633 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2: 3634 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2: 3635 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2: 3636 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2: 3637 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2: 3638 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2: 3639 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2: 3640 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2: 3641 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2: 3642 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3643 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1: 3644 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1: 3645 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1: 3646 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1: 3647 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1: 3648 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1: 3649 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1: 3650 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1: 3651 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1: 3652 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1: 3653 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3654 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2: 3655 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2: 3656 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2: 3657 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2: 3658 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2: 3659 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2: 3660 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2: 3661 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2: 3662 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2: 3663 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2: 3664 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4: 3665 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4: 3666 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4: 3667 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4: 3668 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4: 3669 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4: 3670 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4: 3671 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4: 3672 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4: 3673 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4: 3674 case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8: 3675 case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8: 3676 case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8: 3677 case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8: 3678 case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8: 3679 case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8: 3680 case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8: 3681 case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8: 3682 case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8: 3683 case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8: 3684 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3685 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4: 3686 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4: 3687 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4: 3688 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4: 3689 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4: 3690 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4: 3691 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4: 3692 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4: 3693 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4: 3694 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4: 3695 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8: 3696 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8: 3697 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8: 3698 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8: 3699 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8: 3700 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8: 3701 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8: 3702 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8: 3703 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8: 3704 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8: 3705 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3706 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8: 3707 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8: 3708 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8: 3709 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8: 3710 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8: 3711 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8: 3712 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8: 3713 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8: 3714 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8: 3715 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8: 3716 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3717 } 3718 3719 return false; 3720 } 3721 3722 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3723 CallExpr *TheCall) { 3724 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3725 Expr *Arg = TheCall->getArg(0); 3726 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3727 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3728 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3729 << Arg->getSourceRange(); 3730 } 3731 3732 // For intrinsics which take an immediate value as part of the instruction, 3733 // range check them here. 3734 unsigned i = 0, l = 0, u = 0; 3735 switch (BuiltinID) { 3736 default: return false; 3737 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3738 case SystemZ::BI__builtin_s390_verimb: 3739 case SystemZ::BI__builtin_s390_verimh: 3740 case SystemZ::BI__builtin_s390_verimf: 3741 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3742 case SystemZ::BI__builtin_s390_vfaeb: 3743 case SystemZ::BI__builtin_s390_vfaeh: 3744 case SystemZ::BI__builtin_s390_vfaef: 3745 case SystemZ::BI__builtin_s390_vfaebs: 3746 case SystemZ::BI__builtin_s390_vfaehs: 3747 case SystemZ::BI__builtin_s390_vfaefs: 3748 case SystemZ::BI__builtin_s390_vfaezb: 3749 case SystemZ::BI__builtin_s390_vfaezh: 3750 case SystemZ::BI__builtin_s390_vfaezf: 3751 case SystemZ::BI__builtin_s390_vfaezbs: 3752 case SystemZ::BI__builtin_s390_vfaezhs: 3753 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3754 case SystemZ::BI__builtin_s390_vfisb: 3755 case SystemZ::BI__builtin_s390_vfidb: 3756 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3757 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3758 case SystemZ::BI__builtin_s390_vftcisb: 3759 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3760 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3761 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3762 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3763 case SystemZ::BI__builtin_s390_vstrcb: 3764 case SystemZ::BI__builtin_s390_vstrch: 3765 case SystemZ::BI__builtin_s390_vstrcf: 3766 case SystemZ::BI__builtin_s390_vstrczb: 3767 case SystemZ::BI__builtin_s390_vstrczh: 3768 case SystemZ::BI__builtin_s390_vstrczf: 3769 case SystemZ::BI__builtin_s390_vstrcbs: 3770 case SystemZ::BI__builtin_s390_vstrchs: 3771 case SystemZ::BI__builtin_s390_vstrcfs: 3772 case SystemZ::BI__builtin_s390_vstrczbs: 3773 case SystemZ::BI__builtin_s390_vstrczhs: 3774 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3775 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3776 case SystemZ::BI__builtin_s390_vfminsb: 3777 case SystemZ::BI__builtin_s390_vfmaxsb: 3778 case SystemZ::BI__builtin_s390_vfmindb: 3779 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3780 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3781 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3782 } 3783 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3784 } 3785 3786 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3787 /// This checks that the target supports __builtin_cpu_supports and 3788 /// that the string argument is constant and valid. 3789 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3790 CallExpr *TheCall) { 3791 Expr *Arg = TheCall->getArg(0); 3792 3793 // Check if the argument is a string literal. 3794 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3795 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3796 << Arg->getSourceRange(); 3797 3798 // Check the contents of the string. 3799 StringRef Feature = 3800 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3801 if (!TI.validateCpuSupports(Feature)) 3802 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3803 << Arg->getSourceRange(); 3804 return false; 3805 } 3806 3807 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3808 /// This checks that the target supports __builtin_cpu_is and 3809 /// that the string argument is constant and valid. 3810 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3811 Expr *Arg = TheCall->getArg(0); 3812 3813 // Check if the argument is a string literal. 3814 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3815 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3816 << Arg->getSourceRange(); 3817 3818 // Check the contents of the string. 3819 StringRef Feature = 3820 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3821 if (!TI.validateCpuIs(Feature)) 3822 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3823 << Arg->getSourceRange(); 3824 return false; 3825 } 3826 3827 // Check if the rounding mode is legal. 3828 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3829 // Indicates if this instruction has rounding control or just SAE. 3830 bool HasRC = false; 3831 3832 unsigned ArgNum = 0; 3833 switch (BuiltinID) { 3834 default: 3835 return false; 3836 case X86::BI__builtin_ia32_vcvttsd2si32: 3837 case X86::BI__builtin_ia32_vcvttsd2si64: 3838 case X86::BI__builtin_ia32_vcvttsd2usi32: 3839 case X86::BI__builtin_ia32_vcvttsd2usi64: 3840 case X86::BI__builtin_ia32_vcvttss2si32: 3841 case X86::BI__builtin_ia32_vcvttss2si64: 3842 case X86::BI__builtin_ia32_vcvttss2usi32: 3843 case X86::BI__builtin_ia32_vcvttss2usi64: 3844 ArgNum = 1; 3845 break; 3846 case X86::BI__builtin_ia32_maxpd512: 3847 case X86::BI__builtin_ia32_maxps512: 3848 case X86::BI__builtin_ia32_minpd512: 3849 case X86::BI__builtin_ia32_minps512: 3850 ArgNum = 2; 3851 break; 3852 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3853 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3854 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3855 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3856 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3857 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3858 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3859 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3860 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3861 case X86::BI__builtin_ia32_exp2pd_mask: 3862 case X86::BI__builtin_ia32_exp2ps_mask: 3863 case X86::BI__builtin_ia32_getexppd512_mask: 3864 case X86::BI__builtin_ia32_getexpps512_mask: 3865 case X86::BI__builtin_ia32_rcp28pd_mask: 3866 case X86::BI__builtin_ia32_rcp28ps_mask: 3867 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3868 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3869 case X86::BI__builtin_ia32_vcomisd: 3870 case X86::BI__builtin_ia32_vcomiss: 3871 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3872 ArgNum = 3; 3873 break; 3874 case X86::BI__builtin_ia32_cmppd512_mask: 3875 case X86::BI__builtin_ia32_cmpps512_mask: 3876 case X86::BI__builtin_ia32_cmpsd_mask: 3877 case X86::BI__builtin_ia32_cmpss_mask: 3878 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3879 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3880 case X86::BI__builtin_ia32_getexpss128_round_mask: 3881 case X86::BI__builtin_ia32_getmantpd512_mask: 3882 case X86::BI__builtin_ia32_getmantps512_mask: 3883 case X86::BI__builtin_ia32_maxsd_round_mask: 3884 case X86::BI__builtin_ia32_maxss_round_mask: 3885 case X86::BI__builtin_ia32_minsd_round_mask: 3886 case X86::BI__builtin_ia32_minss_round_mask: 3887 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3888 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3889 case X86::BI__builtin_ia32_reducepd512_mask: 3890 case X86::BI__builtin_ia32_reduceps512_mask: 3891 case X86::BI__builtin_ia32_rndscalepd_mask: 3892 case X86::BI__builtin_ia32_rndscaleps_mask: 3893 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3894 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3895 ArgNum = 4; 3896 break; 3897 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3898 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3899 case X86::BI__builtin_ia32_fixupimmps512_mask: 3900 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3901 case X86::BI__builtin_ia32_fixupimmsd_mask: 3902 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3903 case X86::BI__builtin_ia32_fixupimmss_mask: 3904 case X86::BI__builtin_ia32_fixupimmss_maskz: 3905 case X86::BI__builtin_ia32_getmantsd_round_mask: 3906 case X86::BI__builtin_ia32_getmantss_round_mask: 3907 case X86::BI__builtin_ia32_rangepd512_mask: 3908 case X86::BI__builtin_ia32_rangeps512_mask: 3909 case X86::BI__builtin_ia32_rangesd128_round_mask: 3910 case X86::BI__builtin_ia32_rangess128_round_mask: 3911 case X86::BI__builtin_ia32_reducesd_mask: 3912 case X86::BI__builtin_ia32_reducess_mask: 3913 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3914 case X86::BI__builtin_ia32_rndscaless_round_mask: 3915 ArgNum = 5; 3916 break; 3917 case X86::BI__builtin_ia32_vcvtsd2si64: 3918 case X86::BI__builtin_ia32_vcvtsd2si32: 3919 case X86::BI__builtin_ia32_vcvtsd2usi32: 3920 case X86::BI__builtin_ia32_vcvtsd2usi64: 3921 case X86::BI__builtin_ia32_vcvtss2si32: 3922 case X86::BI__builtin_ia32_vcvtss2si64: 3923 case X86::BI__builtin_ia32_vcvtss2usi32: 3924 case X86::BI__builtin_ia32_vcvtss2usi64: 3925 case X86::BI__builtin_ia32_sqrtpd512: 3926 case X86::BI__builtin_ia32_sqrtps512: 3927 ArgNum = 1; 3928 HasRC = true; 3929 break; 3930 case X86::BI__builtin_ia32_addpd512: 3931 case X86::BI__builtin_ia32_addps512: 3932 case X86::BI__builtin_ia32_divpd512: 3933 case X86::BI__builtin_ia32_divps512: 3934 case X86::BI__builtin_ia32_mulpd512: 3935 case X86::BI__builtin_ia32_mulps512: 3936 case X86::BI__builtin_ia32_subpd512: 3937 case X86::BI__builtin_ia32_subps512: 3938 case X86::BI__builtin_ia32_cvtsi2sd64: 3939 case X86::BI__builtin_ia32_cvtsi2ss32: 3940 case X86::BI__builtin_ia32_cvtsi2ss64: 3941 case X86::BI__builtin_ia32_cvtusi2sd64: 3942 case X86::BI__builtin_ia32_cvtusi2ss32: 3943 case X86::BI__builtin_ia32_cvtusi2ss64: 3944 ArgNum = 2; 3945 HasRC = true; 3946 break; 3947 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3948 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3949 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3950 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3951 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3952 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3953 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3954 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3955 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3956 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3957 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3958 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3959 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3960 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3961 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3962 ArgNum = 3; 3963 HasRC = true; 3964 break; 3965 case X86::BI__builtin_ia32_addss_round_mask: 3966 case X86::BI__builtin_ia32_addsd_round_mask: 3967 case X86::BI__builtin_ia32_divss_round_mask: 3968 case X86::BI__builtin_ia32_divsd_round_mask: 3969 case X86::BI__builtin_ia32_mulss_round_mask: 3970 case X86::BI__builtin_ia32_mulsd_round_mask: 3971 case X86::BI__builtin_ia32_subss_round_mask: 3972 case X86::BI__builtin_ia32_subsd_round_mask: 3973 case X86::BI__builtin_ia32_scalefpd512_mask: 3974 case X86::BI__builtin_ia32_scalefps512_mask: 3975 case X86::BI__builtin_ia32_scalefsd_round_mask: 3976 case X86::BI__builtin_ia32_scalefss_round_mask: 3977 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3978 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3979 case X86::BI__builtin_ia32_sqrtss_round_mask: 3980 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3981 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3982 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3983 case X86::BI__builtin_ia32_vfmaddss3_mask: 3984 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3985 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3986 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3987 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3988 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3989 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3990 case X86::BI__builtin_ia32_vfmaddps512_mask: 3991 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3992 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3993 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3994 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3995 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3996 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3997 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3998 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3999 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4000 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4001 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4002 ArgNum = 4; 4003 HasRC = true; 4004 break; 4005 } 4006 4007 llvm::APSInt Result; 4008 4009 // We can't check the value of a dependent argument. 4010 Expr *Arg = TheCall->getArg(ArgNum); 4011 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4012 return false; 4013 4014 // Check constant-ness first. 4015 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4016 return true; 4017 4018 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4019 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4020 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4021 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4022 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4023 Result == 8/*ROUND_NO_EXC*/ || 4024 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4025 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4026 return false; 4027 4028 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4029 << Arg->getSourceRange(); 4030 } 4031 4032 // Check if the gather/scatter scale is legal. 4033 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4034 CallExpr *TheCall) { 4035 unsigned ArgNum = 0; 4036 switch (BuiltinID) { 4037 default: 4038 return false; 4039 case X86::BI__builtin_ia32_gatherpfdpd: 4040 case X86::BI__builtin_ia32_gatherpfdps: 4041 case X86::BI__builtin_ia32_gatherpfqpd: 4042 case X86::BI__builtin_ia32_gatherpfqps: 4043 case X86::BI__builtin_ia32_scatterpfdpd: 4044 case X86::BI__builtin_ia32_scatterpfdps: 4045 case X86::BI__builtin_ia32_scatterpfqpd: 4046 case X86::BI__builtin_ia32_scatterpfqps: 4047 ArgNum = 3; 4048 break; 4049 case X86::BI__builtin_ia32_gatherd_pd: 4050 case X86::BI__builtin_ia32_gatherd_pd256: 4051 case X86::BI__builtin_ia32_gatherq_pd: 4052 case X86::BI__builtin_ia32_gatherq_pd256: 4053 case X86::BI__builtin_ia32_gatherd_ps: 4054 case X86::BI__builtin_ia32_gatherd_ps256: 4055 case X86::BI__builtin_ia32_gatherq_ps: 4056 case X86::BI__builtin_ia32_gatherq_ps256: 4057 case X86::BI__builtin_ia32_gatherd_q: 4058 case X86::BI__builtin_ia32_gatherd_q256: 4059 case X86::BI__builtin_ia32_gatherq_q: 4060 case X86::BI__builtin_ia32_gatherq_q256: 4061 case X86::BI__builtin_ia32_gatherd_d: 4062 case X86::BI__builtin_ia32_gatherd_d256: 4063 case X86::BI__builtin_ia32_gatherq_d: 4064 case X86::BI__builtin_ia32_gatherq_d256: 4065 case X86::BI__builtin_ia32_gather3div2df: 4066 case X86::BI__builtin_ia32_gather3div2di: 4067 case X86::BI__builtin_ia32_gather3div4df: 4068 case X86::BI__builtin_ia32_gather3div4di: 4069 case X86::BI__builtin_ia32_gather3div4sf: 4070 case X86::BI__builtin_ia32_gather3div4si: 4071 case X86::BI__builtin_ia32_gather3div8sf: 4072 case X86::BI__builtin_ia32_gather3div8si: 4073 case X86::BI__builtin_ia32_gather3siv2df: 4074 case X86::BI__builtin_ia32_gather3siv2di: 4075 case X86::BI__builtin_ia32_gather3siv4df: 4076 case X86::BI__builtin_ia32_gather3siv4di: 4077 case X86::BI__builtin_ia32_gather3siv4sf: 4078 case X86::BI__builtin_ia32_gather3siv4si: 4079 case X86::BI__builtin_ia32_gather3siv8sf: 4080 case X86::BI__builtin_ia32_gather3siv8si: 4081 case X86::BI__builtin_ia32_gathersiv8df: 4082 case X86::BI__builtin_ia32_gathersiv16sf: 4083 case X86::BI__builtin_ia32_gatherdiv8df: 4084 case X86::BI__builtin_ia32_gatherdiv16sf: 4085 case X86::BI__builtin_ia32_gathersiv8di: 4086 case X86::BI__builtin_ia32_gathersiv16si: 4087 case X86::BI__builtin_ia32_gatherdiv8di: 4088 case X86::BI__builtin_ia32_gatherdiv16si: 4089 case X86::BI__builtin_ia32_scatterdiv2df: 4090 case X86::BI__builtin_ia32_scatterdiv2di: 4091 case X86::BI__builtin_ia32_scatterdiv4df: 4092 case X86::BI__builtin_ia32_scatterdiv4di: 4093 case X86::BI__builtin_ia32_scatterdiv4sf: 4094 case X86::BI__builtin_ia32_scatterdiv4si: 4095 case X86::BI__builtin_ia32_scatterdiv8sf: 4096 case X86::BI__builtin_ia32_scatterdiv8si: 4097 case X86::BI__builtin_ia32_scattersiv2df: 4098 case X86::BI__builtin_ia32_scattersiv2di: 4099 case X86::BI__builtin_ia32_scattersiv4df: 4100 case X86::BI__builtin_ia32_scattersiv4di: 4101 case X86::BI__builtin_ia32_scattersiv4sf: 4102 case X86::BI__builtin_ia32_scattersiv4si: 4103 case X86::BI__builtin_ia32_scattersiv8sf: 4104 case X86::BI__builtin_ia32_scattersiv8si: 4105 case X86::BI__builtin_ia32_scattersiv8df: 4106 case X86::BI__builtin_ia32_scattersiv16sf: 4107 case X86::BI__builtin_ia32_scatterdiv8df: 4108 case X86::BI__builtin_ia32_scatterdiv16sf: 4109 case X86::BI__builtin_ia32_scattersiv8di: 4110 case X86::BI__builtin_ia32_scattersiv16si: 4111 case X86::BI__builtin_ia32_scatterdiv8di: 4112 case X86::BI__builtin_ia32_scatterdiv16si: 4113 ArgNum = 4; 4114 break; 4115 } 4116 4117 llvm::APSInt Result; 4118 4119 // We can't check the value of a dependent argument. 4120 Expr *Arg = TheCall->getArg(ArgNum); 4121 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4122 return false; 4123 4124 // Check constant-ness first. 4125 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4126 return true; 4127 4128 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4129 return false; 4130 4131 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4132 << Arg->getSourceRange(); 4133 } 4134 4135 enum { TileRegLow = 0, TileRegHigh = 7 }; 4136 4137 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4138 ArrayRef<int> ArgNums) { 4139 for (int ArgNum : ArgNums) { 4140 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4141 return true; 4142 } 4143 return false; 4144 } 4145 4146 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4147 ArrayRef<int> ArgNums) { 4148 // Because the max number of tile register is TileRegHigh + 1, so here we use 4149 // each bit to represent the usage of them in bitset. 4150 std::bitset<TileRegHigh + 1> ArgValues; 4151 for (int ArgNum : ArgNums) { 4152 Expr *Arg = TheCall->getArg(ArgNum); 4153 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4154 continue; 4155 4156 llvm::APSInt Result; 4157 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4158 return true; 4159 int ArgExtValue = Result.getExtValue(); 4160 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4161 "Incorrect tile register num."); 4162 if (ArgValues.test(ArgExtValue)) 4163 return Diag(TheCall->getBeginLoc(), 4164 diag::err_x86_builtin_tile_arg_duplicate) 4165 << TheCall->getArg(ArgNum)->getSourceRange(); 4166 ArgValues.set(ArgExtValue); 4167 } 4168 return false; 4169 } 4170 4171 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4172 ArrayRef<int> ArgNums) { 4173 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4174 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4175 } 4176 4177 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4178 switch (BuiltinID) { 4179 default: 4180 return false; 4181 case X86::BI__builtin_ia32_tileloadd64: 4182 case X86::BI__builtin_ia32_tileloaddt164: 4183 case X86::BI__builtin_ia32_tilestored64: 4184 case X86::BI__builtin_ia32_tilezero: 4185 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4186 case X86::BI__builtin_ia32_tdpbssd: 4187 case X86::BI__builtin_ia32_tdpbsud: 4188 case X86::BI__builtin_ia32_tdpbusd: 4189 case X86::BI__builtin_ia32_tdpbuud: 4190 case X86::BI__builtin_ia32_tdpbf16ps: 4191 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4192 } 4193 } 4194 static bool isX86_32Builtin(unsigned BuiltinID) { 4195 // These builtins only work on x86-32 targets. 4196 switch (BuiltinID) { 4197 case X86::BI__builtin_ia32_readeflags_u32: 4198 case X86::BI__builtin_ia32_writeeflags_u32: 4199 return true; 4200 } 4201 4202 return false; 4203 } 4204 4205 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4206 CallExpr *TheCall) { 4207 if (BuiltinID == X86::BI__builtin_cpu_supports) 4208 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4209 4210 if (BuiltinID == X86::BI__builtin_cpu_is) 4211 return SemaBuiltinCpuIs(*this, TI, TheCall); 4212 4213 // Check for 32-bit only builtins on a 64-bit target. 4214 const llvm::Triple &TT = TI.getTriple(); 4215 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4216 return Diag(TheCall->getCallee()->getBeginLoc(), 4217 diag::err_32_bit_builtin_64_bit_tgt); 4218 4219 // If the intrinsic has rounding or SAE make sure its valid. 4220 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4221 return true; 4222 4223 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4224 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4225 return true; 4226 4227 // If the intrinsic has a tile arguments, make sure they are valid. 4228 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4229 return true; 4230 4231 // For intrinsics which take an immediate value as part of the instruction, 4232 // range check them here. 4233 int i = 0, l = 0, u = 0; 4234 switch (BuiltinID) { 4235 default: 4236 return false; 4237 case X86::BI__builtin_ia32_vec_ext_v2si: 4238 case X86::BI__builtin_ia32_vec_ext_v2di: 4239 case X86::BI__builtin_ia32_vextractf128_pd256: 4240 case X86::BI__builtin_ia32_vextractf128_ps256: 4241 case X86::BI__builtin_ia32_vextractf128_si256: 4242 case X86::BI__builtin_ia32_extract128i256: 4243 case X86::BI__builtin_ia32_extractf64x4_mask: 4244 case X86::BI__builtin_ia32_extracti64x4_mask: 4245 case X86::BI__builtin_ia32_extractf32x8_mask: 4246 case X86::BI__builtin_ia32_extracti32x8_mask: 4247 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4248 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4249 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4250 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4251 i = 1; l = 0; u = 1; 4252 break; 4253 case X86::BI__builtin_ia32_vec_set_v2di: 4254 case X86::BI__builtin_ia32_vinsertf128_pd256: 4255 case X86::BI__builtin_ia32_vinsertf128_ps256: 4256 case X86::BI__builtin_ia32_vinsertf128_si256: 4257 case X86::BI__builtin_ia32_insert128i256: 4258 case X86::BI__builtin_ia32_insertf32x8: 4259 case X86::BI__builtin_ia32_inserti32x8: 4260 case X86::BI__builtin_ia32_insertf64x4: 4261 case X86::BI__builtin_ia32_inserti64x4: 4262 case X86::BI__builtin_ia32_insertf64x2_256: 4263 case X86::BI__builtin_ia32_inserti64x2_256: 4264 case X86::BI__builtin_ia32_insertf32x4_256: 4265 case X86::BI__builtin_ia32_inserti32x4_256: 4266 i = 2; l = 0; u = 1; 4267 break; 4268 case X86::BI__builtin_ia32_vpermilpd: 4269 case X86::BI__builtin_ia32_vec_ext_v4hi: 4270 case X86::BI__builtin_ia32_vec_ext_v4si: 4271 case X86::BI__builtin_ia32_vec_ext_v4sf: 4272 case X86::BI__builtin_ia32_vec_ext_v4di: 4273 case X86::BI__builtin_ia32_extractf32x4_mask: 4274 case X86::BI__builtin_ia32_extracti32x4_mask: 4275 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4276 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4277 i = 1; l = 0; u = 3; 4278 break; 4279 case X86::BI_mm_prefetch: 4280 case X86::BI__builtin_ia32_vec_ext_v8hi: 4281 case X86::BI__builtin_ia32_vec_ext_v8si: 4282 i = 1; l = 0; u = 7; 4283 break; 4284 case X86::BI__builtin_ia32_sha1rnds4: 4285 case X86::BI__builtin_ia32_blendpd: 4286 case X86::BI__builtin_ia32_shufpd: 4287 case X86::BI__builtin_ia32_vec_set_v4hi: 4288 case X86::BI__builtin_ia32_vec_set_v4si: 4289 case X86::BI__builtin_ia32_vec_set_v4di: 4290 case X86::BI__builtin_ia32_shuf_f32x4_256: 4291 case X86::BI__builtin_ia32_shuf_f64x2_256: 4292 case X86::BI__builtin_ia32_shuf_i32x4_256: 4293 case X86::BI__builtin_ia32_shuf_i64x2_256: 4294 case X86::BI__builtin_ia32_insertf64x2_512: 4295 case X86::BI__builtin_ia32_inserti64x2_512: 4296 case X86::BI__builtin_ia32_insertf32x4: 4297 case X86::BI__builtin_ia32_inserti32x4: 4298 i = 2; l = 0; u = 3; 4299 break; 4300 case X86::BI__builtin_ia32_vpermil2pd: 4301 case X86::BI__builtin_ia32_vpermil2pd256: 4302 case X86::BI__builtin_ia32_vpermil2ps: 4303 case X86::BI__builtin_ia32_vpermil2ps256: 4304 i = 3; l = 0; u = 3; 4305 break; 4306 case X86::BI__builtin_ia32_cmpb128_mask: 4307 case X86::BI__builtin_ia32_cmpw128_mask: 4308 case X86::BI__builtin_ia32_cmpd128_mask: 4309 case X86::BI__builtin_ia32_cmpq128_mask: 4310 case X86::BI__builtin_ia32_cmpb256_mask: 4311 case X86::BI__builtin_ia32_cmpw256_mask: 4312 case X86::BI__builtin_ia32_cmpd256_mask: 4313 case X86::BI__builtin_ia32_cmpq256_mask: 4314 case X86::BI__builtin_ia32_cmpb512_mask: 4315 case X86::BI__builtin_ia32_cmpw512_mask: 4316 case X86::BI__builtin_ia32_cmpd512_mask: 4317 case X86::BI__builtin_ia32_cmpq512_mask: 4318 case X86::BI__builtin_ia32_ucmpb128_mask: 4319 case X86::BI__builtin_ia32_ucmpw128_mask: 4320 case X86::BI__builtin_ia32_ucmpd128_mask: 4321 case X86::BI__builtin_ia32_ucmpq128_mask: 4322 case X86::BI__builtin_ia32_ucmpb256_mask: 4323 case X86::BI__builtin_ia32_ucmpw256_mask: 4324 case X86::BI__builtin_ia32_ucmpd256_mask: 4325 case X86::BI__builtin_ia32_ucmpq256_mask: 4326 case X86::BI__builtin_ia32_ucmpb512_mask: 4327 case X86::BI__builtin_ia32_ucmpw512_mask: 4328 case X86::BI__builtin_ia32_ucmpd512_mask: 4329 case X86::BI__builtin_ia32_ucmpq512_mask: 4330 case X86::BI__builtin_ia32_vpcomub: 4331 case X86::BI__builtin_ia32_vpcomuw: 4332 case X86::BI__builtin_ia32_vpcomud: 4333 case X86::BI__builtin_ia32_vpcomuq: 4334 case X86::BI__builtin_ia32_vpcomb: 4335 case X86::BI__builtin_ia32_vpcomw: 4336 case X86::BI__builtin_ia32_vpcomd: 4337 case X86::BI__builtin_ia32_vpcomq: 4338 case X86::BI__builtin_ia32_vec_set_v8hi: 4339 case X86::BI__builtin_ia32_vec_set_v8si: 4340 i = 2; l = 0; u = 7; 4341 break; 4342 case X86::BI__builtin_ia32_vpermilpd256: 4343 case X86::BI__builtin_ia32_roundps: 4344 case X86::BI__builtin_ia32_roundpd: 4345 case X86::BI__builtin_ia32_roundps256: 4346 case X86::BI__builtin_ia32_roundpd256: 4347 case X86::BI__builtin_ia32_getmantpd128_mask: 4348 case X86::BI__builtin_ia32_getmantpd256_mask: 4349 case X86::BI__builtin_ia32_getmantps128_mask: 4350 case X86::BI__builtin_ia32_getmantps256_mask: 4351 case X86::BI__builtin_ia32_getmantpd512_mask: 4352 case X86::BI__builtin_ia32_getmantps512_mask: 4353 case X86::BI__builtin_ia32_vec_ext_v16qi: 4354 case X86::BI__builtin_ia32_vec_ext_v16hi: 4355 i = 1; l = 0; u = 15; 4356 break; 4357 case X86::BI__builtin_ia32_pblendd128: 4358 case X86::BI__builtin_ia32_blendps: 4359 case X86::BI__builtin_ia32_blendpd256: 4360 case X86::BI__builtin_ia32_shufpd256: 4361 case X86::BI__builtin_ia32_roundss: 4362 case X86::BI__builtin_ia32_roundsd: 4363 case X86::BI__builtin_ia32_rangepd128_mask: 4364 case X86::BI__builtin_ia32_rangepd256_mask: 4365 case X86::BI__builtin_ia32_rangepd512_mask: 4366 case X86::BI__builtin_ia32_rangeps128_mask: 4367 case X86::BI__builtin_ia32_rangeps256_mask: 4368 case X86::BI__builtin_ia32_rangeps512_mask: 4369 case X86::BI__builtin_ia32_getmantsd_round_mask: 4370 case X86::BI__builtin_ia32_getmantss_round_mask: 4371 case X86::BI__builtin_ia32_vec_set_v16qi: 4372 case X86::BI__builtin_ia32_vec_set_v16hi: 4373 i = 2; l = 0; u = 15; 4374 break; 4375 case X86::BI__builtin_ia32_vec_ext_v32qi: 4376 i = 1; l = 0; u = 31; 4377 break; 4378 case X86::BI__builtin_ia32_cmpps: 4379 case X86::BI__builtin_ia32_cmpss: 4380 case X86::BI__builtin_ia32_cmppd: 4381 case X86::BI__builtin_ia32_cmpsd: 4382 case X86::BI__builtin_ia32_cmpps256: 4383 case X86::BI__builtin_ia32_cmppd256: 4384 case X86::BI__builtin_ia32_cmpps128_mask: 4385 case X86::BI__builtin_ia32_cmppd128_mask: 4386 case X86::BI__builtin_ia32_cmpps256_mask: 4387 case X86::BI__builtin_ia32_cmppd256_mask: 4388 case X86::BI__builtin_ia32_cmpps512_mask: 4389 case X86::BI__builtin_ia32_cmppd512_mask: 4390 case X86::BI__builtin_ia32_cmpsd_mask: 4391 case X86::BI__builtin_ia32_cmpss_mask: 4392 case X86::BI__builtin_ia32_vec_set_v32qi: 4393 i = 2; l = 0; u = 31; 4394 break; 4395 case X86::BI__builtin_ia32_permdf256: 4396 case X86::BI__builtin_ia32_permdi256: 4397 case X86::BI__builtin_ia32_permdf512: 4398 case X86::BI__builtin_ia32_permdi512: 4399 case X86::BI__builtin_ia32_vpermilps: 4400 case X86::BI__builtin_ia32_vpermilps256: 4401 case X86::BI__builtin_ia32_vpermilpd512: 4402 case X86::BI__builtin_ia32_vpermilps512: 4403 case X86::BI__builtin_ia32_pshufd: 4404 case X86::BI__builtin_ia32_pshufd256: 4405 case X86::BI__builtin_ia32_pshufd512: 4406 case X86::BI__builtin_ia32_pshufhw: 4407 case X86::BI__builtin_ia32_pshufhw256: 4408 case X86::BI__builtin_ia32_pshufhw512: 4409 case X86::BI__builtin_ia32_pshuflw: 4410 case X86::BI__builtin_ia32_pshuflw256: 4411 case X86::BI__builtin_ia32_pshuflw512: 4412 case X86::BI__builtin_ia32_vcvtps2ph: 4413 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4414 case X86::BI__builtin_ia32_vcvtps2ph256: 4415 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4416 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4417 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4418 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4419 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4420 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4421 case X86::BI__builtin_ia32_rndscaleps_mask: 4422 case X86::BI__builtin_ia32_rndscalepd_mask: 4423 case X86::BI__builtin_ia32_reducepd128_mask: 4424 case X86::BI__builtin_ia32_reducepd256_mask: 4425 case X86::BI__builtin_ia32_reducepd512_mask: 4426 case X86::BI__builtin_ia32_reduceps128_mask: 4427 case X86::BI__builtin_ia32_reduceps256_mask: 4428 case X86::BI__builtin_ia32_reduceps512_mask: 4429 case X86::BI__builtin_ia32_prold512: 4430 case X86::BI__builtin_ia32_prolq512: 4431 case X86::BI__builtin_ia32_prold128: 4432 case X86::BI__builtin_ia32_prold256: 4433 case X86::BI__builtin_ia32_prolq128: 4434 case X86::BI__builtin_ia32_prolq256: 4435 case X86::BI__builtin_ia32_prord512: 4436 case X86::BI__builtin_ia32_prorq512: 4437 case X86::BI__builtin_ia32_prord128: 4438 case X86::BI__builtin_ia32_prord256: 4439 case X86::BI__builtin_ia32_prorq128: 4440 case X86::BI__builtin_ia32_prorq256: 4441 case X86::BI__builtin_ia32_fpclasspd128_mask: 4442 case X86::BI__builtin_ia32_fpclasspd256_mask: 4443 case X86::BI__builtin_ia32_fpclassps128_mask: 4444 case X86::BI__builtin_ia32_fpclassps256_mask: 4445 case X86::BI__builtin_ia32_fpclassps512_mask: 4446 case X86::BI__builtin_ia32_fpclasspd512_mask: 4447 case X86::BI__builtin_ia32_fpclasssd_mask: 4448 case X86::BI__builtin_ia32_fpclassss_mask: 4449 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4450 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4451 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4452 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4453 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4454 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4455 case X86::BI__builtin_ia32_kshiftliqi: 4456 case X86::BI__builtin_ia32_kshiftlihi: 4457 case X86::BI__builtin_ia32_kshiftlisi: 4458 case X86::BI__builtin_ia32_kshiftlidi: 4459 case X86::BI__builtin_ia32_kshiftriqi: 4460 case X86::BI__builtin_ia32_kshiftrihi: 4461 case X86::BI__builtin_ia32_kshiftrisi: 4462 case X86::BI__builtin_ia32_kshiftridi: 4463 i = 1; l = 0; u = 255; 4464 break; 4465 case X86::BI__builtin_ia32_vperm2f128_pd256: 4466 case X86::BI__builtin_ia32_vperm2f128_ps256: 4467 case X86::BI__builtin_ia32_vperm2f128_si256: 4468 case X86::BI__builtin_ia32_permti256: 4469 case X86::BI__builtin_ia32_pblendw128: 4470 case X86::BI__builtin_ia32_pblendw256: 4471 case X86::BI__builtin_ia32_blendps256: 4472 case X86::BI__builtin_ia32_pblendd256: 4473 case X86::BI__builtin_ia32_palignr128: 4474 case X86::BI__builtin_ia32_palignr256: 4475 case X86::BI__builtin_ia32_palignr512: 4476 case X86::BI__builtin_ia32_alignq512: 4477 case X86::BI__builtin_ia32_alignd512: 4478 case X86::BI__builtin_ia32_alignd128: 4479 case X86::BI__builtin_ia32_alignd256: 4480 case X86::BI__builtin_ia32_alignq128: 4481 case X86::BI__builtin_ia32_alignq256: 4482 case X86::BI__builtin_ia32_vcomisd: 4483 case X86::BI__builtin_ia32_vcomiss: 4484 case X86::BI__builtin_ia32_shuf_f32x4: 4485 case X86::BI__builtin_ia32_shuf_f64x2: 4486 case X86::BI__builtin_ia32_shuf_i32x4: 4487 case X86::BI__builtin_ia32_shuf_i64x2: 4488 case X86::BI__builtin_ia32_shufpd512: 4489 case X86::BI__builtin_ia32_shufps: 4490 case X86::BI__builtin_ia32_shufps256: 4491 case X86::BI__builtin_ia32_shufps512: 4492 case X86::BI__builtin_ia32_dbpsadbw128: 4493 case X86::BI__builtin_ia32_dbpsadbw256: 4494 case X86::BI__builtin_ia32_dbpsadbw512: 4495 case X86::BI__builtin_ia32_vpshldd128: 4496 case X86::BI__builtin_ia32_vpshldd256: 4497 case X86::BI__builtin_ia32_vpshldd512: 4498 case X86::BI__builtin_ia32_vpshldq128: 4499 case X86::BI__builtin_ia32_vpshldq256: 4500 case X86::BI__builtin_ia32_vpshldq512: 4501 case X86::BI__builtin_ia32_vpshldw128: 4502 case X86::BI__builtin_ia32_vpshldw256: 4503 case X86::BI__builtin_ia32_vpshldw512: 4504 case X86::BI__builtin_ia32_vpshrdd128: 4505 case X86::BI__builtin_ia32_vpshrdd256: 4506 case X86::BI__builtin_ia32_vpshrdd512: 4507 case X86::BI__builtin_ia32_vpshrdq128: 4508 case X86::BI__builtin_ia32_vpshrdq256: 4509 case X86::BI__builtin_ia32_vpshrdq512: 4510 case X86::BI__builtin_ia32_vpshrdw128: 4511 case X86::BI__builtin_ia32_vpshrdw256: 4512 case X86::BI__builtin_ia32_vpshrdw512: 4513 i = 2; l = 0; u = 255; 4514 break; 4515 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4516 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4517 case X86::BI__builtin_ia32_fixupimmps512_mask: 4518 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4519 case X86::BI__builtin_ia32_fixupimmsd_mask: 4520 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4521 case X86::BI__builtin_ia32_fixupimmss_mask: 4522 case X86::BI__builtin_ia32_fixupimmss_maskz: 4523 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4524 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4525 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4526 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4527 case X86::BI__builtin_ia32_fixupimmps128_mask: 4528 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4529 case X86::BI__builtin_ia32_fixupimmps256_mask: 4530 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4531 case X86::BI__builtin_ia32_pternlogd512_mask: 4532 case X86::BI__builtin_ia32_pternlogd512_maskz: 4533 case X86::BI__builtin_ia32_pternlogq512_mask: 4534 case X86::BI__builtin_ia32_pternlogq512_maskz: 4535 case X86::BI__builtin_ia32_pternlogd128_mask: 4536 case X86::BI__builtin_ia32_pternlogd128_maskz: 4537 case X86::BI__builtin_ia32_pternlogd256_mask: 4538 case X86::BI__builtin_ia32_pternlogd256_maskz: 4539 case X86::BI__builtin_ia32_pternlogq128_mask: 4540 case X86::BI__builtin_ia32_pternlogq128_maskz: 4541 case X86::BI__builtin_ia32_pternlogq256_mask: 4542 case X86::BI__builtin_ia32_pternlogq256_maskz: 4543 i = 3; l = 0; u = 255; 4544 break; 4545 case X86::BI__builtin_ia32_gatherpfdpd: 4546 case X86::BI__builtin_ia32_gatherpfdps: 4547 case X86::BI__builtin_ia32_gatherpfqpd: 4548 case X86::BI__builtin_ia32_gatherpfqps: 4549 case X86::BI__builtin_ia32_scatterpfdpd: 4550 case X86::BI__builtin_ia32_scatterpfdps: 4551 case X86::BI__builtin_ia32_scatterpfqpd: 4552 case X86::BI__builtin_ia32_scatterpfqps: 4553 i = 4; l = 2; u = 3; 4554 break; 4555 case X86::BI__builtin_ia32_reducesd_mask: 4556 case X86::BI__builtin_ia32_reducess_mask: 4557 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4558 case X86::BI__builtin_ia32_rndscaless_round_mask: 4559 i = 4; l = 0; u = 255; 4560 break; 4561 } 4562 4563 // Note that we don't force a hard error on the range check here, allowing 4564 // template-generated or macro-generated dead code to potentially have out-of- 4565 // range values. These need to code generate, but don't need to necessarily 4566 // make any sense. We use a warning that defaults to an error. 4567 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4568 } 4569 4570 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4571 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4572 /// Returns true when the format fits the function and the FormatStringInfo has 4573 /// been populated. 4574 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4575 FormatStringInfo *FSI) { 4576 FSI->HasVAListArg = Format->getFirstArg() == 0; 4577 FSI->FormatIdx = Format->getFormatIdx() - 1; 4578 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4579 4580 // The way the format attribute works in GCC, the implicit this argument 4581 // of member functions is counted. However, it doesn't appear in our own 4582 // lists, so decrement format_idx in that case. 4583 if (IsCXXMember) { 4584 if(FSI->FormatIdx == 0) 4585 return false; 4586 --FSI->FormatIdx; 4587 if (FSI->FirstDataArg != 0) 4588 --FSI->FirstDataArg; 4589 } 4590 return true; 4591 } 4592 4593 /// Checks if a the given expression evaluates to null. 4594 /// 4595 /// Returns true if the value evaluates to null. 4596 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4597 // If the expression has non-null type, it doesn't evaluate to null. 4598 if (auto nullability 4599 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4600 if (*nullability == NullabilityKind::NonNull) 4601 return false; 4602 } 4603 4604 // As a special case, transparent unions initialized with zero are 4605 // considered null for the purposes of the nonnull attribute. 4606 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4607 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4608 if (const CompoundLiteralExpr *CLE = 4609 dyn_cast<CompoundLiteralExpr>(Expr)) 4610 if (const InitListExpr *ILE = 4611 dyn_cast<InitListExpr>(CLE->getInitializer())) 4612 Expr = ILE->getInit(0); 4613 } 4614 4615 bool Result; 4616 return (!Expr->isValueDependent() && 4617 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4618 !Result); 4619 } 4620 4621 static void CheckNonNullArgument(Sema &S, 4622 const Expr *ArgExpr, 4623 SourceLocation CallSiteLoc) { 4624 if (CheckNonNullExpr(S, ArgExpr)) 4625 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4626 S.PDiag(diag::warn_null_arg) 4627 << ArgExpr->getSourceRange()); 4628 } 4629 4630 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4631 FormatStringInfo FSI; 4632 if ((GetFormatStringType(Format) == FST_NSString) && 4633 getFormatStringInfo(Format, false, &FSI)) { 4634 Idx = FSI.FormatIdx; 4635 return true; 4636 } 4637 return false; 4638 } 4639 4640 /// Diagnose use of %s directive in an NSString which is being passed 4641 /// as formatting string to formatting method. 4642 static void 4643 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4644 const NamedDecl *FDecl, 4645 Expr **Args, 4646 unsigned NumArgs) { 4647 unsigned Idx = 0; 4648 bool Format = false; 4649 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4650 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4651 Idx = 2; 4652 Format = true; 4653 } 4654 else 4655 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4656 if (S.GetFormatNSStringIdx(I, Idx)) { 4657 Format = true; 4658 break; 4659 } 4660 } 4661 if (!Format || NumArgs <= Idx) 4662 return; 4663 const Expr *FormatExpr = Args[Idx]; 4664 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4665 FormatExpr = CSCE->getSubExpr(); 4666 const StringLiteral *FormatString; 4667 if (const ObjCStringLiteral *OSL = 4668 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4669 FormatString = OSL->getString(); 4670 else 4671 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4672 if (!FormatString) 4673 return; 4674 if (S.FormatStringHasSArg(FormatString)) { 4675 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4676 << "%s" << 1 << 1; 4677 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4678 << FDecl->getDeclName(); 4679 } 4680 } 4681 4682 /// Determine whether the given type has a non-null nullability annotation. 4683 static bool isNonNullType(ASTContext &ctx, QualType type) { 4684 if (auto nullability = type->getNullability(ctx)) 4685 return *nullability == NullabilityKind::NonNull; 4686 4687 return false; 4688 } 4689 4690 static void CheckNonNullArguments(Sema &S, 4691 const NamedDecl *FDecl, 4692 const FunctionProtoType *Proto, 4693 ArrayRef<const Expr *> Args, 4694 SourceLocation CallSiteLoc) { 4695 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4696 4697 // Already checked by by constant evaluator. 4698 if (S.isConstantEvaluated()) 4699 return; 4700 // Check the attributes attached to the method/function itself. 4701 llvm::SmallBitVector NonNullArgs; 4702 if (FDecl) { 4703 // Handle the nonnull attribute on the function/method declaration itself. 4704 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4705 if (!NonNull->args_size()) { 4706 // Easy case: all pointer arguments are nonnull. 4707 for (const auto *Arg : Args) 4708 if (S.isValidPointerAttrType(Arg->getType())) 4709 CheckNonNullArgument(S, Arg, CallSiteLoc); 4710 return; 4711 } 4712 4713 for (const ParamIdx &Idx : NonNull->args()) { 4714 unsigned IdxAST = Idx.getASTIndex(); 4715 if (IdxAST >= Args.size()) 4716 continue; 4717 if (NonNullArgs.empty()) 4718 NonNullArgs.resize(Args.size()); 4719 NonNullArgs.set(IdxAST); 4720 } 4721 } 4722 } 4723 4724 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4725 // Handle the nonnull attribute on the parameters of the 4726 // function/method. 4727 ArrayRef<ParmVarDecl*> parms; 4728 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4729 parms = FD->parameters(); 4730 else 4731 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4732 4733 unsigned ParamIndex = 0; 4734 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4735 I != E; ++I, ++ParamIndex) { 4736 const ParmVarDecl *PVD = *I; 4737 if (PVD->hasAttr<NonNullAttr>() || 4738 isNonNullType(S.Context, PVD->getType())) { 4739 if (NonNullArgs.empty()) 4740 NonNullArgs.resize(Args.size()); 4741 4742 NonNullArgs.set(ParamIndex); 4743 } 4744 } 4745 } else { 4746 // If we have a non-function, non-method declaration but no 4747 // function prototype, try to dig out the function prototype. 4748 if (!Proto) { 4749 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4750 QualType type = VD->getType().getNonReferenceType(); 4751 if (auto pointerType = type->getAs<PointerType>()) 4752 type = pointerType->getPointeeType(); 4753 else if (auto blockType = type->getAs<BlockPointerType>()) 4754 type = blockType->getPointeeType(); 4755 // FIXME: data member pointers? 4756 4757 // Dig out the function prototype, if there is one. 4758 Proto = type->getAs<FunctionProtoType>(); 4759 } 4760 } 4761 4762 // Fill in non-null argument information from the nullability 4763 // information on the parameter types (if we have them). 4764 if (Proto) { 4765 unsigned Index = 0; 4766 for (auto paramType : Proto->getParamTypes()) { 4767 if (isNonNullType(S.Context, paramType)) { 4768 if (NonNullArgs.empty()) 4769 NonNullArgs.resize(Args.size()); 4770 4771 NonNullArgs.set(Index); 4772 } 4773 4774 ++Index; 4775 } 4776 } 4777 } 4778 4779 // Check for non-null arguments. 4780 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4781 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4782 if (NonNullArgs[ArgIndex]) 4783 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4784 } 4785 } 4786 4787 /// Warn if a pointer or reference argument passed to a function points to an 4788 /// object that is less aligned than the parameter. This can happen when 4789 /// creating a typedef with a lower alignment than the original type and then 4790 /// calling functions defined in terms of the original type. 4791 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4792 StringRef ParamName, QualType ArgTy, 4793 QualType ParamTy) { 4794 4795 // If a function accepts a pointer or reference type 4796 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4797 return; 4798 4799 // If the parameter is a pointer type, get the pointee type for the 4800 // argument too. If the parameter is a reference type, don't try to get 4801 // the pointee type for the argument. 4802 if (ParamTy->isPointerType()) 4803 ArgTy = ArgTy->getPointeeType(); 4804 4805 // Remove reference or pointer 4806 ParamTy = ParamTy->getPointeeType(); 4807 4808 // Find expected alignment, and the actual alignment of the passed object. 4809 // getTypeAlignInChars requires complete types 4810 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 4811 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 4812 ArgTy->isUndeducedType()) 4813 return; 4814 4815 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4816 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4817 4818 // If the argument is less aligned than the parameter, there is a 4819 // potential alignment issue. 4820 if (ArgAlign < ParamAlign) 4821 Diag(Loc, diag::warn_param_mismatched_alignment) 4822 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4823 << ParamName << FDecl; 4824 } 4825 4826 /// Handles the checks for format strings, non-POD arguments to vararg 4827 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4828 /// attributes. 4829 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4830 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4831 bool IsMemberFunction, SourceLocation Loc, 4832 SourceRange Range, VariadicCallType CallType) { 4833 // FIXME: We should check as much as we can in the template definition. 4834 if (CurContext->isDependentContext()) 4835 return; 4836 4837 // Printf and scanf checking. 4838 llvm::SmallBitVector CheckedVarArgs; 4839 if (FDecl) { 4840 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4841 // Only create vector if there are format attributes. 4842 CheckedVarArgs.resize(Args.size()); 4843 4844 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4845 CheckedVarArgs); 4846 } 4847 } 4848 4849 // Refuse POD arguments that weren't caught by the format string 4850 // checks above. 4851 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4852 if (CallType != VariadicDoesNotApply && 4853 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4854 unsigned NumParams = Proto ? Proto->getNumParams() 4855 : FDecl && isa<FunctionDecl>(FDecl) 4856 ? cast<FunctionDecl>(FDecl)->getNumParams() 4857 : FDecl && isa<ObjCMethodDecl>(FDecl) 4858 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4859 : 0; 4860 4861 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4862 // Args[ArgIdx] can be null in malformed code. 4863 if (const Expr *Arg = Args[ArgIdx]) { 4864 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4865 checkVariadicArgument(Arg, CallType); 4866 } 4867 } 4868 } 4869 4870 if (FDecl || Proto) { 4871 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4872 4873 // Type safety checking. 4874 if (FDecl) { 4875 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4876 CheckArgumentWithTypeTag(I, Args, Loc); 4877 } 4878 } 4879 4880 // Check that passed arguments match the alignment of original arguments. 4881 // Try to get the missing prototype from the declaration. 4882 if (!Proto && FDecl) { 4883 const auto *FT = FDecl->getFunctionType(); 4884 if (isa_and_nonnull<FunctionProtoType>(FT)) 4885 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 4886 } 4887 if (Proto) { 4888 // For variadic functions, we may have more args than parameters. 4889 // For some K&R functions, we may have less args than parameters. 4890 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 4891 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 4892 // Args[ArgIdx] can be null in malformed code. 4893 if (const Expr *Arg = Args[ArgIdx]) { 4894 if (Arg->containsErrors()) 4895 continue; 4896 4897 QualType ParamTy = Proto->getParamType(ArgIdx); 4898 QualType ArgTy = Arg->getType(); 4899 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 4900 ArgTy, ParamTy); 4901 } 4902 } 4903 } 4904 4905 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4906 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4907 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4908 if (!Arg->isValueDependent()) { 4909 Expr::EvalResult Align; 4910 if (Arg->EvaluateAsInt(Align, Context)) { 4911 const llvm::APSInt &I = Align.Val.getInt(); 4912 if (!I.isPowerOf2()) 4913 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4914 << Arg->getSourceRange(); 4915 4916 if (I > Sema::MaximumAlignment) 4917 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4918 << Arg->getSourceRange() << Sema::MaximumAlignment; 4919 } 4920 } 4921 } 4922 4923 if (FD) 4924 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4925 } 4926 4927 /// CheckConstructorCall - Check a constructor call for correctness and safety 4928 /// properties not enforced by the C type system. 4929 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 4930 ArrayRef<const Expr *> Args, 4931 const FunctionProtoType *Proto, 4932 SourceLocation Loc) { 4933 VariadicCallType CallType = 4934 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4935 4936 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 4937 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 4938 Context.getPointerType(Ctor->getThisObjectType())); 4939 4940 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4941 Loc, SourceRange(), CallType); 4942 } 4943 4944 /// CheckFunctionCall - Check a direct function call for various correctness 4945 /// and safety properties not strictly enforced by the C type system. 4946 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4947 const FunctionProtoType *Proto) { 4948 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4949 isa<CXXMethodDecl>(FDecl); 4950 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4951 IsMemberOperatorCall; 4952 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4953 TheCall->getCallee()); 4954 Expr** Args = TheCall->getArgs(); 4955 unsigned NumArgs = TheCall->getNumArgs(); 4956 4957 Expr *ImplicitThis = nullptr; 4958 if (IsMemberOperatorCall) { 4959 // If this is a call to a member operator, hide the first argument 4960 // from checkCall. 4961 // FIXME: Our choice of AST representation here is less than ideal. 4962 ImplicitThis = Args[0]; 4963 ++Args; 4964 --NumArgs; 4965 } else if (IsMemberFunction) 4966 ImplicitThis = 4967 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4968 4969 if (ImplicitThis) { 4970 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 4971 // used. 4972 QualType ThisType = ImplicitThis->getType(); 4973 if (!ThisType->isPointerType()) { 4974 assert(!ThisType->isReferenceType()); 4975 ThisType = Context.getPointerType(ThisType); 4976 } 4977 4978 QualType ThisTypeFromDecl = 4979 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 4980 4981 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 4982 ThisTypeFromDecl); 4983 } 4984 4985 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4986 IsMemberFunction, TheCall->getRParenLoc(), 4987 TheCall->getCallee()->getSourceRange(), CallType); 4988 4989 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4990 // None of the checks below are needed for functions that don't have 4991 // simple names (e.g., C++ conversion functions). 4992 if (!FnInfo) 4993 return false; 4994 4995 CheckTCBEnforcement(TheCall, FDecl); 4996 4997 CheckAbsoluteValueFunction(TheCall, FDecl); 4998 CheckMaxUnsignedZero(TheCall, FDecl); 4999 5000 if (getLangOpts().ObjC) 5001 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5002 5003 unsigned CMId = FDecl->getMemoryFunctionKind(); 5004 5005 // Handle memory setting and copying functions. 5006 switch (CMId) { 5007 case 0: 5008 return false; 5009 case Builtin::BIstrlcpy: // fallthrough 5010 case Builtin::BIstrlcat: 5011 CheckStrlcpycatArguments(TheCall, FnInfo); 5012 break; 5013 case Builtin::BIstrncat: 5014 CheckStrncatArguments(TheCall, FnInfo); 5015 break; 5016 case Builtin::BIfree: 5017 CheckFreeArguments(TheCall); 5018 break; 5019 default: 5020 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5021 } 5022 5023 return false; 5024 } 5025 5026 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5027 ArrayRef<const Expr *> Args) { 5028 VariadicCallType CallType = 5029 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5030 5031 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5032 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5033 CallType); 5034 5035 return false; 5036 } 5037 5038 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5039 const FunctionProtoType *Proto) { 5040 QualType Ty; 5041 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5042 Ty = V->getType().getNonReferenceType(); 5043 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5044 Ty = F->getType().getNonReferenceType(); 5045 else 5046 return false; 5047 5048 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5049 !Ty->isFunctionProtoType()) 5050 return false; 5051 5052 VariadicCallType CallType; 5053 if (!Proto || !Proto->isVariadic()) { 5054 CallType = VariadicDoesNotApply; 5055 } else if (Ty->isBlockPointerType()) { 5056 CallType = VariadicBlock; 5057 } else { // Ty->isFunctionPointerType() 5058 CallType = VariadicFunction; 5059 } 5060 5061 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5062 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5063 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5064 TheCall->getCallee()->getSourceRange(), CallType); 5065 5066 return false; 5067 } 5068 5069 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5070 /// such as function pointers returned from functions. 5071 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5072 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5073 TheCall->getCallee()); 5074 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5075 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5076 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5077 TheCall->getCallee()->getSourceRange(), CallType); 5078 5079 return false; 5080 } 5081 5082 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5083 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5084 return false; 5085 5086 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5087 switch (Op) { 5088 case AtomicExpr::AO__c11_atomic_init: 5089 case AtomicExpr::AO__opencl_atomic_init: 5090 llvm_unreachable("There is no ordering argument for an init"); 5091 5092 case AtomicExpr::AO__c11_atomic_load: 5093 case AtomicExpr::AO__opencl_atomic_load: 5094 case AtomicExpr::AO__atomic_load_n: 5095 case AtomicExpr::AO__atomic_load: 5096 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5097 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5098 5099 case AtomicExpr::AO__c11_atomic_store: 5100 case AtomicExpr::AO__opencl_atomic_store: 5101 case AtomicExpr::AO__atomic_store: 5102 case AtomicExpr::AO__atomic_store_n: 5103 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5104 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5105 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5106 5107 default: 5108 return true; 5109 } 5110 } 5111 5112 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5113 AtomicExpr::AtomicOp Op) { 5114 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5115 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5116 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5117 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5118 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5119 Op); 5120 } 5121 5122 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5123 SourceLocation RParenLoc, MultiExprArg Args, 5124 AtomicExpr::AtomicOp Op, 5125 AtomicArgumentOrder ArgOrder) { 5126 // All the non-OpenCL operations take one of the following forms. 5127 // The OpenCL operations take the __c11 forms with one extra argument for 5128 // synchronization scope. 5129 enum { 5130 // C __c11_atomic_init(A *, C) 5131 Init, 5132 5133 // C __c11_atomic_load(A *, int) 5134 Load, 5135 5136 // void __atomic_load(A *, CP, int) 5137 LoadCopy, 5138 5139 // void __atomic_store(A *, CP, int) 5140 Copy, 5141 5142 // C __c11_atomic_add(A *, M, int) 5143 Arithmetic, 5144 5145 // C __atomic_exchange_n(A *, CP, int) 5146 Xchg, 5147 5148 // void __atomic_exchange(A *, C *, CP, int) 5149 GNUXchg, 5150 5151 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5152 C11CmpXchg, 5153 5154 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5155 GNUCmpXchg 5156 } Form = Init; 5157 5158 const unsigned NumForm = GNUCmpXchg + 1; 5159 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5160 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5161 // where: 5162 // C is an appropriate type, 5163 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5164 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5165 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5166 // the int parameters are for orderings. 5167 5168 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5169 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5170 "need to update code for modified forms"); 5171 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5172 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5173 AtomicExpr::AO__atomic_load, 5174 "need to update code for modified C11 atomics"); 5175 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5176 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5177 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5178 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5179 IsOpenCL; 5180 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5181 Op == AtomicExpr::AO__atomic_store_n || 5182 Op == AtomicExpr::AO__atomic_exchange_n || 5183 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5184 bool IsAddSub = false; 5185 5186 switch (Op) { 5187 case AtomicExpr::AO__c11_atomic_init: 5188 case AtomicExpr::AO__opencl_atomic_init: 5189 Form = Init; 5190 break; 5191 5192 case AtomicExpr::AO__c11_atomic_load: 5193 case AtomicExpr::AO__opencl_atomic_load: 5194 case AtomicExpr::AO__atomic_load_n: 5195 Form = Load; 5196 break; 5197 5198 case AtomicExpr::AO__atomic_load: 5199 Form = LoadCopy; 5200 break; 5201 5202 case AtomicExpr::AO__c11_atomic_store: 5203 case AtomicExpr::AO__opencl_atomic_store: 5204 case AtomicExpr::AO__atomic_store: 5205 case AtomicExpr::AO__atomic_store_n: 5206 Form = Copy; 5207 break; 5208 5209 case AtomicExpr::AO__c11_atomic_fetch_add: 5210 case AtomicExpr::AO__c11_atomic_fetch_sub: 5211 case AtomicExpr::AO__opencl_atomic_fetch_add: 5212 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5213 case AtomicExpr::AO__atomic_fetch_add: 5214 case AtomicExpr::AO__atomic_fetch_sub: 5215 case AtomicExpr::AO__atomic_add_fetch: 5216 case AtomicExpr::AO__atomic_sub_fetch: 5217 IsAddSub = true; 5218 Form = Arithmetic; 5219 break; 5220 case AtomicExpr::AO__c11_atomic_fetch_and: 5221 case AtomicExpr::AO__c11_atomic_fetch_or: 5222 case AtomicExpr::AO__c11_atomic_fetch_xor: 5223 case AtomicExpr::AO__opencl_atomic_fetch_and: 5224 case AtomicExpr::AO__opencl_atomic_fetch_or: 5225 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5226 case AtomicExpr::AO__atomic_fetch_and: 5227 case AtomicExpr::AO__atomic_fetch_or: 5228 case AtomicExpr::AO__atomic_fetch_xor: 5229 case AtomicExpr::AO__atomic_fetch_nand: 5230 case AtomicExpr::AO__atomic_and_fetch: 5231 case AtomicExpr::AO__atomic_or_fetch: 5232 case AtomicExpr::AO__atomic_xor_fetch: 5233 case AtomicExpr::AO__atomic_nand_fetch: 5234 Form = Arithmetic; 5235 break; 5236 case AtomicExpr::AO__c11_atomic_fetch_min: 5237 case AtomicExpr::AO__c11_atomic_fetch_max: 5238 case AtomicExpr::AO__opencl_atomic_fetch_min: 5239 case AtomicExpr::AO__opencl_atomic_fetch_max: 5240 case AtomicExpr::AO__atomic_min_fetch: 5241 case AtomicExpr::AO__atomic_max_fetch: 5242 case AtomicExpr::AO__atomic_fetch_min: 5243 case AtomicExpr::AO__atomic_fetch_max: 5244 Form = Arithmetic; 5245 break; 5246 5247 case AtomicExpr::AO__c11_atomic_exchange: 5248 case AtomicExpr::AO__opencl_atomic_exchange: 5249 case AtomicExpr::AO__atomic_exchange_n: 5250 Form = Xchg; 5251 break; 5252 5253 case AtomicExpr::AO__atomic_exchange: 5254 Form = GNUXchg; 5255 break; 5256 5257 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5258 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5259 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5260 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5261 Form = C11CmpXchg; 5262 break; 5263 5264 case AtomicExpr::AO__atomic_compare_exchange: 5265 case AtomicExpr::AO__atomic_compare_exchange_n: 5266 Form = GNUCmpXchg; 5267 break; 5268 } 5269 5270 unsigned AdjustedNumArgs = NumArgs[Form]; 5271 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5272 ++AdjustedNumArgs; 5273 // Check we have the right number of arguments. 5274 if (Args.size() < AdjustedNumArgs) { 5275 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5276 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5277 << ExprRange; 5278 return ExprError(); 5279 } else if (Args.size() > AdjustedNumArgs) { 5280 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5281 diag::err_typecheck_call_too_many_args) 5282 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5283 << ExprRange; 5284 return ExprError(); 5285 } 5286 5287 // Inspect the first argument of the atomic operation. 5288 Expr *Ptr = Args[0]; 5289 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5290 if (ConvertedPtr.isInvalid()) 5291 return ExprError(); 5292 5293 Ptr = ConvertedPtr.get(); 5294 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5295 if (!pointerType) { 5296 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5297 << Ptr->getType() << Ptr->getSourceRange(); 5298 return ExprError(); 5299 } 5300 5301 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5302 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5303 QualType ValType = AtomTy; // 'C' 5304 if (IsC11) { 5305 if (!AtomTy->isAtomicType()) { 5306 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5307 << Ptr->getType() << Ptr->getSourceRange(); 5308 return ExprError(); 5309 } 5310 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5311 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5312 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5313 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5314 << Ptr->getSourceRange(); 5315 return ExprError(); 5316 } 5317 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5318 } else if (Form != Load && Form != LoadCopy) { 5319 if (ValType.isConstQualified()) { 5320 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5321 << Ptr->getType() << Ptr->getSourceRange(); 5322 return ExprError(); 5323 } 5324 } 5325 5326 // For an arithmetic operation, the implied arithmetic must be well-formed. 5327 if (Form == Arithmetic) { 5328 // gcc does not enforce these rules for GNU atomics, but we do so for 5329 // sanity. 5330 auto IsAllowedValueType = [&](QualType ValType) { 5331 if (ValType->isIntegerType()) 5332 return true; 5333 if (ValType->isPointerType()) 5334 return true; 5335 if (!ValType->isFloatingType()) 5336 return false; 5337 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5338 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5339 &Context.getTargetInfo().getLongDoubleFormat() == 5340 &llvm::APFloat::x87DoubleExtended()) 5341 return false; 5342 return true; 5343 }; 5344 if (IsAddSub && !IsAllowedValueType(ValType)) { 5345 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5346 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5347 return ExprError(); 5348 } 5349 if (!IsAddSub && !ValType->isIntegerType()) { 5350 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5351 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5352 return ExprError(); 5353 } 5354 if (IsC11 && ValType->isPointerType() && 5355 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5356 diag::err_incomplete_type)) { 5357 return ExprError(); 5358 } 5359 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5360 // For __atomic_*_n operations, the value type must be a scalar integral or 5361 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5362 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5363 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5364 return ExprError(); 5365 } 5366 5367 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5368 !AtomTy->isScalarType()) { 5369 // For GNU atomics, require a trivially-copyable type. This is not part of 5370 // the GNU atomics specification, but we enforce it for sanity. 5371 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5372 << Ptr->getType() << Ptr->getSourceRange(); 5373 return ExprError(); 5374 } 5375 5376 switch (ValType.getObjCLifetime()) { 5377 case Qualifiers::OCL_None: 5378 case Qualifiers::OCL_ExplicitNone: 5379 // okay 5380 break; 5381 5382 case Qualifiers::OCL_Weak: 5383 case Qualifiers::OCL_Strong: 5384 case Qualifiers::OCL_Autoreleasing: 5385 // FIXME: Can this happen? By this point, ValType should be known 5386 // to be trivially copyable. 5387 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5388 << ValType << Ptr->getSourceRange(); 5389 return ExprError(); 5390 } 5391 5392 // All atomic operations have an overload which takes a pointer to a volatile 5393 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5394 // into the result or the other operands. Similarly atomic_load takes a 5395 // pointer to a const 'A'. 5396 ValType.removeLocalVolatile(); 5397 ValType.removeLocalConst(); 5398 QualType ResultType = ValType; 5399 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5400 Form == Init) 5401 ResultType = Context.VoidTy; 5402 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5403 ResultType = Context.BoolTy; 5404 5405 // The type of a parameter passed 'by value'. In the GNU atomics, such 5406 // arguments are actually passed as pointers. 5407 QualType ByValType = ValType; // 'CP' 5408 bool IsPassedByAddress = false; 5409 if (!IsC11 && !IsN) { 5410 ByValType = Ptr->getType(); 5411 IsPassedByAddress = true; 5412 } 5413 5414 SmallVector<Expr *, 5> APIOrderedArgs; 5415 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5416 APIOrderedArgs.push_back(Args[0]); 5417 switch (Form) { 5418 case Init: 5419 case Load: 5420 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5421 break; 5422 case LoadCopy: 5423 case Copy: 5424 case Arithmetic: 5425 case Xchg: 5426 APIOrderedArgs.push_back(Args[2]); // Val1 5427 APIOrderedArgs.push_back(Args[1]); // Order 5428 break; 5429 case GNUXchg: 5430 APIOrderedArgs.push_back(Args[2]); // Val1 5431 APIOrderedArgs.push_back(Args[3]); // Val2 5432 APIOrderedArgs.push_back(Args[1]); // Order 5433 break; 5434 case C11CmpXchg: 5435 APIOrderedArgs.push_back(Args[2]); // Val1 5436 APIOrderedArgs.push_back(Args[4]); // Val2 5437 APIOrderedArgs.push_back(Args[1]); // Order 5438 APIOrderedArgs.push_back(Args[3]); // OrderFail 5439 break; 5440 case GNUCmpXchg: 5441 APIOrderedArgs.push_back(Args[2]); // Val1 5442 APIOrderedArgs.push_back(Args[4]); // Val2 5443 APIOrderedArgs.push_back(Args[5]); // Weak 5444 APIOrderedArgs.push_back(Args[1]); // Order 5445 APIOrderedArgs.push_back(Args[3]); // OrderFail 5446 break; 5447 } 5448 } else 5449 APIOrderedArgs.append(Args.begin(), Args.end()); 5450 5451 // The first argument's non-CV pointer type is used to deduce the type of 5452 // subsequent arguments, except for: 5453 // - weak flag (always converted to bool) 5454 // - memory order (always converted to int) 5455 // - scope (always converted to int) 5456 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5457 QualType Ty; 5458 if (i < NumVals[Form] + 1) { 5459 switch (i) { 5460 case 0: 5461 // The first argument is always a pointer. It has a fixed type. 5462 // It is always dereferenced, a nullptr is undefined. 5463 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5464 // Nothing else to do: we already know all we want about this pointer. 5465 continue; 5466 case 1: 5467 // The second argument is the non-atomic operand. For arithmetic, this 5468 // is always passed by value, and for a compare_exchange it is always 5469 // passed by address. For the rest, GNU uses by-address and C11 uses 5470 // by-value. 5471 assert(Form != Load); 5472 if (Form == Arithmetic && ValType->isPointerType()) 5473 Ty = Context.getPointerDiffType(); 5474 else if (Form == Init || Form == Arithmetic) 5475 Ty = ValType; 5476 else if (Form == Copy || Form == Xchg) { 5477 if (IsPassedByAddress) { 5478 // The value pointer is always dereferenced, a nullptr is undefined. 5479 CheckNonNullArgument(*this, APIOrderedArgs[i], 5480 ExprRange.getBegin()); 5481 } 5482 Ty = ByValType; 5483 } else { 5484 Expr *ValArg = APIOrderedArgs[i]; 5485 // The value pointer is always dereferenced, a nullptr is undefined. 5486 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5487 LangAS AS = LangAS::Default; 5488 // Keep address space of non-atomic pointer type. 5489 if (const PointerType *PtrTy = 5490 ValArg->getType()->getAs<PointerType>()) { 5491 AS = PtrTy->getPointeeType().getAddressSpace(); 5492 } 5493 Ty = Context.getPointerType( 5494 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5495 } 5496 break; 5497 case 2: 5498 // The third argument to compare_exchange / GNU exchange is the desired 5499 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5500 if (IsPassedByAddress) 5501 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5502 Ty = ByValType; 5503 break; 5504 case 3: 5505 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5506 Ty = Context.BoolTy; 5507 break; 5508 } 5509 } else { 5510 // The order(s) and scope are always converted to int. 5511 Ty = Context.IntTy; 5512 } 5513 5514 InitializedEntity Entity = 5515 InitializedEntity::InitializeParameter(Context, Ty, false); 5516 ExprResult Arg = APIOrderedArgs[i]; 5517 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5518 if (Arg.isInvalid()) 5519 return true; 5520 APIOrderedArgs[i] = Arg.get(); 5521 } 5522 5523 // Permute the arguments into a 'consistent' order. 5524 SmallVector<Expr*, 5> SubExprs; 5525 SubExprs.push_back(Ptr); 5526 switch (Form) { 5527 case Init: 5528 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5529 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5530 break; 5531 case Load: 5532 SubExprs.push_back(APIOrderedArgs[1]); // Order 5533 break; 5534 case LoadCopy: 5535 case Copy: 5536 case Arithmetic: 5537 case Xchg: 5538 SubExprs.push_back(APIOrderedArgs[2]); // Order 5539 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5540 break; 5541 case GNUXchg: 5542 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5543 SubExprs.push_back(APIOrderedArgs[3]); // Order 5544 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5545 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5546 break; 5547 case C11CmpXchg: 5548 SubExprs.push_back(APIOrderedArgs[3]); // Order 5549 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5550 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5551 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5552 break; 5553 case GNUCmpXchg: 5554 SubExprs.push_back(APIOrderedArgs[4]); // Order 5555 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5556 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5557 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5558 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5559 break; 5560 } 5561 5562 if (SubExprs.size() >= 2 && Form != Init) { 5563 if (Optional<llvm::APSInt> Result = 5564 SubExprs[1]->getIntegerConstantExpr(Context)) 5565 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5566 Diag(SubExprs[1]->getBeginLoc(), 5567 diag::warn_atomic_op_has_invalid_memory_order) 5568 << SubExprs[1]->getSourceRange(); 5569 } 5570 5571 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5572 auto *Scope = Args[Args.size() - 1]; 5573 if (Optional<llvm::APSInt> Result = 5574 Scope->getIntegerConstantExpr(Context)) { 5575 if (!ScopeModel->isValid(Result->getZExtValue())) 5576 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5577 << Scope->getSourceRange(); 5578 } 5579 SubExprs.push_back(Scope); 5580 } 5581 5582 AtomicExpr *AE = new (Context) 5583 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5584 5585 if ((Op == AtomicExpr::AO__c11_atomic_load || 5586 Op == AtomicExpr::AO__c11_atomic_store || 5587 Op == AtomicExpr::AO__opencl_atomic_load || 5588 Op == AtomicExpr::AO__opencl_atomic_store ) && 5589 Context.AtomicUsesUnsupportedLibcall(AE)) 5590 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5591 << ((Op == AtomicExpr::AO__c11_atomic_load || 5592 Op == AtomicExpr::AO__opencl_atomic_load) 5593 ? 0 5594 : 1); 5595 5596 if (ValType->isExtIntType()) { 5597 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5598 return ExprError(); 5599 } 5600 5601 return AE; 5602 } 5603 5604 /// checkBuiltinArgument - Given a call to a builtin function, perform 5605 /// normal type-checking on the given argument, updating the call in 5606 /// place. This is useful when a builtin function requires custom 5607 /// type-checking for some of its arguments but not necessarily all of 5608 /// them. 5609 /// 5610 /// Returns true on error. 5611 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5612 FunctionDecl *Fn = E->getDirectCallee(); 5613 assert(Fn && "builtin call without direct callee!"); 5614 5615 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5616 InitializedEntity Entity = 5617 InitializedEntity::InitializeParameter(S.Context, Param); 5618 5619 ExprResult Arg = E->getArg(0); 5620 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5621 if (Arg.isInvalid()) 5622 return true; 5623 5624 E->setArg(ArgIndex, Arg.get()); 5625 return false; 5626 } 5627 5628 /// We have a call to a function like __sync_fetch_and_add, which is an 5629 /// overloaded function based on the pointer type of its first argument. 5630 /// The main BuildCallExpr routines have already promoted the types of 5631 /// arguments because all of these calls are prototyped as void(...). 5632 /// 5633 /// This function goes through and does final semantic checking for these 5634 /// builtins, as well as generating any warnings. 5635 ExprResult 5636 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5637 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5638 Expr *Callee = TheCall->getCallee(); 5639 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5640 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5641 5642 // Ensure that we have at least one argument to do type inference from. 5643 if (TheCall->getNumArgs() < 1) { 5644 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5645 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5646 return ExprError(); 5647 } 5648 5649 // Inspect the first argument of the atomic builtin. This should always be 5650 // a pointer type, whose element is an integral scalar or pointer type. 5651 // Because it is a pointer type, we don't have to worry about any implicit 5652 // casts here. 5653 // FIXME: We don't allow floating point scalars as input. 5654 Expr *FirstArg = TheCall->getArg(0); 5655 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5656 if (FirstArgResult.isInvalid()) 5657 return ExprError(); 5658 FirstArg = FirstArgResult.get(); 5659 TheCall->setArg(0, FirstArg); 5660 5661 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5662 if (!pointerType) { 5663 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5664 << FirstArg->getType() << FirstArg->getSourceRange(); 5665 return ExprError(); 5666 } 5667 5668 QualType ValType = pointerType->getPointeeType(); 5669 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5670 !ValType->isBlockPointerType()) { 5671 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5672 << FirstArg->getType() << FirstArg->getSourceRange(); 5673 return ExprError(); 5674 } 5675 5676 if (ValType.isConstQualified()) { 5677 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5678 << FirstArg->getType() << FirstArg->getSourceRange(); 5679 return ExprError(); 5680 } 5681 5682 switch (ValType.getObjCLifetime()) { 5683 case Qualifiers::OCL_None: 5684 case Qualifiers::OCL_ExplicitNone: 5685 // okay 5686 break; 5687 5688 case Qualifiers::OCL_Weak: 5689 case Qualifiers::OCL_Strong: 5690 case Qualifiers::OCL_Autoreleasing: 5691 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5692 << ValType << FirstArg->getSourceRange(); 5693 return ExprError(); 5694 } 5695 5696 // Strip any qualifiers off ValType. 5697 ValType = ValType.getUnqualifiedType(); 5698 5699 // The majority of builtins return a value, but a few have special return 5700 // types, so allow them to override appropriately below. 5701 QualType ResultType = ValType; 5702 5703 // We need to figure out which concrete builtin this maps onto. For example, 5704 // __sync_fetch_and_add with a 2 byte object turns into 5705 // __sync_fetch_and_add_2. 5706 #define BUILTIN_ROW(x) \ 5707 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5708 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5709 5710 static const unsigned BuiltinIndices[][5] = { 5711 BUILTIN_ROW(__sync_fetch_and_add), 5712 BUILTIN_ROW(__sync_fetch_and_sub), 5713 BUILTIN_ROW(__sync_fetch_and_or), 5714 BUILTIN_ROW(__sync_fetch_and_and), 5715 BUILTIN_ROW(__sync_fetch_and_xor), 5716 BUILTIN_ROW(__sync_fetch_and_nand), 5717 5718 BUILTIN_ROW(__sync_add_and_fetch), 5719 BUILTIN_ROW(__sync_sub_and_fetch), 5720 BUILTIN_ROW(__sync_and_and_fetch), 5721 BUILTIN_ROW(__sync_or_and_fetch), 5722 BUILTIN_ROW(__sync_xor_and_fetch), 5723 BUILTIN_ROW(__sync_nand_and_fetch), 5724 5725 BUILTIN_ROW(__sync_val_compare_and_swap), 5726 BUILTIN_ROW(__sync_bool_compare_and_swap), 5727 BUILTIN_ROW(__sync_lock_test_and_set), 5728 BUILTIN_ROW(__sync_lock_release), 5729 BUILTIN_ROW(__sync_swap) 5730 }; 5731 #undef BUILTIN_ROW 5732 5733 // Determine the index of the size. 5734 unsigned SizeIndex; 5735 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5736 case 1: SizeIndex = 0; break; 5737 case 2: SizeIndex = 1; break; 5738 case 4: SizeIndex = 2; break; 5739 case 8: SizeIndex = 3; break; 5740 case 16: SizeIndex = 4; break; 5741 default: 5742 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5743 << FirstArg->getType() << FirstArg->getSourceRange(); 5744 return ExprError(); 5745 } 5746 5747 // Each of these builtins has one pointer argument, followed by some number of 5748 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5749 // that we ignore. Find out which row of BuiltinIndices to read from as well 5750 // as the number of fixed args. 5751 unsigned BuiltinID = FDecl->getBuiltinID(); 5752 unsigned BuiltinIndex, NumFixed = 1; 5753 bool WarnAboutSemanticsChange = false; 5754 switch (BuiltinID) { 5755 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5756 case Builtin::BI__sync_fetch_and_add: 5757 case Builtin::BI__sync_fetch_and_add_1: 5758 case Builtin::BI__sync_fetch_and_add_2: 5759 case Builtin::BI__sync_fetch_and_add_4: 5760 case Builtin::BI__sync_fetch_and_add_8: 5761 case Builtin::BI__sync_fetch_and_add_16: 5762 BuiltinIndex = 0; 5763 break; 5764 5765 case Builtin::BI__sync_fetch_and_sub: 5766 case Builtin::BI__sync_fetch_and_sub_1: 5767 case Builtin::BI__sync_fetch_and_sub_2: 5768 case Builtin::BI__sync_fetch_and_sub_4: 5769 case Builtin::BI__sync_fetch_and_sub_8: 5770 case Builtin::BI__sync_fetch_and_sub_16: 5771 BuiltinIndex = 1; 5772 break; 5773 5774 case Builtin::BI__sync_fetch_and_or: 5775 case Builtin::BI__sync_fetch_and_or_1: 5776 case Builtin::BI__sync_fetch_and_or_2: 5777 case Builtin::BI__sync_fetch_and_or_4: 5778 case Builtin::BI__sync_fetch_and_or_8: 5779 case Builtin::BI__sync_fetch_and_or_16: 5780 BuiltinIndex = 2; 5781 break; 5782 5783 case Builtin::BI__sync_fetch_and_and: 5784 case Builtin::BI__sync_fetch_and_and_1: 5785 case Builtin::BI__sync_fetch_and_and_2: 5786 case Builtin::BI__sync_fetch_and_and_4: 5787 case Builtin::BI__sync_fetch_and_and_8: 5788 case Builtin::BI__sync_fetch_and_and_16: 5789 BuiltinIndex = 3; 5790 break; 5791 5792 case Builtin::BI__sync_fetch_and_xor: 5793 case Builtin::BI__sync_fetch_and_xor_1: 5794 case Builtin::BI__sync_fetch_and_xor_2: 5795 case Builtin::BI__sync_fetch_and_xor_4: 5796 case Builtin::BI__sync_fetch_and_xor_8: 5797 case Builtin::BI__sync_fetch_and_xor_16: 5798 BuiltinIndex = 4; 5799 break; 5800 5801 case Builtin::BI__sync_fetch_and_nand: 5802 case Builtin::BI__sync_fetch_and_nand_1: 5803 case Builtin::BI__sync_fetch_and_nand_2: 5804 case Builtin::BI__sync_fetch_and_nand_4: 5805 case Builtin::BI__sync_fetch_and_nand_8: 5806 case Builtin::BI__sync_fetch_and_nand_16: 5807 BuiltinIndex = 5; 5808 WarnAboutSemanticsChange = true; 5809 break; 5810 5811 case Builtin::BI__sync_add_and_fetch: 5812 case Builtin::BI__sync_add_and_fetch_1: 5813 case Builtin::BI__sync_add_and_fetch_2: 5814 case Builtin::BI__sync_add_and_fetch_4: 5815 case Builtin::BI__sync_add_and_fetch_8: 5816 case Builtin::BI__sync_add_and_fetch_16: 5817 BuiltinIndex = 6; 5818 break; 5819 5820 case Builtin::BI__sync_sub_and_fetch: 5821 case Builtin::BI__sync_sub_and_fetch_1: 5822 case Builtin::BI__sync_sub_and_fetch_2: 5823 case Builtin::BI__sync_sub_and_fetch_4: 5824 case Builtin::BI__sync_sub_and_fetch_8: 5825 case Builtin::BI__sync_sub_and_fetch_16: 5826 BuiltinIndex = 7; 5827 break; 5828 5829 case Builtin::BI__sync_and_and_fetch: 5830 case Builtin::BI__sync_and_and_fetch_1: 5831 case Builtin::BI__sync_and_and_fetch_2: 5832 case Builtin::BI__sync_and_and_fetch_4: 5833 case Builtin::BI__sync_and_and_fetch_8: 5834 case Builtin::BI__sync_and_and_fetch_16: 5835 BuiltinIndex = 8; 5836 break; 5837 5838 case Builtin::BI__sync_or_and_fetch: 5839 case Builtin::BI__sync_or_and_fetch_1: 5840 case Builtin::BI__sync_or_and_fetch_2: 5841 case Builtin::BI__sync_or_and_fetch_4: 5842 case Builtin::BI__sync_or_and_fetch_8: 5843 case Builtin::BI__sync_or_and_fetch_16: 5844 BuiltinIndex = 9; 5845 break; 5846 5847 case Builtin::BI__sync_xor_and_fetch: 5848 case Builtin::BI__sync_xor_and_fetch_1: 5849 case Builtin::BI__sync_xor_and_fetch_2: 5850 case Builtin::BI__sync_xor_and_fetch_4: 5851 case Builtin::BI__sync_xor_and_fetch_8: 5852 case Builtin::BI__sync_xor_and_fetch_16: 5853 BuiltinIndex = 10; 5854 break; 5855 5856 case Builtin::BI__sync_nand_and_fetch: 5857 case Builtin::BI__sync_nand_and_fetch_1: 5858 case Builtin::BI__sync_nand_and_fetch_2: 5859 case Builtin::BI__sync_nand_and_fetch_4: 5860 case Builtin::BI__sync_nand_and_fetch_8: 5861 case Builtin::BI__sync_nand_and_fetch_16: 5862 BuiltinIndex = 11; 5863 WarnAboutSemanticsChange = true; 5864 break; 5865 5866 case Builtin::BI__sync_val_compare_and_swap: 5867 case Builtin::BI__sync_val_compare_and_swap_1: 5868 case Builtin::BI__sync_val_compare_and_swap_2: 5869 case Builtin::BI__sync_val_compare_and_swap_4: 5870 case Builtin::BI__sync_val_compare_and_swap_8: 5871 case Builtin::BI__sync_val_compare_and_swap_16: 5872 BuiltinIndex = 12; 5873 NumFixed = 2; 5874 break; 5875 5876 case Builtin::BI__sync_bool_compare_and_swap: 5877 case Builtin::BI__sync_bool_compare_and_swap_1: 5878 case Builtin::BI__sync_bool_compare_and_swap_2: 5879 case Builtin::BI__sync_bool_compare_and_swap_4: 5880 case Builtin::BI__sync_bool_compare_and_swap_8: 5881 case Builtin::BI__sync_bool_compare_and_swap_16: 5882 BuiltinIndex = 13; 5883 NumFixed = 2; 5884 ResultType = Context.BoolTy; 5885 break; 5886 5887 case Builtin::BI__sync_lock_test_and_set: 5888 case Builtin::BI__sync_lock_test_and_set_1: 5889 case Builtin::BI__sync_lock_test_and_set_2: 5890 case Builtin::BI__sync_lock_test_and_set_4: 5891 case Builtin::BI__sync_lock_test_and_set_8: 5892 case Builtin::BI__sync_lock_test_and_set_16: 5893 BuiltinIndex = 14; 5894 break; 5895 5896 case Builtin::BI__sync_lock_release: 5897 case Builtin::BI__sync_lock_release_1: 5898 case Builtin::BI__sync_lock_release_2: 5899 case Builtin::BI__sync_lock_release_4: 5900 case Builtin::BI__sync_lock_release_8: 5901 case Builtin::BI__sync_lock_release_16: 5902 BuiltinIndex = 15; 5903 NumFixed = 0; 5904 ResultType = Context.VoidTy; 5905 break; 5906 5907 case Builtin::BI__sync_swap: 5908 case Builtin::BI__sync_swap_1: 5909 case Builtin::BI__sync_swap_2: 5910 case Builtin::BI__sync_swap_4: 5911 case Builtin::BI__sync_swap_8: 5912 case Builtin::BI__sync_swap_16: 5913 BuiltinIndex = 16; 5914 break; 5915 } 5916 5917 // Now that we know how many fixed arguments we expect, first check that we 5918 // have at least that many. 5919 if (TheCall->getNumArgs() < 1+NumFixed) { 5920 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5921 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5922 << Callee->getSourceRange(); 5923 return ExprError(); 5924 } 5925 5926 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5927 << Callee->getSourceRange(); 5928 5929 if (WarnAboutSemanticsChange) { 5930 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5931 << Callee->getSourceRange(); 5932 } 5933 5934 // Get the decl for the concrete builtin from this, we can tell what the 5935 // concrete integer type we should convert to is. 5936 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5937 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5938 FunctionDecl *NewBuiltinDecl; 5939 if (NewBuiltinID == BuiltinID) 5940 NewBuiltinDecl = FDecl; 5941 else { 5942 // Perform builtin lookup to avoid redeclaring it. 5943 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5944 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5945 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5946 assert(Res.getFoundDecl()); 5947 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5948 if (!NewBuiltinDecl) 5949 return ExprError(); 5950 } 5951 5952 // The first argument --- the pointer --- has a fixed type; we 5953 // deduce the types of the rest of the arguments accordingly. Walk 5954 // the remaining arguments, converting them to the deduced value type. 5955 for (unsigned i = 0; i != NumFixed; ++i) { 5956 ExprResult Arg = TheCall->getArg(i+1); 5957 5958 // GCC does an implicit conversion to the pointer or integer ValType. This 5959 // can fail in some cases (1i -> int**), check for this error case now. 5960 // Initialize the argument. 5961 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5962 ValType, /*consume*/ false); 5963 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5964 if (Arg.isInvalid()) 5965 return ExprError(); 5966 5967 // Okay, we have something that *can* be converted to the right type. Check 5968 // to see if there is a potentially weird extension going on here. This can 5969 // happen when you do an atomic operation on something like an char* and 5970 // pass in 42. The 42 gets converted to char. This is even more strange 5971 // for things like 45.123 -> char, etc. 5972 // FIXME: Do this check. 5973 TheCall->setArg(i+1, Arg.get()); 5974 } 5975 5976 // Create a new DeclRefExpr to refer to the new decl. 5977 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5978 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5979 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5980 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5981 5982 // Set the callee in the CallExpr. 5983 // FIXME: This loses syntactic information. 5984 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5985 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5986 CK_BuiltinFnToFnPtr); 5987 TheCall->setCallee(PromotedCall.get()); 5988 5989 // Change the result type of the call to match the original value type. This 5990 // is arbitrary, but the codegen for these builtins ins design to handle it 5991 // gracefully. 5992 TheCall->setType(ResultType); 5993 5994 // Prohibit use of _ExtInt with atomic builtins. 5995 // The arguments would have already been converted to the first argument's 5996 // type, so only need to check the first argument. 5997 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5998 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5999 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6000 return ExprError(); 6001 } 6002 6003 return TheCallResult; 6004 } 6005 6006 /// SemaBuiltinNontemporalOverloaded - We have a call to 6007 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6008 /// overloaded function based on the pointer type of its last argument. 6009 /// 6010 /// This function goes through and does final semantic checking for these 6011 /// builtins. 6012 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6013 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6014 DeclRefExpr *DRE = 6015 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6016 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6017 unsigned BuiltinID = FDecl->getBuiltinID(); 6018 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6019 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6020 "Unexpected nontemporal load/store builtin!"); 6021 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6022 unsigned numArgs = isStore ? 2 : 1; 6023 6024 // Ensure that we have the proper number of arguments. 6025 if (checkArgCount(*this, TheCall, numArgs)) 6026 return ExprError(); 6027 6028 // Inspect the last argument of the nontemporal builtin. This should always 6029 // be a pointer type, from which we imply the type of the memory access. 6030 // Because it is a pointer type, we don't have to worry about any implicit 6031 // casts here. 6032 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6033 ExprResult PointerArgResult = 6034 DefaultFunctionArrayLvalueConversion(PointerArg); 6035 6036 if (PointerArgResult.isInvalid()) 6037 return ExprError(); 6038 PointerArg = PointerArgResult.get(); 6039 TheCall->setArg(numArgs - 1, PointerArg); 6040 6041 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6042 if (!pointerType) { 6043 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6044 << PointerArg->getType() << PointerArg->getSourceRange(); 6045 return ExprError(); 6046 } 6047 6048 QualType ValType = pointerType->getPointeeType(); 6049 6050 // Strip any qualifiers off ValType. 6051 ValType = ValType.getUnqualifiedType(); 6052 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6053 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6054 !ValType->isVectorType()) { 6055 Diag(DRE->getBeginLoc(), 6056 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6057 << PointerArg->getType() << PointerArg->getSourceRange(); 6058 return ExprError(); 6059 } 6060 6061 if (!isStore) { 6062 TheCall->setType(ValType); 6063 return TheCallResult; 6064 } 6065 6066 ExprResult ValArg = TheCall->getArg(0); 6067 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6068 Context, ValType, /*consume*/ false); 6069 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6070 if (ValArg.isInvalid()) 6071 return ExprError(); 6072 6073 TheCall->setArg(0, ValArg.get()); 6074 TheCall->setType(Context.VoidTy); 6075 return TheCallResult; 6076 } 6077 6078 /// CheckObjCString - Checks that the argument to the builtin 6079 /// CFString constructor is correct 6080 /// Note: It might also make sense to do the UTF-16 conversion here (would 6081 /// simplify the backend). 6082 bool Sema::CheckObjCString(Expr *Arg) { 6083 Arg = Arg->IgnoreParenCasts(); 6084 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6085 6086 if (!Literal || !Literal->isAscii()) { 6087 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6088 << Arg->getSourceRange(); 6089 return true; 6090 } 6091 6092 if (Literal->containsNonAsciiOrNull()) { 6093 StringRef String = Literal->getString(); 6094 unsigned NumBytes = String.size(); 6095 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6096 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6097 llvm::UTF16 *ToPtr = &ToBuf[0]; 6098 6099 llvm::ConversionResult Result = 6100 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6101 ToPtr + NumBytes, llvm::strictConversion); 6102 // Check for conversion failure. 6103 if (Result != llvm::conversionOK) 6104 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6105 << Arg->getSourceRange(); 6106 } 6107 return false; 6108 } 6109 6110 /// CheckObjCString - Checks that the format string argument to the os_log() 6111 /// and os_trace() functions is correct, and converts it to const char *. 6112 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6113 Arg = Arg->IgnoreParenCasts(); 6114 auto *Literal = dyn_cast<StringLiteral>(Arg); 6115 if (!Literal) { 6116 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6117 Literal = ObjcLiteral->getString(); 6118 } 6119 } 6120 6121 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6122 return ExprError( 6123 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6124 << Arg->getSourceRange()); 6125 } 6126 6127 ExprResult Result(Literal); 6128 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6129 InitializedEntity Entity = 6130 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6131 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6132 return Result; 6133 } 6134 6135 /// Check that the user is calling the appropriate va_start builtin for the 6136 /// target and calling convention. 6137 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6138 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6139 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6140 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6141 TT.getArch() == llvm::Triple::aarch64_32); 6142 bool IsWindows = TT.isOSWindows(); 6143 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6144 if (IsX64 || IsAArch64) { 6145 CallingConv CC = CC_C; 6146 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6147 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6148 if (IsMSVAStart) { 6149 // Don't allow this in System V ABI functions. 6150 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6151 return S.Diag(Fn->getBeginLoc(), 6152 diag::err_ms_va_start_used_in_sysv_function); 6153 } else { 6154 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6155 // On x64 Windows, don't allow this in System V ABI functions. 6156 // (Yes, that means there's no corresponding way to support variadic 6157 // System V ABI functions on Windows.) 6158 if ((IsWindows && CC == CC_X86_64SysV) || 6159 (!IsWindows && CC == CC_Win64)) 6160 return S.Diag(Fn->getBeginLoc(), 6161 diag::err_va_start_used_in_wrong_abi_function) 6162 << !IsWindows; 6163 } 6164 return false; 6165 } 6166 6167 if (IsMSVAStart) 6168 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6169 return false; 6170 } 6171 6172 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6173 ParmVarDecl **LastParam = nullptr) { 6174 // Determine whether the current function, block, or obj-c method is variadic 6175 // and get its parameter list. 6176 bool IsVariadic = false; 6177 ArrayRef<ParmVarDecl *> Params; 6178 DeclContext *Caller = S.CurContext; 6179 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6180 IsVariadic = Block->isVariadic(); 6181 Params = Block->parameters(); 6182 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6183 IsVariadic = FD->isVariadic(); 6184 Params = FD->parameters(); 6185 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6186 IsVariadic = MD->isVariadic(); 6187 // FIXME: This isn't correct for methods (results in bogus warning). 6188 Params = MD->parameters(); 6189 } else if (isa<CapturedDecl>(Caller)) { 6190 // We don't support va_start in a CapturedDecl. 6191 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6192 return true; 6193 } else { 6194 // This must be some other declcontext that parses exprs. 6195 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6196 return true; 6197 } 6198 6199 if (!IsVariadic) { 6200 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6201 return true; 6202 } 6203 6204 if (LastParam) 6205 *LastParam = Params.empty() ? nullptr : Params.back(); 6206 6207 return false; 6208 } 6209 6210 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6211 /// for validity. Emit an error and return true on failure; return false 6212 /// on success. 6213 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6214 Expr *Fn = TheCall->getCallee(); 6215 6216 if (checkVAStartABI(*this, BuiltinID, Fn)) 6217 return true; 6218 6219 if (checkArgCount(*this, TheCall, 2)) 6220 return true; 6221 6222 // Type-check the first argument normally. 6223 if (checkBuiltinArgument(*this, TheCall, 0)) 6224 return true; 6225 6226 // Check that the current function is variadic, and get its last parameter. 6227 ParmVarDecl *LastParam; 6228 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6229 return true; 6230 6231 // Verify that the second argument to the builtin is the last argument of the 6232 // current function or method. 6233 bool SecondArgIsLastNamedArgument = false; 6234 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6235 6236 // These are valid if SecondArgIsLastNamedArgument is false after the next 6237 // block. 6238 QualType Type; 6239 SourceLocation ParamLoc; 6240 bool IsCRegister = false; 6241 6242 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6243 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6244 SecondArgIsLastNamedArgument = PV == LastParam; 6245 6246 Type = PV->getType(); 6247 ParamLoc = PV->getLocation(); 6248 IsCRegister = 6249 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6250 } 6251 } 6252 6253 if (!SecondArgIsLastNamedArgument) 6254 Diag(TheCall->getArg(1)->getBeginLoc(), 6255 diag::warn_second_arg_of_va_start_not_last_named_param); 6256 else if (IsCRegister || Type->isReferenceType() || 6257 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6258 // Promotable integers are UB, but enumerations need a bit of 6259 // extra checking to see what their promotable type actually is. 6260 if (!Type->isPromotableIntegerType()) 6261 return false; 6262 if (!Type->isEnumeralType()) 6263 return true; 6264 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6265 return !(ED && 6266 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6267 }()) { 6268 unsigned Reason = 0; 6269 if (Type->isReferenceType()) Reason = 1; 6270 else if (IsCRegister) Reason = 2; 6271 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6272 Diag(ParamLoc, diag::note_parameter_type) << Type; 6273 } 6274 6275 TheCall->setType(Context.VoidTy); 6276 return false; 6277 } 6278 6279 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6280 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6281 // const char *named_addr); 6282 6283 Expr *Func = Call->getCallee(); 6284 6285 if (Call->getNumArgs() < 3) 6286 return Diag(Call->getEndLoc(), 6287 diag::err_typecheck_call_too_few_args_at_least) 6288 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6289 6290 // Type-check the first argument normally. 6291 if (checkBuiltinArgument(*this, Call, 0)) 6292 return true; 6293 6294 // Check that the current function is variadic. 6295 if (checkVAStartIsInVariadicFunction(*this, Func)) 6296 return true; 6297 6298 // __va_start on Windows does not validate the parameter qualifiers 6299 6300 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6301 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6302 6303 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6304 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6305 6306 const QualType &ConstCharPtrTy = 6307 Context.getPointerType(Context.CharTy.withConst()); 6308 if (!Arg1Ty->isPointerType() || 6309 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 6310 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6311 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6312 << 0 /* qualifier difference */ 6313 << 3 /* parameter mismatch */ 6314 << 2 << Arg1->getType() << ConstCharPtrTy; 6315 6316 const QualType SizeTy = Context.getSizeType(); 6317 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6318 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6319 << Arg2->getType() << SizeTy << 1 /* different class */ 6320 << 0 /* qualifier difference */ 6321 << 3 /* parameter mismatch */ 6322 << 3 << Arg2->getType() << SizeTy; 6323 6324 return false; 6325 } 6326 6327 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6328 /// friends. This is declared to take (...), so we have to check everything. 6329 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6330 if (checkArgCount(*this, TheCall, 2)) 6331 return true; 6332 6333 ExprResult OrigArg0 = TheCall->getArg(0); 6334 ExprResult OrigArg1 = TheCall->getArg(1); 6335 6336 // Do standard promotions between the two arguments, returning their common 6337 // type. 6338 QualType Res = UsualArithmeticConversions( 6339 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6340 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6341 return true; 6342 6343 // Make sure any conversions are pushed back into the call; this is 6344 // type safe since unordered compare builtins are declared as "_Bool 6345 // foo(...)". 6346 TheCall->setArg(0, OrigArg0.get()); 6347 TheCall->setArg(1, OrigArg1.get()); 6348 6349 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6350 return false; 6351 6352 // If the common type isn't a real floating type, then the arguments were 6353 // invalid for this operation. 6354 if (Res.isNull() || !Res->isRealFloatingType()) 6355 return Diag(OrigArg0.get()->getBeginLoc(), 6356 diag::err_typecheck_call_invalid_ordered_compare) 6357 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6358 << SourceRange(OrigArg0.get()->getBeginLoc(), 6359 OrigArg1.get()->getEndLoc()); 6360 6361 return false; 6362 } 6363 6364 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6365 /// __builtin_isnan and friends. This is declared to take (...), so we have 6366 /// to check everything. We expect the last argument to be a floating point 6367 /// value. 6368 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6369 if (checkArgCount(*this, TheCall, NumArgs)) 6370 return true; 6371 6372 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6373 // on all preceding parameters just being int. Try all of those. 6374 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6375 Expr *Arg = TheCall->getArg(i); 6376 6377 if (Arg->isTypeDependent()) 6378 return false; 6379 6380 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6381 6382 if (Res.isInvalid()) 6383 return true; 6384 TheCall->setArg(i, Res.get()); 6385 } 6386 6387 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6388 6389 if (OrigArg->isTypeDependent()) 6390 return false; 6391 6392 // Usual Unary Conversions will convert half to float, which we want for 6393 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6394 // type how it is, but do normal L->Rvalue conversions. 6395 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6396 OrigArg = UsualUnaryConversions(OrigArg).get(); 6397 else 6398 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6399 TheCall->setArg(NumArgs - 1, OrigArg); 6400 6401 // This operation requires a non-_Complex floating-point number. 6402 if (!OrigArg->getType()->isRealFloatingType()) 6403 return Diag(OrigArg->getBeginLoc(), 6404 diag::err_typecheck_call_invalid_unary_fp) 6405 << OrigArg->getType() << OrigArg->getSourceRange(); 6406 6407 return false; 6408 } 6409 6410 /// Perform semantic analysis for a call to __builtin_complex. 6411 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6412 if (checkArgCount(*this, TheCall, 2)) 6413 return true; 6414 6415 bool Dependent = false; 6416 for (unsigned I = 0; I != 2; ++I) { 6417 Expr *Arg = TheCall->getArg(I); 6418 QualType T = Arg->getType(); 6419 if (T->isDependentType()) { 6420 Dependent = true; 6421 continue; 6422 } 6423 6424 // Despite supporting _Complex int, GCC requires a real floating point type 6425 // for the operands of __builtin_complex. 6426 if (!T->isRealFloatingType()) { 6427 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6428 << Arg->getType() << Arg->getSourceRange(); 6429 } 6430 6431 ExprResult Converted = DefaultLvalueConversion(Arg); 6432 if (Converted.isInvalid()) 6433 return true; 6434 TheCall->setArg(I, Converted.get()); 6435 } 6436 6437 if (Dependent) { 6438 TheCall->setType(Context.DependentTy); 6439 return false; 6440 } 6441 6442 Expr *Real = TheCall->getArg(0); 6443 Expr *Imag = TheCall->getArg(1); 6444 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6445 return Diag(Real->getBeginLoc(), 6446 diag::err_typecheck_call_different_arg_types) 6447 << Real->getType() << Imag->getType() 6448 << Real->getSourceRange() << Imag->getSourceRange(); 6449 } 6450 6451 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6452 // don't allow this builtin to form those types either. 6453 // FIXME: Should we allow these types? 6454 if (Real->getType()->isFloat16Type()) 6455 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6456 << "_Float16"; 6457 if (Real->getType()->isHalfType()) 6458 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6459 << "half"; 6460 6461 TheCall->setType(Context.getComplexType(Real->getType())); 6462 return false; 6463 } 6464 6465 // Customized Sema Checking for VSX builtins that have the following signature: 6466 // vector [...] builtinName(vector [...], vector [...], const int); 6467 // Which takes the same type of vectors (any legal vector type) for the first 6468 // two arguments and takes compile time constant for the third argument. 6469 // Example builtins are : 6470 // vector double vec_xxpermdi(vector double, vector double, int); 6471 // vector short vec_xxsldwi(vector short, vector short, int); 6472 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6473 unsigned ExpectedNumArgs = 3; 6474 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6475 return true; 6476 6477 // Check the third argument is a compile time constant 6478 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6479 return Diag(TheCall->getBeginLoc(), 6480 diag::err_vsx_builtin_nonconstant_argument) 6481 << 3 /* argument index */ << TheCall->getDirectCallee() 6482 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6483 TheCall->getArg(2)->getEndLoc()); 6484 6485 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6486 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6487 6488 // Check the type of argument 1 and argument 2 are vectors. 6489 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6490 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6491 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6492 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6493 << TheCall->getDirectCallee() 6494 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6495 TheCall->getArg(1)->getEndLoc()); 6496 } 6497 6498 // Check the first two arguments are the same type. 6499 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6500 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6501 << TheCall->getDirectCallee() 6502 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6503 TheCall->getArg(1)->getEndLoc()); 6504 } 6505 6506 // When default clang type checking is turned off and the customized type 6507 // checking is used, the returning type of the function must be explicitly 6508 // set. Otherwise it is _Bool by default. 6509 TheCall->setType(Arg1Ty); 6510 6511 return false; 6512 } 6513 6514 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6515 // This is declared to take (...), so we have to check everything. 6516 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6517 if (TheCall->getNumArgs() < 2) 6518 return ExprError(Diag(TheCall->getEndLoc(), 6519 diag::err_typecheck_call_too_few_args_at_least) 6520 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6521 << TheCall->getSourceRange()); 6522 6523 // Determine which of the following types of shufflevector we're checking: 6524 // 1) unary, vector mask: (lhs, mask) 6525 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6526 QualType resType = TheCall->getArg(0)->getType(); 6527 unsigned numElements = 0; 6528 6529 if (!TheCall->getArg(0)->isTypeDependent() && 6530 !TheCall->getArg(1)->isTypeDependent()) { 6531 QualType LHSType = TheCall->getArg(0)->getType(); 6532 QualType RHSType = TheCall->getArg(1)->getType(); 6533 6534 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6535 return ExprError( 6536 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6537 << TheCall->getDirectCallee() 6538 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6539 TheCall->getArg(1)->getEndLoc())); 6540 6541 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6542 unsigned numResElements = TheCall->getNumArgs() - 2; 6543 6544 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6545 // with mask. If so, verify that RHS is an integer vector type with the 6546 // same number of elts as lhs. 6547 if (TheCall->getNumArgs() == 2) { 6548 if (!RHSType->hasIntegerRepresentation() || 6549 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6550 return ExprError(Diag(TheCall->getBeginLoc(), 6551 diag::err_vec_builtin_incompatible_vector) 6552 << TheCall->getDirectCallee() 6553 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6554 TheCall->getArg(1)->getEndLoc())); 6555 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6556 return ExprError(Diag(TheCall->getBeginLoc(), 6557 diag::err_vec_builtin_incompatible_vector) 6558 << TheCall->getDirectCallee() 6559 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6560 TheCall->getArg(1)->getEndLoc())); 6561 } else if (numElements != numResElements) { 6562 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6563 resType = Context.getVectorType(eltType, numResElements, 6564 VectorType::GenericVector); 6565 } 6566 } 6567 6568 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6569 if (TheCall->getArg(i)->isTypeDependent() || 6570 TheCall->getArg(i)->isValueDependent()) 6571 continue; 6572 6573 Optional<llvm::APSInt> Result; 6574 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6575 return ExprError(Diag(TheCall->getBeginLoc(), 6576 diag::err_shufflevector_nonconstant_argument) 6577 << TheCall->getArg(i)->getSourceRange()); 6578 6579 // Allow -1 which will be translated to undef in the IR. 6580 if (Result->isSigned() && Result->isAllOnesValue()) 6581 continue; 6582 6583 if (Result->getActiveBits() > 64 || 6584 Result->getZExtValue() >= numElements * 2) 6585 return ExprError(Diag(TheCall->getBeginLoc(), 6586 diag::err_shufflevector_argument_too_large) 6587 << TheCall->getArg(i)->getSourceRange()); 6588 } 6589 6590 SmallVector<Expr*, 32> exprs; 6591 6592 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6593 exprs.push_back(TheCall->getArg(i)); 6594 TheCall->setArg(i, nullptr); 6595 } 6596 6597 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6598 TheCall->getCallee()->getBeginLoc(), 6599 TheCall->getRParenLoc()); 6600 } 6601 6602 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6603 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6604 SourceLocation BuiltinLoc, 6605 SourceLocation RParenLoc) { 6606 ExprValueKind VK = VK_PRValue; 6607 ExprObjectKind OK = OK_Ordinary; 6608 QualType DstTy = TInfo->getType(); 6609 QualType SrcTy = E->getType(); 6610 6611 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6612 return ExprError(Diag(BuiltinLoc, 6613 diag::err_convertvector_non_vector) 6614 << E->getSourceRange()); 6615 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6616 return ExprError(Diag(BuiltinLoc, 6617 diag::err_convertvector_non_vector_type)); 6618 6619 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6620 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6621 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6622 if (SrcElts != DstElts) 6623 return ExprError(Diag(BuiltinLoc, 6624 diag::err_convertvector_incompatible_vector) 6625 << E->getSourceRange()); 6626 } 6627 6628 return new (Context) 6629 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6630 } 6631 6632 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6633 // This is declared to take (const void*, ...) and can take two 6634 // optional constant int args. 6635 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6636 unsigned NumArgs = TheCall->getNumArgs(); 6637 6638 if (NumArgs > 3) 6639 return Diag(TheCall->getEndLoc(), 6640 diag::err_typecheck_call_too_many_args_at_most) 6641 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6642 6643 // Argument 0 is checked for us and the remaining arguments must be 6644 // constant integers. 6645 for (unsigned i = 1; i != NumArgs; ++i) 6646 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6647 return true; 6648 6649 return false; 6650 } 6651 6652 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6653 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6654 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6655 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6656 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6657 if (checkArgCount(*this, TheCall, 1)) 6658 return true; 6659 Expr *Arg = TheCall->getArg(0); 6660 if (Arg->isInstantiationDependent()) 6661 return false; 6662 6663 QualType ArgTy = Arg->getType(); 6664 if (!ArgTy->hasFloatingRepresentation()) 6665 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6666 << ArgTy; 6667 if (Arg->isLValue()) { 6668 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6669 TheCall->setArg(0, FirstArg.get()); 6670 } 6671 TheCall->setType(TheCall->getArg(0)->getType()); 6672 return false; 6673 } 6674 6675 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6676 // __assume does not evaluate its arguments, and should warn if its argument 6677 // has side effects. 6678 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6679 Expr *Arg = TheCall->getArg(0); 6680 if (Arg->isInstantiationDependent()) return false; 6681 6682 if (Arg->HasSideEffects(Context)) 6683 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6684 << Arg->getSourceRange() 6685 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6686 6687 return false; 6688 } 6689 6690 /// Handle __builtin_alloca_with_align. This is declared 6691 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6692 /// than 8. 6693 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6694 // The alignment must be a constant integer. 6695 Expr *Arg = TheCall->getArg(1); 6696 6697 // We can't check the value of a dependent argument. 6698 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6699 if (const auto *UE = 6700 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6701 if (UE->getKind() == UETT_AlignOf || 6702 UE->getKind() == UETT_PreferredAlignOf) 6703 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6704 << Arg->getSourceRange(); 6705 6706 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6707 6708 if (!Result.isPowerOf2()) 6709 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6710 << Arg->getSourceRange(); 6711 6712 if (Result < Context.getCharWidth()) 6713 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6714 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6715 6716 if (Result > std::numeric_limits<int32_t>::max()) 6717 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6718 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6719 } 6720 6721 return false; 6722 } 6723 6724 /// Handle __builtin_assume_aligned. This is declared 6725 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6726 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6727 unsigned NumArgs = TheCall->getNumArgs(); 6728 6729 if (NumArgs > 3) 6730 return Diag(TheCall->getEndLoc(), 6731 diag::err_typecheck_call_too_many_args_at_most) 6732 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6733 6734 // The alignment must be a constant integer. 6735 Expr *Arg = TheCall->getArg(1); 6736 6737 // We can't check the value of a dependent argument. 6738 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6739 llvm::APSInt Result; 6740 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6741 return true; 6742 6743 if (!Result.isPowerOf2()) 6744 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6745 << Arg->getSourceRange(); 6746 6747 if (Result > Sema::MaximumAlignment) 6748 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6749 << Arg->getSourceRange() << Sema::MaximumAlignment; 6750 } 6751 6752 if (NumArgs > 2) { 6753 ExprResult Arg(TheCall->getArg(2)); 6754 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6755 Context.getSizeType(), false); 6756 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6757 if (Arg.isInvalid()) return true; 6758 TheCall->setArg(2, Arg.get()); 6759 } 6760 6761 return false; 6762 } 6763 6764 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6765 unsigned BuiltinID = 6766 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6767 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6768 6769 unsigned NumArgs = TheCall->getNumArgs(); 6770 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6771 if (NumArgs < NumRequiredArgs) { 6772 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6773 << 0 /* function call */ << NumRequiredArgs << NumArgs 6774 << TheCall->getSourceRange(); 6775 } 6776 if (NumArgs >= NumRequiredArgs + 0x100) { 6777 return Diag(TheCall->getEndLoc(), 6778 diag::err_typecheck_call_too_many_args_at_most) 6779 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6780 << TheCall->getSourceRange(); 6781 } 6782 unsigned i = 0; 6783 6784 // For formatting call, check buffer arg. 6785 if (!IsSizeCall) { 6786 ExprResult Arg(TheCall->getArg(i)); 6787 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6788 Context, Context.VoidPtrTy, false); 6789 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6790 if (Arg.isInvalid()) 6791 return true; 6792 TheCall->setArg(i, Arg.get()); 6793 i++; 6794 } 6795 6796 // Check string literal arg. 6797 unsigned FormatIdx = i; 6798 { 6799 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6800 if (Arg.isInvalid()) 6801 return true; 6802 TheCall->setArg(i, Arg.get()); 6803 i++; 6804 } 6805 6806 // Make sure variadic args are scalar. 6807 unsigned FirstDataArg = i; 6808 while (i < NumArgs) { 6809 ExprResult Arg = DefaultVariadicArgumentPromotion( 6810 TheCall->getArg(i), VariadicFunction, nullptr); 6811 if (Arg.isInvalid()) 6812 return true; 6813 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6814 if (ArgSize.getQuantity() >= 0x100) { 6815 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6816 << i << (int)ArgSize.getQuantity() << 0xff 6817 << TheCall->getSourceRange(); 6818 } 6819 TheCall->setArg(i, Arg.get()); 6820 i++; 6821 } 6822 6823 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6824 // call to avoid duplicate diagnostics. 6825 if (!IsSizeCall) { 6826 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6827 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6828 bool Success = CheckFormatArguments( 6829 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6830 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6831 CheckedVarArgs); 6832 if (!Success) 6833 return true; 6834 } 6835 6836 if (IsSizeCall) { 6837 TheCall->setType(Context.getSizeType()); 6838 } else { 6839 TheCall->setType(Context.VoidPtrTy); 6840 } 6841 return false; 6842 } 6843 6844 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6845 /// TheCall is a constant expression. 6846 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6847 llvm::APSInt &Result) { 6848 Expr *Arg = TheCall->getArg(ArgNum); 6849 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6850 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6851 6852 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6853 6854 Optional<llvm::APSInt> R; 6855 if (!(R = Arg->getIntegerConstantExpr(Context))) 6856 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6857 << FDecl->getDeclName() << Arg->getSourceRange(); 6858 Result = *R; 6859 return false; 6860 } 6861 6862 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6863 /// TheCall is a constant expression in the range [Low, High]. 6864 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6865 int Low, int High, bool RangeIsError) { 6866 if (isConstantEvaluated()) 6867 return false; 6868 llvm::APSInt Result; 6869 6870 // We can't check the value of a dependent argument. 6871 Expr *Arg = TheCall->getArg(ArgNum); 6872 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6873 return false; 6874 6875 // Check constant-ness first. 6876 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6877 return true; 6878 6879 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6880 if (RangeIsError) 6881 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6882 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 6883 else 6884 // Defer the warning until we know if the code will be emitted so that 6885 // dead code can ignore this. 6886 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6887 PDiag(diag::warn_argument_invalid_range) 6888 << toString(Result, 10) << Low << High 6889 << Arg->getSourceRange()); 6890 } 6891 6892 return false; 6893 } 6894 6895 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6896 /// TheCall is a constant expression is a multiple of Num.. 6897 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6898 unsigned Num) { 6899 llvm::APSInt Result; 6900 6901 // We can't check the value of a dependent argument. 6902 Expr *Arg = TheCall->getArg(ArgNum); 6903 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6904 return false; 6905 6906 // Check constant-ness first. 6907 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6908 return true; 6909 6910 if (Result.getSExtValue() % Num != 0) 6911 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6912 << Num << Arg->getSourceRange(); 6913 6914 return false; 6915 } 6916 6917 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6918 /// constant expression representing a power of 2. 6919 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6920 llvm::APSInt Result; 6921 6922 // We can't check the value of a dependent argument. 6923 Expr *Arg = TheCall->getArg(ArgNum); 6924 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6925 return false; 6926 6927 // Check constant-ness first. 6928 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6929 return true; 6930 6931 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6932 // and only if x is a power of 2. 6933 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6934 return false; 6935 6936 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6937 << Arg->getSourceRange(); 6938 } 6939 6940 static bool IsShiftedByte(llvm::APSInt Value) { 6941 if (Value.isNegative()) 6942 return false; 6943 6944 // Check if it's a shifted byte, by shifting it down 6945 while (true) { 6946 // If the value fits in the bottom byte, the check passes. 6947 if (Value < 0x100) 6948 return true; 6949 6950 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6951 // fails. 6952 if ((Value & 0xFF) != 0) 6953 return false; 6954 6955 // If the bottom 8 bits are all 0, but something above that is nonzero, 6956 // then shifting the value right by 8 bits won't affect whether it's a 6957 // shifted byte or not. So do that, and go round again. 6958 Value >>= 8; 6959 } 6960 } 6961 6962 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6963 /// a constant expression representing an arbitrary byte value shifted left by 6964 /// a multiple of 8 bits. 6965 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6966 unsigned ArgBits) { 6967 llvm::APSInt Result; 6968 6969 // We can't check the value of a dependent argument. 6970 Expr *Arg = TheCall->getArg(ArgNum); 6971 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6972 return false; 6973 6974 // Check constant-ness first. 6975 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6976 return true; 6977 6978 // Truncate to the given size. 6979 Result = Result.getLoBits(ArgBits); 6980 Result.setIsUnsigned(true); 6981 6982 if (IsShiftedByte(Result)) 6983 return false; 6984 6985 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6986 << Arg->getSourceRange(); 6987 } 6988 6989 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6990 /// TheCall is a constant expression representing either a shifted byte value, 6991 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6992 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6993 /// Arm MVE intrinsics. 6994 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6995 int ArgNum, 6996 unsigned ArgBits) { 6997 llvm::APSInt Result; 6998 6999 // We can't check the value of a dependent argument. 7000 Expr *Arg = TheCall->getArg(ArgNum); 7001 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7002 return false; 7003 7004 // Check constant-ness first. 7005 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7006 return true; 7007 7008 // Truncate to the given size. 7009 Result = Result.getLoBits(ArgBits); 7010 Result.setIsUnsigned(true); 7011 7012 // Check to see if it's in either of the required forms. 7013 if (IsShiftedByte(Result) || 7014 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7015 return false; 7016 7017 return Diag(TheCall->getBeginLoc(), 7018 diag::err_argument_not_shifted_byte_or_xxff) 7019 << Arg->getSourceRange(); 7020 } 7021 7022 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7023 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7024 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7025 if (checkArgCount(*this, TheCall, 2)) 7026 return true; 7027 Expr *Arg0 = TheCall->getArg(0); 7028 Expr *Arg1 = TheCall->getArg(1); 7029 7030 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7031 if (FirstArg.isInvalid()) 7032 return true; 7033 QualType FirstArgType = FirstArg.get()->getType(); 7034 if (!FirstArgType->isAnyPointerType()) 7035 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7036 << "first" << FirstArgType << Arg0->getSourceRange(); 7037 TheCall->setArg(0, FirstArg.get()); 7038 7039 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7040 if (SecArg.isInvalid()) 7041 return true; 7042 QualType SecArgType = SecArg.get()->getType(); 7043 if (!SecArgType->isIntegerType()) 7044 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7045 << "second" << SecArgType << Arg1->getSourceRange(); 7046 7047 // Derive the return type from the pointer argument. 7048 TheCall->setType(FirstArgType); 7049 return false; 7050 } 7051 7052 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7053 if (checkArgCount(*this, TheCall, 2)) 7054 return true; 7055 7056 Expr *Arg0 = TheCall->getArg(0); 7057 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7058 if (FirstArg.isInvalid()) 7059 return true; 7060 QualType FirstArgType = FirstArg.get()->getType(); 7061 if (!FirstArgType->isAnyPointerType()) 7062 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7063 << "first" << FirstArgType << Arg0->getSourceRange(); 7064 TheCall->setArg(0, FirstArg.get()); 7065 7066 // Derive the return type from the pointer argument. 7067 TheCall->setType(FirstArgType); 7068 7069 // Second arg must be an constant in range [0,15] 7070 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7071 } 7072 7073 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7074 if (checkArgCount(*this, TheCall, 2)) 7075 return true; 7076 Expr *Arg0 = TheCall->getArg(0); 7077 Expr *Arg1 = TheCall->getArg(1); 7078 7079 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7080 if (FirstArg.isInvalid()) 7081 return true; 7082 QualType FirstArgType = FirstArg.get()->getType(); 7083 if (!FirstArgType->isAnyPointerType()) 7084 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7085 << "first" << FirstArgType << Arg0->getSourceRange(); 7086 7087 QualType SecArgType = Arg1->getType(); 7088 if (!SecArgType->isIntegerType()) 7089 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7090 << "second" << SecArgType << Arg1->getSourceRange(); 7091 TheCall->setType(Context.IntTy); 7092 return false; 7093 } 7094 7095 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7096 BuiltinID == AArch64::BI__builtin_arm_stg) { 7097 if (checkArgCount(*this, TheCall, 1)) 7098 return true; 7099 Expr *Arg0 = TheCall->getArg(0); 7100 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7101 if (FirstArg.isInvalid()) 7102 return true; 7103 7104 QualType FirstArgType = FirstArg.get()->getType(); 7105 if (!FirstArgType->isAnyPointerType()) 7106 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7107 << "first" << FirstArgType << Arg0->getSourceRange(); 7108 TheCall->setArg(0, FirstArg.get()); 7109 7110 // Derive the return type from the pointer argument. 7111 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7112 TheCall->setType(FirstArgType); 7113 return false; 7114 } 7115 7116 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7117 Expr *ArgA = TheCall->getArg(0); 7118 Expr *ArgB = TheCall->getArg(1); 7119 7120 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7121 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7122 7123 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7124 return true; 7125 7126 QualType ArgTypeA = ArgExprA.get()->getType(); 7127 QualType ArgTypeB = ArgExprB.get()->getType(); 7128 7129 auto isNull = [&] (Expr *E) -> bool { 7130 return E->isNullPointerConstant( 7131 Context, Expr::NPC_ValueDependentIsNotNull); }; 7132 7133 // argument should be either a pointer or null 7134 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7135 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7136 << "first" << ArgTypeA << ArgA->getSourceRange(); 7137 7138 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7139 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7140 << "second" << ArgTypeB << ArgB->getSourceRange(); 7141 7142 // Ensure Pointee types are compatible 7143 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7144 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7145 QualType pointeeA = ArgTypeA->getPointeeType(); 7146 QualType pointeeB = ArgTypeB->getPointeeType(); 7147 if (!Context.typesAreCompatible( 7148 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7149 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7150 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7151 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7152 << ArgB->getSourceRange(); 7153 } 7154 } 7155 7156 // at least one argument should be pointer type 7157 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7158 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7159 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7160 7161 if (isNull(ArgA)) // adopt type of the other pointer 7162 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7163 7164 if (isNull(ArgB)) 7165 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7166 7167 TheCall->setArg(0, ArgExprA.get()); 7168 TheCall->setArg(1, ArgExprB.get()); 7169 TheCall->setType(Context.LongLongTy); 7170 return false; 7171 } 7172 assert(false && "Unhandled ARM MTE intrinsic"); 7173 return true; 7174 } 7175 7176 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7177 /// TheCall is an ARM/AArch64 special register string literal. 7178 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7179 int ArgNum, unsigned ExpectedFieldNum, 7180 bool AllowName) { 7181 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7182 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7183 BuiltinID == ARM::BI__builtin_arm_rsr || 7184 BuiltinID == ARM::BI__builtin_arm_rsrp || 7185 BuiltinID == ARM::BI__builtin_arm_wsr || 7186 BuiltinID == ARM::BI__builtin_arm_wsrp; 7187 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7188 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7189 BuiltinID == AArch64::BI__builtin_arm_rsr || 7190 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7191 BuiltinID == AArch64::BI__builtin_arm_wsr || 7192 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7193 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7194 7195 // We can't check the value of a dependent argument. 7196 Expr *Arg = TheCall->getArg(ArgNum); 7197 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7198 return false; 7199 7200 // Check if the argument is a string literal. 7201 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7202 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7203 << Arg->getSourceRange(); 7204 7205 // Check the type of special register given. 7206 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7207 SmallVector<StringRef, 6> Fields; 7208 Reg.split(Fields, ":"); 7209 7210 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7211 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7212 << Arg->getSourceRange(); 7213 7214 // If the string is the name of a register then we cannot check that it is 7215 // valid here but if the string is of one the forms described in ACLE then we 7216 // can check that the supplied fields are integers and within the valid 7217 // ranges. 7218 if (Fields.size() > 1) { 7219 bool FiveFields = Fields.size() == 5; 7220 7221 bool ValidString = true; 7222 if (IsARMBuiltin) { 7223 ValidString &= Fields[0].startswith_insensitive("cp") || 7224 Fields[0].startswith_insensitive("p"); 7225 if (ValidString) 7226 Fields[0] = Fields[0].drop_front( 7227 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7228 7229 ValidString &= Fields[2].startswith_insensitive("c"); 7230 if (ValidString) 7231 Fields[2] = Fields[2].drop_front(1); 7232 7233 if (FiveFields) { 7234 ValidString &= Fields[3].startswith_insensitive("c"); 7235 if (ValidString) 7236 Fields[3] = Fields[3].drop_front(1); 7237 } 7238 } 7239 7240 SmallVector<int, 5> Ranges; 7241 if (FiveFields) 7242 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7243 else 7244 Ranges.append({15, 7, 15}); 7245 7246 for (unsigned i=0; i<Fields.size(); ++i) { 7247 int IntField; 7248 ValidString &= !Fields[i].getAsInteger(10, IntField); 7249 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7250 } 7251 7252 if (!ValidString) 7253 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7254 << Arg->getSourceRange(); 7255 } else if (IsAArch64Builtin && Fields.size() == 1) { 7256 // If the register name is one of those that appear in the condition below 7257 // and the special register builtin being used is one of the write builtins, 7258 // then we require that the argument provided for writing to the register 7259 // is an integer constant expression. This is because it will be lowered to 7260 // an MSR (immediate) instruction, so we need to know the immediate at 7261 // compile time. 7262 if (TheCall->getNumArgs() != 2) 7263 return false; 7264 7265 std::string RegLower = Reg.lower(); 7266 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7267 RegLower != "pan" && RegLower != "uao") 7268 return false; 7269 7270 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7271 } 7272 7273 return false; 7274 } 7275 7276 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7277 /// Emit an error and return true on failure; return false on success. 7278 /// TypeStr is a string containing the type descriptor of the value returned by 7279 /// the builtin and the descriptors of the expected type of the arguments. 7280 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 7281 7282 assert((TypeStr[0] != '\0') && 7283 "Invalid types in PPC MMA builtin declaration"); 7284 7285 unsigned Mask = 0; 7286 unsigned ArgNum = 0; 7287 7288 // The first type in TypeStr is the type of the value returned by the 7289 // builtin. So we first read that type and change the type of TheCall. 7290 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7291 TheCall->setType(type); 7292 7293 while (*TypeStr != '\0') { 7294 Mask = 0; 7295 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7296 if (ArgNum >= TheCall->getNumArgs()) { 7297 ArgNum++; 7298 break; 7299 } 7300 7301 Expr *Arg = TheCall->getArg(ArgNum); 7302 QualType ArgType = Arg->getType(); 7303 7304 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 7305 (!ExpectedType->isVoidPointerType() && 7306 ArgType.getCanonicalType() != ExpectedType)) 7307 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7308 << ArgType << ExpectedType << 1 << 0 << 0; 7309 7310 // If the value of the Mask is not 0, we have a constraint in the size of 7311 // the integer argument so here we ensure the argument is a constant that 7312 // is in the valid range. 7313 if (Mask != 0 && 7314 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7315 return true; 7316 7317 ArgNum++; 7318 } 7319 7320 // In case we exited early from the previous loop, there are other types to 7321 // read from TypeStr. So we need to read them all to ensure we have the right 7322 // number of arguments in TheCall and if it is not the case, to display a 7323 // better error message. 7324 while (*TypeStr != '\0') { 7325 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7326 ArgNum++; 7327 } 7328 if (checkArgCount(*this, TheCall, ArgNum)) 7329 return true; 7330 7331 return false; 7332 } 7333 7334 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7335 /// This checks that the target supports __builtin_longjmp and 7336 /// that val is a constant 1. 7337 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7338 if (!Context.getTargetInfo().hasSjLjLowering()) 7339 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7340 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7341 7342 Expr *Arg = TheCall->getArg(1); 7343 llvm::APSInt Result; 7344 7345 // TODO: This is less than ideal. Overload this to take a value. 7346 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7347 return true; 7348 7349 if (Result != 1) 7350 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7351 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7352 7353 return false; 7354 } 7355 7356 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7357 /// This checks that the target supports __builtin_setjmp. 7358 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7359 if (!Context.getTargetInfo().hasSjLjLowering()) 7360 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7361 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7362 return false; 7363 } 7364 7365 namespace { 7366 7367 class UncoveredArgHandler { 7368 enum { Unknown = -1, AllCovered = -2 }; 7369 7370 signed FirstUncoveredArg = Unknown; 7371 SmallVector<const Expr *, 4> DiagnosticExprs; 7372 7373 public: 7374 UncoveredArgHandler() = default; 7375 7376 bool hasUncoveredArg() const { 7377 return (FirstUncoveredArg >= 0); 7378 } 7379 7380 unsigned getUncoveredArg() const { 7381 assert(hasUncoveredArg() && "no uncovered argument"); 7382 return FirstUncoveredArg; 7383 } 7384 7385 void setAllCovered() { 7386 // A string has been found with all arguments covered, so clear out 7387 // the diagnostics. 7388 DiagnosticExprs.clear(); 7389 FirstUncoveredArg = AllCovered; 7390 } 7391 7392 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7393 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7394 7395 // Don't update if a previous string covers all arguments. 7396 if (FirstUncoveredArg == AllCovered) 7397 return; 7398 7399 // UncoveredArgHandler tracks the highest uncovered argument index 7400 // and with it all the strings that match this index. 7401 if (NewFirstUncoveredArg == FirstUncoveredArg) 7402 DiagnosticExprs.push_back(StrExpr); 7403 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7404 DiagnosticExprs.clear(); 7405 DiagnosticExprs.push_back(StrExpr); 7406 FirstUncoveredArg = NewFirstUncoveredArg; 7407 } 7408 } 7409 7410 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7411 }; 7412 7413 enum StringLiteralCheckType { 7414 SLCT_NotALiteral, 7415 SLCT_UncheckedLiteral, 7416 SLCT_CheckedLiteral 7417 }; 7418 7419 } // namespace 7420 7421 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7422 BinaryOperatorKind BinOpKind, 7423 bool AddendIsRight) { 7424 unsigned BitWidth = Offset.getBitWidth(); 7425 unsigned AddendBitWidth = Addend.getBitWidth(); 7426 // There might be negative interim results. 7427 if (Addend.isUnsigned()) { 7428 Addend = Addend.zext(++AddendBitWidth); 7429 Addend.setIsSigned(true); 7430 } 7431 // Adjust the bit width of the APSInts. 7432 if (AddendBitWidth > BitWidth) { 7433 Offset = Offset.sext(AddendBitWidth); 7434 BitWidth = AddendBitWidth; 7435 } else if (BitWidth > AddendBitWidth) { 7436 Addend = Addend.sext(BitWidth); 7437 } 7438 7439 bool Ov = false; 7440 llvm::APSInt ResOffset = Offset; 7441 if (BinOpKind == BO_Add) 7442 ResOffset = Offset.sadd_ov(Addend, Ov); 7443 else { 7444 assert(AddendIsRight && BinOpKind == BO_Sub && 7445 "operator must be add or sub with addend on the right"); 7446 ResOffset = Offset.ssub_ov(Addend, Ov); 7447 } 7448 7449 // We add an offset to a pointer here so we should support an offset as big as 7450 // possible. 7451 if (Ov) { 7452 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7453 "index (intermediate) result too big"); 7454 Offset = Offset.sext(2 * BitWidth); 7455 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7456 return; 7457 } 7458 7459 Offset = ResOffset; 7460 } 7461 7462 namespace { 7463 7464 // This is a wrapper class around StringLiteral to support offsetted string 7465 // literals as format strings. It takes the offset into account when returning 7466 // the string and its length or the source locations to display notes correctly. 7467 class FormatStringLiteral { 7468 const StringLiteral *FExpr; 7469 int64_t Offset; 7470 7471 public: 7472 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7473 : FExpr(fexpr), Offset(Offset) {} 7474 7475 StringRef getString() const { 7476 return FExpr->getString().drop_front(Offset); 7477 } 7478 7479 unsigned getByteLength() const { 7480 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7481 } 7482 7483 unsigned getLength() const { return FExpr->getLength() - Offset; } 7484 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7485 7486 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7487 7488 QualType getType() const { return FExpr->getType(); } 7489 7490 bool isAscii() const { return FExpr->isAscii(); } 7491 bool isWide() const { return FExpr->isWide(); } 7492 bool isUTF8() const { return FExpr->isUTF8(); } 7493 bool isUTF16() const { return FExpr->isUTF16(); } 7494 bool isUTF32() const { return FExpr->isUTF32(); } 7495 bool isPascal() const { return FExpr->isPascal(); } 7496 7497 SourceLocation getLocationOfByte( 7498 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7499 const TargetInfo &Target, unsigned *StartToken = nullptr, 7500 unsigned *StartTokenByteOffset = nullptr) const { 7501 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7502 StartToken, StartTokenByteOffset); 7503 } 7504 7505 SourceLocation getBeginLoc() const LLVM_READONLY { 7506 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7507 } 7508 7509 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7510 }; 7511 7512 } // namespace 7513 7514 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7515 const Expr *OrigFormatExpr, 7516 ArrayRef<const Expr *> Args, 7517 bool HasVAListArg, unsigned format_idx, 7518 unsigned firstDataArg, 7519 Sema::FormatStringType Type, 7520 bool inFunctionCall, 7521 Sema::VariadicCallType CallType, 7522 llvm::SmallBitVector &CheckedVarArgs, 7523 UncoveredArgHandler &UncoveredArg, 7524 bool IgnoreStringsWithoutSpecifiers); 7525 7526 // Determine if an expression is a string literal or constant string. 7527 // If this function returns false on the arguments to a function expecting a 7528 // format string, we will usually need to emit a warning. 7529 // True string literals are then checked by CheckFormatString. 7530 static StringLiteralCheckType 7531 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7532 bool HasVAListArg, unsigned format_idx, 7533 unsigned firstDataArg, Sema::FormatStringType Type, 7534 Sema::VariadicCallType CallType, bool InFunctionCall, 7535 llvm::SmallBitVector &CheckedVarArgs, 7536 UncoveredArgHandler &UncoveredArg, 7537 llvm::APSInt Offset, 7538 bool IgnoreStringsWithoutSpecifiers = false) { 7539 if (S.isConstantEvaluated()) 7540 return SLCT_NotALiteral; 7541 tryAgain: 7542 assert(Offset.isSigned() && "invalid offset"); 7543 7544 if (E->isTypeDependent() || E->isValueDependent()) 7545 return SLCT_NotALiteral; 7546 7547 E = E->IgnoreParenCasts(); 7548 7549 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7550 // Technically -Wformat-nonliteral does not warn about this case. 7551 // The behavior of printf and friends in this case is implementation 7552 // dependent. Ideally if the format string cannot be null then 7553 // it should have a 'nonnull' attribute in the function prototype. 7554 return SLCT_UncheckedLiteral; 7555 7556 switch (E->getStmtClass()) { 7557 case Stmt::BinaryConditionalOperatorClass: 7558 case Stmt::ConditionalOperatorClass: { 7559 // The expression is a literal if both sub-expressions were, and it was 7560 // completely checked only if both sub-expressions were checked. 7561 const AbstractConditionalOperator *C = 7562 cast<AbstractConditionalOperator>(E); 7563 7564 // Determine whether it is necessary to check both sub-expressions, for 7565 // example, because the condition expression is a constant that can be 7566 // evaluated at compile time. 7567 bool CheckLeft = true, CheckRight = true; 7568 7569 bool Cond; 7570 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7571 S.isConstantEvaluated())) { 7572 if (Cond) 7573 CheckRight = false; 7574 else 7575 CheckLeft = false; 7576 } 7577 7578 // We need to maintain the offsets for the right and the left hand side 7579 // separately to check if every possible indexed expression is a valid 7580 // string literal. They might have different offsets for different string 7581 // literals in the end. 7582 StringLiteralCheckType Left; 7583 if (!CheckLeft) 7584 Left = SLCT_UncheckedLiteral; 7585 else { 7586 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7587 HasVAListArg, format_idx, firstDataArg, 7588 Type, CallType, InFunctionCall, 7589 CheckedVarArgs, UncoveredArg, Offset, 7590 IgnoreStringsWithoutSpecifiers); 7591 if (Left == SLCT_NotALiteral || !CheckRight) { 7592 return Left; 7593 } 7594 } 7595 7596 StringLiteralCheckType Right = checkFormatStringExpr( 7597 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7598 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7599 IgnoreStringsWithoutSpecifiers); 7600 7601 return (CheckLeft && Left < Right) ? Left : Right; 7602 } 7603 7604 case Stmt::ImplicitCastExprClass: 7605 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7606 goto tryAgain; 7607 7608 case Stmt::OpaqueValueExprClass: 7609 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7610 E = src; 7611 goto tryAgain; 7612 } 7613 return SLCT_NotALiteral; 7614 7615 case Stmt::PredefinedExprClass: 7616 // While __func__, etc., are technically not string literals, they 7617 // cannot contain format specifiers and thus are not a security 7618 // liability. 7619 return SLCT_UncheckedLiteral; 7620 7621 case Stmt::DeclRefExprClass: { 7622 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7623 7624 // As an exception, do not flag errors for variables binding to 7625 // const string literals. 7626 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7627 bool isConstant = false; 7628 QualType T = DR->getType(); 7629 7630 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7631 isConstant = AT->getElementType().isConstant(S.Context); 7632 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7633 isConstant = T.isConstant(S.Context) && 7634 PT->getPointeeType().isConstant(S.Context); 7635 } else if (T->isObjCObjectPointerType()) { 7636 // In ObjC, there is usually no "const ObjectPointer" type, 7637 // so don't check if the pointee type is constant. 7638 isConstant = T.isConstant(S.Context); 7639 } 7640 7641 if (isConstant) { 7642 if (const Expr *Init = VD->getAnyInitializer()) { 7643 // Look through initializers like const char c[] = { "foo" } 7644 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7645 if (InitList->isStringLiteralInit()) 7646 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7647 } 7648 return checkFormatStringExpr(S, Init, Args, 7649 HasVAListArg, format_idx, 7650 firstDataArg, Type, CallType, 7651 /*InFunctionCall*/ false, CheckedVarArgs, 7652 UncoveredArg, Offset); 7653 } 7654 } 7655 7656 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7657 // special check to see if the format string is a function parameter 7658 // of the function calling the printf function. If the function 7659 // has an attribute indicating it is a printf-like function, then we 7660 // should suppress warnings concerning non-literals being used in a call 7661 // to a vprintf function. For example: 7662 // 7663 // void 7664 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7665 // va_list ap; 7666 // va_start(ap, fmt); 7667 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7668 // ... 7669 // } 7670 if (HasVAListArg) { 7671 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7672 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7673 int PVIndex = PV->getFunctionScopeIndex() + 1; 7674 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7675 // adjust for implicit parameter 7676 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7677 if (MD->isInstance()) 7678 ++PVIndex; 7679 // We also check if the formats are compatible. 7680 // We can't pass a 'scanf' string to a 'printf' function. 7681 if (PVIndex == PVFormat->getFormatIdx() && 7682 Type == S.GetFormatStringType(PVFormat)) 7683 return SLCT_UncheckedLiteral; 7684 } 7685 } 7686 } 7687 } 7688 } 7689 7690 return SLCT_NotALiteral; 7691 } 7692 7693 case Stmt::CallExprClass: 7694 case Stmt::CXXMemberCallExprClass: { 7695 const CallExpr *CE = cast<CallExpr>(E); 7696 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7697 bool IsFirst = true; 7698 StringLiteralCheckType CommonResult; 7699 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7700 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7701 StringLiteralCheckType Result = checkFormatStringExpr( 7702 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7703 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7704 IgnoreStringsWithoutSpecifiers); 7705 if (IsFirst) { 7706 CommonResult = Result; 7707 IsFirst = false; 7708 } 7709 } 7710 if (!IsFirst) 7711 return CommonResult; 7712 7713 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7714 unsigned BuiltinID = FD->getBuiltinID(); 7715 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7716 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7717 const Expr *Arg = CE->getArg(0); 7718 return checkFormatStringExpr(S, Arg, Args, 7719 HasVAListArg, format_idx, 7720 firstDataArg, Type, CallType, 7721 InFunctionCall, CheckedVarArgs, 7722 UncoveredArg, Offset, 7723 IgnoreStringsWithoutSpecifiers); 7724 } 7725 } 7726 } 7727 7728 return SLCT_NotALiteral; 7729 } 7730 case Stmt::ObjCMessageExprClass: { 7731 const auto *ME = cast<ObjCMessageExpr>(E); 7732 if (const auto *MD = ME->getMethodDecl()) { 7733 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7734 // As a special case heuristic, if we're using the method -[NSBundle 7735 // localizedStringForKey:value:table:], ignore any key strings that lack 7736 // format specifiers. The idea is that if the key doesn't have any 7737 // format specifiers then its probably just a key to map to the 7738 // localized strings. If it does have format specifiers though, then its 7739 // likely that the text of the key is the format string in the 7740 // programmer's language, and should be checked. 7741 const ObjCInterfaceDecl *IFace; 7742 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7743 IFace->getIdentifier()->isStr("NSBundle") && 7744 MD->getSelector().isKeywordSelector( 7745 {"localizedStringForKey", "value", "table"})) { 7746 IgnoreStringsWithoutSpecifiers = true; 7747 } 7748 7749 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7750 return checkFormatStringExpr( 7751 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7752 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7753 IgnoreStringsWithoutSpecifiers); 7754 } 7755 } 7756 7757 return SLCT_NotALiteral; 7758 } 7759 case Stmt::ObjCStringLiteralClass: 7760 case Stmt::StringLiteralClass: { 7761 const StringLiteral *StrE = nullptr; 7762 7763 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7764 StrE = ObjCFExpr->getString(); 7765 else 7766 StrE = cast<StringLiteral>(E); 7767 7768 if (StrE) { 7769 if (Offset.isNegative() || Offset > StrE->getLength()) { 7770 // TODO: It would be better to have an explicit warning for out of 7771 // bounds literals. 7772 return SLCT_NotALiteral; 7773 } 7774 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7775 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7776 firstDataArg, Type, InFunctionCall, CallType, 7777 CheckedVarArgs, UncoveredArg, 7778 IgnoreStringsWithoutSpecifiers); 7779 return SLCT_CheckedLiteral; 7780 } 7781 7782 return SLCT_NotALiteral; 7783 } 7784 case Stmt::BinaryOperatorClass: { 7785 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7786 7787 // A string literal + an int offset is still a string literal. 7788 if (BinOp->isAdditiveOp()) { 7789 Expr::EvalResult LResult, RResult; 7790 7791 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7792 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7793 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7794 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7795 7796 if (LIsInt != RIsInt) { 7797 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7798 7799 if (LIsInt) { 7800 if (BinOpKind == BO_Add) { 7801 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7802 E = BinOp->getRHS(); 7803 goto tryAgain; 7804 } 7805 } else { 7806 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7807 E = BinOp->getLHS(); 7808 goto tryAgain; 7809 } 7810 } 7811 } 7812 7813 return SLCT_NotALiteral; 7814 } 7815 case Stmt::UnaryOperatorClass: { 7816 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7817 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7818 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7819 Expr::EvalResult IndexResult; 7820 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7821 Expr::SE_NoSideEffects, 7822 S.isConstantEvaluated())) { 7823 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7824 /*RHS is int*/ true); 7825 E = ASE->getBase(); 7826 goto tryAgain; 7827 } 7828 } 7829 7830 return SLCT_NotALiteral; 7831 } 7832 7833 default: 7834 return SLCT_NotALiteral; 7835 } 7836 } 7837 7838 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7839 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7840 .Case("scanf", FST_Scanf) 7841 .Cases("printf", "printf0", FST_Printf) 7842 .Cases("NSString", "CFString", FST_NSString) 7843 .Case("strftime", FST_Strftime) 7844 .Case("strfmon", FST_Strfmon) 7845 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7846 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7847 .Case("os_trace", FST_OSLog) 7848 .Case("os_log", FST_OSLog) 7849 .Default(FST_Unknown); 7850 } 7851 7852 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7853 /// functions) for correct use of format strings. 7854 /// Returns true if a format string has been fully checked. 7855 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7856 ArrayRef<const Expr *> Args, 7857 bool IsCXXMember, 7858 VariadicCallType CallType, 7859 SourceLocation Loc, SourceRange Range, 7860 llvm::SmallBitVector &CheckedVarArgs) { 7861 FormatStringInfo FSI; 7862 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7863 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7864 FSI.FirstDataArg, GetFormatStringType(Format), 7865 CallType, Loc, Range, CheckedVarArgs); 7866 return false; 7867 } 7868 7869 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7870 bool HasVAListArg, unsigned format_idx, 7871 unsigned firstDataArg, FormatStringType Type, 7872 VariadicCallType CallType, 7873 SourceLocation Loc, SourceRange Range, 7874 llvm::SmallBitVector &CheckedVarArgs) { 7875 // CHECK: printf/scanf-like function is called with no format string. 7876 if (format_idx >= Args.size()) { 7877 Diag(Loc, diag::warn_missing_format_string) << Range; 7878 return false; 7879 } 7880 7881 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7882 7883 // CHECK: format string is not a string literal. 7884 // 7885 // Dynamically generated format strings are difficult to 7886 // automatically vet at compile time. Requiring that format strings 7887 // are string literals: (1) permits the checking of format strings by 7888 // the compiler and thereby (2) can practically remove the source of 7889 // many format string exploits. 7890 7891 // Format string can be either ObjC string (e.g. @"%d") or 7892 // C string (e.g. "%d") 7893 // ObjC string uses the same format specifiers as C string, so we can use 7894 // the same format string checking logic for both ObjC and C strings. 7895 UncoveredArgHandler UncoveredArg; 7896 StringLiteralCheckType CT = 7897 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7898 format_idx, firstDataArg, Type, CallType, 7899 /*IsFunctionCall*/ true, CheckedVarArgs, 7900 UncoveredArg, 7901 /*no string offset*/ llvm::APSInt(64, false) = 0); 7902 7903 // Generate a diagnostic where an uncovered argument is detected. 7904 if (UncoveredArg.hasUncoveredArg()) { 7905 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7906 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7907 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7908 } 7909 7910 if (CT != SLCT_NotALiteral) 7911 // Literal format string found, check done! 7912 return CT == SLCT_CheckedLiteral; 7913 7914 // Strftime is particular as it always uses a single 'time' argument, 7915 // so it is safe to pass a non-literal string. 7916 if (Type == FST_Strftime) 7917 return false; 7918 7919 // Do not emit diag when the string param is a macro expansion and the 7920 // format is either NSString or CFString. This is a hack to prevent 7921 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7922 // which are usually used in place of NS and CF string literals. 7923 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7924 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7925 return false; 7926 7927 // If there are no arguments specified, warn with -Wformat-security, otherwise 7928 // warn only with -Wformat-nonliteral. 7929 if (Args.size() == firstDataArg) { 7930 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7931 << OrigFormatExpr->getSourceRange(); 7932 switch (Type) { 7933 default: 7934 break; 7935 case FST_Kprintf: 7936 case FST_FreeBSDKPrintf: 7937 case FST_Printf: 7938 Diag(FormatLoc, diag::note_format_security_fixit) 7939 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7940 break; 7941 case FST_NSString: 7942 Diag(FormatLoc, diag::note_format_security_fixit) 7943 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7944 break; 7945 } 7946 } else { 7947 Diag(FormatLoc, diag::warn_format_nonliteral) 7948 << OrigFormatExpr->getSourceRange(); 7949 } 7950 return false; 7951 } 7952 7953 namespace { 7954 7955 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7956 protected: 7957 Sema &S; 7958 const FormatStringLiteral *FExpr; 7959 const Expr *OrigFormatExpr; 7960 const Sema::FormatStringType FSType; 7961 const unsigned FirstDataArg; 7962 const unsigned NumDataArgs; 7963 const char *Beg; // Start of format string. 7964 const bool HasVAListArg; 7965 ArrayRef<const Expr *> Args; 7966 unsigned FormatIdx; 7967 llvm::SmallBitVector CoveredArgs; 7968 bool usesPositionalArgs = false; 7969 bool atFirstArg = true; 7970 bool inFunctionCall; 7971 Sema::VariadicCallType CallType; 7972 llvm::SmallBitVector &CheckedVarArgs; 7973 UncoveredArgHandler &UncoveredArg; 7974 7975 public: 7976 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7977 const Expr *origFormatExpr, 7978 const Sema::FormatStringType type, unsigned firstDataArg, 7979 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7980 ArrayRef<const Expr *> Args, unsigned formatIdx, 7981 bool inFunctionCall, Sema::VariadicCallType callType, 7982 llvm::SmallBitVector &CheckedVarArgs, 7983 UncoveredArgHandler &UncoveredArg) 7984 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7985 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7986 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7987 inFunctionCall(inFunctionCall), CallType(callType), 7988 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7989 CoveredArgs.resize(numDataArgs); 7990 CoveredArgs.reset(); 7991 } 7992 7993 void DoneProcessing(); 7994 7995 void HandleIncompleteSpecifier(const char *startSpecifier, 7996 unsigned specifierLen) override; 7997 7998 void HandleInvalidLengthModifier( 7999 const analyze_format_string::FormatSpecifier &FS, 8000 const analyze_format_string::ConversionSpecifier &CS, 8001 const char *startSpecifier, unsigned specifierLen, 8002 unsigned DiagID); 8003 8004 void HandleNonStandardLengthModifier( 8005 const analyze_format_string::FormatSpecifier &FS, 8006 const char *startSpecifier, unsigned specifierLen); 8007 8008 void HandleNonStandardConversionSpecifier( 8009 const analyze_format_string::ConversionSpecifier &CS, 8010 const char *startSpecifier, unsigned specifierLen); 8011 8012 void HandlePosition(const char *startPos, unsigned posLen) override; 8013 8014 void HandleInvalidPosition(const char *startSpecifier, 8015 unsigned specifierLen, 8016 analyze_format_string::PositionContext p) override; 8017 8018 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8019 8020 void HandleNullChar(const char *nullCharacter) override; 8021 8022 template <typename Range> 8023 static void 8024 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8025 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8026 bool IsStringLocation, Range StringRange, 8027 ArrayRef<FixItHint> Fixit = None); 8028 8029 protected: 8030 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8031 const char *startSpec, 8032 unsigned specifierLen, 8033 const char *csStart, unsigned csLen); 8034 8035 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8036 const char *startSpec, 8037 unsigned specifierLen); 8038 8039 SourceRange getFormatStringRange(); 8040 CharSourceRange getSpecifierRange(const char *startSpecifier, 8041 unsigned specifierLen); 8042 SourceLocation getLocationOfByte(const char *x); 8043 8044 const Expr *getDataArg(unsigned i) const; 8045 8046 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8047 const analyze_format_string::ConversionSpecifier &CS, 8048 const char *startSpecifier, unsigned specifierLen, 8049 unsigned argIndex); 8050 8051 template <typename Range> 8052 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8053 bool IsStringLocation, Range StringRange, 8054 ArrayRef<FixItHint> Fixit = None); 8055 }; 8056 8057 } // namespace 8058 8059 SourceRange CheckFormatHandler::getFormatStringRange() { 8060 return OrigFormatExpr->getSourceRange(); 8061 } 8062 8063 CharSourceRange CheckFormatHandler:: 8064 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8065 SourceLocation Start = getLocationOfByte(startSpecifier); 8066 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8067 8068 // Advance the end SourceLocation by one due to half-open ranges. 8069 End = End.getLocWithOffset(1); 8070 8071 return CharSourceRange::getCharRange(Start, End); 8072 } 8073 8074 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8075 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8076 S.getLangOpts(), S.Context.getTargetInfo()); 8077 } 8078 8079 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8080 unsigned specifierLen){ 8081 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8082 getLocationOfByte(startSpecifier), 8083 /*IsStringLocation*/true, 8084 getSpecifierRange(startSpecifier, specifierLen)); 8085 } 8086 8087 void CheckFormatHandler::HandleInvalidLengthModifier( 8088 const analyze_format_string::FormatSpecifier &FS, 8089 const analyze_format_string::ConversionSpecifier &CS, 8090 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8091 using namespace analyze_format_string; 8092 8093 const LengthModifier &LM = FS.getLengthModifier(); 8094 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8095 8096 // See if we know how to fix this length modifier. 8097 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8098 if (FixedLM) { 8099 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8100 getLocationOfByte(LM.getStart()), 8101 /*IsStringLocation*/true, 8102 getSpecifierRange(startSpecifier, specifierLen)); 8103 8104 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8105 << FixedLM->toString() 8106 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8107 8108 } else { 8109 FixItHint Hint; 8110 if (DiagID == diag::warn_format_nonsensical_length) 8111 Hint = FixItHint::CreateRemoval(LMRange); 8112 8113 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8114 getLocationOfByte(LM.getStart()), 8115 /*IsStringLocation*/true, 8116 getSpecifierRange(startSpecifier, specifierLen), 8117 Hint); 8118 } 8119 } 8120 8121 void CheckFormatHandler::HandleNonStandardLengthModifier( 8122 const analyze_format_string::FormatSpecifier &FS, 8123 const char *startSpecifier, unsigned specifierLen) { 8124 using namespace analyze_format_string; 8125 8126 const LengthModifier &LM = FS.getLengthModifier(); 8127 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8128 8129 // See if we know how to fix this length modifier. 8130 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8131 if (FixedLM) { 8132 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8133 << LM.toString() << 0, 8134 getLocationOfByte(LM.getStart()), 8135 /*IsStringLocation*/true, 8136 getSpecifierRange(startSpecifier, specifierLen)); 8137 8138 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8139 << FixedLM->toString() 8140 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8141 8142 } else { 8143 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8144 << LM.toString() << 0, 8145 getLocationOfByte(LM.getStart()), 8146 /*IsStringLocation*/true, 8147 getSpecifierRange(startSpecifier, specifierLen)); 8148 } 8149 } 8150 8151 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8152 const analyze_format_string::ConversionSpecifier &CS, 8153 const char *startSpecifier, unsigned specifierLen) { 8154 using namespace analyze_format_string; 8155 8156 // See if we know how to fix this conversion specifier. 8157 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8158 if (FixedCS) { 8159 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8160 << CS.toString() << /*conversion specifier*/1, 8161 getLocationOfByte(CS.getStart()), 8162 /*IsStringLocation*/true, 8163 getSpecifierRange(startSpecifier, specifierLen)); 8164 8165 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8166 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8167 << FixedCS->toString() 8168 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8169 } else { 8170 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8171 << CS.toString() << /*conversion specifier*/1, 8172 getLocationOfByte(CS.getStart()), 8173 /*IsStringLocation*/true, 8174 getSpecifierRange(startSpecifier, specifierLen)); 8175 } 8176 } 8177 8178 void CheckFormatHandler::HandlePosition(const char *startPos, 8179 unsigned posLen) { 8180 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8181 getLocationOfByte(startPos), 8182 /*IsStringLocation*/true, 8183 getSpecifierRange(startPos, posLen)); 8184 } 8185 8186 void 8187 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8188 analyze_format_string::PositionContext p) { 8189 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8190 << (unsigned) p, 8191 getLocationOfByte(startPos), /*IsStringLocation*/true, 8192 getSpecifierRange(startPos, posLen)); 8193 } 8194 8195 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8196 unsigned posLen) { 8197 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8198 getLocationOfByte(startPos), 8199 /*IsStringLocation*/true, 8200 getSpecifierRange(startPos, posLen)); 8201 } 8202 8203 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8204 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8205 // The presence of a null character is likely an error. 8206 EmitFormatDiagnostic( 8207 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8208 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8209 getFormatStringRange()); 8210 } 8211 } 8212 8213 // Note that this may return NULL if there was an error parsing or building 8214 // one of the argument expressions. 8215 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8216 return Args[FirstDataArg + i]; 8217 } 8218 8219 void CheckFormatHandler::DoneProcessing() { 8220 // Does the number of data arguments exceed the number of 8221 // format conversions in the format string? 8222 if (!HasVAListArg) { 8223 // Find any arguments that weren't covered. 8224 CoveredArgs.flip(); 8225 signed notCoveredArg = CoveredArgs.find_first(); 8226 if (notCoveredArg >= 0) { 8227 assert((unsigned)notCoveredArg < NumDataArgs); 8228 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8229 } else { 8230 UncoveredArg.setAllCovered(); 8231 } 8232 } 8233 } 8234 8235 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8236 const Expr *ArgExpr) { 8237 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8238 "Invalid state"); 8239 8240 if (!ArgExpr) 8241 return; 8242 8243 SourceLocation Loc = ArgExpr->getBeginLoc(); 8244 8245 if (S.getSourceManager().isInSystemMacro(Loc)) 8246 return; 8247 8248 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8249 for (auto E : DiagnosticExprs) 8250 PDiag << E->getSourceRange(); 8251 8252 CheckFormatHandler::EmitFormatDiagnostic( 8253 S, IsFunctionCall, DiagnosticExprs[0], 8254 PDiag, Loc, /*IsStringLocation*/false, 8255 DiagnosticExprs[0]->getSourceRange()); 8256 } 8257 8258 bool 8259 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8260 SourceLocation Loc, 8261 const char *startSpec, 8262 unsigned specifierLen, 8263 const char *csStart, 8264 unsigned csLen) { 8265 bool keepGoing = true; 8266 if (argIndex < NumDataArgs) { 8267 // Consider the argument coverered, even though the specifier doesn't 8268 // make sense. 8269 CoveredArgs.set(argIndex); 8270 } 8271 else { 8272 // If argIndex exceeds the number of data arguments we 8273 // don't issue a warning because that is just a cascade of warnings (and 8274 // they may have intended '%%' anyway). We don't want to continue processing 8275 // the format string after this point, however, as we will like just get 8276 // gibberish when trying to match arguments. 8277 keepGoing = false; 8278 } 8279 8280 StringRef Specifier(csStart, csLen); 8281 8282 // If the specifier in non-printable, it could be the first byte of a UTF-8 8283 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8284 // hex value. 8285 std::string CodePointStr; 8286 if (!llvm::sys::locale::isPrint(*csStart)) { 8287 llvm::UTF32 CodePoint; 8288 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8289 const llvm::UTF8 *E = 8290 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8291 llvm::ConversionResult Result = 8292 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8293 8294 if (Result != llvm::conversionOK) { 8295 unsigned char FirstChar = *csStart; 8296 CodePoint = (llvm::UTF32)FirstChar; 8297 } 8298 8299 llvm::raw_string_ostream OS(CodePointStr); 8300 if (CodePoint < 256) 8301 OS << "\\x" << llvm::format("%02x", CodePoint); 8302 else if (CodePoint <= 0xFFFF) 8303 OS << "\\u" << llvm::format("%04x", CodePoint); 8304 else 8305 OS << "\\U" << llvm::format("%08x", CodePoint); 8306 OS.flush(); 8307 Specifier = CodePointStr; 8308 } 8309 8310 EmitFormatDiagnostic( 8311 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8312 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8313 8314 return keepGoing; 8315 } 8316 8317 void 8318 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8319 const char *startSpec, 8320 unsigned specifierLen) { 8321 EmitFormatDiagnostic( 8322 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8323 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8324 } 8325 8326 bool 8327 CheckFormatHandler::CheckNumArgs( 8328 const analyze_format_string::FormatSpecifier &FS, 8329 const analyze_format_string::ConversionSpecifier &CS, 8330 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8331 8332 if (argIndex >= NumDataArgs) { 8333 PartialDiagnostic PDiag = FS.usesPositionalArg() 8334 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8335 << (argIndex+1) << NumDataArgs) 8336 : S.PDiag(diag::warn_printf_insufficient_data_args); 8337 EmitFormatDiagnostic( 8338 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8339 getSpecifierRange(startSpecifier, specifierLen)); 8340 8341 // Since more arguments than conversion tokens are given, by extension 8342 // all arguments are covered, so mark this as so. 8343 UncoveredArg.setAllCovered(); 8344 return false; 8345 } 8346 return true; 8347 } 8348 8349 template<typename Range> 8350 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8351 SourceLocation Loc, 8352 bool IsStringLocation, 8353 Range StringRange, 8354 ArrayRef<FixItHint> FixIt) { 8355 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8356 Loc, IsStringLocation, StringRange, FixIt); 8357 } 8358 8359 /// If the format string is not within the function call, emit a note 8360 /// so that the function call and string are in diagnostic messages. 8361 /// 8362 /// \param InFunctionCall if true, the format string is within the function 8363 /// call and only one diagnostic message will be produced. Otherwise, an 8364 /// extra note will be emitted pointing to location of the format string. 8365 /// 8366 /// \param ArgumentExpr the expression that is passed as the format string 8367 /// argument in the function call. Used for getting locations when two 8368 /// diagnostics are emitted. 8369 /// 8370 /// \param PDiag the callee should already have provided any strings for the 8371 /// diagnostic message. This function only adds locations and fixits 8372 /// to diagnostics. 8373 /// 8374 /// \param Loc primary location for diagnostic. If two diagnostics are 8375 /// required, one will be at Loc and a new SourceLocation will be created for 8376 /// the other one. 8377 /// 8378 /// \param IsStringLocation if true, Loc points to the format string should be 8379 /// used for the note. Otherwise, Loc points to the argument list and will 8380 /// be used with PDiag. 8381 /// 8382 /// \param StringRange some or all of the string to highlight. This is 8383 /// templated so it can accept either a CharSourceRange or a SourceRange. 8384 /// 8385 /// \param FixIt optional fix it hint for the format string. 8386 template <typename Range> 8387 void CheckFormatHandler::EmitFormatDiagnostic( 8388 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8389 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8390 Range StringRange, ArrayRef<FixItHint> FixIt) { 8391 if (InFunctionCall) { 8392 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8393 D << StringRange; 8394 D << FixIt; 8395 } else { 8396 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8397 << ArgumentExpr->getSourceRange(); 8398 8399 const Sema::SemaDiagnosticBuilder &Note = 8400 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8401 diag::note_format_string_defined); 8402 8403 Note << StringRange; 8404 Note << FixIt; 8405 } 8406 } 8407 8408 //===--- CHECK: Printf format string checking ------------------------------===// 8409 8410 namespace { 8411 8412 class CheckPrintfHandler : public CheckFormatHandler { 8413 public: 8414 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8415 const Expr *origFormatExpr, 8416 const Sema::FormatStringType type, unsigned firstDataArg, 8417 unsigned numDataArgs, bool isObjC, const char *beg, 8418 bool hasVAListArg, ArrayRef<const Expr *> Args, 8419 unsigned formatIdx, bool inFunctionCall, 8420 Sema::VariadicCallType CallType, 8421 llvm::SmallBitVector &CheckedVarArgs, 8422 UncoveredArgHandler &UncoveredArg) 8423 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8424 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8425 inFunctionCall, CallType, CheckedVarArgs, 8426 UncoveredArg) {} 8427 8428 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8429 8430 /// Returns true if '%@' specifiers are allowed in the format string. 8431 bool allowsObjCArg() const { 8432 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8433 FSType == Sema::FST_OSTrace; 8434 } 8435 8436 bool HandleInvalidPrintfConversionSpecifier( 8437 const analyze_printf::PrintfSpecifier &FS, 8438 const char *startSpecifier, 8439 unsigned specifierLen) override; 8440 8441 void handleInvalidMaskType(StringRef MaskType) override; 8442 8443 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8444 const char *startSpecifier, 8445 unsigned specifierLen) override; 8446 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8447 const char *StartSpecifier, 8448 unsigned SpecifierLen, 8449 const Expr *E); 8450 8451 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8452 const char *startSpecifier, unsigned specifierLen); 8453 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8454 const analyze_printf::OptionalAmount &Amt, 8455 unsigned type, 8456 const char *startSpecifier, unsigned specifierLen); 8457 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8458 const analyze_printf::OptionalFlag &flag, 8459 const char *startSpecifier, unsigned specifierLen); 8460 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8461 const analyze_printf::OptionalFlag &ignoredFlag, 8462 const analyze_printf::OptionalFlag &flag, 8463 const char *startSpecifier, unsigned specifierLen); 8464 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8465 const Expr *E); 8466 8467 void HandleEmptyObjCModifierFlag(const char *startFlag, 8468 unsigned flagLen) override; 8469 8470 void HandleInvalidObjCModifierFlag(const char *startFlag, 8471 unsigned flagLen) override; 8472 8473 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8474 const char *flagsEnd, 8475 const char *conversionPosition) 8476 override; 8477 }; 8478 8479 } // namespace 8480 8481 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8482 const analyze_printf::PrintfSpecifier &FS, 8483 const char *startSpecifier, 8484 unsigned specifierLen) { 8485 const analyze_printf::PrintfConversionSpecifier &CS = 8486 FS.getConversionSpecifier(); 8487 8488 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8489 getLocationOfByte(CS.getStart()), 8490 startSpecifier, specifierLen, 8491 CS.getStart(), CS.getLength()); 8492 } 8493 8494 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8495 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8496 } 8497 8498 bool CheckPrintfHandler::HandleAmount( 8499 const analyze_format_string::OptionalAmount &Amt, 8500 unsigned k, const char *startSpecifier, 8501 unsigned specifierLen) { 8502 if (Amt.hasDataArgument()) { 8503 if (!HasVAListArg) { 8504 unsigned argIndex = Amt.getArgIndex(); 8505 if (argIndex >= NumDataArgs) { 8506 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8507 << k, 8508 getLocationOfByte(Amt.getStart()), 8509 /*IsStringLocation*/true, 8510 getSpecifierRange(startSpecifier, specifierLen)); 8511 // Don't do any more checking. We will just emit 8512 // spurious errors. 8513 return false; 8514 } 8515 8516 // Type check the data argument. It should be an 'int'. 8517 // Although not in conformance with C99, we also allow the argument to be 8518 // an 'unsigned int' as that is a reasonably safe case. GCC also 8519 // doesn't emit a warning for that case. 8520 CoveredArgs.set(argIndex); 8521 const Expr *Arg = getDataArg(argIndex); 8522 if (!Arg) 8523 return false; 8524 8525 QualType T = Arg->getType(); 8526 8527 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8528 assert(AT.isValid()); 8529 8530 if (!AT.matchesType(S.Context, T)) { 8531 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8532 << k << AT.getRepresentativeTypeName(S.Context) 8533 << T << Arg->getSourceRange(), 8534 getLocationOfByte(Amt.getStart()), 8535 /*IsStringLocation*/true, 8536 getSpecifierRange(startSpecifier, specifierLen)); 8537 // Don't do any more checking. We will just emit 8538 // spurious errors. 8539 return false; 8540 } 8541 } 8542 } 8543 return true; 8544 } 8545 8546 void CheckPrintfHandler::HandleInvalidAmount( 8547 const analyze_printf::PrintfSpecifier &FS, 8548 const analyze_printf::OptionalAmount &Amt, 8549 unsigned type, 8550 const char *startSpecifier, 8551 unsigned specifierLen) { 8552 const analyze_printf::PrintfConversionSpecifier &CS = 8553 FS.getConversionSpecifier(); 8554 8555 FixItHint fixit = 8556 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8557 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8558 Amt.getConstantLength())) 8559 : FixItHint(); 8560 8561 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8562 << type << CS.toString(), 8563 getLocationOfByte(Amt.getStart()), 8564 /*IsStringLocation*/true, 8565 getSpecifierRange(startSpecifier, specifierLen), 8566 fixit); 8567 } 8568 8569 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8570 const analyze_printf::OptionalFlag &flag, 8571 const char *startSpecifier, 8572 unsigned specifierLen) { 8573 // Warn about pointless flag with a fixit removal. 8574 const analyze_printf::PrintfConversionSpecifier &CS = 8575 FS.getConversionSpecifier(); 8576 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8577 << flag.toString() << CS.toString(), 8578 getLocationOfByte(flag.getPosition()), 8579 /*IsStringLocation*/true, 8580 getSpecifierRange(startSpecifier, specifierLen), 8581 FixItHint::CreateRemoval( 8582 getSpecifierRange(flag.getPosition(), 1))); 8583 } 8584 8585 void CheckPrintfHandler::HandleIgnoredFlag( 8586 const analyze_printf::PrintfSpecifier &FS, 8587 const analyze_printf::OptionalFlag &ignoredFlag, 8588 const analyze_printf::OptionalFlag &flag, 8589 const char *startSpecifier, 8590 unsigned specifierLen) { 8591 // Warn about ignored flag with a fixit removal. 8592 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8593 << ignoredFlag.toString() << flag.toString(), 8594 getLocationOfByte(ignoredFlag.getPosition()), 8595 /*IsStringLocation*/true, 8596 getSpecifierRange(startSpecifier, specifierLen), 8597 FixItHint::CreateRemoval( 8598 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8599 } 8600 8601 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8602 unsigned flagLen) { 8603 // Warn about an empty flag. 8604 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8605 getLocationOfByte(startFlag), 8606 /*IsStringLocation*/true, 8607 getSpecifierRange(startFlag, flagLen)); 8608 } 8609 8610 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8611 unsigned flagLen) { 8612 // Warn about an invalid flag. 8613 auto Range = getSpecifierRange(startFlag, flagLen); 8614 StringRef flag(startFlag, flagLen); 8615 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8616 getLocationOfByte(startFlag), 8617 /*IsStringLocation*/true, 8618 Range, FixItHint::CreateRemoval(Range)); 8619 } 8620 8621 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8622 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8623 // Warn about using '[...]' without a '@' conversion. 8624 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8625 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8626 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8627 getLocationOfByte(conversionPosition), 8628 /*IsStringLocation*/true, 8629 Range, FixItHint::CreateRemoval(Range)); 8630 } 8631 8632 // Determines if the specified is a C++ class or struct containing 8633 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8634 // "c_str()"). 8635 template<typename MemberKind> 8636 static llvm::SmallPtrSet<MemberKind*, 1> 8637 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8638 const RecordType *RT = Ty->getAs<RecordType>(); 8639 llvm::SmallPtrSet<MemberKind*, 1> Results; 8640 8641 if (!RT) 8642 return Results; 8643 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8644 if (!RD || !RD->getDefinition()) 8645 return Results; 8646 8647 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8648 Sema::LookupMemberName); 8649 R.suppressDiagnostics(); 8650 8651 // We just need to include all members of the right kind turned up by the 8652 // filter, at this point. 8653 if (S.LookupQualifiedName(R, RT->getDecl())) 8654 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8655 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8656 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8657 Results.insert(FK); 8658 } 8659 return Results; 8660 } 8661 8662 /// Check if we could call '.c_str()' on an object. 8663 /// 8664 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8665 /// allow the call, or if it would be ambiguous). 8666 bool Sema::hasCStrMethod(const Expr *E) { 8667 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8668 8669 MethodSet Results = 8670 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8671 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8672 MI != ME; ++MI) 8673 if ((*MI)->getMinRequiredArguments() == 0) 8674 return true; 8675 return false; 8676 } 8677 8678 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8679 // better diagnostic if so. AT is assumed to be valid. 8680 // Returns true when a c_str() conversion method is found. 8681 bool CheckPrintfHandler::checkForCStrMembers( 8682 const analyze_printf::ArgType &AT, const Expr *E) { 8683 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8684 8685 MethodSet Results = 8686 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8687 8688 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8689 MI != ME; ++MI) { 8690 const CXXMethodDecl *Method = *MI; 8691 if (Method->getMinRequiredArguments() == 0 && 8692 AT.matchesType(S.Context, Method->getReturnType())) { 8693 // FIXME: Suggest parens if the expression needs them. 8694 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8695 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8696 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8697 return true; 8698 } 8699 } 8700 8701 return false; 8702 } 8703 8704 bool 8705 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8706 &FS, 8707 const char *startSpecifier, 8708 unsigned specifierLen) { 8709 using namespace analyze_format_string; 8710 using namespace analyze_printf; 8711 8712 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8713 8714 if (FS.consumesDataArgument()) { 8715 if (atFirstArg) { 8716 atFirstArg = false; 8717 usesPositionalArgs = FS.usesPositionalArg(); 8718 } 8719 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8720 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8721 startSpecifier, specifierLen); 8722 return false; 8723 } 8724 } 8725 8726 // First check if the field width, precision, and conversion specifier 8727 // have matching data arguments. 8728 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8729 startSpecifier, specifierLen)) { 8730 return false; 8731 } 8732 8733 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8734 startSpecifier, specifierLen)) { 8735 return false; 8736 } 8737 8738 if (!CS.consumesDataArgument()) { 8739 // FIXME: Technically specifying a precision or field width here 8740 // makes no sense. Worth issuing a warning at some point. 8741 return true; 8742 } 8743 8744 // Consume the argument. 8745 unsigned argIndex = FS.getArgIndex(); 8746 if (argIndex < NumDataArgs) { 8747 // The check to see if the argIndex is valid will come later. 8748 // We set the bit here because we may exit early from this 8749 // function if we encounter some other error. 8750 CoveredArgs.set(argIndex); 8751 } 8752 8753 // FreeBSD kernel extensions. 8754 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8755 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8756 // We need at least two arguments. 8757 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8758 return false; 8759 8760 // Claim the second argument. 8761 CoveredArgs.set(argIndex + 1); 8762 8763 // Type check the first argument (int for %b, pointer for %D) 8764 const Expr *Ex = getDataArg(argIndex); 8765 const analyze_printf::ArgType &AT = 8766 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8767 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8768 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8769 EmitFormatDiagnostic( 8770 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8771 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8772 << false << Ex->getSourceRange(), 8773 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8774 getSpecifierRange(startSpecifier, specifierLen)); 8775 8776 // Type check the second argument (char * for both %b and %D) 8777 Ex = getDataArg(argIndex + 1); 8778 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8779 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8780 EmitFormatDiagnostic( 8781 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8782 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8783 << false << Ex->getSourceRange(), 8784 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8785 getSpecifierRange(startSpecifier, specifierLen)); 8786 8787 return true; 8788 } 8789 8790 // Check for using an Objective-C specific conversion specifier 8791 // in a non-ObjC literal. 8792 if (!allowsObjCArg() && CS.isObjCArg()) { 8793 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8794 specifierLen); 8795 } 8796 8797 // %P can only be used with os_log. 8798 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8799 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8800 specifierLen); 8801 } 8802 8803 // %n is not allowed with os_log. 8804 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8805 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8806 getLocationOfByte(CS.getStart()), 8807 /*IsStringLocation*/ false, 8808 getSpecifierRange(startSpecifier, specifierLen)); 8809 8810 return true; 8811 } 8812 8813 // Only scalars are allowed for os_trace. 8814 if (FSType == Sema::FST_OSTrace && 8815 (CS.getKind() == ConversionSpecifier::PArg || 8816 CS.getKind() == ConversionSpecifier::sArg || 8817 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8818 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8819 specifierLen); 8820 } 8821 8822 // Check for use of public/private annotation outside of os_log(). 8823 if (FSType != Sema::FST_OSLog) { 8824 if (FS.isPublic().isSet()) { 8825 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8826 << "public", 8827 getLocationOfByte(FS.isPublic().getPosition()), 8828 /*IsStringLocation*/ false, 8829 getSpecifierRange(startSpecifier, specifierLen)); 8830 } 8831 if (FS.isPrivate().isSet()) { 8832 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8833 << "private", 8834 getLocationOfByte(FS.isPrivate().getPosition()), 8835 /*IsStringLocation*/ false, 8836 getSpecifierRange(startSpecifier, specifierLen)); 8837 } 8838 } 8839 8840 // Check for invalid use of field width 8841 if (!FS.hasValidFieldWidth()) { 8842 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8843 startSpecifier, specifierLen); 8844 } 8845 8846 // Check for invalid use of precision 8847 if (!FS.hasValidPrecision()) { 8848 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8849 startSpecifier, specifierLen); 8850 } 8851 8852 // Precision is mandatory for %P specifier. 8853 if (CS.getKind() == ConversionSpecifier::PArg && 8854 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8855 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8856 getLocationOfByte(startSpecifier), 8857 /*IsStringLocation*/ false, 8858 getSpecifierRange(startSpecifier, specifierLen)); 8859 } 8860 8861 // Check each flag does not conflict with any other component. 8862 if (!FS.hasValidThousandsGroupingPrefix()) 8863 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8864 if (!FS.hasValidLeadingZeros()) 8865 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8866 if (!FS.hasValidPlusPrefix()) 8867 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8868 if (!FS.hasValidSpacePrefix()) 8869 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8870 if (!FS.hasValidAlternativeForm()) 8871 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8872 if (!FS.hasValidLeftJustified()) 8873 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8874 8875 // Check that flags are not ignored by another flag 8876 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8877 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8878 startSpecifier, specifierLen); 8879 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8880 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8881 startSpecifier, specifierLen); 8882 8883 // Check the length modifier is valid with the given conversion specifier. 8884 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8885 S.getLangOpts())) 8886 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8887 diag::warn_format_nonsensical_length); 8888 else if (!FS.hasStandardLengthModifier()) 8889 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8890 else if (!FS.hasStandardLengthConversionCombination()) 8891 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8892 diag::warn_format_non_standard_conversion_spec); 8893 8894 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8895 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8896 8897 // The remaining checks depend on the data arguments. 8898 if (HasVAListArg) 8899 return true; 8900 8901 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8902 return false; 8903 8904 const Expr *Arg = getDataArg(argIndex); 8905 if (!Arg) 8906 return true; 8907 8908 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8909 } 8910 8911 static bool requiresParensToAddCast(const Expr *E) { 8912 // FIXME: We should have a general way to reason about operator 8913 // precedence and whether parens are actually needed here. 8914 // Take care of a few common cases where they aren't. 8915 const Expr *Inside = E->IgnoreImpCasts(); 8916 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8917 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8918 8919 switch (Inside->getStmtClass()) { 8920 case Stmt::ArraySubscriptExprClass: 8921 case Stmt::CallExprClass: 8922 case Stmt::CharacterLiteralClass: 8923 case Stmt::CXXBoolLiteralExprClass: 8924 case Stmt::DeclRefExprClass: 8925 case Stmt::FloatingLiteralClass: 8926 case Stmt::IntegerLiteralClass: 8927 case Stmt::MemberExprClass: 8928 case Stmt::ObjCArrayLiteralClass: 8929 case Stmt::ObjCBoolLiteralExprClass: 8930 case Stmt::ObjCBoxedExprClass: 8931 case Stmt::ObjCDictionaryLiteralClass: 8932 case Stmt::ObjCEncodeExprClass: 8933 case Stmt::ObjCIvarRefExprClass: 8934 case Stmt::ObjCMessageExprClass: 8935 case Stmt::ObjCPropertyRefExprClass: 8936 case Stmt::ObjCStringLiteralClass: 8937 case Stmt::ObjCSubscriptRefExprClass: 8938 case Stmt::ParenExprClass: 8939 case Stmt::StringLiteralClass: 8940 case Stmt::UnaryOperatorClass: 8941 return false; 8942 default: 8943 return true; 8944 } 8945 } 8946 8947 static std::pair<QualType, StringRef> 8948 shouldNotPrintDirectly(const ASTContext &Context, 8949 QualType IntendedTy, 8950 const Expr *E) { 8951 // Use a 'while' to peel off layers of typedefs. 8952 QualType TyTy = IntendedTy; 8953 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8954 StringRef Name = UserTy->getDecl()->getName(); 8955 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8956 .Case("CFIndex", Context.getNSIntegerType()) 8957 .Case("NSInteger", Context.getNSIntegerType()) 8958 .Case("NSUInteger", Context.getNSUIntegerType()) 8959 .Case("SInt32", Context.IntTy) 8960 .Case("UInt32", Context.UnsignedIntTy) 8961 .Default(QualType()); 8962 8963 if (!CastTy.isNull()) 8964 return std::make_pair(CastTy, Name); 8965 8966 TyTy = UserTy->desugar(); 8967 } 8968 8969 // Strip parens if necessary. 8970 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8971 return shouldNotPrintDirectly(Context, 8972 PE->getSubExpr()->getType(), 8973 PE->getSubExpr()); 8974 8975 // If this is a conditional expression, then its result type is constructed 8976 // via usual arithmetic conversions and thus there might be no necessary 8977 // typedef sugar there. Recurse to operands to check for NSInteger & 8978 // Co. usage condition. 8979 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8980 QualType TrueTy, FalseTy; 8981 StringRef TrueName, FalseName; 8982 8983 std::tie(TrueTy, TrueName) = 8984 shouldNotPrintDirectly(Context, 8985 CO->getTrueExpr()->getType(), 8986 CO->getTrueExpr()); 8987 std::tie(FalseTy, FalseName) = 8988 shouldNotPrintDirectly(Context, 8989 CO->getFalseExpr()->getType(), 8990 CO->getFalseExpr()); 8991 8992 if (TrueTy == FalseTy) 8993 return std::make_pair(TrueTy, TrueName); 8994 else if (TrueTy.isNull()) 8995 return std::make_pair(FalseTy, FalseName); 8996 else if (FalseTy.isNull()) 8997 return std::make_pair(TrueTy, TrueName); 8998 } 8999 9000 return std::make_pair(QualType(), StringRef()); 9001 } 9002 9003 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9004 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9005 /// type do not count. 9006 static bool 9007 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9008 QualType From = ICE->getSubExpr()->getType(); 9009 QualType To = ICE->getType(); 9010 // It's an integer promotion if the destination type is the promoted 9011 // source type. 9012 if (ICE->getCastKind() == CK_IntegralCast && 9013 From->isPromotableIntegerType() && 9014 S.Context.getPromotedIntegerType(From) == To) 9015 return true; 9016 // Look through vector types, since we do default argument promotion for 9017 // those in OpenCL. 9018 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9019 From = VecTy->getElementType(); 9020 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9021 To = VecTy->getElementType(); 9022 // It's a floating promotion if the source type is a lower rank. 9023 return ICE->getCastKind() == CK_FloatingCast && 9024 S.Context.getFloatingTypeOrder(From, To) < 0; 9025 } 9026 9027 bool 9028 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9029 const char *StartSpecifier, 9030 unsigned SpecifierLen, 9031 const Expr *E) { 9032 using namespace analyze_format_string; 9033 using namespace analyze_printf; 9034 9035 // Now type check the data expression that matches the 9036 // format specifier. 9037 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9038 if (!AT.isValid()) 9039 return true; 9040 9041 QualType ExprTy = E->getType(); 9042 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9043 ExprTy = TET->getUnderlyingExpr()->getType(); 9044 } 9045 9046 // Diagnose attempts to print a boolean value as a character. Unlike other 9047 // -Wformat diagnostics, this is fine from a type perspective, but it still 9048 // doesn't make sense. 9049 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9050 E->isKnownToHaveBooleanValue()) { 9051 const CharSourceRange &CSR = 9052 getSpecifierRange(StartSpecifier, SpecifierLen); 9053 SmallString<4> FSString; 9054 llvm::raw_svector_ostream os(FSString); 9055 FS.toString(os); 9056 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9057 << FSString, 9058 E->getExprLoc(), false, CSR); 9059 return true; 9060 } 9061 9062 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9063 if (Match == analyze_printf::ArgType::Match) 9064 return true; 9065 9066 // Look through argument promotions for our error message's reported type. 9067 // This includes the integral and floating promotions, but excludes array 9068 // and function pointer decay (seeing that an argument intended to be a 9069 // string has type 'char [6]' is probably more confusing than 'char *') and 9070 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9071 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9072 if (isArithmeticArgumentPromotion(S, ICE)) { 9073 E = ICE->getSubExpr(); 9074 ExprTy = E->getType(); 9075 9076 // Check if we didn't match because of an implicit cast from a 'char' 9077 // or 'short' to an 'int'. This is done because printf is a varargs 9078 // function. 9079 if (ICE->getType() == S.Context.IntTy || 9080 ICE->getType() == S.Context.UnsignedIntTy) { 9081 // All further checking is done on the subexpression 9082 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9083 AT.matchesType(S.Context, ExprTy); 9084 if (ImplicitMatch == analyze_printf::ArgType::Match) 9085 return true; 9086 if (ImplicitMatch == ArgType::NoMatchPedantic || 9087 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9088 Match = ImplicitMatch; 9089 } 9090 } 9091 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9092 // Special case for 'a', which has type 'int' in C. 9093 // Note, however, that we do /not/ want to treat multibyte constants like 9094 // 'MooV' as characters! This form is deprecated but still exists. In 9095 // addition, don't treat expressions as of type 'char' if one byte length 9096 // modifier is provided. 9097 if (ExprTy == S.Context.IntTy && 9098 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9099 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9100 ExprTy = S.Context.CharTy; 9101 } 9102 9103 // Look through enums to their underlying type. 9104 bool IsEnum = false; 9105 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9106 ExprTy = EnumTy->getDecl()->getIntegerType(); 9107 IsEnum = true; 9108 } 9109 9110 // %C in an Objective-C context prints a unichar, not a wchar_t. 9111 // If the argument is an integer of some kind, believe the %C and suggest 9112 // a cast instead of changing the conversion specifier. 9113 QualType IntendedTy = ExprTy; 9114 if (isObjCContext() && 9115 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9116 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9117 !ExprTy->isCharType()) { 9118 // 'unichar' is defined as a typedef of unsigned short, but we should 9119 // prefer using the typedef if it is visible. 9120 IntendedTy = S.Context.UnsignedShortTy; 9121 9122 // While we are here, check if the value is an IntegerLiteral that happens 9123 // to be within the valid range. 9124 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9125 const llvm::APInt &V = IL->getValue(); 9126 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9127 return true; 9128 } 9129 9130 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9131 Sema::LookupOrdinaryName); 9132 if (S.LookupName(Result, S.getCurScope())) { 9133 NamedDecl *ND = Result.getFoundDecl(); 9134 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9135 if (TD->getUnderlyingType() == IntendedTy) 9136 IntendedTy = S.Context.getTypedefType(TD); 9137 } 9138 } 9139 } 9140 9141 // Special-case some of Darwin's platform-independence types by suggesting 9142 // casts to primitive types that are known to be large enough. 9143 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9144 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9145 QualType CastTy; 9146 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9147 if (!CastTy.isNull()) { 9148 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9149 // (long in ASTContext). Only complain to pedants. 9150 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9151 (AT.isSizeT() || AT.isPtrdiffT()) && 9152 AT.matchesType(S.Context, CastTy)) 9153 Match = ArgType::NoMatchPedantic; 9154 IntendedTy = CastTy; 9155 ShouldNotPrintDirectly = true; 9156 } 9157 } 9158 9159 // We may be able to offer a FixItHint if it is a supported type. 9160 PrintfSpecifier fixedFS = FS; 9161 bool Success = 9162 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9163 9164 if (Success) { 9165 // Get the fix string from the fixed format specifier 9166 SmallString<16> buf; 9167 llvm::raw_svector_ostream os(buf); 9168 fixedFS.toString(os); 9169 9170 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9171 9172 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9173 unsigned Diag; 9174 switch (Match) { 9175 case ArgType::Match: llvm_unreachable("expected non-matching"); 9176 case ArgType::NoMatchPedantic: 9177 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9178 break; 9179 case ArgType::NoMatchTypeConfusion: 9180 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9181 break; 9182 case ArgType::NoMatch: 9183 Diag = diag::warn_format_conversion_argument_type_mismatch; 9184 break; 9185 } 9186 9187 // In this case, the specifier is wrong and should be changed to match 9188 // the argument. 9189 EmitFormatDiagnostic(S.PDiag(Diag) 9190 << AT.getRepresentativeTypeName(S.Context) 9191 << IntendedTy << IsEnum << E->getSourceRange(), 9192 E->getBeginLoc(), 9193 /*IsStringLocation*/ false, SpecRange, 9194 FixItHint::CreateReplacement(SpecRange, os.str())); 9195 } else { 9196 // The canonical type for formatting this value is different from the 9197 // actual type of the expression. (This occurs, for example, with Darwin's 9198 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9199 // should be printed as 'long' for 64-bit compatibility.) 9200 // Rather than emitting a normal format/argument mismatch, we want to 9201 // add a cast to the recommended type (and correct the format string 9202 // if necessary). 9203 SmallString<16> CastBuf; 9204 llvm::raw_svector_ostream CastFix(CastBuf); 9205 CastFix << "("; 9206 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9207 CastFix << ")"; 9208 9209 SmallVector<FixItHint,4> Hints; 9210 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9211 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9212 9213 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9214 // If there's already a cast present, just replace it. 9215 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9216 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9217 9218 } else if (!requiresParensToAddCast(E)) { 9219 // If the expression has high enough precedence, 9220 // just write the C-style cast. 9221 Hints.push_back( 9222 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9223 } else { 9224 // Otherwise, add parens around the expression as well as the cast. 9225 CastFix << "("; 9226 Hints.push_back( 9227 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9228 9229 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9230 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9231 } 9232 9233 if (ShouldNotPrintDirectly) { 9234 // The expression has a type that should not be printed directly. 9235 // We extract the name from the typedef because we don't want to show 9236 // the underlying type in the diagnostic. 9237 StringRef Name; 9238 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9239 Name = TypedefTy->getDecl()->getName(); 9240 else 9241 Name = CastTyName; 9242 unsigned Diag = Match == ArgType::NoMatchPedantic 9243 ? diag::warn_format_argument_needs_cast_pedantic 9244 : diag::warn_format_argument_needs_cast; 9245 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9246 << E->getSourceRange(), 9247 E->getBeginLoc(), /*IsStringLocation=*/false, 9248 SpecRange, Hints); 9249 } else { 9250 // In this case, the expression could be printed using a different 9251 // specifier, but we've decided that the specifier is probably correct 9252 // and we should cast instead. Just use the normal warning message. 9253 EmitFormatDiagnostic( 9254 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9255 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9256 << E->getSourceRange(), 9257 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9258 } 9259 } 9260 } else { 9261 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9262 SpecifierLen); 9263 // Since the warning for passing non-POD types to variadic functions 9264 // was deferred until now, we emit a warning for non-POD 9265 // arguments here. 9266 switch (S.isValidVarArgType(ExprTy)) { 9267 case Sema::VAK_Valid: 9268 case Sema::VAK_ValidInCXX11: { 9269 unsigned Diag; 9270 switch (Match) { 9271 case ArgType::Match: llvm_unreachable("expected non-matching"); 9272 case ArgType::NoMatchPedantic: 9273 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9274 break; 9275 case ArgType::NoMatchTypeConfusion: 9276 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9277 break; 9278 case ArgType::NoMatch: 9279 Diag = diag::warn_format_conversion_argument_type_mismatch; 9280 break; 9281 } 9282 9283 EmitFormatDiagnostic( 9284 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9285 << IsEnum << CSR << E->getSourceRange(), 9286 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9287 break; 9288 } 9289 case Sema::VAK_Undefined: 9290 case Sema::VAK_MSVCUndefined: 9291 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9292 << S.getLangOpts().CPlusPlus11 << ExprTy 9293 << CallType 9294 << AT.getRepresentativeTypeName(S.Context) << CSR 9295 << E->getSourceRange(), 9296 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9297 checkForCStrMembers(AT, E); 9298 break; 9299 9300 case Sema::VAK_Invalid: 9301 if (ExprTy->isObjCObjectType()) 9302 EmitFormatDiagnostic( 9303 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9304 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9305 << AT.getRepresentativeTypeName(S.Context) << CSR 9306 << E->getSourceRange(), 9307 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9308 else 9309 // FIXME: If this is an initializer list, suggest removing the braces 9310 // or inserting a cast to the target type. 9311 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9312 << isa<InitListExpr>(E) << ExprTy << CallType 9313 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9314 break; 9315 } 9316 9317 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9318 "format string specifier index out of range"); 9319 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9320 } 9321 9322 return true; 9323 } 9324 9325 //===--- CHECK: Scanf format string checking ------------------------------===// 9326 9327 namespace { 9328 9329 class CheckScanfHandler : public CheckFormatHandler { 9330 public: 9331 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9332 const Expr *origFormatExpr, Sema::FormatStringType type, 9333 unsigned firstDataArg, unsigned numDataArgs, 9334 const char *beg, bool hasVAListArg, 9335 ArrayRef<const Expr *> Args, unsigned formatIdx, 9336 bool inFunctionCall, Sema::VariadicCallType CallType, 9337 llvm::SmallBitVector &CheckedVarArgs, 9338 UncoveredArgHandler &UncoveredArg) 9339 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9340 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9341 inFunctionCall, CallType, CheckedVarArgs, 9342 UncoveredArg) {} 9343 9344 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9345 const char *startSpecifier, 9346 unsigned specifierLen) override; 9347 9348 bool HandleInvalidScanfConversionSpecifier( 9349 const analyze_scanf::ScanfSpecifier &FS, 9350 const char *startSpecifier, 9351 unsigned specifierLen) override; 9352 9353 void HandleIncompleteScanList(const char *start, const char *end) override; 9354 }; 9355 9356 } // namespace 9357 9358 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9359 const char *end) { 9360 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9361 getLocationOfByte(end), /*IsStringLocation*/true, 9362 getSpecifierRange(start, end - start)); 9363 } 9364 9365 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9366 const analyze_scanf::ScanfSpecifier &FS, 9367 const char *startSpecifier, 9368 unsigned specifierLen) { 9369 const analyze_scanf::ScanfConversionSpecifier &CS = 9370 FS.getConversionSpecifier(); 9371 9372 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9373 getLocationOfByte(CS.getStart()), 9374 startSpecifier, specifierLen, 9375 CS.getStart(), CS.getLength()); 9376 } 9377 9378 bool CheckScanfHandler::HandleScanfSpecifier( 9379 const analyze_scanf::ScanfSpecifier &FS, 9380 const char *startSpecifier, 9381 unsigned specifierLen) { 9382 using namespace analyze_scanf; 9383 using namespace analyze_format_string; 9384 9385 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9386 9387 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9388 // be used to decide if we are using positional arguments consistently. 9389 if (FS.consumesDataArgument()) { 9390 if (atFirstArg) { 9391 atFirstArg = false; 9392 usesPositionalArgs = FS.usesPositionalArg(); 9393 } 9394 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9395 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9396 startSpecifier, specifierLen); 9397 return false; 9398 } 9399 } 9400 9401 // Check if the field with is non-zero. 9402 const OptionalAmount &Amt = FS.getFieldWidth(); 9403 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9404 if (Amt.getConstantAmount() == 0) { 9405 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9406 Amt.getConstantLength()); 9407 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9408 getLocationOfByte(Amt.getStart()), 9409 /*IsStringLocation*/true, R, 9410 FixItHint::CreateRemoval(R)); 9411 } 9412 } 9413 9414 if (!FS.consumesDataArgument()) { 9415 // FIXME: Technically specifying a precision or field width here 9416 // makes no sense. Worth issuing a warning at some point. 9417 return true; 9418 } 9419 9420 // Consume the argument. 9421 unsigned argIndex = FS.getArgIndex(); 9422 if (argIndex < NumDataArgs) { 9423 // The check to see if the argIndex is valid will come later. 9424 // We set the bit here because we may exit early from this 9425 // function if we encounter some other error. 9426 CoveredArgs.set(argIndex); 9427 } 9428 9429 // Check the length modifier is valid with the given conversion specifier. 9430 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9431 S.getLangOpts())) 9432 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9433 diag::warn_format_nonsensical_length); 9434 else if (!FS.hasStandardLengthModifier()) 9435 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9436 else if (!FS.hasStandardLengthConversionCombination()) 9437 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9438 diag::warn_format_non_standard_conversion_spec); 9439 9440 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9441 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9442 9443 // The remaining checks depend on the data arguments. 9444 if (HasVAListArg) 9445 return true; 9446 9447 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9448 return false; 9449 9450 // Check that the argument type matches the format specifier. 9451 const Expr *Ex = getDataArg(argIndex); 9452 if (!Ex) 9453 return true; 9454 9455 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9456 9457 if (!AT.isValid()) { 9458 return true; 9459 } 9460 9461 analyze_format_string::ArgType::MatchKind Match = 9462 AT.matchesType(S.Context, Ex->getType()); 9463 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9464 if (Match == analyze_format_string::ArgType::Match) 9465 return true; 9466 9467 ScanfSpecifier fixedFS = FS; 9468 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9469 S.getLangOpts(), S.Context); 9470 9471 unsigned Diag = 9472 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9473 : diag::warn_format_conversion_argument_type_mismatch; 9474 9475 if (Success) { 9476 // Get the fix string from the fixed format specifier. 9477 SmallString<128> buf; 9478 llvm::raw_svector_ostream os(buf); 9479 fixedFS.toString(os); 9480 9481 EmitFormatDiagnostic( 9482 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9483 << Ex->getType() << false << Ex->getSourceRange(), 9484 Ex->getBeginLoc(), 9485 /*IsStringLocation*/ false, 9486 getSpecifierRange(startSpecifier, specifierLen), 9487 FixItHint::CreateReplacement( 9488 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9489 } else { 9490 EmitFormatDiagnostic(S.PDiag(Diag) 9491 << AT.getRepresentativeTypeName(S.Context) 9492 << Ex->getType() << false << Ex->getSourceRange(), 9493 Ex->getBeginLoc(), 9494 /*IsStringLocation*/ false, 9495 getSpecifierRange(startSpecifier, specifierLen)); 9496 } 9497 9498 return true; 9499 } 9500 9501 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9502 const Expr *OrigFormatExpr, 9503 ArrayRef<const Expr *> Args, 9504 bool HasVAListArg, unsigned format_idx, 9505 unsigned firstDataArg, 9506 Sema::FormatStringType Type, 9507 bool inFunctionCall, 9508 Sema::VariadicCallType CallType, 9509 llvm::SmallBitVector &CheckedVarArgs, 9510 UncoveredArgHandler &UncoveredArg, 9511 bool IgnoreStringsWithoutSpecifiers) { 9512 // CHECK: is the format string a wide literal? 9513 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9514 CheckFormatHandler::EmitFormatDiagnostic( 9515 S, inFunctionCall, Args[format_idx], 9516 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9517 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9518 return; 9519 } 9520 9521 // Str - The format string. NOTE: this is NOT null-terminated! 9522 StringRef StrRef = FExpr->getString(); 9523 const char *Str = StrRef.data(); 9524 // Account for cases where the string literal is truncated in a declaration. 9525 const ConstantArrayType *T = 9526 S.Context.getAsConstantArrayType(FExpr->getType()); 9527 assert(T && "String literal not of constant array type!"); 9528 size_t TypeSize = T->getSize().getZExtValue(); 9529 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9530 const unsigned numDataArgs = Args.size() - firstDataArg; 9531 9532 if (IgnoreStringsWithoutSpecifiers && 9533 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9534 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9535 return; 9536 9537 // Emit a warning if the string literal is truncated and does not contain an 9538 // embedded null character. 9539 if (TypeSize <= StrRef.size() && 9540 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9541 CheckFormatHandler::EmitFormatDiagnostic( 9542 S, inFunctionCall, Args[format_idx], 9543 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9544 FExpr->getBeginLoc(), 9545 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9546 return; 9547 } 9548 9549 // CHECK: empty format string? 9550 if (StrLen == 0 && numDataArgs > 0) { 9551 CheckFormatHandler::EmitFormatDiagnostic( 9552 S, inFunctionCall, Args[format_idx], 9553 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9554 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9555 return; 9556 } 9557 9558 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9559 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9560 Type == Sema::FST_OSTrace) { 9561 CheckPrintfHandler H( 9562 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9563 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9564 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9565 CheckedVarArgs, UncoveredArg); 9566 9567 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9568 S.getLangOpts(), 9569 S.Context.getTargetInfo(), 9570 Type == Sema::FST_FreeBSDKPrintf)) 9571 H.DoneProcessing(); 9572 } else if (Type == Sema::FST_Scanf) { 9573 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9574 numDataArgs, Str, HasVAListArg, Args, format_idx, 9575 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9576 9577 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9578 S.getLangOpts(), 9579 S.Context.getTargetInfo())) 9580 H.DoneProcessing(); 9581 } // TODO: handle other formats 9582 } 9583 9584 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9585 // Str - The format string. NOTE: this is NOT null-terminated! 9586 StringRef StrRef = FExpr->getString(); 9587 const char *Str = StrRef.data(); 9588 // Account for cases where the string literal is truncated in a declaration. 9589 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9590 assert(T && "String literal not of constant array type!"); 9591 size_t TypeSize = T->getSize().getZExtValue(); 9592 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9593 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9594 getLangOpts(), 9595 Context.getTargetInfo()); 9596 } 9597 9598 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9599 9600 // Returns the related absolute value function that is larger, of 0 if one 9601 // does not exist. 9602 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9603 switch (AbsFunction) { 9604 default: 9605 return 0; 9606 9607 case Builtin::BI__builtin_abs: 9608 return Builtin::BI__builtin_labs; 9609 case Builtin::BI__builtin_labs: 9610 return Builtin::BI__builtin_llabs; 9611 case Builtin::BI__builtin_llabs: 9612 return 0; 9613 9614 case Builtin::BI__builtin_fabsf: 9615 return Builtin::BI__builtin_fabs; 9616 case Builtin::BI__builtin_fabs: 9617 return Builtin::BI__builtin_fabsl; 9618 case Builtin::BI__builtin_fabsl: 9619 return 0; 9620 9621 case Builtin::BI__builtin_cabsf: 9622 return Builtin::BI__builtin_cabs; 9623 case Builtin::BI__builtin_cabs: 9624 return Builtin::BI__builtin_cabsl; 9625 case Builtin::BI__builtin_cabsl: 9626 return 0; 9627 9628 case Builtin::BIabs: 9629 return Builtin::BIlabs; 9630 case Builtin::BIlabs: 9631 return Builtin::BIllabs; 9632 case Builtin::BIllabs: 9633 return 0; 9634 9635 case Builtin::BIfabsf: 9636 return Builtin::BIfabs; 9637 case Builtin::BIfabs: 9638 return Builtin::BIfabsl; 9639 case Builtin::BIfabsl: 9640 return 0; 9641 9642 case Builtin::BIcabsf: 9643 return Builtin::BIcabs; 9644 case Builtin::BIcabs: 9645 return Builtin::BIcabsl; 9646 case Builtin::BIcabsl: 9647 return 0; 9648 } 9649 } 9650 9651 // Returns the argument type of the absolute value function. 9652 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9653 unsigned AbsType) { 9654 if (AbsType == 0) 9655 return QualType(); 9656 9657 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9658 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9659 if (Error != ASTContext::GE_None) 9660 return QualType(); 9661 9662 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9663 if (!FT) 9664 return QualType(); 9665 9666 if (FT->getNumParams() != 1) 9667 return QualType(); 9668 9669 return FT->getParamType(0); 9670 } 9671 9672 // Returns the best absolute value function, or zero, based on type and 9673 // current absolute value function. 9674 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9675 unsigned AbsFunctionKind) { 9676 unsigned BestKind = 0; 9677 uint64_t ArgSize = Context.getTypeSize(ArgType); 9678 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9679 Kind = getLargerAbsoluteValueFunction(Kind)) { 9680 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9681 if (Context.getTypeSize(ParamType) >= ArgSize) { 9682 if (BestKind == 0) 9683 BestKind = Kind; 9684 else if (Context.hasSameType(ParamType, ArgType)) { 9685 BestKind = Kind; 9686 break; 9687 } 9688 } 9689 } 9690 return BestKind; 9691 } 9692 9693 enum AbsoluteValueKind { 9694 AVK_Integer, 9695 AVK_Floating, 9696 AVK_Complex 9697 }; 9698 9699 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9700 if (T->isIntegralOrEnumerationType()) 9701 return AVK_Integer; 9702 if (T->isRealFloatingType()) 9703 return AVK_Floating; 9704 if (T->isAnyComplexType()) 9705 return AVK_Complex; 9706 9707 llvm_unreachable("Type not integer, floating, or complex"); 9708 } 9709 9710 // Changes the absolute value function to a different type. Preserves whether 9711 // the function is a builtin. 9712 static unsigned changeAbsFunction(unsigned AbsKind, 9713 AbsoluteValueKind ValueKind) { 9714 switch (ValueKind) { 9715 case AVK_Integer: 9716 switch (AbsKind) { 9717 default: 9718 return 0; 9719 case Builtin::BI__builtin_fabsf: 9720 case Builtin::BI__builtin_fabs: 9721 case Builtin::BI__builtin_fabsl: 9722 case Builtin::BI__builtin_cabsf: 9723 case Builtin::BI__builtin_cabs: 9724 case Builtin::BI__builtin_cabsl: 9725 return Builtin::BI__builtin_abs; 9726 case Builtin::BIfabsf: 9727 case Builtin::BIfabs: 9728 case Builtin::BIfabsl: 9729 case Builtin::BIcabsf: 9730 case Builtin::BIcabs: 9731 case Builtin::BIcabsl: 9732 return Builtin::BIabs; 9733 } 9734 case AVK_Floating: 9735 switch (AbsKind) { 9736 default: 9737 return 0; 9738 case Builtin::BI__builtin_abs: 9739 case Builtin::BI__builtin_labs: 9740 case Builtin::BI__builtin_llabs: 9741 case Builtin::BI__builtin_cabsf: 9742 case Builtin::BI__builtin_cabs: 9743 case Builtin::BI__builtin_cabsl: 9744 return Builtin::BI__builtin_fabsf; 9745 case Builtin::BIabs: 9746 case Builtin::BIlabs: 9747 case Builtin::BIllabs: 9748 case Builtin::BIcabsf: 9749 case Builtin::BIcabs: 9750 case Builtin::BIcabsl: 9751 return Builtin::BIfabsf; 9752 } 9753 case AVK_Complex: 9754 switch (AbsKind) { 9755 default: 9756 return 0; 9757 case Builtin::BI__builtin_abs: 9758 case Builtin::BI__builtin_labs: 9759 case Builtin::BI__builtin_llabs: 9760 case Builtin::BI__builtin_fabsf: 9761 case Builtin::BI__builtin_fabs: 9762 case Builtin::BI__builtin_fabsl: 9763 return Builtin::BI__builtin_cabsf; 9764 case Builtin::BIabs: 9765 case Builtin::BIlabs: 9766 case Builtin::BIllabs: 9767 case Builtin::BIfabsf: 9768 case Builtin::BIfabs: 9769 case Builtin::BIfabsl: 9770 return Builtin::BIcabsf; 9771 } 9772 } 9773 llvm_unreachable("Unable to convert function"); 9774 } 9775 9776 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9777 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9778 if (!FnInfo) 9779 return 0; 9780 9781 switch (FDecl->getBuiltinID()) { 9782 default: 9783 return 0; 9784 case Builtin::BI__builtin_abs: 9785 case Builtin::BI__builtin_fabs: 9786 case Builtin::BI__builtin_fabsf: 9787 case Builtin::BI__builtin_fabsl: 9788 case Builtin::BI__builtin_labs: 9789 case Builtin::BI__builtin_llabs: 9790 case Builtin::BI__builtin_cabs: 9791 case Builtin::BI__builtin_cabsf: 9792 case Builtin::BI__builtin_cabsl: 9793 case Builtin::BIabs: 9794 case Builtin::BIlabs: 9795 case Builtin::BIllabs: 9796 case Builtin::BIfabs: 9797 case Builtin::BIfabsf: 9798 case Builtin::BIfabsl: 9799 case Builtin::BIcabs: 9800 case Builtin::BIcabsf: 9801 case Builtin::BIcabsl: 9802 return FDecl->getBuiltinID(); 9803 } 9804 llvm_unreachable("Unknown Builtin type"); 9805 } 9806 9807 // If the replacement is valid, emit a note with replacement function. 9808 // Additionally, suggest including the proper header if not already included. 9809 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9810 unsigned AbsKind, QualType ArgType) { 9811 bool EmitHeaderHint = true; 9812 const char *HeaderName = nullptr; 9813 const char *FunctionName = nullptr; 9814 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9815 FunctionName = "std::abs"; 9816 if (ArgType->isIntegralOrEnumerationType()) { 9817 HeaderName = "cstdlib"; 9818 } else if (ArgType->isRealFloatingType()) { 9819 HeaderName = "cmath"; 9820 } else { 9821 llvm_unreachable("Invalid Type"); 9822 } 9823 9824 // Lookup all std::abs 9825 if (NamespaceDecl *Std = S.getStdNamespace()) { 9826 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9827 R.suppressDiagnostics(); 9828 S.LookupQualifiedName(R, Std); 9829 9830 for (const auto *I : R) { 9831 const FunctionDecl *FDecl = nullptr; 9832 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9833 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9834 } else { 9835 FDecl = dyn_cast<FunctionDecl>(I); 9836 } 9837 if (!FDecl) 9838 continue; 9839 9840 // Found std::abs(), check that they are the right ones. 9841 if (FDecl->getNumParams() != 1) 9842 continue; 9843 9844 // Check that the parameter type can handle the argument. 9845 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9846 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9847 S.Context.getTypeSize(ArgType) <= 9848 S.Context.getTypeSize(ParamType)) { 9849 // Found a function, don't need the header hint. 9850 EmitHeaderHint = false; 9851 break; 9852 } 9853 } 9854 } 9855 } else { 9856 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9857 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9858 9859 if (HeaderName) { 9860 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9861 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9862 R.suppressDiagnostics(); 9863 S.LookupName(R, S.getCurScope()); 9864 9865 if (R.isSingleResult()) { 9866 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9867 if (FD && FD->getBuiltinID() == AbsKind) { 9868 EmitHeaderHint = false; 9869 } else { 9870 return; 9871 } 9872 } else if (!R.empty()) { 9873 return; 9874 } 9875 } 9876 } 9877 9878 S.Diag(Loc, diag::note_replace_abs_function) 9879 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9880 9881 if (!HeaderName) 9882 return; 9883 9884 if (!EmitHeaderHint) 9885 return; 9886 9887 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9888 << FunctionName; 9889 } 9890 9891 template <std::size_t StrLen> 9892 static bool IsStdFunction(const FunctionDecl *FDecl, 9893 const char (&Str)[StrLen]) { 9894 if (!FDecl) 9895 return false; 9896 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9897 return false; 9898 if (!FDecl->isInStdNamespace()) 9899 return false; 9900 9901 return true; 9902 } 9903 9904 // Warn when using the wrong abs() function. 9905 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9906 const FunctionDecl *FDecl) { 9907 if (Call->getNumArgs() != 1) 9908 return; 9909 9910 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9911 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9912 if (AbsKind == 0 && !IsStdAbs) 9913 return; 9914 9915 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9916 QualType ParamType = Call->getArg(0)->getType(); 9917 9918 // Unsigned types cannot be negative. Suggest removing the absolute value 9919 // function call. 9920 if (ArgType->isUnsignedIntegerType()) { 9921 const char *FunctionName = 9922 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9923 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9924 Diag(Call->getExprLoc(), diag::note_remove_abs) 9925 << FunctionName 9926 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9927 return; 9928 } 9929 9930 // Taking the absolute value of a pointer is very suspicious, they probably 9931 // wanted to index into an array, dereference a pointer, call a function, etc. 9932 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9933 unsigned DiagType = 0; 9934 if (ArgType->isFunctionType()) 9935 DiagType = 1; 9936 else if (ArgType->isArrayType()) 9937 DiagType = 2; 9938 9939 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9940 return; 9941 } 9942 9943 // std::abs has overloads which prevent most of the absolute value problems 9944 // from occurring. 9945 if (IsStdAbs) 9946 return; 9947 9948 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9949 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9950 9951 // The argument and parameter are the same kind. Check if they are the right 9952 // size. 9953 if (ArgValueKind == ParamValueKind) { 9954 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9955 return; 9956 9957 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9958 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9959 << FDecl << ArgType << ParamType; 9960 9961 if (NewAbsKind == 0) 9962 return; 9963 9964 emitReplacement(*this, Call->getExprLoc(), 9965 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9966 return; 9967 } 9968 9969 // ArgValueKind != ParamValueKind 9970 // The wrong type of absolute value function was used. Attempt to find the 9971 // proper one. 9972 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9973 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9974 if (NewAbsKind == 0) 9975 return; 9976 9977 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9978 << FDecl << ParamValueKind << ArgValueKind; 9979 9980 emitReplacement(*this, Call->getExprLoc(), 9981 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9982 } 9983 9984 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9985 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9986 const FunctionDecl *FDecl) { 9987 if (!Call || !FDecl) return; 9988 9989 // Ignore template specializations and macros. 9990 if (inTemplateInstantiation()) return; 9991 if (Call->getExprLoc().isMacroID()) return; 9992 9993 // Only care about the one template argument, two function parameter std::max 9994 if (Call->getNumArgs() != 2) return; 9995 if (!IsStdFunction(FDecl, "max")) return; 9996 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9997 if (!ArgList) return; 9998 if (ArgList->size() != 1) return; 9999 10000 // Check that template type argument is unsigned integer. 10001 const auto& TA = ArgList->get(0); 10002 if (TA.getKind() != TemplateArgument::Type) return; 10003 QualType ArgType = TA.getAsType(); 10004 if (!ArgType->isUnsignedIntegerType()) return; 10005 10006 // See if either argument is a literal zero. 10007 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10008 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10009 if (!MTE) return false; 10010 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10011 if (!Num) return false; 10012 if (Num->getValue() != 0) return false; 10013 return true; 10014 }; 10015 10016 const Expr *FirstArg = Call->getArg(0); 10017 const Expr *SecondArg = Call->getArg(1); 10018 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10019 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10020 10021 // Only warn when exactly one argument is zero. 10022 if (IsFirstArgZero == IsSecondArgZero) return; 10023 10024 SourceRange FirstRange = FirstArg->getSourceRange(); 10025 SourceRange SecondRange = SecondArg->getSourceRange(); 10026 10027 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10028 10029 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10030 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10031 10032 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10033 SourceRange RemovalRange; 10034 if (IsFirstArgZero) { 10035 RemovalRange = SourceRange(FirstRange.getBegin(), 10036 SecondRange.getBegin().getLocWithOffset(-1)); 10037 } else { 10038 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10039 SecondRange.getEnd()); 10040 } 10041 10042 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10043 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10044 << FixItHint::CreateRemoval(RemovalRange); 10045 } 10046 10047 //===--- CHECK: Standard memory functions ---------------------------------===// 10048 10049 /// Takes the expression passed to the size_t parameter of functions 10050 /// such as memcmp, strncat, etc and warns if it's a comparison. 10051 /// 10052 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10053 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10054 IdentifierInfo *FnName, 10055 SourceLocation FnLoc, 10056 SourceLocation RParenLoc) { 10057 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10058 if (!Size) 10059 return false; 10060 10061 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10062 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10063 return false; 10064 10065 SourceRange SizeRange = Size->getSourceRange(); 10066 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10067 << SizeRange << FnName; 10068 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10069 << FnName 10070 << FixItHint::CreateInsertion( 10071 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10072 << FixItHint::CreateRemoval(RParenLoc); 10073 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10074 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10075 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10076 ")"); 10077 10078 return true; 10079 } 10080 10081 /// Determine whether the given type is or contains a dynamic class type 10082 /// (e.g., whether it has a vtable). 10083 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10084 bool &IsContained) { 10085 // Look through array types while ignoring qualifiers. 10086 const Type *Ty = T->getBaseElementTypeUnsafe(); 10087 IsContained = false; 10088 10089 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10090 RD = RD ? RD->getDefinition() : nullptr; 10091 if (!RD || RD->isInvalidDecl()) 10092 return nullptr; 10093 10094 if (RD->isDynamicClass()) 10095 return RD; 10096 10097 // Check all the fields. If any bases were dynamic, the class is dynamic. 10098 // It's impossible for a class to transitively contain itself by value, so 10099 // infinite recursion is impossible. 10100 for (auto *FD : RD->fields()) { 10101 bool SubContained; 10102 if (const CXXRecordDecl *ContainedRD = 10103 getContainedDynamicClass(FD->getType(), SubContained)) { 10104 IsContained = true; 10105 return ContainedRD; 10106 } 10107 } 10108 10109 return nullptr; 10110 } 10111 10112 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10113 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10114 if (Unary->getKind() == UETT_SizeOf) 10115 return Unary; 10116 return nullptr; 10117 } 10118 10119 /// If E is a sizeof expression, returns its argument expression, 10120 /// otherwise returns NULL. 10121 static const Expr *getSizeOfExprArg(const Expr *E) { 10122 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10123 if (!SizeOf->isArgumentType()) 10124 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10125 return nullptr; 10126 } 10127 10128 /// If E is a sizeof expression, returns its argument type. 10129 static QualType getSizeOfArgType(const Expr *E) { 10130 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10131 return SizeOf->getTypeOfArgument(); 10132 return QualType(); 10133 } 10134 10135 namespace { 10136 10137 struct SearchNonTrivialToInitializeField 10138 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10139 using Super = 10140 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10141 10142 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10143 10144 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10145 SourceLocation SL) { 10146 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10147 asDerived().visitArray(PDIK, AT, SL); 10148 return; 10149 } 10150 10151 Super::visitWithKind(PDIK, FT, SL); 10152 } 10153 10154 void visitARCStrong(QualType FT, SourceLocation SL) { 10155 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10156 } 10157 void visitARCWeak(QualType FT, SourceLocation SL) { 10158 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10159 } 10160 void visitStruct(QualType FT, SourceLocation SL) { 10161 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10162 visit(FD->getType(), FD->getLocation()); 10163 } 10164 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10165 const ArrayType *AT, SourceLocation SL) { 10166 visit(getContext().getBaseElementType(AT), SL); 10167 } 10168 void visitTrivial(QualType FT, SourceLocation SL) {} 10169 10170 static void diag(QualType RT, const Expr *E, Sema &S) { 10171 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10172 } 10173 10174 ASTContext &getContext() { return S.getASTContext(); } 10175 10176 const Expr *E; 10177 Sema &S; 10178 }; 10179 10180 struct SearchNonTrivialToCopyField 10181 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10182 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10183 10184 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10185 10186 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10187 SourceLocation SL) { 10188 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10189 asDerived().visitArray(PCK, AT, SL); 10190 return; 10191 } 10192 10193 Super::visitWithKind(PCK, FT, SL); 10194 } 10195 10196 void visitARCStrong(QualType FT, SourceLocation SL) { 10197 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10198 } 10199 void visitARCWeak(QualType FT, SourceLocation SL) { 10200 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10201 } 10202 void visitStruct(QualType FT, SourceLocation SL) { 10203 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10204 visit(FD->getType(), FD->getLocation()); 10205 } 10206 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10207 SourceLocation SL) { 10208 visit(getContext().getBaseElementType(AT), SL); 10209 } 10210 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10211 SourceLocation SL) {} 10212 void visitTrivial(QualType FT, SourceLocation SL) {} 10213 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10214 10215 static void diag(QualType RT, const Expr *E, Sema &S) { 10216 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10217 } 10218 10219 ASTContext &getContext() { return S.getASTContext(); } 10220 10221 const Expr *E; 10222 Sema &S; 10223 }; 10224 10225 } 10226 10227 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10228 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10229 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10230 10231 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10232 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10233 return false; 10234 10235 return doesExprLikelyComputeSize(BO->getLHS()) || 10236 doesExprLikelyComputeSize(BO->getRHS()); 10237 } 10238 10239 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10240 } 10241 10242 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10243 /// 10244 /// \code 10245 /// #define MACRO 0 10246 /// foo(MACRO); 10247 /// foo(0); 10248 /// \endcode 10249 /// 10250 /// This should return true for the first call to foo, but not for the second 10251 /// (regardless of whether foo is a macro or function). 10252 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10253 SourceLocation CallLoc, 10254 SourceLocation ArgLoc) { 10255 if (!CallLoc.isMacroID()) 10256 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10257 10258 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10259 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10260 } 10261 10262 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10263 /// last two arguments transposed. 10264 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10265 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10266 return; 10267 10268 const Expr *SizeArg = 10269 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10270 10271 auto isLiteralZero = [](const Expr *E) { 10272 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10273 }; 10274 10275 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10276 SourceLocation CallLoc = Call->getRParenLoc(); 10277 SourceManager &SM = S.getSourceManager(); 10278 if (isLiteralZero(SizeArg) && 10279 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10280 10281 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10282 10283 // Some platforms #define bzero to __builtin_memset. See if this is the 10284 // case, and if so, emit a better diagnostic. 10285 if (BId == Builtin::BIbzero || 10286 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10287 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10288 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10289 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10290 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10291 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10292 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10293 } 10294 return; 10295 } 10296 10297 // If the second argument to a memset is a sizeof expression and the third 10298 // isn't, this is also likely an error. This should catch 10299 // 'memset(buf, sizeof(buf), 0xff)'. 10300 if (BId == Builtin::BImemset && 10301 doesExprLikelyComputeSize(Call->getArg(1)) && 10302 !doesExprLikelyComputeSize(Call->getArg(2))) { 10303 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10304 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10305 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10306 return; 10307 } 10308 } 10309 10310 /// Check for dangerous or invalid arguments to memset(). 10311 /// 10312 /// This issues warnings on known problematic, dangerous or unspecified 10313 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10314 /// function calls. 10315 /// 10316 /// \param Call The call expression to diagnose. 10317 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10318 unsigned BId, 10319 IdentifierInfo *FnName) { 10320 assert(BId != 0); 10321 10322 // It is possible to have a non-standard definition of memset. Validate 10323 // we have enough arguments, and if not, abort further checking. 10324 unsigned ExpectedNumArgs = 10325 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10326 if (Call->getNumArgs() < ExpectedNumArgs) 10327 return; 10328 10329 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10330 BId == Builtin::BIstrndup ? 1 : 2); 10331 unsigned LenArg = 10332 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10333 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10334 10335 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10336 Call->getBeginLoc(), Call->getRParenLoc())) 10337 return; 10338 10339 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10340 CheckMemaccessSize(*this, BId, Call); 10341 10342 // We have special checking when the length is a sizeof expression. 10343 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10344 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10345 llvm::FoldingSetNodeID SizeOfArgID; 10346 10347 // Although widely used, 'bzero' is not a standard function. Be more strict 10348 // with the argument types before allowing diagnostics and only allow the 10349 // form bzero(ptr, sizeof(...)). 10350 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10351 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10352 return; 10353 10354 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10355 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10356 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10357 10358 QualType DestTy = Dest->getType(); 10359 QualType PointeeTy; 10360 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10361 PointeeTy = DestPtrTy->getPointeeType(); 10362 10363 // Never warn about void type pointers. This can be used to suppress 10364 // false positives. 10365 if (PointeeTy->isVoidType()) 10366 continue; 10367 10368 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10369 // actually comparing the expressions for equality. Because computing the 10370 // expression IDs can be expensive, we only do this if the diagnostic is 10371 // enabled. 10372 if (SizeOfArg && 10373 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10374 SizeOfArg->getExprLoc())) { 10375 // We only compute IDs for expressions if the warning is enabled, and 10376 // cache the sizeof arg's ID. 10377 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10378 SizeOfArg->Profile(SizeOfArgID, Context, true); 10379 llvm::FoldingSetNodeID DestID; 10380 Dest->Profile(DestID, Context, true); 10381 if (DestID == SizeOfArgID) { 10382 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10383 // over sizeof(src) as well. 10384 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10385 StringRef ReadableName = FnName->getName(); 10386 10387 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10388 if (UnaryOp->getOpcode() == UO_AddrOf) 10389 ActionIdx = 1; // If its an address-of operator, just remove it. 10390 if (!PointeeTy->isIncompleteType() && 10391 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10392 ActionIdx = 2; // If the pointee's size is sizeof(char), 10393 // suggest an explicit length. 10394 10395 // If the function is defined as a builtin macro, do not show macro 10396 // expansion. 10397 SourceLocation SL = SizeOfArg->getExprLoc(); 10398 SourceRange DSR = Dest->getSourceRange(); 10399 SourceRange SSR = SizeOfArg->getSourceRange(); 10400 SourceManager &SM = getSourceManager(); 10401 10402 if (SM.isMacroArgExpansion(SL)) { 10403 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10404 SL = SM.getSpellingLoc(SL); 10405 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10406 SM.getSpellingLoc(DSR.getEnd())); 10407 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10408 SM.getSpellingLoc(SSR.getEnd())); 10409 } 10410 10411 DiagRuntimeBehavior(SL, SizeOfArg, 10412 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10413 << ReadableName 10414 << PointeeTy 10415 << DestTy 10416 << DSR 10417 << SSR); 10418 DiagRuntimeBehavior(SL, SizeOfArg, 10419 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10420 << ActionIdx 10421 << SSR); 10422 10423 break; 10424 } 10425 } 10426 10427 // Also check for cases where the sizeof argument is the exact same 10428 // type as the memory argument, and where it points to a user-defined 10429 // record type. 10430 if (SizeOfArgTy != QualType()) { 10431 if (PointeeTy->isRecordType() && 10432 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10433 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10434 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10435 << FnName << SizeOfArgTy << ArgIdx 10436 << PointeeTy << Dest->getSourceRange() 10437 << LenExpr->getSourceRange()); 10438 break; 10439 } 10440 } 10441 } else if (DestTy->isArrayType()) { 10442 PointeeTy = DestTy; 10443 } 10444 10445 if (PointeeTy == QualType()) 10446 continue; 10447 10448 // Always complain about dynamic classes. 10449 bool IsContained; 10450 if (const CXXRecordDecl *ContainedRD = 10451 getContainedDynamicClass(PointeeTy, IsContained)) { 10452 10453 unsigned OperationType = 0; 10454 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10455 // "overwritten" if we're warning about the destination for any call 10456 // but memcmp; otherwise a verb appropriate to the call. 10457 if (ArgIdx != 0 || IsCmp) { 10458 if (BId == Builtin::BImemcpy) 10459 OperationType = 1; 10460 else if(BId == Builtin::BImemmove) 10461 OperationType = 2; 10462 else if (IsCmp) 10463 OperationType = 3; 10464 } 10465 10466 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10467 PDiag(diag::warn_dyn_class_memaccess) 10468 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10469 << IsContained << ContainedRD << OperationType 10470 << Call->getCallee()->getSourceRange()); 10471 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10472 BId != Builtin::BImemset) 10473 DiagRuntimeBehavior( 10474 Dest->getExprLoc(), Dest, 10475 PDiag(diag::warn_arc_object_memaccess) 10476 << ArgIdx << FnName << PointeeTy 10477 << Call->getCallee()->getSourceRange()); 10478 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10479 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10480 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10481 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10482 PDiag(diag::warn_cstruct_memaccess) 10483 << ArgIdx << FnName << PointeeTy << 0); 10484 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10485 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10486 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10487 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10488 PDiag(diag::warn_cstruct_memaccess) 10489 << ArgIdx << FnName << PointeeTy << 1); 10490 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10491 } else { 10492 continue; 10493 } 10494 } else 10495 continue; 10496 10497 DiagRuntimeBehavior( 10498 Dest->getExprLoc(), Dest, 10499 PDiag(diag::note_bad_memaccess_silence) 10500 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10501 break; 10502 } 10503 } 10504 10505 // A little helper routine: ignore addition and subtraction of integer literals. 10506 // This intentionally does not ignore all integer constant expressions because 10507 // we don't want to remove sizeof(). 10508 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10509 Ex = Ex->IgnoreParenCasts(); 10510 10511 while (true) { 10512 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10513 if (!BO || !BO->isAdditiveOp()) 10514 break; 10515 10516 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10517 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10518 10519 if (isa<IntegerLiteral>(RHS)) 10520 Ex = LHS; 10521 else if (isa<IntegerLiteral>(LHS)) 10522 Ex = RHS; 10523 else 10524 break; 10525 } 10526 10527 return Ex; 10528 } 10529 10530 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10531 ASTContext &Context) { 10532 // Only handle constant-sized or VLAs, but not flexible members. 10533 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10534 // Only issue the FIXIT for arrays of size > 1. 10535 if (CAT->getSize().getSExtValue() <= 1) 10536 return false; 10537 } else if (!Ty->isVariableArrayType()) { 10538 return false; 10539 } 10540 return true; 10541 } 10542 10543 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10544 // be the size of the source, instead of the destination. 10545 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10546 IdentifierInfo *FnName) { 10547 10548 // Don't crash if the user has the wrong number of arguments 10549 unsigned NumArgs = Call->getNumArgs(); 10550 if ((NumArgs != 3) && (NumArgs != 4)) 10551 return; 10552 10553 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10554 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10555 const Expr *CompareWithSrc = nullptr; 10556 10557 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10558 Call->getBeginLoc(), Call->getRParenLoc())) 10559 return; 10560 10561 // Look for 'strlcpy(dst, x, sizeof(x))' 10562 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10563 CompareWithSrc = Ex; 10564 else { 10565 // Look for 'strlcpy(dst, x, strlen(x))' 10566 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10567 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10568 SizeCall->getNumArgs() == 1) 10569 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10570 } 10571 } 10572 10573 if (!CompareWithSrc) 10574 return; 10575 10576 // Determine if the argument to sizeof/strlen is equal to the source 10577 // argument. In principle there's all kinds of things you could do 10578 // here, for instance creating an == expression and evaluating it with 10579 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10580 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10581 if (!SrcArgDRE) 10582 return; 10583 10584 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10585 if (!CompareWithSrcDRE || 10586 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10587 return; 10588 10589 const Expr *OriginalSizeArg = Call->getArg(2); 10590 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10591 << OriginalSizeArg->getSourceRange() << FnName; 10592 10593 // Output a FIXIT hint if the destination is an array (rather than a 10594 // pointer to an array). This could be enhanced to handle some 10595 // pointers if we know the actual size, like if DstArg is 'array+2' 10596 // we could say 'sizeof(array)-2'. 10597 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10598 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10599 return; 10600 10601 SmallString<128> sizeString; 10602 llvm::raw_svector_ostream OS(sizeString); 10603 OS << "sizeof("; 10604 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10605 OS << ")"; 10606 10607 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10608 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10609 OS.str()); 10610 } 10611 10612 /// Check if two expressions refer to the same declaration. 10613 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10614 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10615 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10616 return D1->getDecl() == D2->getDecl(); 10617 return false; 10618 } 10619 10620 static const Expr *getStrlenExprArg(const Expr *E) { 10621 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10622 const FunctionDecl *FD = CE->getDirectCallee(); 10623 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10624 return nullptr; 10625 return CE->getArg(0)->IgnoreParenCasts(); 10626 } 10627 return nullptr; 10628 } 10629 10630 // Warn on anti-patterns as the 'size' argument to strncat. 10631 // The correct size argument should look like following: 10632 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10633 void Sema::CheckStrncatArguments(const CallExpr *CE, 10634 IdentifierInfo *FnName) { 10635 // Don't crash if the user has the wrong number of arguments. 10636 if (CE->getNumArgs() < 3) 10637 return; 10638 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10639 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10640 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10641 10642 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10643 CE->getRParenLoc())) 10644 return; 10645 10646 // Identify common expressions, which are wrongly used as the size argument 10647 // to strncat and may lead to buffer overflows. 10648 unsigned PatternType = 0; 10649 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10650 // - sizeof(dst) 10651 if (referToTheSameDecl(SizeOfArg, DstArg)) 10652 PatternType = 1; 10653 // - sizeof(src) 10654 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10655 PatternType = 2; 10656 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10657 if (BE->getOpcode() == BO_Sub) { 10658 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10659 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10660 // - sizeof(dst) - strlen(dst) 10661 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10662 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10663 PatternType = 1; 10664 // - sizeof(src) - (anything) 10665 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10666 PatternType = 2; 10667 } 10668 } 10669 10670 if (PatternType == 0) 10671 return; 10672 10673 // Generate the diagnostic. 10674 SourceLocation SL = LenArg->getBeginLoc(); 10675 SourceRange SR = LenArg->getSourceRange(); 10676 SourceManager &SM = getSourceManager(); 10677 10678 // If the function is defined as a builtin macro, do not show macro expansion. 10679 if (SM.isMacroArgExpansion(SL)) { 10680 SL = SM.getSpellingLoc(SL); 10681 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10682 SM.getSpellingLoc(SR.getEnd())); 10683 } 10684 10685 // Check if the destination is an array (rather than a pointer to an array). 10686 QualType DstTy = DstArg->getType(); 10687 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10688 Context); 10689 if (!isKnownSizeArray) { 10690 if (PatternType == 1) 10691 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10692 else 10693 Diag(SL, diag::warn_strncat_src_size) << SR; 10694 return; 10695 } 10696 10697 if (PatternType == 1) 10698 Diag(SL, diag::warn_strncat_large_size) << SR; 10699 else 10700 Diag(SL, diag::warn_strncat_src_size) << SR; 10701 10702 SmallString<128> sizeString; 10703 llvm::raw_svector_ostream OS(sizeString); 10704 OS << "sizeof("; 10705 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10706 OS << ") - "; 10707 OS << "strlen("; 10708 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10709 OS << ") - 1"; 10710 10711 Diag(SL, diag::note_strncat_wrong_size) 10712 << FixItHint::CreateReplacement(SR, OS.str()); 10713 } 10714 10715 namespace { 10716 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10717 const UnaryOperator *UnaryExpr, const Decl *D) { 10718 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10719 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10720 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10721 return; 10722 } 10723 } 10724 10725 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10726 const UnaryOperator *UnaryExpr) { 10727 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10728 const Decl *D = Lvalue->getDecl(); 10729 if (isa<VarDecl, FunctionDecl>(D)) 10730 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10731 } 10732 10733 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10734 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10735 Lvalue->getMemberDecl()); 10736 } 10737 10738 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10739 const UnaryOperator *UnaryExpr) { 10740 const auto *Lambda = dyn_cast<LambdaExpr>( 10741 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10742 if (!Lambda) 10743 return; 10744 10745 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10746 << CalleeName << 2 /*object: lambda expression*/; 10747 } 10748 10749 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10750 const DeclRefExpr *Lvalue) { 10751 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10752 if (Var == nullptr) 10753 return; 10754 10755 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10756 << CalleeName << 0 /*object: */ << Var; 10757 } 10758 10759 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10760 const CastExpr *Cast) { 10761 SmallString<128> SizeString; 10762 llvm::raw_svector_ostream OS(SizeString); 10763 10764 clang::CastKind Kind = Cast->getCastKind(); 10765 if (Kind == clang::CK_BitCast && 10766 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10767 return; 10768 if (Kind == clang::CK_IntegralToPointer && 10769 !isa<IntegerLiteral>( 10770 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10771 return; 10772 10773 switch (Cast->getCastKind()) { 10774 case clang::CK_BitCast: 10775 case clang::CK_IntegralToPointer: 10776 case clang::CK_FunctionToPointerDecay: 10777 OS << '\''; 10778 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10779 OS << '\''; 10780 break; 10781 default: 10782 return; 10783 } 10784 10785 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10786 << CalleeName << 0 /*object: */ << OS.str(); 10787 } 10788 } // namespace 10789 10790 /// Alerts the user that they are attempting to free a non-malloc'd object. 10791 void Sema::CheckFreeArguments(const CallExpr *E) { 10792 const std::string CalleeName = 10793 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10794 10795 { // Prefer something that doesn't involve a cast to make things simpler. 10796 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10797 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10798 switch (UnaryExpr->getOpcode()) { 10799 case UnaryOperator::Opcode::UO_AddrOf: 10800 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10801 case UnaryOperator::Opcode::UO_Plus: 10802 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10803 default: 10804 break; 10805 } 10806 10807 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10808 if (Lvalue->getType()->isArrayType()) 10809 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10810 10811 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10812 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10813 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10814 return; 10815 } 10816 10817 if (isa<BlockExpr>(Arg)) { 10818 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10819 << CalleeName << 1 /*object: block*/; 10820 return; 10821 } 10822 } 10823 // Maybe the cast was important, check after the other cases. 10824 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10825 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10826 } 10827 10828 void 10829 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10830 SourceLocation ReturnLoc, 10831 bool isObjCMethod, 10832 const AttrVec *Attrs, 10833 const FunctionDecl *FD) { 10834 // Check if the return value is null but should not be. 10835 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10836 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10837 CheckNonNullExpr(*this, RetValExp)) 10838 Diag(ReturnLoc, diag::warn_null_ret) 10839 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10840 10841 // C++11 [basic.stc.dynamic.allocation]p4: 10842 // If an allocation function declared with a non-throwing 10843 // exception-specification fails to allocate storage, it shall return 10844 // a null pointer. Any other allocation function that fails to allocate 10845 // storage shall indicate failure only by throwing an exception [...] 10846 if (FD) { 10847 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10848 if (Op == OO_New || Op == OO_Array_New) { 10849 const FunctionProtoType *Proto 10850 = FD->getType()->castAs<FunctionProtoType>(); 10851 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10852 CheckNonNullExpr(*this, RetValExp)) 10853 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10854 << FD << getLangOpts().CPlusPlus11; 10855 } 10856 } 10857 10858 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10859 // here prevent the user from using a PPC MMA type as trailing return type. 10860 if (Context.getTargetInfo().getTriple().isPPC64()) 10861 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10862 } 10863 10864 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10865 10866 /// Check for comparisons of floating point operands using != and ==. 10867 /// Issue a warning if these are no self-comparisons, as they are not likely 10868 /// to do what the programmer intended. 10869 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10870 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10871 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10872 10873 // Special case: check for x == x (which is OK). 10874 // Do not emit warnings for such cases. 10875 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10876 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10877 if (DRL->getDecl() == DRR->getDecl()) 10878 return; 10879 10880 // Special case: check for comparisons against literals that can be exactly 10881 // represented by APFloat. In such cases, do not emit a warning. This 10882 // is a heuristic: often comparison against such literals are used to 10883 // detect if a value in a variable has not changed. This clearly can 10884 // lead to false negatives. 10885 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10886 if (FLL->isExact()) 10887 return; 10888 } else 10889 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10890 if (FLR->isExact()) 10891 return; 10892 10893 // Check for comparisons with builtin types. 10894 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10895 if (CL->getBuiltinCallee()) 10896 return; 10897 10898 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10899 if (CR->getBuiltinCallee()) 10900 return; 10901 10902 // Emit the diagnostic. 10903 Diag(Loc, diag::warn_floatingpoint_eq) 10904 << LHS->getSourceRange() << RHS->getSourceRange(); 10905 } 10906 10907 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10908 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10909 10910 namespace { 10911 10912 /// Structure recording the 'active' range of an integer-valued 10913 /// expression. 10914 struct IntRange { 10915 /// The number of bits active in the int. Note that this includes exactly one 10916 /// sign bit if !NonNegative. 10917 unsigned Width; 10918 10919 /// True if the int is known not to have negative values. If so, all leading 10920 /// bits before Width are known zero, otherwise they are known to be the 10921 /// same as the MSB within Width. 10922 bool NonNegative; 10923 10924 IntRange(unsigned Width, bool NonNegative) 10925 : Width(Width), NonNegative(NonNegative) {} 10926 10927 /// Number of bits excluding the sign bit. 10928 unsigned valueBits() const { 10929 return NonNegative ? Width : Width - 1; 10930 } 10931 10932 /// Returns the range of the bool type. 10933 static IntRange forBoolType() { 10934 return IntRange(1, true); 10935 } 10936 10937 /// Returns the range of an opaque value of the given integral type. 10938 static IntRange forValueOfType(ASTContext &C, QualType T) { 10939 return forValueOfCanonicalType(C, 10940 T->getCanonicalTypeInternal().getTypePtr()); 10941 } 10942 10943 /// Returns the range of an opaque value of a canonical integral type. 10944 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10945 assert(T->isCanonicalUnqualified()); 10946 10947 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10948 T = VT->getElementType().getTypePtr(); 10949 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10950 T = CT->getElementType().getTypePtr(); 10951 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10952 T = AT->getValueType().getTypePtr(); 10953 10954 if (!C.getLangOpts().CPlusPlus) { 10955 // For enum types in C code, use the underlying datatype. 10956 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10957 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10958 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10959 // For enum types in C++, use the known bit width of the enumerators. 10960 EnumDecl *Enum = ET->getDecl(); 10961 // In C++11, enums can have a fixed underlying type. Use this type to 10962 // compute the range. 10963 if (Enum->isFixed()) { 10964 return IntRange(C.getIntWidth(QualType(T, 0)), 10965 !ET->isSignedIntegerOrEnumerationType()); 10966 } 10967 10968 unsigned NumPositive = Enum->getNumPositiveBits(); 10969 unsigned NumNegative = Enum->getNumNegativeBits(); 10970 10971 if (NumNegative == 0) 10972 return IntRange(NumPositive, true/*NonNegative*/); 10973 else 10974 return IntRange(std::max(NumPositive + 1, NumNegative), 10975 false/*NonNegative*/); 10976 } 10977 10978 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10979 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10980 10981 const BuiltinType *BT = cast<BuiltinType>(T); 10982 assert(BT->isInteger()); 10983 10984 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10985 } 10986 10987 /// Returns the "target" range of a canonical integral type, i.e. 10988 /// the range of values expressible in the type. 10989 /// 10990 /// This matches forValueOfCanonicalType except that enums have the 10991 /// full range of their type, not the range of their enumerators. 10992 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10993 assert(T->isCanonicalUnqualified()); 10994 10995 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10996 T = VT->getElementType().getTypePtr(); 10997 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10998 T = CT->getElementType().getTypePtr(); 10999 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11000 T = AT->getValueType().getTypePtr(); 11001 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11002 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11003 11004 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11005 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11006 11007 const BuiltinType *BT = cast<BuiltinType>(T); 11008 assert(BT->isInteger()); 11009 11010 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11011 } 11012 11013 /// Returns the supremum of two ranges: i.e. their conservative merge. 11014 static IntRange join(IntRange L, IntRange R) { 11015 bool Unsigned = L.NonNegative && R.NonNegative; 11016 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11017 L.NonNegative && R.NonNegative); 11018 } 11019 11020 /// Return the range of a bitwise-AND of the two ranges. 11021 static IntRange bit_and(IntRange L, IntRange R) { 11022 unsigned Bits = std::max(L.Width, R.Width); 11023 bool NonNegative = false; 11024 if (L.NonNegative) { 11025 Bits = std::min(Bits, L.Width); 11026 NonNegative = true; 11027 } 11028 if (R.NonNegative) { 11029 Bits = std::min(Bits, R.Width); 11030 NonNegative = true; 11031 } 11032 return IntRange(Bits, NonNegative); 11033 } 11034 11035 /// Return the range of a sum of the two ranges. 11036 static IntRange sum(IntRange L, IntRange R) { 11037 bool Unsigned = L.NonNegative && R.NonNegative; 11038 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11039 Unsigned); 11040 } 11041 11042 /// Return the range of a difference of the two ranges. 11043 static IntRange difference(IntRange L, IntRange R) { 11044 // We need a 1-bit-wider range if: 11045 // 1) LHS can be negative: least value can be reduced. 11046 // 2) RHS can be negative: greatest value can be increased. 11047 bool CanWiden = !L.NonNegative || !R.NonNegative; 11048 bool Unsigned = L.NonNegative && R.Width == 0; 11049 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11050 !Unsigned, 11051 Unsigned); 11052 } 11053 11054 /// Return the range of a product of the two ranges. 11055 static IntRange product(IntRange L, IntRange R) { 11056 // If both LHS and RHS can be negative, we can form 11057 // -2^L * -2^R = 2^(L + R) 11058 // which requires L + R + 1 value bits to represent. 11059 bool CanWiden = !L.NonNegative && !R.NonNegative; 11060 bool Unsigned = L.NonNegative && R.NonNegative; 11061 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11062 Unsigned); 11063 } 11064 11065 /// Return the range of a remainder operation between the two ranges. 11066 static IntRange rem(IntRange L, IntRange R) { 11067 // The result of a remainder can't be larger than the result of 11068 // either side. The sign of the result is the sign of the LHS. 11069 bool Unsigned = L.NonNegative; 11070 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11071 Unsigned); 11072 } 11073 }; 11074 11075 } // namespace 11076 11077 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11078 unsigned MaxWidth) { 11079 if (value.isSigned() && value.isNegative()) 11080 return IntRange(value.getMinSignedBits(), false); 11081 11082 if (value.getBitWidth() > MaxWidth) 11083 value = value.trunc(MaxWidth); 11084 11085 // isNonNegative() just checks the sign bit without considering 11086 // signedness. 11087 return IntRange(value.getActiveBits(), true); 11088 } 11089 11090 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11091 unsigned MaxWidth) { 11092 if (result.isInt()) 11093 return GetValueRange(C, result.getInt(), MaxWidth); 11094 11095 if (result.isVector()) { 11096 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11097 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11098 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11099 R = IntRange::join(R, El); 11100 } 11101 return R; 11102 } 11103 11104 if (result.isComplexInt()) { 11105 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11106 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11107 return IntRange::join(R, I); 11108 } 11109 11110 // This can happen with lossless casts to intptr_t of "based" lvalues. 11111 // Assume it might use arbitrary bits. 11112 // FIXME: The only reason we need to pass the type in here is to get 11113 // the sign right on this one case. It would be nice if APValue 11114 // preserved this. 11115 assert(result.isLValue() || result.isAddrLabelDiff()); 11116 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11117 } 11118 11119 static QualType GetExprType(const Expr *E) { 11120 QualType Ty = E->getType(); 11121 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11122 Ty = AtomicRHS->getValueType(); 11123 return Ty; 11124 } 11125 11126 /// Pseudo-evaluate the given integer expression, estimating the 11127 /// range of values it might take. 11128 /// 11129 /// \param MaxWidth The width to which the value will be truncated. 11130 /// \param Approximate If \c true, return a likely range for the result: in 11131 /// particular, assume that aritmetic on narrower types doesn't leave 11132 /// those types. If \c false, return a range including all possible 11133 /// result values. 11134 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11135 bool InConstantContext, bool Approximate) { 11136 E = E->IgnoreParens(); 11137 11138 // Try a full evaluation first. 11139 Expr::EvalResult result; 11140 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11141 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11142 11143 // I think we only want to look through implicit casts here; if the 11144 // user has an explicit widening cast, we should treat the value as 11145 // being of the new, wider type. 11146 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11147 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11148 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11149 Approximate); 11150 11151 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11152 11153 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11154 CE->getCastKind() == CK_BooleanToSignedIntegral; 11155 11156 // Assume that non-integer casts can span the full range of the type. 11157 if (!isIntegerCast) 11158 return OutputTypeRange; 11159 11160 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11161 std::min(MaxWidth, OutputTypeRange.Width), 11162 InConstantContext, Approximate); 11163 11164 // Bail out if the subexpr's range is as wide as the cast type. 11165 if (SubRange.Width >= OutputTypeRange.Width) 11166 return OutputTypeRange; 11167 11168 // Otherwise, we take the smaller width, and we're non-negative if 11169 // either the output type or the subexpr is. 11170 return IntRange(SubRange.Width, 11171 SubRange.NonNegative || OutputTypeRange.NonNegative); 11172 } 11173 11174 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11175 // If we can fold the condition, just take that operand. 11176 bool CondResult; 11177 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11178 return GetExprRange(C, 11179 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11180 MaxWidth, InConstantContext, Approximate); 11181 11182 // Otherwise, conservatively merge. 11183 // GetExprRange requires an integer expression, but a throw expression 11184 // results in a void type. 11185 Expr *E = CO->getTrueExpr(); 11186 IntRange L = E->getType()->isVoidType() 11187 ? IntRange{0, true} 11188 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11189 E = CO->getFalseExpr(); 11190 IntRange R = E->getType()->isVoidType() 11191 ? IntRange{0, true} 11192 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11193 return IntRange::join(L, R); 11194 } 11195 11196 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11197 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11198 11199 switch (BO->getOpcode()) { 11200 case BO_Cmp: 11201 llvm_unreachable("builtin <=> should have class type"); 11202 11203 // Boolean-valued operations are single-bit and positive. 11204 case BO_LAnd: 11205 case BO_LOr: 11206 case BO_LT: 11207 case BO_GT: 11208 case BO_LE: 11209 case BO_GE: 11210 case BO_EQ: 11211 case BO_NE: 11212 return IntRange::forBoolType(); 11213 11214 // The type of the assignments is the type of the LHS, so the RHS 11215 // is not necessarily the same type. 11216 case BO_MulAssign: 11217 case BO_DivAssign: 11218 case BO_RemAssign: 11219 case BO_AddAssign: 11220 case BO_SubAssign: 11221 case BO_XorAssign: 11222 case BO_OrAssign: 11223 // TODO: bitfields? 11224 return IntRange::forValueOfType(C, GetExprType(E)); 11225 11226 // Simple assignments just pass through the RHS, which will have 11227 // been coerced to the LHS type. 11228 case BO_Assign: 11229 // TODO: bitfields? 11230 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11231 Approximate); 11232 11233 // Operations with opaque sources are black-listed. 11234 case BO_PtrMemD: 11235 case BO_PtrMemI: 11236 return IntRange::forValueOfType(C, GetExprType(E)); 11237 11238 // Bitwise-and uses the *infinum* of the two source ranges. 11239 case BO_And: 11240 case BO_AndAssign: 11241 Combine = IntRange::bit_and; 11242 break; 11243 11244 // Left shift gets black-listed based on a judgement call. 11245 case BO_Shl: 11246 // ...except that we want to treat '1 << (blah)' as logically 11247 // positive. It's an important idiom. 11248 if (IntegerLiteral *I 11249 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11250 if (I->getValue() == 1) { 11251 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11252 return IntRange(R.Width, /*NonNegative*/ true); 11253 } 11254 } 11255 LLVM_FALLTHROUGH; 11256 11257 case BO_ShlAssign: 11258 return IntRange::forValueOfType(C, GetExprType(E)); 11259 11260 // Right shift by a constant can narrow its left argument. 11261 case BO_Shr: 11262 case BO_ShrAssign: { 11263 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11264 Approximate); 11265 11266 // If the shift amount is a positive constant, drop the width by 11267 // that much. 11268 if (Optional<llvm::APSInt> shift = 11269 BO->getRHS()->getIntegerConstantExpr(C)) { 11270 if (shift->isNonNegative()) { 11271 unsigned zext = shift->getZExtValue(); 11272 if (zext >= L.Width) 11273 L.Width = (L.NonNegative ? 0 : 1); 11274 else 11275 L.Width -= zext; 11276 } 11277 } 11278 11279 return L; 11280 } 11281 11282 // Comma acts as its right operand. 11283 case BO_Comma: 11284 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11285 Approximate); 11286 11287 case BO_Add: 11288 if (!Approximate) 11289 Combine = IntRange::sum; 11290 break; 11291 11292 case BO_Sub: 11293 if (BO->getLHS()->getType()->isPointerType()) 11294 return IntRange::forValueOfType(C, GetExprType(E)); 11295 if (!Approximate) 11296 Combine = IntRange::difference; 11297 break; 11298 11299 case BO_Mul: 11300 if (!Approximate) 11301 Combine = IntRange::product; 11302 break; 11303 11304 // The width of a division result is mostly determined by the size 11305 // of the LHS. 11306 case BO_Div: { 11307 // Don't 'pre-truncate' the operands. 11308 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11309 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11310 Approximate); 11311 11312 // If the divisor is constant, use that. 11313 if (Optional<llvm::APSInt> divisor = 11314 BO->getRHS()->getIntegerConstantExpr(C)) { 11315 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11316 if (log2 >= L.Width) 11317 L.Width = (L.NonNegative ? 0 : 1); 11318 else 11319 L.Width = std::min(L.Width - log2, MaxWidth); 11320 return L; 11321 } 11322 11323 // Otherwise, just use the LHS's width. 11324 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11325 // could be -1. 11326 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11327 Approximate); 11328 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11329 } 11330 11331 case BO_Rem: 11332 Combine = IntRange::rem; 11333 break; 11334 11335 // The default behavior is okay for these. 11336 case BO_Xor: 11337 case BO_Or: 11338 break; 11339 } 11340 11341 // Combine the two ranges, but limit the result to the type in which we 11342 // performed the computation. 11343 QualType T = GetExprType(E); 11344 unsigned opWidth = C.getIntWidth(T); 11345 IntRange L = 11346 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11347 IntRange R = 11348 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11349 IntRange C = Combine(L, R); 11350 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11351 C.Width = std::min(C.Width, MaxWidth); 11352 return C; 11353 } 11354 11355 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11356 switch (UO->getOpcode()) { 11357 // Boolean-valued operations are white-listed. 11358 case UO_LNot: 11359 return IntRange::forBoolType(); 11360 11361 // Operations with opaque sources are black-listed. 11362 case UO_Deref: 11363 case UO_AddrOf: // should be impossible 11364 return IntRange::forValueOfType(C, GetExprType(E)); 11365 11366 default: 11367 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11368 Approximate); 11369 } 11370 } 11371 11372 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11373 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11374 Approximate); 11375 11376 if (const auto *BitField = E->getSourceBitField()) 11377 return IntRange(BitField->getBitWidthValue(C), 11378 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11379 11380 return IntRange::forValueOfType(C, GetExprType(E)); 11381 } 11382 11383 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11384 bool InConstantContext, bool Approximate) { 11385 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11386 Approximate); 11387 } 11388 11389 /// Checks whether the given value, which currently has the given 11390 /// source semantics, has the same value when coerced through the 11391 /// target semantics. 11392 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11393 const llvm::fltSemantics &Src, 11394 const llvm::fltSemantics &Tgt) { 11395 llvm::APFloat truncated = value; 11396 11397 bool ignored; 11398 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11399 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11400 11401 return truncated.bitwiseIsEqual(value); 11402 } 11403 11404 /// Checks whether the given value, which currently has the given 11405 /// source semantics, has the same value when coerced through the 11406 /// target semantics. 11407 /// 11408 /// The value might be a vector of floats (or a complex number). 11409 static bool IsSameFloatAfterCast(const APValue &value, 11410 const llvm::fltSemantics &Src, 11411 const llvm::fltSemantics &Tgt) { 11412 if (value.isFloat()) 11413 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11414 11415 if (value.isVector()) { 11416 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11417 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11418 return false; 11419 return true; 11420 } 11421 11422 assert(value.isComplexFloat()); 11423 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11424 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11425 } 11426 11427 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11428 bool IsListInit = false); 11429 11430 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11431 // Suppress cases where we are comparing against an enum constant. 11432 if (const DeclRefExpr *DR = 11433 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11434 if (isa<EnumConstantDecl>(DR->getDecl())) 11435 return true; 11436 11437 // Suppress cases where the value is expanded from a macro, unless that macro 11438 // is how a language represents a boolean literal. This is the case in both C 11439 // and Objective-C. 11440 SourceLocation BeginLoc = E->getBeginLoc(); 11441 if (BeginLoc.isMacroID()) { 11442 StringRef MacroName = Lexer::getImmediateMacroName( 11443 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11444 return MacroName != "YES" && MacroName != "NO" && 11445 MacroName != "true" && MacroName != "false"; 11446 } 11447 11448 return false; 11449 } 11450 11451 static bool isKnownToHaveUnsignedValue(Expr *E) { 11452 return E->getType()->isIntegerType() && 11453 (!E->getType()->isSignedIntegerType() || 11454 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11455 } 11456 11457 namespace { 11458 /// The promoted range of values of a type. In general this has the 11459 /// following structure: 11460 /// 11461 /// |-----------| . . . |-----------| 11462 /// ^ ^ ^ ^ 11463 /// Min HoleMin HoleMax Max 11464 /// 11465 /// ... where there is only a hole if a signed type is promoted to unsigned 11466 /// (in which case Min and Max are the smallest and largest representable 11467 /// values). 11468 struct PromotedRange { 11469 // Min, or HoleMax if there is a hole. 11470 llvm::APSInt PromotedMin; 11471 // Max, or HoleMin if there is a hole. 11472 llvm::APSInt PromotedMax; 11473 11474 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11475 if (R.Width == 0) 11476 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11477 else if (R.Width >= BitWidth && !Unsigned) { 11478 // Promotion made the type *narrower*. This happens when promoting 11479 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11480 // Treat all values of 'signed int' as being in range for now. 11481 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11482 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11483 } else { 11484 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11485 .extOrTrunc(BitWidth); 11486 PromotedMin.setIsUnsigned(Unsigned); 11487 11488 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11489 .extOrTrunc(BitWidth); 11490 PromotedMax.setIsUnsigned(Unsigned); 11491 } 11492 } 11493 11494 // Determine whether this range is contiguous (has no hole). 11495 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11496 11497 // Where a constant value is within the range. 11498 enum ComparisonResult { 11499 LT = 0x1, 11500 LE = 0x2, 11501 GT = 0x4, 11502 GE = 0x8, 11503 EQ = 0x10, 11504 NE = 0x20, 11505 InRangeFlag = 0x40, 11506 11507 Less = LE | LT | NE, 11508 Min = LE | InRangeFlag, 11509 InRange = InRangeFlag, 11510 Max = GE | InRangeFlag, 11511 Greater = GE | GT | NE, 11512 11513 OnlyValue = LE | GE | EQ | InRangeFlag, 11514 InHole = NE 11515 }; 11516 11517 ComparisonResult compare(const llvm::APSInt &Value) const { 11518 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11519 Value.isUnsigned() == PromotedMin.isUnsigned()); 11520 if (!isContiguous()) { 11521 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11522 if (Value.isMinValue()) return Min; 11523 if (Value.isMaxValue()) return Max; 11524 if (Value >= PromotedMin) return InRange; 11525 if (Value <= PromotedMax) return InRange; 11526 return InHole; 11527 } 11528 11529 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11530 case -1: return Less; 11531 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11532 case 1: 11533 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11534 case -1: return InRange; 11535 case 0: return Max; 11536 case 1: return Greater; 11537 } 11538 } 11539 11540 llvm_unreachable("impossible compare result"); 11541 } 11542 11543 static llvm::Optional<StringRef> 11544 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11545 if (Op == BO_Cmp) { 11546 ComparisonResult LTFlag = LT, GTFlag = GT; 11547 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11548 11549 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11550 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11551 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11552 return llvm::None; 11553 } 11554 11555 ComparisonResult TrueFlag, FalseFlag; 11556 if (Op == BO_EQ) { 11557 TrueFlag = EQ; 11558 FalseFlag = NE; 11559 } else if (Op == BO_NE) { 11560 TrueFlag = NE; 11561 FalseFlag = EQ; 11562 } else { 11563 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11564 TrueFlag = LT; 11565 FalseFlag = GE; 11566 } else { 11567 TrueFlag = GT; 11568 FalseFlag = LE; 11569 } 11570 if (Op == BO_GE || Op == BO_LE) 11571 std::swap(TrueFlag, FalseFlag); 11572 } 11573 if (R & TrueFlag) 11574 return StringRef("true"); 11575 if (R & FalseFlag) 11576 return StringRef("false"); 11577 return llvm::None; 11578 } 11579 }; 11580 } 11581 11582 static bool HasEnumType(Expr *E) { 11583 // Strip off implicit integral promotions. 11584 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11585 if (ICE->getCastKind() != CK_IntegralCast && 11586 ICE->getCastKind() != CK_NoOp) 11587 break; 11588 E = ICE->getSubExpr(); 11589 } 11590 11591 return E->getType()->isEnumeralType(); 11592 } 11593 11594 static int classifyConstantValue(Expr *Constant) { 11595 // The values of this enumeration are used in the diagnostics 11596 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11597 enum ConstantValueKind { 11598 Miscellaneous = 0, 11599 LiteralTrue, 11600 LiteralFalse 11601 }; 11602 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11603 return BL->getValue() ? ConstantValueKind::LiteralTrue 11604 : ConstantValueKind::LiteralFalse; 11605 return ConstantValueKind::Miscellaneous; 11606 } 11607 11608 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11609 Expr *Constant, Expr *Other, 11610 const llvm::APSInt &Value, 11611 bool RhsConstant) { 11612 if (S.inTemplateInstantiation()) 11613 return false; 11614 11615 Expr *OriginalOther = Other; 11616 11617 Constant = Constant->IgnoreParenImpCasts(); 11618 Other = Other->IgnoreParenImpCasts(); 11619 11620 // Suppress warnings on tautological comparisons between values of the same 11621 // enumeration type. There are only two ways we could warn on this: 11622 // - If the constant is outside the range of representable values of 11623 // the enumeration. In such a case, we should warn about the cast 11624 // to enumeration type, not about the comparison. 11625 // - If the constant is the maximum / minimum in-range value. For an 11626 // enumeratin type, such comparisons can be meaningful and useful. 11627 if (Constant->getType()->isEnumeralType() && 11628 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11629 return false; 11630 11631 IntRange OtherValueRange = GetExprRange( 11632 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11633 11634 QualType OtherT = Other->getType(); 11635 if (const auto *AT = OtherT->getAs<AtomicType>()) 11636 OtherT = AT->getValueType(); 11637 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11638 11639 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11640 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11641 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11642 S.NSAPIObj->isObjCBOOLType(OtherT) && 11643 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11644 11645 // Whether we're treating Other as being a bool because of the form of 11646 // expression despite it having another type (typically 'int' in C). 11647 bool OtherIsBooleanDespiteType = 11648 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11649 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11650 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11651 11652 // Check if all values in the range of possible values of this expression 11653 // lead to the same comparison outcome. 11654 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11655 Value.isUnsigned()); 11656 auto Cmp = OtherPromotedValueRange.compare(Value); 11657 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11658 if (!Result) 11659 return false; 11660 11661 // Also consider the range determined by the type alone. This allows us to 11662 // classify the warning under the proper diagnostic group. 11663 bool TautologicalTypeCompare = false; 11664 { 11665 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11666 Value.isUnsigned()); 11667 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11668 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11669 RhsConstant)) { 11670 TautologicalTypeCompare = true; 11671 Cmp = TypeCmp; 11672 Result = TypeResult; 11673 } 11674 } 11675 11676 // Don't warn if the non-constant operand actually always evaluates to the 11677 // same value. 11678 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11679 return false; 11680 11681 // Suppress the diagnostic for an in-range comparison if the constant comes 11682 // from a macro or enumerator. We don't want to diagnose 11683 // 11684 // some_long_value <= INT_MAX 11685 // 11686 // when sizeof(int) == sizeof(long). 11687 bool InRange = Cmp & PromotedRange::InRangeFlag; 11688 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11689 return false; 11690 11691 // A comparison of an unsigned bit-field against 0 is really a type problem, 11692 // even though at the type level the bit-field might promote to 'signed int'. 11693 if (Other->refersToBitField() && InRange && Value == 0 && 11694 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11695 TautologicalTypeCompare = true; 11696 11697 // If this is a comparison to an enum constant, include that 11698 // constant in the diagnostic. 11699 const EnumConstantDecl *ED = nullptr; 11700 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11701 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11702 11703 // Should be enough for uint128 (39 decimal digits) 11704 SmallString<64> PrettySourceValue; 11705 llvm::raw_svector_ostream OS(PrettySourceValue); 11706 if (ED) { 11707 OS << '\'' << *ED << "' (" << Value << ")"; 11708 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11709 Constant->IgnoreParenImpCasts())) { 11710 OS << (BL->getValue() ? "YES" : "NO"); 11711 } else { 11712 OS << Value; 11713 } 11714 11715 if (!TautologicalTypeCompare) { 11716 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11717 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11718 << E->getOpcodeStr() << OS.str() << *Result 11719 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11720 return true; 11721 } 11722 11723 if (IsObjCSignedCharBool) { 11724 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11725 S.PDiag(diag::warn_tautological_compare_objc_bool) 11726 << OS.str() << *Result); 11727 return true; 11728 } 11729 11730 // FIXME: We use a somewhat different formatting for the in-range cases and 11731 // cases involving boolean values for historical reasons. We should pick a 11732 // consistent way of presenting these diagnostics. 11733 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11734 11735 S.DiagRuntimeBehavior( 11736 E->getOperatorLoc(), E, 11737 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11738 : diag::warn_tautological_bool_compare) 11739 << OS.str() << classifyConstantValue(Constant) << OtherT 11740 << OtherIsBooleanDespiteType << *Result 11741 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11742 } else { 11743 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11744 unsigned Diag = 11745 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11746 ? (HasEnumType(OriginalOther) 11747 ? diag::warn_unsigned_enum_always_true_comparison 11748 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11749 : diag::warn_unsigned_always_true_comparison) 11750 : diag::warn_tautological_constant_compare; 11751 11752 S.Diag(E->getOperatorLoc(), Diag) 11753 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11754 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11755 } 11756 11757 return true; 11758 } 11759 11760 /// Analyze the operands of the given comparison. Implements the 11761 /// fallback case from AnalyzeComparison. 11762 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11763 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11764 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11765 } 11766 11767 /// Implements -Wsign-compare. 11768 /// 11769 /// \param E the binary operator to check for warnings 11770 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11771 // The type the comparison is being performed in. 11772 QualType T = E->getLHS()->getType(); 11773 11774 // Only analyze comparison operators where both sides have been converted to 11775 // the same type. 11776 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11777 return AnalyzeImpConvsInComparison(S, E); 11778 11779 // Don't analyze value-dependent comparisons directly. 11780 if (E->isValueDependent()) 11781 return AnalyzeImpConvsInComparison(S, E); 11782 11783 Expr *LHS = E->getLHS(); 11784 Expr *RHS = E->getRHS(); 11785 11786 if (T->isIntegralType(S.Context)) { 11787 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11788 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11789 11790 // We don't care about expressions whose result is a constant. 11791 if (RHSValue && LHSValue) 11792 return AnalyzeImpConvsInComparison(S, E); 11793 11794 // We only care about expressions where just one side is literal 11795 if ((bool)RHSValue ^ (bool)LHSValue) { 11796 // Is the constant on the RHS or LHS? 11797 const bool RhsConstant = (bool)RHSValue; 11798 Expr *Const = RhsConstant ? RHS : LHS; 11799 Expr *Other = RhsConstant ? LHS : RHS; 11800 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11801 11802 // Check whether an integer constant comparison results in a value 11803 // of 'true' or 'false'. 11804 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11805 return AnalyzeImpConvsInComparison(S, E); 11806 } 11807 } 11808 11809 if (!T->hasUnsignedIntegerRepresentation()) { 11810 // We don't do anything special if this isn't an unsigned integral 11811 // comparison: we're only interested in integral comparisons, and 11812 // signed comparisons only happen in cases we don't care to warn about. 11813 return AnalyzeImpConvsInComparison(S, E); 11814 } 11815 11816 LHS = LHS->IgnoreParenImpCasts(); 11817 RHS = RHS->IgnoreParenImpCasts(); 11818 11819 if (!S.getLangOpts().CPlusPlus) { 11820 // Avoid warning about comparison of integers with different signs when 11821 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11822 // the type of `E`. 11823 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11824 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11825 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11826 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11827 } 11828 11829 // Check to see if one of the (unmodified) operands is of different 11830 // signedness. 11831 Expr *signedOperand, *unsignedOperand; 11832 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11833 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11834 "unsigned comparison between two signed integer expressions?"); 11835 signedOperand = LHS; 11836 unsignedOperand = RHS; 11837 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11838 signedOperand = RHS; 11839 unsignedOperand = LHS; 11840 } else { 11841 return AnalyzeImpConvsInComparison(S, E); 11842 } 11843 11844 // Otherwise, calculate the effective range of the signed operand. 11845 IntRange signedRange = GetExprRange( 11846 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11847 11848 // Go ahead and analyze implicit conversions in the operands. Note 11849 // that we skip the implicit conversions on both sides. 11850 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11851 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11852 11853 // If the signed range is non-negative, -Wsign-compare won't fire. 11854 if (signedRange.NonNegative) 11855 return; 11856 11857 // For (in)equality comparisons, if the unsigned operand is a 11858 // constant which cannot collide with a overflowed signed operand, 11859 // then reinterpreting the signed operand as unsigned will not 11860 // change the result of the comparison. 11861 if (E->isEqualityOp()) { 11862 unsigned comparisonWidth = S.Context.getIntWidth(T); 11863 IntRange unsignedRange = 11864 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11865 /*Approximate*/ true); 11866 11867 // We should never be unable to prove that the unsigned operand is 11868 // non-negative. 11869 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11870 11871 if (unsignedRange.Width < comparisonWidth) 11872 return; 11873 } 11874 11875 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11876 S.PDiag(diag::warn_mixed_sign_comparison) 11877 << LHS->getType() << RHS->getType() 11878 << LHS->getSourceRange() << RHS->getSourceRange()); 11879 } 11880 11881 /// Analyzes an attempt to assign the given value to a bitfield. 11882 /// 11883 /// Returns true if there was something fishy about the attempt. 11884 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11885 SourceLocation InitLoc) { 11886 assert(Bitfield->isBitField()); 11887 if (Bitfield->isInvalidDecl()) 11888 return false; 11889 11890 // White-list bool bitfields. 11891 QualType BitfieldType = Bitfield->getType(); 11892 if (BitfieldType->isBooleanType()) 11893 return false; 11894 11895 if (BitfieldType->isEnumeralType()) { 11896 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11897 // If the underlying enum type was not explicitly specified as an unsigned 11898 // type and the enum contain only positive values, MSVC++ will cause an 11899 // inconsistency by storing this as a signed type. 11900 if (S.getLangOpts().CPlusPlus11 && 11901 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11902 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11903 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11904 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11905 << BitfieldEnumDecl; 11906 } 11907 } 11908 11909 if (Bitfield->getType()->isBooleanType()) 11910 return false; 11911 11912 // Ignore value- or type-dependent expressions. 11913 if (Bitfield->getBitWidth()->isValueDependent() || 11914 Bitfield->getBitWidth()->isTypeDependent() || 11915 Init->isValueDependent() || 11916 Init->isTypeDependent()) 11917 return false; 11918 11919 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11920 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11921 11922 Expr::EvalResult Result; 11923 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11924 Expr::SE_AllowSideEffects)) { 11925 // The RHS is not constant. If the RHS has an enum type, make sure the 11926 // bitfield is wide enough to hold all the values of the enum without 11927 // truncation. 11928 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11929 EnumDecl *ED = EnumTy->getDecl(); 11930 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11931 11932 // Enum types are implicitly signed on Windows, so check if there are any 11933 // negative enumerators to see if the enum was intended to be signed or 11934 // not. 11935 bool SignedEnum = ED->getNumNegativeBits() > 0; 11936 11937 // Check for surprising sign changes when assigning enum values to a 11938 // bitfield of different signedness. If the bitfield is signed and we 11939 // have exactly the right number of bits to store this unsigned enum, 11940 // suggest changing the enum to an unsigned type. This typically happens 11941 // on Windows where unfixed enums always use an underlying type of 'int'. 11942 unsigned DiagID = 0; 11943 if (SignedEnum && !SignedBitfield) { 11944 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11945 } else if (SignedBitfield && !SignedEnum && 11946 ED->getNumPositiveBits() == FieldWidth) { 11947 DiagID = diag::warn_signed_bitfield_enum_conversion; 11948 } 11949 11950 if (DiagID) { 11951 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11952 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11953 SourceRange TypeRange = 11954 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11955 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11956 << SignedEnum << TypeRange; 11957 } 11958 11959 // Compute the required bitwidth. If the enum has negative values, we need 11960 // one more bit than the normal number of positive bits to represent the 11961 // sign bit. 11962 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11963 ED->getNumNegativeBits()) 11964 : ED->getNumPositiveBits(); 11965 11966 // Check the bitwidth. 11967 if (BitsNeeded > FieldWidth) { 11968 Expr *WidthExpr = Bitfield->getBitWidth(); 11969 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11970 << Bitfield << ED; 11971 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11972 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11973 } 11974 } 11975 11976 return false; 11977 } 11978 11979 llvm::APSInt Value = Result.Val.getInt(); 11980 11981 unsigned OriginalWidth = Value.getBitWidth(); 11982 11983 if (!Value.isSigned() || Value.isNegative()) 11984 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11985 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11986 OriginalWidth = Value.getMinSignedBits(); 11987 11988 if (OriginalWidth <= FieldWidth) 11989 return false; 11990 11991 // Compute the value which the bitfield will contain. 11992 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11993 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11994 11995 // Check whether the stored value is equal to the original value. 11996 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11997 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11998 return false; 11999 12000 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12001 // therefore don't strictly fit into a signed bitfield of width 1. 12002 if (FieldWidth == 1 && Value == 1) 12003 return false; 12004 12005 std::string PrettyValue = toString(Value, 10); 12006 std::string PrettyTrunc = toString(TruncatedValue, 10); 12007 12008 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12009 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12010 << Init->getSourceRange(); 12011 12012 return true; 12013 } 12014 12015 /// Analyze the given simple or compound assignment for warning-worthy 12016 /// operations. 12017 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12018 // Just recurse on the LHS. 12019 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12020 12021 // We want to recurse on the RHS as normal unless we're assigning to 12022 // a bitfield. 12023 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12024 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12025 E->getOperatorLoc())) { 12026 // Recurse, ignoring any implicit conversions on the RHS. 12027 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12028 E->getOperatorLoc()); 12029 } 12030 } 12031 12032 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12033 12034 // Diagnose implicitly sequentially-consistent atomic assignment. 12035 if (E->getLHS()->getType()->isAtomicType()) 12036 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12037 } 12038 12039 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12040 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12041 SourceLocation CContext, unsigned diag, 12042 bool pruneControlFlow = false) { 12043 if (pruneControlFlow) { 12044 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12045 S.PDiag(diag) 12046 << SourceType << T << E->getSourceRange() 12047 << SourceRange(CContext)); 12048 return; 12049 } 12050 S.Diag(E->getExprLoc(), diag) 12051 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12052 } 12053 12054 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12055 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12056 SourceLocation CContext, 12057 unsigned diag, bool pruneControlFlow = false) { 12058 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12059 } 12060 12061 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12062 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12063 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12064 } 12065 12066 static void adornObjCBoolConversionDiagWithTernaryFixit( 12067 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12068 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12069 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12070 Ignored = OVE->getSourceExpr(); 12071 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12072 isa<BinaryOperator>(Ignored) || 12073 isa<CXXOperatorCallExpr>(Ignored); 12074 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12075 if (NeedsParens) 12076 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12077 << FixItHint::CreateInsertion(EndLoc, ")"); 12078 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12079 } 12080 12081 /// Diagnose an implicit cast from a floating point value to an integer value. 12082 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12083 SourceLocation CContext) { 12084 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12085 const bool PruneWarnings = S.inTemplateInstantiation(); 12086 12087 Expr *InnerE = E->IgnoreParenImpCasts(); 12088 // We also want to warn on, e.g., "int i = -1.234" 12089 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12090 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12091 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12092 12093 const bool IsLiteral = 12094 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12095 12096 llvm::APFloat Value(0.0); 12097 bool IsConstant = 12098 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12099 if (!IsConstant) { 12100 if (isObjCSignedCharBool(S, T)) { 12101 return adornObjCBoolConversionDiagWithTernaryFixit( 12102 S, E, 12103 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12104 << E->getType()); 12105 } 12106 12107 return DiagnoseImpCast(S, E, T, CContext, 12108 diag::warn_impcast_float_integer, PruneWarnings); 12109 } 12110 12111 bool isExact = false; 12112 12113 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12114 T->hasUnsignedIntegerRepresentation()); 12115 llvm::APFloat::opStatus Result = Value.convertToInteger( 12116 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12117 12118 // FIXME: Force the precision of the source value down so we don't print 12119 // digits which are usually useless (we don't really care here if we 12120 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12121 // would automatically print the shortest representation, but it's a bit 12122 // tricky to implement. 12123 SmallString<16> PrettySourceValue; 12124 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12125 precision = (precision * 59 + 195) / 196; 12126 Value.toString(PrettySourceValue, precision); 12127 12128 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12129 return adornObjCBoolConversionDiagWithTernaryFixit( 12130 S, E, 12131 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12132 << PrettySourceValue); 12133 } 12134 12135 if (Result == llvm::APFloat::opOK && isExact) { 12136 if (IsLiteral) return; 12137 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12138 PruneWarnings); 12139 } 12140 12141 // Conversion of a floating-point value to a non-bool integer where the 12142 // integral part cannot be represented by the integer type is undefined. 12143 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12144 return DiagnoseImpCast( 12145 S, E, T, CContext, 12146 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12147 : diag::warn_impcast_float_to_integer_out_of_range, 12148 PruneWarnings); 12149 12150 unsigned DiagID = 0; 12151 if (IsLiteral) { 12152 // Warn on floating point literal to integer. 12153 DiagID = diag::warn_impcast_literal_float_to_integer; 12154 } else if (IntegerValue == 0) { 12155 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12156 return DiagnoseImpCast(S, E, T, CContext, 12157 diag::warn_impcast_float_integer, PruneWarnings); 12158 } 12159 // Warn on non-zero to zero conversion. 12160 DiagID = diag::warn_impcast_float_to_integer_zero; 12161 } else { 12162 if (IntegerValue.isUnsigned()) { 12163 if (!IntegerValue.isMaxValue()) { 12164 return DiagnoseImpCast(S, E, T, CContext, 12165 diag::warn_impcast_float_integer, PruneWarnings); 12166 } 12167 } else { // IntegerValue.isSigned() 12168 if (!IntegerValue.isMaxSignedValue() && 12169 !IntegerValue.isMinSignedValue()) { 12170 return DiagnoseImpCast(S, E, T, CContext, 12171 diag::warn_impcast_float_integer, PruneWarnings); 12172 } 12173 } 12174 // Warn on evaluatable floating point expression to integer conversion. 12175 DiagID = diag::warn_impcast_float_to_integer; 12176 } 12177 12178 SmallString<16> PrettyTargetValue; 12179 if (IsBool) 12180 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12181 else 12182 IntegerValue.toString(PrettyTargetValue); 12183 12184 if (PruneWarnings) { 12185 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12186 S.PDiag(DiagID) 12187 << E->getType() << T.getUnqualifiedType() 12188 << PrettySourceValue << PrettyTargetValue 12189 << E->getSourceRange() << SourceRange(CContext)); 12190 } else { 12191 S.Diag(E->getExprLoc(), DiagID) 12192 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12193 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12194 } 12195 } 12196 12197 /// Analyze the given compound assignment for the possible losing of 12198 /// floating-point precision. 12199 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12200 assert(isa<CompoundAssignOperator>(E) && 12201 "Must be compound assignment operation"); 12202 // Recurse on the LHS and RHS in here 12203 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12204 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12205 12206 if (E->getLHS()->getType()->isAtomicType()) 12207 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12208 12209 // Now check the outermost expression 12210 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12211 const auto *RBT = cast<CompoundAssignOperator>(E) 12212 ->getComputationResultType() 12213 ->getAs<BuiltinType>(); 12214 12215 // The below checks assume source is floating point. 12216 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12217 12218 // If source is floating point but target is an integer. 12219 if (ResultBT->isInteger()) 12220 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12221 E->getExprLoc(), diag::warn_impcast_float_integer); 12222 12223 if (!ResultBT->isFloatingPoint()) 12224 return; 12225 12226 // If both source and target are floating points, warn about losing precision. 12227 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12228 QualType(ResultBT, 0), QualType(RBT, 0)); 12229 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12230 // warn about dropping FP rank. 12231 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12232 diag::warn_impcast_float_result_precision); 12233 } 12234 12235 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12236 IntRange Range) { 12237 if (!Range.Width) return "0"; 12238 12239 llvm::APSInt ValueInRange = Value; 12240 ValueInRange.setIsSigned(!Range.NonNegative); 12241 ValueInRange = ValueInRange.trunc(Range.Width); 12242 return toString(ValueInRange, 10); 12243 } 12244 12245 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12246 if (!isa<ImplicitCastExpr>(Ex)) 12247 return false; 12248 12249 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12250 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12251 const Type *Source = 12252 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12253 if (Target->isDependentType()) 12254 return false; 12255 12256 const BuiltinType *FloatCandidateBT = 12257 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12258 const Type *BoolCandidateType = ToBool ? Target : Source; 12259 12260 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12261 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12262 } 12263 12264 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12265 SourceLocation CC) { 12266 unsigned NumArgs = TheCall->getNumArgs(); 12267 for (unsigned i = 0; i < NumArgs; ++i) { 12268 Expr *CurrA = TheCall->getArg(i); 12269 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12270 continue; 12271 12272 bool IsSwapped = ((i > 0) && 12273 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12274 IsSwapped |= ((i < (NumArgs - 1)) && 12275 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12276 if (IsSwapped) { 12277 // Warn on this floating-point to bool conversion. 12278 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12279 CurrA->getType(), CC, 12280 diag::warn_impcast_floating_point_to_bool); 12281 } 12282 } 12283 } 12284 12285 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12286 SourceLocation CC) { 12287 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12288 E->getExprLoc())) 12289 return; 12290 12291 // Don't warn on functions which have return type nullptr_t. 12292 if (isa<CallExpr>(E)) 12293 return; 12294 12295 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12296 const Expr::NullPointerConstantKind NullKind = 12297 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12298 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12299 return; 12300 12301 // Return if target type is a safe conversion. 12302 if (T->isAnyPointerType() || T->isBlockPointerType() || 12303 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12304 return; 12305 12306 SourceLocation Loc = E->getSourceRange().getBegin(); 12307 12308 // Venture through the macro stacks to get to the source of macro arguments. 12309 // The new location is a better location than the complete location that was 12310 // passed in. 12311 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12312 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12313 12314 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12315 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12316 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12317 Loc, S.SourceMgr, S.getLangOpts()); 12318 if (MacroName == "NULL") 12319 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12320 } 12321 12322 // Only warn if the null and context location are in the same macro expansion. 12323 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12324 return; 12325 12326 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12327 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12328 << FixItHint::CreateReplacement(Loc, 12329 S.getFixItZeroLiteralForType(T, Loc)); 12330 } 12331 12332 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12333 ObjCArrayLiteral *ArrayLiteral); 12334 12335 static void 12336 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12337 ObjCDictionaryLiteral *DictionaryLiteral); 12338 12339 /// Check a single element within a collection literal against the 12340 /// target element type. 12341 static void checkObjCCollectionLiteralElement(Sema &S, 12342 QualType TargetElementType, 12343 Expr *Element, 12344 unsigned ElementKind) { 12345 // Skip a bitcast to 'id' or qualified 'id'. 12346 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12347 if (ICE->getCastKind() == CK_BitCast && 12348 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12349 Element = ICE->getSubExpr(); 12350 } 12351 12352 QualType ElementType = Element->getType(); 12353 ExprResult ElementResult(Element); 12354 if (ElementType->getAs<ObjCObjectPointerType>() && 12355 S.CheckSingleAssignmentConstraints(TargetElementType, 12356 ElementResult, 12357 false, false) 12358 != Sema::Compatible) { 12359 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12360 << ElementType << ElementKind << TargetElementType 12361 << Element->getSourceRange(); 12362 } 12363 12364 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12365 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12366 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12367 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12368 } 12369 12370 /// Check an Objective-C array literal being converted to the given 12371 /// target type. 12372 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12373 ObjCArrayLiteral *ArrayLiteral) { 12374 if (!S.NSArrayDecl) 12375 return; 12376 12377 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12378 if (!TargetObjCPtr) 12379 return; 12380 12381 if (TargetObjCPtr->isUnspecialized() || 12382 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12383 != S.NSArrayDecl->getCanonicalDecl()) 12384 return; 12385 12386 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12387 if (TypeArgs.size() != 1) 12388 return; 12389 12390 QualType TargetElementType = TypeArgs[0]; 12391 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12392 checkObjCCollectionLiteralElement(S, TargetElementType, 12393 ArrayLiteral->getElement(I), 12394 0); 12395 } 12396 } 12397 12398 /// Check an Objective-C dictionary literal being converted to the given 12399 /// target type. 12400 static void 12401 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12402 ObjCDictionaryLiteral *DictionaryLiteral) { 12403 if (!S.NSDictionaryDecl) 12404 return; 12405 12406 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12407 if (!TargetObjCPtr) 12408 return; 12409 12410 if (TargetObjCPtr->isUnspecialized() || 12411 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12412 != S.NSDictionaryDecl->getCanonicalDecl()) 12413 return; 12414 12415 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12416 if (TypeArgs.size() != 2) 12417 return; 12418 12419 QualType TargetKeyType = TypeArgs[0]; 12420 QualType TargetObjectType = TypeArgs[1]; 12421 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12422 auto Element = DictionaryLiteral->getKeyValueElement(I); 12423 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12424 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12425 } 12426 } 12427 12428 // Helper function to filter out cases for constant width constant conversion. 12429 // Don't warn on char array initialization or for non-decimal values. 12430 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12431 SourceLocation CC) { 12432 // If initializing from a constant, and the constant starts with '0', 12433 // then it is a binary, octal, or hexadecimal. Allow these constants 12434 // to fill all the bits, even if there is a sign change. 12435 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12436 const char FirstLiteralCharacter = 12437 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12438 if (FirstLiteralCharacter == '0') 12439 return false; 12440 } 12441 12442 // If the CC location points to a '{', and the type is char, then assume 12443 // assume it is an array initialization. 12444 if (CC.isValid() && T->isCharType()) { 12445 const char FirstContextCharacter = 12446 S.getSourceManager().getCharacterData(CC)[0]; 12447 if (FirstContextCharacter == '{') 12448 return false; 12449 } 12450 12451 return true; 12452 } 12453 12454 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12455 const auto *IL = dyn_cast<IntegerLiteral>(E); 12456 if (!IL) { 12457 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12458 if (UO->getOpcode() == UO_Minus) 12459 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12460 } 12461 } 12462 12463 return IL; 12464 } 12465 12466 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12467 E = E->IgnoreParenImpCasts(); 12468 SourceLocation ExprLoc = E->getExprLoc(); 12469 12470 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12471 BinaryOperator::Opcode Opc = BO->getOpcode(); 12472 Expr::EvalResult Result; 12473 // Do not diagnose unsigned shifts. 12474 if (Opc == BO_Shl) { 12475 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12476 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12477 if (LHS && LHS->getValue() == 0) 12478 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12479 else if (!E->isValueDependent() && LHS && RHS && 12480 RHS->getValue().isNonNegative() && 12481 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12482 S.Diag(ExprLoc, diag::warn_left_shift_always) 12483 << (Result.Val.getInt() != 0); 12484 else if (E->getType()->isSignedIntegerType()) 12485 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12486 } 12487 } 12488 12489 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12490 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12491 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12492 if (!LHS || !RHS) 12493 return; 12494 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12495 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12496 // Do not diagnose common idioms. 12497 return; 12498 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12499 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12500 } 12501 } 12502 12503 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12504 SourceLocation CC, 12505 bool *ICContext = nullptr, 12506 bool IsListInit = false) { 12507 if (E->isTypeDependent() || E->isValueDependent()) return; 12508 12509 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12510 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12511 if (Source == Target) return; 12512 if (Target->isDependentType()) return; 12513 12514 // If the conversion context location is invalid don't complain. We also 12515 // don't want to emit a warning if the issue occurs from the expansion of 12516 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12517 // delay this check as long as possible. Once we detect we are in that 12518 // scenario, we just return. 12519 if (CC.isInvalid()) 12520 return; 12521 12522 if (Source->isAtomicType()) 12523 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12524 12525 // Diagnose implicit casts to bool. 12526 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12527 if (isa<StringLiteral>(E)) 12528 // Warn on string literal to bool. Checks for string literals in logical 12529 // and expressions, for instance, assert(0 && "error here"), are 12530 // prevented by a check in AnalyzeImplicitConversions(). 12531 return DiagnoseImpCast(S, E, T, CC, 12532 diag::warn_impcast_string_literal_to_bool); 12533 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12534 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12535 // This covers the literal expressions that evaluate to Objective-C 12536 // objects. 12537 return DiagnoseImpCast(S, E, T, CC, 12538 diag::warn_impcast_objective_c_literal_to_bool); 12539 } 12540 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12541 // Warn on pointer to bool conversion that is always true. 12542 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12543 SourceRange(CC)); 12544 } 12545 } 12546 12547 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12548 // is a typedef for signed char (macOS), then that constant value has to be 1 12549 // or 0. 12550 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12551 Expr::EvalResult Result; 12552 if (E->EvaluateAsInt(Result, S.getASTContext(), 12553 Expr::SE_AllowSideEffects)) { 12554 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12555 adornObjCBoolConversionDiagWithTernaryFixit( 12556 S, E, 12557 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12558 << toString(Result.Val.getInt(), 10)); 12559 } 12560 return; 12561 } 12562 } 12563 12564 // Check implicit casts from Objective-C collection literals to specialized 12565 // collection types, e.g., NSArray<NSString *> *. 12566 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12567 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12568 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12569 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12570 12571 // Strip vector types. 12572 if (const auto *SourceVT = dyn_cast<VectorType>(Source)) { 12573 if (Target->isVLSTBuiltinType()) { 12574 auto SourceVectorKind = SourceVT->getVectorKind(); 12575 if (SourceVectorKind == VectorType::SveFixedLengthDataVector || 12576 SourceVectorKind == VectorType::SveFixedLengthPredicateVector || 12577 (SourceVectorKind == VectorType::GenericVector && 12578 S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits)) 12579 return; 12580 } 12581 12582 if (!isa<VectorType>(Target)) { 12583 if (S.SourceMgr.isInSystemMacro(CC)) 12584 return; 12585 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12586 } 12587 12588 // If the vector cast is cast between two vectors of the same size, it is 12589 // a bitcast, not a conversion. 12590 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12591 return; 12592 12593 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12594 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12595 } 12596 if (auto VecTy = dyn_cast<VectorType>(Target)) 12597 Target = VecTy->getElementType().getTypePtr(); 12598 12599 // Strip complex types. 12600 if (isa<ComplexType>(Source)) { 12601 if (!isa<ComplexType>(Target)) { 12602 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12603 return; 12604 12605 return DiagnoseImpCast(S, E, T, CC, 12606 S.getLangOpts().CPlusPlus 12607 ? diag::err_impcast_complex_scalar 12608 : diag::warn_impcast_complex_scalar); 12609 } 12610 12611 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12612 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12613 } 12614 12615 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12616 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12617 12618 // If the source is floating point... 12619 if (SourceBT && SourceBT->isFloatingPoint()) { 12620 // ...and the target is floating point... 12621 if (TargetBT && TargetBT->isFloatingPoint()) { 12622 // ...then warn if we're dropping FP rank. 12623 12624 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12625 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12626 if (Order > 0) { 12627 // Don't warn about float constants that are precisely 12628 // representable in the target type. 12629 Expr::EvalResult result; 12630 if (E->EvaluateAsRValue(result, S.Context)) { 12631 // Value might be a float, a float vector, or a float complex. 12632 if (IsSameFloatAfterCast(result.Val, 12633 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12634 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12635 return; 12636 } 12637 12638 if (S.SourceMgr.isInSystemMacro(CC)) 12639 return; 12640 12641 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12642 } 12643 // ... or possibly if we're increasing rank, too 12644 else if (Order < 0) { 12645 if (S.SourceMgr.isInSystemMacro(CC)) 12646 return; 12647 12648 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12649 } 12650 return; 12651 } 12652 12653 // If the target is integral, always warn. 12654 if (TargetBT && TargetBT->isInteger()) { 12655 if (S.SourceMgr.isInSystemMacro(CC)) 12656 return; 12657 12658 DiagnoseFloatingImpCast(S, E, T, CC); 12659 } 12660 12661 // Detect the case where a call result is converted from floating-point to 12662 // to bool, and the final argument to the call is converted from bool, to 12663 // discover this typo: 12664 // 12665 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12666 // 12667 // FIXME: This is an incredibly special case; is there some more general 12668 // way to detect this class of misplaced-parentheses bug? 12669 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12670 // Check last argument of function call to see if it is an 12671 // implicit cast from a type matching the type the result 12672 // is being cast to. 12673 CallExpr *CEx = cast<CallExpr>(E); 12674 if (unsigned NumArgs = CEx->getNumArgs()) { 12675 Expr *LastA = CEx->getArg(NumArgs - 1); 12676 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12677 if (isa<ImplicitCastExpr>(LastA) && 12678 InnerE->getType()->isBooleanType()) { 12679 // Warn on this floating-point to bool conversion 12680 DiagnoseImpCast(S, E, T, CC, 12681 diag::warn_impcast_floating_point_to_bool); 12682 } 12683 } 12684 } 12685 return; 12686 } 12687 12688 // Valid casts involving fixed point types should be accounted for here. 12689 if (Source->isFixedPointType()) { 12690 if (Target->isUnsaturatedFixedPointType()) { 12691 Expr::EvalResult Result; 12692 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12693 S.isConstantEvaluated())) { 12694 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12695 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12696 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12697 if (Value > MaxVal || Value < MinVal) { 12698 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12699 S.PDiag(diag::warn_impcast_fixed_point_range) 12700 << Value.toString() << T 12701 << E->getSourceRange() 12702 << clang::SourceRange(CC)); 12703 return; 12704 } 12705 } 12706 } else if (Target->isIntegerType()) { 12707 Expr::EvalResult Result; 12708 if (!S.isConstantEvaluated() && 12709 E->EvaluateAsFixedPoint(Result, S.Context, 12710 Expr::SE_AllowSideEffects)) { 12711 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12712 12713 bool Overflowed; 12714 llvm::APSInt IntResult = FXResult.convertToInt( 12715 S.Context.getIntWidth(T), 12716 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12717 12718 if (Overflowed) { 12719 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12720 S.PDiag(diag::warn_impcast_fixed_point_range) 12721 << FXResult.toString() << T 12722 << E->getSourceRange() 12723 << clang::SourceRange(CC)); 12724 return; 12725 } 12726 } 12727 } 12728 } else if (Target->isUnsaturatedFixedPointType()) { 12729 if (Source->isIntegerType()) { 12730 Expr::EvalResult Result; 12731 if (!S.isConstantEvaluated() && 12732 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12733 llvm::APSInt Value = Result.Val.getInt(); 12734 12735 bool Overflowed; 12736 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12737 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12738 12739 if (Overflowed) { 12740 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12741 S.PDiag(diag::warn_impcast_fixed_point_range) 12742 << toString(Value, /*Radix=*/10) << T 12743 << E->getSourceRange() 12744 << clang::SourceRange(CC)); 12745 return; 12746 } 12747 } 12748 } 12749 } 12750 12751 // If we are casting an integer type to a floating point type without 12752 // initialization-list syntax, we might lose accuracy if the floating 12753 // point type has a narrower significand than the integer type. 12754 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12755 TargetBT->isFloatingType() && !IsListInit) { 12756 // Determine the number of precision bits in the source integer type. 12757 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12758 /*Approximate*/ true); 12759 unsigned int SourcePrecision = SourceRange.Width; 12760 12761 // Determine the number of precision bits in the 12762 // target floating point type. 12763 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12764 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12765 12766 if (SourcePrecision > 0 && TargetPrecision > 0 && 12767 SourcePrecision > TargetPrecision) { 12768 12769 if (Optional<llvm::APSInt> SourceInt = 12770 E->getIntegerConstantExpr(S.Context)) { 12771 // If the source integer is a constant, convert it to the target 12772 // floating point type. Issue a warning if the value changes 12773 // during the whole conversion. 12774 llvm::APFloat TargetFloatValue( 12775 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12776 llvm::APFloat::opStatus ConversionStatus = 12777 TargetFloatValue.convertFromAPInt( 12778 *SourceInt, SourceBT->isSignedInteger(), 12779 llvm::APFloat::rmNearestTiesToEven); 12780 12781 if (ConversionStatus != llvm::APFloat::opOK) { 12782 SmallString<32> PrettySourceValue; 12783 SourceInt->toString(PrettySourceValue, 10); 12784 SmallString<32> PrettyTargetValue; 12785 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12786 12787 S.DiagRuntimeBehavior( 12788 E->getExprLoc(), E, 12789 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12790 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12791 << E->getSourceRange() << clang::SourceRange(CC)); 12792 } 12793 } else { 12794 // Otherwise, the implicit conversion may lose precision. 12795 DiagnoseImpCast(S, E, T, CC, 12796 diag::warn_impcast_integer_float_precision); 12797 } 12798 } 12799 } 12800 12801 DiagnoseNullConversion(S, E, T, CC); 12802 12803 S.DiscardMisalignedMemberAddress(Target, E); 12804 12805 if (Target->isBooleanType()) 12806 DiagnoseIntInBoolContext(S, E); 12807 12808 if (!Source->isIntegerType() || !Target->isIntegerType()) 12809 return; 12810 12811 // TODO: remove this early return once the false positives for constant->bool 12812 // in templates, macros, etc, are reduced or removed. 12813 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12814 return; 12815 12816 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12817 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12818 return adornObjCBoolConversionDiagWithTernaryFixit( 12819 S, E, 12820 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12821 << E->getType()); 12822 } 12823 12824 IntRange SourceTypeRange = 12825 IntRange::forTargetOfCanonicalType(S.Context, Source); 12826 IntRange LikelySourceRange = 12827 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12828 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12829 12830 if (LikelySourceRange.Width > TargetRange.Width) { 12831 // If the source is a constant, use a default-on diagnostic. 12832 // TODO: this should happen for bitfield stores, too. 12833 Expr::EvalResult Result; 12834 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12835 S.isConstantEvaluated())) { 12836 llvm::APSInt Value(32); 12837 Value = Result.Val.getInt(); 12838 12839 if (S.SourceMgr.isInSystemMacro(CC)) 12840 return; 12841 12842 std::string PrettySourceValue = toString(Value, 10); 12843 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12844 12845 S.DiagRuntimeBehavior( 12846 E->getExprLoc(), E, 12847 S.PDiag(diag::warn_impcast_integer_precision_constant) 12848 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12849 << E->getSourceRange() << SourceRange(CC)); 12850 return; 12851 } 12852 12853 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12854 if (S.SourceMgr.isInSystemMacro(CC)) 12855 return; 12856 12857 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12858 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12859 /* pruneControlFlow */ true); 12860 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12861 } 12862 12863 if (TargetRange.Width > SourceTypeRange.Width) { 12864 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12865 if (UO->getOpcode() == UO_Minus) 12866 if (Source->isUnsignedIntegerType()) { 12867 if (Target->isUnsignedIntegerType()) 12868 return DiagnoseImpCast(S, E, T, CC, 12869 diag::warn_impcast_high_order_zero_bits); 12870 if (Target->isSignedIntegerType()) 12871 return DiagnoseImpCast(S, E, T, CC, 12872 diag::warn_impcast_nonnegative_result); 12873 } 12874 } 12875 12876 if (TargetRange.Width == LikelySourceRange.Width && 12877 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12878 Source->isSignedIntegerType()) { 12879 // Warn when doing a signed to signed conversion, warn if the positive 12880 // source value is exactly the width of the target type, which will 12881 // cause a negative value to be stored. 12882 12883 Expr::EvalResult Result; 12884 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12885 !S.SourceMgr.isInSystemMacro(CC)) { 12886 llvm::APSInt Value = Result.Val.getInt(); 12887 if (isSameWidthConstantConversion(S, E, T, CC)) { 12888 std::string PrettySourceValue = toString(Value, 10); 12889 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12890 12891 S.DiagRuntimeBehavior( 12892 E->getExprLoc(), E, 12893 S.PDiag(diag::warn_impcast_integer_precision_constant) 12894 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12895 << E->getSourceRange() << SourceRange(CC)); 12896 return; 12897 } 12898 } 12899 12900 // Fall through for non-constants to give a sign conversion warning. 12901 } 12902 12903 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12904 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12905 LikelySourceRange.Width == TargetRange.Width)) { 12906 if (S.SourceMgr.isInSystemMacro(CC)) 12907 return; 12908 12909 unsigned DiagID = diag::warn_impcast_integer_sign; 12910 12911 // Traditionally, gcc has warned about this under -Wsign-compare. 12912 // We also want to warn about it in -Wconversion. 12913 // So if -Wconversion is off, use a completely identical diagnostic 12914 // in the sign-compare group. 12915 // The conditional-checking code will 12916 if (ICContext) { 12917 DiagID = diag::warn_impcast_integer_sign_conditional; 12918 *ICContext = true; 12919 } 12920 12921 return DiagnoseImpCast(S, E, T, CC, DiagID); 12922 } 12923 12924 // Diagnose conversions between different enumeration types. 12925 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12926 // type, to give us better diagnostics. 12927 QualType SourceType = E->getType(); 12928 if (!S.getLangOpts().CPlusPlus) { 12929 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12930 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12931 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12932 SourceType = S.Context.getTypeDeclType(Enum); 12933 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12934 } 12935 } 12936 12937 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12938 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12939 if (SourceEnum->getDecl()->hasNameForLinkage() && 12940 TargetEnum->getDecl()->hasNameForLinkage() && 12941 SourceEnum != TargetEnum) { 12942 if (S.SourceMgr.isInSystemMacro(CC)) 12943 return; 12944 12945 return DiagnoseImpCast(S, E, SourceType, T, CC, 12946 diag::warn_impcast_different_enum_types); 12947 } 12948 } 12949 12950 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12951 SourceLocation CC, QualType T); 12952 12953 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12954 SourceLocation CC, bool &ICContext) { 12955 E = E->IgnoreParenImpCasts(); 12956 12957 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12958 return CheckConditionalOperator(S, CO, CC, T); 12959 12960 AnalyzeImplicitConversions(S, E, CC); 12961 if (E->getType() != T) 12962 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12963 } 12964 12965 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12966 SourceLocation CC, QualType T) { 12967 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12968 12969 Expr *TrueExpr = E->getTrueExpr(); 12970 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12971 TrueExpr = BCO->getCommon(); 12972 12973 bool Suspicious = false; 12974 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12975 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12976 12977 if (T->isBooleanType()) 12978 DiagnoseIntInBoolContext(S, E); 12979 12980 // If -Wconversion would have warned about either of the candidates 12981 // for a signedness conversion to the context type... 12982 if (!Suspicious) return; 12983 12984 // ...but it's currently ignored... 12985 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12986 return; 12987 12988 // ...then check whether it would have warned about either of the 12989 // candidates for a signedness conversion to the condition type. 12990 if (E->getType() == T) return; 12991 12992 Suspicious = false; 12993 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12994 E->getType(), CC, &Suspicious); 12995 if (!Suspicious) 12996 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12997 E->getType(), CC, &Suspicious); 12998 } 12999 13000 /// Check conversion of given expression to boolean. 13001 /// Input argument E is a logical expression. 13002 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13003 if (S.getLangOpts().Bool) 13004 return; 13005 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13006 return; 13007 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13008 } 13009 13010 namespace { 13011 struct AnalyzeImplicitConversionsWorkItem { 13012 Expr *E; 13013 SourceLocation CC; 13014 bool IsListInit; 13015 }; 13016 } 13017 13018 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13019 /// that should be visited are added to WorkList. 13020 static void AnalyzeImplicitConversions( 13021 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13022 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13023 Expr *OrigE = Item.E; 13024 SourceLocation CC = Item.CC; 13025 13026 QualType T = OrigE->getType(); 13027 Expr *E = OrigE->IgnoreParenImpCasts(); 13028 13029 // Propagate whether we are in a C++ list initialization expression. 13030 // If so, we do not issue warnings for implicit int-float conversion 13031 // precision loss, because C++11 narrowing already handles it. 13032 bool IsListInit = Item.IsListInit || 13033 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13034 13035 if (E->isTypeDependent() || E->isValueDependent()) 13036 return; 13037 13038 Expr *SourceExpr = E; 13039 // Examine, but don't traverse into the source expression of an 13040 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13041 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13042 // evaluate it in the context of checking the specific conversion to T though. 13043 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13044 if (auto *Src = OVE->getSourceExpr()) 13045 SourceExpr = Src; 13046 13047 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13048 if (UO->getOpcode() == UO_Not && 13049 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13050 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13051 << OrigE->getSourceRange() << T->isBooleanType() 13052 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13053 13054 // For conditional operators, we analyze the arguments as if they 13055 // were being fed directly into the output. 13056 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13057 CheckConditionalOperator(S, CO, CC, T); 13058 return; 13059 } 13060 13061 // Check implicit argument conversions for function calls. 13062 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13063 CheckImplicitArgumentConversions(S, Call, CC); 13064 13065 // Go ahead and check any implicit conversions we might have skipped. 13066 // The non-canonical typecheck is just an optimization; 13067 // CheckImplicitConversion will filter out dead implicit conversions. 13068 if (SourceExpr->getType() != T) 13069 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13070 13071 // Now continue drilling into this expression. 13072 13073 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13074 // The bound subexpressions in a PseudoObjectExpr are not reachable 13075 // as transitive children. 13076 // FIXME: Use a more uniform representation for this. 13077 for (auto *SE : POE->semantics()) 13078 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13079 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13080 } 13081 13082 // Skip past explicit casts. 13083 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13084 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13085 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13086 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13087 WorkList.push_back({E, CC, IsListInit}); 13088 return; 13089 } 13090 13091 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13092 // Do a somewhat different check with comparison operators. 13093 if (BO->isComparisonOp()) 13094 return AnalyzeComparison(S, BO); 13095 13096 // And with simple assignments. 13097 if (BO->getOpcode() == BO_Assign) 13098 return AnalyzeAssignment(S, BO); 13099 // And with compound assignments. 13100 if (BO->isAssignmentOp()) 13101 return AnalyzeCompoundAssignment(S, BO); 13102 } 13103 13104 // These break the otherwise-useful invariant below. Fortunately, 13105 // we don't really need to recurse into them, because any internal 13106 // expressions should have been analyzed already when they were 13107 // built into statements. 13108 if (isa<StmtExpr>(E)) return; 13109 13110 // Don't descend into unevaluated contexts. 13111 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13112 13113 // Now just recurse over the expression's children. 13114 CC = E->getExprLoc(); 13115 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13116 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13117 for (Stmt *SubStmt : E->children()) { 13118 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13119 if (!ChildExpr) 13120 continue; 13121 13122 if (IsLogicalAndOperator && 13123 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13124 // Ignore checking string literals that are in logical and operators. 13125 // This is a common pattern for asserts. 13126 continue; 13127 WorkList.push_back({ChildExpr, CC, IsListInit}); 13128 } 13129 13130 if (BO && BO->isLogicalOp()) { 13131 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13132 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13133 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13134 13135 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13136 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13137 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13138 } 13139 13140 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13141 if (U->getOpcode() == UO_LNot) { 13142 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13143 } else if (U->getOpcode() != UO_AddrOf) { 13144 if (U->getSubExpr()->getType()->isAtomicType()) 13145 S.Diag(U->getSubExpr()->getBeginLoc(), 13146 diag::warn_atomic_implicit_seq_cst); 13147 } 13148 } 13149 } 13150 13151 /// AnalyzeImplicitConversions - Find and report any interesting 13152 /// implicit conversions in the given expression. There are a couple 13153 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13154 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13155 bool IsListInit/*= false*/) { 13156 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13157 WorkList.push_back({OrigE, CC, IsListInit}); 13158 while (!WorkList.empty()) 13159 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13160 } 13161 13162 /// Diagnose integer type and any valid implicit conversion to it. 13163 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13164 // Taking into account implicit conversions, 13165 // allow any integer. 13166 if (!E->getType()->isIntegerType()) { 13167 S.Diag(E->getBeginLoc(), 13168 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13169 return true; 13170 } 13171 // Potentially emit standard warnings for implicit conversions if enabled 13172 // using -Wconversion. 13173 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13174 return false; 13175 } 13176 13177 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13178 // Returns true when emitting a warning about taking the address of a reference. 13179 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13180 const PartialDiagnostic &PD) { 13181 E = E->IgnoreParenImpCasts(); 13182 13183 const FunctionDecl *FD = nullptr; 13184 13185 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13186 if (!DRE->getDecl()->getType()->isReferenceType()) 13187 return false; 13188 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13189 if (!M->getMemberDecl()->getType()->isReferenceType()) 13190 return false; 13191 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13192 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13193 return false; 13194 FD = Call->getDirectCallee(); 13195 } else { 13196 return false; 13197 } 13198 13199 SemaRef.Diag(E->getExprLoc(), PD); 13200 13201 // If possible, point to location of function. 13202 if (FD) { 13203 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13204 } 13205 13206 return true; 13207 } 13208 13209 // Returns true if the SourceLocation is expanded from any macro body. 13210 // Returns false if the SourceLocation is invalid, is from not in a macro 13211 // expansion, or is from expanded from a top-level macro argument. 13212 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13213 if (Loc.isInvalid()) 13214 return false; 13215 13216 while (Loc.isMacroID()) { 13217 if (SM.isMacroBodyExpansion(Loc)) 13218 return true; 13219 Loc = SM.getImmediateMacroCallerLoc(Loc); 13220 } 13221 13222 return false; 13223 } 13224 13225 /// Diagnose pointers that are always non-null. 13226 /// \param E the expression containing the pointer 13227 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13228 /// compared to a null pointer 13229 /// \param IsEqual True when the comparison is equal to a null pointer 13230 /// \param Range Extra SourceRange to highlight in the diagnostic 13231 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13232 Expr::NullPointerConstantKind NullKind, 13233 bool IsEqual, SourceRange Range) { 13234 if (!E) 13235 return; 13236 13237 // Don't warn inside macros. 13238 if (E->getExprLoc().isMacroID()) { 13239 const SourceManager &SM = getSourceManager(); 13240 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13241 IsInAnyMacroBody(SM, Range.getBegin())) 13242 return; 13243 } 13244 E = E->IgnoreImpCasts(); 13245 13246 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13247 13248 if (isa<CXXThisExpr>(E)) { 13249 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13250 : diag::warn_this_bool_conversion; 13251 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13252 return; 13253 } 13254 13255 bool IsAddressOf = false; 13256 13257 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13258 if (UO->getOpcode() != UO_AddrOf) 13259 return; 13260 IsAddressOf = true; 13261 E = UO->getSubExpr(); 13262 } 13263 13264 if (IsAddressOf) { 13265 unsigned DiagID = IsCompare 13266 ? diag::warn_address_of_reference_null_compare 13267 : diag::warn_address_of_reference_bool_conversion; 13268 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13269 << IsEqual; 13270 if (CheckForReference(*this, E, PD)) { 13271 return; 13272 } 13273 } 13274 13275 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13276 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13277 std::string Str; 13278 llvm::raw_string_ostream S(Str); 13279 E->printPretty(S, nullptr, getPrintingPolicy()); 13280 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13281 : diag::warn_cast_nonnull_to_bool; 13282 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13283 << E->getSourceRange() << Range << IsEqual; 13284 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13285 }; 13286 13287 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13288 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13289 if (auto *Callee = Call->getDirectCallee()) { 13290 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13291 ComplainAboutNonnullParamOrCall(A); 13292 return; 13293 } 13294 } 13295 } 13296 13297 // Expect to find a single Decl. Skip anything more complicated. 13298 ValueDecl *D = nullptr; 13299 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13300 D = R->getDecl(); 13301 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13302 D = M->getMemberDecl(); 13303 } 13304 13305 // Weak Decls can be null. 13306 if (!D || D->isWeak()) 13307 return; 13308 13309 // Check for parameter decl with nonnull attribute 13310 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13311 if (getCurFunction() && 13312 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13313 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13314 ComplainAboutNonnullParamOrCall(A); 13315 return; 13316 } 13317 13318 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13319 // Skip function template not specialized yet. 13320 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13321 return; 13322 auto ParamIter = llvm::find(FD->parameters(), PV); 13323 assert(ParamIter != FD->param_end()); 13324 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13325 13326 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13327 if (!NonNull->args_size()) { 13328 ComplainAboutNonnullParamOrCall(NonNull); 13329 return; 13330 } 13331 13332 for (const ParamIdx &ArgNo : NonNull->args()) { 13333 if (ArgNo.getASTIndex() == ParamNo) { 13334 ComplainAboutNonnullParamOrCall(NonNull); 13335 return; 13336 } 13337 } 13338 } 13339 } 13340 } 13341 } 13342 13343 QualType T = D->getType(); 13344 const bool IsArray = T->isArrayType(); 13345 const bool IsFunction = T->isFunctionType(); 13346 13347 // Address of function is used to silence the function warning. 13348 if (IsAddressOf && IsFunction) { 13349 return; 13350 } 13351 13352 // Found nothing. 13353 if (!IsAddressOf && !IsFunction && !IsArray) 13354 return; 13355 13356 // Pretty print the expression for the diagnostic. 13357 std::string Str; 13358 llvm::raw_string_ostream S(Str); 13359 E->printPretty(S, nullptr, getPrintingPolicy()); 13360 13361 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13362 : diag::warn_impcast_pointer_to_bool; 13363 enum { 13364 AddressOf, 13365 FunctionPointer, 13366 ArrayPointer 13367 } DiagType; 13368 if (IsAddressOf) 13369 DiagType = AddressOf; 13370 else if (IsFunction) 13371 DiagType = FunctionPointer; 13372 else if (IsArray) 13373 DiagType = ArrayPointer; 13374 else 13375 llvm_unreachable("Could not determine diagnostic."); 13376 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13377 << Range << IsEqual; 13378 13379 if (!IsFunction) 13380 return; 13381 13382 // Suggest '&' to silence the function warning. 13383 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13384 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13385 13386 // Check to see if '()' fixit should be emitted. 13387 QualType ReturnType; 13388 UnresolvedSet<4> NonTemplateOverloads; 13389 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13390 if (ReturnType.isNull()) 13391 return; 13392 13393 if (IsCompare) { 13394 // There are two cases here. If there is null constant, the only suggest 13395 // for a pointer return type. If the null is 0, then suggest if the return 13396 // type is a pointer or an integer type. 13397 if (!ReturnType->isPointerType()) { 13398 if (NullKind == Expr::NPCK_ZeroExpression || 13399 NullKind == Expr::NPCK_ZeroLiteral) { 13400 if (!ReturnType->isIntegerType()) 13401 return; 13402 } else { 13403 return; 13404 } 13405 } 13406 } else { // !IsCompare 13407 // For function to bool, only suggest if the function pointer has bool 13408 // return type. 13409 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13410 return; 13411 } 13412 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13413 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13414 } 13415 13416 /// Diagnoses "dangerous" implicit conversions within the given 13417 /// expression (which is a full expression). Implements -Wconversion 13418 /// and -Wsign-compare. 13419 /// 13420 /// \param CC the "context" location of the implicit conversion, i.e. 13421 /// the most location of the syntactic entity requiring the implicit 13422 /// conversion 13423 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13424 // Don't diagnose in unevaluated contexts. 13425 if (isUnevaluatedContext()) 13426 return; 13427 13428 // Don't diagnose for value- or type-dependent expressions. 13429 if (E->isTypeDependent() || E->isValueDependent()) 13430 return; 13431 13432 // Check for array bounds violations in cases where the check isn't triggered 13433 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13434 // ArraySubscriptExpr is on the RHS of a variable initialization. 13435 CheckArrayAccess(E); 13436 13437 // This is not the right CC for (e.g.) a variable initialization. 13438 AnalyzeImplicitConversions(*this, E, CC); 13439 } 13440 13441 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13442 /// Input argument E is a logical expression. 13443 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13444 ::CheckBoolLikeConversion(*this, E, CC); 13445 } 13446 13447 /// Diagnose when expression is an integer constant expression and its evaluation 13448 /// results in integer overflow 13449 void Sema::CheckForIntOverflow (Expr *E) { 13450 // Use a work list to deal with nested struct initializers. 13451 SmallVector<Expr *, 2> Exprs(1, E); 13452 13453 do { 13454 Expr *OriginalE = Exprs.pop_back_val(); 13455 Expr *E = OriginalE->IgnoreParenCasts(); 13456 13457 if (isa<BinaryOperator>(E)) { 13458 E->EvaluateForOverflow(Context); 13459 continue; 13460 } 13461 13462 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13463 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13464 else if (isa<ObjCBoxedExpr>(OriginalE)) 13465 E->EvaluateForOverflow(Context); 13466 else if (auto Call = dyn_cast<CallExpr>(E)) 13467 Exprs.append(Call->arg_begin(), Call->arg_end()); 13468 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13469 Exprs.append(Message->arg_begin(), Message->arg_end()); 13470 } while (!Exprs.empty()); 13471 } 13472 13473 namespace { 13474 13475 /// Visitor for expressions which looks for unsequenced operations on the 13476 /// same object. 13477 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13478 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13479 13480 /// A tree of sequenced regions within an expression. Two regions are 13481 /// unsequenced if one is an ancestor or a descendent of the other. When we 13482 /// finish processing an expression with sequencing, such as a comma 13483 /// expression, we fold its tree nodes into its parent, since they are 13484 /// unsequenced with respect to nodes we will visit later. 13485 class SequenceTree { 13486 struct Value { 13487 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13488 unsigned Parent : 31; 13489 unsigned Merged : 1; 13490 }; 13491 SmallVector<Value, 8> Values; 13492 13493 public: 13494 /// A region within an expression which may be sequenced with respect 13495 /// to some other region. 13496 class Seq { 13497 friend class SequenceTree; 13498 13499 unsigned Index; 13500 13501 explicit Seq(unsigned N) : Index(N) {} 13502 13503 public: 13504 Seq() : Index(0) {} 13505 }; 13506 13507 SequenceTree() { Values.push_back(Value(0)); } 13508 Seq root() const { return Seq(0); } 13509 13510 /// Create a new sequence of operations, which is an unsequenced 13511 /// subset of \p Parent. This sequence of operations is sequenced with 13512 /// respect to other children of \p Parent. 13513 Seq allocate(Seq Parent) { 13514 Values.push_back(Value(Parent.Index)); 13515 return Seq(Values.size() - 1); 13516 } 13517 13518 /// Merge a sequence of operations into its parent. 13519 void merge(Seq S) { 13520 Values[S.Index].Merged = true; 13521 } 13522 13523 /// Determine whether two operations are unsequenced. This operation 13524 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13525 /// should have been merged into its parent as appropriate. 13526 bool isUnsequenced(Seq Cur, Seq Old) { 13527 unsigned C = representative(Cur.Index); 13528 unsigned Target = representative(Old.Index); 13529 while (C >= Target) { 13530 if (C == Target) 13531 return true; 13532 C = Values[C].Parent; 13533 } 13534 return false; 13535 } 13536 13537 private: 13538 /// Pick a representative for a sequence. 13539 unsigned representative(unsigned K) { 13540 if (Values[K].Merged) 13541 // Perform path compression as we go. 13542 return Values[K].Parent = representative(Values[K].Parent); 13543 return K; 13544 } 13545 }; 13546 13547 /// An object for which we can track unsequenced uses. 13548 using Object = const NamedDecl *; 13549 13550 /// Different flavors of object usage which we track. We only track the 13551 /// least-sequenced usage of each kind. 13552 enum UsageKind { 13553 /// A read of an object. Multiple unsequenced reads are OK. 13554 UK_Use, 13555 13556 /// A modification of an object which is sequenced before the value 13557 /// computation of the expression, such as ++n in C++. 13558 UK_ModAsValue, 13559 13560 /// A modification of an object which is not sequenced before the value 13561 /// computation of the expression, such as n++. 13562 UK_ModAsSideEffect, 13563 13564 UK_Count = UK_ModAsSideEffect + 1 13565 }; 13566 13567 /// Bundle together a sequencing region and the expression corresponding 13568 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13569 struct Usage { 13570 const Expr *UsageExpr; 13571 SequenceTree::Seq Seq; 13572 13573 Usage() : UsageExpr(nullptr), Seq() {} 13574 }; 13575 13576 struct UsageInfo { 13577 Usage Uses[UK_Count]; 13578 13579 /// Have we issued a diagnostic for this object already? 13580 bool Diagnosed; 13581 13582 UsageInfo() : Uses(), Diagnosed(false) {} 13583 }; 13584 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13585 13586 Sema &SemaRef; 13587 13588 /// Sequenced regions within the expression. 13589 SequenceTree Tree; 13590 13591 /// Declaration modifications and references which we have seen. 13592 UsageInfoMap UsageMap; 13593 13594 /// The region we are currently within. 13595 SequenceTree::Seq Region; 13596 13597 /// Filled in with declarations which were modified as a side-effect 13598 /// (that is, post-increment operations). 13599 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13600 13601 /// Expressions to check later. We defer checking these to reduce 13602 /// stack usage. 13603 SmallVectorImpl<const Expr *> &WorkList; 13604 13605 /// RAII object wrapping the visitation of a sequenced subexpression of an 13606 /// expression. At the end of this process, the side-effects of the evaluation 13607 /// become sequenced with respect to the value computation of the result, so 13608 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13609 /// UK_ModAsValue. 13610 struct SequencedSubexpression { 13611 SequencedSubexpression(SequenceChecker &Self) 13612 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13613 Self.ModAsSideEffect = &ModAsSideEffect; 13614 } 13615 13616 ~SequencedSubexpression() { 13617 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13618 // Add a new usage with usage kind UK_ModAsValue, and then restore 13619 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13620 // the previous one was empty). 13621 UsageInfo &UI = Self.UsageMap[M.first]; 13622 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13623 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13624 SideEffectUsage = M.second; 13625 } 13626 Self.ModAsSideEffect = OldModAsSideEffect; 13627 } 13628 13629 SequenceChecker &Self; 13630 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13631 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13632 }; 13633 13634 /// RAII object wrapping the visitation of a subexpression which we might 13635 /// choose to evaluate as a constant. If any subexpression is evaluated and 13636 /// found to be non-constant, this allows us to suppress the evaluation of 13637 /// the outer expression. 13638 class EvaluationTracker { 13639 public: 13640 EvaluationTracker(SequenceChecker &Self) 13641 : Self(Self), Prev(Self.EvalTracker) { 13642 Self.EvalTracker = this; 13643 } 13644 13645 ~EvaluationTracker() { 13646 Self.EvalTracker = Prev; 13647 if (Prev) 13648 Prev->EvalOK &= EvalOK; 13649 } 13650 13651 bool evaluate(const Expr *E, bool &Result) { 13652 if (!EvalOK || E->isValueDependent()) 13653 return false; 13654 EvalOK = E->EvaluateAsBooleanCondition( 13655 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13656 return EvalOK; 13657 } 13658 13659 private: 13660 SequenceChecker &Self; 13661 EvaluationTracker *Prev; 13662 bool EvalOK = true; 13663 } *EvalTracker = nullptr; 13664 13665 /// Find the object which is produced by the specified expression, 13666 /// if any. 13667 Object getObject(const Expr *E, bool Mod) const { 13668 E = E->IgnoreParenCasts(); 13669 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13670 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13671 return getObject(UO->getSubExpr(), Mod); 13672 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13673 if (BO->getOpcode() == BO_Comma) 13674 return getObject(BO->getRHS(), Mod); 13675 if (Mod && BO->isAssignmentOp()) 13676 return getObject(BO->getLHS(), Mod); 13677 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13678 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13679 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13680 return ME->getMemberDecl(); 13681 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13682 // FIXME: If this is a reference, map through to its value. 13683 return DRE->getDecl(); 13684 return nullptr; 13685 } 13686 13687 /// Note that an object \p O was modified or used by an expression 13688 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13689 /// the object \p O as obtained via the \p UsageMap. 13690 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13691 // Get the old usage for the given object and usage kind. 13692 Usage &U = UI.Uses[UK]; 13693 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13694 // If we have a modification as side effect and are in a sequenced 13695 // subexpression, save the old Usage so that we can restore it later 13696 // in SequencedSubexpression::~SequencedSubexpression. 13697 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13698 ModAsSideEffect->push_back(std::make_pair(O, U)); 13699 // Then record the new usage with the current sequencing region. 13700 U.UsageExpr = UsageExpr; 13701 U.Seq = Region; 13702 } 13703 } 13704 13705 /// Check whether a modification or use of an object \p O in an expression 13706 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13707 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13708 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13709 /// usage and false we are checking for a mod-use unsequenced usage. 13710 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13711 UsageKind OtherKind, bool IsModMod) { 13712 if (UI.Diagnosed) 13713 return; 13714 13715 const Usage &U = UI.Uses[OtherKind]; 13716 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13717 return; 13718 13719 const Expr *Mod = U.UsageExpr; 13720 const Expr *ModOrUse = UsageExpr; 13721 if (OtherKind == UK_Use) 13722 std::swap(Mod, ModOrUse); 13723 13724 SemaRef.DiagRuntimeBehavior( 13725 Mod->getExprLoc(), {Mod, ModOrUse}, 13726 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13727 : diag::warn_unsequenced_mod_use) 13728 << O << SourceRange(ModOrUse->getExprLoc())); 13729 UI.Diagnosed = true; 13730 } 13731 13732 // A note on note{Pre, Post}{Use, Mod}: 13733 // 13734 // (It helps to follow the algorithm with an expression such as 13735 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13736 // operations before C++17 and both are well-defined in C++17). 13737 // 13738 // When visiting a node which uses/modify an object we first call notePreUse 13739 // or notePreMod before visiting its sub-expression(s). At this point the 13740 // children of the current node have not yet been visited and so the eventual 13741 // uses/modifications resulting from the children of the current node have not 13742 // been recorded yet. 13743 // 13744 // We then visit the children of the current node. After that notePostUse or 13745 // notePostMod is called. These will 1) detect an unsequenced modification 13746 // as side effect (as in "k++ + k") and 2) add a new usage with the 13747 // appropriate usage kind. 13748 // 13749 // We also have to be careful that some operation sequences modification as 13750 // side effect as well (for example: || or ,). To account for this we wrap 13751 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13752 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13753 // which record usages which are modifications as side effect, and then 13754 // downgrade them (or more accurately restore the previous usage which was a 13755 // modification as side effect) when exiting the scope of the sequenced 13756 // subexpression. 13757 13758 void notePreUse(Object O, const Expr *UseExpr) { 13759 UsageInfo &UI = UsageMap[O]; 13760 // Uses conflict with other modifications. 13761 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13762 } 13763 13764 void notePostUse(Object O, const Expr *UseExpr) { 13765 UsageInfo &UI = UsageMap[O]; 13766 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13767 /*IsModMod=*/false); 13768 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13769 } 13770 13771 void notePreMod(Object O, const Expr *ModExpr) { 13772 UsageInfo &UI = UsageMap[O]; 13773 // Modifications conflict with other modifications and with uses. 13774 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13775 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13776 } 13777 13778 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13779 UsageInfo &UI = UsageMap[O]; 13780 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13781 /*IsModMod=*/true); 13782 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13783 } 13784 13785 public: 13786 SequenceChecker(Sema &S, const Expr *E, 13787 SmallVectorImpl<const Expr *> &WorkList) 13788 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13789 Visit(E); 13790 // Silence a -Wunused-private-field since WorkList is now unused. 13791 // TODO: Evaluate if it can be used, and if not remove it. 13792 (void)this->WorkList; 13793 } 13794 13795 void VisitStmt(const Stmt *S) { 13796 // Skip all statements which aren't expressions for now. 13797 } 13798 13799 void VisitExpr(const Expr *E) { 13800 // By default, just recurse to evaluated subexpressions. 13801 Base::VisitStmt(E); 13802 } 13803 13804 void VisitCastExpr(const CastExpr *E) { 13805 Object O = Object(); 13806 if (E->getCastKind() == CK_LValueToRValue) 13807 O = getObject(E->getSubExpr(), false); 13808 13809 if (O) 13810 notePreUse(O, E); 13811 VisitExpr(E); 13812 if (O) 13813 notePostUse(O, E); 13814 } 13815 13816 void VisitSequencedExpressions(const Expr *SequencedBefore, 13817 const Expr *SequencedAfter) { 13818 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13819 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13820 SequenceTree::Seq OldRegion = Region; 13821 13822 { 13823 SequencedSubexpression SeqBefore(*this); 13824 Region = BeforeRegion; 13825 Visit(SequencedBefore); 13826 } 13827 13828 Region = AfterRegion; 13829 Visit(SequencedAfter); 13830 13831 Region = OldRegion; 13832 13833 Tree.merge(BeforeRegion); 13834 Tree.merge(AfterRegion); 13835 } 13836 13837 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13838 // C++17 [expr.sub]p1: 13839 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13840 // expression E1 is sequenced before the expression E2. 13841 if (SemaRef.getLangOpts().CPlusPlus17) 13842 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13843 else { 13844 Visit(ASE->getLHS()); 13845 Visit(ASE->getRHS()); 13846 } 13847 } 13848 13849 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13850 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13851 void VisitBinPtrMem(const BinaryOperator *BO) { 13852 // C++17 [expr.mptr.oper]p4: 13853 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13854 // the expression E1 is sequenced before the expression E2. 13855 if (SemaRef.getLangOpts().CPlusPlus17) 13856 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13857 else { 13858 Visit(BO->getLHS()); 13859 Visit(BO->getRHS()); 13860 } 13861 } 13862 13863 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13864 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13865 void VisitBinShlShr(const BinaryOperator *BO) { 13866 // C++17 [expr.shift]p4: 13867 // The expression E1 is sequenced before the expression E2. 13868 if (SemaRef.getLangOpts().CPlusPlus17) 13869 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13870 else { 13871 Visit(BO->getLHS()); 13872 Visit(BO->getRHS()); 13873 } 13874 } 13875 13876 void VisitBinComma(const BinaryOperator *BO) { 13877 // C++11 [expr.comma]p1: 13878 // Every value computation and side effect associated with the left 13879 // expression is sequenced before every value computation and side 13880 // effect associated with the right expression. 13881 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13882 } 13883 13884 void VisitBinAssign(const BinaryOperator *BO) { 13885 SequenceTree::Seq RHSRegion; 13886 SequenceTree::Seq LHSRegion; 13887 if (SemaRef.getLangOpts().CPlusPlus17) { 13888 RHSRegion = Tree.allocate(Region); 13889 LHSRegion = Tree.allocate(Region); 13890 } else { 13891 RHSRegion = Region; 13892 LHSRegion = Region; 13893 } 13894 SequenceTree::Seq OldRegion = Region; 13895 13896 // C++11 [expr.ass]p1: 13897 // [...] the assignment is sequenced after the value computation 13898 // of the right and left operands, [...] 13899 // 13900 // so check it before inspecting the operands and update the 13901 // map afterwards. 13902 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13903 if (O) 13904 notePreMod(O, BO); 13905 13906 if (SemaRef.getLangOpts().CPlusPlus17) { 13907 // C++17 [expr.ass]p1: 13908 // [...] The right operand is sequenced before the left operand. [...] 13909 { 13910 SequencedSubexpression SeqBefore(*this); 13911 Region = RHSRegion; 13912 Visit(BO->getRHS()); 13913 } 13914 13915 Region = LHSRegion; 13916 Visit(BO->getLHS()); 13917 13918 if (O && isa<CompoundAssignOperator>(BO)) 13919 notePostUse(O, BO); 13920 13921 } else { 13922 // C++11 does not specify any sequencing between the LHS and RHS. 13923 Region = LHSRegion; 13924 Visit(BO->getLHS()); 13925 13926 if (O && isa<CompoundAssignOperator>(BO)) 13927 notePostUse(O, BO); 13928 13929 Region = RHSRegion; 13930 Visit(BO->getRHS()); 13931 } 13932 13933 // C++11 [expr.ass]p1: 13934 // the assignment is sequenced [...] before the value computation of the 13935 // assignment expression. 13936 // C11 6.5.16/3 has no such rule. 13937 Region = OldRegion; 13938 if (O) 13939 notePostMod(O, BO, 13940 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13941 : UK_ModAsSideEffect); 13942 if (SemaRef.getLangOpts().CPlusPlus17) { 13943 Tree.merge(RHSRegion); 13944 Tree.merge(LHSRegion); 13945 } 13946 } 13947 13948 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13949 VisitBinAssign(CAO); 13950 } 13951 13952 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13953 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13954 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13955 Object O = getObject(UO->getSubExpr(), true); 13956 if (!O) 13957 return VisitExpr(UO); 13958 13959 notePreMod(O, UO); 13960 Visit(UO->getSubExpr()); 13961 // C++11 [expr.pre.incr]p1: 13962 // the expression ++x is equivalent to x+=1 13963 notePostMod(O, UO, 13964 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13965 : UK_ModAsSideEffect); 13966 } 13967 13968 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13969 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13970 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13971 Object O = getObject(UO->getSubExpr(), true); 13972 if (!O) 13973 return VisitExpr(UO); 13974 13975 notePreMod(O, UO); 13976 Visit(UO->getSubExpr()); 13977 notePostMod(O, UO, UK_ModAsSideEffect); 13978 } 13979 13980 void VisitBinLOr(const BinaryOperator *BO) { 13981 // C++11 [expr.log.or]p2: 13982 // If the second expression is evaluated, every value computation and 13983 // side effect associated with the first expression is sequenced before 13984 // every value computation and side effect associated with the 13985 // second expression. 13986 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13987 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13988 SequenceTree::Seq OldRegion = Region; 13989 13990 EvaluationTracker Eval(*this); 13991 { 13992 SequencedSubexpression Sequenced(*this); 13993 Region = LHSRegion; 13994 Visit(BO->getLHS()); 13995 } 13996 13997 // C++11 [expr.log.or]p1: 13998 // [...] the second operand is not evaluated if the first operand 13999 // evaluates to true. 14000 bool EvalResult = false; 14001 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14002 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14003 if (ShouldVisitRHS) { 14004 Region = RHSRegion; 14005 Visit(BO->getRHS()); 14006 } 14007 14008 Region = OldRegion; 14009 Tree.merge(LHSRegion); 14010 Tree.merge(RHSRegion); 14011 } 14012 14013 void VisitBinLAnd(const BinaryOperator *BO) { 14014 // C++11 [expr.log.and]p2: 14015 // If the second expression is evaluated, every value computation and 14016 // side effect associated with the first expression is sequenced before 14017 // every value computation and side effect associated with the 14018 // second expression. 14019 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14020 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14021 SequenceTree::Seq OldRegion = Region; 14022 14023 EvaluationTracker Eval(*this); 14024 { 14025 SequencedSubexpression Sequenced(*this); 14026 Region = LHSRegion; 14027 Visit(BO->getLHS()); 14028 } 14029 14030 // C++11 [expr.log.and]p1: 14031 // [...] the second operand is not evaluated if the first operand is false. 14032 bool EvalResult = false; 14033 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14034 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14035 if (ShouldVisitRHS) { 14036 Region = RHSRegion; 14037 Visit(BO->getRHS()); 14038 } 14039 14040 Region = OldRegion; 14041 Tree.merge(LHSRegion); 14042 Tree.merge(RHSRegion); 14043 } 14044 14045 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14046 // C++11 [expr.cond]p1: 14047 // [...] Every value computation and side effect associated with the first 14048 // expression is sequenced before every value computation and side effect 14049 // associated with the second or third expression. 14050 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14051 14052 // No sequencing is specified between the true and false expression. 14053 // However since exactly one of both is going to be evaluated we can 14054 // consider them to be sequenced. This is needed to avoid warning on 14055 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14056 // both the true and false expressions because we can't evaluate x. 14057 // This will still allow us to detect an expression like (pre C++17) 14058 // "(x ? y += 1 : y += 2) = y". 14059 // 14060 // We don't wrap the visitation of the true and false expression with 14061 // SequencedSubexpression because we don't want to downgrade modifications 14062 // as side effect in the true and false expressions after the visition 14063 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14064 // not warn between the two "y++", but we should warn between the "y++" 14065 // and the "y". 14066 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14067 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14068 SequenceTree::Seq OldRegion = Region; 14069 14070 EvaluationTracker Eval(*this); 14071 { 14072 SequencedSubexpression Sequenced(*this); 14073 Region = ConditionRegion; 14074 Visit(CO->getCond()); 14075 } 14076 14077 // C++11 [expr.cond]p1: 14078 // [...] The first expression is contextually converted to bool (Clause 4). 14079 // It is evaluated and if it is true, the result of the conditional 14080 // expression is the value of the second expression, otherwise that of the 14081 // third expression. Only one of the second and third expressions is 14082 // evaluated. [...] 14083 bool EvalResult = false; 14084 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14085 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14086 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14087 if (ShouldVisitTrueExpr) { 14088 Region = TrueRegion; 14089 Visit(CO->getTrueExpr()); 14090 } 14091 if (ShouldVisitFalseExpr) { 14092 Region = FalseRegion; 14093 Visit(CO->getFalseExpr()); 14094 } 14095 14096 Region = OldRegion; 14097 Tree.merge(ConditionRegion); 14098 Tree.merge(TrueRegion); 14099 Tree.merge(FalseRegion); 14100 } 14101 14102 void VisitCallExpr(const CallExpr *CE) { 14103 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14104 14105 if (CE->isUnevaluatedBuiltinCall(Context)) 14106 return; 14107 14108 // C++11 [intro.execution]p15: 14109 // When calling a function [...], every value computation and side effect 14110 // associated with any argument expression, or with the postfix expression 14111 // designating the called function, is sequenced before execution of every 14112 // expression or statement in the body of the function [and thus before 14113 // the value computation of its result]. 14114 SequencedSubexpression Sequenced(*this); 14115 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14116 // C++17 [expr.call]p5 14117 // The postfix-expression is sequenced before each expression in the 14118 // expression-list and any default argument. [...] 14119 SequenceTree::Seq CalleeRegion; 14120 SequenceTree::Seq OtherRegion; 14121 if (SemaRef.getLangOpts().CPlusPlus17) { 14122 CalleeRegion = Tree.allocate(Region); 14123 OtherRegion = Tree.allocate(Region); 14124 } else { 14125 CalleeRegion = Region; 14126 OtherRegion = Region; 14127 } 14128 SequenceTree::Seq OldRegion = Region; 14129 14130 // Visit the callee expression first. 14131 Region = CalleeRegion; 14132 if (SemaRef.getLangOpts().CPlusPlus17) { 14133 SequencedSubexpression Sequenced(*this); 14134 Visit(CE->getCallee()); 14135 } else { 14136 Visit(CE->getCallee()); 14137 } 14138 14139 // Then visit the argument expressions. 14140 Region = OtherRegion; 14141 for (const Expr *Argument : CE->arguments()) 14142 Visit(Argument); 14143 14144 Region = OldRegion; 14145 if (SemaRef.getLangOpts().CPlusPlus17) { 14146 Tree.merge(CalleeRegion); 14147 Tree.merge(OtherRegion); 14148 } 14149 }); 14150 } 14151 14152 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14153 // C++17 [over.match.oper]p2: 14154 // [...] the operator notation is first transformed to the equivalent 14155 // function-call notation as summarized in Table 12 (where @ denotes one 14156 // of the operators covered in the specified subclause). However, the 14157 // operands are sequenced in the order prescribed for the built-in 14158 // operator (Clause 8). 14159 // 14160 // From the above only overloaded binary operators and overloaded call 14161 // operators have sequencing rules in C++17 that we need to handle 14162 // separately. 14163 if (!SemaRef.getLangOpts().CPlusPlus17 || 14164 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14165 return VisitCallExpr(CXXOCE); 14166 14167 enum { 14168 NoSequencing, 14169 LHSBeforeRHS, 14170 RHSBeforeLHS, 14171 LHSBeforeRest 14172 } SequencingKind; 14173 switch (CXXOCE->getOperator()) { 14174 case OO_Equal: 14175 case OO_PlusEqual: 14176 case OO_MinusEqual: 14177 case OO_StarEqual: 14178 case OO_SlashEqual: 14179 case OO_PercentEqual: 14180 case OO_CaretEqual: 14181 case OO_AmpEqual: 14182 case OO_PipeEqual: 14183 case OO_LessLessEqual: 14184 case OO_GreaterGreaterEqual: 14185 SequencingKind = RHSBeforeLHS; 14186 break; 14187 14188 case OO_LessLess: 14189 case OO_GreaterGreater: 14190 case OO_AmpAmp: 14191 case OO_PipePipe: 14192 case OO_Comma: 14193 case OO_ArrowStar: 14194 case OO_Subscript: 14195 SequencingKind = LHSBeforeRHS; 14196 break; 14197 14198 case OO_Call: 14199 SequencingKind = LHSBeforeRest; 14200 break; 14201 14202 default: 14203 SequencingKind = NoSequencing; 14204 break; 14205 } 14206 14207 if (SequencingKind == NoSequencing) 14208 return VisitCallExpr(CXXOCE); 14209 14210 // This is a call, so all subexpressions are sequenced before the result. 14211 SequencedSubexpression Sequenced(*this); 14212 14213 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14214 assert(SemaRef.getLangOpts().CPlusPlus17 && 14215 "Should only get there with C++17 and above!"); 14216 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14217 "Should only get there with an overloaded binary operator" 14218 " or an overloaded call operator!"); 14219 14220 if (SequencingKind == LHSBeforeRest) { 14221 assert(CXXOCE->getOperator() == OO_Call && 14222 "We should only have an overloaded call operator here!"); 14223 14224 // This is very similar to VisitCallExpr, except that we only have the 14225 // C++17 case. The postfix-expression is the first argument of the 14226 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14227 // are in the following arguments. 14228 // 14229 // Note that we intentionally do not visit the callee expression since 14230 // it is just a decayed reference to a function. 14231 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14232 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14233 SequenceTree::Seq OldRegion = Region; 14234 14235 assert(CXXOCE->getNumArgs() >= 1 && 14236 "An overloaded call operator must have at least one argument" 14237 " for the postfix-expression!"); 14238 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14239 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14240 CXXOCE->getNumArgs() - 1); 14241 14242 // Visit the postfix-expression first. 14243 { 14244 Region = PostfixExprRegion; 14245 SequencedSubexpression Sequenced(*this); 14246 Visit(PostfixExpr); 14247 } 14248 14249 // Then visit the argument expressions. 14250 Region = ArgsRegion; 14251 for (const Expr *Arg : Args) 14252 Visit(Arg); 14253 14254 Region = OldRegion; 14255 Tree.merge(PostfixExprRegion); 14256 Tree.merge(ArgsRegion); 14257 } else { 14258 assert(CXXOCE->getNumArgs() == 2 && 14259 "Should only have two arguments here!"); 14260 assert((SequencingKind == LHSBeforeRHS || 14261 SequencingKind == RHSBeforeLHS) && 14262 "Unexpected sequencing kind!"); 14263 14264 // We do not visit the callee expression since it is just a decayed 14265 // reference to a function. 14266 const Expr *E1 = CXXOCE->getArg(0); 14267 const Expr *E2 = CXXOCE->getArg(1); 14268 if (SequencingKind == RHSBeforeLHS) 14269 std::swap(E1, E2); 14270 14271 return VisitSequencedExpressions(E1, E2); 14272 } 14273 }); 14274 } 14275 14276 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14277 // This is a call, so all subexpressions are sequenced before the result. 14278 SequencedSubexpression Sequenced(*this); 14279 14280 if (!CCE->isListInitialization()) 14281 return VisitExpr(CCE); 14282 14283 // In C++11, list initializations are sequenced. 14284 SmallVector<SequenceTree::Seq, 32> Elts; 14285 SequenceTree::Seq Parent = Region; 14286 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14287 E = CCE->arg_end(); 14288 I != E; ++I) { 14289 Region = Tree.allocate(Parent); 14290 Elts.push_back(Region); 14291 Visit(*I); 14292 } 14293 14294 // Forget that the initializers are sequenced. 14295 Region = Parent; 14296 for (unsigned I = 0; I < Elts.size(); ++I) 14297 Tree.merge(Elts[I]); 14298 } 14299 14300 void VisitInitListExpr(const InitListExpr *ILE) { 14301 if (!SemaRef.getLangOpts().CPlusPlus11) 14302 return VisitExpr(ILE); 14303 14304 // In C++11, list initializations are sequenced. 14305 SmallVector<SequenceTree::Seq, 32> Elts; 14306 SequenceTree::Seq Parent = Region; 14307 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14308 const Expr *E = ILE->getInit(I); 14309 if (!E) 14310 continue; 14311 Region = Tree.allocate(Parent); 14312 Elts.push_back(Region); 14313 Visit(E); 14314 } 14315 14316 // Forget that the initializers are sequenced. 14317 Region = Parent; 14318 for (unsigned I = 0; I < Elts.size(); ++I) 14319 Tree.merge(Elts[I]); 14320 } 14321 }; 14322 14323 } // namespace 14324 14325 void Sema::CheckUnsequencedOperations(const Expr *E) { 14326 SmallVector<const Expr *, 8> WorkList; 14327 WorkList.push_back(E); 14328 while (!WorkList.empty()) { 14329 const Expr *Item = WorkList.pop_back_val(); 14330 SequenceChecker(*this, Item, WorkList); 14331 } 14332 } 14333 14334 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14335 bool IsConstexpr) { 14336 llvm::SaveAndRestore<bool> ConstantContext( 14337 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14338 CheckImplicitConversions(E, CheckLoc); 14339 if (!E->isInstantiationDependent()) 14340 CheckUnsequencedOperations(E); 14341 if (!IsConstexpr && !E->isValueDependent()) 14342 CheckForIntOverflow(E); 14343 DiagnoseMisalignedMembers(); 14344 } 14345 14346 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14347 FieldDecl *BitField, 14348 Expr *Init) { 14349 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14350 } 14351 14352 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14353 SourceLocation Loc) { 14354 if (!PType->isVariablyModifiedType()) 14355 return; 14356 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14357 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14358 return; 14359 } 14360 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14361 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14362 return; 14363 } 14364 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14365 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14366 return; 14367 } 14368 14369 const ArrayType *AT = S.Context.getAsArrayType(PType); 14370 if (!AT) 14371 return; 14372 14373 if (AT->getSizeModifier() != ArrayType::Star) { 14374 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14375 return; 14376 } 14377 14378 S.Diag(Loc, diag::err_array_star_in_function_definition); 14379 } 14380 14381 /// CheckParmsForFunctionDef - Check that the parameters of the given 14382 /// function are appropriate for the definition of a function. This 14383 /// takes care of any checks that cannot be performed on the 14384 /// declaration itself, e.g., that the types of each of the function 14385 /// parameters are complete. 14386 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14387 bool CheckParameterNames) { 14388 bool HasInvalidParm = false; 14389 for (ParmVarDecl *Param : Parameters) { 14390 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14391 // function declarator that is part of a function definition of 14392 // that function shall not have incomplete type. 14393 // 14394 // This is also C++ [dcl.fct]p6. 14395 if (!Param->isInvalidDecl() && 14396 RequireCompleteType(Param->getLocation(), Param->getType(), 14397 diag::err_typecheck_decl_incomplete_type)) { 14398 Param->setInvalidDecl(); 14399 HasInvalidParm = true; 14400 } 14401 14402 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14403 // declaration of each parameter shall include an identifier. 14404 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14405 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14406 // Diagnose this as an extension in C17 and earlier. 14407 if (!getLangOpts().C2x) 14408 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14409 } 14410 14411 // C99 6.7.5.3p12: 14412 // If the function declarator is not part of a definition of that 14413 // function, parameters may have incomplete type and may use the [*] 14414 // notation in their sequences of declarator specifiers to specify 14415 // variable length array types. 14416 QualType PType = Param->getOriginalType(); 14417 // FIXME: This diagnostic should point the '[*]' if source-location 14418 // information is added for it. 14419 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14420 14421 // If the parameter is a c++ class type and it has to be destructed in the 14422 // callee function, declare the destructor so that it can be called by the 14423 // callee function. Do not perform any direct access check on the dtor here. 14424 if (!Param->isInvalidDecl()) { 14425 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14426 if (!ClassDecl->isInvalidDecl() && 14427 !ClassDecl->hasIrrelevantDestructor() && 14428 !ClassDecl->isDependentContext() && 14429 ClassDecl->isParamDestroyedInCallee()) { 14430 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14431 MarkFunctionReferenced(Param->getLocation(), Destructor); 14432 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14433 } 14434 } 14435 } 14436 14437 // Parameters with the pass_object_size attribute only need to be marked 14438 // constant at function definitions. Because we lack information about 14439 // whether we're on a declaration or definition when we're instantiating the 14440 // attribute, we need to check for constness here. 14441 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14442 if (!Param->getType().isConstQualified()) 14443 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14444 << Attr->getSpelling() << 1; 14445 14446 // Check for parameter names shadowing fields from the class. 14447 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14448 // The owning context for the parameter should be the function, but we 14449 // want to see if this function's declaration context is a record. 14450 DeclContext *DC = Param->getDeclContext(); 14451 if (DC && DC->isFunctionOrMethod()) { 14452 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14453 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14454 RD, /*DeclIsField*/ false); 14455 } 14456 } 14457 } 14458 14459 return HasInvalidParm; 14460 } 14461 14462 Optional<std::pair<CharUnits, CharUnits>> 14463 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14464 14465 /// Compute the alignment and offset of the base class object given the 14466 /// derived-to-base cast expression and the alignment and offset of the derived 14467 /// class object. 14468 static std::pair<CharUnits, CharUnits> 14469 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14470 CharUnits BaseAlignment, CharUnits Offset, 14471 ASTContext &Ctx) { 14472 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14473 ++PathI) { 14474 const CXXBaseSpecifier *Base = *PathI; 14475 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14476 if (Base->isVirtual()) { 14477 // The complete object may have a lower alignment than the non-virtual 14478 // alignment of the base, in which case the base may be misaligned. Choose 14479 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14480 // conservative lower bound of the complete object alignment. 14481 CharUnits NonVirtualAlignment = 14482 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14483 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14484 Offset = CharUnits::Zero(); 14485 } else { 14486 const ASTRecordLayout &RL = 14487 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14488 Offset += RL.getBaseClassOffset(BaseDecl); 14489 } 14490 DerivedType = Base->getType(); 14491 } 14492 14493 return std::make_pair(BaseAlignment, Offset); 14494 } 14495 14496 /// Compute the alignment and offset of a binary additive operator. 14497 static Optional<std::pair<CharUnits, CharUnits>> 14498 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14499 bool IsSub, ASTContext &Ctx) { 14500 QualType PointeeType = PtrE->getType()->getPointeeType(); 14501 14502 if (!PointeeType->isConstantSizeType()) 14503 return llvm::None; 14504 14505 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14506 14507 if (!P) 14508 return llvm::None; 14509 14510 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14511 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14512 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14513 if (IsSub) 14514 Offset = -Offset; 14515 return std::make_pair(P->first, P->second + Offset); 14516 } 14517 14518 // If the integer expression isn't a constant expression, compute the lower 14519 // bound of the alignment using the alignment and offset of the pointer 14520 // expression and the element size. 14521 return std::make_pair( 14522 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14523 CharUnits::Zero()); 14524 } 14525 14526 /// This helper function takes an lvalue expression and returns the alignment of 14527 /// a VarDecl and a constant offset from the VarDecl. 14528 Optional<std::pair<CharUnits, CharUnits>> 14529 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14530 E = E->IgnoreParens(); 14531 switch (E->getStmtClass()) { 14532 default: 14533 break; 14534 case Stmt::CStyleCastExprClass: 14535 case Stmt::CXXStaticCastExprClass: 14536 case Stmt::ImplicitCastExprClass: { 14537 auto *CE = cast<CastExpr>(E); 14538 const Expr *From = CE->getSubExpr(); 14539 switch (CE->getCastKind()) { 14540 default: 14541 break; 14542 case CK_NoOp: 14543 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14544 case CK_UncheckedDerivedToBase: 14545 case CK_DerivedToBase: { 14546 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14547 if (!P) 14548 break; 14549 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14550 P->second, Ctx); 14551 } 14552 } 14553 break; 14554 } 14555 case Stmt::ArraySubscriptExprClass: { 14556 auto *ASE = cast<ArraySubscriptExpr>(E); 14557 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14558 false, Ctx); 14559 } 14560 case Stmt::DeclRefExprClass: { 14561 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14562 // FIXME: If VD is captured by copy or is an escaping __block variable, 14563 // use the alignment of VD's type. 14564 if (!VD->getType()->isReferenceType()) 14565 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14566 if (VD->hasInit()) 14567 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14568 } 14569 break; 14570 } 14571 case Stmt::MemberExprClass: { 14572 auto *ME = cast<MemberExpr>(E); 14573 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14574 if (!FD || FD->getType()->isReferenceType() || 14575 FD->getParent()->isInvalidDecl()) 14576 break; 14577 Optional<std::pair<CharUnits, CharUnits>> P; 14578 if (ME->isArrow()) 14579 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14580 else 14581 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14582 if (!P) 14583 break; 14584 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14585 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14586 return std::make_pair(P->first, 14587 P->second + CharUnits::fromQuantity(Offset)); 14588 } 14589 case Stmt::UnaryOperatorClass: { 14590 auto *UO = cast<UnaryOperator>(E); 14591 switch (UO->getOpcode()) { 14592 default: 14593 break; 14594 case UO_Deref: 14595 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14596 } 14597 break; 14598 } 14599 case Stmt::BinaryOperatorClass: { 14600 auto *BO = cast<BinaryOperator>(E); 14601 auto Opcode = BO->getOpcode(); 14602 switch (Opcode) { 14603 default: 14604 break; 14605 case BO_Comma: 14606 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14607 } 14608 break; 14609 } 14610 } 14611 return llvm::None; 14612 } 14613 14614 /// This helper function takes a pointer expression and returns the alignment of 14615 /// a VarDecl and a constant offset from the VarDecl. 14616 Optional<std::pair<CharUnits, CharUnits>> 14617 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14618 E = E->IgnoreParens(); 14619 switch (E->getStmtClass()) { 14620 default: 14621 break; 14622 case Stmt::CStyleCastExprClass: 14623 case Stmt::CXXStaticCastExprClass: 14624 case Stmt::ImplicitCastExprClass: { 14625 auto *CE = cast<CastExpr>(E); 14626 const Expr *From = CE->getSubExpr(); 14627 switch (CE->getCastKind()) { 14628 default: 14629 break; 14630 case CK_NoOp: 14631 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14632 case CK_ArrayToPointerDecay: 14633 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14634 case CK_UncheckedDerivedToBase: 14635 case CK_DerivedToBase: { 14636 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14637 if (!P) 14638 break; 14639 return getDerivedToBaseAlignmentAndOffset( 14640 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14641 } 14642 } 14643 break; 14644 } 14645 case Stmt::CXXThisExprClass: { 14646 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14647 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14648 return std::make_pair(Alignment, CharUnits::Zero()); 14649 } 14650 case Stmt::UnaryOperatorClass: { 14651 auto *UO = cast<UnaryOperator>(E); 14652 if (UO->getOpcode() == UO_AddrOf) 14653 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14654 break; 14655 } 14656 case Stmt::BinaryOperatorClass: { 14657 auto *BO = cast<BinaryOperator>(E); 14658 auto Opcode = BO->getOpcode(); 14659 switch (Opcode) { 14660 default: 14661 break; 14662 case BO_Add: 14663 case BO_Sub: { 14664 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14665 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14666 std::swap(LHS, RHS); 14667 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14668 Ctx); 14669 } 14670 case BO_Comma: 14671 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14672 } 14673 break; 14674 } 14675 } 14676 return llvm::None; 14677 } 14678 14679 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14680 // See if we can compute the alignment of a VarDecl and an offset from it. 14681 Optional<std::pair<CharUnits, CharUnits>> P = 14682 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14683 14684 if (P) 14685 return P->first.alignmentAtOffset(P->second); 14686 14687 // If that failed, return the type's alignment. 14688 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14689 } 14690 14691 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14692 /// pointer cast increases the alignment requirements. 14693 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14694 // This is actually a lot of work to potentially be doing on every 14695 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14696 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14697 return; 14698 14699 // Ignore dependent types. 14700 if (T->isDependentType() || Op->getType()->isDependentType()) 14701 return; 14702 14703 // Require that the destination be a pointer type. 14704 const PointerType *DestPtr = T->getAs<PointerType>(); 14705 if (!DestPtr) return; 14706 14707 // If the destination has alignment 1, we're done. 14708 QualType DestPointee = DestPtr->getPointeeType(); 14709 if (DestPointee->isIncompleteType()) return; 14710 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14711 if (DestAlign.isOne()) return; 14712 14713 // Require that the source be a pointer type. 14714 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14715 if (!SrcPtr) return; 14716 QualType SrcPointee = SrcPtr->getPointeeType(); 14717 14718 // Explicitly allow casts from cv void*. We already implicitly 14719 // allowed casts to cv void*, since they have alignment 1. 14720 // Also allow casts involving incomplete types, which implicitly 14721 // includes 'void'. 14722 if (SrcPointee->isIncompleteType()) return; 14723 14724 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14725 14726 if (SrcAlign >= DestAlign) return; 14727 14728 Diag(TRange.getBegin(), diag::warn_cast_align) 14729 << Op->getType() << T 14730 << static_cast<unsigned>(SrcAlign.getQuantity()) 14731 << static_cast<unsigned>(DestAlign.getQuantity()) 14732 << TRange << Op->getSourceRange(); 14733 } 14734 14735 /// Check whether this array fits the idiom of a size-one tail padded 14736 /// array member of a struct. 14737 /// 14738 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14739 /// commonly used to emulate flexible arrays in C89 code. 14740 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14741 const NamedDecl *ND) { 14742 if (Size != 1 || !ND) return false; 14743 14744 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14745 if (!FD) return false; 14746 14747 // Don't consider sizes resulting from macro expansions or template argument 14748 // substitution to form C89 tail-padded arrays. 14749 14750 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14751 while (TInfo) { 14752 TypeLoc TL = TInfo->getTypeLoc(); 14753 // Look through typedefs. 14754 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14755 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14756 TInfo = TDL->getTypeSourceInfo(); 14757 continue; 14758 } 14759 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14760 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14761 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14762 return false; 14763 } 14764 break; 14765 } 14766 14767 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14768 if (!RD) return false; 14769 if (RD->isUnion()) return false; 14770 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14771 if (!CRD->isStandardLayout()) return false; 14772 } 14773 14774 // See if this is the last field decl in the record. 14775 const Decl *D = FD; 14776 while ((D = D->getNextDeclInContext())) 14777 if (isa<FieldDecl>(D)) 14778 return false; 14779 return true; 14780 } 14781 14782 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14783 const ArraySubscriptExpr *ASE, 14784 bool AllowOnePastEnd, bool IndexNegated) { 14785 // Already diagnosed by the constant evaluator. 14786 if (isConstantEvaluated()) 14787 return; 14788 14789 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14790 if (IndexExpr->isValueDependent()) 14791 return; 14792 14793 const Type *EffectiveType = 14794 BaseExpr->getType()->getPointeeOrArrayElementType(); 14795 BaseExpr = BaseExpr->IgnoreParenCasts(); 14796 const ConstantArrayType *ArrayTy = 14797 Context.getAsConstantArrayType(BaseExpr->getType()); 14798 14799 const Type *BaseType = 14800 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 14801 bool IsUnboundedArray = (BaseType == nullptr); 14802 if (EffectiveType->isDependentType() || 14803 (!IsUnboundedArray && BaseType->isDependentType())) 14804 return; 14805 14806 Expr::EvalResult Result; 14807 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14808 return; 14809 14810 llvm::APSInt index = Result.Val.getInt(); 14811 if (IndexNegated) { 14812 index.setIsUnsigned(false); 14813 index = -index; 14814 } 14815 14816 const NamedDecl *ND = nullptr; 14817 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14818 ND = DRE->getDecl(); 14819 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14820 ND = ME->getMemberDecl(); 14821 14822 if (IsUnboundedArray) { 14823 if (index.isUnsigned() || !index.isNegative()) { 14824 const auto &ASTC = getASTContext(); 14825 unsigned AddrBits = 14826 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 14827 EffectiveType->getCanonicalTypeInternal())); 14828 if (index.getBitWidth() < AddrBits) 14829 index = index.zext(AddrBits); 14830 Optional<CharUnits> ElemCharUnits = 14831 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 14832 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 14833 // pointer) bounds-checking isn't meaningful. 14834 if (!ElemCharUnits) 14835 return; 14836 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 14837 // If index has more active bits than address space, we already know 14838 // we have a bounds violation to warn about. Otherwise, compute 14839 // address of (index + 1)th element, and warn about bounds violation 14840 // only if that address exceeds address space. 14841 if (index.getActiveBits() <= AddrBits) { 14842 bool Overflow; 14843 llvm::APInt Product(index); 14844 Product += 1; 14845 Product = Product.umul_ov(ElemBytes, Overflow); 14846 if (!Overflow && Product.getActiveBits() <= AddrBits) 14847 return; 14848 } 14849 14850 // Need to compute max possible elements in address space, since that 14851 // is included in diag message. 14852 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 14853 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 14854 MaxElems += 1; 14855 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 14856 MaxElems = MaxElems.udiv(ElemBytes); 14857 14858 unsigned DiagID = 14859 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 14860 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 14861 14862 // Diag message shows element size in bits and in "bytes" (platform- 14863 // dependent CharUnits) 14864 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14865 PDiag(DiagID) 14866 << toString(index, 10, true) << AddrBits 14867 << (unsigned)ASTC.toBits(*ElemCharUnits) 14868 << toString(ElemBytes, 10, false) 14869 << toString(MaxElems, 10, false) 14870 << (unsigned)MaxElems.getLimitedValue(~0U) 14871 << IndexExpr->getSourceRange()); 14872 14873 if (!ND) { 14874 // Try harder to find a NamedDecl to point at in the note. 14875 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14876 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14877 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14878 ND = DRE->getDecl(); 14879 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 14880 ND = ME->getMemberDecl(); 14881 } 14882 14883 if (ND) 14884 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14885 PDiag(diag::note_array_declared_here) << ND); 14886 } 14887 return; 14888 } 14889 14890 if (index.isUnsigned() || !index.isNegative()) { 14891 // It is possible that the type of the base expression after 14892 // IgnoreParenCasts is incomplete, even though the type of the base 14893 // expression before IgnoreParenCasts is complete (see PR39746 for an 14894 // example). In this case we have no information about whether the array 14895 // access exceeds the array bounds. However we can still diagnose an array 14896 // access which precedes the array bounds. 14897 if (BaseType->isIncompleteType()) 14898 return; 14899 14900 llvm::APInt size = ArrayTy->getSize(); 14901 if (!size.isStrictlyPositive()) 14902 return; 14903 14904 if (BaseType != EffectiveType) { 14905 // Make sure we're comparing apples to apples when comparing index to size 14906 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14907 uint64_t array_typesize = Context.getTypeSize(BaseType); 14908 // Handle ptrarith_typesize being zero, such as when casting to void* 14909 if (!ptrarith_typesize) ptrarith_typesize = 1; 14910 if (ptrarith_typesize != array_typesize) { 14911 // There's a cast to a different size type involved 14912 uint64_t ratio = array_typesize / ptrarith_typesize; 14913 // TODO: Be smarter about handling cases where array_typesize is not a 14914 // multiple of ptrarith_typesize 14915 if (ptrarith_typesize * ratio == array_typesize) 14916 size *= llvm::APInt(size.getBitWidth(), ratio); 14917 } 14918 } 14919 14920 if (size.getBitWidth() > index.getBitWidth()) 14921 index = index.zext(size.getBitWidth()); 14922 else if (size.getBitWidth() < index.getBitWidth()) 14923 size = size.zext(index.getBitWidth()); 14924 14925 // For array subscripting the index must be less than size, but for pointer 14926 // arithmetic also allow the index (offset) to be equal to size since 14927 // computing the next address after the end of the array is legal and 14928 // commonly done e.g. in C++ iterators and range-based for loops. 14929 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14930 return; 14931 14932 // Also don't warn for arrays of size 1 which are members of some 14933 // structure. These are often used to approximate flexible arrays in C89 14934 // code. 14935 if (IsTailPaddedMemberArray(*this, size, ND)) 14936 return; 14937 14938 // Suppress the warning if the subscript expression (as identified by the 14939 // ']' location) and the index expression are both from macro expansions 14940 // within a system header. 14941 if (ASE) { 14942 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14943 ASE->getRBracketLoc()); 14944 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14945 SourceLocation IndexLoc = 14946 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14947 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14948 return; 14949 } 14950 } 14951 14952 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 14953 : diag::warn_ptr_arith_exceeds_bounds; 14954 14955 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14956 PDiag(DiagID) << toString(index, 10, true) 14957 << toString(size, 10, true) 14958 << (unsigned)size.getLimitedValue(~0U) 14959 << IndexExpr->getSourceRange()); 14960 } else { 14961 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14962 if (!ASE) { 14963 DiagID = diag::warn_ptr_arith_precedes_bounds; 14964 if (index.isNegative()) index = -index; 14965 } 14966 14967 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14968 PDiag(DiagID) << toString(index, 10, true) 14969 << IndexExpr->getSourceRange()); 14970 } 14971 14972 if (!ND) { 14973 // Try harder to find a NamedDecl to point at in the note. 14974 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14975 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14976 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14977 ND = DRE->getDecl(); 14978 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 14979 ND = ME->getMemberDecl(); 14980 } 14981 14982 if (ND) 14983 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14984 PDiag(diag::note_array_declared_here) << ND); 14985 } 14986 14987 void Sema::CheckArrayAccess(const Expr *expr) { 14988 int AllowOnePastEnd = 0; 14989 while (expr) { 14990 expr = expr->IgnoreParenImpCasts(); 14991 switch (expr->getStmtClass()) { 14992 case Stmt::ArraySubscriptExprClass: { 14993 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14994 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14995 AllowOnePastEnd > 0); 14996 expr = ASE->getBase(); 14997 break; 14998 } 14999 case Stmt::MemberExprClass: { 15000 expr = cast<MemberExpr>(expr)->getBase(); 15001 break; 15002 } 15003 case Stmt::OMPArraySectionExprClass: { 15004 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15005 if (ASE->getLowerBound()) 15006 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15007 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15008 return; 15009 } 15010 case Stmt::UnaryOperatorClass: { 15011 // Only unwrap the * and & unary operators 15012 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15013 expr = UO->getSubExpr(); 15014 switch (UO->getOpcode()) { 15015 case UO_AddrOf: 15016 AllowOnePastEnd++; 15017 break; 15018 case UO_Deref: 15019 AllowOnePastEnd--; 15020 break; 15021 default: 15022 return; 15023 } 15024 break; 15025 } 15026 case Stmt::ConditionalOperatorClass: { 15027 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15028 if (const Expr *lhs = cond->getLHS()) 15029 CheckArrayAccess(lhs); 15030 if (const Expr *rhs = cond->getRHS()) 15031 CheckArrayAccess(rhs); 15032 return; 15033 } 15034 case Stmt::CXXOperatorCallExprClass: { 15035 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15036 for (const auto *Arg : OCE->arguments()) 15037 CheckArrayAccess(Arg); 15038 return; 15039 } 15040 default: 15041 return; 15042 } 15043 } 15044 } 15045 15046 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15047 15048 namespace { 15049 15050 struct RetainCycleOwner { 15051 VarDecl *Variable = nullptr; 15052 SourceRange Range; 15053 SourceLocation Loc; 15054 bool Indirect = false; 15055 15056 RetainCycleOwner() = default; 15057 15058 void setLocsFrom(Expr *e) { 15059 Loc = e->getExprLoc(); 15060 Range = e->getSourceRange(); 15061 } 15062 }; 15063 15064 } // namespace 15065 15066 /// Consider whether capturing the given variable can possibly lead to 15067 /// a retain cycle. 15068 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15069 // In ARC, it's captured strongly iff the variable has __strong 15070 // lifetime. In MRR, it's captured strongly if the variable is 15071 // __block and has an appropriate type. 15072 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15073 return false; 15074 15075 owner.Variable = var; 15076 if (ref) 15077 owner.setLocsFrom(ref); 15078 return true; 15079 } 15080 15081 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15082 while (true) { 15083 e = e->IgnoreParens(); 15084 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15085 switch (cast->getCastKind()) { 15086 case CK_BitCast: 15087 case CK_LValueBitCast: 15088 case CK_LValueToRValue: 15089 case CK_ARCReclaimReturnedObject: 15090 e = cast->getSubExpr(); 15091 continue; 15092 15093 default: 15094 return false; 15095 } 15096 } 15097 15098 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15099 ObjCIvarDecl *ivar = ref->getDecl(); 15100 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15101 return false; 15102 15103 // Try to find a retain cycle in the base. 15104 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15105 return false; 15106 15107 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15108 owner.Indirect = true; 15109 return true; 15110 } 15111 15112 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15113 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15114 if (!var) return false; 15115 return considerVariable(var, ref, owner); 15116 } 15117 15118 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15119 if (member->isArrow()) return false; 15120 15121 // Don't count this as an indirect ownership. 15122 e = member->getBase(); 15123 continue; 15124 } 15125 15126 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15127 // Only pay attention to pseudo-objects on property references. 15128 ObjCPropertyRefExpr *pre 15129 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15130 ->IgnoreParens()); 15131 if (!pre) return false; 15132 if (pre->isImplicitProperty()) return false; 15133 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15134 if (!property->isRetaining() && 15135 !(property->getPropertyIvarDecl() && 15136 property->getPropertyIvarDecl()->getType() 15137 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15138 return false; 15139 15140 owner.Indirect = true; 15141 if (pre->isSuperReceiver()) { 15142 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15143 if (!owner.Variable) 15144 return false; 15145 owner.Loc = pre->getLocation(); 15146 owner.Range = pre->getSourceRange(); 15147 return true; 15148 } 15149 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15150 ->getSourceExpr()); 15151 continue; 15152 } 15153 15154 // Array ivars? 15155 15156 return false; 15157 } 15158 } 15159 15160 namespace { 15161 15162 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15163 ASTContext &Context; 15164 VarDecl *Variable; 15165 Expr *Capturer = nullptr; 15166 bool VarWillBeReased = false; 15167 15168 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15169 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15170 Context(Context), Variable(variable) {} 15171 15172 void VisitDeclRefExpr(DeclRefExpr *ref) { 15173 if (ref->getDecl() == Variable && !Capturer) 15174 Capturer = ref; 15175 } 15176 15177 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15178 if (Capturer) return; 15179 Visit(ref->getBase()); 15180 if (Capturer && ref->isFreeIvar()) 15181 Capturer = ref; 15182 } 15183 15184 void VisitBlockExpr(BlockExpr *block) { 15185 // Look inside nested blocks 15186 if (block->getBlockDecl()->capturesVariable(Variable)) 15187 Visit(block->getBlockDecl()->getBody()); 15188 } 15189 15190 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15191 if (Capturer) return; 15192 if (OVE->getSourceExpr()) 15193 Visit(OVE->getSourceExpr()); 15194 } 15195 15196 void VisitBinaryOperator(BinaryOperator *BinOp) { 15197 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15198 return; 15199 Expr *LHS = BinOp->getLHS(); 15200 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15201 if (DRE->getDecl() != Variable) 15202 return; 15203 if (Expr *RHS = BinOp->getRHS()) { 15204 RHS = RHS->IgnoreParenCasts(); 15205 Optional<llvm::APSInt> Value; 15206 VarWillBeReased = 15207 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15208 *Value == 0); 15209 } 15210 } 15211 } 15212 }; 15213 15214 } // namespace 15215 15216 /// Check whether the given argument is a block which captures a 15217 /// variable. 15218 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15219 assert(owner.Variable && owner.Loc.isValid()); 15220 15221 e = e->IgnoreParenCasts(); 15222 15223 // Look through [^{...} copy] and Block_copy(^{...}). 15224 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15225 Selector Cmd = ME->getSelector(); 15226 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15227 e = ME->getInstanceReceiver(); 15228 if (!e) 15229 return nullptr; 15230 e = e->IgnoreParenCasts(); 15231 } 15232 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15233 if (CE->getNumArgs() == 1) { 15234 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15235 if (Fn) { 15236 const IdentifierInfo *FnI = Fn->getIdentifier(); 15237 if (FnI && FnI->isStr("_Block_copy")) { 15238 e = CE->getArg(0)->IgnoreParenCasts(); 15239 } 15240 } 15241 } 15242 } 15243 15244 BlockExpr *block = dyn_cast<BlockExpr>(e); 15245 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15246 return nullptr; 15247 15248 FindCaptureVisitor visitor(S.Context, owner.Variable); 15249 visitor.Visit(block->getBlockDecl()->getBody()); 15250 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15251 } 15252 15253 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15254 RetainCycleOwner &owner) { 15255 assert(capturer); 15256 assert(owner.Variable && owner.Loc.isValid()); 15257 15258 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15259 << owner.Variable << capturer->getSourceRange(); 15260 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15261 << owner.Indirect << owner.Range; 15262 } 15263 15264 /// Check for a keyword selector that starts with the word 'add' or 15265 /// 'set'. 15266 static bool isSetterLikeSelector(Selector sel) { 15267 if (sel.isUnarySelector()) return false; 15268 15269 StringRef str = sel.getNameForSlot(0); 15270 while (!str.empty() && str.front() == '_') str = str.substr(1); 15271 if (str.startswith("set")) 15272 str = str.substr(3); 15273 else if (str.startswith("add")) { 15274 // Specially allow 'addOperationWithBlock:'. 15275 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15276 return false; 15277 str = str.substr(3); 15278 } 15279 else 15280 return false; 15281 15282 if (str.empty()) return true; 15283 return !isLowercase(str.front()); 15284 } 15285 15286 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15287 ObjCMessageExpr *Message) { 15288 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15289 Message->getReceiverInterface(), 15290 NSAPI::ClassId_NSMutableArray); 15291 if (!IsMutableArray) { 15292 return None; 15293 } 15294 15295 Selector Sel = Message->getSelector(); 15296 15297 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15298 S.NSAPIObj->getNSArrayMethodKind(Sel); 15299 if (!MKOpt) { 15300 return None; 15301 } 15302 15303 NSAPI::NSArrayMethodKind MK = *MKOpt; 15304 15305 switch (MK) { 15306 case NSAPI::NSMutableArr_addObject: 15307 case NSAPI::NSMutableArr_insertObjectAtIndex: 15308 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15309 return 0; 15310 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15311 return 1; 15312 15313 default: 15314 return None; 15315 } 15316 15317 return None; 15318 } 15319 15320 static 15321 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15322 ObjCMessageExpr *Message) { 15323 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15324 Message->getReceiverInterface(), 15325 NSAPI::ClassId_NSMutableDictionary); 15326 if (!IsMutableDictionary) { 15327 return None; 15328 } 15329 15330 Selector Sel = Message->getSelector(); 15331 15332 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15333 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15334 if (!MKOpt) { 15335 return None; 15336 } 15337 15338 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15339 15340 switch (MK) { 15341 case NSAPI::NSMutableDict_setObjectForKey: 15342 case NSAPI::NSMutableDict_setValueForKey: 15343 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15344 return 0; 15345 15346 default: 15347 return None; 15348 } 15349 15350 return None; 15351 } 15352 15353 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15354 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15355 Message->getReceiverInterface(), 15356 NSAPI::ClassId_NSMutableSet); 15357 15358 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15359 Message->getReceiverInterface(), 15360 NSAPI::ClassId_NSMutableOrderedSet); 15361 if (!IsMutableSet && !IsMutableOrderedSet) { 15362 return None; 15363 } 15364 15365 Selector Sel = Message->getSelector(); 15366 15367 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15368 if (!MKOpt) { 15369 return None; 15370 } 15371 15372 NSAPI::NSSetMethodKind MK = *MKOpt; 15373 15374 switch (MK) { 15375 case NSAPI::NSMutableSet_addObject: 15376 case NSAPI::NSOrderedSet_setObjectAtIndex: 15377 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15378 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15379 return 0; 15380 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15381 return 1; 15382 } 15383 15384 return None; 15385 } 15386 15387 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15388 if (!Message->isInstanceMessage()) { 15389 return; 15390 } 15391 15392 Optional<int> ArgOpt; 15393 15394 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15395 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15396 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15397 return; 15398 } 15399 15400 int ArgIndex = *ArgOpt; 15401 15402 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15403 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15404 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15405 } 15406 15407 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15408 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15409 if (ArgRE->isObjCSelfExpr()) { 15410 Diag(Message->getSourceRange().getBegin(), 15411 diag::warn_objc_circular_container) 15412 << ArgRE->getDecl() << StringRef("'super'"); 15413 } 15414 } 15415 } else { 15416 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15417 15418 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15419 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15420 } 15421 15422 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15423 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15424 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15425 ValueDecl *Decl = ReceiverRE->getDecl(); 15426 Diag(Message->getSourceRange().getBegin(), 15427 diag::warn_objc_circular_container) 15428 << Decl << Decl; 15429 if (!ArgRE->isObjCSelfExpr()) { 15430 Diag(Decl->getLocation(), 15431 diag::note_objc_circular_container_declared_here) 15432 << Decl; 15433 } 15434 } 15435 } 15436 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15437 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15438 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15439 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15440 Diag(Message->getSourceRange().getBegin(), 15441 diag::warn_objc_circular_container) 15442 << Decl << Decl; 15443 Diag(Decl->getLocation(), 15444 diag::note_objc_circular_container_declared_here) 15445 << Decl; 15446 } 15447 } 15448 } 15449 } 15450 } 15451 15452 /// Check a message send to see if it's likely to cause a retain cycle. 15453 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15454 // Only check instance methods whose selector looks like a setter. 15455 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15456 return; 15457 15458 // Try to find a variable that the receiver is strongly owned by. 15459 RetainCycleOwner owner; 15460 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15461 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15462 return; 15463 } else { 15464 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15465 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15466 owner.Loc = msg->getSuperLoc(); 15467 owner.Range = msg->getSuperLoc(); 15468 } 15469 15470 // Check whether the receiver is captured by any of the arguments. 15471 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15472 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15473 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15474 // noescape blocks should not be retained by the method. 15475 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15476 continue; 15477 return diagnoseRetainCycle(*this, capturer, owner); 15478 } 15479 } 15480 } 15481 15482 /// Check a property assign to see if it's likely to cause a retain cycle. 15483 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15484 RetainCycleOwner owner; 15485 if (!findRetainCycleOwner(*this, receiver, owner)) 15486 return; 15487 15488 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15489 diagnoseRetainCycle(*this, capturer, owner); 15490 } 15491 15492 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15493 RetainCycleOwner Owner; 15494 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15495 return; 15496 15497 // Because we don't have an expression for the variable, we have to set the 15498 // location explicitly here. 15499 Owner.Loc = Var->getLocation(); 15500 Owner.Range = Var->getSourceRange(); 15501 15502 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15503 diagnoseRetainCycle(*this, Capturer, Owner); 15504 } 15505 15506 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15507 Expr *RHS, bool isProperty) { 15508 // Check if RHS is an Objective-C object literal, which also can get 15509 // immediately zapped in a weak reference. Note that we explicitly 15510 // allow ObjCStringLiterals, since those are designed to never really die. 15511 RHS = RHS->IgnoreParenImpCasts(); 15512 15513 // This enum needs to match with the 'select' in 15514 // warn_objc_arc_literal_assign (off-by-1). 15515 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15516 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15517 return false; 15518 15519 S.Diag(Loc, diag::warn_arc_literal_assign) 15520 << (unsigned) Kind 15521 << (isProperty ? 0 : 1) 15522 << RHS->getSourceRange(); 15523 15524 return true; 15525 } 15526 15527 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15528 Qualifiers::ObjCLifetime LT, 15529 Expr *RHS, bool isProperty) { 15530 // Strip off any implicit cast added to get to the one ARC-specific. 15531 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15532 if (cast->getCastKind() == CK_ARCConsumeObject) { 15533 S.Diag(Loc, diag::warn_arc_retained_assign) 15534 << (LT == Qualifiers::OCL_ExplicitNone) 15535 << (isProperty ? 0 : 1) 15536 << RHS->getSourceRange(); 15537 return true; 15538 } 15539 RHS = cast->getSubExpr(); 15540 } 15541 15542 if (LT == Qualifiers::OCL_Weak && 15543 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15544 return true; 15545 15546 return false; 15547 } 15548 15549 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15550 QualType LHS, Expr *RHS) { 15551 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15552 15553 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15554 return false; 15555 15556 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15557 return true; 15558 15559 return false; 15560 } 15561 15562 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15563 Expr *LHS, Expr *RHS) { 15564 QualType LHSType; 15565 // PropertyRef on LHS type need be directly obtained from 15566 // its declaration as it has a PseudoType. 15567 ObjCPropertyRefExpr *PRE 15568 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15569 if (PRE && !PRE->isImplicitProperty()) { 15570 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15571 if (PD) 15572 LHSType = PD->getType(); 15573 } 15574 15575 if (LHSType.isNull()) 15576 LHSType = LHS->getType(); 15577 15578 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15579 15580 if (LT == Qualifiers::OCL_Weak) { 15581 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15582 getCurFunction()->markSafeWeakUse(LHS); 15583 } 15584 15585 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15586 return; 15587 15588 // FIXME. Check for other life times. 15589 if (LT != Qualifiers::OCL_None) 15590 return; 15591 15592 if (PRE) { 15593 if (PRE->isImplicitProperty()) 15594 return; 15595 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15596 if (!PD) 15597 return; 15598 15599 unsigned Attributes = PD->getPropertyAttributes(); 15600 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15601 // when 'assign' attribute was not explicitly specified 15602 // by user, ignore it and rely on property type itself 15603 // for lifetime info. 15604 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15605 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15606 LHSType->isObjCRetainableType()) 15607 return; 15608 15609 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15610 if (cast->getCastKind() == CK_ARCConsumeObject) { 15611 Diag(Loc, diag::warn_arc_retained_property_assign) 15612 << RHS->getSourceRange(); 15613 return; 15614 } 15615 RHS = cast->getSubExpr(); 15616 } 15617 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15618 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15619 return; 15620 } 15621 } 15622 } 15623 15624 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15625 15626 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15627 SourceLocation StmtLoc, 15628 const NullStmt *Body) { 15629 // Do not warn if the body is a macro that expands to nothing, e.g: 15630 // 15631 // #define CALL(x) 15632 // if (condition) 15633 // CALL(0); 15634 if (Body->hasLeadingEmptyMacro()) 15635 return false; 15636 15637 // Get line numbers of statement and body. 15638 bool StmtLineInvalid; 15639 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15640 &StmtLineInvalid); 15641 if (StmtLineInvalid) 15642 return false; 15643 15644 bool BodyLineInvalid; 15645 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15646 &BodyLineInvalid); 15647 if (BodyLineInvalid) 15648 return false; 15649 15650 // Warn if null statement and body are on the same line. 15651 if (StmtLine != BodyLine) 15652 return false; 15653 15654 return true; 15655 } 15656 15657 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15658 const Stmt *Body, 15659 unsigned DiagID) { 15660 // Since this is a syntactic check, don't emit diagnostic for template 15661 // instantiations, this just adds noise. 15662 if (CurrentInstantiationScope) 15663 return; 15664 15665 // The body should be a null statement. 15666 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15667 if (!NBody) 15668 return; 15669 15670 // Do the usual checks. 15671 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15672 return; 15673 15674 Diag(NBody->getSemiLoc(), DiagID); 15675 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15676 } 15677 15678 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15679 const Stmt *PossibleBody) { 15680 assert(!CurrentInstantiationScope); // Ensured by caller 15681 15682 SourceLocation StmtLoc; 15683 const Stmt *Body; 15684 unsigned DiagID; 15685 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15686 StmtLoc = FS->getRParenLoc(); 15687 Body = FS->getBody(); 15688 DiagID = diag::warn_empty_for_body; 15689 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15690 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15691 Body = WS->getBody(); 15692 DiagID = diag::warn_empty_while_body; 15693 } else 15694 return; // Neither `for' nor `while'. 15695 15696 // The body should be a null statement. 15697 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15698 if (!NBody) 15699 return; 15700 15701 // Skip expensive checks if diagnostic is disabled. 15702 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15703 return; 15704 15705 // Do the usual checks. 15706 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15707 return; 15708 15709 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15710 // noise level low, emit diagnostics only if for/while is followed by a 15711 // CompoundStmt, e.g.: 15712 // for (int i = 0; i < n; i++); 15713 // { 15714 // a(i); 15715 // } 15716 // or if for/while is followed by a statement with more indentation 15717 // than for/while itself: 15718 // for (int i = 0; i < n; i++); 15719 // a(i); 15720 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15721 if (!ProbableTypo) { 15722 bool BodyColInvalid; 15723 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15724 PossibleBody->getBeginLoc(), &BodyColInvalid); 15725 if (BodyColInvalid) 15726 return; 15727 15728 bool StmtColInvalid; 15729 unsigned StmtCol = 15730 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15731 if (StmtColInvalid) 15732 return; 15733 15734 if (BodyCol > StmtCol) 15735 ProbableTypo = true; 15736 } 15737 15738 if (ProbableTypo) { 15739 Diag(NBody->getSemiLoc(), DiagID); 15740 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15741 } 15742 } 15743 15744 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15745 15746 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15747 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15748 SourceLocation OpLoc) { 15749 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15750 return; 15751 15752 if (inTemplateInstantiation()) 15753 return; 15754 15755 // Strip parens and casts away. 15756 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15757 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15758 15759 // Check for a call expression 15760 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15761 if (!CE || CE->getNumArgs() != 1) 15762 return; 15763 15764 // Check for a call to std::move 15765 if (!CE->isCallToStdMove()) 15766 return; 15767 15768 // Get argument from std::move 15769 RHSExpr = CE->getArg(0); 15770 15771 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15772 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15773 15774 // Two DeclRefExpr's, check that the decls are the same. 15775 if (LHSDeclRef && RHSDeclRef) { 15776 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15777 return; 15778 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15779 RHSDeclRef->getDecl()->getCanonicalDecl()) 15780 return; 15781 15782 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15783 << LHSExpr->getSourceRange() 15784 << RHSExpr->getSourceRange(); 15785 return; 15786 } 15787 15788 // Member variables require a different approach to check for self moves. 15789 // MemberExpr's are the same if every nested MemberExpr refers to the same 15790 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15791 // the base Expr's are CXXThisExpr's. 15792 const Expr *LHSBase = LHSExpr; 15793 const Expr *RHSBase = RHSExpr; 15794 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15795 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15796 if (!LHSME || !RHSME) 15797 return; 15798 15799 while (LHSME && RHSME) { 15800 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15801 RHSME->getMemberDecl()->getCanonicalDecl()) 15802 return; 15803 15804 LHSBase = LHSME->getBase(); 15805 RHSBase = RHSME->getBase(); 15806 LHSME = dyn_cast<MemberExpr>(LHSBase); 15807 RHSME = dyn_cast<MemberExpr>(RHSBase); 15808 } 15809 15810 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15811 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15812 if (LHSDeclRef && RHSDeclRef) { 15813 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15814 return; 15815 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15816 RHSDeclRef->getDecl()->getCanonicalDecl()) 15817 return; 15818 15819 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15820 << LHSExpr->getSourceRange() 15821 << RHSExpr->getSourceRange(); 15822 return; 15823 } 15824 15825 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15826 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15827 << LHSExpr->getSourceRange() 15828 << RHSExpr->getSourceRange(); 15829 } 15830 15831 //===--- Layout compatibility ----------------------------------------------// 15832 15833 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15834 15835 /// Check if two enumeration types are layout-compatible. 15836 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15837 // C++11 [dcl.enum] p8: 15838 // Two enumeration types are layout-compatible if they have the same 15839 // underlying type. 15840 return ED1->isComplete() && ED2->isComplete() && 15841 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15842 } 15843 15844 /// Check if two fields are layout-compatible. 15845 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15846 FieldDecl *Field2) { 15847 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15848 return false; 15849 15850 if (Field1->isBitField() != Field2->isBitField()) 15851 return false; 15852 15853 if (Field1->isBitField()) { 15854 // Make sure that the bit-fields are the same length. 15855 unsigned Bits1 = Field1->getBitWidthValue(C); 15856 unsigned Bits2 = Field2->getBitWidthValue(C); 15857 15858 if (Bits1 != Bits2) 15859 return false; 15860 } 15861 15862 return true; 15863 } 15864 15865 /// Check if two standard-layout structs are layout-compatible. 15866 /// (C++11 [class.mem] p17) 15867 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15868 RecordDecl *RD2) { 15869 // If both records are C++ classes, check that base classes match. 15870 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15871 // If one of records is a CXXRecordDecl we are in C++ mode, 15872 // thus the other one is a CXXRecordDecl, too. 15873 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15874 // Check number of base classes. 15875 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15876 return false; 15877 15878 // Check the base classes. 15879 for (CXXRecordDecl::base_class_const_iterator 15880 Base1 = D1CXX->bases_begin(), 15881 BaseEnd1 = D1CXX->bases_end(), 15882 Base2 = D2CXX->bases_begin(); 15883 Base1 != BaseEnd1; 15884 ++Base1, ++Base2) { 15885 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15886 return false; 15887 } 15888 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15889 // If only RD2 is a C++ class, it should have zero base classes. 15890 if (D2CXX->getNumBases() > 0) 15891 return false; 15892 } 15893 15894 // Check the fields. 15895 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15896 Field2End = RD2->field_end(), 15897 Field1 = RD1->field_begin(), 15898 Field1End = RD1->field_end(); 15899 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15900 if (!isLayoutCompatible(C, *Field1, *Field2)) 15901 return false; 15902 } 15903 if (Field1 != Field1End || Field2 != Field2End) 15904 return false; 15905 15906 return true; 15907 } 15908 15909 /// Check if two standard-layout unions are layout-compatible. 15910 /// (C++11 [class.mem] p18) 15911 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15912 RecordDecl *RD2) { 15913 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15914 for (auto *Field2 : RD2->fields()) 15915 UnmatchedFields.insert(Field2); 15916 15917 for (auto *Field1 : RD1->fields()) { 15918 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15919 I = UnmatchedFields.begin(), 15920 E = UnmatchedFields.end(); 15921 15922 for ( ; I != E; ++I) { 15923 if (isLayoutCompatible(C, Field1, *I)) { 15924 bool Result = UnmatchedFields.erase(*I); 15925 (void) Result; 15926 assert(Result); 15927 break; 15928 } 15929 } 15930 if (I == E) 15931 return false; 15932 } 15933 15934 return UnmatchedFields.empty(); 15935 } 15936 15937 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15938 RecordDecl *RD2) { 15939 if (RD1->isUnion() != RD2->isUnion()) 15940 return false; 15941 15942 if (RD1->isUnion()) 15943 return isLayoutCompatibleUnion(C, RD1, RD2); 15944 else 15945 return isLayoutCompatibleStruct(C, RD1, RD2); 15946 } 15947 15948 /// Check if two types are layout-compatible in C++11 sense. 15949 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15950 if (T1.isNull() || T2.isNull()) 15951 return false; 15952 15953 // C++11 [basic.types] p11: 15954 // If two types T1 and T2 are the same type, then T1 and T2 are 15955 // layout-compatible types. 15956 if (C.hasSameType(T1, T2)) 15957 return true; 15958 15959 T1 = T1.getCanonicalType().getUnqualifiedType(); 15960 T2 = T2.getCanonicalType().getUnqualifiedType(); 15961 15962 const Type::TypeClass TC1 = T1->getTypeClass(); 15963 const Type::TypeClass TC2 = T2->getTypeClass(); 15964 15965 if (TC1 != TC2) 15966 return false; 15967 15968 if (TC1 == Type::Enum) { 15969 return isLayoutCompatible(C, 15970 cast<EnumType>(T1)->getDecl(), 15971 cast<EnumType>(T2)->getDecl()); 15972 } else if (TC1 == Type::Record) { 15973 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15974 return false; 15975 15976 return isLayoutCompatible(C, 15977 cast<RecordType>(T1)->getDecl(), 15978 cast<RecordType>(T2)->getDecl()); 15979 } 15980 15981 return false; 15982 } 15983 15984 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15985 15986 /// Given a type tag expression find the type tag itself. 15987 /// 15988 /// \param TypeExpr Type tag expression, as it appears in user's code. 15989 /// 15990 /// \param VD Declaration of an identifier that appears in a type tag. 15991 /// 15992 /// \param MagicValue Type tag magic value. 15993 /// 15994 /// \param isConstantEvaluated wether the evalaution should be performed in 15995 15996 /// constant context. 15997 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15998 const ValueDecl **VD, uint64_t *MagicValue, 15999 bool isConstantEvaluated) { 16000 while(true) { 16001 if (!TypeExpr) 16002 return false; 16003 16004 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16005 16006 switch (TypeExpr->getStmtClass()) { 16007 case Stmt::UnaryOperatorClass: { 16008 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16009 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16010 TypeExpr = UO->getSubExpr(); 16011 continue; 16012 } 16013 return false; 16014 } 16015 16016 case Stmt::DeclRefExprClass: { 16017 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16018 *VD = DRE->getDecl(); 16019 return true; 16020 } 16021 16022 case Stmt::IntegerLiteralClass: { 16023 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16024 llvm::APInt MagicValueAPInt = IL->getValue(); 16025 if (MagicValueAPInt.getActiveBits() <= 64) { 16026 *MagicValue = MagicValueAPInt.getZExtValue(); 16027 return true; 16028 } else 16029 return false; 16030 } 16031 16032 case Stmt::BinaryConditionalOperatorClass: 16033 case Stmt::ConditionalOperatorClass: { 16034 const AbstractConditionalOperator *ACO = 16035 cast<AbstractConditionalOperator>(TypeExpr); 16036 bool Result; 16037 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16038 isConstantEvaluated)) { 16039 if (Result) 16040 TypeExpr = ACO->getTrueExpr(); 16041 else 16042 TypeExpr = ACO->getFalseExpr(); 16043 continue; 16044 } 16045 return false; 16046 } 16047 16048 case Stmt::BinaryOperatorClass: { 16049 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16050 if (BO->getOpcode() == BO_Comma) { 16051 TypeExpr = BO->getRHS(); 16052 continue; 16053 } 16054 return false; 16055 } 16056 16057 default: 16058 return false; 16059 } 16060 } 16061 } 16062 16063 /// Retrieve the C type corresponding to type tag TypeExpr. 16064 /// 16065 /// \param TypeExpr Expression that specifies a type tag. 16066 /// 16067 /// \param MagicValues Registered magic values. 16068 /// 16069 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16070 /// kind. 16071 /// 16072 /// \param TypeInfo Information about the corresponding C type. 16073 /// 16074 /// \param isConstantEvaluated wether the evalaution should be performed in 16075 /// constant context. 16076 /// 16077 /// \returns true if the corresponding C type was found. 16078 static bool GetMatchingCType( 16079 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16080 const ASTContext &Ctx, 16081 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16082 *MagicValues, 16083 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16084 bool isConstantEvaluated) { 16085 FoundWrongKind = false; 16086 16087 // Variable declaration that has type_tag_for_datatype attribute. 16088 const ValueDecl *VD = nullptr; 16089 16090 uint64_t MagicValue; 16091 16092 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16093 return false; 16094 16095 if (VD) { 16096 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16097 if (I->getArgumentKind() != ArgumentKind) { 16098 FoundWrongKind = true; 16099 return false; 16100 } 16101 TypeInfo.Type = I->getMatchingCType(); 16102 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16103 TypeInfo.MustBeNull = I->getMustBeNull(); 16104 return true; 16105 } 16106 return false; 16107 } 16108 16109 if (!MagicValues) 16110 return false; 16111 16112 llvm::DenseMap<Sema::TypeTagMagicValue, 16113 Sema::TypeTagData>::const_iterator I = 16114 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16115 if (I == MagicValues->end()) 16116 return false; 16117 16118 TypeInfo = I->second; 16119 return true; 16120 } 16121 16122 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16123 uint64_t MagicValue, QualType Type, 16124 bool LayoutCompatible, 16125 bool MustBeNull) { 16126 if (!TypeTagForDatatypeMagicValues) 16127 TypeTagForDatatypeMagicValues.reset( 16128 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16129 16130 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16131 (*TypeTagForDatatypeMagicValues)[Magic] = 16132 TypeTagData(Type, LayoutCompatible, MustBeNull); 16133 } 16134 16135 static bool IsSameCharType(QualType T1, QualType T2) { 16136 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16137 if (!BT1) 16138 return false; 16139 16140 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16141 if (!BT2) 16142 return false; 16143 16144 BuiltinType::Kind T1Kind = BT1->getKind(); 16145 BuiltinType::Kind T2Kind = BT2->getKind(); 16146 16147 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16148 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16149 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16150 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16151 } 16152 16153 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16154 const ArrayRef<const Expr *> ExprArgs, 16155 SourceLocation CallSiteLoc) { 16156 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16157 bool IsPointerAttr = Attr->getIsPointer(); 16158 16159 // Retrieve the argument representing the 'type_tag'. 16160 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16161 if (TypeTagIdxAST >= ExprArgs.size()) { 16162 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16163 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16164 return; 16165 } 16166 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16167 bool FoundWrongKind; 16168 TypeTagData TypeInfo; 16169 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16170 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16171 TypeInfo, isConstantEvaluated())) { 16172 if (FoundWrongKind) 16173 Diag(TypeTagExpr->getExprLoc(), 16174 diag::warn_type_tag_for_datatype_wrong_kind) 16175 << TypeTagExpr->getSourceRange(); 16176 return; 16177 } 16178 16179 // Retrieve the argument representing the 'arg_idx'. 16180 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16181 if (ArgumentIdxAST >= ExprArgs.size()) { 16182 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16183 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16184 return; 16185 } 16186 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16187 if (IsPointerAttr) { 16188 // Skip implicit cast of pointer to `void *' (as a function argument). 16189 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16190 if (ICE->getType()->isVoidPointerType() && 16191 ICE->getCastKind() == CK_BitCast) 16192 ArgumentExpr = ICE->getSubExpr(); 16193 } 16194 QualType ArgumentType = ArgumentExpr->getType(); 16195 16196 // Passing a `void*' pointer shouldn't trigger a warning. 16197 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16198 return; 16199 16200 if (TypeInfo.MustBeNull) { 16201 // Type tag with matching void type requires a null pointer. 16202 if (!ArgumentExpr->isNullPointerConstant(Context, 16203 Expr::NPC_ValueDependentIsNotNull)) { 16204 Diag(ArgumentExpr->getExprLoc(), 16205 diag::warn_type_safety_null_pointer_required) 16206 << ArgumentKind->getName() 16207 << ArgumentExpr->getSourceRange() 16208 << TypeTagExpr->getSourceRange(); 16209 } 16210 return; 16211 } 16212 16213 QualType RequiredType = TypeInfo.Type; 16214 if (IsPointerAttr) 16215 RequiredType = Context.getPointerType(RequiredType); 16216 16217 bool mismatch = false; 16218 if (!TypeInfo.LayoutCompatible) { 16219 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16220 16221 // C++11 [basic.fundamental] p1: 16222 // Plain char, signed char, and unsigned char are three distinct types. 16223 // 16224 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16225 // char' depending on the current char signedness mode. 16226 if (mismatch) 16227 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16228 RequiredType->getPointeeType())) || 16229 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16230 mismatch = false; 16231 } else 16232 if (IsPointerAttr) 16233 mismatch = !isLayoutCompatible(Context, 16234 ArgumentType->getPointeeType(), 16235 RequiredType->getPointeeType()); 16236 else 16237 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16238 16239 if (mismatch) 16240 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16241 << ArgumentType << ArgumentKind 16242 << TypeInfo.LayoutCompatible << RequiredType 16243 << ArgumentExpr->getSourceRange() 16244 << TypeTagExpr->getSourceRange(); 16245 } 16246 16247 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16248 CharUnits Alignment) { 16249 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16250 } 16251 16252 void Sema::DiagnoseMisalignedMembers() { 16253 for (MisalignedMember &m : MisalignedMembers) { 16254 const NamedDecl *ND = m.RD; 16255 if (ND->getName().empty()) { 16256 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16257 ND = TD; 16258 } 16259 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16260 << m.MD << ND << m.E->getSourceRange(); 16261 } 16262 MisalignedMembers.clear(); 16263 } 16264 16265 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16266 E = E->IgnoreParens(); 16267 if (!T->isPointerType() && !T->isIntegerType()) 16268 return; 16269 if (isa<UnaryOperator>(E) && 16270 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16271 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16272 if (isa<MemberExpr>(Op)) { 16273 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16274 if (MA != MisalignedMembers.end() && 16275 (T->isIntegerType() || 16276 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16277 Context.getTypeAlignInChars( 16278 T->getPointeeType()) <= MA->Alignment)))) 16279 MisalignedMembers.erase(MA); 16280 } 16281 } 16282 } 16283 16284 void Sema::RefersToMemberWithReducedAlignment( 16285 Expr *E, 16286 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16287 Action) { 16288 const auto *ME = dyn_cast<MemberExpr>(E); 16289 if (!ME) 16290 return; 16291 16292 // No need to check expressions with an __unaligned-qualified type. 16293 if (E->getType().getQualifiers().hasUnaligned()) 16294 return; 16295 16296 // For a chain of MemberExpr like "a.b.c.d" this list 16297 // will keep FieldDecl's like [d, c, b]. 16298 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16299 const MemberExpr *TopME = nullptr; 16300 bool AnyIsPacked = false; 16301 do { 16302 QualType BaseType = ME->getBase()->getType(); 16303 if (BaseType->isDependentType()) 16304 return; 16305 if (ME->isArrow()) 16306 BaseType = BaseType->getPointeeType(); 16307 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16308 if (RD->isInvalidDecl()) 16309 return; 16310 16311 ValueDecl *MD = ME->getMemberDecl(); 16312 auto *FD = dyn_cast<FieldDecl>(MD); 16313 // We do not care about non-data members. 16314 if (!FD || FD->isInvalidDecl()) 16315 return; 16316 16317 AnyIsPacked = 16318 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16319 ReverseMemberChain.push_back(FD); 16320 16321 TopME = ME; 16322 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16323 } while (ME); 16324 assert(TopME && "We did not compute a topmost MemberExpr!"); 16325 16326 // Not the scope of this diagnostic. 16327 if (!AnyIsPacked) 16328 return; 16329 16330 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16331 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16332 // TODO: The innermost base of the member expression may be too complicated. 16333 // For now, just disregard these cases. This is left for future 16334 // improvement. 16335 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16336 return; 16337 16338 // Alignment expected by the whole expression. 16339 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16340 16341 // No need to do anything else with this case. 16342 if (ExpectedAlignment.isOne()) 16343 return; 16344 16345 // Synthesize offset of the whole access. 16346 CharUnits Offset; 16347 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16348 I++) { 16349 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16350 } 16351 16352 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16353 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16354 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16355 16356 // The base expression of the innermost MemberExpr may give 16357 // stronger guarantees than the class containing the member. 16358 if (DRE && !TopME->isArrow()) { 16359 const ValueDecl *VD = DRE->getDecl(); 16360 if (!VD->getType()->isReferenceType()) 16361 CompleteObjectAlignment = 16362 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16363 } 16364 16365 // Check if the synthesized offset fulfills the alignment. 16366 if (Offset % ExpectedAlignment != 0 || 16367 // It may fulfill the offset it but the effective alignment may still be 16368 // lower than the expected expression alignment. 16369 CompleteObjectAlignment < ExpectedAlignment) { 16370 // If this happens, we want to determine a sensible culprit of this. 16371 // Intuitively, watching the chain of member expressions from right to 16372 // left, we start with the required alignment (as required by the field 16373 // type) but some packed attribute in that chain has reduced the alignment. 16374 // It may happen that another packed structure increases it again. But if 16375 // we are here such increase has not been enough. So pointing the first 16376 // FieldDecl that either is packed or else its RecordDecl is, 16377 // seems reasonable. 16378 FieldDecl *FD = nullptr; 16379 CharUnits Alignment; 16380 for (FieldDecl *FDI : ReverseMemberChain) { 16381 if (FDI->hasAttr<PackedAttr>() || 16382 FDI->getParent()->hasAttr<PackedAttr>()) { 16383 FD = FDI; 16384 Alignment = std::min( 16385 Context.getTypeAlignInChars(FD->getType()), 16386 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16387 break; 16388 } 16389 } 16390 assert(FD && "We did not find a packed FieldDecl!"); 16391 Action(E, FD->getParent(), FD, Alignment); 16392 } 16393 } 16394 16395 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16396 using namespace std::placeholders; 16397 16398 RefersToMemberWithReducedAlignment( 16399 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16400 _2, _3, _4)); 16401 } 16402 16403 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16404 ExprResult CallResult) { 16405 if (checkArgCount(*this, TheCall, 1)) 16406 return ExprError(); 16407 16408 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16409 if (MatrixArg.isInvalid()) 16410 return MatrixArg; 16411 Expr *Matrix = MatrixArg.get(); 16412 16413 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16414 if (!MType) { 16415 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16416 return ExprError(); 16417 } 16418 16419 // Create returned matrix type by swapping rows and columns of the argument 16420 // matrix type. 16421 QualType ResultType = Context.getConstantMatrixType( 16422 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16423 16424 // Change the return type to the type of the returned matrix. 16425 TheCall->setType(ResultType); 16426 16427 // Update call argument to use the possibly converted matrix argument. 16428 TheCall->setArg(0, Matrix); 16429 return CallResult; 16430 } 16431 16432 // Get and verify the matrix dimensions. 16433 static llvm::Optional<unsigned> 16434 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16435 SourceLocation ErrorPos; 16436 Optional<llvm::APSInt> Value = 16437 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16438 if (!Value) { 16439 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16440 << Name; 16441 return {}; 16442 } 16443 uint64_t Dim = Value->getZExtValue(); 16444 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16445 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16446 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16447 return {}; 16448 } 16449 return Dim; 16450 } 16451 16452 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16453 ExprResult CallResult) { 16454 if (!getLangOpts().MatrixTypes) { 16455 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16456 return ExprError(); 16457 } 16458 16459 if (checkArgCount(*this, TheCall, 4)) 16460 return ExprError(); 16461 16462 unsigned PtrArgIdx = 0; 16463 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16464 Expr *RowsExpr = TheCall->getArg(1); 16465 Expr *ColumnsExpr = TheCall->getArg(2); 16466 Expr *StrideExpr = TheCall->getArg(3); 16467 16468 bool ArgError = false; 16469 16470 // Check pointer argument. 16471 { 16472 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16473 if (PtrConv.isInvalid()) 16474 return PtrConv; 16475 PtrExpr = PtrConv.get(); 16476 TheCall->setArg(0, PtrExpr); 16477 if (PtrExpr->isTypeDependent()) { 16478 TheCall->setType(Context.DependentTy); 16479 return TheCall; 16480 } 16481 } 16482 16483 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16484 QualType ElementTy; 16485 if (!PtrTy) { 16486 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16487 << PtrArgIdx + 1; 16488 ArgError = true; 16489 } else { 16490 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16491 16492 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16493 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16494 << PtrArgIdx + 1; 16495 ArgError = true; 16496 } 16497 } 16498 16499 // Apply default Lvalue conversions and convert the expression to size_t. 16500 auto ApplyArgumentConversions = [this](Expr *E) { 16501 ExprResult Conv = DefaultLvalueConversion(E); 16502 if (Conv.isInvalid()) 16503 return Conv; 16504 16505 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16506 }; 16507 16508 // Apply conversion to row and column expressions. 16509 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16510 if (!RowsConv.isInvalid()) { 16511 RowsExpr = RowsConv.get(); 16512 TheCall->setArg(1, RowsExpr); 16513 } else 16514 RowsExpr = nullptr; 16515 16516 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16517 if (!ColumnsConv.isInvalid()) { 16518 ColumnsExpr = ColumnsConv.get(); 16519 TheCall->setArg(2, ColumnsExpr); 16520 } else 16521 ColumnsExpr = nullptr; 16522 16523 // If any any part of the result matrix type is still pending, just use 16524 // Context.DependentTy, until all parts are resolved. 16525 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16526 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16527 TheCall->setType(Context.DependentTy); 16528 return CallResult; 16529 } 16530 16531 // Check row and column dimenions. 16532 llvm::Optional<unsigned> MaybeRows; 16533 if (RowsExpr) 16534 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16535 16536 llvm::Optional<unsigned> MaybeColumns; 16537 if (ColumnsExpr) 16538 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16539 16540 // Check stride argument. 16541 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16542 if (StrideConv.isInvalid()) 16543 return ExprError(); 16544 StrideExpr = StrideConv.get(); 16545 TheCall->setArg(3, StrideExpr); 16546 16547 if (MaybeRows) { 16548 if (Optional<llvm::APSInt> Value = 16549 StrideExpr->getIntegerConstantExpr(Context)) { 16550 uint64_t Stride = Value->getZExtValue(); 16551 if (Stride < *MaybeRows) { 16552 Diag(StrideExpr->getBeginLoc(), 16553 diag::err_builtin_matrix_stride_too_small); 16554 ArgError = true; 16555 } 16556 } 16557 } 16558 16559 if (ArgError || !MaybeRows || !MaybeColumns) 16560 return ExprError(); 16561 16562 TheCall->setType( 16563 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16564 return CallResult; 16565 } 16566 16567 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16568 ExprResult CallResult) { 16569 if (checkArgCount(*this, TheCall, 3)) 16570 return ExprError(); 16571 16572 unsigned PtrArgIdx = 1; 16573 Expr *MatrixExpr = TheCall->getArg(0); 16574 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16575 Expr *StrideExpr = TheCall->getArg(2); 16576 16577 bool ArgError = false; 16578 16579 { 16580 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16581 if (MatrixConv.isInvalid()) 16582 return MatrixConv; 16583 MatrixExpr = MatrixConv.get(); 16584 TheCall->setArg(0, MatrixExpr); 16585 } 16586 if (MatrixExpr->isTypeDependent()) { 16587 TheCall->setType(Context.DependentTy); 16588 return TheCall; 16589 } 16590 16591 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16592 if (!MatrixTy) { 16593 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16594 ArgError = true; 16595 } 16596 16597 { 16598 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16599 if (PtrConv.isInvalid()) 16600 return PtrConv; 16601 PtrExpr = PtrConv.get(); 16602 TheCall->setArg(1, PtrExpr); 16603 if (PtrExpr->isTypeDependent()) { 16604 TheCall->setType(Context.DependentTy); 16605 return TheCall; 16606 } 16607 } 16608 16609 // Check pointer argument. 16610 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16611 if (!PtrTy) { 16612 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16613 << PtrArgIdx + 1; 16614 ArgError = true; 16615 } else { 16616 QualType ElementTy = PtrTy->getPointeeType(); 16617 if (ElementTy.isConstQualified()) { 16618 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16619 ArgError = true; 16620 } 16621 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16622 if (MatrixTy && 16623 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16624 Diag(PtrExpr->getBeginLoc(), 16625 diag::err_builtin_matrix_pointer_arg_mismatch) 16626 << ElementTy << MatrixTy->getElementType(); 16627 ArgError = true; 16628 } 16629 } 16630 16631 // Apply default Lvalue conversions and convert the stride expression to 16632 // size_t. 16633 { 16634 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16635 if (StrideConv.isInvalid()) 16636 return StrideConv; 16637 16638 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16639 if (StrideConv.isInvalid()) 16640 return StrideConv; 16641 StrideExpr = StrideConv.get(); 16642 TheCall->setArg(2, StrideExpr); 16643 } 16644 16645 // Check stride argument. 16646 if (MatrixTy) { 16647 if (Optional<llvm::APSInt> Value = 16648 StrideExpr->getIntegerConstantExpr(Context)) { 16649 uint64_t Stride = Value->getZExtValue(); 16650 if (Stride < MatrixTy->getNumRows()) { 16651 Diag(StrideExpr->getBeginLoc(), 16652 diag::err_builtin_matrix_stride_too_small); 16653 ArgError = true; 16654 } 16655 } 16656 } 16657 16658 if (ArgError) 16659 return ExprError(); 16660 16661 return CallResult; 16662 } 16663 16664 /// \brief Enforce the bounds of a TCB 16665 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16666 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16667 /// and enforce_tcb_leaf attributes. 16668 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16669 const FunctionDecl *Callee) { 16670 const FunctionDecl *Caller = getCurFunctionDecl(); 16671 16672 // Calls to builtins are not enforced. 16673 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16674 Callee->getBuiltinID() != 0) 16675 return; 16676 16677 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16678 // all TCBs the callee is a part of. 16679 llvm::StringSet<> CalleeTCBs; 16680 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16681 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16682 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16683 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16684 16685 // Go through the TCBs the caller is a part of and emit warnings if Caller 16686 // is in a TCB that the Callee is not. 16687 for_each( 16688 Caller->specific_attrs<EnforceTCBAttr>(), 16689 [&](const auto *A) { 16690 StringRef CallerTCB = A->getTCBName(); 16691 if (CalleeTCBs.count(CallerTCB) == 0) { 16692 this->Diag(TheCall->getExprLoc(), 16693 diag::warn_tcb_enforcement_violation) << Callee 16694 << CallerTCB; 16695 } 16696 }); 16697 } 16698