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 <cstddef> 95 #include <cstdint> 96 #include <functional> 97 #include <limits> 98 #include <string> 99 #include <tuple> 100 #include <utility> 101 102 using namespace clang; 103 using namespace sema; 104 105 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 106 unsigned ByteNo) const { 107 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 108 Context.getTargetInfo()); 109 } 110 111 /// Checks that a call expression's argument count is the desired number. 112 /// This is useful when doing custom type-checking. Returns true on error. 113 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 114 unsigned argCount = call->getNumArgs(); 115 if (argCount == desiredArgCount) return false; 116 117 if (argCount < desiredArgCount) 118 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 119 << 0 /*function call*/ << desiredArgCount << argCount 120 << call->getSourceRange(); 121 122 // Highlight all the excess arguments. 123 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 124 call->getArg(argCount - 1)->getEndLoc()); 125 126 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 127 << 0 /*function call*/ << desiredArgCount << argCount 128 << call->getArg(1)->getSourceRange(); 129 } 130 131 /// Check that the first argument to __builtin_annotation is an integer 132 /// and the second argument is a non-wide string literal. 133 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 134 if (checkArgCount(S, TheCall, 2)) 135 return true; 136 137 // First argument should be an integer. 138 Expr *ValArg = TheCall->getArg(0); 139 QualType Ty = ValArg->getType(); 140 if (!Ty->isIntegerType()) { 141 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 142 << ValArg->getSourceRange(); 143 return true; 144 } 145 146 // Second argument should be a constant string. 147 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 148 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 149 if (!Literal || !Literal->isAscii()) { 150 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 151 << StrArg->getSourceRange(); 152 return true; 153 } 154 155 TheCall->setType(Ty); 156 return false; 157 } 158 159 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 160 // We need at least one argument. 161 if (TheCall->getNumArgs() < 1) { 162 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 163 << 0 << 1 << TheCall->getNumArgs() 164 << TheCall->getCallee()->getSourceRange(); 165 return true; 166 } 167 168 // All arguments should be wide string literals. 169 for (Expr *Arg : TheCall->arguments()) { 170 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 171 if (!Literal || !Literal->isWide()) { 172 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 173 << Arg->getSourceRange(); 174 return true; 175 } 176 } 177 178 return false; 179 } 180 181 /// Check that the argument to __builtin_addressof is a glvalue, and set the 182 /// result type to the corresponding pointer type. 183 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 184 if (checkArgCount(S, TheCall, 1)) 185 return true; 186 187 ExprResult Arg(TheCall->getArg(0)); 188 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 189 if (ResultType.isNull()) 190 return true; 191 192 TheCall->setArg(0, Arg.get()); 193 TheCall->setType(ResultType); 194 return false; 195 } 196 197 /// Check the number of arguments and set the result type to 198 /// the argument type. 199 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 200 if (checkArgCount(S, TheCall, 1)) 201 return true; 202 203 TheCall->setType(TheCall->getArg(0)->getType()); 204 return false; 205 } 206 207 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 208 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 209 /// type (but not a function pointer) and that the alignment is a power-of-two. 210 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 211 if (checkArgCount(S, TheCall, 2)) 212 return true; 213 214 clang::Expr *Source = TheCall->getArg(0); 215 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 216 217 auto IsValidIntegerType = [](QualType Ty) { 218 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 219 }; 220 QualType SrcTy = Source->getType(); 221 // We should also be able to use it with arrays (but not functions!). 222 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 223 SrcTy = S.Context.getDecayedType(SrcTy); 224 } 225 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 226 SrcTy->isFunctionPointerType()) { 227 // FIXME: this is not quite the right error message since we don't allow 228 // floating point types, or member pointers. 229 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 230 << SrcTy; 231 return true; 232 } 233 234 clang::Expr *AlignOp = TheCall->getArg(1); 235 if (!IsValidIntegerType(AlignOp->getType())) { 236 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 237 << AlignOp->getType(); 238 return true; 239 } 240 Expr::EvalResult AlignResult; 241 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 242 // We can't check validity of alignment if it is value dependent. 243 if (!AlignOp->isValueDependent() && 244 AlignOp->EvaluateAsInt(AlignResult, S.Context, 245 Expr::SE_AllowSideEffects)) { 246 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 247 llvm::APSInt MaxValue( 248 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 249 if (AlignValue < 1) { 250 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 251 return true; 252 } 253 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 254 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 255 << MaxValue.toString(10); 256 return true; 257 } 258 if (!AlignValue.isPowerOf2()) { 259 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 260 return true; 261 } 262 if (AlignValue == 1) { 263 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 264 << IsBooleanAlignBuiltin; 265 } 266 } 267 268 ExprResult SrcArg = S.PerformCopyInitialization( 269 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 270 SourceLocation(), Source); 271 if (SrcArg.isInvalid()) 272 return true; 273 TheCall->setArg(0, SrcArg.get()); 274 ExprResult AlignArg = 275 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 276 S.Context, AlignOp->getType(), false), 277 SourceLocation(), AlignOp); 278 if (AlignArg.isInvalid()) 279 return true; 280 TheCall->setArg(1, AlignArg.get()); 281 // For align_up/align_down, the return type is the same as the (potentially 282 // decayed) argument type including qualifiers. For is_aligned(), the result 283 // is always bool. 284 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 285 return false; 286 } 287 288 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 289 unsigned BuiltinID) { 290 if (checkArgCount(S, TheCall, 3)) 291 return true; 292 293 // First two arguments should be integers. 294 for (unsigned I = 0; I < 2; ++I) { 295 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 296 if (Arg.isInvalid()) return true; 297 TheCall->setArg(I, Arg.get()); 298 299 QualType Ty = Arg.get()->getType(); 300 if (!Ty->isIntegerType()) { 301 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 302 << Ty << Arg.get()->getSourceRange(); 303 return true; 304 } 305 } 306 307 // Third argument should be a pointer to a non-const integer. 308 // IRGen correctly handles volatile, restrict, and address spaces, and 309 // the other qualifiers aren't possible. 310 { 311 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 312 if (Arg.isInvalid()) return true; 313 TheCall->setArg(2, Arg.get()); 314 315 QualType Ty = Arg.get()->getType(); 316 const auto *PtrTy = Ty->getAs<PointerType>(); 317 if (!PtrTy || 318 !PtrTy->getPointeeType()->isIntegerType() || 319 PtrTy->getPointeeType().isConstQualified()) { 320 S.Diag(Arg.get()->getBeginLoc(), 321 diag::err_overflow_builtin_must_be_ptr_int) 322 << Ty << Arg.get()->getSourceRange(); 323 return true; 324 } 325 } 326 327 // Disallow signed ExtIntType args larger than 128 bits to mul function until 328 // we improve backend support. 329 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 330 for (unsigned I = 0; I < 3; ++I) { 331 const auto Arg = TheCall->getArg(I); 332 // Third argument will be a pointer. 333 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 334 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 335 S.getASTContext().getIntWidth(Ty) > 128) 336 return S.Diag(Arg->getBeginLoc(), 337 diag::err_overflow_builtin_ext_int_max_size) 338 << 128; 339 } 340 } 341 342 return false; 343 } 344 345 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 346 if (checkArgCount(S, BuiltinCall, 2)) 347 return true; 348 349 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 350 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 351 Expr *Call = BuiltinCall->getArg(0); 352 Expr *Chain = BuiltinCall->getArg(1); 353 354 if (Call->getStmtClass() != Stmt::CallExprClass) { 355 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 356 << Call->getSourceRange(); 357 return true; 358 } 359 360 auto CE = cast<CallExpr>(Call); 361 if (CE->getCallee()->getType()->isBlockPointerType()) { 362 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 363 << Call->getSourceRange(); 364 return true; 365 } 366 367 const Decl *TargetDecl = CE->getCalleeDecl(); 368 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 369 if (FD->getBuiltinID()) { 370 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 371 << Call->getSourceRange(); 372 return true; 373 } 374 375 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 376 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 377 << Call->getSourceRange(); 378 return true; 379 } 380 381 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 382 if (ChainResult.isInvalid()) 383 return true; 384 if (!ChainResult.get()->getType()->isPointerType()) { 385 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 386 << Chain->getSourceRange(); 387 return true; 388 } 389 390 QualType ReturnTy = CE->getCallReturnType(S.Context); 391 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 392 QualType BuiltinTy = S.Context.getFunctionType( 393 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 394 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 395 396 Builtin = 397 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 398 399 BuiltinCall->setType(CE->getType()); 400 BuiltinCall->setValueKind(CE->getValueKind()); 401 BuiltinCall->setObjectKind(CE->getObjectKind()); 402 BuiltinCall->setCallee(Builtin); 403 BuiltinCall->setArg(1, ChainResult.get()); 404 405 return false; 406 } 407 408 namespace { 409 410 class EstimateSizeFormatHandler 411 : public analyze_format_string::FormatStringHandler { 412 size_t Size; 413 414 public: 415 EstimateSizeFormatHandler(StringRef Format) 416 : Size(std::min(Format.find(0), Format.size()) + 417 1 /* null byte always written by sprintf */) {} 418 419 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 420 const char *, unsigned SpecifierLen) override { 421 422 const size_t FieldWidth = computeFieldWidth(FS); 423 const size_t Precision = computePrecision(FS); 424 425 // The actual format. 426 switch (FS.getConversionSpecifier().getKind()) { 427 // Just a char. 428 case analyze_format_string::ConversionSpecifier::cArg: 429 case analyze_format_string::ConversionSpecifier::CArg: 430 Size += std::max(FieldWidth, (size_t)1); 431 break; 432 // Just an integer. 433 case analyze_format_string::ConversionSpecifier::dArg: 434 case analyze_format_string::ConversionSpecifier::DArg: 435 case analyze_format_string::ConversionSpecifier::iArg: 436 case analyze_format_string::ConversionSpecifier::oArg: 437 case analyze_format_string::ConversionSpecifier::OArg: 438 case analyze_format_string::ConversionSpecifier::uArg: 439 case analyze_format_string::ConversionSpecifier::UArg: 440 case analyze_format_string::ConversionSpecifier::xArg: 441 case analyze_format_string::ConversionSpecifier::XArg: 442 Size += std::max(FieldWidth, Precision); 443 break; 444 445 // %g style conversion switches between %f or %e style dynamically. 446 // %f always takes less space, so default to it. 447 case analyze_format_string::ConversionSpecifier::gArg: 448 case analyze_format_string::ConversionSpecifier::GArg: 449 450 // Floating point number in the form '[+]ddd.ddd'. 451 case analyze_format_string::ConversionSpecifier::fArg: 452 case analyze_format_string::ConversionSpecifier::FArg: 453 Size += std::max(FieldWidth, 1 /* integer part */ + 454 (Precision ? 1 + Precision 455 : 0) /* period + decimal */); 456 break; 457 458 // Floating point number in the form '[-]d.ddde[+-]dd'. 459 case analyze_format_string::ConversionSpecifier::eArg: 460 case analyze_format_string::ConversionSpecifier::EArg: 461 Size += 462 std::max(FieldWidth, 463 1 /* integer part */ + 464 (Precision ? 1 + Precision : 0) /* period + decimal */ + 465 1 /* e or E letter */ + 2 /* exponent */); 466 break; 467 468 // Floating point number in the form '[-]0xh.hhhhp±dd'. 469 case analyze_format_string::ConversionSpecifier::aArg: 470 case analyze_format_string::ConversionSpecifier::AArg: 471 Size += 472 std::max(FieldWidth, 473 2 /* 0x */ + 1 /* integer part */ + 474 (Precision ? 1 + Precision : 0) /* period + decimal */ + 475 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 476 break; 477 478 // Just a string. 479 case analyze_format_string::ConversionSpecifier::sArg: 480 case analyze_format_string::ConversionSpecifier::SArg: 481 Size += FieldWidth; 482 break; 483 484 // Just a pointer in the form '0xddd'. 485 case analyze_format_string::ConversionSpecifier::pArg: 486 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 487 break; 488 489 // A plain percent. 490 case analyze_format_string::ConversionSpecifier::PercentArg: 491 Size += 1; 492 break; 493 494 default: 495 break; 496 } 497 498 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 499 500 if (FS.hasAlternativeForm()) { 501 switch (FS.getConversionSpecifier().getKind()) { 502 default: 503 break; 504 // Force a leading '0'. 505 case analyze_format_string::ConversionSpecifier::oArg: 506 Size += 1; 507 break; 508 // Force a leading '0x'. 509 case analyze_format_string::ConversionSpecifier::xArg: 510 case analyze_format_string::ConversionSpecifier::XArg: 511 Size += 2; 512 break; 513 // Force a period '.' before decimal, even if precision is 0. 514 case analyze_format_string::ConversionSpecifier::aArg: 515 case analyze_format_string::ConversionSpecifier::AArg: 516 case analyze_format_string::ConversionSpecifier::eArg: 517 case analyze_format_string::ConversionSpecifier::EArg: 518 case analyze_format_string::ConversionSpecifier::fArg: 519 case analyze_format_string::ConversionSpecifier::FArg: 520 case analyze_format_string::ConversionSpecifier::gArg: 521 case analyze_format_string::ConversionSpecifier::GArg: 522 Size += (Precision ? 0 : 1); 523 break; 524 } 525 } 526 assert(SpecifierLen <= Size && "no underflow"); 527 Size -= SpecifierLen; 528 return true; 529 } 530 531 size_t getSizeLowerBound() const { return Size; } 532 533 private: 534 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 535 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 536 size_t FieldWidth = 0; 537 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 538 FieldWidth = FW.getConstantAmount(); 539 return FieldWidth; 540 } 541 542 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 543 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 544 size_t Precision = 0; 545 546 // See man 3 printf for default precision value based on the specifier. 547 switch (FW.getHowSpecified()) { 548 case analyze_format_string::OptionalAmount::NotSpecified: 549 switch (FS.getConversionSpecifier().getKind()) { 550 default: 551 break; 552 case analyze_format_string::ConversionSpecifier::dArg: // %d 553 case analyze_format_string::ConversionSpecifier::DArg: // %D 554 case analyze_format_string::ConversionSpecifier::iArg: // %i 555 Precision = 1; 556 break; 557 case analyze_format_string::ConversionSpecifier::oArg: // %d 558 case analyze_format_string::ConversionSpecifier::OArg: // %D 559 case analyze_format_string::ConversionSpecifier::uArg: // %d 560 case analyze_format_string::ConversionSpecifier::UArg: // %D 561 case analyze_format_string::ConversionSpecifier::xArg: // %d 562 case analyze_format_string::ConversionSpecifier::XArg: // %D 563 Precision = 1; 564 break; 565 case analyze_format_string::ConversionSpecifier::fArg: // %f 566 case analyze_format_string::ConversionSpecifier::FArg: // %F 567 case analyze_format_string::ConversionSpecifier::eArg: // %e 568 case analyze_format_string::ConversionSpecifier::EArg: // %E 569 case analyze_format_string::ConversionSpecifier::gArg: // %g 570 case analyze_format_string::ConversionSpecifier::GArg: // %G 571 Precision = 6; 572 break; 573 case analyze_format_string::ConversionSpecifier::pArg: // %d 574 Precision = 1; 575 break; 576 } 577 break; 578 case analyze_format_string::OptionalAmount::Constant: 579 Precision = FW.getConstantAmount(); 580 break; 581 default: 582 break; 583 } 584 return Precision; 585 } 586 }; 587 588 } // namespace 589 590 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 591 /// __builtin_*_chk function, then use the object size argument specified in the 592 /// source. Otherwise, infer the object size using __builtin_object_size. 593 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 594 CallExpr *TheCall) { 595 // FIXME: There are some more useful checks we could be doing here: 596 // - Evaluate strlen of strcpy arguments, use as object size. 597 598 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 599 isConstantEvaluated()) 600 return; 601 602 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 603 if (!BuiltinID) 604 return; 605 606 const TargetInfo &TI = getASTContext().getTargetInfo(); 607 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 608 609 unsigned DiagID = 0; 610 bool IsChkVariant = false; 611 Optional<llvm::APSInt> UsedSize; 612 unsigned SizeIndex, ObjectIndex; 613 switch (BuiltinID) { 614 default: 615 return; 616 case Builtin::BIsprintf: 617 case Builtin::BI__builtin___sprintf_chk: { 618 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 619 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 620 621 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 622 623 if (!Format->isAscii() && !Format->isUTF8()) 624 return; 625 626 StringRef FormatStrRef = Format->getString(); 627 EstimateSizeFormatHandler H(FormatStrRef); 628 const char *FormatBytes = FormatStrRef.data(); 629 const ConstantArrayType *T = 630 Context.getAsConstantArrayType(Format->getType()); 631 assert(T && "String literal not of constant array type!"); 632 size_t TypeSize = T->getSize().getZExtValue(); 633 634 // In case there's a null byte somewhere. 635 size_t StrLen = 636 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 637 if (!analyze_format_string::ParsePrintfString( 638 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 639 Context.getTargetInfo(), false)) { 640 DiagID = diag::warn_fortify_source_format_overflow; 641 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 642 .extOrTrunc(SizeTypeWidth); 643 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 644 IsChkVariant = true; 645 ObjectIndex = 2; 646 } else { 647 IsChkVariant = false; 648 ObjectIndex = 0; 649 } 650 break; 651 } 652 } 653 return; 654 } 655 case Builtin::BI__builtin___memcpy_chk: 656 case Builtin::BI__builtin___memmove_chk: 657 case Builtin::BI__builtin___memset_chk: 658 case Builtin::BI__builtin___strlcat_chk: 659 case Builtin::BI__builtin___strlcpy_chk: 660 case Builtin::BI__builtin___strncat_chk: 661 case Builtin::BI__builtin___strncpy_chk: 662 case Builtin::BI__builtin___stpncpy_chk: 663 case Builtin::BI__builtin___memccpy_chk: 664 case Builtin::BI__builtin___mempcpy_chk: { 665 DiagID = diag::warn_builtin_chk_overflow; 666 IsChkVariant = true; 667 SizeIndex = TheCall->getNumArgs() - 2; 668 ObjectIndex = TheCall->getNumArgs() - 1; 669 break; 670 } 671 672 case Builtin::BI__builtin___snprintf_chk: 673 case Builtin::BI__builtin___vsnprintf_chk: { 674 DiagID = diag::warn_builtin_chk_overflow; 675 IsChkVariant = true; 676 SizeIndex = 1; 677 ObjectIndex = 3; 678 break; 679 } 680 681 case Builtin::BIstrncat: 682 case Builtin::BI__builtin_strncat: 683 case Builtin::BIstrncpy: 684 case Builtin::BI__builtin_strncpy: 685 case Builtin::BIstpncpy: 686 case Builtin::BI__builtin_stpncpy: { 687 // Whether these functions overflow depends on the runtime strlen of the 688 // string, not just the buffer size, so emitting the "always overflow" 689 // diagnostic isn't quite right. We should still diagnose passing a buffer 690 // size larger than the destination buffer though; this is a runtime abort 691 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 692 DiagID = diag::warn_fortify_source_size_mismatch; 693 SizeIndex = TheCall->getNumArgs() - 1; 694 ObjectIndex = 0; 695 break; 696 } 697 698 case Builtin::BImemcpy: 699 case Builtin::BI__builtin_memcpy: 700 case Builtin::BImemmove: 701 case Builtin::BI__builtin_memmove: 702 case Builtin::BImemset: 703 case Builtin::BI__builtin_memset: 704 case Builtin::BImempcpy: 705 case Builtin::BI__builtin_mempcpy: { 706 DiagID = diag::warn_fortify_source_overflow; 707 SizeIndex = TheCall->getNumArgs() - 1; 708 ObjectIndex = 0; 709 break; 710 } 711 case Builtin::BIsnprintf: 712 case Builtin::BI__builtin_snprintf: 713 case Builtin::BIvsnprintf: 714 case Builtin::BI__builtin_vsnprintf: { 715 DiagID = diag::warn_fortify_source_size_mismatch; 716 SizeIndex = 1; 717 ObjectIndex = 0; 718 break; 719 } 720 } 721 722 llvm::APSInt ObjectSize; 723 // For __builtin___*_chk, the object size is explicitly provided by the caller 724 // (usually using __builtin_object_size). Use that value to check this call. 725 if (IsChkVariant) { 726 Expr::EvalResult Result; 727 Expr *SizeArg = TheCall->getArg(ObjectIndex); 728 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 729 return; 730 ObjectSize = Result.Val.getInt(); 731 732 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 733 } else { 734 // If the parameter has a pass_object_size attribute, then we should use its 735 // (potentially) more strict checking mode. Otherwise, conservatively assume 736 // type 0. 737 int BOSType = 0; 738 if (const auto *POS = 739 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 740 BOSType = POS->getType(); 741 742 Expr *ObjArg = TheCall->getArg(ObjectIndex); 743 uint64_t Result; 744 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 745 return; 746 // Get the object size in the target's size_t width. 747 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 748 } 749 750 // Evaluate the number of bytes of the object that this call will use. 751 if (!UsedSize) { 752 Expr::EvalResult Result; 753 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 754 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 755 return; 756 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 757 } 758 759 if (UsedSize.getValue().ule(ObjectSize)) 760 return; 761 762 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 763 // Skim off the details of whichever builtin was called to produce a better 764 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 765 if (IsChkVariant) { 766 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 767 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 768 } else if (FunctionName.startswith("__builtin_")) { 769 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 770 } 771 772 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 773 PDiag(DiagID) 774 << FunctionName << ObjectSize.toString(/*Radix=*/10) 775 << UsedSize.getValue().toString(/*Radix=*/10)); 776 } 777 778 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 779 Scope::ScopeFlags NeededScopeFlags, 780 unsigned DiagID) { 781 // Scopes aren't available during instantiation. Fortunately, builtin 782 // functions cannot be template args so they cannot be formed through template 783 // instantiation. Therefore checking once during the parse is sufficient. 784 if (SemaRef.inTemplateInstantiation()) 785 return false; 786 787 Scope *S = SemaRef.getCurScope(); 788 while (S && !S->isSEHExceptScope()) 789 S = S->getParent(); 790 if (!S || !(S->getFlags() & NeededScopeFlags)) { 791 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 792 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 793 << DRE->getDecl()->getIdentifier(); 794 return true; 795 } 796 797 return false; 798 } 799 800 static inline bool isBlockPointer(Expr *Arg) { 801 return Arg->getType()->isBlockPointerType(); 802 } 803 804 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 805 /// void*, which is a requirement of device side enqueue. 806 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 807 const BlockPointerType *BPT = 808 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 809 ArrayRef<QualType> Params = 810 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 811 unsigned ArgCounter = 0; 812 bool IllegalParams = false; 813 // Iterate through the block parameters until either one is found that is not 814 // a local void*, or the block is valid. 815 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 816 I != E; ++I, ++ArgCounter) { 817 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 818 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 819 LangAS::opencl_local) { 820 // Get the location of the error. If a block literal has been passed 821 // (BlockExpr) then we can point straight to the offending argument, 822 // else we just point to the variable reference. 823 SourceLocation ErrorLoc; 824 if (isa<BlockExpr>(BlockArg)) { 825 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 826 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 827 } else if (isa<DeclRefExpr>(BlockArg)) { 828 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 829 } 830 S.Diag(ErrorLoc, 831 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 832 IllegalParams = true; 833 } 834 } 835 836 return IllegalParams; 837 } 838 839 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 840 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 841 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 842 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 843 return true; 844 } 845 return false; 846 } 847 848 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 849 if (checkArgCount(S, TheCall, 2)) 850 return true; 851 852 if (checkOpenCLSubgroupExt(S, TheCall)) 853 return true; 854 855 // First argument is an ndrange_t type. 856 Expr *NDRangeArg = TheCall->getArg(0); 857 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 858 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 859 << TheCall->getDirectCallee() << "'ndrange_t'"; 860 return true; 861 } 862 863 Expr *BlockArg = TheCall->getArg(1); 864 if (!isBlockPointer(BlockArg)) { 865 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 866 << TheCall->getDirectCallee() << "block"; 867 return true; 868 } 869 return checkOpenCLBlockArgs(S, BlockArg); 870 } 871 872 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 873 /// get_kernel_work_group_size 874 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 875 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 876 if (checkArgCount(S, TheCall, 1)) 877 return true; 878 879 Expr *BlockArg = TheCall->getArg(0); 880 if (!isBlockPointer(BlockArg)) { 881 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 882 << TheCall->getDirectCallee() << "block"; 883 return true; 884 } 885 return checkOpenCLBlockArgs(S, BlockArg); 886 } 887 888 /// Diagnose integer type and any valid implicit conversion to it. 889 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 890 const QualType &IntType); 891 892 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 893 unsigned Start, unsigned End) { 894 bool IllegalParams = false; 895 for (unsigned I = Start; I <= End; ++I) 896 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 897 S.Context.getSizeType()); 898 return IllegalParams; 899 } 900 901 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 902 /// 'local void*' parameter of passed block. 903 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 904 Expr *BlockArg, 905 unsigned NumNonVarArgs) { 906 const BlockPointerType *BPT = 907 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 908 unsigned NumBlockParams = 909 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 910 unsigned TotalNumArgs = TheCall->getNumArgs(); 911 912 // For each argument passed to the block, a corresponding uint needs to 913 // be passed to describe the size of the local memory. 914 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 915 S.Diag(TheCall->getBeginLoc(), 916 diag::err_opencl_enqueue_kernel_local_size_args); 917 return true; 918 } 919 920 // Check that the sizes of the local memory are specified by integers. 921 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 922 TotalNumArgs - 1); 923 } 924 925 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 926 /// overload formats specified in Table 6.13.17.1. 927 /// int enqueue_kernel(queue_t queue, 928 /// kernel_enqueue_flags_t flags, 929 /// const ndrange_t ndrange, 930 /// void (^block)(void)) 931 /// int enqueue_kernel(queue_t queue, 932 /// kernel_enqueue_flags_t flags, 933 /// const ndrange_t ndrange, 934 /// uint num_events_in_wait_list, 935 /// clk_event_t *event_wait_list, 936 /// clk_event_t *event_ret, 937 /// void (^block)(void)) 938 /// int enqueue_kernel(queue_t queue, 939 /// kernel_enqueue_flags_t flags, 940 /// const ndrange_t ndrange, 941 /// void (^block)(local void*, ...), 942 /// uint size0, ...) 943 /// int enqueue_kernel(queue_t queue, 944 /// kernel_enqueue_flags_t flags, 945 /// const ndrange_t ndrange, 946 /// uint num_events_in_wait_list, 947 /// clk_event_t *event_wait_list, 948 /// clk_event_t *event_ret, 949 /// void (^block)(local void*, ...), 950 /// uint size0, ...) 951 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 952 unsigned NumArgs = TheCall->getNumArgs(); 953 954 if (NumArgs < 4) { 955 S.Diag(TheCall->getBeginLoc(), 956 diag::err_typecheck_call_too_few_args_at_least) 957 << 0 << 4 << NumArgs; 958 return true; 959 } 960 961 Expr *Arg0 = TheCall->getArg(0); 962 Expr *Arg1 = TheCall->getArg(1); 963 Expr *Arg2 = TheCall->getArg(2); 964 Expr *Arg3 = TheCall->getArg(3); 965 966 // First argument always needs to be a queue_t type. 967 if (!Arg0->getType()->isQueueT()) { 968 S.Diag(TheCall->getArg(0)->getBeginLoc(), 969 diag::err_opencl_builtin_expected_type) 970 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 971 return true; 972 } 973 974 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 975 if (!Arg1->getType()->isIntegerType()) { 976 S.Diag(TheCall->getArg(1)->getBeginLoc(), 977 diag::err_opencl_builtin_expected_type) 978 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 979 return true; 980 } 981 982 // Third argument is always an ndrange_t type. 983 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 984 S.Diag(TheCall->getArg(2)->getBeginLoc(), 985 diag::err_opencl_builtin_expected_type) 986 << TheCall->getDirectCallee() << "'ndrange_t'"; 987 return true; 988 } 989 990 // With four arguments, there is only one form that the function could be 991 // called in: no events and no variable arguments. 992 if (NumArgs == 4) { 993 // check that the last argument is the right block type. 994 if (!isBlockPointer(Arg3)) { 995 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 996 << TheCall->getDirectCallee() << "block"; 997 return true; 998 } 999 // we have a block type, check the prototype 1000 const BlockPointerType *BPT = 1001 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1002 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1003 S.Diag(Arg3->getBeginLoc(), 1004 diag::err_opencl_enqueue_kernel_blocks_no_args); 1005 return true; 1006 } 1007 return false; 1008 } 1009 // we can have block + varargs. 1010 if (isBlockPointer(Arg3)) 1011 return (checkOpenCLBlockArgs(S, Arg3) || 1012 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1013 // last two cases with either exactly 7 args or 7 args and varargs. 1014 if (NumArgs >= 7) { 1015 // check common block argument. 1016 Expr *Arg6 = TheCall->getArg(6); 1017 if (!isBlockPointer(Arg6)) { 1018 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1019 << TheCall->getDirectCallee() << "block"; 1020 return true; 1021 } 1022 if (checkOpenCLBlockArgs(S, Arg6)) 1023 return true; 1024 1025 // Forth argument has to be any integer type. 1026 if (!Arg3->getType()->isIntegerType()) { 1027 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1028 diag::err_opencl_builtin_expected_type) 1029 << TheCall->getDirectCallee() << "integer"; 1030 return true; 1031 } 1032 // check remaining common arguments. 1033 Expr *Arg4 = TheCall->getArg(4); 1034 Expr *Arg5 = TheCall->getArg(5); 1035 1036 // Fifth argument is always passed as a pointer to clk_event_t. 1037 if (!Arg4->isNullPointerConstant(S.Context, 1038 Expr::NPC_ValueDependentIsNotNull) && 1039 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1040 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1041 diag::err_opencl_builtin_expected_type) 1042 << TheCall->getDirectCallee() 1043 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1044 return true; 1045 } 1046 1047 // Sixth argument is always passed as a pointer to clk_event_t. 1048 if (!Arg5->isNullPointerConstant(S.Context, 1049 Expr::NPC_ValueDependentIsNotNull) && 1050 !(Arg5->getType()->isPointerType() && 1051 Arg5->getType()->getPointeeType()->isClkEventT())) { 1052 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1053 diag::err_opencl_builtin_expected_type) 1054 << TheCall->getDirectCallee() 1055 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1056 return true; 1057 } 1058 1059 if (NumArgs == 7) 1060 return false; 1061 1062 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1063 } 1064 1065 // None of the specific case has been detected, give generic error 1066 S.Diag(TheCall->getBeginLoc(), 1067 diag::err_opencl_enqueue_kernel_incorrect_args); 1068 return true; 1069 } 1070 1071 /// Returns OpenCL access qual. 1072 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1073 return D->getAttr<OpenCLAccessAttr>(); 1074 } 1075 1076 /// Returns true if pipe element type is different from the pointer. 1077 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1078 const Expr *Arg0 = Call->getArg(0); 1079 // First argument type should always be pipe. 1080 if (!Arg0->getType()->isPipeType()) { 1081 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1082 << Call->getDirectCallee() << Arg0->getSourceRange(); 1083 return true; 1084 } 1085 OpenCLAccessAttr *AccessQual = 1086 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1087 // Validates the access qualifier is compatible with the call. 1088 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1089 // read_only and write_only, and assumed to be read_only if no qualifier is 1090 // specified. 1091 switch (Call->getDirectCallee()->getBuiltinID()) { 1092 case Builtin::BIread_pipe: 1093 case Builtin::BIreserve_read_pipe: 1094 case Builtin::BIcommit_read_pipe: 1095 case Builtin::BIwork_group_reserve_read_pipe: 1096 case Builtin::BIsub_group_reserve_read_pipe: 1097 case Builtin::BIwork_group_commit_read_pipe: 1098 case Builtin::BIsub_group_commit_read_pipe: 1099 if (!(!AccessQual || AccessQual->isReadOnly())) { 1100 S.Diag(Arg0->getBeginLoc(), 1101 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1102 << "read_only" << Arg0->getSourceRange(); 1103 return true; 1104 } 1105 break; 1106 case Builtin::BIwrite_pipe: 1107 case Builtin::BIreserve_write_pipe: 1108 case Builtin::BIcommit_write_pipe: 1109 case Builtin::BIwork_group_reserve_write_pipe: 1110 case Builtin::BIsub_group_reserve_write_pipe: 1111 case Builtin::BIwork_group_commit_write_pipe: 1112 case Builtin::BIsub_group_commit_write_pipe: 1113 if (!(AccessQual && AccessQual->isWriteOnly())) { 1114 S.Diag(Arg0->getBeginLoc(), 1115 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1116 << "write_only" << Arg0->getSourceRange(); 1117 return true; 1118 } 1119 break; 1120 default: 1121 break; 1122 } 1123 return false; 1124 } 1125 1126 /// Returns true if pipe element type is different from the pointer. 1127 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1128 const Expr *Arg0 = Call->getArg(0); 1129 const Expr *ArgIdx = Call->getArg(Idx); 1130 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1131 const QualType EltTy = PipeTy->getElementType(); 1132 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1133 // The Idx argument should be a pointer and the type of the pointer and 1134 // the type of pipe element should also be the same. 1135 if (!ArgTy || 1136 !S.Context.hasSameType( 1137 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1138 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1139 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1140 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1141 return true; 1142 } 1143 return false; 1144 } 1145 1146 // Performs semantic analysis for the read/write_pipe call. 1147 // \param S Reference to the semantic analyzer. 1148 // \param Call A pointer to the builtin call. 1149 // \return True if a semantic error has been found, false otherwise. 1150 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1151 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1152 // functions have two forms. 1153 switch (Call->getNumArgs()) { 1154 case 2: 1155 if (checkOpenCLPipeArg(S, Call)) 1156 return true; 1157 // The call with 2 arguments should be 1158 // read/write_pipe(pipe T, T*). 1159 // Check packet type T. 1160 if (checkOpenCLPipePacketType(S, Call, 1)) 1161 return true; 1162 break; 1163 1164 case 4: { 1165 if (checkOpenCLPipeArg(S, Call)) 1166 return true; 1167 // The call with 4 arguments should be 1168 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1169 // Check reserve_id_t. 1170 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1171 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1172 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1173 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1174 return true; 1175 } 1176 1177 // Check the index. 1178 const Expr *Arg2 = Call->getArg(2); 1179 if (!Arg2->getType()->isIntegerType() && 1180 !Arg2->getType()->isUnsignedIntegerType()) { 1181 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1182 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1183 << Arg2->getType() << Arg2->getSourceRange(); 1184 return true; 1185 } 1186 1187 // Check packet type T. 1188 if (checkOpenCLPipePacketType(S, Call, 3)) 1189 return true; 1190 } break; 1191 default: 1192 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1193 << Call->getDirectCallee() << Call->getSourceRange(); 1194 return true; 1195 } 1196 1197 return false; 1198 } 1199 1200 // Performs a semantic analysis on the {work_group_/sub_group_ 1201 // /_}reserve_{read/write}_pipe 1202 // \param S Reference to the semantic analyzer. 1203 // \param Call The call to the builtin function to be analyzed. 1204 // \return True if a semantic error was found, false otherwise. 1205 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1206 if (checkArgCount(S, Call, 2)) 1207 return true; 1208 1209 if (checkOpenCLPipeArg(S, Call)) 1210 return true; 1211 1212 // Check the reserve size. 1213 if (!Call->getArg(1)->getType()->isIntegerType() && 1214 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1215 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1216 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1217 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1218 return true; 1219 } 1220 1221 // Since return type of reserve_read/write_pipe built-in function is 1222 // reserve_id_t, which is not defined in the builtin def file , we used int 1223 // as return type and need to override the return type of these functions. 1224 Call->setType(S.Context.OCLReserveIDTy); 1225 1226 return false; 1227 } 1228 1229 // Performs a semantic analysis on {work_group_/sub_group_ 1230 // /_}commit_{read/write}_pipe 1231 // \param S Reference to the semantic analyzer. 1232 // \param Call The call to the builtin function to be analyzed. 1233 // \return True if a semantic error was found, false otherwise. 1234 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1235 if (checkArgCount(S, Call, 2)) 1236 return true; 1237 1238 if (checkOpenCLPipeArg(S, Call)) 1239 return true; 1240 1241 // Check reserve_id_t. 1242 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1243 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1244 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1245 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1246 return true; 1247 } 1248 1249 return false; 1250 } 1251 1252 // Performs a semantic analysis on the call to built-in Pipe 1253 // Query Functions. 1254 // \param S Reference to the semantic analyzer. 1255 // \param Call The call to the builtin function to be analyzed. 1256 // \return True if a semantic error was found, false otherwise. 1257 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1258 if (checkArgCount(S, Call, 1)) 1259 return true; 1260 1261 if (!Call->getArg(0)->getType()->isPipeType()) { 1262 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1263 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1264 return true; 1265 } 1266 1267 return false; 1268 } 1269 1270 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1271 // Performs semantic analysis for the to_global/local/private call. 1272 // \param S Reference to the semantic analyzer. 1273 // \param BuiltinID ID of the builtin function. 1274 // \param Call A pointer to the builtin call. 1275 // \return True if a semantic error has been found, false otherwise. 1276 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1277 CallExpr *Call) { 1278 if (checkArgCount(S, Call, 1)) 1279 return true; 1280 1281 auto RT = Call->getArg(0)->getType(); 1282 if (!RT->isPointerType() || RT->getPointeeType() 1283 .getAddressSpace() == LangAS::opencl_constant) { 1284 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1285 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1286 return true; 1287 } 1288 1289 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1290 S.Diag(Call->getArg(0)->getBeginLoc(), 1291 diag::warn_opencl_generic_address_space_arg) 1292 << Call->getDirectCallee()->getNameInfo().getAsString() 1293 << Call->getArg(0)->getSourceRange(); 1294 } 1295 1296 RT = RT->getPointeeType(); 1297 auto Qual = RT.getQualifiers(); 1298 switch (BuiltinID) { 1299 case Builtin::BIto_global: 1300 Qual.setAddressSpace(LangAS::opencl_global); 1301 break; 1302 case Builtin::BIto_local: 1303 Qual.setAddressSpace(LangAS::opencl_local); 1304 break; 1305 case Builtin::BIto_private: 1306 Qual.setAddressSpace(LangAS::opencl_private); 1307 break; 1308 default: 1309 llvm_unreachable("Invalid builtin function"); 1310 } 1311 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1312 RT.getUnqualifiedType(), Qual))); 1313 1314 return false; 1315 } 1316 1317 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1318 if (checkArgCount(S, TheCall, 1)) 1319 return ExprError(); 1320 1321 // Compute __builtin_launder's parameter type from the argument. 1322 // The parameter type is: 1323 // * The type of the argument if it's not an array or function type, 1324 // Otherwise, 1325 // * The decayed argument type. 1326 QualType ParamTy = [&]() { 1327 QualType ArgTy = TheCall->getArg(0)->getType(); 1328 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1329 return S.Context.getPointerType(Ty->getElementType()); 1330 if (ArgTy->isFunctionType()) { 1331 return S.Context.getPointerType(ArgTy); 1332 } 1333 return ArgTy; 1334 }(); 1335 1336 TheCall->setType(ParamTy); 1337 1338 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1339 if (!ParamTy->isPointerType()) 1340 return 0; 1341 if (ParamTy->isFunctionPointerType()) 1342 return 1; 1343 if (ParamTy->isVoidPointerType()) 1344 return 2; 1345 return llvm::Optional<unsigned>{}; 1346 }(); 1347 if (DiagSelect.hasValue()) { 1348 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1349 << DiagSelect.getValue() << TheCall->getSourceRange(); 1350 return ExprError(); 1351 } 1352 1353 // We either have an incomplete class type, or we have a class template 1354 // whose instantiation has not been forced. Example: 1355 // 1356 // template <class T> struct Foo { T value; }; 1357 // Foo<int> *p = nullptr; 1358 // auto *d = __builtin_launder(p); 1359 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1360 diag::err_incomplete_type)) 1361 return ExprError(); 1362 1363 assert(ParamTy->getPointeeType()->isObjectType() && 1364 "Unhandled non-object pointer case"); 1365 1366 InitializedEntity Entity = 1367 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1368 ExprResult Arg = 1369 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1370 if (Arg.isInvalid()) 1371 return ExprError(); 1372 TheCall->setArg(0, Arg.get()); 1373 1374 return TheCall; 1375 } 1376 1377 // Emit an error and return true if the current architecture is not in the list 1378 // of supported architectures. 1379 static bool 1380 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1381 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1382 llvm::Triple::ArchType CurArch = 1383 S.getASTContext().getTargetInfo().getTriple().getArch(); 1384 if (llvm::is_contained(SupportedArchs, CurArch)) 1385 return false; 1386 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1387 << TheCall->getSourceRange(); 1388 return true; 1389 } 1390 1391 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1392 SourceLocation CallSiteLoc); 1393 1394 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1395 CallExpr *TheCall) { 1396 switch (TI.getTriple().getArch()) { 1397 default: 1398 // Some builtins don't require additional checking, so just consider these 1399 // acceptable. 1400 return false; 1401 case llvm::Triple::arm: 1402 case llvm::Triple::armeb: 1403 case llvm::Triple::thumb: 1404 case llvm::Triple::thumbeb: 1405 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1406 case llvm::Triple::aarch64: 1407 case llvm::Triple::aarch64_32: 1408 case llvm::Triple::aarch64_be: 1409 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1410 case llvm::Triple::bpfeb: 1411 case llvm::Triple::bpfel: 1412 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1413 case llvm::Triple::hexagon: 1414 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1415 case llvm::Triple::mips: 1416 case llvm::Triple::mipsel: 1417 case llvm::Triple::mips64: 1418 case llvm::Triple::mips64el: 1419 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1420 case llvm::Triple::systemz: 1421 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1422 case llvm::Triple::x86: 1423 case llvm::Triple::x86_64: 1424 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1425 case llvm::Triple::ppc: 1426 case llvm::Triple::ppcle: 1427 case llvm::Triple::ppc64: 1428 case llvm::Triple::ppc64le: 1429 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1430 case llvm::Triple::amdgcn: 1431 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1432 case llvm::Triple::riscv32: 1433 case llvm::Triple::riscv64: 1434 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1435 } 1436 } 1437 1438 ExprResult 1439 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1440 CallExpr *TheCall) { 1441 ExprResult TheCallResult(TheCall); 1442 1443 // Find out if any arguments are required to be integer constant expressions. 1444 unsigned ICEArguments = 0; 1445 ASTContext::GetBuiltinTypeError Error; 1446 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1447 if (Error != ASTContext::GE_None) 1448 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1449 1450 // If any arguments are required to be ICE's, check and diagnose. 1451 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1452 // Skip arguments not required to be ICE's. 1453 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1454 1455 llvm::APSInt Result; 1456 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1457 return true; 1458 ICEArguments &= ~(1 << ArgNo); 1459 } 1460 1461 switch (BuiltinID) { 1462 case Builtin::BI__builtin___CFStringMakeConstantString: 1463 assert(TheCall->getNumArgs() == 1 && 1464 "Wrong # arguments to builtin CFStringMakeConstantString"); 1465 if (CheckObjCString(TheCall->getArg(0))) 1466 return ExprError(); 1467 break; 1468 case Builtin::BI__builtin_ms_va_start: 1469 case Builtin::BI__builtin_stdarg_start: 1470 case Builtin::BI__builtin_va_start: 1471 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1472 return ExprError(); 1473 break; 1474 case Builtin::BI__va_start: { 1475 switch (Context.getTargetInfo().getTriple().getArch()) { 1476 case llvm::Triple::aarch64: 1477 case llvm::Triple::arm: 1478 case llvm::Triple::thumb: 1479 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1480 return ExprError(); 1481 break; 1482 default: 1483 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1484 return ExprError(); 1485 break; 1486 } 1487 break; 1488 } 1489 1490 // The acquire, release, and no fence variants are ARM and AArch64 only. 1491 case Builtin::BI_interlockedbittestandset_acq: 1492 case Builtin::BI_interlockedbittestandset_rel: 1493 case Builtin::BI_interlockedbittestandset_nf: 1494 case Builtin::BI_interlockedbittestandreset_acq: 1495 case Builtin::BI_interlockedbittestandreset_rel: 1496 case Builtin::BI_interlockedbittestandreset_nf: 1497 if (CheckBuiltinTargetSupport( 1498 *this, BuiltinID, TheCall, 1499 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1500 return ExprError(); 1501 break; 1502 1503 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1504 case Builtin::BI_bittest64: 1505 case Builtin::BI_bittestandcomplement64: 1506 case Builtin::BI_bittestandreset64: 1507 case Builtin::BI_bittestandset64: 1508 case Builtin::BI_interlockedbittestandreset64: 1509 case Builtin::BI_interlockedbittestandset64: 1510 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1511 {llvm::Triple::x86_64, llvm::Triple::arm, 1512 llvm::Triple::thumb, llvm::Triple::aarch64})) 1513 return ExprError(); 1514 break; 1515 1516 case Builtin::BI__builtin_isgreater: 1517 case Builtin::BI__builtin_isgreaterequal: 1518 case Builtin::BI__builtin_isless: 1519 case Builtin::BI__builtin_islessequal: 1520 case Builtin::BI__builtin_islessgreater: 1521 case Builtin::BI__builtin_isunordered: 1522 if (SemaBuiltinUnorderedCompare(TheCall)) 1523 return ExprError(); 1524 break; 1525 case Builtin::BI__builtin_fpclassify: 1526 if (SemaBuiltinFPClassification(TheCall, 6)) 1527 return ExprError(); 1528 break; 1529 case Builtin::BI__builtin_isfinite: 1530 case Builtin::BI__builtin_isinf: 1531 case Builtin::BI__builtin_isinf_sign: 1532 case Builtin::BI__builtin_isnan: 1533 case Builtin::BI__builtin_isnormal: 1534 case Builtin::BI__builtin_signbit: 1535 case Builtin::BI__builtin_signbitf: 1536 case Builtin::BI__builtin_signbitl: 1537 if (SemaBuiltinFPClassification(TheCall, 1)) 1538 return ExprError(); 1539 break; 1540 case Builtin::BI__builtin_shufflevector: 1541 return SemaBuiltinShuffleVector(TheCall); 1542 // TheCall will be freed by the smart pointer here, but that's fine, since 1543 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1544 case Builtin::BI__builtin_prefetch: 1545 if (SemaBuiltinPrefetch(TheCall)) 1546 return ExprError(); 1547 break; 1548 case Builtin::BI__builtin_alloca_with_align: 1549 if (SemaBuiltinAllocaWithAlign(TheCall)) 1550 return ExprError(); 1551 LLVM_FALLTHROUGH; 1552 case Builtin::BI__builtin_alloca: 1553 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1554 << TheCall->getDirectCallee(); 1555 break; 1556 case Builtin::BI__assume: 1557 case Builtin::BI__builtin_assume: 1558 if (SemaBuiltinAssume(TheCall)) 1559 return ExprError(); 1560 break; 1561 case Builtin::BI__builtin_assume_aligned: 1562 if (SemaBuiltinAssumeAligned(TheCall)) 1563 return ExprError(); 1564 break; 1565 case Builtin::BI__builtin_dynamic_object_size: 1566 case Builtin::BI__builtin_object_size: 1567 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1568 return ExprError(); 1569 break; 1570 case Builtin::BI__builtin_longjmp: 1571 if (SemaBuiltinLongjmp(TheCall)) 1572 return ExprError(); 1573 break; 1574 case Builtin::BI__builtin_setjmp: 1575 if (SemaBuiltinSetjmp(TheCall)) 1576 return ExprError(); 1577 break; 1578 case Builtin::BI__builtin_classify_type: 1579 if (checkArgCount(*this, TheCall, 1)) return true; 1580 TheCall->setType(Context.IntTy); 1581 break; 1582 case Builtin::BI__builtin_complex: 1583 if (SemaBuiltinComplex(TheCall)) 1584 return ExprError(); 1585 break; 1586 case Builtin::BI__builtin_constant_p: { 1587 if (checkArgCount(*this, TheCall, 1)) return true; 1588 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1589 if (Arg.isInvalid()) return true; 1590 TheCall->setArg(0, Arg.get()); 1591 TheCall->setType(Context.IntTy); 1592 break; 1593 } 1594 case Builtin::BI__builtin_launder: 1595 return SemaBuiltinLaunder(*this, TheCall); 1596 case Builtin::BI__sync_fetch_and_add: 1597 case Builtin::BI__sync_fetch_and_add_1: 1598 case Builtin::BI__sync_fetch_and_add_2: 1599 case Builtin::BI__sync_fetch_and_add_4: 1600 case Builtin::BI__sync_fetch_and_add_8: 1601 case Builtin::BI__sync_fetch_and_add_16: 1602 case Builtin::BI__sync_fetch_and_sub: 1603 case Builtin::BI__sync_fetch_and_sub_1: 1604 case Builtin::BI__sync_fetch_and_sub_2: 1605 case Builtin::BI__sync_fetch_and_sub_4: 1606 case Builtin::BI__sync_fetch_and_sub_8: 1607 case Builtin::BI__sync_fetch_and_sub_16: 1608 case Builtin::BI__sync_fetch_and_or: 1609 case Builtin::BI__sync_fetch_and_or_1: 1610 case Builtin::BI__sync_fetch_and_or_2: 1611 case Builtin::BI__sync_fetch_and_or_4: 1612 case Builtin::BI__sync_fetch_and_or_8: 1613 case Builtin::BI__sync_fetch_and_or_16: 1614 case Builtin::BI__sync_fetch_and_and: 1615 case Builtin::BI__sync_fetch_and_and_1: 1616 case Builtin::BI__sync_fetch_and_and_2: 1617 case Builtin::BI__sync_fetch_and_and_4: 1618 case Builtin::BI__sync_fetch_and_and_8: 1619 case Builtin::BI__sync_fetch_and_and_16: 1620 case Builtin::BI__sync_fetch_and_xor: 1621 case Builtin::BI__sync_fetch_and_xor_1: 1622 case Builtin::BI__sync_fetch_and_xor_2: 1623 case Builtin::BI__sync_fetch_and_xor_4: 1624 case Builtin::BI__sync_fetch_and_xor_8: 1625 case Builtin::BI__sync_fetch_and_xor_16: 1626 case Builtin::BI__sync_fetch_and_nand: 1627 case Builtin::BI__sync_fetch_and_nand_1: 1628 case Builtin::BI__sync_fetch_and_nand_2: 1629 case Builtin::BI__sync_fetch_and_nand_4: 1630 case Builtin::BI__sync_fetch_and_nand_8: 1631 case Builtin::BI__sync_fetch_and_nand_16: 1632 case Builtin::BI__sync_add_and_fetch: 1633 case Builtin::BI__sync_add_and_fetch_1: 1634 case Builtin::BI__sync_add_and_fetch_2: 1635 case Builtin::BI__sync_add_and_fetch_4: 1636 case Builtin::BI__sync_add_and_fetch_8: 1637 case Builtin::BI__sync_add_and_fetch_16: 1638 case Builtin::BI__sync_sub_and_fetch: 1639 case Builtin::BI__sync_sub_and_fetch_1: 1640 case Builtin::BI__sync_sub_and_fetch_2: 1641 case Builtin::BI__sync_sub_and_fetch_4: 1642 case Builtin::BI__sync_sub_and_fetch_8: 1643 case Builtin::BI__sync_sub_and_fetch_16: 1644 case Builtin::BI__sync_and_and_fetch: 1645 case Builtin::BI__sync_and_and_fetch_1: 1646 case Builtin::BI__sync_and_and_fetch_2: 1647 case Builtin::BI__sync_and_and_fetch_4: 1648 case Builtin::BI__sync_and_and_fetch_8: 1649 case Builtin::BI__sync_and_and_fetch_16: 1650 case Builtin::BI__sync_or_and_fetch: 1651 case Builtin::BI__sync_or_and_fetch_1: 1652 case Builtin::BI__sync_or_and_fetch_2: 1653 case Builtin::BI__sync_or_and_fetch_4: 1654 case Builtin::BI__sync_or_and_fetch_8: 1655 case Builtin::BI__sync_or_and_fetch_16: 1656 case Builtin::BI__sync_xor_and_fetch: 1657 case Builtin::BI__sync_xor_and_fetch_1: 1658 case Builtin::BI__sync_xor_and_fetch_2: 1659 case Builtin::BI__sync_xor_and_fetch_4: 1660 case Builtin::BI__sync_xor_and_fetch_8: 1661 case Builtin::BI__sync_xor_and_fetch_16: 1662 case Builtin::BI__sync_nand_and_fetch: 1663 case Builtin::BI__sync_nand_and_fetch_1: 1664 case Builtin::BI__sync_nand_and_fetch_2: 1665 case Builtin::BI__sync_nand_and_fetch_4: 1666 case Builtin::BI__sync_nand_and_fetch_8: 1667 case Builtin::BI__sync_nand_and_fetch_16: 1668 case Builtin::BI__sync_val_compare_and_swap: 1669 case Builtin::BI__sync_val_compare_and_swap_1: 1670 case Builtin::BI__sync_val_compare_and_swap_2: 1671 case Builtin::BI__sync_val_compare_and_swap_4: 1672 case Builtin::BI__sync_val_compare_and_swap_8: 1673 case Builtin::BI__sync_val_compare_and_swap_16: 1674 case Builtin::BI__sync_bool_compare_and_swap: 1675 case Builtin::BI__sync_bool_compare_and_swap_1: 1676 case Builtin::BI__sync_bool_compare_and_swap_2: 1677 case Builtin::BI__sync_bool_compare_and_swap_4: 1678 case Builtin::BI__sync_bool_compare_and_swap_8: 1679 case Builtin::BI__sync_bool_compare_and_swap_16: 1680 case Builtin::BI__sync_lock_test_and_set: 1681 case Builtin::BI__sync_lock_test_and_set_1: 1682 case Builtin::BI__sync_lock_test_and_set_2: 1683 case Builtin::BI__sync_lock_test_and_set_4: 1684 case Builtin::BI__sync_lock_test_and_set_8: 1685 case Builtin::BI__sync_lock_test_and_set_16: 1686 case Builtin::BI__sync_lock_release: 1687 case Builtin::BI__sync_lock_release_1: 1688 case Builtin::BI__sync_lock_release_2: 1689 case Builtin::BI__sync_lock_release_4: 1690 case Builtin::BI__sync_lock_release_8: 1691 case Builtin::BI__sync_lock_release_16: 1692 case Builtin::BI__sync_swap: 1693 case Builtin::BI__sync_swap_1: 1694 case Builtin::BI__sync_swap_2: 1695 case Builtin::BI__sync_swap_4: 1696 case Builtin::BI__sync_swap_8: 1697 case Builtin::BI__sync_swap_16: 1698 return SemaBuiltinAtomicOverloaded(TheCallResult); 1699 case Builtin::BI__sync_synchronize: 1700 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1701 << TheCall->getCallee()->getSourceRange(); 1702 break; 1703 case Builtin::BI__builtin_nontemporal_load: 1704 case Builtin::BI__builtin_nontemporal_store: 1705 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1706 case Builtin::BI__builtin_memcpy_inline: { 1707 clang::Expr *SizeOp = TheCall->getArg(2); 1708 // We warn about copying to or from `nullptr` pointers when `size` is 1709 // greater than 0. When `size` is value dependent we cannot evaluate its 1710 // value so we bail out. 1711 if (SizeOp->isValueDependent()) 1712 break; 1713 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1714 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1715 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1716 } 1717 break; 1718 } 1719 #define BUILTIN(ID, TYPE, ATTRS) 1720 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1721 case Builtin::BI##ID: \ 1722 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1723 #include "clang/Basic/Builtins.def" 1724 case Builtin::BI__annotation: 1725 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1726 return ExprError(); 1727 break; 1728 case Builtin::BI__builtin_annotation: 1729 if (SemaBuiltinAnnotation(*this, TheCall)) 1730 return ExprError(); 1731 break; 1732 case Builtin::BI__builtin_addressof: 1733 if (SemaBuiltinAddressof(*this, TheCall)) 1734 return ExprError(); 1735 break; 1736 case Builtin::BI__builtin_is_aligned: 1737 case Builtin::BI__builtin_align_up: 1738 case Builtin::BI__builtin_align_down: 1739 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1740 return ExprError(); 1741 break; 1742 case Builtin::BI__builtin_add_overflow: 1743 case Builtin::BI__builtin_sub_overflow: 1744 case Builtin::BI__builtin_mul_overflow: 1745 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1746 return ExprError(); 1747 break; 1748 case Builtin::BI__builtin_operator_new: 1749 case Builtin::BI__builtin_operator_delete: { 1750 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1751 ExprResult Res = 1752 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1753 if (Res.isInvalid()) 1754 CorrectDelayedTyposInExpr(TheCallResult.get()); 1755 return Res; 1756 } 1757 case Builtin::BI__builtin_dump_struct: { 1758 // We first want to ensure we are called with 2 arguments 1759 if (checkArgCount(*this, TheCall, 2)) 1760 return ExprError(); 1761 // Ensure that the first argument is of type 'struct XX *' 1762 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1763 const QualType PtrArgType = PtrArg->getType(); 1764 if (!PtrArgType->isPointerType() || 1765 !PtrArgType->getPointeeType()->isRecordType()) { 1766 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1767 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1768 << "structure pointer"; 1769 return ExprError(); 1770 } 1771 1772 // Ensure that the second argument is of type 'FunctionType' 1773 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1774 const QualType FnPtrArgType = FnPtrArg->getType(); 1775 if (!FnPtrArgType->isPointerType()) { 1776 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1777 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1778 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1779 return ExprError(); 1780 } 1781 1782 const auto *FuncType = 1783 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1784 1785 if (!FuncType) { 1786 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1787 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1788 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1789 return ExprError(); 1790 } 1791 1792 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1793 if (!FT->getNumParams()) { 1794 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1795 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1796 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1797 return ExprError(); 1798 } 1799 QualType PT = FT->getParamType(0); 1800 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1801 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1802 !PT->getPointeeType().isConstQualified()) { 1803 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1804 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1805 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1806 return ExprError(); 1807 } 1808 } 1809 1810 TheCall->setType(Context.IntTy); 1811 break; 1812 } 1813 case Builtin::BI__builtin_expect_with_probability: { 1814 // We first want to ensure we are called with 3 arguments 1815 if (checkArgCount(*this, TheCall, 3)) 1816 return ExprError(); 1817 // then check probability is constant float in range [0.0, 1.0] 1818 const Expr *ProbArg = TheCall->getArg(2); 1819 SmallVector<PartialDiagnosticAt, 8> Notes; 1820 Expr::EvalResult Eval; 1821 Eval.Diag = &Notes; 1822 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1823 !Eval.Val.isFloat()) { 1824 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1825 << ProbArg->getSourceRange(); 1826 for (const PartialDiagnosticAt &PDiag : Notes) 1827 Diag(PDiag.first, PDiag.second); 1828 return ExprError(); 1829 } 1830 llvm::APFloat Probability = Eval.Val.getFloat(); 1831 bool LoseInfo = false; 1832 Probability.convert(llvm::APFloat::IEEEdouble(), 1833 llvm::RoundingMode::Dynamic, &LoseInfo); 1834 if (!(Probability >= llvm::APFloat(0.0) && 1835 Probability <= llvm::APFloat(1.0))) { 1836 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1837 << ProbArg->getSourceRange(); 1838 return ExprError(); 1839 } 1840 break; 1841 } 1842 case Builtin::BI__builtin_preserve_access_index: 1843 if (SemaBuiltinPreserveAI(*this, TheCall)) 1844 return ExprError(); 1845 break; 1846 case Builtin::BI__builtin_call_with_static_chain: 1847 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1848 return ExprError(); 1849 break; 1850 case Builtin::BI__exception_code: 1851 case Builtin::BI_exception_code: 1852 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1853 diag::err_seh___except_block)) 1854 return ExprError(); 1855 break; 1856 case Builtin::BI__exception_info: 1857 case Builtin::BI_exception_info: 1858 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1859 diag::err_seh___except_filter)) 1860 return ExprError(); 1861 break; 1862 case Builtin::BI__GetExceptionInfo: 1863 if (checkArgCount(*this, TheCall, 1)) 1864 return ExprError(); 1865 1866 if (CheckCXXThrowOperand( 1867 TheCall->getBeginLoc(), 1868 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1869 TheCall)) 1870 return ExprError(); 1871 1872 TheCall->setType(Context.VoidPtrTy); 1873 break; 1874 // OpenCL v2.0, s6.13.16 - Pipe functions 1875 case Builtin::BIread_pipe: 1876 case Builtin::BIwrite_pipe: 1877 // Since those two functions are declared with var args, we need a semantic 1878 // check for the argument. 1879 if (SemaBuiltinRWPipe(*this, TheCall)) 1880 return ExprError(); 1881 break; 1882 case Builtin::BIreserve_read_pipe: 1883 case Builtin::BIreserve_write_pipe: 1884 case Builtin::BIwork_group_reserve_read_pipe: 1885 case Builtin::BIwork_group_reserve_write_pipe: 1886 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1887 return ExprError(); 1888 break; 1889 case Builtin::BIsub_group_reserve_read_pipe: 1890 case Builtin::BIsub_group_reserve_write_pipe: 1891 if (checkOpenCLSubgroupExt(*this, TheCall) || 1892 SemaBuiltinReserveRWPipe(*this, TheCall)) 1893 return ExprError(); 1894 break; 1895 case Builtin::BIcommit_read_pipe: 1896 case Builtin::BIcommit_write_pipe: 1897 case Builtin::BIwork_group_commit_read_pipe: 1898 case Builtin::BIwork_group_commit_write_pipe: 1899 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1900 return ExprError(); 1901 break; 1902 case Builtin::BIsub_group_commit_read_pipe: 1903 case Builtin::BIsub_group_commit_write_pipe: 1904 if (checkOpenCLSubgroupExt(*this, TheCall) || 1905 SemaBuiltinCommitRWPipe(*this, TheCall)) 1906 return ExprError(); 1907 break; 1908 case Builtin::BIget_pipe_num_packets: 1909 case Builtin::BIget_pipe_max_packets: 1910 if (SemaBuiltinPipePackets(*this, TheCall)) 1911 return ExprError(); 1912 break; 1913 case Builtin::BIto_global: 1914 case Builtin::BIto_local: 1915 case Builtin::BIto_private: 1916 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1917 return ExprError(); 1918 break; 1919 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1920 case Builtin::BIenqueue_kernel: 1921 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1922 return ExprError(); 1923 break; 1924 case Builtin::BIget_kernel_work_group_size: 1925 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1926 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1927 return ExprError(); 1928 break; 1929 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1930 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1931 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1932 return ExprError(); 1933 break; 1934 case Builtin::BI__builtin_os_log_format: 1935 Cleanup.setExprNeedsCleanups(true); 1936 LLVM_FALLTHROUGH; 1937 case Builtin::BI__builtin_os_log_format_buffer_size: 1938 if (SemaBuiltinOSLogFormat(TheCall)) 1939 return ExprError(); 1940 break; 1941 case Builtin::BI__builtin_frame_address: 1942 case Builtin::BI__builtin_return_address: { 1943 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1944 return ExprError(); 1945 1946 // -Wframe-address warning if non-zero passed to builtin 1947 // return/frame address. 1948 Expr::EvalResult Result; 1949 if (!TheCall->getArg(0)->isValueDependent() && 1950 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1951 Result.Val.getInt() != 0) 1952 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1953 << ((BuiltinID == Builtin::BI__builtin_return_address) 1954 ? "__builtin_return_address" 1955 : "__builtin_frame_address") 1956 << TheCall->getSourceRange(); 1957 break; 1958 } 1959 1960 case Builtin::BI__builtin_matrix_transpose: 1961 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1962 1963 case Builtin::BI__builtin_matrix_column_major_load: 1964 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1965 1966 case Builtin::BI__builtin_matrix_column_major_store: 1967 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1968 } 1969 1970 // Since the target specific builtins for each arch overlap, only check those 1971 // of the arch we are compiling for. 1972 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1973 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1974 assert(Context.getAuxTargetInfo() && 1975 "Aux Target Builtin, but not an aux target?"); 1976 1977 if (CheckTSBuiltinFunctionCall( 1978 *Context.getAuxTargetInfo(), 1979 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1980 return ExprError(); 1981 } else { 1982 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 1983 TheCall)) 1984 return ExprError(); 1985 } 1986 } 1987 1988 return TheCallResult; 1989 } 1990 1991 // Get the valid immediate range for the specified NEON type code. 1992 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1993 NeonTypeFlags Type(t); 1994 int IsQuad = ForceQuad ? true : Type.isQuad(); 1995 switch (Type.getEltType()) { 1996 case NeonTypeFlags::Int8: 1997 case NeonTypeFlags::Poly8: 1998 return shift ? 7 : (8 << IsQuad) - 1; 1999 case NeonTypeFlags::Int16: 2000 case NeonTypeFlags::Poly16: 2001 return shift ? 15 : (4 << IsQuad) - 1; 2002 case NeonTypeFlags::Int32: 2003 return shift ? 31 : (2 << IsQuad) - 1; 2004 case NeonTypeFlags::Int64: 2005 case NeonTypeFlags::Poly64: 2006 return shift ? 63 : (1 << IsQuad) - 1; 2007 case NeonTypeFlags::Poly128: 2008 return shift ? 127 : (1 << IsQuad) - 1; 2009 case NeonTypeFlags::Float16: 2010 assert(!shift && "cannot shift float types!"); 2011 return (4 << IsQuad) - 1; 2012 case NeonTypeFlags::Float32: 2013 assert(!shift && "cannot shift float types!"); 2014 return (2 << IsQuad) - 1; 2015 case NeonTypeFlags::Float64: 2016 assert(!shift && "cannot shift float types!"); 2017 return (1 << IsQuad) - 1; 2018 case NeonTypeFlags::BFloat16: 2019 assert(!shift && "cannot shift float types!"); 2020 return (4 << IsQuad) - 1; 2021 } 2022 llvm_unreachable("Invalid NeonTypeFlag!"); 2023 } 2024 2025 /// getNeonEltType - Return the QualType corresponding to the elements of 2026 /// the vector type specified by the NeonTypeFlags. This is used to check 2027 /// the pointer arguments for Neon load/store intrinsics. 2028 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2029 bool IsPolyUnsigned, bool IsInt64Long) { 2030 switch (Flags.getEltType()) { 2031 case NeonTypeFlags::Int8: 2032 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2033 case NeonTypeFlags::Int16: 2034 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2035 case NeonTypeFlags::Int32: 2036 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2037 case NeonTypeFlags::Int64: 2038 if (IsInt64Long) 2039 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2040 else 2041 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2042 : Context.LongLongTy; 2043 case NeonTypeFlags::Poly8: 2044 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2045 case NeonTypeFlags::Poly16: 2046 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2047 case NeonTypeFlags::Poly64: 2048 if (IsInt64Long) 2049 return Context.UnsignedLongTy; 2050 else 2051 return Context.UnsignedLongLongTy; 2052 case NeonTypeFlags::Poly128: 2053 break; 2054 case NeonTypeFlags::Float16: 2055 return Context.HalfTy; 2056 case NeonTypeFlags::Float32: 2057 return Context.FloatTy; 2058 case NeonTypeFlags::Float64: 2059 return Context.DoubleTy; 2060 case NeonTypeFlags::BFloat16: 2061 return Context.BFloat16Ty; 2062 } 2063 llvm_unreachable("Invalid NeonTypeFlag!"); 2064 } 2065 2066 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2067 // Range check SVE intrinsics that take immediate values. 2068 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2069 2070 switch (BuiltinID) { 2071 default: 2072 return false; 2073 #define GET_SVE_IMMEDIATE_CHECK 2074 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2075 #undef GET_SVE_IMMEDIATE_CHECK 2076 } 2077 2078 // Perform all the immediate checks for this builtin call. 2079 bool HasError = false; 2080 for (auto &I : ImmChecks) { 2081 int ArgNum, CheckTy, ElementSizeInBits; 2082 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2083 2084 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2085 2086 // Function that checks whether the operand (ArgNum) is an immediate 2087 // that is one of the predefined values. 2088 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2089 int ErrDiag) -> bool { 2090 // We can't check the value of a dependent argument. 2091 Expr *Arg = TheCall->getArg(ArgNum); 2092 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2093 return false; 2094 2095 // Check constant-ness first. 2096 llvm::APSInt Imm; 2097 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2098 return true; 2099 2100 if (!CheckImm(Imm.getSExtValue())) 2101 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2102 return false; 2103 }; 2104 2105 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2106 case SVETypeFlags::ImmCheck0_31: 2107 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2108 HasError = true; 2109 break; 2110 case SVETypeFlags::ImmCheck0_13: 2111 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2112 HasError = true; 2113 break; 2114 case SVETypeFlags::ImmCheck1_16: 2115 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2116 HasError = true; 2117 break; 2118 case SVETypeFlags::ImmCheck0_7: 2119 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2120 HasError = true; 2121 break; 2122 case SVETypeFlags::ImmCheckExtract: 2123 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2124 (2048 / ElementSizeInBits) - 1)) 2125 HasError = true; 2126 break; 2127 case SVETypeFlags::ImmCheckShiftRight: 2128 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2129 HasError = true; 2130 break; 2131 case SVETypeFlags::ImmCheckShiftRightNarrow: 2132 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2133 ElementSizeInBits / 2)) 2134 HasError = true; 2135 break; 2136 case SVETypeFlags::ImmCheckShiftLeft: 2137 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2138 ElementSizeInBits - 1)) 2139 HasError = true; 2140 break; 2141 case SVETypeFlags::ImmCheckLaneIndex: 2142 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2143 (128 / (1 * ElementSizeInBits)) - 1)) 2144 HasError = true; 2145 break; 2146 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2147 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2148 (128 / (2 * ElementSizeInBits)) - 1)) 2149 HasError = true; 2150 break; 2151 case SVETypeFlags::ImmCheckLaneIndexDot: 2152 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2153 (128 / (4 * ElementSizeInBits)) - 1)) 2154 HasError = true; 2155 break; 2156 case SVETypeFlags::ImmCheckComplexRot90_270: 2157 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2158 diag::err_rotation_argument_to_cadd)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckComplexRotAll90: 2162 if (CheckImmediateInSet( 2163 [](int64_t V) { 2164 return V == 0 || V == 90 || V == 180 || V == 270; 2165 }, 2166 diag::err_rotation_argument_to_cmla)) 2167 HasError = true; 2168 break; 2169 case SVETypeFlags::ImmCheck0_1: 2170 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2171 HasError = true; 2172 break; 2173 case SVETypeFlags::ImmCheck0_2: 2174 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2175 HasError = true; 2176 break; 2177 case SVETypeFlags::ImmCheck0_3: 2178 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2179 HasError = true; 2180 break; 2181 } 2182 } 2183 2184 return HasError; 2185 } 2186 2187 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2188 unsigned BuiltinID, CallExpr *TheCall) { 2189 llvm::APSInt Result; 2190 uint64_t mask = 0; 2191 unsigned TV = 0; 2192 int PtrArgNum = -1; 2193 bool HasConstPtr = false; 2194 switch (BuiltinID) { 2195 #define GET_NEON_OVERLOAD_CHECK 2196 #include "clang/Basic/arm_neon.inc" 2197 #include "clang/Basic/arm_fp16.inc" 2198 #undef GET_NEON_OVERLOAD_CHECK 2199 } 2200 2201 // For NEON intrinsics which are overloaded on vector element type, validate 2202 // the immediate which specifies which variant to emit. 2203 unsigned ImmArg = TheCall->getNumArgs()-1; 2204 if (mask) { 2205 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2206 return true; 2207 2208 TV = Result.getLimitedValue(64); 2209 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2210 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2211 << TheCall->getArg(ImmArg)->getSourceRange(); 2212 } 2213 2214 if (PtrArgNum >= 0) { 2215 // Check that pointer arguments have the specified type. 2216 Expr *Arg = TheCall->getArg(PtrArgNum); 2217 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2218 Arg = ICE->getSubExpr(); 2219 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2220 QualType RHSTy = RHS.get()->getType(); 2221 2222 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2223 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2224 Arch == llvm::Triple::aarch64_32 || 2225 Arch == llvm::Triple::aarch64_be; 2226 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2227 QualType EltTy = 2228 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2229 if (HasConstPtr) 2230 EltTy = EltTy.withConst(); 2231 QualType LHSTy = Context.getPointerType(EltTy); 2232 AssignConvertType ConvTy; 2233 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2234 if (RHS.isInvalid()) 2235 return true; 2236 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2237 RHS.get(), AA_Assigning)) 2238 return true; 2239 } 2240 2241 // For NEON intrinsics which take an immediate value as part of the 2242 // instruction, range check them here. 2243 unsigned i = 0, l = 0, u = 0; 2244 switch (BuiltinID) { 2245 default: 2246 return false; 2247 #define GET_NEON_IMMEDIATE_CHECK 2248 #include "clang/Basic/arm_neon.inc" 2249 #include "clang/Basic/arm_fp16.inc" 2250 #undef GET_NEON_IMMEDIATE_CHECK 2251 } 2252 2253 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2254 } 2255 2256 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2257 switch (BuiltinID) { 2258 default: 2259 return false; 2260 #include "clang/Basic/arm_mve_builtin_sema.inc" 2261 } 2262 } 2263 2264 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2265 CallExpr *TheCall) { 2266 bool Err = false; 2267 switch (BuiltinID) { 2268 default: 2269 return false; 2270 #include "clang/Basic/arm_cde_builtin_sema.inc" 2271 } 2272 2273 if (Err) 2274 return true; 2275 2276 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2277 } 2278 2279 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2280 const Expr *CoprocArg, bool WantCDE) { 2281 if (isConstantEvaluated()) 2282 return false; 2283 2284 // We can't check the value of a dependent argument. 2285 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2286 return false; 2287 2288 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2289 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2290 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2291 2292 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2293 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2294 2295 if (IsCDECoproc != WantCDE) 2296 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2297 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2298 2299 return false; 2300 } 2301 2302 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2303 unsigned MaxWidth) { 2304 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2305 BuiltinID == ARM::BI__builtin_arm_ldaex || 2306 BuiltinID == ARM::BI__builtin_arm_strex || 2307 BuiltinID == ARM::BI__builtin_arm_stlex || 2308 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2309 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2310 BuiltinID == AArch64::BI__builtin_arm_strex || 2311 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2312 "unexpected ARM builtin"); 2313 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2314 BuiltinID == ARM::BI__builtin_arm_ldaex || 2315 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2316 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2317 2318 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2319 2320 // Ensure that we have the proper number of arguments. 2321 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2322 return true; 2323 2324 // Inspect the pointer argument of the atomic builtin. This should always be 2325 // a pointer type, whose element is an integral scalar or pointer type. 2326 // Because it is a pointer type, we don't have to worry about any implicit 2327 // casts here. 2328 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2329 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2330 if (PointerArgRes.isInvalid()) 2331 return true; 2332 PointerArg = PointerArgRes.get(); 2333 2334 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2335 if (!pointerType) { 2336 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2337 << PointerArg->getType() << PointerArg->getSourceRange(); 2338 return true; 2339 } 2340 2341 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2342 // task is to insert the appropriate casts into the AST. First work out just 2343 // what the appropriate type is. 2344 QualType ValType = pointerType->getPointeeType(); 2345 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2346 if (IsLdrex) 2347 AddrType.addConst(); 2348 2349 // Issue a warning if the cast is dodgy. 2350 CastKind CastNeeded = CK_NoOp; 2351 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2352 CastNeeded = CK_BitCast; 2353 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2354 << PointerArg->getType() << Context.getPointerType(AddrType) 2355 << AA_Passing << PointerArg->getSourceRange(); 2356 } 2357 2358 // Finally, do the cast and replace the argument with the corrected version. 2359 AddrType = Context.getPointerType(AddrType); 2360 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2361 if (PointerArgRes.isInvalid()) 2362 return true; 2363 PointerArg = PointerArgRes.get(); 2364 2365 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2366 2367 // In general, we allow ints, floats and pointers to be loaded and stored. 2368 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2369 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2370 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2371 << PointerArg->getType() << PointerArg->getSourceRange(); 2372 return true; 2373 } 2374 2375 // But ARM doesn't have instructions to deal with 128-bit versions. 2376 if (Context.getTypeSize(ValType) > MaxWidth) { 2377 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2378 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2379 << PointerArg->getType() << PointerArg->getSourceRange(); 2380 return true; 2381 } 2382 2383 switch (ValType.getObjCLifetime()) { 2384 case Qualifiers::OCL_None: 2385 case Qualifiers::OCL_ExplicitNone: 2386 // okay 2387 break; 2388 2389 case Qualifiers::OCL_Weak: 2390 case Qualifiers::OCL_Strong: 2391 case Qualifiers::OCL_Autoreleasing: 2392 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2393 << ValType << PointerArg->getSourceRange(); 2394 return true; 2395 } 2396 2397 if (IsLdrex) { 2398 TheCall->setType(ValType); 2399 return false; 2400 } 2401 2402 // Initialize the argument to be stored. 2403 ExprResult ValArg = TheCall->getArg(0); 2404 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2405 Context, ValType, /*consume*/ false); 2406 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2407 if (ValArg.isInvalid()) 2408 return true; 2409 TheCall->setArg(0, ValArg.get()); 2410 2411 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2412 // but the custom checker bypasses all default analysis. 2413 TheCall->setType(Context.IntTy); 2414 return false; 2415 } 2416 2417 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2418 CallExpr *TheCall) { 2419 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2420 BuiltinID == ARM::BI__builtin_arm_ldaex || 2421 BuiltinID == ARM::BI__builtin_arm_strex || 2422 BuiltinID == ARM::BI__builtin_arm_stlex) { 2423 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2424 } 2425 2426 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2427 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2428 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2429 } 2430 2431 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2432 BuiltinID == ARM::BI__builtin_arm_wsr64) 2433 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2434 2435 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2436 BuiltinID == ARM::BI__builtin_arm_rsrp || 2437 BuiltinID == ARM::BI__builtin_arm_wsr || 2438 BuiltinID == ARM::BI__builtin_arm_wsrp) 2439 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2440 2441 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2442 return true; 2443 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2444 return true; 2445 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2446 return true; 2447 2448 // For intrinsics which take an immediate value as part of the instruction, 2449 // range check them here. 2450 // FIXME: VFP Intrinsics should error if VFP not present. 2451 switch (BuiltinID) { 2452 default: return false; 2453 case ARM::BI__builtin_arm_ssat: 2454 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2455 case ARM::BI__builtin_arm_usat: 2456 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2457 case ARM::BI__builtin_arm_ssat16: 2458 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2459 case ARM::BI__builtin_arm_usat16: 2460 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2461 case ARM::BI__builtin_arm_vcvtr_f: 2462 case ARM::BI__builtin_arm_vcvtr_d: 2463 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2464 case ARM::BI__builtin_arm_dmb: 2465 case ARM::BI__builtin_arm_dsb: 2466 case ARM::BI__builtin_arm_isb: 2467 case ARM::BI__builtin_arm_dbg: 2468 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2469 case ARM::BI__builtin_arm_cdp: 2470 case ARM::BI__builtin_arm_cdp2: 2471 case ARM::BI__builtin_arm_mcr: 2472 case ARM::BI__builtin_arm_mcr2: 2473 case ARM::BI__builtin_arm_mrc: 2474 case ARM::BI__builtin_arm_mrc2: 2475 case ARM::BI__builtin_arm_mcrr: 2476 case ARM::BI__builtin_arm_mcrr2: 2477 case ARM::BI__builtin_arm_mrrc: 2478 case ARM::BI__builtin_arm_mrrc2: 2479 case ARM::BI__builtin_arm_ldc: 2480 case ARM::BI__builtin_arm_ldcl: 2481 case ARM::BI__builtin_arm_ldc2: 2482 case ARM::BI__builtin_arm_ldc2l: 2483 case ARM::BI__builtin_arm_stc: 2484 case ARM::BI__builtin_arm_stcl: 2485 case ARM::BI__builtin_arm_stc2: 2486 case ARM::BI__builtin_arm_stc2l: 2487 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2488 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2489 /*WantCDE*/ false); 2490 } 2491 } 2492 2493 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2494 unsigned BuiltinID, 2495 CallExpr *TheCall) { 2496 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2497 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2498 BuiltinID == AArch64::BI__builtin_arm_strex || 2499 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2500 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2501 } 2502 2503 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2504 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2505 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2506 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2507 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2508 } 2509 2510 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2511 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2512 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2513 2514 // Memory Tagging Extensions (MTE) Intrinsics 2515 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2516 BuiltinID == AArch64::BI__builtin_arm_addg || 2517 BuiltinID == AArch64::BI__builtin_arm_gmi || 2518 BuiltinID == AArch64::BI__builtin_arm_ldg || 2519 BuiltinID == AArch64::BI__builtin_arm_stg || 2520 BuiltinID == AArch64::BI__builtin_arm_subp) { 2521 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2522 } 2523 2524 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2525 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2526 BuiltinID == AArch64::BI__builtin_arm_wsr || 2527 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2528 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2529 2530 // Only check the valid encoding range. Any constant in this range would be 2531 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2532 // an exception for incorrect registers. This matches MSVC behavior. 2533 if (BuiltinID == AArch64::BI_ReadStatusReg || 2534 BuiltinID == AArch64::BI_WriteStatusReg) 2535 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2536 2537 if (BuiltinID == AArch64::BI__getReg) 2538 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2539 2540 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2541 return true; 2542 2543 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2544 return true; 2545 2546 // For intrinsics which take an immediate value as part of the instruction, 2547 // range check them here. 2548 unsigned i = 0, l = 0, u = 0; 2549 switch (BuiltinID) { 2550 default: return false; 2551 case AArch64::BI__builtin_arm_dmb: 2552 case AArch64::BI__builtin_arm_dsb: 2553 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2554 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2555 } 2556 2557 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2558 } 2559 2560 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2561 if (Arg->getType()->getAsPlaceholderType()) 2562 return false; 2563 2564 // The first argument needs to be a record field access. 2565 // If it is an array element access, we delay decision 2566 // to BPF backend to check whether the access is a 2567 // field access or not. 2568 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2569 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2570 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2571 } 2572 2573 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2574 QualType VectorTy, QualType EltTy) { 2575 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2576 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2577 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2578 << Call->getSourceRange() << VectorEltTy << EltTy; 2579 return false; 2580 } 2581 return true; 2582 } 2583 2584 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2585 QualType ArgType = Arg->getType(); 2586 if (ArgType->getAsPlaceholderType()) 2587 return false; 2588 2589 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2590 // format: 2591 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2592 // 2. <type> var; 2593 // __builtin_preserve_type_info(var, flag); 2594 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2595 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2596 return false; 2597 2598 // Typedef type. 2599 if (ArgType->getAs<TypedefType>()) 2600 return true; 2601 2602 // Record type or Enum type. 2603 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2604 if (const auto *RT = Ty->getAs<RecordType>()) { 2605 if (!RT->getDecl()->getDeclName().isEmpty()) 2606 return true; 2607 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2608 if (!ET->getDecl()->getDeclName().isEmpty()) 2609 return true; 2610 } 2611 2612 return false; 2613 } 2614 2615 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2616 QualType ArgType = Arg->getType(); 2617 if (ArgType->getAsPlaceholderType()) 2618 return false; 2619 2620 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2621 // format: 2622 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2623 // flag); 2624 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2625 if (!UO) 2626 return false; 2627 2628 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2629 if (!CE || CE->getCastKind() != CK_IntegralToPointer) 2630 return false; 2631 2632 // The integer must be from an EnumConstantDecl. 2633 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2634 if (!DR) 2635 return false; 2636 2637 const EnumConstantDecl *Enumerator = 2638 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2639 if (!Enumerator) 2640 return false; 2641 2642 // The type must be EnumType. 2643 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2644 const auto *ET = Ty->getAs<EnumType>(); 2645 if (!ET) 2646 return false; 2647 2648 // The enum value must be supported. 2649 for (auto *EDI : ET->getDecl()->enumerators()) { 2650 if (EDI == Enumerator) 2651 return true; 2652 } 2653 2654 return false; 2655 } 2656 2657 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2658 CallExpr *TheCall) { 2659 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2660 BuiltinID == BPF::BI__builtin_btf_type_id || 2661 BuiltinID == BPF::BI__builtin_preserve_type_info || 2662 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2663 "unexpected BPF builtin"); 2664 2665 if (checkArgCount(*this, TheCall, 2)) 2666 return true; 2667 2668 // The second argument needs to be a constant int 2669 Expr *Arg = TheCall->getArg(1); 2670 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2671 diag::kind kind; 2672 if (!Value) { 2673 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2674 kind = diag::err_preserve_field_info_not_const; 2675 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2676 kind = diag::err_btf_type_id_not_const; 2677 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2678 kind = diag::err_preserve_type_info_not_const; 2679 else 2680 kind = diag::err_preserve_enum_value_not_const; 2681 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2682 return true; 2683 } 2684 2685 // The first argument 2686 Arg = TheCall->getArg(0); 2687 bool InvalidArg = false; 2688 bool ReturnUnsignedInt = true; 2689 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2690 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2691 InvalidArg = true; 2692 kind = diag::err_preserve_field_info_not_field; 2693 } 2694 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2695 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2696 InvalidArg = true; 2697 kind = diag::err_preserve_type_info_invalid; 2698 } 2699 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2700 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2701 InvalidArg = true; 2702 kind = diag::err_preserve_enum_value_invalid; 2703 } 2704 ReturnUnsignedInt = false; 2705 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2706 ReturnUnsignedInt = false; 2707 } 2708 2709 if (InvalidArg) { 2710 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2711 return true; 2712 } 2713 2714 if (ReturnUnsignedInt) 2715 TheCall->setType(Context.UnsignedIntTy); 2716 else 2717 TheCall->setType(Context.UnsignedLongTy); 2718 return false; 2719 } 2720 2721 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2722 struct ArgInfo { 2723 uint8_t OpNum; 2724 bool IsSigned; 2725 uint8_t BitWidth; 2726 uint8_t Align; 2727 }; 2728 struct BuiltinInfo { 2729 unsigned BuiltinID; 2730 ArgInfo Infos[2]; 2731 }; 2732 2733 static BuiltinInfo Infos[] = { 2734 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2735 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2736 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2737 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2738 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2739 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2740 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2741 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2742 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2743 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2744 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2745 2746 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2749 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2757 2758 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2810 {{ 1, false, 6, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2818 {{ 1, false, 5, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2825 { 2, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2827 { 2, false, 6, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2829 { 3, false, 5, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2831 { 3, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2848 {{ 2, false, 4, 0 }, 2849 { 3, false, 5, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2851 {{ 2, false, 4, 0 }, 2852 { 3, false, 5, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2854 {{ 2, false, 4, 0 }, 2855 { 3, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2857 {{ 2, false, 4, 0 }, 2858 { 3, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2870 { 2, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2872 { 2, false, 6, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2882 {{ 1, false, 4, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2885 {{ 1, false, 4, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2906 {{ 3, false, 1, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2911 {{ 3, false, 1, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2916 {{ 3, false, 1, 0 }} }, 2917 }; 2918 2919 // Use a dynamically initialized static to sort the table exactly once on 2920 // first run. 2921 static const bool SortOnce = 2922 (llvm::sort(Infos, 2923 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2924 return LHS.BuiltinID < RHS.BuiltinID; 2925 }), 2926 true); 2927 (void)SortOnce; 2928 2929 const BuiltinInfo *F = llvm::partition_point( 2930 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2931 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2932 return false; 2933 2934 bool Error = false; 2935 2936 for (const ArgInfo &A : F->Infos) { 2937 // Ignore empty ArgInfo elements. 2938 if (A.BitWidth == 0) 2939 continue; 2940 2941 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2942 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2943 if (!A.Align) { 2944 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2945 } else { 2946 unsigned M = 1 << A.Align; 2947 Min *= M; 2948 Max *= M; 2949 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2950 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2951 } 2952 } 2953 return Error; 2954 } 2955 2956 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2957 CallExpr *TheCall) { 2958 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2959 } 2960 2961 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2962 unsigned BuiltinID, CallExpr *TheCall) { 2963 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2964 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2965 } 2966 2967 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2968 CallExpr *TheCall) { 2969 2970 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2971 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2972 if (!TI.hasFeature("dsp")) 2973 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2974 } 2975 2976 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2977 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2978 if (!TI.hasFeature("dspr2")) 2979 return Diag(TheCall->getBeginLoc(), 2980 diag::err_mips_builtin_requires_dspr2); 2981 } 2982 2983 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2984 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2985 if (!TI.hasFeature("msa")) 2986 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2987 } 2988 2989 return false; 2990 } 2991 2992 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2993 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2994 // ordering for DSP is unspecified. MSA is ordered by the data format used 2995 // by the underlying instruction i.e., df/m, df/n and then by size. 2996 // 2997 // FIXME: The size tests here should instead be tablegen'd along with the 2998 // definitions from include/clang/Basic/BuiltinsMips.def. 2999 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3000 // be too. 3001 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3002 unsigned i = 0, l = 0, u = 0, m = 0; 3003 switch (BuiltinID) { 3004 default: return false; 3005 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3006 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3007 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3008 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3009 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3010 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3011 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3012 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3013 // df/m field. 3014 // These intrinsics take an unsigned 3 bit immediate. 3015 case Mips::BI__builtin_msa_bclri_b: 3016 case Mips::BI__builtin_msa_bnegi_b: 3017 case Mips::BI__builtin_msa_bseti_b: 3018 case Mips::BI__builtin_msa_sat_s_b: 3019 case Mips::BI__builtin_msa_sat_u_b: 3020 case Mips::BI__builtin_msa_slli_b: 3021 case Mips::BI__builtin_msa_srai_b: 3022 case Mips::BI__builtin_msa_srari_b: 3023 case Mips::BI__builtin_msa_srli_b: 3024 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3025 case Mips::BI__builtin_msa_binsli_b: 3026 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3027 // These intrinsics take an unsigned 4 bit immediate. 3028 case Mips::BI__builtin_msa_bclri_h: 3029 case Mips::BI__builtin_msa_bnegi_h: 3030 case Mips::BI__builtin_msa_bseti_h: 3031 case Mips::BI__builtin_msa_sat_s_h: 3032 case Mips::BI__builtin_msa_sat_u_h: 3033 case Mips::BI__builtin_msa_slli_h: 3034 case Mips::BI__builtin_msa_srai_h: 3035 case Mips::BI__builtin_msa_srari_h: 3036 case Mips::BI__builtin_msa_srli_h: 3037 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3038 case Mips::BI__builtin_msa_binsli_h: 3039 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3040 // These intrinsics take an unsigned 5 bit immediate. 3041 // The first block of intrinsics actually have an unsigned 5 bit field, 3042 // not a df/n field. 3043 case Mips::BI__builtin_msa_cfcmsa: 3044 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3045 case Mips::BI__builtin_msa_clei_u_b: 3046 case Mips::BI__builtin_msa_clei_u_h: 3047 case Mips::BI__builtin_msa_clei_u_w: 3048 case Mips::BI__builtin_msa_clei_u_d: 3049 case Mips::BI__builtin_msa_clti_u_b: 3050 case Mips::BI__builtin_msa_clti_u_h: 3051 case Mips::BI__builtin_msa_clti_u_w: 3052 case Mips::BI__builtin_msa_clti_u_d: 3053 case Mips::BI__builtin_msa_maxi_u_b: 3054 case Mips::BI__builtin_msa_maxi_u_h: 3055 case Mips::BI__builtin_msa_maxi_u_w: 3056 case Mips::BI__builtin_msa_maxi_u_d: 3057 case Mips::BI__builtin_msa_mini_u_b: 3058 case Mips::BI__builtin_msa_mini_u_h: 3059 case Mips::BI__builtin_msa_mini_u_w: 3060 case Mips::BI__builtin_msa_mini_u_d: 3061 case Mips::BI__builtin_msa_addvi_b: 3062 case Mips::BI__builtin_msa_addvi_h: 3063 case Mips::BI__builtin_msa_addvi_w: 3064 case Mips::BI__builtin_msa_addvi_d: 3065 case Mips::BI__builtin_msa_bclri_w: 3066 case Mips::BI__builtin_msa_bnegi_w: 3067 case Mips::BI__builtin_msa_bseti_w: 3068 case Mips::BI__builtin_msa_sat_s_w: 3069 case Mips::BI__builtin_msa_sat_u_w: 3070 case Mips::BI__builtin_msa_slli_w: 3071 case Mips::BI__builtin_msa_srai_w: 3072 case Mips::BI__builtin_msa_srari_w: 3073 case Mips::BI__builtin_msa_srli_w: 3074 case Mips::BI__builtin_msa_srlri_w: 3075 case Mips::BI__builtin_msa_subvi_b: 3076 case Mips::BI__builtin_msa_subvi_h: 3077 case Mips::BI__builtin_msa_subvi_w: 3078 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3079 case Mips::BI__builtin_msa_binsli_w: 3080 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3081 // These intrinsics take an unsigned 6 bit immediate. 3082 case Mips::BI__builtin_msa_bclri_d: 3083 case Mips::BI__builtin_msa_bnegi_d: 3084 case Mips::BI__builtin_msa_bseti_d: 3085 case Mips::BI__builtin_msa_sat_s_d: 3086 case Mips::BI__builtin_msa_sat_u_d: 3087 case Mips::BI__builtin_msa_slli_d: 3088 case Mips::BI__builtin_msa_srai_d: 3089 case Mips::BI__builtin_msa_srari_d: 3090 case Mips::BI__builtin_msa_srli_d: 3091 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3092 case Mips::BI__builtin_msa_binsli_d: 3093 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3094 // These intrinsics take a signed 5 bit immediate. 3095 case Mips::BI__builtin_msa_ceqi_b: 3096 case Mips::BI__builtin_msa_ceqi_h: 3097 case Mips::BI__builtin_msa_ceqi_w: 3098 case Mips::BI__builtin_msa_ceqi_d: 3099 case Mips::BI__builtin_msa_clti_s_b: 3100 case Mips::BI__builtin_msa_clti_s_h: 3101 case Mips::BI__builtin_msa_clti_s_w: 3102 case Mips::BI__builtin_msa_clti_s_d: 3103 case Mips::BI__builtin_msa_clei_s_b: 3104 case Mips::BI__builtin_msa_clei_s_h: 3105 case Mips::BI__builtin_msa_clei_s_w: 3106 case Mips::BI__builtin_msa_clei_s_d: 3107 case Mips::BI__builtin_msa_maxi_s_b: 3108 case Mips::BI__builtin_msa_maxi_s_h: 3109 case Mips::BI__builtin_msa_maxi_s_w: 3110 case Mips::BI__builtin_msa_maxi_s_d: 3111 case Mips::BI__builtin_msa_mini_s_b: 3112 case Mips::BI__builtin_msa_mini_s_h: 3113 case Mips::BI__builtin_msa_mini_s_w: 3114 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3115 // These intrinsics take an unsigned 8 bit immediate. 3116 case Mips::BI__builtin_msa_andi_b: 3117 case Mips::BI__builtin_msa_nori_b: 3118 case Mips::BI__builtin_msa_ori_b: 3119 case Mips::BI__builtin_msa_shf_b: 3120 case Mips::BI__builtin_msa_shf_h: 3121 case Mips::BI__builtin_msa_shf_w: 3122 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3123 case Mips::BI__builtin_msa_bseli_b: 3124 case Mips::BI__builtin_msa_bmnzi_b: 3125 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3126 // df/n format 3127 // These intrinsics take an unsigned 4 bit immediate. 3128 case Mips::BI__builtin_msa_copy_s_b: 3129 case Mips::BI__builtin_msa_copy_u_b: 3130 case Mips::BI__builtin_msa_insve_b: 3131 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3132 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3133 // These intrinsics take an unsigned 3 bit immediate. 3134 case Mips::BI__builtin_msa_copy_s_h: 3135 case Mips::BI__builtin_msa_copy_u_h: 3136 case Mips::BI__builtin_msa_insve_h: 3137 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3138 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3139 // These intrinsics take an unsigned 2 bit immediate. 3140 case Mips::BI__builtin_msa_copy_s_w: 3141 case Mips::BI__builtin_msa_copy_u_w: 3142 case Mips::BI__builtin_msa_insve_w: 3143 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3144 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3145 // These intrinsics take an unsigned 1 bit immediate. 3146 case Mips::BI__builtin_msa_copy_s_d: 3147 case Mips::BI__builtin_msa_copy_u_d: 3148 case Mips::BI__builtin_msa_insve_d: 3149 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3150 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3151 // Memory offsets and immediate loads. 3152 // These intrinsics take a signed 10 bit immediate. 3153 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3154 case Mips::BI__builtin_msa_ldi_h: 3155 case Mips::BI__builtin_msa_ldi_w: 3156 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3157 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3158 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3159 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3160 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3161 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3162 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3163 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3164 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3165 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3166 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3167 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3168 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3169 } 3170 3171 if (!m) 3172 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3173 3174 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3175 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3176 } 3177 3178 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3179 /// advancing the pointer over the consumed characters. The decoded type is 3180 /// returned. If the decoded type represents a constant integer with a 3181 /// constraint on its value then Mask is set to that value. The type descriptors 3182 /// used in Str are specific to PPC MMA builtins and are documented in the file 3183 /// defining the PPC builtins. 3184 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3185 unsigned &Mask) { 3186 bool RequireICE = false; 3187 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3188 switch (*Str++) { 3189 case 'V': 3190 return Context.getVectorType(Context.UnsignedCharTy, 16, 3191 VectorType::VectorKind::AltiVecVector); 3192 case 'i': { 3193 char *End; 3194 unsigned size = strtoul(Str, &End, 10); 3195 assert(End != Str && "Missing constant parameter constraint"); 3196 Str = End; 3197 Mask = size; 3198 return Context.IntTy; 3199 } 3200 case 'W': { 3201 char *End; 3202 unsigned size = strtoul(Str, &End, 10); 3203 assert(End != Str && "Missing PowerPC MMA type size"); 3204 Str = End; 3205 QualType Type; 3206 switch (size) { 3207 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3208 case size: Type = Context.Id##Ty; break; 3209 #include "clang/Basic/PPCTypes.def" 3210 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3211 } 3212 bool CheckVectorArgs = false; 3213 while (!CheckVectorArgs) { 3214 switch (*Str++) { 3215 case '*': 3216 Type = Context.getPointerType(Type); 3217 break; 3218 case 'C': 3219 Type = Type.withConst(); 3220 break; 3221 default: 3222 CheckVectorArgs = true; 3223 --Str; 3224 break; 3225 } 3226 } 3227 return Type; 3228 } 3229 default: 3230 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3231 } 3232 } 3233 3234 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3235 CallExpr *TheCall) { 3236 unsigned i = 0, l = 0, u = 0; 3237 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3238 BuiltinID == PPC::BI__builtin_divdeu || 3239 BuiltinID == PPC::BI__builtin_bpermd; 3240 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3241 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3242 BuiltinID == PPC::BI__builtin_divweu || 3243 BuiltinID == PPC::BI__builtin_divde || 3244 BuiltinID == PPC::BI__builtin_divdeu; 3245 3246 if (Is64BitBltin && !IsTarget64Bit) 3247 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3248 << TheCall->getSourceRange(); 3249 3250 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3251 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3252 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3253 << TheCall->getSourceRange(); 3254 3255 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3256 if (!TI.hasFeature("vsx")) 3257 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3258 << TheCall->getSourceRange(); 3259 return false; 3260 }; 3261 3262 switch (BuiltinID) { 3263 default: return false; 3264 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3265 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3266 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3267 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3268 case PPC::BI__builtin_altivec_dss: 3269 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3270 case PPC::BI__builtin_tbegin: 3271 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3272 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3273 case PPC::BI__builtin_tabortwc: 3274 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3275 case PPC::BI__builtin_tabortwci: 3276 case PPC::BI__builtin_tabortdci: 3277 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3278 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3279 case PPC::BI__builtin_altivec_dst: 3280 case PPC::BI__builtin_altivec_dstt: 3281 case PPC::BI__builtin_altivec_dstst: 3282 case PPC::BI__builtin_altivec_dststt: 3283 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3284 case PPC::BI__builtin_vsx_xxpermdi: 3285 case PPC::BI__builtin_vsx_xxsldwi: 3286 return SemaBuiltinVSX(TheCall); 3287 case PPC::BI__builtin_unpack_vector_int128: 3288 return SemaVSXCheck(TheCall) || 3289 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3290 case PPC::BI__builtin_pack_vector_int128: 3291 return SemaVSXCheck(TheCall); 3292 case PPC::BI__builtin_altivec_vgnb: 3293 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3294 case PPC::BI__builtin_altivec_vec_replace_elt: 3295 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3296 QualType VecTy = TheCall->getArg(0)->getType(); 3297 QualType EltTy = TheCall->getArg(1)->getType(); 3298 unsigned Width = Context.getIntWidth(EltTy); 3299 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3300 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3301 } 3302 case PPC::BI__builtin_vsx_xxeval: 3303 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3304 case PPC::BI__builtin_altivec_vsldbi: 3305 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3306 case PPC::BI__builtin_altivec_vsrdbi: 3307 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3308 case PPC::BI__builtin_vsx_xxpermx: 3309 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3310 #define CUSTOM_BUILTIN(Name, Types, Acc) \ 3311 case PPC::BI__builtin_##Name: \ 3312 return SemaBuiltinPPCMMACall(TheCall, Types); 3313 #include "clang/Basic/BuiltinsPPC.def" 3314 } 3315 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3316 } 3317 3318 // Check if the given type is a non-pointer PPC MMA type. This function is used 3319 // in Sema to prevent invalid uses of restricted PPC MMA types. 3320 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3321 if (Type->isPointerType() || Type->isArrayType()) 3322 return false; 3323 3324 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3325 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3326 if (false 3327 #include "clang/Basic/PPCTypes.def" 3328 ) { 3329 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3330 return true; 3331 } 3332 return false; 3333 } 3334 3335 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3336 CallExpr *TheCall) { 3337 // position of memory order and scope arguments in the builtin 3338 unsigned OrderIndex, ScopeIndex; 3339 switch (BuiltinID) { 3340 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3341 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3342 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3343 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3344 OrderIndex = 2; 3345 ScopeIndex = 3; 3346 break; 3347 case AMDGPU::BI__builtin_amdgcn_fence: 3348 OrderIndex = 0; 3349 ScopeIndex = 1; 3350 break; 3351 default: 3352 return false; 3353 } 3354 3355 ExprResult Arg = TheCall->getArg(OrderIndex); 3356 auto ArgExpr = Arg.get(); 3357 Expr::EvalResult ArgResult; 3358 3359 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3360 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3361 << ArgExpr->getType(); 3362 int ord = ArgResult.Val.getInt().getZExtValue(); 3363 3364 // Check valididty of memory ordering as per C11 / C++11's memody model. 3365 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3366 case llvm::AtomicOrderingCABI::acquire: 3367 case llvm::AtomicOrderingCABI::release: 3368 case llvm::AtomicOrderingCABI::acq_rel: 3369 case llvm::AtomicOrderingCABI::seq_cst: 3370 break; 3371 default: { 3372 return Diag(ArgExpr->getBeginLoc(), 3373 diag::warn_atomic_op_has_invalid_memory_order) 3374 << ArgExpr->getSourceRange(); 3375 } 3376 } 3377 3378 Arg = TheCall->getArg(ScopeIndex); 3379 ArgExpr = Arg.get(); 3380 Expr::EvalResult ArgResult1; 3381 // Check that sync scope is a constant literal 3382 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3383 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3384 << ArgExpr->getType(); 3385 3386 return false; 3387 } 3388 3389 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3390 unsigned BuiltinID, 3391 CallExpr *TheCall) { 3392 switch (BuiltinID) { 3393 default: 3394 break; 3395 #define BUILTIN(ID, TYPE, ATTRS) case RISCV::BI##ID: 3396 #include "clang/Basic/BuiltinsRISCV.def" 3397 if (!TI.hasFeature("experimental-v")) 3398 return Diag(TheCall->getBeginLoc(), diag::err_riscvv_builtin_requires_v) 3399 << TheCall->getSourceRange(); 3400 break; 3401 } 3402 3403 return false; 3404 } 3405 3406 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3407 CallExpr *TheCall) { 3408 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3409 Expr *Arg = TheCall->getArg(0); 3410 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3411 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3412 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3413 << Arg->getSourceRange(); 3414 } 3415 3416 // For intrinsics which take an immediate value as part of the instruction, 3417 // range check them here. 3418 unsigned i = 0, l = 0, u = 0; 3419 switch (BuiltinID) { 3420 default: return false; 3421 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3422 case SystemZ::BI__builtin_s390_verimb: 3423 case SystemZ::BI__builtin_s390_verimh: 3424 case SystemZ::BI__builtin_s390_verimf: 3425 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3426 case SystemZ::BI__builtin_s390_vfaeb: 3427 case SystemZ::BI__builtin_s390_vfaeh: 3428 case SystemZ::BI__builtin_s390_vfaef: 3429 case SystemZ::BI__builtin_s390_vfaebs: 3430 case SystemZ::BI__builtin_s390_vfaehs: 3431 case SystemZ::BI__builtin_s390_vfaefs: 3432 case SystemZ::BI__builtin_s390_vfaezb: 3433 case SystemZ::BI__builtin_s390_vfaezh: 3434 case SystemZ::BI__builtin_s390_vfaezf: 3435 case SystemZ::BI__builtin_s390_vfaezbs: 3436 case SystemZ::BI__builtin_s390_vfaezhs: 3437 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3438 case SystemZ::BI__builtin_s390_vfisb: 3439 case SystemZ::BI__builtin_s390_vfidb: 3440 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3441 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3442 case SystemZ::BI__builtin_s390_vftcisb: 3443 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3444 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3445 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3446 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3447 case SystemZ::BI__builtin_s390_vstrcb: 3448 case SystemZ::BI__builtin_s390_vstrch: 3449 case SystemZ::BI__builtin_s390_vstrcf: 3450 case SystemZ::BI__builtin_s390_vstrczb: 3451 case SystemZ::BI__builtin_s390_vstrczh: 3452 case SystemZ::BI__builtin_s390_vstrczf: 3453 case SystemZ::BI__builtin_s390_vstrcbs: 3454 case SystemZ::BI__builtin_s390_vstrchs: 3455 case SystemZ::BI__builtin_s390_vstrcfs: 3456 case SystemZ::BI__builtin_s390_vstrczbs: 3457 case SystemZ::BI__builtin_s390_vstrczhs: 3458 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3459 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3460 case SystemZ::BI__builtin_s390_vfminsb: 3461 case SystemZ::BI__builtin_s390_vfmaxsb: 3462 case SystemZ::BI__builtin_s390_vfmindb: 3463 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3464 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3465 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3466 } 3467 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3468 } 3469 3470 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3471 /// This checks that the target supports __builtin_cpu_supports and 3472 /// that the string argument is constant and valid. 3473 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3474 CallExpr *TheCall) { 3475 Expr *Arg = TheCall->getArg(0); 3476 3477 // Check if the argument is a string literal. 3478 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3479 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3480 << Arg->getSourceRange(); 3481 3482 // Check the contents of the string. 3483 StringRef Feature = 3484 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3485 if (!TI.validateCpuSupports(Feature)) 3486 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3487 << Arg->getSourceRange(); 3488 return false; 3489 } 3490 3491 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3492 /// This checks that the target supports __builtin_cpu_is and 3493 /// that the string argument is constant and valid. 3494 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3495 Expr *Arg = TheCall->getArg(0); 3496 3497 // Check if the argument is a string literal. 3498 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3499 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3500 << Arg->getSourceRange(); 3501 3502 // Check the contents of the string. 3503 StringRef Feature = 3504 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3505 if (!TI.validateCpuIs(Feature)) 3506 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3507 << Arg->getSourceRange(); 3508 return false; 3509 } 3510 3511 // Check if the rounding mode is legal. 3512 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3513 // Indicates if this instruction has rounding control or just SAE. 3514 bool HasRC = false; 3515 3516 unsigned ArgNum = 0; 3517 switch (BuiltinID) { 3518 default: 3519 return false; 3520 case X86::BI__builtin_ia32_vcvttsd2si32: 3521 case X86::BI__builtin_ia32_vcvttsd2si64: 3522 case X86::BI__builtin_ia32_vcvttsd2usi32: 3523 case X86::BI__builtin_ia32_vcvttsd2usi64: 3524 case X86::BI__builtin_ia32_vcvttss2si32: 3525 case X86::BI__builtin_ia32_vcvttss2si64: 3526 case X86::BI__builtin_ia32_vcvttss2usi32: 3527 case X86::BI__builtin_ia32_vcvttss2usi64: 3528 ArgNum = 1; 3529 break; 3530 case X86::BI__builtin_ia32_maxpd512: 3531 case X86::BI__builtin_ia32_maxps512: 3532 case X86::BI__builtin_ia32_minpd512: 3533 case X86::BI__builtin_ia32_minps512: 3534 ArgNum = 2; 3535 break; 3536 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3537 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3538 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3539 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3540 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3541 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3542 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3543 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3544 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3545 case X86::BI__builtin_ia32_exp2pd_mask: 3546 case X86::BI__builtin_ia32_exp2ps_mask: 3547 case X86::BI__builtin_ia32_getexppd512_mask: 3548 case X86::BI__builtin_ia32_getexpps512_mask: 3549 case X86::BI__builtin_ia32_rcp28pd_mask: 3550 case X86::BI__builtin_ia32_rcp28ps_mask: 3551 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3552 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3553 case X86::BI__builtin_ia32_vcomisd: 3554 case X86::BI__builtin_ia32_vcomiss: 3555 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3556 ArgNum = 3; 3557 break; 3558 case X86::BI__builtin_ia32_cmppd512_mask: 3559 case X86::BI__builtin_ia32_cmpps512_mask: 3560 case X86::BI__builtin_ia32_cmpsd_mask: 3561 case X86::BI__builtin_ia32_cmpss_mask: 3562 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3563 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3564 case X86::BI__builtin_ia32_getexpss128_round_mask: 3565 case X86::BI__builtin_ia32_getmantpd512_mask: 3566 case X86::BI__builtin_ia32_getmantps512_mask: 3567 case X86::BI__builtin_ia32_maxsd_round_mask: 3568 case X86::BI__builtin_ia32_maxss_round_mask: 3569 case X86::BI__builtin_ia32_minsd_round_mask: 3570 case X86::BI__builtin_ia32_minss_round_mask: 3571 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3572 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3573 case X86::BI__builtin_ia32_reducepd512_mask: 3574 case X86::BI__builtin_ia32_reduceps512_mask: 3575 case X86::BI__builtin_ia32_rndscalepd_mask: 3576 case X86::BI__builtin_ia32_rndscaleps_mask: 3577 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3578 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3579 ArgNum = 4; 3580 break; 3581 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3582 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3583 case X86::BI__builtin_ia32_fixupimmps512_mask: 3584 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3585 case X86::BI__builtin_ia32_fixupimmsd_mask: 3586 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3587 case X86::BI__builtin_ia32_fixupimmss_mask: 3588 case X86::BI__builtin_ia32_fixupimmss_maskz: 3589 case X86::BI__builtin_ia32_getmantsd_round_mask: 3590 case X86::BI__builtin_ia32_getmantss_round_mask: 3591 case X86::BI__builtin_ia32_rangepd512_mask: 3592 case X86::BI__builtin_ia32_rangeps512_mask: 3593 case X86::BI__builtin_ia32_rangesd128_round_mask: 3594 case X86::BI__builtin_ia32_rangess128_round_mask: 3595 case X86::BI__builtin_ia32_reducesd_mask: 3596 case X86::BI__builtin_ia32_reducess_mask: 3597 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3598 case X86::BI__builtin_ia32_rndscaless_round_mask: 3599 ArgNum = 5; 3600 break; 3601 case X86::BI__builtin_ia32_vcvtsd2si64: 3602 case X86::BI__builtin_ia32_vcvtsd2si32: 3603 case X86::BI__builtin_ia32_vcvtsd2usi32: 3604 case X86::BI__builtin_ia32_vcvtsd2usi64: 3605 case X86::BI__builtin_ia32_vcvtss2si32: 3606 case X86::BI__builtin_ia32_vcvtss2si64: 3607 case X86::BI__builtin_ia32_vcvtss2usi32: 3608 case X86::BI__builtin_ia32_vcvtss2usi64: 3609 case X86::BI__builtin_ia32_sqrtpd512: 3610 case X86::BI__builtin_ia32_sqrtps512: 3611 ArgNum = 1; 3612 HasRC = true; 3613 break; 3614 case X86::BI__builtin_ia32_addpd512: 3615 case X86::BI__builtin_ia32_addps512: 3616 case X86::BI__builtin_ia32_divpd512: 3617 case X86::BI__builtin_ia32_divps512: 3618 case X86::BI__builtin_ia32_mulpd512: 3619 case X86::BI__builtin_ia32_mulps512: 3620 case X86::BI__builtin_ia32_subpd512: 3621 case X86::BI__builtin_ia32_subps512: 3622 case X86::BI__builtin_ia32_cvtsi2sd64: 3623 case X86::BI__builtin_ia32_cvtsi2ss32: 3624 case X86::BI__builtin_ia32_cvtsi2ss64: 3625 case X86::BI__builtin_ia32_cvtusi2sd64: 3626 case X86::BI__builtin_ia32_cvtusi2ss32: 3627 case X86::BI__builtin_ia32_cvtusi2ss64: 3628 ArgNum = 2; 3629 HasRC = true; 3630 break; 3631 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3632 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3633 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3634 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3635 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3636 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3637 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3638 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3639 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3640 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3641 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3642 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3643 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3644 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3645 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3646 ArgNum = 3; 3647 HasRC = true; 3648 break; 3649 case X86::BI__builtin_ia32_addss_round_mask: 3650 case X86::BI__builtin_ia32_addsd_round_mask: 3651 case X86::BI__builtin_ia32_divss_round_mask: 3652 case X86::BI__builtin_ia32_divsd_round_mask: 3653 case X86::BI__builtin_ia32_mulss_round_mask: 3654 case X86::BI__builtin_ia32_mulsd_round_mask: 3655 case X86::BI__builtin_ia32_subss_round_mask: 3656 case X86::BI__builtin_ia32_subsd_round_mask: 3657 case X86::BI__builtin_ia32_scalefpd512_mask: 3658 case X86::BI__builtin_ia32_scalefps512_mask: 3659 case X86::BI__builtin_ia32_scalefsd_round_mask: 3660 case X86::BI__builtin_ia32_scalefss_round_mask: 3661 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3662 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3663 case X86::BI__builtin_ia32_sqrtss_round_mask: 3664 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3665 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3666 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3667 case X86::BI__builtin_ia32_vfmaddss3_mask: 3668 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3669 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3670 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3671 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3672 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3673 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3674 case X86::BI__builtin_ia32_vfmaddps512_mask: 3675 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3676 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3677 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3678 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3679 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3680 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3681 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3682 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3683 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3684 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3685 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3686 ArgNum = 4; 3687 HasRC = true; 3688 break; 3689 } 3690 3691 llvm::APSInt Result; 3692 3693 // We can't check the value of a dependent argument. 3694 Expr *Arg = TheCall->getArg(ArgNum); 3695 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3696 return false; 3697 3698 // Check constant-ness first. 3699 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3700 return true; 3701 3702 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3703 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3704 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3705 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3706 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3707 Result == 8/*ROUND_NO_EXC*/ || 3708 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3709 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3710 return false; 3711 3712 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3713 << Arg->getSourceRange(); 3714 } 3715 3716 // Check if the gather/scatter scale is legal. 3717 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3718 CallExpr *TheCall) { 3719 unsigned ArgNum = 0; 3720 switch (BuiltinID) { 3721 default: 3722 return false; 3723 case X86::BI__builtin_ia32_gatherpfdpd: 3724 case X86::BI__builtin_ia32_gatherpfdps: 3725 case X86::BI__builtin_ia32_gatherpfqpd: 3726 case X86::BI__builtin_ia32_gatherpfqps: 3727 case X86::BI__builtin_ia32_scatterpfdpd: 3728 case X86::BI__builtin_ia32_scatterpfdps: 3729 case X86::BI__builtin_ia32_scatterpfqpd: 3730 case X86::BI__builtin_ia32_scatterpfqps: 3731 ArgNum = 3; 3732 break; 3733 case X86::BI__builtin_ia32_gatherd_pd: 3734 case X86::BI__builtin_ia32_gatherd_pd256: 3735 case X86::BI__builtin_ia32_gatherq_pd: 3736 case X86::BI__builtin_ia32_gatherq_pd256: 3737 case X86::BI__builtin_ia32_gatherd_ps: 3738 case X86::BI__builtin_ia32_gatherd_ps256: 3739 case X86::BI__builtin_ia32_gatherq_ps: 3740 case X86::BI__builtin_ia32_gatherq_ps256: 3741 case X86::BI__builtin_ia32_gatherd_q: 3742 case X86::BI__builtin_ia32_gatherd_q256: 3743 case X86::BI__builtin_ia32_gatherq_q: 3744 case X86::BI__builtin_ia32_gatherq_q256: 3745 case X86::BI__builtin_ia32_gatherd_d: 3746 case X86::BI__builtin_ia32_gatherd_d256: 3747 case X86::BI__builtin_ia32_gatherq_d: 3748 case X86::BI__builtin_ia32_gatherq_d256: 3749 case X86::BI__builtin_ia32_gather3div2df: 3750 case X86::BI__builtin_ia32_gather3div2di: 3751 case X86::BI__builtin_ia32_gather3div4df: 3752 case X86::BI__builtin_ia32_gather3div4di: 3753 case X86::BI__builtin_ia32_gather3div4sf: 3754 case X86::BI__builtin_ia32_gather3div4si: 3755 case X86::BI__builtin_ia32_gather3div8sf: 3756 case X86::BI__builtin_ia32_gather3div8si: 3757 case X86::BI__builtin_ia32_gather3siv2df: 3758 case X86::BI__builtin_ia32_gather3siv2di: 3759 case X86::BI__builtin_ia32_gather3siv4df: 3760 case X86::BI__builtin_ia32_gather3siv4di: 3761 case X86::BI__builtin_ia32_gather3siv4sf: 3762 case X86::BI__builtin_ia32_gather3siv4si: 3763 case X86::BI__builtin_ia32_gather3siv8sf: 3764 case X86::BI__builtin_ia32_gather3siv8si: 3765 case X86::BI__builtin_ia32_gathersiv8df: 3766 case X86::BI__builtin_ia32_gathersiv16sf: 3767 case X86::BI__builtin_ia32_gatherdiv8df: 3768 case X86::BI__builtin_ia32_gatherdiv16sf: 3769 case X86::BI__builtin_ia32_gathersiv8di: 3770 case X86::BI__builtin_ia32_gathersiv16si: 3771 case X86::BI__builtin_ia32_gatherdiv8di: 3772 case X86::BI__builtin_ia32_gatherdiv16si: 3773 case X86::BI__builtin_ia32_scatterdiv2df: 3774 case X86::BI__builtin_ia32_scatterdiv2di: 3775 case X86::BI__builtin_ia32_scatterdiv4df: 3776 case X86::BI__builtin_ia32_scatterdiv4di: 3777 case X86::BI__builtin_ia32_scatterdiv4sf: 3778 case X86::BI__builtin_ia32_scatterdiv4si: 3779 case X86::BI__builtin_ia32_scatterdiv8sf: 3780 case X86::BI__builtin_ia32_scatterdiv8si: 3781 case X86::BI__builtin_ia32_scattersiv2df: 3782 case X86::BI__builtin_ia32_scattersiv2di: 3783 case X86::BI__builtin_ia32_scattersiv4df: 3784 case X86::BI__builtin_ia32_scattersiv4di: 3785 case X86::BI__builtin_ia32_scattersiv4sf: 3786 case X86::BI__builtin_ia32_scattersiv4si: 3787 case X86::BI__builtin_ia32_scattersiv8sf: 3788 case X86::BI__builtin_ia32_scattersiv8si: 3789 case X86::BI__builtin_ia32_scattersiv8df: 3790 case X86::BI__builtin_ia32_scattersiv16sf: 3791 case X86::BI__builtin_ia32_scatterdiv8df: 3792 case X86::BI__builtin_ia32_scatterdiv16sf: 3793 case X86::BI__builtin_ia32_scattersiv8di: 3794 case X86::BI__builtin_ia32_scattersiv16si: 3795 case X86::BI__builtin_ia32_scatterdiv8di: 3796 case X86::BI__builtin_ia32_scatterdiv16si: 3797 ArgNum = 4; 3798 break; 3799 } 3800 3801 llvm::APSInt Result; 3802 3803 // We can't check the value of a dependent argument. 3804 Expr *Arg = TheCall->getArg(ArgNum); 3805 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3806 return false; 3807 3808 // Check constant-ness first. 3809 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3810 return true; 3811 3812 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3813 return false; 3814 3815 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3816 << Arg->getSourceRange(); 3817 } 3818 3819 enum { TileRegLow = 0, TileRegHigh = 7 }; 3820 3821 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3822 ArrayRef<int> ArgNums) { 3823 for (int ArgNum : ArgNums) { 3824 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3825 return true; 3826 } 3827 return false; 3828 } 3829 3830 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3831 ArrayRef<int> ArgNums) { 3832 // Because the max number of tile register is TileRegHigh + 1, so here we use 3833 // each bit to represent the usage of them in bitset. 3834 std::bitset<TileRegHigh + 1> ArgValues; 3835 for (int ArgNum : ArgNums) { 3836 Expr *Arg = TheCall->getArg(ArgNum); 3837 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3838 continue; 3839 3840 llvm::APSInt Result; 3841 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3842 return true; 3843 int ArgExtValue = Result.getExtValue(); 3844 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3845 "Incorrect tile register num."); 3846 if (ArgValues.test(ArgExtValue)) 3847 return Diag(TheCall->getBeginLoc(), 3848 diag::err_x86_builtin_tile_arg_duplicate) 3849 << TheCall->getArg(ArgNum)->getSourceRange(); 3850 ArgValues.set(ArgExtValue); 3851 } 3852 return false; 3853 } 3854 3855 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3856 ArrayRef<int> ArgNums) { 3857 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3858 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3859 } 3860 3861 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3862 switch (BuiltinID) { 3863 default: 3864 return false; 3865 case X86::BI__builtin_ia32_tileloadd64: 3866 case X86::BI__builtin_ia32_tileloaddt164: 3867 case X86::BI__builtin_ia32_tilestored64: 3868 case X86::BI__builtin_ia32_tilezero: 3869 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3870 case X86::BI__builtin_ia32_tdpbssd: 3871 case X86::BI__builtin_ia32_tdpbsud: 3872 case X86::BI__builtin_ia32_tdpbusd: 3873 case X86::BI__builtin_ia32_tdpbuud: 3874 case X86::BI__builtin_ia32_tdpbf16ps: 3875 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3876 } 3877 } 3878 static bool isX86_32Builtin(unsigned BuiltinID) { 3879 // These builtins only work on x86-32 targets. 3880 switch (BuiltinID) { 3881 case X86::BI__builtin_ia32_readeflags_u32: 3882 case X86::BI__builtin_ia32_writeeflags_u32: 3883 return true; 3884 } 3885 3886 return false; 3887 } 3888 3889 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3890 CallExpr *TheCall) { 3891 if (BuiltinID == X86::BI__builtin_cpu_supports) 3892 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3893 3894 if (BuiltinID == X86::BI__builtin_cpu_is) 3895 return SemaBuiltinCpuIs(*this, TI, TheCall); 3896 3897 // Check for 32-bit only builtins on a 64-bit target. 3898 const llvm::Triple &TT = TI.getTriple(); 3899 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3900 return Diag(TheCall->getCallee()->getBeginLoc(), 3901 diag::err_32_bit_builtin_64_bit_tgt); 3902 3903 // If the intrinsic has rounding or SAE make sure its valid. 3904 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3905 return true; 3906 3907 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3908 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3909 return true; 3910 3911 // If the intrinsic has a tile arguments, make sure they are valid. 3912 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3913 return true; 3914 3915 // For intrinsics which take an immediate value as part of the instruction, 3916 // range check them here. 3917 int i = 0, l = 0, u = 0; 3918 switch (BuiltinID) { 3919 default: 3920 return false; 3921 case X86::BI__builtin_ia32_vec_ext_v2si: 3922 case X86::BI__builtin_ia32_vec_ext_v2di: 3923 case X86::BI__builtin_ia32_vextractf128_pd256: 3924 case X86::BI__builtin_ia32_vextractf128_ps256: 3925 case X86::BI__builtin_ia32_vextractf128_si256: 3926 case X86::BI__builtin_ia32_extract128i256: 3927 case X86::BI__builtin_ia32_extractf64x4_mask: 3928 case X86::BI__builtin_ia32_extracti64x4_mask: 3929 case X86::BI__builtin_ia32_extractf32x8_mask: 3930 case X86::BI__builtin_ia32_extracti32x8_mask: 3931 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3932 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3933 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3934 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3935 i = 1; l = 0; u = 1; 3936 break; 3937 case X86::BI__builtin_ia32_vec_set_v2di: 3938 case X86::BI__builtin_ia32_vinsertf128_pd256: 3939 case X86::BI__builtin_ia32_vinsertf128_ps256: 3940 case X86::BI__builtin_ia32_vinsertf128_si256: 3941 case X86::BI__builtin_ia32_insert128i256: 3942 case X86::BI__builtin_ia32_insertf32x8: 3943 case X86::BI__builtin_ia32_inserti32x8: 3944 case X86::BI__builtin_ia32_insertf64x4: 3945 case X86::BI__builtin_ia32_inserti64x4: 3946 case X86::BI__builtin_ia32_insertf64x2_256: 3947 case X86::BI__builtin_ia32_inserti64x2_256: 3948 case X86::BI__builtin_ia32_insertf32x4_256: 3949 case X86::BI__builtin_ia32_inserti32x4_256: 3950 i = 2; l = 0; u = 1; 3951 break; 3952 case X86::BI__builtin_ia32_vpermilpd: 3953 case X86::BI__builtin_ia32_vec_ext_v4hi: 3954 case X86::BI__builtin_ia32_vec_ext_v4si: 3955 case X86::BI__builtin_ia32_vec_ext_v4sf: 3956 case X86::BI__builtin_ia32_vec_ext_v4di: 3957 case X86::BI__builtin_ia32_extractf32x4_mask: 3958 case X86::BI__builtin_ia32_extracti32x4_mask: 3959 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3960 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3961 i = 1; l = 0; u = 3; 3962 break; 3963 case X86::BI_mm_prefetch: 3964 case X86::BI__builtin_ia32_vec_ext_v8hi: 3965 case X86::BI__builtin_ia32_vec_ext_v8si: 3966 i = 1; l = 0; u = 7; 3967 break; 3968 case X86::BI__builtin_ia32_sha1rnds4: 3969 case X86::BI__builtin_ia32_blendpd: 3970 case X86::BI__builtin_ia32_shufpd: 3971 case X86::BI__builtin_ia32_vec_set_v4hi: 3972 case X86::BI__builtin_ia32_vec_set_v4si: 3973 case X86::BI__builtin_ia32_vec_set_v4di: 3974 case X86::BI__builtin_ia32_shuf_f32x4_256: 3975 case X86::BI__builtin_ia32_shuf_f64x2_256: 3976 case X86::BI__builtin_ia32_shuf_i32x4_256: 3977 case X86::BI__builtin_ia32_shuf_i64x2_256: 3978 case X86::BI__builtin_ia32_insertf64x2_512: 3979 case X86::BI__builtin_ia32_inserti64x2_512: 3980 case X86::BI__builtin_ia32_insertf32x4: 3981 case X86::BI__builtin_ia32_inserti32x4: 3982 i = 2; l = 0; u = 3; 3983 break; 3984 case X86::BI__builtin_ia32_vpermil2pd: 3985 case X86::BI__builtin_ia32_vpermil2pd256: 3986 case X86::BI__builtin_ia32_vpermil2ps: 3987 case X86::BI__builtin_ia32_vpermil2ps256: 3988 i = 3; l = 0; u = 3; 3989 break; 3990 case X86::BI__builtin_ia32_cmpb128_mask: 3991 case X86::BI__builtin_ia32_cmpw128_mask: 3992 case X86::BI__builtin_ia32_cmpd128_mask: 3993 case X86::BI__builtin_ia32_cmpq128_mask: 3994 case X86::BI__builtin_ia32_cmpb256_mask: 3995 case X86::BI__builtin_ia32_cmpw256_mask: 3996 case X86::BI__builtin_ia32_cmpd256_mask: 3997 case X86::BI__builtin_ia32_cmpq256_mask: 3998 case X86::BI__builtin_ia32_cmpb512_mask: 3999 case X86::BI__builtin_ia32_cmpw512_mask: 4000 case X86::BI__builtin_ia32_cmpd512_mask: 4001 case X86::BI__builtin_ia32_cmpq512_mask: 4002 case X86::BI__builtin_ia32_ucmpb128_mask: 4003 case X86::BI__builtin_ia32_ucmpw128_mask: 4004 case X86::BI__builtin_ia32_ucmpd128_mask: 4005 case X86::BI__builtin_ia32_ucmpq128_mask: 4006 case X86::BI__builtin_ia32_ucmpb256_mask: 4007 case X86::BI__builtin_ia32_ucmpw256_mask: 4008 case X86::BI__builtin_ia32_ucmpd256_mask: 4009 case X86::BI__builtin_ia32_ucmpq256_mask: 4010 case X86::BI__builtin_ia32_ucmpb512_mask: 4011 case X86::BI__builtin_ia32_ucmpw512_mask: 4012 case X86::BI__builtin_ia32_ucmpd512_mask: 4013 case X86::BI__builtin_ia32_ucmpq512_mask: 4014 case X86::BI__builtin_ia32_vpcomub: 4015 case X86::BI__builtin_ia32_vpcomuw: 4016 case X86::BI__builtin_ia32_vpcomud: 4017 case X86::BI__builtin_ia32_vpcomuq: 4018 case X86::BI__builtin_ia32_vpcomb: 4019 case X86::BI__builtin_ia32_vpcomw: 4020 case X86::BI__builtin_ia32_vpcomd: 4021 case X86::BI__builtin_ia32_vpcomq: 4022 case X86::BI__builtin_ia32_vec_set_v8hi: 4023 case X86::BI__builtin_ia32_vec_set_v8si: 4024 i = 2; l = 0; u = 7; 4025 break; 4026 case X86::BI__builtin_ia32_vpermilpd256: 4027 case X86::BI__builtin_ia32_roundps: 4028 case X86::BI__builtin_ia32_roundpd: 4029 case X86::BI__builtin_ia32_roundps256: 4030 case X86::BI__builtin_ia32_roundpd256: 4031 case X86::BI__builtin_ia32_getmantpd128_mask: 4032 case X86::BI__builtin_ia32_getmantpd256_mask: 4033 case X86::BI__builtin_ia32_getmantps128_mask: 4034 case X86::BI__builtin_ia32_getmantps256_mask: 4035 case X86::BI__builtin_ia32_getmantpd512_mask: 4036 case X86::BI__builtin_ia32_getmantps512_mask: 4037 case X86::BI__builtin_ia32_vec_ext_v16qi: 4038 case X86::BI__builtin_ia32_vec_ext_v16hi: 4039 i = 1; l = 0; u = 15; 4040 break; 4041 case X86::BI__builtin_ia32_pblendd128: 4042 case X86::BI__builtin_ia32_blendps: 4043 case X86::BI__builtin_ia32_blendpd256: 4044 case X86::BI__builtin_ia32_shufpd256: 4045 case X86::BI__builtin_ia32_roundss: 4046 case X86::BI__builtin_ia32_roundsd: 4047 case X86::BI__builtin_ia32_rangepd128_mask: 4048 case X86::BI__builtin_ia32_rangepd256_mask: 4049 case X86::BI__builtin_ia32_rangepd512_mask: 4050 case X86::BI__builtin_ia32_rangeps128_mask: 4051 case X86::BI__builtin_ia32_rangeps256_mask: 4052 case X86::BI__builtin_ia32_rangeps512_mask: 4053 case X86::BI__builtin_ia32_getmantsd_round_mask: 4054 case X86::BI__builtin_ia32_getmantss_round_mask: 4055 case X86::BI__builtin_ia32_vec_set_v16qi: 4056 case X86::BI__builtin_ia32_vec_set_v16hi: 4057 i = 2; l = 0; u = 15; 4058 break; 4059 case X86::BI__builtin_ia32_vec_ext_v32qi: 4060 i = 1; l = 0; u = 31; 4061 break; 4062 case X86::BI__builtin_ia32_cmpps: 4063 case X86::BI__builtin_ia32_cmpss: 4064 case X86::BI__builtin_ia32_cmppd: 4065 case X86::BI__builtin_ia32_cmpsd: 4066 case X86::BI__builtin_ia32_cmpps256: 4067 case X86::BI__builtin_ia32_cmppd256: 4068 case X86::BI__builtin_ia32_cmpps128_mask: 4069 case X86::BI__builtin_ia32_cmppd128_mask: 4070 case X86::BI__builtin_ia32_cmpps256_mask: 4071 case X86::BI__builtin_ia32_cmppd256_mask: 4072 case X86::BI__builtin_ia32_cmpps512_mask: 4073 case X86::BI__builtin_ia32_cmppd512_mask: 4074 case X86::BI__builtin_ia32_cmpsd_mask: 4075 case X86::BI__builtin_ia32_cmpss_mask: 4076 case X86::BI__builtin_ia32_vec_set_v32qi: 4077 i = 2; l = 0; u = 31; 4078 break; 4079 case X86::BI__builtin_ia32_permdf256: 4080 case X86::BI__builtin_ia32_permdi256: 4081 case X86::BI__builtin_ia32_permdf512: 4082 case X86::BI__builtin_ia32_permdi512: 4083 case X86::BI__builtin_ia32_vpermilps: 4084 case X86::BI__builtin_ia32_vpermilps256: 4085 case X86::BI__builtin_ia32_vpermilpd512: 4086 case X86::BI__builtin_ia32_vpermilps512: 4087 case X86::BI__builtin_ia32_pshufd: 4088 case X86::BI__builtin_ia32_pshufd256: 4089 case X86::BI__builtin_ia32_pshufd512: 4090 case X86::BI__builtin_ia32_pshufhw: 4091 case X86::BI__builtin_ia32_pshufhw256: 4092 case X86::BI__builtin_ia32_pshufhw512: 4093 case X86::BI__builtin_ia32_pshuflw: 4094 case X86::BI__builtin_ia32_pshuflw256: 4095 case X86::BI__builtin_ia32_pshuflw512: 4096 case X86::BI__builtin_ia32_vcvtps2ph: 4097 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4098 case X86::BI__builtin_ia32_vcvtps2ph256: 4099 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4100 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4101 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4102 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4103 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4104 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4105 case X86::BI__builtin_ia32_rndscaleps_mask: 4106 case X86::BI__builtin_ia32_rndscalepd_mask: 4107 case X86::BI__builtin_ia32_reducepd128_mask: 4108 case X86::BI__builtin_ia32_reducepd256_mask: 4109 case X86::BI__builtin_ia32_reducepd512_mask: 4110 case X86::BI__builtin_ia32_reduceps128_mask: 4111 case X86::BI__builtin_ia32_reduceps256_mask: 4112 case X86::BI__builtin_ia32_reduceps512_mask: 4113 case X86::BI__builtin_ia32_prold512: 4114 case X86::BI__builtin_ia32_prolq512: 4115 case X86::BI__builtin_ia32_prold128: 4116 case X86::BI__builtin_ia32_prold256: 4117 case X86::BI__builtin_ia32_prolq128: 4118 case X86::BI__builtin_ia32_prolq256: 4119 case X86::BI__builtin_ia32_prord512: 4120 case X86::BI__builtin_ia32_prorq512: 4121 case X86::BI__builtin_ia32_prord128: 4122 case X86::BI__builtin_ia32_prord256: 4123 case X86::BI__builtin_ia32_prorq128: 4124 case X86::BI__builtin_ia32_prorq256: 4125 case X86::BI__builtin_ia32_fpclasspd128_mask: 4126 case X86::BI__builtin_ia32_fpclasspd256_mask: 4127 case X86::BI__builtin_ia32_fpclassps128_mask: 4128 case X86::BI__builtin_ia32_fpclassps256_mask: 4129 case X86::BI__builtin_ia32_fpclassps512_mask: 4130 case X86::BI__builtin_ia32_fpclasspd512_mask: 4131 case X86::BI__builtin_ia32_fpclasssd_mask: 4132 case X86::BI__builtin_ia32_fpclassss_mask: 4133 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4134 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4135 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4136 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4137 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4138 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4139 case X86::BI__builtin_ia32_kshiftliqi: 4140 case X86::BI__builtin_ia32_kshiftlihi: 4141 case X86::BI__builtin_ia32_kshiftlisi: 4142 case X86::BI__builtin_ia32_kshiftlidi: 4143 case X86::BI__builtin_ia32_kshiftriqi: 4144 case X86::BI__builtin_ia32_kshiftrihi: 4145 case X86::BI__builtin_ia32_kshiftrisi: 4146 case X86::BI__builtin_ia32_kshiftridi: 4147 i = 1; l = 0; u = 255; 4148 break; 4149 case X86::BI__builtin_ia32_vperm2f128_pd256: 4150 case X86::BI__builtin_ia32_vperm2f128_ps256: 4151 case X86::BI__builtin_ia32_vperm2f128_si256: 4152 case X86::BI__builtin_ia32_permti256: 4153 case X86::BI__builtin_ia32_pblendw128: 4154 case X86::BI__builtin_ia32_pblendw256: 4155 case X86::BI__builtin_ia32_blendps256: 4156 case X86::BI__builtin_ia32_pblendd256: 4157 case X86::BI__builtin_ia32_palignr128: 4158 case X86::BI__builtin_ia32_palignr256: 4159 case X86::BI__builtin_ia32_palignr512: 4160 case X86::BI__builtin_ia32_alignq512: 4161 case X86::BI__builtin_ia32_alignd512: 4162 case X86::BI__builtin_ia32_alignd128: 4163 case X86::BI__builtin_ia32_alignd256: 4164 case X86::BI__builtin_ia32_alignq128: 4165 case X86::BI__builtin_ia32_alignq256: 4166 case X86::BI__builtin_ia32_vcomisd: 4167 case X86::BI__builtin_ia32_vcomiss: 4168 case X86::BI__builtin_ia32_shuf_f32x4: 4169 case X86::BI__builtin_ia32_shuf_f64x2: 4170 case X86::BI__builtin_ia32_shuf_i32x4: 4171 case X86::BI__builtin_ia32_shuf_i64x2: 4172 case X86::BI__builtin_ia32_shufpd512: 4173 case X86::BI__builtin_ia32_shufps: 4174 case X86::BI__builtin_ia32_shufps256: 4175 case X86::BI__builtin_ia32_shufps512: 4176 case X86::BI__builtin_ia32_dbpsadbw128: 4177 case X86::BI__builtin_ia32_dbpsadbw256: 4178 case X86::BI__builtin_ia32_dbpsadbw512: 4179 case X86::BI__builtin_ia32_vpshldd128: 4180 case X86::BI__builtin_ia32_vpshldd256: 4181 case X86::BI__builtin_ia32_vpshldd512: 4182 case X86::BI__builtin_ia32_vpshldq128: 4183 case X86::BI__builtin_ia32_vpshldq256: 4184 case X86::BI__builtin_ia32_vpshldq512: 4185 case X86::BI__builtin_ia32_vpshldw128: 4186 case X86::BI__builtin_ia32_vpshldw256: 4187 case X86::BI__builtin_ia32_vpshldw512: 4188 case X86::BI__builtin_ia32_vpshrdd128: 4189 case X86::BI__builtin_ia32_vpshrdd256: 4190 case X86::BI__builtin_ia32_vpshrdd512: 4191 case X86::BI__builtin_ia32_vpshrdq128: 4192 case X86::BI__builtin_ia32_vpshrdq256: 4193 case X86::BI__builtin_ia32_vpshrdq512: 4194 case X86::BI__builtin_ia32_vpshrdw128: 4195 case X86::BI__builtin_ia32_vpshrdw256: 4196 case X86::BI__builtin_ia32_vpshrdw512: 4197 i = 2; l = 0; u = 255; 4198 break; 4199 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4200 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4201 case X86::BI__builtin_ia32_fixupimmps512_mask: 4202 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4203 case X86::BI__builtin_ia32_fixupimmsd_mask: 4204 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4205 case X86::BI__builtin_ia32_fixupimmss_mask: 4206 case X86::BI__builtin_ia32_fixupimmss_maskz: 4207 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4208 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4209 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4210 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4211 case X86::BI__builtin_ia32_fixupimmps128_mask: 4212 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4213 case X86::BI__builtin_ia32_fixupimmps256_mask: 4214 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4215 case X86::BI__builtin_ia32_pternlogd512_mask: 4216 case X86::BI__builtin_ia32_pternlogd512_maskz: 4217 case X86::BI__builtin_ia32_pternlogq512_mask: 4218 case X86::BI__builtin_ia32_pternlogq512_maskz: 4219 case X86::BI__builtin_ia32_pternlogd128_mask: 4220 case X86::BI__builtin_ia32_pternlogd128_maskz: 4221 case X86::BI__builtin_ia32_pternlogd256_mask: 4222 case X86::BI__builtin_ia32_pternlogd256_maskz: 4223 case X86::BI__builtin_ia32_pternlogq128_mask: 4224 case X86::BI__builtin_ia32_pternlogq128_maskz: 4225 case X86::BI__builtin_ia32_pternlogq256_mask: 4226 case X86::BI__builtin_ia32_pternlogq256_maskz: 4227 i = 3; l = 0; u = 255; 4228 break; 4229 case X86::BI__builtin_ia32_gatherpfdpd: 4230 case X86::BI__builtin_ia32_gatherpfdps: 4231 case X86::BI__builtin_ia32_gatherpfqpd: 4232 case X86::BI__builtin_ia32_gatherpfqps: 4233 case X86::BI__builtin_ia32_scatterpfdpd: 4234 case X86::BI__builtin_ia32_scatterpfdps: 4235 case X86::BI__builtin_ia32_scatterpfqpd: 4236 case X86::BI__builtin_ia32_scatterpfqps: 4237 i = 4; l = 2; u = 3; 4238 break; 4239 case X86::BI__builtin_ia32_reducesd_mask: 4240 case X86::BI__builtin_ia32_reducess_mask: 4241 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4242 case X86::BI__builtin_ia32_rndscaless_round_mask: 4243 i = 4; l = 0; u = 255; 4244 break; 4245 } 4246 4247 // Note that we don't force a hard error on the range check here, allowing 4248 // template-generated or macro-generated dead code to potentially have out-of- 4249 // range values. These need to code generate, but don't need to necessarily 4250 // make any sense. We use a warning that defaults to an error. 4251 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4252 } 4253 4254 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4255 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4256 /// Returns true when the format fits the function and the FormatStringInfo has 4257 /// been populated. 4258 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4259 FormatStringInfo *FSI) { 4260 FSI->HasVAListArg = Format->getFirstArg() == 0; 4261 FSI->FormatIdx = Format->getFormatIdx() - 1; 4262 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4263 4264 // The way the format attribute works in GCC, the implicit this argument 4265 // of member functions is counted. However, it doesn't appear in our own 4266 // lists, so decrement format_idx in that case. 4267 if (IsCXXMember) { 4268 if(FSI->FormatIdx == 0) 4269 return false; 4270 --FSI->FormatIdx; 4271 if (FSI->FirstDataArg != 0) 4272 --FSI->FirstDataArg; 4273 } 4274 return true; 4275 } 4276 4277 /// Checks if a the given expression evaluates to null. 4278 /// 4279 /// Returns true if the value evaluates to null. 4280 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4281 // If the expression has non-null type, it doesn't evaluate to null. 4282 if (auto nullability 4283 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4284 if (*nullability == NullabilityKind::NonNull) 4285 return false; 4286 } 4287 4288 // As a special case, transparent unions initialized with zero are 4289 // considered null for the purposes of the nonnull attribute. 4290 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4291 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4292 if (const CompoundLiteralExpr *CLE = 4293 dyn_cast<CompoundLiteralExpr>(Expr)) 4294 if (const InitListExpr *ILE = 4295 dyn_cast<InitListExpr>(CLE->getInitializer())) 4296 Expr = ILE->getInit(0); 4297 } 4298 4299 bool Result; 4300 return (!Expr->isValueDependent() && 4301 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4302 !Result); 4303 } 4304 4305 static void CheckNonNullArgument(Sema &S, 4306 const Expr *ArgExpr, 4307 SourceLocation CallSiteLoc) { 4308 if (CheckNonNullExpr(S, ArgExpr)) 4309 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4310 S.PDiag(diag::warn_null_arg) 4311 << ArgExpr->getSourceRange()); 4312 } 4313 4314 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4315 FormatStringInfo FSI; 4316 if ((GetFormatStringType(Format) == FST_NSString) && 4317 getFormatStringInfo(Format, false, &FSI)) { 4318 Idx = FSI.FormatIdx; 4319 return true; 4320 } 4321 return false; 4322 } 4323 4324 /// Diagnose use of %s directive in an NSString which is being passed 4325 /// as formatting string to formatting method. 4326 static void 4327 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4328 const NamedDecl *FDecl, 4329 Expr **Args, 4330 unsigned NumArgs) { 4331 unsigned Idx = 0; 4332 bool Format = false; 4333 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4334 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4335 Idx = 2; 4336 Format = true; 4337 } 4338 else 4339 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4340 if (S.GetFormatNSStringIdx(I, Idx)) { 4341 Format = true; 4342 break; 4343 } 4344 } 4345 if (!Format || NumArgs <= Idx) 4346 return; 4347 const Expr *FormatExpr = Args[Idx]; 4348 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4349 FormatExpr = CSCE->getSubExpr(); 4350 const StringLiteral *FormatString; 4351 if (const ObjCStringLiteral *OSL = 4352 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4353 FormatString = OSL->getString(); 4354 else 4355 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4356 if (!FormatString) 4357 return; 4358 if (S.FormatStringHasSArg(FormatString)) { 4359 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4360 << "%s" << 1 << 1; 4361 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4362 << FDecl->getDeclName(); 4363 } 4364 } 4365 4366 /// Determine whether the given type has a non-null nullability annotation. 4367 static bool isNonNullType(ASTContext &ctx, QualType type) { 4368 if (auto nullability = type->getNullability(ctx)) 4369 return *nullability == NullabilityKind::NonNull; 4370 4371 return false; 4372 } 4373 4374 static void CheckNonNullArguments(Sema &S, 4375 const NamedDecl *FDecl, 4376 const FunctionProtoType *Proto, 4377 ArrayRef<const Expr *> Args, 4378 SourceLocation CallSiteLoc) { 4379 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4380 4381 // Already checked by by constant evaluator. 4382 if (S.isConstantEvaluated()) 4383 return; 4384 // Check the attributes attached to the method/function itself. 4385 llvm::SmallBitVector NonNullArgs; 4386 if (FDecl) { 4387 // Handle the nonnull attribute on the function/method declaration itself. 4388 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4389 if (!NonNull->args_size()) { 4390 // Easy case: all pointer arguments are nonnull. 4391 for (const auto *Arg : Args) 4392 if (S.isValidPointerAttrType(Arg->getType())) 4393 CheckNonNullArgument(S, Arg, CallSiteLoc); 4394 return; 4395 } 4396 4397 for (const ParamIdx &Idx : NonNull->args()) { 4398 unsigned IdxAST = Idx.getASTIndex(); 4399 if (IdxAST >= Args.size()) 4400 continue; 4401 if (NonNullArgs.empty()) 4402 NonNullArgs.resize(Args.size()); 4403 NonNullArgs.set(IdxAST); 4404 } 4405 } 4406 } 4407 4408 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4409 // Handle the nonnull attribute on the parameters of the 4410 // function/method. 4411 ArrayRef<ParmVarDecl*> parms; 4412 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4413 parms = FD->parameters(); 4414 else 4415 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4416 4417 unsigned ParamIndex = 0; 4418 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4419 I != E; ++I, ++ParamIndex) { 4420 const ParmVarDecl *PVD = *I; 4421 if (PVD->hasAttr<NonNullAttr>() || 4422 isNonNullType(S.Context, PVD->getType())) { 4423 if (NonNullArgs.empty()) 4424 NonNullArgs.resize(Args.size()); 4425 4426 NonNullArgs.set(ParamIndex); 4427 } 4428 } 4429 } else { 4430 // If we have a non-function, non-method declaration but no 4431 // function prototype, try to dig out the function prototype. 4432 if (!Proto) { 4433 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4434 QualType type = VD->getType().getNonReferenceType(); 4435 if (auto pointerType = type->getAs<PointerType>()) 4436 type = pointerType->getPointeeType(); 4437 else if (auto blockType = type->getAs<BlockPointerType>()) 4438 type = blockType->getPointeeType(); 4439 // FIXME: data member pointers? 4440 4441 // Dig out the function prototype, if there is one. 4442 Proto = type->getAs<FunctionProtoType>(); 4443 } 4444 } 4445 4446 // Fill in non-null argument information from the nullability 4447 // information on the parameter types (if we have them). 4448 if (Proto) { 4449 unsigned Index = 0; 4450 for (auto paramType : Proto->getParamTypes()) { 4451 if (isNonNullType(S.Context, paramType)) { 4452 if (NonNullArgs.empty()) 4453 NonNullArgs.resize(Args.size()); 4454 4455 NonNullArgs.set(Index); 4456 } 4457 4458 ++Index; 4459 } 4460 } 4461 } 4462 4463 // Check for non-null arguments. 4464 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4465 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4466 if (NonNullArgs[ArgIndex]) 4467 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4468 } 4469 } 4470 4471 /// Handles the checks for format strings, non-POD arguments to vararg 4472 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4473 /// attributes. 4474 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4475 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4476 bool IsMemberFunction, SourceLocation Loc, 4477 SourceRange Range, VariadicCallType CallType) { 4478 // FIXME: We should check as much as we can in the template definition. 4479 if (CurContext->isDependentContext()) 4480 return; 4481 4482 // Printf and scanf checking. 4483 llvm::SmallBitVector CheckedVarArgs; 4484 if (FDecl) { 4485 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4486 // Only create vector if there are format attributes. 4487 CheckedVarArgs.resize(Args.size()); 4488 4489 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4490 CheckedVarArgs); 4491 } 4492 } 4493 4494 // Refuse POD arguments that weren't caught by the format string 4495 // checks above. 4496 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4497 if (CallType != VariadicDoesNotApply && 4498 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4499 unsigned NumParams = Proto ? Proto->getNumParams() 4500 : FDecl && isa<FunctionDecl>(FDecl) 4501 ? cast<FunctionDecl>(FDecl)->getNumParams() 4502 : FDecl && isa<ObjCMethodDecl>(FDecl) 4503 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4504 : 0; 4505 4506 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4507 // Args[ArgIdx] can be null in malformed code. 4508 if (const Expr *Arg = Args[ArgIdx]) { 4509 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4510 checkVariadicArgument(Arg, CallType); 4511 } 4512 } 4513 } 4514 4515 if (FDecl || Proto) { 4516 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4517 4518 // Type safety checking. 4519 if (FDecl) { 4520 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4521 CheckArgumentWithTypeTag(I, Args, Loc); 4522 } 4523 } 4524 4525 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4526 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4527 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4528 if (!Arg->isValueDependent()) { 4529 Expr::EvalResult Align; 4530 if (Arg->EvaluateAsInt(Align, Context)) { 4531 const llvm::APSInt &I = Align.Val.getInt(); 4532 if (!I.isPowerOf2()) 4533 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4534 << Arg->getSourceRange(); 4535 4536 if (I > Sema::MaximumAlignment) 4537 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4538 << Arg->getSourceRange() << Sema::MaximumAlignment; 4539 } 4540 } 4541 } 4542 4543 if (FD) 4544 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4545 } 4546 4547 /// CheckConstructorCall - Check a constructor call for correctness and safety 4548 /// properties not enforced by the C type system. 4549 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4550 ArrayRef<const Expr *> Args, 4551 const FunctionProtoType *Proto, 4552 SourceLocation Loc) { 4553 VariadicCallType CallType = 4554 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4555 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4556 Loc, SourceRange(), CallType); 4557 } 4558 4559 /// CheckFunctionCall - Check a direct function call for various correctness 4560 /// and safety properties not strictly enforced by the C type system. 4561 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4562 const FunctionProtoType *Proto) { 4563 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4564 isa<CXXMethodDecl>(FDecl); 4565 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4566 IsMemberOperatorCall; 4567 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4568 TheCall->getCallee()); 4569 Expr** Args = TheCall->getArgs(); 4570 unsigned NumArgs = TheCall->getNumArgs(); 4571 4572 Expr *ImplicitThis = nullptr; 4573 if (IsMemberOperatorCall) { 4574 // If this is a call to a member operator, hide the first argument 4575 // from checkCall. 4576 // FIXME: Our choice of AST representation here is less than ideal. 4577 ImplicitThis = Args[0]; 4578 ++Args; 4579 --NumArgs; 4580 } else if (IsMemberFunction) 4581 ImplicitThis = 4582 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4583 4584 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4585 IsMemberFunction, TheCall->getRParenLoc(), 4586 TheCall->getCallee()->getSourceRange(), CallType); 4587 4588 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4589 // None of the checks below are needed for functions that don't have 4590 // simple names (e.g., C++ conversion functions). 4591 if (!FnInfo) 4592 return false; 4593 4594 CheckTCBEnforcement(TheCall, FDecl); 4595 4596 CheckAbsoluteValueFunction(TheCall, FDecl); 4597 CheckMaxUnsignedZero(TheCall, FDecl); 4598 4599 if (getLangOpts().ObjC) 4600 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4601 4602 unsigned CMId = FDecl->getMemoryFunctionKind(); 4603 4604 // Handle memory setting and copying functions. 4605 switch (CMId) { 4606 case 0: 4607 return false; 4608 case Builtin::BIstrlcpy: // fallthrough 4609 case Builtin::BIstrlcat: 4610 CheckStrlcpycatArguments(TheCall, FnInfo); 4611 break; 4612 case Builtin::BIstrncat: 4613 CheckStrncatArguments(TheCall, FnInfo); 4614 break; 4615 case Builtin::BIfree: 4616 CheckFreeArguments(TheCall); 4617 break; 4618 default: 4619 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4620 } 4621 4622 return false; 4623 } 4624 4625 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4626 ArrayRef<const Expr *> Args) { 4627 VariadicCallType CallType = 4628 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4629 4630 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4631 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4632 CallType); 4633 4634 return false; 4635 } 4636 4637 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4638 const FunctionProtoType *Proto) { 4639 QualType Ty; 4640 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4641 Ty = V->getType().getNonReferenceType(); 4642 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4643 Ty = F->getType().getNonReferenceType(); 4644 else 4645 return false; 4646 4647 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4648 !Ty->isFunctionProtoType()) 4649 return false; 4650 4651 VariadicCallType CallType; 4652 if (!Proto || !Proto->isVariadic()) { 4653 CallType = VariadicDoesNotApply; 4654 } else if (Ty->isBlockPointerType()) { 4655 CallType = VariadicBlock; 4656 } else { // Ty->isFunctionPointerType() 4657 CallType = VariadicFunction; 4658 } 4659 4660 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4661 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4662 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4663 TheCall->getCallee()->getSourceRange(), CallType); 4664 4665 return false; 4666 } 4667 4668 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4669 /// such as function pointers returned from functions. 4670 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4671 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4672 TheCall->getCallee()); 4673 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4674 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4675 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4676 TheCall->getCallee()->getSourceRange(), CallType); 4677 4678 return false; 4679 } 4680 4681 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4682 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4683 return false; 4684 4685 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4686 switch (Op) { 4687 case AtomicExpr::AO__c11_atomic_init: 4688 case AtomicExpr::AO__opencl_atomic_init: 4689 llvm_unreachable("There is no ordering argument for an init"); 4690 4691 case AtomicExpr::AO__c11_atomic_load: 4692 case AtomicExpr::AO__opencl_atomic_load: 4693 case AtomicExpr::AO__atomic_load_n: 4694 case AtomicExpr::AO__atomic_load: 4695 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4696 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4697 4698 case AtomicExpr::AO__c11_atomic_store: 4699 case AtomicExpr::AO__opencl_atomic_store: 4700 case AtomicExpr::AO__atomic_store: 4701 case AtomicExpr::AO__atomic_store_n: 4702 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4703 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4704 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4705 4706 default: 4707 return true; 4708 } 4709 } 4710 4711 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4712 AtomicExpr::AtomicOp Op) { 4713 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4714 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4715 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4716 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4717 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4718 Op); 4719 } 4720 4721 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4722 SourceLocation RParenLoc, MultiExprArg Args, 4723 AtomicExpr::AtomicOp Op, 4724 AtomicArgumentOrder ArgOrder) { 4725 // All the non-OpenCL operations take one of the following forms. 4726 // The OpenCL operations take the __c11 forms with one extra argument for 4727 // synchronization scope. 4728 enum { 4729 // C __c11_atomic_init(A *, C) 4730 Init, 4731 4732 // C __c11_atomic_load(A *, int) 4733 Load, 4734 4735 // void __atomic_load(A *, CP, int) 4736 LoadCopy, 4737 4738 // void __atomic_store(A *, CP, int) 4739 Copy, 4740 4741 // C __c11_atomic_add(A *, M, int) 4742 Arithmetic, 4743 4744 // C __atomic_exchange_n(A *, CP, int) 4745 Xchg, 4746 4747 // void __atomic_exchange(A *, C *, CP, int) 4748 GNUXchg, 4749 4750 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4751 C11CmpXchg, 4752 4753 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4754 GNUCmpXchg 4755 } Form = Init; 4756 4757 const unsigned NumForm = GNUCmpXchg + 1; 4758 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4759 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4760 // where: 4761 // C is an appropriate type, 4762 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4763 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4764 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4765 // the int parameters are for orderings. 4766 4767 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4768 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4769 "need to update code for modified forms"); 4770 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4771 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4772 AtomicExpr::AO__atomic_load, 4773 "need to update code for modified C11 atomics"); 4774 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4775 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4776 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4777 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4778 IsOpenCL; 4779 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4780 Op == AtomicExpr::AO__atomic_store_n || 4781 Op == AtomicExpr::AO__atomic_exchange_n || 4782 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4783 bool IsAddSub = false; 4784 4785 switch (Op) { 4786 case AtomicExpr::AO__c11_atomic_init: 4787 case AtomicExpr::AO__opencl_atomic_init: 4788 Form = Init; 4789 break; 4790 4791 case AtomicExpr::AO__c11_atomic_load: 4792 case AtomicExpr::AO__opencl_atomic_load: 4793 case AtomicExpr::AO__atomic_load_n: 4794 Form = Load; 4795 break; 4796 4797 case AtomicExpr::AO__atomic_load: 4798 Form = LoadCopy; 4799 break; 4800 4801 case AtomicExpr::AO__c11_atomic_store: 4802 case AtomicExpr::AO__opencl_atomic_store: 4803 case AtomicExpr::AO__atomic_store: 4804 case AtomicExpr::AO__atomic_store_n: 4805 Form = Copy; 4806 break; 4807 4808 case AtomicExpr::AO__c11_atomic_fetch_add: 4809 case AtomicExpr::AO__c11_atomic_fetch_sub: 4810 case AtomicExpr::AO__opencl_atomic_fetch_add: 4811 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4812 case AtomicExpr::AO__atomic_fetch_add: 4813 case AtomicExpr::AO__atomic_fetch_sub: 4814 case AtomicExpr::AO__atomic_add_fetch: 4815 case AtomicExpr::AO__atomic_sub_fetch: 4816 IsAddSub = true; 4817 LLVM_FALLTHROUGH; 4818 case AtomicExpr::AO__c11_atomic_fetch_and: 4819 case AtomicExpr::AO__c11_atomic_fetch_or: 4820 case AtomicExpr::AO__c11_atomic_fetch_xor: 4821 case AtomicExpr::AO__opencl_atomic_fetch_and: 4822 case AtomicExpr::AO__opencl_atomic_fetch_or: 4823 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4824 case AtomicExpr::AO__atomic_fetch_and: 4825 case AtomicExpr::AO__atomic_fetch_or: 4826 case AtomicExpr::AO__atomic_fetch_xor: 4827 case AtomicExpr::AO__atomic_fetch_nand: 4828 case AtomicExpr::AO__atomic_and_fetch: 4829 case AtomicExpr::AO__atomic_or_fetch: 4830 case AtomicExpr::AO__atomic_xor_fetch: 4831 case AtomicExpr::AO__atomic_nand_fetch: 4832 case AtomicExpr::AO__c11_atomic_fetch_min: 4833 case AtomicExpr::AO__c11_atomic_fetch_max: 4834 case AtomicExpr::AO__opencl_atomic_fetch_min: 4835 case AtomicExpr::AO__opencl_atomic_fetch_max: 4836 case AtomicExpr::AO__atomic_min_fetch: 4837 case AtomicExpr::AO__atomic_max_fetch: 4838 case AtomicExpr::AO__atomic_fetch_min: 4839 case AtomicExpr::AO__atomic_fetch_max: 4840 Form = Arithmetic; 4841 break; 4842 4843 case AtomicExpr::AO__c11_atomic_exchange: 4844 case AtomicExpr::AO__opencl_atomic_exchange: 4845 case AtomicExpr::AO__atomic_exchange_n: 4846 Form = Xchg; 4847 break; 4848 4849 case AtomicExpr::AO__atomic_exchange: 4850 Form = GNUXchg; 4851 break; 4852 4853 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4854 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4855 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4856 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4857 Form = C11CmpXchg; 4858 break; 4859 4860 case AtomicExpr::AO__atomic_compare_exchange: 4861 case AtomicExpr::AO__atomic_compare_exchange_n: 4862 Form = GNUCmpXchg; 4863 break; 4864 } 4865 4866 unsigned AdjustedNumArgs = NumArgs[Form]; 4867 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4868 ++AdjustedNumArgs; 4869 // Check we have the right number of arguments. 4870 if (Args.size() < AdjustedNumArgs) { 4871 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4872 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4873 << ExprRange; 4874 return ExprError(); 4875 } else if (Args.size() > AdjustedNumArgs) { 4876 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4877 diag::err_typecheck_call_too_many_args) 4878 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4879 << ExprRange; 4880 return ExprError(); 4881 } 4882 4883 // Inspect the first argument of the atomic operation. 4884 Expr *Ptr = Args[0]; 4885 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4886 if (ConvertedPtr.isInvalid()) 4887 return ExprError(); 4888 4889 Ptr = ConvertedPtr.get(); 4890 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4891 if (!pointerType) { 4892 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4893 << Ptr->getType() << Ptr->getSourceRange(); 4894 return ExprError(); 4895 } 4896 4897 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4898 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4899 QualType ValType = AtomTy; // 'C' 4900 if (IsC11) { 4901 if (!AtomTy->isAtomicType()) { 4902 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4903 << Ptr->getType() << Ptr->getSourceRange(); 4904 return ExprError(); 4905 } 4906 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4907 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4908 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4909 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4910 << Ptr->getSourceRange(); 4911 return ExprError(); 4912 } 4913 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4914 } else if (Form != Load && Form != LoadCopy) { 4915 if (ValType.isConstQualified()) { 4916 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4917 << Ptr->getType() << Ptr->getSourceRange(); 4918 return ExprError(); 4919 } 4920 } 4921 4922 // For an arithmetic operation, the implied arithmetic must be well-formed. 4923 if (Form == Arithmetic) { 4924 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4925 if (IsAddSub && !ValType->isIntegerType() 4926 && !ValType->isPointerType()) { 4927 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4928 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4929 return ExprError(); 4930 } 4931 if (!IsAddSub && !ValType->isIntegerType()) { 4932 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4933 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4934 return ExprError(); 4935 } 4936 if (IsC11 && ValType->isPointerType() && 4937 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4938 diag::err_incomplete_type)) { 4939 return ExprError(); 4940 } 4941 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4942 // For __atomic_*_n operations, the value type must be a scalar integral or 4943 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4944 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4945 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4946 return ExprError(); 4947 } 4948 4949 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4950 !AtomTy->isScalarType()) { 4951 // For GNU atomics, require a trivially-copyable type. This is not part of 4952 // the GNU atomics specification, but we enforce it for sanity. 4953 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4954 << Ptr->getType() << Ptr->getSourceRange(); 4955 return ExprError(); 4956 } 4957 4958 switch (ValType.getObjCLifetime()) { 4959 case Qualifiers::OCL_None: 4960 case Qualifiers::OCL_ExplicitNone: 4961 // okay 4962 break; 4963 4964 case Qualifiers::OCL_Weak: 4965 case Qualifiers::OCL_Strong: 4966 case Qualifiers::OCL_Autoreleasing: 4967 // FIXME: Can this happen? By this point, ValType should be known 4968 // to be trivially copyable. 4969 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4970 << ValType << Ptr->getSourceRange(); 4971 return ExprError(); 4972 } 4973 4974 // All atomic operations have an overload which takes a pointer to a volatile 4975 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4976 // into the result or the other operands. Similarly atomic_load takes a 4977 // pointer to a const 'A'. 4978 ValType.removeLocalVolatile(); 4979 ValType.removeLocalConst(); 4980 QualType ResultType = ValType; 4981 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4982 Form == Init) 4983 ResultType = Context.VoidTy; 4984 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4985 ResultType = Context.BoolTy; 4986 4987 // The type of a parameter passed 'by value'. In the GNU atomics, such 4988 // arguments are actually passed as pointers. 4989 QualType ByValType = ValType; // 'CP' 4990 bool IsPassedByAddress = false; 4991 if (!IsC11 && !IsN) { 4992 ByValType = Ptr->getType(); 4993 IsPassedByAddress = true; 4994 } 4995 4996 SmallVector<Expr *, 5> APIOrderedArgs; 4997 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4998 APIOrderedArgs.push_back(Args[0]); 4999 switch (Form) { 5000 case Init: 5001 case Load: 5002 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5003 break; 5004 case LoadCopy: 5005 case Copy: 5006 case Arithmetic: 5007 case Xchg: 5008 APIOrderedArgs.push_back(Args[2]); // Val1 5009 APIOrderedArgs.push_back(Args[1]); // Order 5010 break; 5011 case GNUXchg: 5012 APIOrderedArgs.push_back(Args[2]); // Val1 5013 APIOrderedArgs.push_back(Args[3]); // Val2 5014 APIOrderedArgs.push_back(Args[1]); // Order 5015 break; 5016 case C11CmpXchg: 5017 APIOrderedArgs.push_back(Args[2]); // Val1 5018 APIOrderedArgs.push_back(Args[4]); // Val2 5019 APIOrderedArgs.push_back(Args[1]); // Order 5020 APIOrderedArgs.push_back(Args[3]); // OrderFail 5021 break; 5022 case GNUCmpXchg: 5023 APIOrderedArgs.push_back(Args[2]); // Val1 5024 APIOrderedArgs.push_back(Args[4]); // Val2 5025 APIOrderedArgs.push_back(Args[5]); // Weak 5026 APIOrderedArgs.push_back(Args[1]); // Order 5027 APIOrderedArgs.push_back(Args[3]); // OrderFail 5028 break; 5029 } 5030 } else 5031 APIOrderedArgs.append(Args.begin(), Args.end()); 5032 5033 // The first argument's non-CV pointer type is used to deduce the type of 5034 // subsequent arguments, except for: 5035 // - weak flag (always converted to bool) 5036 // - memory order (always converted to int) 5037 // - scope (always converted to int) 5038 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5039 QualType Ty; 5040 if (i < NumVals[Form] + 1) { 5041 switch (i) { 5042 case 0: 5043 // The first argument is always a pointer. It has a fixed type. 5044 // It is always dereferenced, a nullptr is undefined. 5045 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5046 // Nothing else to do: we already know all we want about this pointer. 5047 continue; 5048 case 1: 5049 // The second argument is the non-atomic operand. For arithmetic, this 5050 // is always passed by value, and for a compare_exchange it is always 5051 // passed by address. For the rest, GNU uses by-address and C11 uses 5052 // by-value. 5053 assert(Form != Load); 5054 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 5055 Ty = ValType; 5056 else if (Form == Copy || Form == Xchg) { 5057 if (IsPassedByAddress) { 5058 // The value pointer is always dereferenced, a nullptr is undefined. 5059 CheckNonNullArgument(*this, APIOrderedArgs[i], 5060 ExprRange.getBegin()); 5061 } 5062 Ty = ByValType; 5063 } else if (Form == Arithmetic) 5064 Ty = Context.getPointerDiffType(); 5065 else { 5066 Expr *ValArg = APIOrderedArgs[i]; 5067 // The value pointer is always dereferenced, a nullptr is undefined. 5068 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5069 LangAS AS = LangAS::Default; 5070 // Keep address space of non-atomic pointer type. 5071 if (const PointerType *PtrTy = 5072 ValArg->getType()->getAs<PointerType>()) { 5073 AS = PtrTy->getPointeeType().getAddressSpace(); 5074 } 5075 Ty = Context.getPointerType( 5076 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5077 } 5078 break; 5079 case 2: 5080 // The third argument to compare_exchange / GNU exchange is the desired 5081 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5082 if (IsPassedByAddress) 5083 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5084 Ty = ByValType; 5085 break; 5086 case 3: 5087 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5088 Ty = Context.BoolTy; 5089 break; 5090 } 5091 } else { 5092 // The order(s) and scope are always converted to int. 5093 Ty = Context.IntTy; 5094 } 5095 5096 InitializedEntity Entity = 5097 InitializedEntity::InitializeParameter(Context, Ty, false); 5098 ExprResult Arg = APIOrderedArgs[i]; 5099 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5100 if (Arg.isInvalid()) 5101 return true; 5102 APIOrderedArgs[i] = Arg.get(); 5103 } 5104 5105 // Permute the arguments into a 'consistent' order. 5106 SmallVector<Expr*, 5> SubExprs; 5107 SubExprs.push_back(Ptr); 5108 switch (Form) { 5109 case Init: 5110 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5111 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5112 break; 5113 case Load: 5114 SubExprs.push_back(APIOrderedArgs[1]); // Order 5115 break; 5116 case LoadCopy: 5117 case Copy: 5118 case Arithmetic: 5119 case Xchg: 5120 SubExprs.push_back(APIOrderedArgs[2]); // Order 5121 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5122 break; 5123 case GNUXchg: 5124 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5125 SubExprs.push_back(APIOrderedArgs[3]); // Order 5126 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5127 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5128 break; 5129 case C11CmpXchg: 5130 SubExprs.push_back(APIOrderedArgs[3]); // Order 5131 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5132 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5133 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5134 break; 5135 case GNUCmpXchg: 5136 SubExprs.push_back(APIOrderedArgs[4]); // Order 5137 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5138 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5139 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5140 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5141 break; 5142 } 5143 5144 if (SubExprs.size() >= 2 && Form != Init) { 5145 if (Optional<llvm::APSInt> Result = 5146 SubExprs[1]->getIntegerConstantExpr(Context)) 5147 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5148 Diag(SubExprs[1]->getBeginLoc(), 5149 diag::warn_atomic_op_has_invalid_memory_order) 5150 << SubExprs[1]->getSourceRange(); 5151 } 5152 5153 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5154 auto *Scope = Args[Args.size() - 1]; 5155 if (Optional<llvm::APSInt> Result = 5156 Scope->getIntegerConstantExpr(Context)) { 5157 if (!ScopeModel->isValid(Result->getZExtValue())) 5158 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5159 << Scope->getSourceRange(); 5160 } 5161 SubExprs.push_back(Scope); 5162 } 5163 5164 AtomicExpr *AE = new (Context) 5165 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5166 5167 if ((Op == AtomicExpr::AO__c11_atomic_load || 5168 Op == AtomicExpr::AO__c11_atomic_store || 5169 Op == AtomicExpr::AO__opencl_atomic_load || 5170 Op == AtomicExpr::AO__opencl_atomic_store ) && 5171 Context.AtomicUsesUnsupportedLibcall(AE)) 5172 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5173 << ((Op == AtomicExpr::AO__c11_atomic_load || 5174 Op == AtomicExpr::AO__opencl_atomic_load) 5175 ? 0 5176 : 1); 5177 5178 if (ValType->isExtIntType()) { 5179 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5180 return ExprError(); 5181 } 5182 5183 return AE; 5184 } 5185 5186 /// checkBuiltinArgument - Given a call to a builtin function, perform 5187 /// normal type-checking on the given argument, updating the call in 5188 /// place. This is useful when a builtin function requires custom 5189 /// type-checking for some of its arguments but not necessarily all of 5190 /// them. 5191 /// 5192 /// Returns true on error. 5193 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5194 FunctionDecl *Fn = E->getDirectCallee(); 5195 assert(Fn && "builtin call without direct callee!"); 5196 5197 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5198 InitializedEntity Entity = 5199 InitializedEntity::InitializeParameter(S.Context, Param); 5200 5201 ExprResult Arg = E->getArg(0); 5202 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5203 if (Arg.isInvalid()) 5204 return true; 5205 5206 E->setArg(ArgIndex, Arg.get()); 5207 return false; 5208 } 5209 5210 /// We have a call to a function like __sync_fetch_and_add, which is an 5211 /// overloaded function based on the pointer type of its first argument. 5212 /// The main BuildCallExpr routines have already promoted the types of 5213 /// arguments because all of these calls are prototyped as void(...). 5214 /// 5215 /// This function goes through and does final semantic checking for these 5216 /// builtins, as well as generating any warnings. 5217 ExprResult 5218 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5219 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5220 Expr *Callee = TheCall->getCallee(); 5221 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5222 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5223 5224 // Ensure that we have at least one argument to do type inference from. 5225 if (TheCall->getNumArgs() < 1) { 5226 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5227 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5228 return ExprError(); 5229 } 5230 5231 // Inspect the first argument of the atomic builtin. This should always be 5232 // a pointer type, whose element is an integral scalar or pointer type. 5233 // Because it is a pointer type, we don't have to worry about any implicit 5234 // casts here. 5235 // FIXME: We don't allow floating point scalars as input. 5236 Expr *FirstArg = TheCall->getArg(0); 5237 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5238 if (FirstArgResult.isInvalid()) 5239 return ExprError(); 5240 FirstArg = FirstArgResult.get(); 5241 TheCall->setArg(0, FirstArg); 5242 5243 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5244 if (!pointerType) { 5245 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5246 << FirstArg->getType() << FirstArg->getSourceRange(); 5247 return ExprError(); 5248 } 5249 5250 QualType ValType = pointerType->getPointeeType(); 5251 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5252 !ValType->isBlockPointerType()) { 5253 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5254 << FirstArg->getType() << FirstArg->getSourceRange(); 5255 return ExprError(); 5256 } 5257 5258 if (ValType.isConstQualified()) { 5259 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5260 << FirstArg->getType() << FirstArg->getSourceRange(); 5261 return ExprError(); 5262 } 5263 5264 switch (ValType.getObjCLifetime()) { 5265 case Qualifiers::OCL_None: 5266 case Qualifiers::OCL_ExplicitNone: 5267 // okay 5268 break; 5269 5270 case Qualifiers::OCL_Weak: 5271 case Qualifiers::OCL_Strong: 5272 case Qualifiers::OCL_Autoreleasing: 5273 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5274 << ValType << FirstArg->getSourceRange(); 5275 return ExprError(); 5276 } 5277 5278 // Strip any qualifiers off ValType. 5279 ValType = ValType.getUnqualifiedType(); 5280 5281 // The majority of builtins return a value, but a few have special return 5282 // types, so allow them to override appropriately below. 5283 QualType ResultType = ValType; 5284 5285 // We need to figure out which concrete builtin this maps onto. For example, 5286 // __sync_fetch_and_add with a 2 byte object turns into 5287 // __sync_fetch_and_add_2. 5288 #define BUILTIN_ROW(x) \ 5289 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5290 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5291 5292 static const unsigned BuiltinIndices[][5] = { 5293 BUILTIN_ROW(__sync_fetch_and_add), 5294 BUILTIN_ROW(__sync_fetch_and_sub), 5295 BUILTIN_ROW(__sync_fetch_and_or), 5296 BUILTIN_ROW(__sync_fetch_and_and), 5297 BUILTIN_ROW(__sync_fetch_and_xor), 5298 BUILTIN_ROW(__sync_fetch_and_nand), 5299 5300 BUILTIN_ROW(__sync_add_and_fetch), 5301 BUILTIN_ROW(__sync_sub_and_fetch), 5302 BUILTIN_ROW(__sync_and_and_fetch), 5303 BUILTIN_ROW(__sync_or_and_fetch), 5304 BUILTIN_ROW(__sync_xor_and_fetch), 5305 BUILTIN_ROW(__sync_nand_and_fetch), 5306 5307 BUILTIN_ROW(__sync_val_compare_and_swap), 5308 BUILTIN_ROW(__sync_bool_compare_and_swap), 5309 BUILTIN_ROW(__sync_lock_test_and_set), 5310 BUILTIN_ROW(__sync_lock_release), 5311 BUILTIN_ROW(__sync_swap) 5312 }; 5313 #undef BUILTIN_ROW 5314 5315 // Determine the index of the size. 5316 unsigned SizeIndex; 5317 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5318 case 1: SizeIndex = 0; break; 5319 case 2: SizeIndex = 1; break; 5320 case 4: SizeIndex = 2; break; 5321 case 8: SizeIndex = 3; break; 5322 case 16: SizeIndex = 4; break; 5323 default: 5324 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5325 << FirstArg->getType() << FirstArg->getSourceRange(); 5326 return ExprError(); 5327 } 5328 5329 // Each of these builtins has one pointer argument, followed by some number of 5330 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5331 // that we ignore. Find out which row of BuiltinIndices to read from as well 5332 // as the number of fixed args. 5333 unsigned BuiltinID = FDecl->getBuiltinID(); 5334 unsigned BuiltinIndex, NumFixed = 1; 5335 bool WarnAboutSemanticsChange = false; 5336 switch (BuiltinID) { 5337 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5338 case Builtin::BI__sync_fetch_and_add: 5339 case Builtin::BI__sync_fetch_and_add_1: 5340 case Builtin::BI__sync_fetch_and_add_2: 5341 case Builtin::BI__sync_fetch_and_add_4: 5342 case Builtin::BI__sync_fetch_and_add_8: 5343 case Builtin::BI__sync_fetch_and_add_16: 5344 BuiltinIndex = 0; 5345 break; 5346 5347 case Builtin::BI__sync_fetch_and_sub: 5348 case Builtin::BI__sync_fetch_and_sub_1: 5349 case Builtin::BI__sync_fetch_and_sub_2: 5350 case Builtin::BI__sync_fetch_and_sub_4: 5351 case Builtin::BI__sync_fetch_and_sub_8: 5352 case Builtin::BI__sync_fetch_and_sub_16: 5353 BuiltinIndex = 1; 5354 break; 5355 5356 case Builtin::BI__sync_fetch_and_or: 5357 case Builtin::BI__sync_fetch_and_or_1: 5358 case Builtin::BI__sync_fetch_and_or_2: 5359 case Builtin::BI__sync_fetch_and_or_4: 5360 case Builtin::BI__sync_fetch_and_or_8: 5361 case Builtin::BI__sync_fetch_and_or_16: 5362 BuiltinIndex = 2; 5363 break; 5364 5365 case Builtin::BI__sync_fetch_and_and: 5366 case Builtin::BI__sync_fetch_and_and_1: 5367 case Builtin::BI__sync_fetch_and_and_2: 5368 case Builtin::BI__sync_fetch_and_and_4: 5369 case Builtin::BI__sync_fetch_and_and_8: 5370 case Builtin::BI__sync_fetch_and_and_16: 5371 BuiltinIndex = 3; 5372 break; 5373 5374 case Builtin::BI__sync_fetch_and_xor: 5375 case Builtin::BI__sync_fetch_and_xor_1: 5376 case Builtin::BI__sync_fetch_and_xor_2: 5377 case Builtin::BI__sync_fetch_and_xor_4: 5378 case Builtin::BI__sync_fetch_and_xor_8: 5379 case Builtin::BI__sync_fetch_and_xor_16: 5380 BuiltinIndex = 4; 5381 break; 5382 5383 case Builtin::BI__sync_fetch_and_nand: 5384 case Builtin::BI__sync_fetch_and_nand_1: 5385 case Builtin::BI__sync_fetch_and_nand_2: 5386 case Builtin::BI__sync_fetch_and_nand_4: 5387 case Builtin::BI__sync_fetch_and_nand_8: 5388 case Builtin::BI__sync_fetch_and_nand_16: 5389 BuiltinIndex = 5; 5390 WarnAboutSemanticsChange = true; 5391 break; 5392 5393 case Builtin::BI__sync_add_and_fetch: 5394 case Builtin::BI__sync_add_and_fetch_1: 5395 case Builtin::BI__sync_add_and_fetch_2: 5396 case Builtin::BI__sync_add_and_fetch_4: 5397 case Builtin::BI__sync_add_and_fetch_8: 5398 case Builtin::BI__sync_add_and_fetch_16: 5399 BuiltinIndex = 6; 5400 break; 5401 5402 case Builtin::BI__sync_sub_and_fetch: 5403 case Builtin::BI__sync_sub_and_fetch_1: 5404 case Builtin::BI__sync_sub_and_fetch_2: 5405 case Builtin::BI__sync_sub_and_fetch_4: 5406 case Builtin::BI__sync_sub_and_fetch_8: 5407 case Builtin::BI__sync_sub_and_fetch_16: 5408 BuiltinIndex = 7; 5409 break; 5410 5411 case Builtin::BI__sync_and_and_fetch: 5412 case Builtin::BI__sync_and_and_fetch_1: 5413 case Builtin::BI__sync_and_and_fetch_2: 5414 case Builtin::BI__sync_and_and_fetch_4: 5415 case Builtin::BI__sync_and_and_fetch_8: 5416 case Builtin::BI__sync_and_and_fetch_16: 5417 BuiltinIndex = 8; 5418 break; 5419 5420 case Builtin::BI__sync_or_and_fetch: 5421 case Builtin::BI__sync_or_and_fetch_1: 5422 case Builtin::BI__sync_or_and_fetch_2: 5423 case Builtin::BI__sync_or_and_fetch_4: 5424 case Builtin::BI__sync_or_and_fetch_8: 5425 case Builtin::BI__sync_or_and_fetch_16: 5426 BuiltinIndex = 9; 5427 break; 5428 5429 case Builtin::BI__sync_xor_and_fetch: 5430 case Builtin::BI__sync_xor_and_fetch_1: 5431 case Builtin::BI__sync_xor_and_fetch_2: 5432 case Builtin::BI__sync_xor_and_fetch_4: 5433 case Builtin::BI__sync_xor_and_fetch_8: 5434 case Builtin::BI__sync_xor_and_fetch_16: 5435 BuiltinIndex = 10; 5436 break; 5437 5438 case Builtin::BI__sync_nand_and_fetch: 5439 case Builtin::BI__sync_nand_and_fetch_1: 5440 case Builtin::BI__sync_nand_and_fetch_2: 5441 case Builtin::BI__sync_nand_and_fetch_4: 5442 case Builtin::BI__sync_nand_and_fetch_8: 5443 case Builtin::BI__sync_nand_and_fetch_16: 5444 BuiltinIndex = 11; 5445 WarnAboutSemanticsChange = true; 5446 break; 5447 5448 case Builtin::BI__sync_val_compare_and_swap: 5449 case Builtin::BI__sync_val_compare_and_swap_1: 5450 case Builtin::BI__sync_val_compare_and_swap_2: 5451 case Builtin::BI__sync_val_compare_and_swap_4: 5452 case Builtin::BI__sync_val_compare_and_swap_8: 5453 case Builtin::BI__sync_val_compare_and_swap_16: 5454 BuiltinIndex = 12; 5455 NumFixed = 2; 5456 break; 5457 5458 case Builtin::BI__sync_bool_compare_and_swap: 5459 case Builtin::BI__sync_bool_compare_and_swap_1: 5460 case Builtin::BI__sync_bool_compare_and_swap_2: 5461 case Builtin::BI__sync_bool_compare_and_swap_4: 5462 case Builtin::BI__sync_bool_compare_and_swap_8: 5463 case Builtin::BI__sync_bool_compare_and_swap_16: 5464 BuiltinIndex = 13; 5465 NumFixed = 2; 5466 ResultType = Context.BoolTy; 5467 break; 5468 5469 case Builtin::BI__sync_lock_test_and_set: 5470 case Builtin::BI__sync_lock_test_and_set_1: 5471 case Builtin::BI__sync_lock_test_and_set_2: 5472 case Builtin::BI__sync_lock_test_and_set_4: 5473 case Builtin::BI__sync_lock_test_and_set_8: 5474 case Builtin::BI__sync_lock_test_and_set_16: 5475 BuiltinIndex = 14; 5476 break; 5477 5478 case Builtin::BI__sync_lock_release: 5479 case Builtin::BI__sync_lock_release_1: 5480 case Builtin::BI__sync_lock_release_2: 5481 case Builtin::BI__sync_lock_release_4: 5482 case Builtin::BI__sync_lock_release_8: 5483 case Builtin::BI__sync_lock_release_16: 5484 BuiltinIndex = 15; 5485 NumFixed = 0; 5486 ResultType = Context.VoidTy; 5487 break; 5488 5489 case Builtin::BI__sync_swap: 5490 case Builtin::BI__sync_swap_1: 5491 case Builtin::BI__sync_swap_2: 5492 case Builtin::BI__sync_swap_4: 5493 case Builtin::BI__sync_swap_8: 5494 case Builtin::BI__sync_swap_16: 5495 BuiltinIndex = 16; 5496 break; 5497 } 5498 5499 // Now that we know how many fixed arguments we expect, first check that we 5500 // have at least that many. 5501 if (TheCall->getNumArgs() < 1+NumFixed) { 5502 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5503 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5504 << Callee->getSourceRange(); 5505 return ExprError(); 5506 } 5507 5508 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5509 << Callee->getSourceRange(); 5510 5511 if (WarnAboutSemanticsChange) { 5512 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5513 << Callee->getSourceRange(); 5514 } 5515 5516 // Get the decl for the concrete builtin from this, we can tell what the 5517 // concrete integer type we should convert to is. 5518 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5519 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5520 FunctionDecl *NewBuiltinDecl; 5521 if (NewBuiltinID == BuiltinID) 5522 NewBuiltinDecl = FDecl; 5523 else { 5524 // Perform builtin lookup to avoid redeclaring it. 5525 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5526 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5527 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5528 assert(Res.getFoundDecl()); 5529 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5530 if (!NewBuiltinDecl) 5531 return ExprError(); 5532 } 5533 5534 // The first argument --- the pointer --- has a fixed type; we 5535 // deduce the types of the rest of the arguments accordingly. Walk 5536 // the remaining arguments, converting them to the deduced value type. 5537 for (unsigned i = 0; i != NumFixed; ++i) { 5538 ExprResult Arg = TheCall->getArg(i+1); 5539 5540 // GCC does an implicit conversion to the pointer or integer ValType. This 5541 // can fail in some cases (1i -> int**), check for this error case now. 5542 // Initialize the argument. 5543 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5544 ValType, /*consume*/ false); 5545 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5546 if (Arg.isInvalid()) 5547 return ExprError(); 5548 5549 // Okay, we have something that *can* be converted to the right type. Check 5550 // to see if there is a potentially weird extension going on here. This can 5551 // happen when you do an atomic operation on something like an char* and 5552 // pass in 42. The 42 gets converted to char. This is even more strange 5553 // for things like 45.123 -> char, etc. 5554 // FIXME: Do this check. 5555 TheCall->setArg(i+1, Arg.get()); 5556 } 5557 5558 // Create a new DeclRefExpr to refer to the new decl. 5559 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5560 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5561 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5562 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5563 5564 // Set the callee in the CallExpr. 5565 // FIXME: This loses syntactic information. 5566 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5567 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5568 CK_BuiltinFnToFnPtr); 5569 TheCall->setCallee(PromotedCall.get()); 5570 5571 // Change the result type of the call to match the original value type. This 5572 // is arbitrary, but the codegen for these builtins ins design to handle it 5573 // gracefully. 5574 TheCall->setType(ResultType); 5575 5576 // Prohibit use of _ExtInt with atomic builtins. 5577 // The arguments would have already been converted to the first argument's 5578 // type, so only need to check the first argument. 5579 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5580 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5581 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5582 return ExprError(); 5583 } 5584 5585 return TheCallResult; 5586 } 5587 5588 /// SemaBuiltinNontemporalOverloaded - We have a call to 5589 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5590 /// overloaded function based on the pointer type of its last argument. 5591 /// 5592 /// This function goes through and does final semantic checking for these 5593 /// builtins. 5594 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5595 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5596 DeclRefExpr *DRE = 5597 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5598 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5599 unsigned BuiltinID = FDecl->getBuiltinID(); 5600 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5601 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5602 "Unexpected nontemporal load/store builtin!"); 5603 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5604 unsigned numArgs = isStore ? 2 : 1; 5605 5606 // Ensure that we have the proper number of arguments. 5607 if (checkArgCount(*this, TheCall, numArgs)) 5608 return ExprError(); 5609 5610 // Inspect the last argument of the nontemporal builtin. This should always 5611 // be a pointer type, from which we imply the type of the memory access. 5612 // Because it is a pointer type, we don't have to worry about any implicit 5613 // casts here. 5614 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5615 ExprResult PointerArgResult = 5616 DefaultFunctionArrayLvalueConversion(PointerArg); 5617 5618 if (PointerArgResult.isInvalid()) 5619 return ExprError(); 5620 PointerArg = PointerArgResult.get(); 5621 TheCall->setArg(numArgs - 1, PointerArg); 5622 5623 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5624 if (!pointerType) { 5625 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5626 << PointerArg->getType() << PointerArg->getSourceRange(); 5627 return ExprError(); 5628 } 5629 5630 QualType ValType = pointerType->getPointeeType(); 5631 5632 // Strip any qualifiers off ValType. 5633 ValType = ValType.getUnqualifiedType(); 5634 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5635 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5636 !ValType->isVectorType()) { 5637 Diag(DRE->getBeginLoc(), 5638 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5639 << PointerArg->getType() << PointerArg->getSourceRange(); 5640 return ExprError(); 5641 } 5642 5643 if (!isStore) { 5644 TheCall->setType(ValType); 5645 return TheCallResult; 5646 } 5647 5648 ExprResult ValArg = TheCall->getArg(0); 5649 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5650 Context, ValType, /*consume*/ false); 5651 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5652 if (ValArg.isInvalid()) 5653 return ExprError(); 5654 5655 TheCall->setArg(0, ValArg.get()); 5656 TheCall->setType(Context.VoidTy); 5657 return TheCallResult; 5658 } 5659 5660 /// CheckObjCString - Checks that the argument to the builtin 5661 /// CFString constructor is correct 5662 /// Note: It might also make sense to do the UTF-16 conversion here (would 5663 /// simplify the backend). 5664 bool Sema::CheckObjCString(Expr *Arg) { 5665 Arg = Arg->IgnoreParenCasts(); 5666 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5667 5668 if (!Literal || !Literal->isAscii()) { 5669 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5670 << Arg->getSourceRange(); 5671 return true; 5672 } 5673 5674 if (Literal->containsNonAsciiOrNull()) { 5675 StringRef String = Literal->getString(); 5676 unsigned NumBytes = String.size(); 5677 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5678 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5679 llvm::UTF16 *ToPtr = &ToBuf[0]; 5680 5681 llvm::ConversionResult Result = 5682 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5683 ToPtr + NumBytes, llvm::strictConversion); 5684 // Check for conversion failure. 5685 if (Result != llvm::conversionOK) 5686 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5687 << Arg->getSourceRange(); 5688 } 5689 return false; 5690 } 5691 5692 /// CheckObjCString - Checks that the format string argument to the os_log() 5693 /// and os_trace() functions is correct, and converts it to const char *. 5694 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5695 Arg = Arg->IgnoreParenCasts(); 5696 auto *Literal = dyn_cast<StringLiteral>(Arg); 5697 if (!Literal) { 5698 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5699 Literal = ObjcLiteral->getString(); 5700 } 5701 } 5702 5703 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5704 return ExprError( 5705 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5706 << Arg->getSourceRange()); 5707 } 5708 5709 ExprResult Result(Literal); 5710 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5711 InitializedEntity Entity = 5712 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5713 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5714 return Result; 5715 } 5716 5717 /// Check that the user is calling the appropriate va_start builtin for the 5718 /// target and calling convention. 5719 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5720 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5721 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5722 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5723 TT.getArch() == llvm::Triple::aarch64_32); 5724 bool IsWindows = TT.isOSWindows(); 5725 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5726 if (IsX64 || IsAArch64) { 5727 CallingConv CC = CC_C; 5728 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5729 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5730 if (IsMSVAStart) { 5731 // Don't allow this in System V ABI functions. 5732 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5733 return S.Diag(Fn->getBeginLoc(), 5734 diag::err_ms_va_start_used_in_sysv_function); 5735 } else { 5736 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5737 // On x64 Windows, don't allow this in System V ABI functions. 5738 // (Yes, that means there's no corresponding way to support variadic 5739 // System V ABI functions on Windows.) 5740 if ((IsWindows && CC == CC_X86_64SysV) || 5741 (!IsWindows && CC == CC_Win64)) 5742 return S.Diag(Fn->getBeginLoc(), 5743 diag::err_va_start_used_in_wrong_abi_function) 5744 << !IsWindows; 5745 } 5746 return false; 5747 } 5748 5749 if (IsMSVAStart) 5750 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5751 return false; 5752 } 5753 5754 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5755 ParmVarDecl **LastParam = nullptr) { 5756 // Determine whether the current function, block, or obj-c method is variadic 5757 // and get its parameter list. 5758 bool IsVariadic = false; 5759 ArrayRef<ParmVarDecl *> Params; 5760 DeclContext *Caller = S.CurContext; 5761 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5762 IsVariadic = Block->isVariadic(); 5763 Params = Block->parameters(); 5764 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5765 IsVariadic = FD->isVariadic(); 5766 Params = FD->parameters(); 5767 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5768 IsVariadic = MD->isVariadic(); 5769 // FIXME: This isn't correct for methods (results in bogus warning). 5770 Params = MD->parameters(); 5771 } else if (isa<CapturedDecl>(Caller)) { 5772 // We don't support va_start in a CapturedDecl. 5773 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5774 return true; 5775 } else { 5776 // This must be some other declcontext that parses exprs. 5777 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5778 return true; 5779 } 5780 5781 if (!IsVariadic) { 5782 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5783 return true; 5784 } 5785 5786 if (LastParam) 5787 *LastParam = Params.empty() ? nullptr : Params.back(); 5788 5789 return false; 5790 } 5791 5792 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5793 /// for validity. Emit an error and return true on failure; return false 5794 /// on success. 5795 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5796 Expr *Fn = TheCall->getCallee(); 5797 5798 if (checkVAStartABI(*this, BuiltinID, Fn)) 5799 return true; 5800 5801 if (checkArgCount(*this, TheCall, 2)) 5802 return true; 5803 5804 // Type-check the first argument normally. 5805 if (checkBuiltinArgument(*this, TheCall, 0)) 5806 return true; 5807 5808 // Check that the current function is variadic, and get its last parameter. 5809 ParmVarDecl *LastParam; 5810 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5811 return true; 5812 5813 // Verify that the second argument to the builtin is the last argument of the 5814 // current function or method. 5815 bool SecondArgIsLastNamedArgument = false; 5816 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5817 5818 // These are valid if SecondArgIsLastNamedArgument is false after the next 5819 // block. 5820 QualType Type; 5821 SourceLocation ParamLoc; 5822 bool IsCRegister = false; 5823 5824 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5825 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5826 SecondArgIsLastNamedArgument = PV == LastParam; 5827 5828 Type = PV->getType(); 5829 ParamLoc = PV->getLocation(); 5830 IsCRegister = 5831 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5832 } 5833 } 5834 5835 if (!SecondArgIsLastNamedArgument) 5836 Diag(TheCall->getArg(1)->getBeginLoc(), 5837 diag::warn_second_arg_of_va_start_not_last_named_param); 5838 else if (IsCRegister || Type->isReferenceType() || 5839 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5840 // Promotable integers are UB, but enumerations need a bit of 5841 // extra checking to see what their promotable type actually is. 5842 if (!Type->isPromotableIntegerType()) 5843 return false; 5844 if (!Type->isEnumeralType()) 5845 return true; 5846 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5847 return !(ED && 5848 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5849 }()) { 5850 unsigned Reason = 0; 5851 if (Type->isReferenceType()) Reason = 1; 5852 else if (IsCRegister) Reason = 2; 5853 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5854 Diag(ParamLoc, diag::note_parameter_type) << Type; 5855 } 5856 5857 TheCall->setType(Context.VoidTy); 5858 return false; 5859 } 5860 5861 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5862 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5863 // const char *named_addr); 5864 5865 Expr *Func = Call->getCallee(); 5866 5867 if (Call->getNumArgs() < 3) 5868 return Diag(Call->getEndLoc(), 5869 diag::err_typecheck_call_too_few_args_at_least) 5870 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5871 5872 // Type-check the first argument normally. 5873 if (checkBuiltinArgument(*this, Call, 0)) 5874 return true; 5875 5876 // Check that the current function is variadic. 5877 if (checkVAStartIsInVariadicFunction(*this, Func)) 5878 return true; 5879 5880 // __va_start on Windows does not validate the parameter qualifiers 5881 5882 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5883 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5884 5885 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5886 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5887 5888 const QualType &ConstCharPtrTy = 5889 Context.getPointerType(Context.CharTy.withConst()); 5890 if (!Arg1Ty->isPointerType() || 5891 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5892 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5893 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5894 << 0 /* qualifier difference */ 5895 << 3 /* parameter mismatch */ 5896 << 2 << Arg1->getType() << ConstCharPtrTy; 5897 5898 const QualType SizeTy = Context.getSizeType(); 5899 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5900 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5901 << Arg2->getType() << SizeTy << 1 /* different class */ 5902 << 0 /* qualifier difference */ 5903 << 3 /* parameter mismatch */ 5904 << 3 << Arg2->getType() << SizeTy; 5905 5906 return false; 5907 } 5908 5909 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5910 /// friends. This is declared to take (...), so we have to check everything. 5911 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5912 if (checkArgCount(*this, TheCall, 2)) 5913 return true; 5914 5915 ExprResult OrigArg0 = TheCall->getArg(0); 5916 ExprResult OrigArg1 = TheCall->getArg(1); 5917 5918 // Do standard promotions between the two arguments, returning their common 5919 // type. 5920 QualType Res = UsualArithmeticConversions( 5921 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5922 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5923 return true; 5924 5925 // Make sure any conversions are pushed back into the call; this is 5926 // type safe since unordered compare builtins are declared as "_Bool 5927 // foo(...)". 5928 TheCall->setArg(0, OrigArg0.get()); 5929 TheCall->setArg(1, OrigArg1.get()); 5930 5931 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5932 return false; 5933 5934 // If the common type isn't a real floating type, then the arguments were 5935 // invalid for this operation. 5936 if (Res.isNull() || !Res->isRealFloatingType()) 5937 return Diag(OrigArg0.get()->getBeginLoc(), 5938 diag::err_typecheck_call_invalid_ordered_compare) 5939 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5940 << SourceRange(OrigArg0.get()->getBeginLoc(), 5941 OrigArg1.get()->getEndLoc()); 5942 5943 return false; 5944 } 5945 5946 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5947 /// __builtin_isnan and friends. This is declared to take (...), so we have 5948 /// to check everything. We expect the last argument to be a floating point 5949 /// value. 5950 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5951 if (checkArgCount(*this, TheCall, NumArgs)) 5952 return true; 5953 5954 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5955 // on all preceding parameters just being int. Try all of those. 5956 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5957 Expr *Arg = TheCall->getArg(i); 5958 5959 if (Arg->isTypeDependent()) 5960 return false; 5961 5962 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5963 5964 if (Res.isInvalid()) 5965 return true; 5966 TheCall->setArg(i, Res.get()); 5967 } 5968 5969 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5970 5971 if (OrigArg->isTypeDependent()) 5972 return false; 5973 5974 // Usual Unary Conversions will convert half to float, which we want for 5975 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5976 // type how it is, but do normal L->Rvalue conversions. 5977 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5978 OrigArg = UsualUnaryConversions(OrigArg).get(); 5979 else 5980 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5981 TheCall->setArg(NumArgs - 1, OrigArg); 5982 5983 // This operation requires a non-_Complex floating-point number. 5984 if (!OrigArg->getType()->isRealFloatingType()) 5985 return Diag(OrigArg->getBeginLoc(), 5986 diag::err_typecheck_call_invalid_unary_fp) 5987 << OrigArg->getType() << OrigArg->getSourceRange(); 5988 5989 return false; 5990 } 5991 5992 /// Perform semantic analysis for a call to __builtin_complex. 5993 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 5994 if (checkArgCount(*this, TheCall, 2)) 5995 return true; 5996 5997 bool Dependent = false; 5998 for (unsigned I = 0; I != 2; ++I) { 5999 Expr *Arg = TheCall->getArg(I); 6000 QualType T = Arg->getType(); 6001 if (T->isDependentType()) { 6002 Dependent = true; 6003 continue; 6004 } 6005 6006 // Despite supporting _Complex int, GCC requires a real floating point type 6007 // for the operands of __builtin_complex. 6008 if (!T->isRealFloatingType()) { 6009 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6010 << Arg->getType() << Arg->getSourceRange(); 6011 } 6012 6013 ExprResult Converted = DefaultLvalueConversion(Arg); 6014 if (Converted.isInvalid()) 6015 return true; 6016 TheCall->setArg(I, Converted.get()); 6017 } 6018 6019 if (Dependent) { 6020 TheCall->setType(Context.DependentTy); 6021 return false; 6022 } 6023 6024 Expr *Real = TheCall->getArg(0); 6025 Expr *Imag = TheCall->getArg(1); 6026 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6027 return Diag(Real->getBeginLoc(), 6028 diag::err_typecheck_call_different_arg_types) 6029 << Real->getType() << Imag->getType() 6030 << Real->getSourceRange() << Imag->getSourceRange(); 6031 } 6032 6033 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6034 // don't allow this builtin to form those types either. 6035 // FIXME: Should we allow these types? 6036 if (Real->getType()->isFloat16Type()) 6037 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6038 << "_Float16"; 6039 if (Real->getType()->isHalfType()) 6040 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6041 << "half"; 6042 6043 TheCall->setType(Context.getComplexType(Real->getType())); 6044 return false; 6045 } 6046 6047 // Customized Sema Checking for VSX builtins that have the following signature: 6048 // vector [...] builtinName(vector [...], vector [...], const int); 6049 // Which takes the same type of vectors (any legal vector type) for the first 6050 // two arguments and takes compile time constant for the third argument. 6051 // Example builtins are : 6052 // vector double vec_xxpermdi(vector double, vector double, int); 6053 // vector short vec_xxsldwi(vector short, vector short, int); 6054 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6055 unsigned ExpectedNumArgs = 3; 6056 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6057 return true; 6058 6059 // Check the third argument is a compile time constant 6060 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6061 return Diag(TheCall->getBeginLoc(), 6062 diag::err_vsx_builtin_nonconstant_argument) 6063 << 3 /* argument index */ << TheCall->getDirectCallee() 6064 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6065 TheCall->getArg(2)->getEndLoc()); 6066 6067 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6068 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6069 6070 // Check the type of argument 1 and argument 2 are vectors. 6071 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6072 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6073 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6074 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6075 << TheCall->getDirectCallee() 6076 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6077 TheCall->getArg(1)->getEndLoc()); 6078 } 6079 6080 // Check the first two arguments are the same type. 6081 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6082 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6083 << TheCall->getDirectCallee() 6084 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6085 TheCall->getArg(1)->getEndLoc()); 6086 } 6087 6088 // When default clang type checking is turned off and the customized type 6089 // checking is used, the returning type of the function must be explicitly 6090 // set. Otherwise it is _Bool by default. 6091 TheCall->setType(Arg1Ty); 6092 6093 return false; 6094 } 6095 6096 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6097 // This is declared to take (...), so we have to check everything. 6098 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6099 if (TheCall->getNumArgs() < 2) 6100 return ExprError(Diag(TheCall->getEndLoc(), 6101 diag::err_typecheck_call_too_few_args_at_least) 6102 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6103 << TheCall->getSourceRange()); 6104 6105 // Determine which of the following types of shufflevector we're checking: 6106 // 1) unary, vector mask: (lhs, mask) 6107 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6108 QualType resType = TheCall->getArg(0)->getType(); 6109 unsigned numElements = 0; 6110 6111 if (!TheCall->getArg(0)->isTypeDependent() && 6112 !TheCall->getArg(1)->isTypeDependent()) { 6113 QualType LHSType = TheCall->getArg(0)->getType(); 6114 QualType RHSType = TheCall->getArg(1)->getType(); 6115 6116 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6117 return ExprError( 6118 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6119 << TheCall->getDirectCallee() 6120 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6121 TheCall->getArg(1)->getEndLoc())); 6122 6123 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6124 unsigned numResElements = TheCall->getNumArgs() - 2; 6125 6126 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6127 // with mask. If so, verify that RHS is an integer vector type with the 6128 // same number of elts as lhs. 6129 if (TheCall->getNumArgs() == 2) { 6130 if (!RHSType->hasIntegerRepresentation() || 6131 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6132 return ExprError(Diag(TheCall->getBeginLoc(), 6133 diag::err_vec_builtin_incompatible_vector) 6134 << TheCall->getDirectCallee() 6135 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6136 TheCall->getArg(1)->getEndLoc())); 6137 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6138 return ExprError(Diag(TheCall->getBeginLoc(), 6139 diag::err_vec_builtin_incompatible_vector) 6140 << TheCall->getDirectCallee() 6141 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6142 TheCall->getArg(1)->getEndLoc())); 6143 } else if (numElements != numResElements) { 6144 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6145 resType = Context.getVectorType(eltType, numResElements, 6146 VectorType::GenericVector); 6147 } 6148 } 6149 6150 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6151 if (TheCall->getArg(i)->isTypeDependent() || 6152 TheCall->getArg(i)->isValueDependent()) 6153 continue; 6154 6155 Optional<llvm::APSInt> Result; 6156 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6157 return ExprError(Diag(TheCall->getBeginLoc(), 6158 diag::err_shufflevector_nonconstant_argument) 6159 << TheCall->getArg(i)->getSourceRange()); 6160 6161 // Allow -1 which will be translated to undef in the IR. 6162 if (Result->isSigned() && Result->isAllOnesValue()) 6163 continue; 6164 6165 if (Result->getActiveBits() > 64 || 6166 Result->getZExtValue() >= numElements * 2) 6167 return ExprError(Diag(TheCall->getBeginLoc(), 6168 diag::err_shufflevector_argument_too_large) 6169 << TheCall->getArg(i)->getSourceRange()); 6170 } 6171 6172 SmallVector<Expr*, 32> exprs; 6173 6174 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6175 exprs.push_back(TheCall->getArg(i)); 6176 TheCall->setArg(i, nullptr); 6177 } 6178 6179 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6180 TheCall->getCallee()->getBeginLoc(), 6181 TheCall->getRParenLoc()); 6182 } 6183 6184 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6185 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6186 SourceLocation BuiltinLoc, 6187 SourceLocation RParenLoc) { 6188 ExprValueKind VK = VK_RValue; 6189 ExprObjectKind OK = OK_Ordinary; 6190 QualType DstTy = TInfo->getType(); 6191 QualType SrcTy = E->getType(); 6192 6193 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6194 return ExprError(Diag(BuiltinLoc, 6195 diag::err_convertvector_non_vector) 6196 << E->getSourceRange()); 6197 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6198 return ExprError(Diag(BuiltinLoc, 6199 diag::err_convertvector_non_vector_type)); 6200 6201 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6202 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6203 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6204 if (SrcElts != DstElts) 6205 return ExprError(Diag(BuiltinLoc, 6206 diag::err_convertvector_incompatible_vector) 6207 << E->getSourceRange()); 6208 } 6209 6210 return new (Context) 6211 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6212 } 6213 6214 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6215 // This is declared to take (const void*, ...) and can take two 6216 // optional constant int args. 6217 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6218 unsigned NumArgs = TheCall->getNumArgs(); 6219 6220 if (NumArgs > 3) 6221 return Diag(TheCall->getEndLoc(), 6222 diag::err_typecheck_call_too_many_args_at_most) 6223 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6224 6225 // Argument 0 is checked for us and the remaining arguments must be 6226 // constant integers. 6227 for (unsigned i = 1; i != NumArgs; ++i) 6228 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6229 return true; 6230 6231 return false; 6232 } 6233 6234 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6235 // __assume does not evaluate its arguments, and should warn if its argument 6236 // has side effects. 6237 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6238 Expr *Arg = TheCall->getArg(0); 6239 if (Arg->isInstantiationDependent()) return false; 6240 6241 if (Arg->HasSideEffects(Context)) 6242 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6243 << Arg->getSourceRange() 6244 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6245 6246 return false; 6247 } 6248 6249 /// Handle __builtin_alloca_with_align. This is declared 6250 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6251 /// than 8. 6252 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6253 // The alignment must be a constant integer. 6254 Expr *Arg = TheCall->getArg(1); 6255 6256 // We can't check the value of a dependent argument. 6257 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6258 if (const auto *UE = 6259 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6260 if (UE->getKind() == UETT_AlignOf || 6261 UE->getKind() == UETT_PreferredAlignOf) 6262 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6263 << Arg->getSourceRange(); 6264 6265 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6266 6267 if (!Result.isPowerOf2()) 6268 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6269 << Arg->getSourceRange(); 6270 6271 if (Result < Context.getCharWidth()) 6272 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6273 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6274 6275 if (Result > std::numeric_limits<int32_t>::max()) 6276 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6277 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6278 } 6279 6280 return false; 6281 } 6282 6283 /// Handle __builtin_assume_aligned. This is declared 6284 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6285 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6286 unsigned NumArgs = TheCall->getNumArgs(); 6287 6288 if (NumArgs > 3) 6289 return Diag(TheCall->getEndLoc(), 6290 diag::err_typecheck_call_too_many_args_at_most) 6291 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6292 6293 // The alignment must be a constant integer. 6294 Expr *Arg = TheCall->getArg(1); 6295 6296 // We can't check the value of a dependent argument. 6297 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6298 llvm::APSInt Result; 6299 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6300 return true; 6301 6302 if (!Result.isPowerOf2()) 6303 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6304 << Arg->getSourceRange(); 6305 6306 if (Result > Sema::MaximumAlignment) 6307 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6308 << Arg->getSourceRange() << Sema::MaximumAlignment; 6309 } 6310 6311 if (NumArgs > 2) { 6312 ExprResult Arg(TheCall->getArg(2)); 6313 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6314 Context.getSizeType(), false); 6315 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6316 if (Arg.isInvalid()) return true; 6317 TheCall->setArg(2, Arg.get()); 6318 } 6319 6320 return false; 6321 } 6322 6323 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6324 unsigned BuiltinID = 6325 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6326 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6327 6328 unsigned NumArgs = TheCall->getNumArgs(); 6329 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6330 if (NumArgs < NumRequiredArgs) { 6331 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6332 << 0 /* function call */ << NumRequiredArgs << NumArgs 6333 << TheCall->getSourceRange(); 6334 } 6335 if (NumArgs >= NumRequiredArgs + 0x100) { 6336 return Diag(TheCall->getEndLoc(), 6337 diag::err_typecheck_call_too_many_args_at_most) 6338 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6339 << TheCall->getSourceRange(); 6340 } 6341 unsigned i = 0; 6342 6343 // For formatting call, check buffer arg. 6344 if (!IsSizeCall) { 6345 ExprResult Arg(TheCall->getArg(i)); 6346 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6347 Context, Context.VoidPtrTy, false); 6348 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6349 if (Arg.isInvalid()) 6350 return true; 6351 TheCall->setArg(i, Arg.get()); 6352 i++; 6353 } 6354 6355 // Check string literal arg. 6356 unsigned FormatIdx = i; 6357 { 6358 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6359 if (Arg.isInvalid()) 6360 return true; 6361 TheCall->setArg(i, Arg.get()); 6362 i++; 6363 } 6364 6365 // Make sure variadic args are scalar. 6366 unsigned FirstDataArg = i; 6367 while (i < NumArgs) { 6368 ExprResult Arg = DefaultVariadicArgumentPromotion( 6369 TheCall->getArg(i), VariadicFunction, nullptr); 6370 if (Arg.isInvalid()) 6371 return true; 6372 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6373 if (ArgSize.getQuantity() >= 0x100) { 6374 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6375 << i << (int)ArgSize.getQuantity() << 0xff 6376 << TheCall->getSourceRange(); 6377 } 6378 TheCall->setArg(i, Arg.get()); 6379 i++; 6380 } 6381 6382 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6383 // call to avoid duplicate diagnostics. 6384 if (!IsSizeCall) { 6385 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6386 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6387 bool Success = CheckFormatArguments( 6388 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6389 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6390 CheckedVarArgs); 6391 if (!Success) 6392 return true; 6393 } 6394 6395 if (IsSizeCall) { 6396 TheCall->setType(Context.getSizeType()); 6397 } else { 6398 TheCall->setType(Context.VoidPtrTy); 6399 } 6400 return false; 6401 } 6402 6403 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6404 /// TheCall is a constant expression. 6405 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6406 llvm::APSInt &Result) { 6407 Expr *Arg = TheCall->getArg(ArgNum); 6408 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6409 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6410 6411 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6412 6413 Optional<llvm::APSInt> R; 6414 if (!(R = Arg->getIntegerConstantExpr(Context))) 6415 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6416 << FDecl->getDeclName() << Arg->getSourceRange(); 6417 Result = *R; 6418 return false; 6419 } 6420 6421 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6422 /// TheCall is a constant expression in the range [Low, High]. 6423 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6424 int Low, int High, bool RangeIsError) { 6425 if (isConstantEvaluated()) 6426 return false; 6427 llvm::APSInt Result; 6428 6429 // We can't check the value of a dependent argument. 6430 Expr *Arg = TheCall->getArg(ArgNum); 6431 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6432 return false; 6433 6434 // Check constant-ness first. 6435 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6436 return true; 6437 6438 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6439 if (RangeIsError) 6440 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6441 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6442 else 6443 // Defer the warning until we know if the code will be emitted so that 6444 // dead code can ignore this. 6445 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6446 PDiag(diag::warn_argument_invalid_range) 6447 << Result.toString(10) << Low << High 6448 << Arg->getSourceRange()); 6449 } 6450 6451 return false; 6452 } 6453 6454 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6455 /// TheCall is a constant expression is a multiple of Num.. 6456 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6457 unsigned Num) { 6458 llvm::APSInt Result; 6459 6460 // We can't check the value of a dependent argument. 6461 Expr *Arg = TheCall->getArg(ArgNum); 6462 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6463 return false; 6464 6465 // Check constant-ness first. 6466 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6467 return true; 6468 6469 if (Result.getSExtValue() % Num != 0) 6470 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6471 << Num << Arg->getSourceRange(); 6472 6473 return false; 6474 } 6475 6476 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6477 /// constant expression representing a power of 2. 6478 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6479 llvm::APSInt Result; 6480 6481 // We can't check the value of a dependent argument. 6482 Expr *Arg = TheCall->getArg(ArgNum); 6483 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6484 return false; 6485 6486 // Check constant-ness first. 6487 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6488 return true; 6489 6490 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6491 // and only if x is a power of 2. 6492 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6493 return false; 6494 6495 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6496 << Arg->getSourceRange(); 6497 } 6498 6499 static bool IsShiftedByte(llvm::APSInt Value) { 6500 if (Value.isNegative()) 6501 return false; 6502 6503 // Check if it's a shifted byte, by shifting it down 6504 while (true) { 6505 // If the value fits in the bottom byte, the check passes. 6506 if (Value < 0x100) 6507 return true; 6508 6509 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6510 // fails. 6511 if ((Value & 0xFF) != 0) 6512 return false; 6513 6514 // If the bottom 8 bits are all 0, but something above that is nonzero, 6515 // then shifting the value right by 8 bits won't affect whether it's a 6516 // shifted byte or not. So do that, and go round again. 6517 Value >>= 8; 6518 } 6519 } 6520 6521 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6522 /// a constant expression representing an arbitrary byte value shifted left by 6523 /// a multiple of 8 bits. 6524 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6525 unsigned ArgBits) { 6526 llvm::APSInt Result; 6527 6528 // We can't check the value of a dependent argument. 6529 Expr *Arg = TheCall->getArg(ArgNum); 6530 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6531 return false; 6532 6533 // Check constant-ness first. 6534 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6535 return true; 6536 6537 // Truncate to the given size. 6538 Result = Result.getLoBits(ArgBits); 6539 Result.setIsUnsigned(true); 6540 6541 if (IsShiftedByte(Result)) 6542 return false; 6543 6544 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6545 << Arg->getSourceRange(); 6546 } 6547 6548 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6549 /// TheCall is a constant expression representing either a shifted byte value, 6550 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6551 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6552 /// Arm MVE intrinsics. 6553 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6554 int ArgNum, 6555 unsigned ArgBits) { 6556 llvm::APSInt Result; 6557 6558 // We can't check the value of a dependent argument. 6559 Expr *Arg = TheCall->getArg(ArgNum); 6560 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6561 return false; 6562 6563 // Check constant-ness first. 6564 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6565 return true; 6566 6567 // Truncate to the given size. 6568 Result = Result.getLoBits(ArgBits); 6569 Result.setIsUnsigned(true); 6570 6571 // Check to see if it's in either of the required forms. 6572 if (IsShiftedByte(Result) || 6573 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6574 return false; 6575 6576 return Diag(TheCall->getBeginLoc(), 6577 diag::err_argument_not_shifted_byte_or_xxff) 6578 << Arg->getSourceRange(); 6579 } 6580 6581 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6582 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6583 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6584 if (checkArgCount(*this, TheCall, 2)) 6585 return true; 6586 Expr *Arg0 = TheCall->getArg(0); 6587 Expr *Arg1 = TheCall->getArg(1); 6588 6589 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6590 if (FirstArg.isInvalid()) 6591 return true; 6592 QualType FirstArgType = FirstArg.get()->getType(); 6593 if (!FirstArgType->isAnyPointerType()) 6594 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6595 << "first" << FirstArgType << Arg0->getSourceRange(); 6596 TheCall->setArg(0, FirstArg.get()); 6597 6598 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6599 if (SecArg.isInvalid()) 6600 return true; 6601 QualType SecArgType = SecArg.get()->getType(); 6602 if (!SecArgType->isIntegerType()) 6603 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6604 << "second" << SecArgType << Arg1->getSourceRange(); 6605 6606 // Derive the return type from the pointer argument. 6607 TheCall->setType(FirstArgType); 6608 return false; 6609 } 6610 6611 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6612 if (checkArgCount(*this, TheCall, 2)) 6613 return true; 6614 6615 Expr *Arg0 = TheCall->getArg(0); 6616 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6617 if (FirstArg.isInvalid()) 6618 return true; 6619 QualType FirstArgType = FirstArg.get()->getType(); 6620 if (!FirstArgType->isAnyPointerType()) 6621 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6622 << "first" << FirstArgType << Arg0->getSourceRange(); 6623 TheCall->setArg(0, FirstArg.get()); 6624 6625 // Derive the return type from the pointer argument. 6626 TheCall->setType(FirstArgType); 6627 6628 // Second arg must be an constant in range [0,15] 6629 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6630 } 6631 6632 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6633 if (checkArgCount(*this, TheCall, 2)) 6634 return true; 6635 Expr *Arg0 = TheCall->getArg(0); 6636 Expr *Arg1 = TheCall->getArg(1); 6637 6638 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6639 if (FirstArg.isInvalid()) 6640 return true; 6641 QualType FirstArgType = FirstArg.get()->getType(); 6642 if (!FirstArgType->isAnyPointerType()) 6643 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6644 << "first" << FirstArgType << Arg0->getSourceRange(); 6645 6646 QualType SecArgType = Arg1->getType(); 6647 if (!SecArgType->isIntegerType()) 6648 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6649 << "second" << SecArgType << Arg1->getSourceRange(); 6650 TheCall->setType(Context.IntTy); 6651 return false; 6652 } 6653 6654 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6655 BuiltinID == AArch64::BI__builtin_arm_stg) { 6656 if (checkArgCount(*this, TheCall, 1)) 6657 return true; 6658 Expr *Arg0 = TheCall->getArg(0); 6659 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6660 if (FirstArg.isInvalid()) 6661 return true; 6662 6663 QualType FirstArgType = FirstArg.get()->getType(); 6664 if (!FirstArgType->isAnyPointerType()) 6665 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6666 << "first" << FirstArgType << Arg0->getSourceRange(); 6667 TheCall->setArg(0, FirstArg.get()); 6668 6669 // Derive the return type from the pointer argument. 6670 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6671 TheCall->setType(FirstArgType); 6672 return false; 6673 } 6674 6675 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6676 Expr *ArgA = TheCall->getArg(0); 6677 Expr *ArgB = TheCall->getArg(1); 6678 6679 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6680 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6681 6682 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6683 return true; 6684 6685 QualType ArgTypeA = ArgExprA.get()->getType(); 6686 QualType ArgTypeB = ArgExprB.get()->getType(); 6687 6688 auto isNull = [&] (Expr *E) -> bool { 6689 return E->isNullPointerConstant( 6690 Context, Expr::NPC_ValueDependentIsNotNull); }; 6691 6692 // argument should be either a pointer or null 6693 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6694 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6695 << "first" << ArgTypeA << ArgA->getSourceRange(); 6696 6697 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6698 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6699 << "second" << ArgTypeB << ArgB->getSourceRange(); 6700 6701 // Ensure Pointee types are compatible 6702 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6703 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6704 QualType pointeeA = ArgTypeA->getPointeeType(); 6705 QualType pointeeB = ArgTypeB->getPointeeType(); 6706 if (!Context.typesAreCompatible( 6707 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6708 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6709 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6710 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6711 << ArgB->getSourceRange(); 6712 } 6713 } 6714 6715 // at least one argument should be pointer type 6716 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6717 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6718 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6719 6720 if (isNull(ArgA)) // adopt type of the other pointer 6721 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6722 6723 if (isNull(ArgB)) 6724 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6725 6726 TheCall->setArg(0, ArgExprA.get()); 6727 TheCall->setArg(1, ArgExprB.get()); 6728 TheCall->setType(Context.LongLongTy); 6729 return false; 6730 } 6731 assert(false && "Unhandled ARM MTE intrinsic"); 6732 return true; 6733 } 6734 6735 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6736 /// TheCall is an ARM/AArch64 special register string literal. 6737 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6738 int ArgNum, unsigned ExpectedFieldNum, 6739 bool AllowName) { 6740 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6741 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6742 BuiltinID == ARM::BI__builtin_arm_rsr || 6743 BuiltinID == ARM::BI__builtin_arm_rsrp || 6744 BuiltinID == ARM::BI__builtin_arm_wsr || 6745 BuiltinID == ARM::BI__builtin_arm_wsrp; 6746 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6747 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6748 BuiltinID == AArch64::BI__builtin_arm_rsr || 6749 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6750 BuiltinID == AArch64::BI__builtin_arm_wsr || 6751 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6752 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6753 6754 // We can't check the value of a dependent argument. 6755 Expr *Arg = TheCall->getArg(ArgNum); 6756 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6757 return false; 6758 6759 // Check if the argument is a string literal. 6760 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6761 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6762 << Arg->getSourceRange(); 6763 6764 // Check the type of special register given. 6765 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6766 SmallVector<StringRef, 6> Fields; 6767 Reg.split(Fields, ":"); 6768 6769 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6770 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6771 << Arg->getSourceRange(); 6772 6773 // If the string is the name of a register then we cannot check that it is 6774 // valid here but if the string is of one the forms described in ACLE then we 6775 // can check that the supplied fields are integers and within the valid 6776 // ranges. 6777 if (Fields.size() > 1) { 6778 bool FiveFields = Fields.size() == 5; 6779 6780 bool ValidString = true; 6781 if (IsARMBuiltin) { 6782 ValidString &= Fields[0].startswith_lower("cp") || 6783 Fields[0].startswith_lower("p"); 6784 if (ValidString) 6785 Fields[0] = 6786 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6787 6788 ValidString &= Fields[2].startswith_lower("c"); 6789 if (ValidString) 6790 Fields[2] = Fields[2].drop_front(1); 6791 6792 if (FiveFields) { 6793 ValidString &= Fields[3].startswith_lower("c"); 6794 if (ValidString) 6795 Fields[3] = Fields[3].drop_front(1); 6796 } 6797 } 6798 6799 SmallVector<int, 5> Ranges; 6800 if (FiveFields) 6801 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6802 else 6803 Ranges.append({15, 7, 15}); 6804 6805 for (unsigned i=0; i<Fields.size(); ++i) { 6806 int IntField; 6807 ValidString &= !Fields[i].getAsInteger(10, IntField); 6808 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6809 } 6810 6811 if (!ValidString) 6812 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6813 << Arg->getSourceRange(); 6814 } else if (IsAArch64Builtin && Fields.size() == 1) { 6815 // If the register name is one of those that appear in the condition below 6816 // and the special register builtin being used is one of the write builtins, 6817 // then we require that the argument provided for writing to the register 6818 // is an integer constant expression. This is because it will be lowered to 6819 // an MSR (immediate) instruction, so we need to know the immediate at 6820 // compile time. 6821 if (TheCall->getNumArgs() != 2) 6822 return false; 6823 6824 std::string RegLower = Reg.lower(); 6825 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6826 RegLower != "pan" && RegLower != "uao") 6827 return false; 6828 6829 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6830 } 6831 6832 return false; 6833 } 6834 6835 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 6836 /// Emit an error and return true on failure; return false on success. 6837 /// TypeStr is a string containing the type descriptor of the value returned by 6838 /// the builtin and the descriptors of the expected type of the arguments. 6839 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 6840 6841 assert((TypeStr[0] != '\0') && 6842 "Invalid types in PPC MMA builtin declaration"); 6843 6844 unsigned Mask = 0; 6845 unsigned ArgNum = 0; 6846 6847 // The first type in TypeStr is the type of the value returned by the 6848 // builtin. So we first read that type and change the type of TheCall. 6849 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6850 TheCall->setType(type); 6851 6852 while (*TypeStr != '\0') { 6853 Mask = 0; 6854 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6855 if (ArgNum >= TheCall->getNumArgs()) { 6856 ArgNum++; 6857 break; 6858 } 6859 6860 Expr *Arg = TheCall->getArg(ArgNum); 6861 QualType ArgType = Arg->getType(); 6862 6863 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 6864 (!ExpectedType->isVoidPointerType() && 6865 ArgType.getCanonicalType() != ExpectedType)) 6866 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6867 << ArgType << ExpectedType << 1 << 0 << 0; 6868 6869 // If the value of the Mask is not 0, we have a constraint in the size of 6870 // the integer argument so here we ensure the argument is a constant that 6871 // is in the valid range. 6872 if (Mask != 0 && 6873 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 6874 return true; 6875 6876 ArgNum++; 6877 } 6878 6879 // In case we exited early from the previous loop, there are other types to 6880 // read from TypeStr. So we need to read them all to ensure we have the right 6881 // number of arguments in TheCall and if it is not the case, to display a 6882 // better error message. 6883 while (*TypeStr != '\0') { 6884 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6885 ArgNum++; 6886 } 6887 if (checkArgCount(*this, TheCall, ArgNum)) 6888 return true; 6889 6890 return false; 6891 } 6892 6893 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6894 /// This checks that the target supports __builtin_longjmp and 6895 /// that val is a constant 1. 6896 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6897 if (!Context.getTargetInfo().hasSjLjLowering()) 6898 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6899 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6900 6901 Expr *Arg = TheCall->getArg(1); 6902 llvm::APSInt Result; 6903 6904 // TODO: This is less than ideal. Overload this to take a value. 6905 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6906 return true; 6907 6908 if (Result != 1) 6909 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6910 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6911 6912 return false; 6913 } 6914 6915 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6916 /// This checks that the target supports __builtin_setjmp. 6917 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6918 if (!Context.getTargetInfo().hasSjLjLowering()) 6919 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6920 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6921 return false; 6922 } 6923 6924 namespace { 6925 6926 class UncoveredArgHandler { 6927 enum { Unknown = -1, AllCovered = -2 }; 6928 6929 signed FirstUncoveredArg = Unknown; 6930 SmallVector<const Expr *, 4> DiagnosticExprs; 6931 6932 public: 6933 UncoveredArgHandler() = default; 6934 6935 bool hasUncoveredArg() const { 6936 return (FirstUncoveredArg >= 0); 6937 } 6938 6939 unsigned getUncoveredArg() const { 6940 assert(hasUncoveredArg() && "no uncovered argument"); 6941 return FirstUncoveredArg; 6942 } 6943 6944 void setAllCovered() { 6945 // A string has been found with all arguments covered, so clear out 6946 // the diagnostics. 6947 DiagnosticExprs.clear(); 6948 FirstUncoveredArg = AllCovered; 6949 } 6950 6951 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6952 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6953 6954 // Don't update if a previous string covers all arguments. 6955 if (FirstUncoveredArg == AllCovered) 6956 return; 6957 6958 // UncoveredArgHandler tracks the highest uncovered argument index 6959 // and with it all the strings that match this index. 6960 if (NewFirstUncoveredArg == FirstUncoveredArg) 6961 DiagnosticExprs.push_back(StrExpr); 6962 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6963 DiagnosticExprs.clear(); 6964 DiagnosticExprs.push_back(StrExpr); 6965 FirstUncoveredArg = NewFirstUncoveredArg; 6966 } 6967 } 6968 6969 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6970 }; 6971 6972 enum StringLiteralCheckType { 6973 SLCT_NotALiteral, 6974 SLCT_UncheckedLiteral, 6975 SLCT_CheckedLiteral 6976 }; 6977 6978 } // namespace 6979 6980 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6981 BinaryOperatorKind BinOpKind, 6982 bool AddendIsRight) { 6983 unsigned BitWidth = Offset.getBitWidth(); 6984 unsigned AddendBitWidth = Addend.getBitWidth(); 6985 // There might be negative interim results. 6986 if (Addend.isUnsigned()) { 6987 Addend = Addend.zext(++AddendBitWidth); 6988 Addend.setIsSigned(true); 6989 } 6990 // Adjust the bit width of the APSInts. 6991 if (AddendBitWidth > BitWidth) { 6992 Offset = Offset.sext(AddendBitWidth); 6993 BitWidth = AddendBitWidth; 6994 } else if (BitWidth > AddendBitWidth) { 6995 Addend = Addend.sext(BitWidth); 6996 } 6997 6998 bool Ov = false; 6999 llvm::APSInt ResOffset = Offset; 7000 if (BinOpKind == BO_Add) 7001 ResOffset = Offset.sadd_ov(Addend, Ov); 7002 else { 7003 assert(AddendIsRight && BinOpKind == BO_Sub && 7004 "operator must be add or sub with addend on the right"); 7005 ResOffset = Offset.ssub_ov(Addend, Ov); 7006 } 7007 7008 // We add an offset to a pointer here so we should support an offset as big as 7009 // possible. 7010 if (Ov) { 7011 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7012 "index (intermediate) result too big"); 7013 Offset = Offset.sext(2 * BitWidth); 7014 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7015 return; 7016 } 7017 7018 Offset = ResOffset; 7019 } 7020 7021 namespace { 7022 7023 // This is a wrapper class around StringLiteral to support offsetted string 7024 // literals as format strings. It takes the offset into account when returning 7025 // the string and its length or the source locations to display notes correctly. 7026 class FormatStringLiteral { 7027 const StringLiteral *FExpr; 7028 int64_t Offset; 7029 7030 public: 7031 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7032 : FExpr(fexpr), Offset(Offset) {} 7033 7034 StringRef getString() const { 7035 return FExpr->getString().drop_front(Offset); 7036 } 7037 7038 unsigned getByteLength() const { 7039 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7040 } 7041 7042 unsigned getLength() const { return FExpr->getLength() - Offset; } 7043 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7044 7045 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7046 7047 QualType getType() const { return FExpr->getType(); } 7048 7049 bool isAscii() const { return FExpr->isAscii(); } 7050 bool isWide() const { return FExpr->isWide(); } 7051 bool isUTF8() const { return FExpr->isUTF8(); } 7052 bool isUTF16() const { return FExpr->isUTF16(); } 7053 bool isUTF32() const { return FExpr->isUTF32(); } 7054 bool isPascal() const { return FExpr->isPascal(); } 7055 7056 SourceLocation getLocationOfByte( 7057 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7058 const TargetInfo &Target, unsigned *StartToken = nullptr, 7059 unsigned *StartTokenByteOffset = nullptr) const { 7060 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7061 StartToken, StartTokenByteOffset); 7062 } 7063 7064 SourceLocation getBeginLoc() const LLVM_READONLY { 7065 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7066 } 7067 7068 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7069 }; 7070 7071 } // namespace 7072 7073 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7074 const Expr *OrigFormatExpr, 7075 ArrayRef<const Expr *> Args, 7076 bool HasVAListArg, unsigned format_idx, 7077 unsigned firstDataArg, 7078 Sema::FormatStringType Type, 7079 bool inFunctionCall, 7080 Sema::VariadicCallType CallType, 7081 llvm::SmallBitVector &CheckedVarArgs, 7082 UncoveredArgHandler &UncoveredArg, 7083 bool IgnoreStringsWithoutSpecifiers); 7084 7085 // Determine if an expression is a string literal or constant string. 7086 // If this function returns false on the arguments to a function expecting a 7087 // format string, we will usually need to emit a warning. 7088 // True string literals are then checked by CheckFormatString. 7089 static StringLiteralCheckType 7090 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7091 bool HasVAListArg, unsigned format_idx, 7092 unsigned firstDataArg, Sema::FormatStringType Type, 7093 Sema::VariadicCallType CallType, bool InFunctionCall, 7094 llvm::SmallBitVector &CheckedVarArgs, 7095 UncoveredArgHandler &UncoveredArg, 7096 llvm::APSInt Offset, 7097 bool IgnoreStringsWithoutSpecifiers = false) { 7098 if (S.isConstantEvaluated()) 7099 return SLCT_NotALiteral; 7100 tryAgain: 7101 assert(Offset.isSigned() && "invalid offset"); 7102 7103 if (E->isTypeDependent() || E->isValueDependent()) 7104 return SLCT_NotALiteral; 7105 7106 E = E->IgnoreParenCasts(); 7107 7108 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7109 // Technically -Wformat-nonliteral does not warn about this case. 7110 // The behavior of printf and friends in this case is implementation 7111 // dependent. Ideally if the format string cannot be null then 7112 // it should have a 'nonnull' attribute in the function prototype. 7113 return SLCT_UncheckedLiteral; 7114 7115 switch (E->getStmtClass()) { 7116 case Stmt::BinaryConditionalOperatorClass: 7117 case Stmt::ConditionalOperatorClass: { 7118 // The expression is a literal if both sub-expressions were, and it was 7119 // completely checked only if both sub-expressions were checked. 7120 const AbstractConditionalOperator *C = 7121 cast<AbstractConditionalOperator>(E); 7122 7123 // Determine whether it is necessary to check both sub-expressions, for 7124 // example, because the condition expression is a constant that can be 7125 // evaluated at compile time. 7126 bool CheckLeft = true, CheckRight = true; 7127 7128 bool Cond; 7129 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7130 S.isConstantEvaluated())) { 7131 if (Cond) 7132 CheckRight = false; 7133 else 7134 CheckLeft = false; 7135 } 7136 7137 // We need to maintain the offsets for the right and the left hand side 7138 // separately to check if every possible indexed expression is a valid 7139 // string literal. They might have different offsets for different string 7140 // literals in the end. 7141 StringLiteralCheckType Left; 7142 if (!CheckLeft) 7143 Left = SLCT_UncheckedLiteral; 7144 else { 7145 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7146 HasVAListArg, format_idx, firstDataArg, 7147 Type, CallType, InFunctionCall, 7148 CheckedVarArgs, UncoveredArg, Offset, 7149 IgnoreStringsWithoutSpecifiers); 7150 if (Left == SLCT_NotALiteral || !CheckRight) { 7151 return Left; 7152 } 7153 } 7154 7155 StringLiteralCheckType Right = checkFormatStringExpr( 7156 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7157 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7158 IgnoreStringsWithoutSpecifiers); 7159 7160 return (CheckLeft && Left < Right) ? Left : Right; 7161 } 7162 7163 case Stmt::ImplicitCastExprClass: 7164 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7165 goto tryAgain; 7166 7167 case Stmt::OpaqueValueExprClass: 7168 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7169 E = src; 7170 goto tryAgain; 7171 } 7172 return SLCT_NotALiteral; 7173 7174 case Stmt::PredefinedExprClass: 7175 // While __func__, etc., are technically not string literals, they 7176 // cannot contain format specifiers and thus are not a security 7177 // liability. 7178 return SLCT_UncheckedLiteral; 7179 7180 case Stmt::DeclRefExprClass: { 7181 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7182 7183 // As an exception, do not flag errors for variables binding to 7184 // const string literals. 7185 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7186 bool isConstant = false; 7187 QualType T = DR->getType(); 7188 7189 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7190 isConstant = AT->getElementType().isConstant(S.Context); 7191 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7192 isConstant = T.isConstant(S.Context) && 7193 PT->getPointeeType().isConstant(S.Context); 7194 } else if (T->isObjCObjectPointerType()) { 7195 // In ObjC, there is usually no "const ObjectPointer" type, 7196 // so don't check if the pointee type is constant. 7197 isConstant = T.isConstant(S.Context); 7198 } 7199 7200 if (isConstant) { 7201 if (const Expr *Init = VD->getAnyInitializer()) { 7202 // Look through initializers like const char c[] = { "foo" } 7203 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7204 if (InitList->isStringLiteralInit()) 7205 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7206 } 7207 return checkFormatStringExpr(S, Init, Args, 7208 HasVAListArg, format_idx, 7209 firstDataArg, Type, CallType, 7210 /*InFunctionCall*/ false, CheckedVarArgs, 7211 UncoveredArg, Offset); 7212 } 7213 } 7214 7215 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7216 // special check to see if the format string is a function parameter 7217 // of the function calling the printf function. If the function 7218 // has an attribute indicating it is a printf-like function, then we 7219 // should suppress warnings concerning non-literals being used in a call 7220 // to a vprintf function. For example: 7221 // 7222 // void 7223 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7224 // va_list ap; 7225 // va_start(ap, fmt); 7226 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7227 // ... 7228 // } 7229 if (HasVAListArg) { 7230 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7231 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7232 int PVIndex = PV->getFunctionScopeIndex() + 1; 7233 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7234 // adjust for implicit parameter 7235 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7236 if (MD->isInstance()) 7237 ++PVIndex; 7238 // We also check if the formats are compatible. 7239 // We can't pass a 'scanf' string to a 'printf' function. 7240 if (PVIndex == PVFormat->getFormatIdx() && 7241 Type == S.GetFormatStringType(PVFormat)) 7242 return SLCT_UncheckedLiteral; 7243 } 7244 } 7245 } 7246 } 7247 } 7248 7249 return SLCT_NotALiteral; 7250 } 7251 7252 case Stmt::CallExprClass: 7253 case Stmt::CXXMemberCallExprClass: { 7254 const CallExpr *CE = cast<CallExpr>(E); 7255 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7256 bool IsFirst = true; 7257 StringLiteralCheckType CommonResult; 7258 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7259 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7260 StringLiteralCheckType Result = checkFormatStringExpr( 7261 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7262 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7263 IgnoreStringsWithoutSpecifiers); 7264 if (IsFirst) { 7265 CommonResult = Result; 7266 IsFirst = false; 7267 } 7268 } 7269 if (!IsFirst) 7270 return CommonResult; 7271 7272 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7273 unsigned BuiltinID = FD->getBuiltinID(); 7274 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7275 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7276 const Expr *Arg = CE->getArg(0); 7277 return checkFormatStringExpr(S, Arg, Args, 7278 HasVAListArg, format_idx, 7279 firstDataArg, Type, CallType, 7280 InFunctionCall, CheckedVarArgs, 7281 UncoveredArg, Offset, 7282 IgnoreStringsWithoutSpecifiers); 7283 } 7284 } 7285 } 7286 7287 return SLCT_NotALiteral; 7288 } 7289 case Stmt::ObjCMessageExprClass: { 7290 const auto *ME = cast<ObjCMessageExpr>(E); 7291 if (const auto *MD = ME->getMethodDecl()) { 7292 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7293 // As a special case heuristic, if we're using the method -[NSBundle 7294 // localizedStringForKey:value:table:], ignore any key strings that lack 7295 // format specifiers. The idea is that if the key doesn't have any 7296 // format specifiers then its probably just a key to map to the 7297 // localized strings. If it does have format specifiers though, then its 7298 // likely that the text of the key is the format string in the 7299 // programmer's language, and should be checked. 7300 const ObjCInterfaceDecl *IFace; 7301 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7302 IFace->getIdentifier()->isStr("NSBundle") && 7303 MD->getSelector().isKeywordSelector( 7304 {"localizedStringForKey", "value", "table"})) { 7305 IgnoreStringsWithoutSpecifiers = true; 7306 } 7307 7308 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7309 return checkFormatStringExpr( 7310 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7311 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7312 IgnoreStringsWithoutSpecifiers); 7313 } 7314 } 7315 7316 return SLCT_NotALiteral; 7317 } 7318 case Stmt::ObjCStringLiteralClass: 7319 case Stmt::StringLiteralClass: { 7320 const StringLiteral *StrE = nullptr; 7321 7322 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7323 StrE = ObjCFExpr->getString(); 7324 else 7325 StrE = cast<StringLiteral>(E); 7326 7327 if (StrE) { 7328 if (Offset.isNegative() || Offset > StrE->getLength()) { 7329 // TODO: It would be better to have an explicit warning for out of 7330 // bounds literals. 7331 return SLCT_NotALiteral; 7332 } 7333 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7334 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7335 firstDataArg, Type, InFunctionCall, CallType, 7336 CheckedVarArgs, UncoveredArg, 7337 IgnoreStringsWithoutSpecifiers); 7338 return SLCT_CheckedLiteral; 7339 } 7340 7341 return SLCT_NotALiteral; 7342 } 7343 case Stmt::BinaryOperatorClass: { 7344 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7345 7346 // A string literal + an int offset is still a string literal. 7347 if (BinOp->isAdditiveOp()) { 7348 Expr::EvalResult LResult, RResult; 7349 7350 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7351 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7352 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7353 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7354 7355 if (LIsInt != RIsInt) { 7356 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7357 7358 if (LIsInt) { 7359 if (BinOpKind == BO_Add) { 7360 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7361 E = BinOp->getRHS(); 7362 goto tryAgain; 7363 } 7364 } else { 7365 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7366 E = BinOp->getLHS(); 7367 goto tryAgain; 7368 } 7369 } 7370 } 7371 7372 return SLCT_NotALiteral; 7373 } 7374 case Stmt::UnaryOperatorClass: { 7375 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7376 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7377 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7378 Expr::EvalResult IndexResult; 7379 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7380 Expr::SE_NoSideEffects, 7381 S.isConstantEvaluated())) { 7382 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7383 /*RHS is int*/ true); 7384 E = ASE->getBase(); 7385 goto tryAgain; 7386 } 7387 } 7388 7389 return SLCT_NotALiteral; 7390 } 7391 7392 default: 7393 return SLCT_NotALiteral; 7394 } 7395 } 7396 7397 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7398 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7399 .Case("scanf", FST_Scanf) 7400 .Cases("printf", "printf0", FST_Printf) 7401 .Cases("NSString", "CFString", FST_NSString) 7402 .Case("strftime", FST_Strftime) 7403 .Case("strfmon", FST_Strfmon) 7404 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7405 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7406 .Case("os_trace", FST_OSLog) 7407 .Case("os_log", FST_OSLog) 7408 .Default(FST_Unknown); 7409 } 7410 7411 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7412 /// functions) for correct use of format strings. 7413 /// Returns true if a format string has been fully checked. 7414 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7415 ArrayRef<const Expr *> Args, 7416 bool IsCXXMember, 7417 VariadicCallType CallType, 7418 SourceLocation Loc, SourceRange Range, 7419 llvm::SmallBitVector &CheckedVarArgs) { 7420 FormatStringInfo FSI; 7421 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7422 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7423 FSI.FirstDataArg, GetFormatStringType(Format), 7424 CallType, Loc, Range, CheckedVarArgs); 7425 return false; 7426 } 7427 7428 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7429 bool HasVAListArg, unsigned format_idx, 7430 unsigned firstDataArg, FormatStringType Type, 7431 VariadicCallType CallType, 7432 SourceLocation Loc, SourceRange Range, 7433 llvm::SmallBitVector &CheckedVarArgs) { 7434 // CHECK: printf/scanf-like function is called with no format string. 7435 if (format_idx >= Args.size()) { 7436 Diag(Loc, diag::warn_missing_format_string) << Range; 7437 return false; 7438 } 7439 7440 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7441 7442 // CHECK: format string is not a string literal. 7443 // 7444 // Dynamically generated format strings are difficult to 7445 // automatically vet at compile time. Requiring that format strings 7446 // are string literals: (1) permits the checking of format strings by 7447 // the compiler and thereby (2) can practically remove the source of 7448 // many format string exploits. 7449 7450 // Format string can be either ObjC string (e.g. @"%d") or 7451 // C string (e.g. "%d") 7452 // ObjC string uses the same format specifiers as C string, so we can use 7453 // the same format string checking logic for both ObjC and C strings. 7454 UncoveredArgHandler UncoveredArg; 7455 StringLiteralCheckType CT = 7456 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7457 format_idx, firstDataArg, Type, CallType, 7458 /*IsFunctionCall*/ true, CheckedVarArgs, 7459 UncoveredArg, 7460 /*no string offset*/ llvm::APSInt(64, false) = 0); 7461 7462 // Generate a diagnostic where an uncovered argument is detected. 7463 if (UncoveredArg.hasUncoveredArg()) { 7464 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7465 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7466 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7467 } 7468 7469 if (CT != SLCT_NotALiteral) 7470 // Literal format string found, check done! 7471 return CT == SLCT_CheckedLiteral; 7472 7473 // Strftime is particular as it always uses a single 'time' argument, 7474 // so it is safe to pass a non-literal string. 7475 if (Type == FST_Strftime) 7476 return false; 7477 7478 // Do not emit diag when the string param is a macro expansion and the 7479 // format is either NSString or CFString. This is a hack to prevent 7480 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7481 // which are usually used in place of NS and CF string literals. 7482 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7483 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7484 return false; 7485 7486 // If there are no arguments specified, warn with -Wformat-security, otherwise 7487 // warn only with -Wformat-nonliteral. 7488 if (Args.size() == firstDataArg) { 7489 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7490 << OrigFormatExpr->getSourceRange(); 7491 switch (Type) { 7492 default: 7493 break; 7494 case FST_Kprintf: 7495 case FST_FreeBSDKPrintf: 7496 case FST_Printf: 7497 Diag(FormatLoc, diag::note_format_security_fixit) 7498 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7499 break; 7500 case FST_NSString: 7501 Diag(FormatLoc, diag::note_format_security_fixit) 7502 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7503 break; 7504 } 7505 } else { 7506 Diag(FormatLoc, diag::warn_format_nonliteral) 7507 << OrigFormatExpr->getSourceRange(); 7508 } 7509 return false; 7510 } 7511 7512 namespace { 7513 7514 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7515 protected: 7516 Sema &S; 7517 const FormatStringLiteral *FExpr; 7518 const Expr *OrigFormatExpr; 7519 const Sema::FormatStringType FSType; 7520 const unsigned FirstDataArg; 7521 const unsigned NumDataArgs; 7522 const char *Beg; // Start of format string. 7523 const bool HasVAListArg; 7524 ArrayRef<const Expr *> Args; 7525 unsigned FormatIdx; 7526 llvm::SmallBitVector CoveredArgs; 7527 bool usesPositionalArgs = false; 7528 bool atFirstArg = true; 7529 bool inFunctionCall; 7530 Sema::VariadicCallType CallType; 7531 llvm::SmallBitVector &CheckedVarArgs; 7532 UncoveredArgHandler &UncoveredArg; 7533 7534 public: 7535 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7536 const Expr *origFormatExpr, 7537 const Sema::FormatStringType type, unsigned firstDataArg, 7538 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7539 ArrayRef<const Expr *> Args, unsigned formatIdx, 7540 bool inFunctionCall, Sema::VariadicCallType callType, 7541 llvm::SmallBitVector &CheckedVarArgs, 7542 UncoveredArgHandler &UncoveredArg) 7543 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7544 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7545 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7546 inFunctionCall(inFunctionCall), CallType(callType), 7547 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7548 CoveredArgs.resize(numDataArgs); 7549 CoveredArgs.reset(); 7550 } 7551 7552 void DoneProcessing(); 7553 7554 void HandleIncompleteSpecifier(const char *startSpecifier, 7555 unsigned specifierLen) override; 7556 7557 void HandleInvalidLengthModifier( 7558 const analyze_format_string::FormatSpecifier &FS, 7559 const analyze_format_string::ConversionSpecifier &CS, 7560 const char *startSpecifier, unsigned specifierLen, 7561 unsigned DiagID); 7562 7563 void HandleNonStandardLengthModifier( 7564 const analyze_format_string::FormatSpecifier &FS, 7565 const char *startSpecifier, unsigned specifierLen); 7566 7567 void HandleNonStandardConversionSpecifier( 7568 const analyze_format_string::ConversionSpecifier &CS, 7569 const char *startSpecifier, unsigned specifierLen); 7570 7571 void HandlePosition(const char *startPos, unsigned posLen) override; 7572 7573 void HandleInvalidPosition(const char *startSpecifier, 7574 unsigned specifierLen, 7575 analyze_format_string::PositionContext p) override; 7576 7577 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7578 7579 void HandleNullChar(const char *nullCharacter) override; 7580 7581 template <typename Range> 7582 static void 7583 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7584 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7585 bool IsStringLocation, Range StringRange, 7586 ArrayRef<FixItHint> Fixit = None); 7587 7588 protected: 7589 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7590 const char *startSpec, 7591 unsigned specifierLen, 7592 const char *csStart, unsigned csLen); 7593 7594 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7595 const char *startSpec, 7596 unsigned specifierLen); 7597 7598 SourceRange getFormatStringRange(); 7599 CharSourceRange getSpecifierRange(const char *startSpecifier, 7600 unsigned specifierLen); 7601 SourceLocation getLocationOfByte(const char *x); 7602 7603 const Expr *getDataArg(unsigned i) const; 7604 7605 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7606 const analyze_format_string::ConversionSpecifier &CS, 7607 const char *startSpecifier, unsigned specifierLen, 7608 unsigned argIndex); 7609 7610 template <typename Range> 7611 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7612 bool IsStringLocation, Range StringRange, 7613 ArrayRef<FixItHint> Fixit = None); 7614 }; 7615 7616 } // namespace 7617 7618 SourceRange CheckFormatHandler::getFormatStringRange() { 7619 return OrigFormatExpr->getSourceRange(); 7620 } 7621 7622 CharSourceRange CheckFormatHandler:: 7623 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7624 SourceLocation Start = getLocationOfByte(startSpecifier); 7625 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7626 7627 // Advance the end SourceLocation by one due to half-open ranges. 7628 End = End.getLocWithOffset(1); 7629 7630 return CharSourceRange::getCharRange(Start, End); 7631 } 7632 7633 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7634 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7635 S.getLangOpts(), S.Context.getTargetInfo()); 7636 } 7637 7638 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7639 unsigned specifierLen){ 7640 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7641 getLocationOfByte(startSpecifier), 7642 /*IsStringLocation*/true, 7643 getSpecifierRange(startSpecifier, specifierLen)); 7644 } 7645 7646 void CheckFormatHandler::HandleInvalidLengthModifier( 7647 const analyze_format_string::FormatSpecifier &FS, 7648 const analyze_format_string::ConversionSpecifier &CS, 7649 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7650 using namespace analyze_format_string; 7651 7652 const LengthModifier &LM = FS.getLengthModifier(); 7653 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7654 7655 // See if we know how to fix this length modifier. 7656 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7657 if (FixedLM) { 7658 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7659 getLocationOfByte(LM.getStart()), 7660 /*IsStringLocation*/true, 7661 getSpecifierRange(startSpecifier, specifierLen)); 7662 7663 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7664 << FixedLM->toString() 7665 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7666 7667 } else { 7668 FixItHint Hint; 7669 if (DiagID == diag::warn_format_nonsensical_length) 7670 Hint = FixItHint::CreateRemoval(LMRange); 7671 7672 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7673 getLocationOfByte(LM.getStart()), 7674 /*IsStringLocation*/true, 7675 getSpecifierRange(startSpecifier, specifierLen), 7676 Hint); 7677 } 7678 } 7679 7680 void CheckFormatHandler::HandleNonStandardLengthModifier( 7681 const analyze_format_string::FormatSpecifier &FS, 7682 const char *startSpecifier, unsigned specifierLen) { 7683 using namespace analyze_format_string; 7684 7685 const LengthModifier &LM = FS.getLengthModifier(); 7686 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7687 7688 // See if we know how to fix this length modifier. 7689 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7690 if (FixedLM) { 7691 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7692 << LM.toString() << 0, 7693 getLocationOfByte(LM.getStart()), 7694 /*IsStringLocation*/true, 7695 getSpecifierRange(startSpecifier, specifierLen)); 7696 7697 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7698 << FixedLM->toString() 7699 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7700 7701 } else { 7702 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7703 << LM.toString() << 0, 7704 getLocationOfByte(LM.getStart()), 7705 /*IsStringLocation*/true, 7706 getSpecifierRange(startSpecifier, specifierLen)); 7707 } 7708 } 7709 7710 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7711 const analyze_format_string::ConversionSpecifier &CS, 7712 const char *startSpecifier, unsigned specifierLen) { 7713 using namespace analyze_format_string; 7714 7715 // See if we know how to fix this conversion specifier. 7716 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7717 if (FixedCS) { 7718 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7719 << CS.toString() << /*conversion specifier*/1, 7720 getLocationOfByte(CS.getStart()), 7721 /*IsStringLocation*/true, 7722 getSpecifierRange(startSpecifier, specifierLen)); 7723 7724 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7725 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7726 << FixedCS->toString() 7727 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7728 } else { 7729 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7730 << CS.toString() << /*conversion specifier*/1, 7731 getLocationOfByte(CS.getStart()), 7732 /*IsStringLocation*/true, 7733 getSpecifierRange(startSpecifier, specifierLen)); 7734 } 7735 } 7736 7737 void CheckFormatHandler::HandlePosition(const char *startPos, 7738 unsigned posLen) { 7739 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7740 getLocationOfByte(startPos), 7741 /*IsStringLocation*/true, 7742 getSpecifierRange(startPos, posLen)); 7743 } 7744 7745 void 7746 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7747 analyze_format_string::PositionContext p) { 7748 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7749 << (unsigned) p, 7750 getLocationOfByte(startPos), /*IsStringLocation*/true, 7751 getSpecifierRange(startPos, posLen)); 7752 } 7753 7754 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7755 unsigned posLen) { 7756 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7757 getLocationOfByte(startPos), 7758 /*IsStringLocation*/true, 7759 getSpecifierRange(startPos, posLen)); 7760 } 7761 7762 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7763 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7764 // The presence of a null character is likely an error. 7765 EmitFormatDiagnostic( 7766 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7767 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7768 getFormatStringRange()); 7769 } 7770 } 7771 7772 // Note that this may return NULL if there was an error parsing or building 7773 // one of the argument expressions. 7774 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7775 return Args[FirstDataArg + i]; 7776 } 7777 7778 void CheckFormatHandler::DoneProcessing() { 7779 // Does the number of data arguments exceed the number of 7780 // format conversions in the format string? 7781 if (!HasVAListArg) { 7782 // Find any arguments that weren't covered. 7783 CoveredArgs.flip(); 7784 signed notCoveredArg = CoveredArgs.find_first(); 7785 if (notCoveredArg >= 0) { 7786 assert((unsigned)notCoveredArg < NumDataArgs); 7787 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7788 } else { 7789 UncoveredArg.setAllCovered(); 7790 } 7791 } 7792 } 7793 7794 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7795 const Expr *ArgExpr) { 7796 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7797 "Invalid state"); 7798 7799 if (!ArgExpr) 7800 return; 7801 7802 SourceLocation Loc = ArgExpr->getBeginLoc(); 7803 7804 if (S.getSourceManager().isInSystemMacro(Loc)) 7805 return; 7806 7807 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7808 for (auto E : DiagnosticExprs) 7809 PDiag << E->getSourceRange(); 7810 7811 CheckFormatHandler::EmitFormatDiagnostic( 7812 S, IsFunctionCall, DiagnosticExprs[0], 7813 PDiag, Loc, /*IsStringLocation*/false, 7814 DiagnosticExprs[0]->getSourceRange()); 7815 } 7816 7817 bool 7818 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7819 SourceLocation Loc, 7820 const char *startSpec, 7821 unsigned specifierLen, 7822 const char *csStart, 7823 unsigned csLen) { 7824 bool keepGoing = true; 7825 if (argIndex < NumDataArgs) { 7826 // Consider the argument coverered, even though the specifier doesn't 7827 // make sense. 7828 CoveredArgs.set(argIndex); 7829 } 7830 else { 7831 // If argIndex exceeds the number of data arguments we 7832 // don't issue a warning because that is just a cascade of warnings (and 7833 // they may have intended '%%' anyway). We don't want to continue processing 7834 // the format string after this point, however, as we will like just get 7835 // gibberish when trying to match arguments. 7836 keepGoing = false; 7837 } 7838 7839 StringRef Specifier(csStart, csLen); 7840 7841 // If the specifier in non-printable, it could be the first byte of a UTF-8 7842 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7843 // hex value. 7844 std::string CodePointStr; 7845 if (!llvm::sys::locale::isPrint(*csStart)) { 7846 llvm::UTF32 CodePoint; 7847 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7848 const llvm::UTF8 *E = 7849 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7850 llvm::ConversionResult Result = 7851 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7852 7853 if (Result != llvm::conversionOK) { 7854 unsigned char FirstChar = *csStart; 7855 CodePoint = (llvm::UTF32)FirstChar; 7856 } 7857 7858 llvm::raw_string_ostream OS(CodePointStr); 7859 if (CodePoint < 256) 7860 OS << "\\x" << llvm::format("%02x", CodePoint); 7861 else if (CodePoint <= 0xFFFF) 7862 OS << "\\u" << llvm::format("%04x", CodePoint); 7863 else 7864 OS << "\\U" << llvm::format("%08x", CodePoint); 7865 OS.flush(); 7866 Specifier = CodePointStr; 7867 } 7868 7869 EmitFormatDiagnostic( 7870 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7871 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7872 7873 return keepGoing; 7874 } 7875 7876 void 7877 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7878 const char *startSpec, 7879 unsigned specifierLen) { 7880 EmitFormatDiagnostic( 7881 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7882 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7883 } 7884 7885 bool 7886 CheckFormatHandler::CheckNumArgs( 7887 const analyze_format_string::FormatSpecifier &FS, 7888 const analyze_format_string::ConversionSpecifier &CS, 7889 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7890 7891 if (argIndex >= NumDataArgs) { 7892 PartialDiagnostic PDiag = FS.usesPositionalArg() 7893 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7894 << (argIndex+1) << NumDataArgs) 7895 : S.PDiag(diag::warn_printf_insufficient_data_args); 7896 EmitFormatDiagnostic( 7897 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7898 getSpecifierRange(startSpecifier, specifierLen)); 7899 7900 // Since more arguments than conversion tokens are given, by extension 7901 // all arguments are covered, so mark this as so. 7902 UncoveredArg.setAllCovered(); 7903 return false; 7904 } 7905 return true; 7906 } 7907 7908 template<typename Range> 7909 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7910 SourceLocation Loc, 7911 bool IsStringLocation, 7912 Range StringRange, 7913 ArrayRef<FixItHint> FixIt) { 7914 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7915 Loc, IsStringLocation, StringRange, FixIt); 7916 } 7917 7918 /// If the format string is not within the function call, emit a note 7919 /// so that the function call and string are in diagnostic messages. 7920 /// 7921 /// \param InFunctionCall if true, the format string is within the function 7922 /// call and only one diagnostic message will be produced. Otherwise, an 7923 /// extra note will be emitted pointing to location of the format string. 7924 /// 7925 /// \param ArgumentExpr the expression that is passed as the format string 7926 /// argument in the function call. Used for getting locations when two 7927 /// diagnostics are emitted. 7928 /// 7929 /// \param PDiag the callee should already have provided any strings for the 7930 /// diagnostic message. This function only adds locations and fixits 7931 /// to diagnostics. 7932 /// 7933 /// \param Loc primary location for diagnostic. If two diagnostics are 7934 /// required, one will be at Loc and a new SourceLocation will be created for 7935 /// the other one. 7936 /// 7937 /// \param IsStringLocation if true, Loc points to the format string should be 7938 /// used for the note. Otherwise, Loc points to the argument list and will 7939 /// be used with PDiag. 7940 /// 7941 /// \param StringRange some or all of the string to highlight. This is 7942 /// templated so it can accept either a CharSourceRange or a SourceRange. 7943 /// 7944 /// \param FixIt optional fix it hint for the format string. 7945 template <typename Range> 7946 void CheckFormatHandler::EmitFormatDiagnostic( 7947 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7948 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7949 Range StringRange, ArrayRef<FixItHint> FixIt) { 7950 if (InFunctionCall) { 7951 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7952 D << StringRange; 7953 D << FixIt; 7954 } else { 7955 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7956 << ArgumentExpr->getSourceRange(); 7957 7958 const Sema::SemaDiagnosticBuilder &Note = 7959 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7960 diag::note_format_string_defined); 7961 7962 Note << StringRange; 7963 Note << FixIt; 7964 } 7965 } 7966 7967 //===--- CHECK: Printf format string checking ------------------------------===// 7968 7969 namespace { 7970 7971 class CheckPrintfHandler : public CheckFormatHandler { 7972 public: 7973 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7974 const Expr *origFormatExpr, 7975 const Sema::FormatStringType type, unsigned firstDataArg, 7976 unsigned numDataArgs, bool isObjC, const char *beg, 7977 bool hasVAListArg, ArrayRef<const Expr *> Args, 7978 unsigned formatIdx, bool inFunctionCall, 7979 Sema::VariadicCallType CallType, 7980 llvm::SmallBitVector &CheckedVarArgs, 7981 UncoveredArgHandler &UncoveredArg) 7982 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7983 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7984 inFunctionCall, CallType, CheckedVarArgs, 7985 UncoveredArg) {} 7986 7987 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7988 7989 /// Returns true if '%@' specifiers are allowed in the format string. 7990 bool allowsObjCArg() const { 7991 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7992 FSType == Sema::FST_OSTrace; 7993 } 7994 7995 bool HandleInvalidPrintfConversionSpecifier( 7996 const analyze_printf::PrintfSpecifier &FS, 7997 const char *startSpecifier, 7998 unsigned specifierLen) override; 7999 8000 void handleInvalidMaskType(StringRef MaskType) override; 8001 8002 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8003 const char *startSpecifier, 8004 unsigned specifierLen) override; 8005 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8006 const char *StartSpecifier, 8007 unsigned SpecifierLen, 8008 const Expr *E); 8009 8010 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8011 const char *startSpecifier, unsigned specifierLen); 8012 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8013 const analyze_printf::OptionalAmount &Amt, 8014 unsigned type, 8015 const char *startSpecifier, unsigned specifierLen); 8016 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8017 const analyze_printf::OptionalFlag &flag, 8018 const char *startSpecifier, unsigned specifierLen); 8019 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8020 const analyze_printf::OptionalFlag &ignoredFlag, 8021 const analyze_printf::OptionalFlag &flag, 8022 const char *startSpecifier, unsigned specifierLen); 8023 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8024 const Expr *E); 8025 8026 void HandleEmptyObjCModifierFlag(const char *startFlag, 8027 unsigned flagLen) override; 8028 8029 void HandleInvalidObjCModifierFlag(const char *startFlag, 8030 unsigned flagLen) override; 8031 8032 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8033 const char *flagsEnd, 8034 const char *conversionPosition) 8035 override; 8036 }; 8037 8038 } // namespace 8039 8040 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8041 const analyze_printf::PrintfSpecifier &FS, 8042 const char *startSpecifier, 8043 unsigned specifierLen) { 8044 const analyze_printf::PrintfConversionSpecifier &CS = 8045 FS.getConversionSpecifier(); 8046 8047 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8048 getLocationOfByte(CS.getStart()), 8049 startSpecifier, specifierLen, 8050 CS.getStart(), CS.getLength()); 8051 } 8052 8053 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8054 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8055 } 8056 8057 bool CheckPrintfHandler::HandleAmount( 8058 const analyze_format_string::OptionalAmount &Amt, 8059 unsigned k, const char *startSpecifier, 8060 unsigned specifierLen) { 8061 if (Amt.hasDataArgument()) { 8062 if (!HasVAListArg) { 8063 unsigned argIndex = Amt.getArgIndex(); 8064 if (argIndex >= NumDataArgs) { 8065 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8066 << k, 8067 getLocationOfByte(Amt.getStart()), 8068 /*IsStringLocation*/true, 8069 getSpecifierRange(startSpecifier, specifierLen)); 8070 // Don't do any more checking. We will just emit 8071 // spurious errors. 8072 return false; 8073 } 8074 8075 // Type check the data argument. It should be an 'int'. 8076 // Although not in conformance with C99, we also allow the argument to be 8077 // an 'unsigned int' as that is a reasonably safe case. GCC also 8078 // doesn't emit a warning for that case. 8079 CoveredArgs.set(argIndex); 8080 const Expr *Arg = getDataArg(argIndex); 8081 if (!Arg) 8082 return false; 8083 8084 QualType T = Arg->getType(); 8085 8086 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8087 assert(AT.isValid()); 8088 8089 if (!AT.matchesType(S.Context, T)) { 8090 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8091 << k << AT.getRepresentativeTypeName(S.Context) 8092 << T << Arg->getSourceRange(), 8093 getLocationOfByte(Amt.getStart()), 8094 /*IsStringLocation*/true, 8095 getSpecifierRange(startSpecifier, specifierLen)); 8096 // Don't do any more checking. We will just emit 8097 // spurious errors. 8098 return false; 8099 } 8100 } 8101 } 8102 return true; 8103 } 8104 8105 void CheckPrintfHandler::HandleInvalidAmount( 8106 const analyze_printf::PrintfSpecifier &FS, 8107 const analyze_printf::OptionalAmount &Amt, 8108 unsigned type, 8109 const char *startSpecifier, 8110 unsigned specifierLen) { 8111 const analyze_printf::PrintfConversionSpecifier &CS = 8112 FS.getConversionSpecifier(); 8113 8114 FixItHint fixit = 8115 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8116 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8117 Amt.getConstantLength())) 8118 : FixItHint(); 8119 8120 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8121 << type << CS.toString(), 8122 getLocationOfByte(Amt.getStart()), 8123 /*IsStringLocation*/true, 8124 getSpecifierRange(startSpecifier, specifierLen), 8125 fixit); 8126 } 8127 8128 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8129 const analyze_printf::OptionalFlag &flag, 8130 const char *startSpecifier, 8131 unsigned specifierLen) { 8132 // Warn about pointless flag with a fixit removal. 8133 const analyze_printf::PrintfConversionSpecifier &CS = 8134 FS.getConversionSpecifier(); 8135 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8136 << flag.toString() << CS.toString(), 8137 getLocationOfByte(flag.getPosition()), 8138 /*IsStringLocation*/true, 8139 getSpecifierRange(startSpecifier, specifierLen), 8140 FixItHint::CreateRemoval( 8141 getSpecifierRange(flag.getPosition(), 1))); 8142 } 8143 8144 void CheckPrintfHandler::HandleIgnoredFlag( 8145 const analyze_printf::PrintfSpecifier &FS, 8146 const analyze_printf::OptionalFlag &ignoredFlag, 8147 const analyze_printf::OptionalFlag &flag, 8148 const char *startSpecifier, 8149 unsigned specifierLen) { 8150 // Warn about ignored flag with a fixit removal. 8151 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8152 << ignoredFlag.toString() << flag.toString(), 8153 getLocationOfByte(ignoredFlag.getPosition()), 8154 /*IsStringLocation*/true, 8155 getSpecifierRange(startSpecifier, specifierLen), 8156 FixItHint::CreateRemoval( 8157 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8158 } 8159 8160 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8161 unsigned flagLen) { 8162 // Warn about an empty flag. 8163 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8164 getLocationOfByte(startFlag), 8165 /*IsStringLocation*/true, 8166 getSpecifierRange(startFlag, flagLen)); 8167 } 8168 8169 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8170 unsigned flagLen) { 8171 // Warn about an invalid flag. 8172 auto Range = getSpecifierRange(startFlag, flagLen); 8173 StringRef flag(startFlag, flagLen); 8174 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8175 getLocationOfByte(startFlag), 8176 /*IsStringLocation*/true, 8177 Range, FixItHint::CreateRemoval(Range)); 8178 } 8179 8180 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8181 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8182 // Warn about using '[...]' without a '@' conversion. 8183 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8184 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8185 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8186 getLocationOfByte(conversionPosition), 8187 /*IsStringLocation*/true, 8188 Range, FixItHint::CreateRemoval(Range)); 8189 } 8190 8191 // Determines if the specified is a C++ class or struct containing 8192 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8193 // "c_str()"). 8194 template<typename MemberKind> 8195 static llvm::SmallPtrSet<MemberKind*, 1> 8196 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8197 const RecordType *RT = Ty->getAs<RecordType>(); 8198 llvm::SmallPtrSet<MemberKind*, 1> Results; 8199 8200 if (!RT) 8201 return Results; 8202 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8203 if (!RD || !RD->getDefinition()) 8204 return Results; 8205 8206 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8207 Sema::LookupMemberName); 8208 R.suppressDiagnostics(); 8209 8210 // We just need to include all members of the right kind turned up by the 8211 // filter, at this point. 8212 if (S.LookupQualifiedName(R, RT->getDecl())) 8213 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8214 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8215 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8216 Results.insert(FK); 8217 } 8218 return Results; 8219 } 8220 8221 /// Check if we could call '.c_str()' on an object. 8222 /// 8223 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8224 /// allow the call, or if it would be ambiguous). 8225 bool Sema::hasCStrMethod(const Expr *E) { 8226 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8227 8228 MethodSet Results = 8229 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8230 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8231 MI != ME; ++MI) 8232 if ((*MI)->getMinRequiredArguments() == 0) 8233 return true; 8234 return false; 8235 } 8236 8237 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8238 // better diagnostic if so. AT is assumed to be valid. 8239 // Returns true when a c_str() conversion method is found. 8240 bool CheckPrintfHandler::checkForCStrMembers( 8241 const analyze_printf::ArgType &AT, const Expr *E) { 8242 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8243 8244 MethodSet Results = 8245 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8246 8247 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8248 MI != ME; ++MI) { 8249 const CXXMethodDecl *Method = *MI; 8250 if (Method->getMinRequiredArguments() == 0 && 8251 AT.matchesType(S.Context, Method->getReturnType())) { 8252 // FIXME: Suggest parens if the expression needs them. 8253 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8254 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8255 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8256 return true; 8257 } 8258 } 8259 8260 return false; 8261 } 8262 8263 bool 8264 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8265 &FS, 8266 const char *startSpecifier, 8267 unsigned specifierLen) { 8268 using namespace analyze_format_string; 8269 using namespace analyze_printf; 8270 8271 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8272 8273 if (FS.consumesDataArgument()) { 8274 if (atFirstArg) { 8275 atFirstArg = false; 8276 usesPositionalArgs = FS.usesPositionalArg(); 8277 } 8278 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8279 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8280 startSpecifier, specifierLen); 8281 return false; 8282 } 8283 } 8284 8285 // First check if the field width, precision, and conversion specifier 8286 // have matching data arguments. 8287 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8288 startSpecifier, specifierLen)) { 8289 return false; 8290 } 8291 8292 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8293 startSpecifier, specifierLen)) { 8294 return false; 8295 } 8296 8297 if (!CS.consumesDataArgument()) { 8298 // FIXME: Technically specifying a precision or field width here 8299 // makes no sense. Worth issuing a warning at some point. 8300 return true; 8301 } 8302 8303 // Consume the argument. 8304 unsigned argIndex = FS.getArgIndex(); 8305 if (argIndex < NumDataArgs) { 8306 // The check to see if the argIndex is valid will come later. 8307 // We set the bit here because we may exit early from this 8308 // function if we encounter some other error. 8309 CoveredArgs.set(argIndex); 8310 } 8311 8312 // FreeBSD kernel extensions. 8313 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8314 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8315 // We need at least two arguments. 8316 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8317 return false; 8318 8319 // Claim the second argument. 8320 CoveredArgs.set(argIndex + 1); 8321 8322 // Type check the first argument (int for %b, pointer for %D) 8323 const Expr *Ex = getDataArg(argIndex); 8324 const analyze_printf::ArgType &AT = 8325 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8326 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8327 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8328 EmitFormatDiagnostic( 8329 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8330 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8331 << false << Ex->getSourceRange(), 8332 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8333 getSpecifierRange(startSpecifier, specifierLen)); 8334 8335 // Type check the second argument (char * for both %b and %D) 8336 Ex = getDataArg(argIndex + 1); 8337 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8338 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8339 EmitFormatDiagnostic( 8340 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8341 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8342 << false << Ex->getSourceRange(), 8343 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8344 getSpecifierRange(startSpecifier, specifierLen)); 8345 8346 return true; 8347 } 8348 8349 // Check for using an Objective-C specific conversion specifier 8350 // in a non-ObjC literal. 8351 if (!allowsObjCArg() && CS.isObjCArg()) { 8352 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8353 specifierLen); 8354 } 8355 8356 // %P can only be used with os_log. 8357 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8358 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8359 specifierLen); 8360 } 8361 8362 // %n is not allowed with os_log. 8363 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8364 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8365 getLocationOfByte(CS.getStart()), 8366 /*IsStringLocation*/ false, 8367 getSpecifierRange(startSpecifier, specifierLen)); 8368 8369 return true; 8370 } 8371 8372 // Only scalars are allowed for os_trace. 8373 if (FSType == Sema::FST_OSTrace && 8374 (CS.getKind() == ConversionSpecifier::PArg || 8375 CS.getKind() == ConversionSpecifier::sArg || 8376 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8377 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8378 specifierLen); 8379 } 8380 8381 // Check for use of public/private annotation outside of os_log(). 8382 if (FSType != Sema::FST_OSLog) { 8383 if (FS.isPublic().isSet()) { 8384 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8385 << "public", 8386 getLocationOfByte(FS.isPublic().getPosition()), 8387 /*IsStringLocation*/ false, 8388 getSpecifierRange(startSpecifier, specifierLen)); 8389 } 8390 if (FS.isPrivate().isSet()) { 8391 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8392 << "private", 8393 getLocationOfByte(FS.isPrivate().getPosition()), 8394 /*IsStringLocation*/ false, 8395 getSpecifierRange(startSpecifier, specifierLen)); 8396 } 8397 } 8398 8399 // Check for invalid use of field width 8400 if (!FS.hasValidFieldWidth()) { 8401 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8402 startSpecifier, specifierLen); 8403 } 8404 8405 // Check for invalid use of precision 8406 if (!FS.hasValidPrecision()) { 8407 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8408 startSpecifier, specifierLen); 8409 } 8410 8411 // Precision is mandatory for %P specifier. 8412 if (CS.getKind() == ConversionSpecifier::PArg && 8413 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8414 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8415 getLocationOfByte(startSpecifier), 8416 /*IsStringLocation*/ false, 8417 getSpecifierRange(startSpecifier, specifierLen)); 8418 } 8419 8420 // Check each flag does not conflict with any other component. 8421 if (!FS.hasValidThousandsGroupingPrefix()) 8422 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8423 if (!FS.hasValidLeadingZeros()) 8424 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8425 if (!FS.hasValidPlusPrefix()) 8426 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8427 if (!FS.hasValidSpacePrefix()) 8428 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8429 if (!FS.hasValidAlternativeForm()) 8430 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8431 if (!FS.hasValidLeftJustified()) 8432 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8433 8434 // Check that flags are not ignored by another flag 8435 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8436 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8437 startSpecifier, specifierLen); 8438 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8439 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8440 startSpecifier, specifierLen); 8441 8442 // Check the length modifier is valid with the given conversion specifier. 8443 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8444 S.getLangOpts())) 8445 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8446 diag::warn_format_nonsensical_length); 8447 else if (!FS.hasStandardLengthModifier()) 8448 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8449 else if (!FS.hasStandardLengthConversionCombination()) 8450 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8451 diag::warn_format_non_standard_conversion_spec); 8452 8453 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8454 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8455 8456 // The remaining checks depend on the data arguments. 8457 if (HasVAListArg) 8458 return true; 8459 8460 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8461 return false; 8462 8463 const Expr *Arg = getDataArg(argIndex); 8464 if (!Arg) 8465 return true; 8466 8467 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8468 } 8469 8470 static bool requiresParensToAddCast(const Expr *E) { 8471 // FIXME: We should have a general way to reason about operator 8472 // precedence and whether parens are actually needed here. 8473 // Take care of a few common cases where they aren't. 8474 const Expr *Inside = E->IgnoreImpCasts(); 8475 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8476 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8477 8478 switch (Inside->getStmtClass()) { 8479 case Stmt::ArraySubscriptExprClass: 8480 case Stmt::CallExprClass: 8481 case Stmt::CharacterLiteralClass: 8482 case Stmt::CXXBoolLiteralExprClass: 8483 case Stmt::DeclRefExprClass: 8484 case Stmt::FloatingLiteralClass: 8485 case Stmt::IntegerLiteralClass: 8486 case Stmt::MemberExprClass: 8487 case Stmt::ObjCArrayLiteralClass: 8488 case Stmt::ObjCBoolLiteralExprClass: 8489 case Stmt::ObjCBoxedExprClass: 8490 case Stmt::ObjCDictionaryLiteralClass: 8491 case Stmt::ObjCEncodeExprClass: 8492 case Stmt::ObjCIvarRefExprClass: 8493 case Stmt::ObjCMessageExprClass: 8494 case Stmt::ObjCPropertyRefExprClass: 8495 case Stmt::ObjCStringLiteralClass: 8496 case Stmt::ObjCSubscriptRefExprClass: 8497 case Stmt::ParenExprClass: 8498 case Stmt::StringLiteralClass: 8499 case Stmt::UnaryOperatorClass: 8500 return false; 8501 default: 8502 return true; 8503 } 8504 } 8505 8506 static std::pair<QualType, StringRef> 8507 shouldNotPrintDirectly(const ASTContext &Context, 8508 QualType IntendedTy, 8509 const Expr *E) { 8510 // Use a 'while' to peel off layers of typedefs. 8511 QualType TyTy = IntendedTy; 8512 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8513 StringRef Name = UserTy->getDecl()->getName(); 8514 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8515 .Case("CFIndex", Context.getNSIntegerType()) 8516 .Case("NSInteger", Context.getNSIntegerType()) 8517 .Case("NSUInteger", Context.getNSUIntegerType()) 8518 .Case("SInt32", Context.IntTy) 8519 .Case("UInt32", Context.UnsignedIntTy) 8520 .Default(QualType()); 8521 8522 if (!CastTy.isNull()) 8523 return std::make_pair(CastTy, Name); 8524 8525 TyTy = UserTy->desugar(); 8526 } 8527 8528 // Strip parens if necessary. 8529 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8530 return shouldNotPrintDirectly(Context, 8531 PE->getSubExpr()->getType(), 8532 PE->getSubExpr()); 8533 8534 // If this is a conditional expression, then its result type is constructed 8535 // via usual arithmetic conversions and thus there might be no necessary 8536 // typedef sugar there. Recurse to operands to check for NSInteger & 8537 // Co. usage condition. 8538 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8539 QualType TrueTy, FalseTy; 8540 StringRef TrueName, FalseName; 8541 8542 std::tie(TrueTy, TrueName) = 8543 shouldNotPrintDirectly(Context, 8544 CO->getTrueExpr()->getType(), 8545 CO->getTrueExpr()); 8546 std::tie(FalseTy, FalseName) = 8547 shouldNotPrintDirectly(Context, 8548 CO->getFalseExpr()->getType(), 8549 CO->getFalseExpr()); 8550 8551 if (TrueTy == FalseTy) 8552 return std::make_pair(TrueTy, TrueName); 8553 else if (TrueTy.isNull()) 8554 return std::make_pair(FalseTy, FalseName); 8555 else if (FalseTy.isNull()) 8556 return std::make_pair(TrueTy, TrueName); 8557 } 8558 8559 return std::make_pair(QualType(), StringRef()); 8560 } 8561 8562 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8563 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8564 /// type do not count. 8565 static bool 8566 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8567 QualType From = ICE->getSubExpr()->getType(); 8568 QualType To = ICE->getType(); 8569 // It's an integer promotion if the destination type is the promoted 8570 // source type. 8571 if (ICE->getCastKind() == CK_IntegralCast && 8572 From->isPromotableIntegerType() && 8573 S.Context.getPromotedIntegerType(From) == To) 8574 return true; 8575 // Look through vector types, since we do default argument promotion for 8576 // those in OpenCL. 8577 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8578 From = VecTy->getElementType(); 8579 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8580 To = VecTy->getElementType(); 8581 // It's a floating promotion if the source type is a lower rank. 8582 return ICE->getCastKind() == CK_FloatingCast && 8583 S.Context.getFloatingTypeOrder(From, To) < 0; 8584 } 8585 8586 bool 8587 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8588 const char *StartSpecifier, 8589 unsigned SpecifierLen, 8590 const Expr *E) { 8591 using namespace analyze_format_string; 8592 using namespace analyze_printf; 8593 8594 // Now type check the data expression that matches the 8595 // format specifier. 8596 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8597 if (!AT.isValid()) 8598 return true; 8599 8600 QualType ExprTy = E->getType(); 8601 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8602 ExprTy = TET->getUnderlyingExpr()->getType(); 8603 } 8604 8605 // Diagnose attempts to print a boolean value as a character. Unlike other 8606 // -Wformat diagnostics, this is fine from a type perspective, but it still 8607 // doesn't make sense. 8608 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8609 E->isKnownToHaveBooleanValue()) { 8610 const CharSourceRange &CSR = 8611 getSpecifierRange(StartSpecifier, SpecifierLen); 8612 SmallString<4> FSString; 8613 llvm::raw_svector_ostream os(FSString); 8614 FS.toString(os); 8615 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8616 << FSString, 8617 E->getExprLoc(), false, CSR); 8618 return true; 8619 } 8620 8621 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8622 if (Match == analyze_printf::ArgType::Match) 8623 return true; 8624 8625 // Look through argument promotions for our error message's reported type. 8626 // This includes the integral and floating promotions, but excludes array 8627 // and function pointer decay (seeing that an argument intended to be a 8628 // string has type 'char [6]' is probably more confusing than 'char *') and 8629 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8630 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8631 if (isArithmeticArgumentPromotion(S, ICE)) { 8632 E = ICE->getSubExpr(); 8633 ExprTy = E->getType(); 8634 8635 // Check if we didn't match because of an implicit cast from a 'char' 8636 // or 'short' to an 'int'. This is done because printf is a varargs 8637 // function. 8638 if (ICE->getType() == S.Context.IntTy || 8639 ICE->getType() == S.Context.UnsignedIntTy) { 8640 // All further checking is done on the subexpression 8641 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8642 AT.matchesType(S.Context, ExprTy); 8643 if (ImplicitMatch == analyze_printf::ArgType::Match) 8644 return true; 8645 if (ImplicitMatch == ArgType::NoMatchPedantic || 8646 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8647 Match = ImplicitMatch; 8648 } 8649 } 8650 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8651 // Special case for 'a', which has type 'int' in C. 8652 // Note, however, that we do /not/ want to treat multibyte constants like 8653 // 'MooV' as characters! This form is deprecated but still exists. 8654 if (ExprTy == S.Context.IntTy) 8655 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8656 ExprTy = S.Context.CharTy; 8657 } 8658 8659 // Look through enums to their underlying type. 8660 bool IsEnum = false; 8661 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8662 ExprTy = EnumTy->getDecl()->getIntegerType(); 8663 IsEnum = true; 8664 } 8665 8666 // %C in an Objective-C context prints a unichar, not a wchar_t. 8667 // If the argument is an integer of some kind, believe the %C and suggest 8668 // a cast instead of changing the conversion specifier. 8669 QualType IntendedTy = ExprTy; 8670 if (isObjCContext() && 8671 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8672 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8673 !ExprTy->isCharType()) { 8674 // 'unichar' is defined as a typedef of unsigned short, but we should 8675 // prefer using the typedef if it is visible. 8676 IntendedTy = S.Context.UnsignedShortTy; 8677 8678 // While we are here, check if the value is an IntegerLiteral that happens 8679 // to be within the valid range. 8680 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8681 const llvm::APInt &V = IL->getValue(); 8682 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8683 return true; 8684 } 8685 8686 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8687 Sema::LookupOrdinaryName); 8688 if (S.LookupName(Result, S.getCurScope())) { 8689 NamedDecl *ND = Result.getFoundDecl(); 8690 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8691 if (TD->getUnderlyingType() == IntendedTy) 8692 IntendedTy = S.Context.getTypedefType(TD); 8693 } 8694 } 8695 } 8696 8697 // Special-case some of Darwin's platform-independence types by suggesting 8698 // casts to primitive types that are known to be large enough. 8699 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8700 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8701 QualType CastTy; 8702 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8703 if (!CastTy.isNull()) { 8704 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8705 // (long in ASTContext). Only complain to pedants. 8706 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8707 (AT.isSizeT() || AT.isPtrdiffT()) && 8708 AT.matchesType(S.Context, CastTy)) 8709 Match = ArgType::NoMatchPedantic; 8710 IntendedTy = CastTy; 8711 ShouldNotPrintDirectly = true; 8712 } 8713 } 8714 8715 // We may be able to offer a FixItHint if it is a supported type. 8716 PrintfSpecifier fixedFS = FS; 8717 bool Success = 8718 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8719 8720 if (Success) { 8721 // Get the fix string from the fixed format specifier 8722 SmallString<16> buf; 8723 llvm::raw_svector_ostream os(buf); 8724 fixedFS.toString(os); 8725 8726 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8727 8728 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8729 unsigned Diag; 8730 switch (Match) { 8731 case ArgType::Match: llvm_unreachable("expected non-matching"); 8732 case ArgType::NoMatchPedantic: 8733 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8734 break; 8735 case ArgType::NoMatchTypeConfusion: 8736 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8737 break; 8738 case ArgType::NoMatch: 8739 Diag = diag::warn_format_conversion_argument_type_mismatch; 8740 break; 8741 } 8742 8743 // In this case, the specifier is wrong and should be changed to match 8744 // the argument. 8745 EmitFormatDiagnostic(S.PDiag(Diag) 8746 << AT.getRepresentativeTypeName(S.Context) 8747 << IntendedTy << IsEnum << E->getSourceRange(), 8748 E->getBeginLoc(), 8749 /*IsStringLocation*/ false, SpecRange, 8750 FixItHint::CreateReplacement(SpecRange, os.str())); 8751 } else { 8752 // The canonical type for formatting this value is different from the 8753 // actual type of the expression. (This occurs, for example, with Darwin's 8754 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8755 // should be printed as 'long' for 64-bit compatibility.) 8756 // Rather than emitting a normal format/argument mismatch, we want to 8757 // add a cast to the recommended type (and correct the format string 8758 // if necessary). 8759 SmallString<16> CastBuf; 8760 llvm::raw_svector_ostream CastFix(CastBuf); 8761 CastFix << "("; 8762 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8763 CastFix << ")"; 8764 8765 SmallVector<FixItHint,4> Hints; 8766 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8767 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8768 8769 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8770 // If there's already a cast present, just replace it. 8771 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8772 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8773 8774 } else if (!requiresParensToAddCast(E)) { 8775 // If the expression has high enough precedence, 8776 // just write the C-style cast. 8777 Hints.push_back( 8778 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8779 } else { 8780 // Otherwise, add parens around the expression as well as the cast. 8781 CastFix << "("; 8782 Hints.push_back( 8783 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8784 8785 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8786 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8787 } 8788 8789 if (ShouldNotPrintDirectly) { 8790 // The expression has a type that should not be printed directly. 8791 // We extract the name from the typedef because we don't want to show 8792 // the underlying type in the diagnostic. 8793 StringRef Name; 8794 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8795 Name = TypedefTy->getDecl()->getName(); 8796 else 8797 Name = CastTyName; 8798 unsigned Diag = Match == ArgType::NoMatchPedantic 8799 ? diag::warn_format_argument_needs_cast_pedantic 8800 : diag::warn_format_argument_needs_cast; 8801 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8802 << E->getSourceRange(), 8803 E->getBeginLoc(), /*IsStringLocation=*/false, 8804 SpecRange, Hints); 8805 } else { 8806 // In this case, the expression could be printed using a different 8807 // specifier, but we've decided that the specifier is probably correct 8808 // and we should cast instead. Just use the normal warning message. 8809 EmitFormatDiagnostic( 8810 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8811 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8812 << E->getSourceRange(), 8813 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8814 } 8815 } 8816 } else { 8817 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8818 SpecifierLen); 8819 // Since the warning for passing non-POD types to variadic functions 8820 // was deferred until now, we emit a warning for non-POD 8821 // arguments here. 8822 switch (S.isValidVarArgType(ExprTy)) { 8823 case Sema::VAK_Valid: 8824 case Sema::VAK_ValidInCXX11: { 8825 unsigned Diag; 8826 switch (Match) { 8827 case ArgType::Match: llvm_unreachable("expected non-matching"); 8828 case ArgType::NoMatchPedantic: 8829 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8830 break; 8831 case ArgType::NoMatchTypeConfusion: 8832 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8833 break; 8834 case ArgType::NoMatch: 8835 Diag = diag::warn_format_conversion_argument_type_mismatch; 8836 break; 8837 } 8838 8839 EmitFormatDiagnostic( 8840 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8841 << IsEnum << CSR << E->getSourceRange(), 8842 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8843 break; 8844 } 8845 case Sema::VAK_Undefined: 8846 case Sema::VAK_MSVCUndefined: 8847 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8848 << S.getLangOpts().CPlusPlus11 << ExprTy 8849 << CallType 8850 << AT.getRepresentativeTypeName(S.Context) << CSR 8851 << E->getSourceRange(), 8852 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8853 checkForCStrMembers(AT, E); 8854 break; 8855 8856 case Sema::VAK_Invalid: 8857 if (ExprTy->isObjCObjectType()) 8858 EmitFormatDiagnostic( 8859 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8860 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8861 << AT.getRepresentativeTypeName(S.Context) << CSR 8862 << E->getSourceRange(), 8863 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8864 else 8865 // FIXME: If this is an initializer list, suggest removing the braces 8866 // or inserting a cast to the target type. 8867 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8868 << isa<InitListExpr>(E) << ExprTy << CallType 8869 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8870 break; 8871 } 8872 8873 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8874 "format string specifier index out of range"); 8875 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8876 } 8877 8878 return true; 8879 } 8880 8881 //===--- CHECK: Scanf format string checking ------------------------------===// 8882 8883 namespace { 8884 8885 class CheckScanfHandler : public CheckFormatHandler { 8886 public: 8887 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8888 const Expr *origFormatExpr, Sema::FormatStringType type, 8889 unsigned firstDataArg, unsigned numDataArgs, 8890 const char *beg, bool hasVAListArg, 8891 ArrayRef<const Expr *> Args, unsigned formatIdx, 8892 bool inFunctionCall, Sema::VariadicCallType CallType, 8893 llvm::SmallBitVector &CheckedVarArgs, 8894 UncoveredArgHandler &UncoveredArg) 8895 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8896 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8897 inFunctionCall, CallType, CheckedVarArgs, 8898 UncoveredArg) {} 8899 8900 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8901 const char *startSpecifier, 8902 unsigned specifierLen) override; 8903 8904 bool HandleInvalidScanfConversionSpecifier( 8905 const analyze_scanf::ScanfSpecifier &FS, 8906 const char *startSpecifier, 8907 unsigned specifierLen) override; 8908 8909 void HandleIncompleteScanList(const char *start, const char *end) override; 8910 }; 8911 8912 } // namespace 8913 8914 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8915 const char *end) { 8916 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8917 getLocationOfByte(end), /*IsStringLocation*/true, 8918 getSpecifierRange(start, end - start)); 8919 } 8920 8921 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8922 const analyze_scanf::ScanfSpecifier &FS, 8923 const char *startSpecifier, 8924 unsigned specifierLen) { 8925 const analyze_scanf::ScanfConversionSpecifier &CS = 8926 FS.getConversionSpecifier(); 8927 8928 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8929 getLocationOfByte(CS.getStart()), 8930 startSpecifier, specifierLen, 8931 CS.getStart(), CS.getLength()); 8932 } 8933 8934 bool CheckScanfHandler::HandleScanfSpecifier( 8935 const analyze_scanf::ScanfSpecifier &FS, 8936 const char *startSpecifier, 8937 unsigned specifierLen) { 8938 using namespace analyze_scanf; 8939 using namespace analyze_format_string; 8940 8941 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8942 8943 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8944 // be used to decide if we are using positional arguments consistently. 8945 if (FS.consumesDataArgument()) { 8946 if (atFirstArg) { 8947 atFirstArg = false; 8948 usesPositionalArgs = FS.usesPositionalArg(); 8949 } 8950 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8951 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8952 startSpecifier, specifierLen); 8953 return false; 8954 } 8955 } 8956 8957 // Check if the field with is non-zero. 8958 const OptionalAmount &Amt = FS.getFieldWidth(); 8959 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8960 if (Amt.getConstantAmount() == 0) { 8961 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8962 Amt.getConstantLength()); 8963 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8964 getLocationOfByte(Amt.getStart()), 8965 /*IsStringLocation*/true, R, 8966 FixItHint::CreateRemoval(R)); 8967 } 8968 } 8969 8970 if (!FS.consumesDataArgument()) { 8971 // FIXME: Technically specifying a precision or field width here 8972 // makes no sense. Worth issuing a warning at some point. 8973 return true; 8974 } 8975 8976 // Consume the argument. 8977 unsigned argIndex = FS.getArgIndex(); 8978 if (argIndex < NumDataArgs) { 8979 // The check to see if the argIndex is valid will come later. 8980 // We set the bit here because we may exit early from this 8981 // function if we encounter some other error. 8982 CoveredArgs.set(argIndex); 8983 } 8984 8985 // Check the length modifier is valid with the given conversion specifier. 8986 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8987 S.getLangOpts())) 8988 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8989 diag::warn_format_nonsensical_length); 8990 else if (!FS.hasStandardLengthModifier()) 8991 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8992 else if (!FS.hasStandardLengthConversionCombination()) 8993 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8994 diag::warn_format_non_standard_conversion_spec); 8995 8996 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8997 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8998 8999 // The remaining checks depend on the data arguments. 9000 if (HasVAListArg) 9001 return true; 9002 9003 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9004 return false; 9005 9006 // Check that the argument type matches the format specifier. 9007 const Expr *Ex = getDataArg(argIndex); 9008 if (!Ex) 9009 return true; 9010 9011 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9012 9013 if (!AT.isValid()) { 9014 return true; 9015 } 9016 9017 analyze_format_string::ArgType::MatchKind Match = 9018 AT.matchesType(S.Context, Ex->getType()); 9019 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9020 if (Match == analyze_format_string::ArgType::Match) 9021 return true; 9022 9023 ScanfSpecifier fixedFS = FS; 9024 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9025 S.getLangOpts(), S.Context); 9026 9027 unsigned Diag = 9028 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9029 : diag::warn_format_conversion_argument_type_mismatch; 9030 9031 if (Success) { 9032 // Get the fix string from the fixed format specifier. 9033 SmallString<128> buf; 9034 llvm::raw_svector_ostream os(buf); 9035 fixedFS.toString(os); 9036 9037 EmitFormatDiagnostic( 9038 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9039 << Ex->getType() << false << Ex->getSourceRange(), 9040 Ex->getBeginLoc(), 9041 /*IsStringLocation*/ false, 9042 getSpecifierRange(startSpecifier, specifierLen), 9043 FixItHint::CreateReplacement( 9044 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9045 } else { 9046 EmitFormatDiagnostic(S.PDiag(Diag) 9047 << AT.getRepresentativeTypeName(S.Context) 9048 << Ex->getType() << false << Ex->getSourceRange(), 9049 Ex->getBeginLoc(), 9050 /*IsStringLocation*/ false, 9051 getSpecifierRange(startSpecifier, specifierLen)); 9052 } 9053 9054 return true; 9055 } 9056 9057 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9058 const Expr *OrigFormatExpr, 9059 ArrayRef<const Expr *> Args, 9060 bool HasVAListArg, unsigned format_idx, 9061 unsigned firstDataArg, 9062 Sema::FormatStringType Type, 9063 bool inFunctionCall, 9064 Sema::VariadicCallType CallType, 9065 llvm::SmallBitVector &CheckedVarArgs, 9066 UncoveredArgHandler &UncoveredArg, 9067 bool IgnoreStringsWithoutSpecifiers) { 9068 // CHECK: is the format string a wide literal? 9069 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9070 CheckFormatHandler::EmitFormatDiagnostic( 9071 S, inFunctionCall, Args[format_idx], 9072 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9073 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9074 return; 9075 } 9076 9077 // Str - The format string. NOTE: this is NOT null-terminated! 9078 StringRef StrRef = FExpr->getString(); 9079 const char *Str = StrRef.data(); 9080 // Account for cases where the string literal is truncated in a declaration. 9081 const ConstantArrayType *T = 9082 S.Context.getAsConstantArrayType(FExpr->getType()); 9083 assert(T && "String literal not of constant array type!"); 9084 size_t TypeSize = T->getSize().getZExtValue(); 9085 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9086 const unsigned numDataArgs = Args.size() - firstDataArg; 9087 9088 if (IgnoreStringsWithoutSpecifiers && 9089 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9090 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9091 return; 9092 9093 // Emit a warning if the string literal is truncated and does not contain an 9094 // embedded null character. 9095 if (TypeSize <= StrRef.size() && 9096 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9097 CheckFormatHandler::EmitFormatDiagnostic( 9098 S, inFunctionCall, Args[format_idx], 9099 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9100 FExpr->getBeginLoc(), 9101 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9102 return; 9103 } 9104 9105 // CHECK: empty format string? 9106 if (StrLen == 0 && numDataArgs > 0) { 9107 CheckFormatHandler::EmitFormatDiagnostic( 9108 S, inFunctionCall, Args[format_idx], 9109 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9110 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9111 return; 9112 } 9113 9114 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9115 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9116 Type == Sema::FST_OSTrace) { 9117 CheckPrintfHandler H( 9118 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9119 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9120 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9121 CheckedVarArgs, UncoveredArg); 9122 9123 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9124 S.getLangOpts(), 9125 S.Context.getTargetInfo(), 9126 Type == Sema::FST_FreeBSDKPrintf)) 9127 H.DoneProcessing(); 9128 } else if (Type == Sema::FST_Scanf) { 9129 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9130 numDataArgs, Str, HasVAListArg, Args, format_idx, 9131 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9132 9133 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9134 S.getLangOpts(), 9135 S.Context.getTargetInfo())) 9136 H.DoneProcessing(); 9137 } // TODO: handle other formats 9138 } 9139 9140 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9141 // Str - The format string. NOTE: this is NOT null-terminated! 9142 StringRef StrRef = FExpr->getString(); 9143 const char *Str = StrRef.data(); 9144 // Account for cases where the string literal is truncated in a declaration. 9145 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9146 assert(T && "String literal not of constant array type!"); 9147 size_t TypeSize = T->getSize().getZExtValue(); 9148 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9149 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9150 getLangOpts(), 9151 Context.getTargetInfo()); 9152 } 9153 9154 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9155 9156 // Returns the related absolute value function that is larger, of 0 if one 9157 // does not exist. 9158 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9159 switch (AbsFunction) { 9160 default: 9161 return 0; 9162 9163 case Builtin::BI__builtin_abs: 9164 return Builtin::BI__builtin_labs; 9165 case Builtin::BI__builtin_labs: 9166 return Builtin::BI__builtin_llabs; 9167 case Builtin::BI__builtin_llabs: 9168 return 0; 9169 9170 case Builtin::BI__builtin_fabsf: 9171 return Builtin::BI__builtin_fabs; 9172 case Builtin::BI__builtin_fabs: 9173 return Builtin::BI__builtin_fabsl; 9174 case Builtin::BI__builtin_fabsl: 9175 return 0; 9176 9177 case Builtin::BI__builtin_cabsf: 9178 return Builtin::BI__builtin_cabs; 9179 case Builtin::BI__builtin_cabs: 9180 return Builtin::BI__builtin_cabsl; 9181 case Builtin::BI__builtin_cabsl: 9182 return 0; 9183 9184 case Builtin::BIabs: 9185 return Builtin::BIlabs; 9186 case Builtin::BIlabs: 9187 return Builtin::BIllabs; 9188 case Builtin::BIllabs: 9189 return 0; 9190 9191 case Builtin::BIfabsf: 9192 return Builtin::BIfabs; 9193 case Builtin::BIfabs: 9194 return Builtin::BIfabsl; 9195 case Builtin::BIfabsl: 9196 return 0; 9197 9198 case Builtin::BIcabsf: 9199 return Builtin::BIcabs; 9200 case Builtin::BIcabs: 9201 return Builtin::BIcabsl; 9202 case Builtin::BIcabsl: 9203 return 0; 9204 } 9205 } 9206 9207 // Returns the argument type of the absolute value function. 9208 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9209 unsigned AbsType) { 9210 if (AbsType == 0) 9211 return QualType(); 9212 9213 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9214 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9215 if (Error != ASTContext::GE_None) 9216 return QualType(); 9217 9218 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9219 if (!FT) 9220 return QualType(); 9221 9222 if (FT->getNumParams() != 1) 9223 return QualType(); 9224 9225 return FT->getParamType(0); 9226 } 9227 9228 // Returns the best absolute value function, or zero, based on type and 9229 // current absolute value function. 9230 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9231 unsigned AbsFunctionKind) { 9232 unsigned BestKind = 0; 9233 uint64_t ArgSize = Context.getTypeSize(ArgType); 9234 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9235 Kind = getLargerAbsoluteValueFunction(Kind)) { 9236 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9237 if (Context.getTypeSize(ParamType) >= ArgSize) { 9238 if (BestKind == 0) 9239 BestKind = Kind; 9240 else if (Context.hasSameType(ParamType, ArgType)) { 9241 BestKind = Kind; 9242 break; 9243 } 9244 } 9245 } 9246 return BestKind; 9247 } 9248 9249 enum AbsoluteValueKind { 9250 AVK_Integer, 9251 AVK_Floating, 9252 AVK_Complex 9253 }; 9254 9255 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9256 if (T->isIntegralOrEnumerationType()) 9257 return AVK_Integer; 9258 if (T->isRealFloatingType()) 9259 return AVK_Floating; 9260 if (T->isAnyComplexType()) 9261 return AVK_Complex; 9262 9263 llvm_unreachable("Type not integer, floating, or complex"); 9264 } 9265 9266 // Changes the absolute value function to a different type. Preserves whether 9267 // the function is a builtin. 9268 static unsigned changeAbsFunction(unsigned AbsKind, 9269 AbsoluteValueKind ValueKind) { 9270 switch (ValueKind) { 9271 case AVK_Integer: 9272 switch (AbsKind) { 9273 default: 9274 return 0; 9275 case Builtin::BI__builtin_fabsf: 9276 case Builtin::BI__builtin_fabs: 9277 case Builtin::BI__builtin_fabsl: 9278 case Builtin::BI__builtin_cabsf: 9279 case Builtin::BI__builtin_cabs: 9280 case Builtin::BI__builtin_cabsl: 9281 return Builtin::BI__builtin_abs; 9282 case Builtin::BIfabsf: 9283 case Builtin::BIfabs: 9284 case Builtin::BIfabsl: 9285 case Builtin::BIcabsf: 9286 case Builtin::BIcabs: 9287 case Builtin::BIcabsl: 9288 return Builtin::BIabs; 9289 } 9290 case AVK_Floating: 9291 switch (AbsKind) { 9292 default: 9293 return 0; 9294 case Builtin::BI__builtin_abs: 9295 case Builtin::BI__builtin_labs: 9296 case Builtin::BI__builtin_llabs: 9297 case Builtin::BI__builtin_cabsf: 9298 case Builtin::BI__builtin_cabs: 9299 case Builtin::BI__builtin_cabsl: 9300 return Builtin::BI__builtin_fabsf; 9301 case Builtin::BIabs: 9302 case Builtin::BIlabs: 9303 case Builtin::BIllabs: 9304 case Builtin::BIcabsf: 9305 case Builtin::BIcabs: 9306 case Builtin::BIcabsl: 9307 return Builtin::BIfabsf; 9308 } 9309 case AVK_Complex: 9310 switch (AbsKind) { 9311 default: 9312 return 0; 9313 case Builtin::BI__builtin_abs: 9314 case Builtin::BI__builtin_labs: 9315 case Builtin::BI__builtin_llabs: 9316 case Builtin::BI__builtin_fabsf: 9317 case Builtin::BI__builtin_fabs: 9318 case Builtin::BI__builtin_fabsl: 9319 return Builtin::BI__builtin_cabsf; 9320 case Builtin::BIabs: 9321 case Builtin::BIlabs: 9322 case Builtin::BIllabs: 9323 case Builtin::BIfabsf: 9324 case Builtin::BIfabs: 9325 case Builtin::BIfabsl: 9326 return Builtin::BIcabsf; 9327 } 9328 } 9329 llvm_unreachable("Unable to convert function"); 9330 } 9331 9332 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9333 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9334 if (!FnInfo) 9335 return 0; 9336 9337 switch (FDecl->getBuiltinID()) { 9338 default: 9339 return 0; 9340 case Builtin::BI__builtin_abs: 9341 case Builtin::BI__builtin_fabs: 9342 case Builtin::BI__builtin_fabsf: 9343 case Builtin::BI__builtin_fabsl: 9344 case Builtin::BI__builtin_labs: 9345 case Builtin::BI__builtin_llabs: 9346 case Builtin::BI__builtin_cabs: 9347 case Builtin::BI__builtin_cabsf: 9348 case Builtin::BI__builtin_cabsl: 9349 case Builtin::BIabs: 9350 case Builtin::BIlabs: 9351 case Builtin::BIllabs: 9352 case Builtin::BIfabs: 9353 case Builtin::BIfabsf: 9354 case Builtin::BIfabsl: 9355 case Builtin::BIcabs: 9356 case Builtin::BIcabsf: 9357 case Builtin::BIcabsl: 9358 return FDecl->getBuiltinID(); 9359 } 9360 llvm_unreachable("Unknown Builtin type"); 9361 } 9362 9363 // If the replacement is valid, emit a note with replacement function. 9364 // Additionally, suggest including the proper header if not already included. 9365 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9366 unsigned AbsKind, QualType ArgType) { 9367 bool EmitHeaderHint = true; 9368 const char *HeaderName = nullptr; 9369 const char *FunctionName = nullptr; 9370 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9371 FunctionName = "std::abs"; 9372 if (ArgType->isIntegralOrEnumerationType()) { 9373 HeaderName = "cstdlib"; 9374 } else if (ArgType->isRealFloatingType()) { 9375 HeaderName = "cmath"; 9376 } else { 9377 llvm_unreachable("Invalid Type"); 9378 } 9379 9380 // Lookup all std::abs 9381 if (NamespaceDecl *Std = S.getStdNamespace()) { 9382 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9383 R.suppressDiagnostics(); 9384 S.LookupQualifiedName(R, Std); 9385 9386 for (const auto *I : R) { 9387 const FunctionDecl *FDecl = nullptr; 9388 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9389 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9390 } else { 9391 FDecl = dyn_cast<FunctionDecl>(I); 9392 } 9393 if (!FDecl) 9394 continue; 9395 9396 // Found std::abs(), check that they are the right ones. 9397 if (FDecl->getNumParams() != 1) 9398 continue; 9399 9400 // Check that the parameter type can handle the argument. 9401 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9402 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9403 S.Context.getTypeSize(ArgType) <= 9404 S.Context.getTypeSize(ParamType)) { 9405 // Found a function, don't need the header hint. 9406 EmitHeaderHint = false; 9407 break; 9408 } 9409 } 9410 } 9411 } else { 9412 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9413 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9414 9415 if (HeaderName) { 9416 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9417 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9418 R.suppressDiagnostics(); 9419 S.LookupName(R, S.getCurScope()); 9420 9421 if (R.isSingleResult()) { 9422 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9423 if (FD && FD->getBuiltinID() == AbsKind) { 9424 EmitHeaderHint = false; 9425 } else { 9426 return; 9427 } 9428 } else if (!R.empty()) { 9429 return; 9430 } 9431 } 9432 } 9433 9434 S.Diag(Loc, diag::note_replace_abs_function) 9435 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9436 9437 if (!HeaderName) 9438 return; 9439 9440 if (!EmitHeaderHint) 9441 return; 9442 9443 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9444 << FunctionName; 9445 } 9446 9447 template <std::size_t StrLen> 9448 static bool IsStdFunction(const FunctionDecl *FDecl, 9449 const char (&Str)[StrLen]) { 9450 if (!FDecl) 9451 return false; 9452 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9453 return false; 9454 if (!FDecl->isInStdNamespace()) 9455 return false; 9456 9457 return true; 9458 } 9459 9460 // Warn when using the wrong abs() function. 9461 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9462 const FunctionDecl *FDecl) { 9463 if (Call->getNumArgs() != 1) 9464 return; 9465 9466 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9467 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9468 if (AbsKind == 0 && !IsStdAbs) 9469 return; 9470 9471 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9472 QualType ParamType = Call->getArg(0)->getType(); 9473 9474 // Unsigned types cannot be negative. Suggest removing the absolute value 9475 // function call. 9476 if (ArgType->isUnsignedIntegerType()) { 9477 const char *FunctionName = 9478 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9479 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9480 Diag(Call->getExprLoc(), diag::note_remove_abs) 9481 << FunctionName 9482 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9483 return; 9484 } 9485 9486 // Taking the absolute value of a pointer is very suspicious, they probably 9487 // wanted to index into an array, dereference a pointer, call a function, etc. 9488 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9489 unsigned DiagType = 0; 9490 if (ArgType->isFunctionType()) 9491 DiagType = 1; 9492 else if (ArgType->isArrayType()) 9493 DiagType = 2; 9494 9495 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9496 return; 9497 } 9498 9499 // std::abs has overloads which prevent most of the absolute value problems 9500 // from occurring. 9501 if (IsStdAbs) 9502 return; 9503 9504 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9505 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9506 9507 // The argument and parameter are the same kind. Check if they are the right 9508 // size. 9509 if (ArgValueKind == ParamValueKind) { 9510 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9511 return; 9512 9513 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9514 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9515 << FDecl << ArgType << ParamType; 9516 9517 if (NewAbsKind == 0) 9518 return; 9519 9520 emitReplacement(*this, Call->getExprLoc(), 9521 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9522 return; 9523 } 9524 9525 // ArgValueKind != ParamValueKind 9526 // The wrong type of absolute value function was used. Attempt to find the 9527 // proper one. 9528 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9529 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9530 if (NewAbsKind == 0) 9531 return; 9532 9533 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9534 << FDecl << ParamValueKind << ArgValueKind; 9535 9536 emitReplacement(*this, Call->getExprLoc(), 9537 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9538 } 9539 9540 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9541 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9542 const FunctionDecl *FDecl) { 9543 if (!Call || !FDecl) return; 9544 9545 // Ignore template specializations and macros. 9546 if (inTemplateInstantiation()) return; 9547 if (Call->getExprLoc().isMacroID()) return; 9548 9549 // Only care about the one template argument, two function parameter std::max 9550 if (Call->getNumArgs() != 2) return; 9551 if (!IsStdFunction(FDecl, "max")) return; 9552 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9553 if (!ArgList) return; 9554 if (ArgList->size() != 1) return; 9555 9556 // Check that template type argument is unsigned integer. 9557 const auto& TA = ArgList->get(0); 9558 if (TA.getKind() != TemplateArgument::Type) return; 9559 QualType ArgType = TA.getAsType(); 9560 if (!ArgType->isUnsignedIntegerType()) return; 9561 9562 // See if either argument is a literal zero. 9563 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9564 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9565 if (!MTE) return false; 9566 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9567 if (!Num) return false; 9568 if (Num->getValue() != 0) return false; 9569 return true; 9570 }; 9571 9572 const Expr *FirstArg = Call->getArg(0); 9573 const Expr *SecondArg = Call->getArg(1); 9574 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9575 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9576 9577 // Only warn when exactly one argument is zero. 9578 if (IsFirstArgZero == IsSecondArgZero) return; 9579 9580 SourceRange FirstRange = FirstArg->getSourceRange(); 9581 SourceRange SecondRange = SecondArg->getSourceRange(); 9582 9583 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9584 9585 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9586 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9587 9588 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9589 SourceRange RemovalRange; 9590 if (IsFirstArgZero) { 9591 RemovalRange = SourceRange(FirstRange.getBegin(), 9592 SecondRange.getBegin().getLocWithOffset(-1)); 9593 } else { 9594 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9595 SecondRange.getEnd()); 9596 } 9597 9598 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9599 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9600 << FixItHint::CreateRemoval(RemovalRange); 9601 } 9602 9603 //===--- CHECK: Standard memory functions ---------------------------------===// 9604 9605 /// Takes the expression passed to the size_t parameter of functions 9606 /// such as memcmp, strncat, etc and warns if it's a comparison. 9607 /// 9608 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9609 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9610 IdentifierInfo *FnName, 9611 SourceLocation FnLoc, 9612 SourceLocation RParenLoc) { 9613 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9614 if (!Size) 9615 return false; 9616 9617 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9618 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9619 return false; 9620 9621 SourceRange SizeRange = Size->getSourceRange(); 9622 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9623 << SizeRange << FnName; 9624 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9625 << FnName 9626 << FixItHint::CreateInsertion( 9627 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9628 << FixItHint::CreateRemoval(RParenLoc); 9629 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9630 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9631 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9632 ")"); 9633 9634 return true; 9635 } 9636 9637 /// Determine whether the given type is or contains a dynamic class type 9638 /// (e.g., whether it has a vtable). 9639 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9640 bool &IsContained) { 9641 // Look through array types while ignoring qualifiers. 9642 const Type *Ty = T->getBaseElementTypeUnsafe(); 9643 IsContained = false; 9644 9645 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9646 RD = RD ? RD->getDefinition() : nullptr; 9647 if (!RD || RD->isInvalidDecl()) 9648 return nullptr; 9649 9650 if (RD->isDynamicClass()) 9651 return RD; 9652 9653 // Check all the fields. If any bases were dynamic, the class is dynamic. 9654 // It's impossible for a class to transitively contain itself by value, so 9655 // infinite recursion is impossible. 9656 for (auto *FD : RD->fields()) { 9657 bool SubContained; 9658 if (const CXXRecordDecl *ContainedRD = 9659 getContainedDynamicClass(FD->getType(), SubContained)) { 9660 IsContained = true; 9661 return ContainedRD; 9662 } 9663 } 9664 9665 return nullptr; 9666 } 9667 9668 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9669 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9670 if (Unary->getKind() == UETT_SizeOf) 9671 return Unary; 9672 return nullptr; 9673 } 9674 9675 /// If E is a sizeof expression, returns its argument expression, 9676 /// otherwise returns NULL. 9677 static const Expr *getSizeOfExprArg(const Expr *E) { 9678 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9679 if (!SizeOf->isArgumentType()) 9680 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9681 return nullptr; 9682 } 9683 9684 /// If E is a sizeof expression, returns its argument type. 9685 static QualType getSizeOfArgType(const Expr *E) { 9686 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9687 return SizeOf->getTypeOfArgument(); 9688 return QualType(); 9689 } 9690 9691 namespace { 9692 9693 struct SearchNonTrivialToInitializeField 9694 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9695 using Super = 9696 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9697 9698 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9699 9700 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9701 SourceLocation SL) { 9702 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9703 asDerived().visitArray(PDIK, AT, SL); 9704 return; 9705 } 9706 9707 Super::visitWithKind(PDIK, FT, SL); 9708 } 9709 9710 void visitARCStrong(QualType FT, SourceLocation SL) { 9711 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9712 } 9713 void visitARCWeak(QualType FT, SourceLocation SL) { 9714 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9715 } 9716 void visitStruct(QualType FT, SourceLocation SL) { 9717 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9718 visit(FD->getType(), FD->getLocation()); 9719 } 9720 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9721 const ArrayType *AT, SourceLocation SL) { 9722 visit(getContext().getBaseElementType(AT), SL); 9723 } 9724 void visitTrivial(QualType FT, SourceLocation SL) {} 9725 9726 static void diag(QualType RT, const Expr *E, Sema &S) { 9727 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9728 } 9729 9730 ASTContext &getContext() { return S.getASTContext(); } 9731 9732 const Expr *E; 9733 Sema &S; 9734 }; 9735 9736 struct SearchNonTrivialToCopyField 9737 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9738 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9739 9740 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9741 9742 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9743 SourceLocation SL) { 9744 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9745 asDerived().visitArray(PCK, AT, SL); 9746 return; 9747 } 9748 9749 Super::visitWithKind(PCK, FT, SL); 9750 } 9751 9752 void visitARCStrong(QualType FT, SourceLocation SL) { 9753 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9754 } 9755 void visitARCWeak(QualType FT, SourceLocation SL) { 9756 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9757 } 9758 void visitStruct(QualType FT, SourceLocation SL) { 9759 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9760 visit(FD->getType(), FD->getLocation()); 9761 } 9762 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9763 SourceLocation SL) { 9764 visit(getContext().getBaseElementType(AT), SL); 9765 } 9766 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9767 SourceLocation SL) {} 9768 void visitTrivial(QualType FT, SourceLocation SL) {} 9769 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9770 9771 static void diag(QualType RT, const Expr *E, Sema &S) { 9772 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9773 } 9774 9775 ASTContext &getContext() { return S.getASTContext(); } 9776 9777 const Expr *E; 9778 Sema &S; 9779 }; 9780 9781 } 9782 9783 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9784 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9785 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9786 9787 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9788 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9789 return false; 9790 9791 return doesExprLikelyComputeSize(BO->getLHS()) || 9792 doesExprLikelyComputeSize(BO->getRHS()); 9793 } 9794 9795 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9796 } 9797 9798 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9799 /// 9800 /// \code 9801 /// #define MACRO 0 9802 /// foo(MACRO); 9803 /// foo(0); 9804 /// \endcode 9805 /// 9806 /// This should return true for the first call to foo, but not for the second 9807 /// (regardless of whether foo is a macro or function). 9808 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9809 SourceLocation CallLoc, 9810 SourceLocation ArgLoc) { 9811 if (!CallLoc.isMacroID()) 9812 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9813 9814 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9815 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9816 } 9817 9818 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9819 /// last two arguments transposed. 9820 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9821 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9822 return; 9823 9824 const Expr *SizeArg = 9825 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9826 9827 auto isLiteralZero = [](const Expr *E) { 9828 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9829 }; 9830 9831 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9832 SourceLocation CallLoc = Call->getRParenLoc(); 9833 SourceManager &SM = S.getSourceManager(); 9834 if (isLiteralZero(SizeArg) && 9835 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9836 9837 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9838 9839 // Some platforms #define bzero to __builtin_memset. See if this is the 9840 // case, and if so, emit a better diagnostic. 9841 if (BId == Builtin::BIbzero || 9842 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9843 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9844 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9845 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9846 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9847 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9848 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9849 } 9850 return; 9851 } 9852 9853 // If the second argument to a memset is a sizeof expression and the third 9854 // isn't, this is also likely an error. This should catch 9855 // 'memset(buf, sizeof(buf), 0xff)'. 9856 if (BId == Builtin::BImemset && 9857 doesExprLikelyComputeSize(Call->getArg(1)) && 9858 !doesExprLikelyComputeSize(Call->getArg(2))) { 9859 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9860 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9861 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9862 return; 9863 } 9864 } 9865 9866 /// Check for dangerous or invalid arguments to memset(). 9867 /// 9868 /// This issues warnings on known problematic, dangerous or unspecified 9869 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9870 /// function calls. 9871 /// 9872 /// \param Call The call expression to diagnose. 9873 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9874 unsigned BId, 9875 IdentifierInfo *FnName) { 9876 assert(BId != 0); 9877 9878 // It is possible to have a non-standard definition of memset. Validate 9879 // we have enough arguments, and if not, abort further checking. 9880 unsigned ExpectedNumArgs = 9881 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9882 if (Call->getNumArgs() < ExpectedNumArgs) 9883 return; 9884 9885 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9886 BId == Builtin::BIstrndup ? 1 : 2); 9887 unsigned LenArg = 9888 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9889 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9890 9891 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9892 Call->getBeginLoc(), Call->getRParenLoc())) 9893 return; 9894 9895 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9896 CheckMemaccessSize(*this, BId, Call); 9897 9898 // We have special checking when the length is a sizeof expression. 9899 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9900 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9901 llvm::FoldingSetNodeID SizeOfArgID; 9902 9903 // Although widely used, 'bzero' is not a standard function. Be more strict 9904 // with the argument types before allowing diagnostics and only allow the 9905 // form bzero(ptr, sizeof(...)). 9906 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9907 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9908 return; 9909 9910 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9911 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9912 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9913 9914 QualType DestTy = Dest->getType(); 9915 QualType PointeeTy; 9916 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9917 PointeeTy = DestPtrTy->getPointeeType(); 9918 9919 // Never warn about void type pointers. This can be used to suppress 9920 // false positives. 9921 if (PointeeTy->isVoidType()) 9922 continue; 9923 9924 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9925 // actually comparing the expressions for equality. Because computing the 9926 // expression IDs can be expensive, we only do this if the diagnostic is 9927 // enabled. 9928 if (SizeOfArg && 9929 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9930 SizeOfArg->getExprLoc())) { 9931 // We only compute IDs for expressions if the warning is enabled, and 9932 // cache the sizeof arg's ID. 9933 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9934 SizeOfArg->Profile(SizeOfArgID, Context, true); 9935 llvm::FoldingSetNodeID DestID; 9936 Dest->Profile(DestID, Context, true); 9937 if (DestID == SizeOfArgID) { 9938 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9939 // over sizeof(src) as well. 9940 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9941 StringRef ReadableName = FnName->getName(); 9942 9943 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9944 if (UnaryOp->getOpcode() == UO_AddrOf) 9945 ActionIdx = 1; // If its an address-of operator, just remove it. 9946 if (!PointeeTy->isIncompleteType() && 9947 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9948 ActionIdx = 2; // If the pointee's size is sizeof(char), 9949 // suggest an explicit length. 9950 9951 // If the function is defined as a builtin macro, do not show macro 9952 // expansion. 9953 SourceLocation SL = SizeOfArg->getExprLoc(); 9954 SourceRange DSR = Dest->getSourceRange(); 9955 SourceRange SSR = SizeOfArg->getSourceRange(); 9956 SourceManager &SM = getSourceManager(); 9957 9958 if (SM.isMacroArgExpansion(SL)) { 9959 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9960 SL = SM.getSpellingLoc(SL); 9961 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9962 SM.getSpellingLoc(DSR.getEnd())); 9963 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9964 SM.getSpellingLoc(SSR.getEnd())); 9965 } 9966 9967 DiagRuntimeBehavior(SL, SizeOfArg, 9968 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9969 << ReadableName 9970 << PointeeTy 9971 << DestTy 9972 << DSR 9973 << SSR); 9974 DiagRuntimeBehavior(SL, SizeOfArg, 9975 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9976 << ActionIdx 9977 << SSR); 9978 9979 break; 9980 } 9981 } 9982 9983 // Also check for cases where the sizeof argument is the exact same 9984 // type as the memory argument, and where it points to a user-defined 9985 // record type. 9986 if (SizeOfArgTy != QualType()) { 9987 if (PointeeTy->isRecordType() && 9988 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9989 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9990 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9991 << FnName << SizeOfArgTy << ArgIdx 9992 << PointeeTy << Dest->getSourceRange() 9993 << LenExpr->getSourceRange()); 9994 break; 9995 } 9996 } 9997 } else if (DestTy->isArrayType()) { 9998 PointeeTy = DestTy; 9999 } 10000 10001 if (PointeeTy == QualType()) 10002 continue; 10003 10004 // Always complain about dynamic classes. 10005 bool IsContained; 10006 if (const CXXRecordDecl *ContainedRD = 10007 getContainedDynamicClass(PointeeTy, IsContained)) { 10008 10009 unsigned OperationType = 0; 10010 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10011 // "overwritten" if we're warning about the destination for any call 10012 // but memcmp; otherwise a verb appropriate to the call. 10013 if (ArgIdx != 0 || IsCmp) { 10014 if (BId == Builtin::BImemcpy) 10015 OperationType = 1; 10016 else if(BId == Builtin::BImemmove) 10017 OperationType = 2; 10018 else if (IsCmp) 10019 OperationType = 3; 10020 } 10021 10022 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10023 PDiag(diag::warn_dyn_class_memaccess) 10024 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10025 << IsContained << ContainedRD << OperationType 10026 << Call->getCallee()->getSourceRange()); 10027 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10028 BId != Builtin::BImemset) 10029 DiagRuntimeBehavior( 10030 Dest->getExprLoc(), Dest, 10031 PDiag(diag::warn_arc_object_memaccess) 10032 << ArgIdx << FnName << PointeeTy 10033 << Call->getCallee()->getSourceRange()); 10034 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10035 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10036 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10037 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10038 PDiag(diag::warn_cstruct_memaccess) 10039 << ArgIdx << FnName << PointeeTy << 0); 10040 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10041 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10042 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10043 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10044 PDiag(diag::warn_cstruct_memaccess) 10045 << ArgIdx << FnName << PointeeTy << 1); 10046 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10047 } else { 10048 continue; 10049 } 10050 } else 10051 continue; 10052 10053 DiagRuntimeBehavior( 10054 Dest->getExprLoc(), Dest, 10055 PDiag(diag::note_bad_memaccess_silence) 10056 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10057 break; 10058 } 10059 } 10060 10061 // A little helper routine: ignore addition and subtraction of integer literals. 10062 // This intentionally does not ignore all integer constant expressions because 10063 // we don't want to remove sizeof(). 10064 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10065 Ex = Ex->IgnoreParenCasts(); 10066 10067 while (true) { 10068 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10069 if (!BO || !BO->isAdditiveOp()) 10070 break; 10071 10072 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10073 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10074 10075 if (isa<IntegerLiteral>(RHS)) 10076 Ex = LHS; 10077 else if (isa<IntegerLiteral>(LHS)) 10078 Ex = RHS; 10079 else 10080 break; 10081 } 10082 10083 return Ex; 10084 } 10085 10086 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10087 ASTContext &Context) { 10088 // Only handle constant-sized or VLAs, but not flexible members. 10089 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10090 // Only issue the FIXIT for arrays of size > 1. 10091 if (CAT->getSize().getSExtValue() <= 1) 10092 return false; 10093 } else if (!Ty->isVariableArrayType()) { 10094 return false; 10095 } 10096 return true; 10097 } 10098 10099 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10100 // be the size of the source, instead of the destination. 10101 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10102 IdentifierInfo *FnName) { 10103 10104 // Don't crash if the user has the wrong number of arguments 10105 unsigned NumArgs = Call->getNumArgs(); 10106 if ((NumArgs != 3) && (NumArgs != 4)) 10107 return; 10108 10109 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10110 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10111 const Expr *CompareWithSrc = nullptr; 10112 10113 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10114 Call->getBeginLoc(), Call->getRParenLoc())) 10115 return; 10116 10117 // Look for 'strlcpy(dst, x, sizeof(x))' 10118 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10119 CompareWithSrc = Ex; 10120 else { 10121 // Look for 'strlcpy(dst, x, strlen(x))' 10122 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10123 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10124 SizeCall->getNumArgs() == 1) 10125 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10126 } 10127 } 10128 10129 if (!CompareWithSrc) 10130 return; 10131 10132 // Determine if the argument to sizeof/strlen is equal to the source 10133 // argument. In principle there's all kinds of things you could do 10134 // here, for instance creating an == expression and evaluating it with 10135 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10136 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10137 if (!SrcArgDRE) 10138 return; 10139 10140 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10141 if (!CompareWithSrcDRE || 10142 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10143 return; 10144 10145 const Expr *OriginalSizeArg = Call->getArg(2); 10146 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10147 << OriginalSizeArg->getSourceRange() << FnName; 10148 10149 // Output a FIXIT hint if the destination is an array (rather than a 10150 // pointer to an array). This could be enhanced to handle some 10151 // pointers if we know the actual size, like if DstArg is 'array+2' 10152 // we could say 'sizeof(array)-2'. 10153 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10154 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10155 return; 10156 10157 SmallString<128> sizeString; 10158 llvm::raw_svector_ostream OS(sizeString); 10159 OS << "sizeof("; 10160 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10161 OS << ")"; 10162 10163 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10164 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10165 OS.str()); 10166 } 10167 10168 /// Check if two expressions refer to the same declaration. 10169 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10170 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10171 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10172 return D1->getDecl() == D2->getDecl(); 10173 return false; 10174 } 10175 10176 static const Expr *getStrlenExprArg(const Expr *E) { 10177 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10178 const FunctionDecl *FD = CE->getDirectCallee(); 10179 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10180 return nullptr; 10181 return CE->getArg(0)->IgnoreParenCasts(); 10182 } 10183 return nullptr; 10184 } 10185 10186 // Warn on anti-patterns as the 'size' argument to strncat. 10187 // The correct size argument should look like following: 10188 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10189 void Sema::CheckStrncatArguments(const CallExpr *CE, 10190 IdentifierInfo *FnName) { 10191 // Don't crash if the user has the wrong number of arguments. 10192 if (CE->getNumArgs() < 3) 10193 return; 10194 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10195 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10196 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10197 10198 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10199 CE->getRParenLoc())) 10200 return; 10201 10202 // Identify common expressions, which are wrongly used as the size argument 10203 // to strncat and may lead to buffer overflows. 10204 unsigned PatternType = 0; 10205 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10206 // - sizeof(dst) 10207 if (referToTheSameDecl(SizeOfArg, DstArg)) 10208 PatternType = 1; 10209 // - sizeof(src) 10210 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10211 PatternType = 2; 10212 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10213 if (BE->getOpcode() == BO_Sub) { 10214 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10215 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10216 // - sizeof(dst) - strlen(dst) 10217 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10218 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10219 PatternType = 1; 10220 // - sizeof(src) - (anything) 10221 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10222 PatternType = 2; 10223 } 10224 } 10225 10226 if (PatternType == 0) 10227 return; 10228 10229 // Generate the diagnostic. 10230 SourceLocation SL = LenArg->getBeginLoc(); 10231 SourceRange SR = LenArg->getSourceRange(); 10232 SourceManager &SM = getSourceManager(); 10233 10234 // If the function is defined as a builtin macro, do not show macro expansion. 10235 if (SM.isMacroArgExpansion(SL)) { 10236 SL = SM.getSpellingLoc(SL); 10237 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10238 SM.getSpellingLoc(SR.getEnd())); 10239 } 10240 10241 // Check if the destination is an array (rather than a pointer to an array). 10242 QualType DstTy = DstArg->getType(); 10243 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10244 Context); 10245 if (!isKnownSizeArray) { 10246 if (PatternType == 1) 10247 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10248 else 10249 Diag(SL, diag::warn_strncat_src_size) << SR; 10250 return; 10251 } 10252 10253 if (PatternType == 1) 10254 Diag(SL, diag::warn_strncat_large_size) << SR; 10255 else 10256 Diag(SL, diag::warn_strncat_src_size) << SR; 10257 10258 SmallString<128> sizeString; 10259 llvm::raw_svector_ostream OS(sizeString); 10260 OS << "sizeof("; 10261 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10262 OS << ") - "; 10263 OS << "strlen("; 10264 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10265 OS << ") - 1"; 10266 10267 Diag(SL, diag::note_strncat_wrong_size) 10268 << FixItHint::CreateReplacement(SR, OS.str()); 10269 } 10270 10271 namespace { 10272 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10273 const UnaryOperator *UnaryExpr, const Decl *D) { 10274 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10275 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10276 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10277 return; 10278 } 10279 } 10280 10281 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10282 const UnaryOperator *UnaryExpr) { 10283 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10284 const Decl *D = Lvalue->getDecl(); 10285 if (isa<VarDecl, FunctionDecl>(D)) 10286 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10287 } 10288 10289 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10290 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10291 Lvalue->getMemberDecl()); 10292 } 10293 10294 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10295 const UnaryOperator *UnaryExpr) { 10296 const auto *Lambda = dyn_cast<LambdaExpr>( 10297 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10298 if (!Lambda) 10299 return; 10300 10301 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10302 << CalleeName << 2 /*object: lambda expression*/; 10303 } 10304 10305 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10306 const DeclRefExpr *Lvalue) { 10307 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10308 if (Var == nullptr) 10309 return; 10310 10311 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10312 << CalleeName << 0 /*object: */ << Var; 10313 } 10314 10315 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10316 const CastExpr *Cast) { 10317 SmallString<128> SizeString; 10318 llvm::raw_svector_ostream OS(SizeString); 10319 switch (Cast->getCastKind()) { 10320 case clang::CK_BitCast: 10321 if (!Cast->getSubExpr()->getType()->isFunctionPointerType()) 10322 return; 10323 LLVM_FALLTHROUGH; 10324 case clang::CK_IntegralToPointer: 10325 case clang::CK_FunctionToPointerDecay: 10326 OS << '\''; 10327 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10328 OS << '\''; 10329 break; 10330 default: 10331 return; 10332 } 10333 10334 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10335 << CalleeName << 0 /*object: */ << OS.str(); 10336 } 10337 } // namespace 10338 10339 /// Alerts the user that they are attempting to free a non-malloc'd object. 10340 void Sema::CheckFreeArguments(const CallExpr *E) { 10341 const std::string CalleeName = 10342 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10343 10344 { // Prefer something that doesn't involve a cast to make things simpler. 10345 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10346 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10347 switch (UnaryExpr->getOpcode()) { 10348 case UnaryOperator::Opcode::UO_AddrOf: 10349 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10350 case UnaryOperator::Opcode::UO_Plus: 10351 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10352 default: 10353 break; 10354 } 10355 10356 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10357 if (Lvalue->getType()->isArrayType()) 10358 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10359 10360 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10361 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10362 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10363 return; 10364 } 10365 10366 if (isa<BlockExpr>(Arg)) { 10367 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10368 << CalleeName << 1 /*object: block*/; 10369 return; 10370 } 10371 } 10372 // Maybe the cast was important, check after the other cases. 10373 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10374 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10375 } 10376 10377 void 10378 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10379 SourceLocation ReturnLoc, 10380 bool isObjCMethod, 10381 const AttrVec *Attrs, 10382 const FunctionDecl *FD) { 10383 // Check if the return value is null but should not be. 10384 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10385 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10386 CheckNonNullExpr(*this, RetValExp)) 10387 Diag(ReturnLoc, diag::warn_null_ret) 10388 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10389 10390 // C++11 [basic.stc.dynamic.allocation]p4: 10391 // If an allocation function declared with a non-throwing 10392 // exception-specification fails to allocate storage, it shall return 10393 // a null pointer. Any other allocation function that fails to allocate 10394 // storage shall indicate failure only by throwing an exception [...] 10395 if (FD) { 10396 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10397 if (Op == OO_New || Op == OO_Array_New) { 10398 const FunctionProtoType *Proto 10399 = FD->getType()->castAs<FunctionProtoType>(); 10400 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10401 CheckNonNullExpr(*this, RetValExp)) 10402 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10403 << FD << getLangOpts().CPlusPlus11; 10404 } 10405 } 10406 10407 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10408 // here prevent the user from using a PPC MMA type as trailing return type. 10409 if (Context.getTargetInfo().getTriple().isPPC64()) 10410 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10411 } 10412 10413 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10414 10415 /// Check for comparisons of floating point operands using != and ==. 10416 /// Issue a warning if these are no self-comparisons, as they are not likely 10417 /// to do what the programmer intended. 10418 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10419 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10420 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10421 10422 // Special case: check for x == x (which is OK). 10423 // Do not emit warnings for such cases. 10424 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10425 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10426 if (DRL->getDecl() == DRR->getDecl()) 10427 return; 10428 10429 // Special case: check for comparisons against literals that can be exactly 10430 // represented by APFloat. In such cases, do not emit a warning. This 10431 // is a heuristic: often comparison against such literals are used to 10432 // detect if a value in a variable has not changed. This clearly can 10433 // lead to false negatives. 10434 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10435 if (FLL->isExact()) 10436 return; 10437 } else 10438 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10439 if (FLR->isExact()) 10440 return; 10441 10442 // Check for comparisons with builtin types. 10443 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10444 if (CL->getBuiltinCallee()) 10445 return; 10446 10447 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10448 if (CR->getBuiltinCallee()) 10449 return; 10450 10451 // Emit the diagnostic. 10452 Diag(Loc, diag::warn_floatingpoint_eq) 10453 << LHS->getSourceRange() << RHS->getSourceRange(); 10454 } 10455 10456 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10457 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10458 10459 namespace { 10460 10461 /// Structure recording the 'active' range of an integer-valued 10462 /// expression. 10463 struct IntRange { 10464 /// The number of bits active in the int. Note that this includes exactly one 10465 /// sign bit if !NonNegative. 10466 unsigned Width; 10467 10468 /// True if the int is known not to have negative values. If so, all leading 10469 /// bits before Width are known zero, otherwise they are known to be the 10470 /// same as the MSB within Width. 10471 bool NonNegative; 10472 10473 IntRange(unsigned Width, bool NonNegative) 10474 : Width(Width), NonNegative(NonNegative) {} 10475 10476 /// Number of bits excluding the sign bit. 10477 unsigned valueBits() const { 10478 return NonNegative ? Width : Width - 1; 10479 } 10480 10481 /// Returns the range of the bool type. 10482 static IntRange forBoolType() { 10483 return IntRange(1, true); 10484 } 10485 10486 /// Returns the range of an opaque value of the given integral type. 10487 static IntRange forValueOfType(ASTContext &C, QualType T) { 10488 return forValueOfCanonicalType(C, 10489 T->getCanonicalTypeInternal().getTypePtr()); 10490 } 10491 10492 /// Returns the range of an opaque value of a canonical integral type. 10493 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10494 assert(T->isCanonicalUnqualified()); 10495 10496 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10497 T = VT->getElementType().getTypePtr(); 10498 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10499 T = CT->getElementType().getTypePtr(); 10500 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10501 T = AT->getValueType().getTypePtr(); 10502 10503 if (!C.getLangOpts().CPlusPlus) { 10504 // For enum types in C code, use the underlying datatype. 10505 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10506 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10507 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10508 // For enum types in C++, use the known bit width of the enumerators. 10509 EnumDecl *Enum = ET->getDecl(); 10510 // In C++11, enums can have a fixed underlying type. Use this type to 10511 // compute the range. 10512 if (Enum->isFixed()) { 10513 return IntRange(C.getIntWidth(QualType(T, 0)), 10514 !ET->isSignedIntegerOrEnumerationType()); 10515 } 10516 10517 unsigned NumPositive = Enum->getNumPositiveBits(); 10518 unsigned NumNegative = Enum->getNumNegativeBits(); 10519 10520 if (NumNegative == 0) 10521 return IntRange(NumPositive, true/*NonNegative*/); 10522 else 10523 return IntRange(std::max(NumPositive + 1, NumNegative), 10524 false/*NonNegative*/); 10525 } 10526 10527 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10528 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10529 10530 const BuiltinType *BT = cast<BuiltinType>(T); 10531 assert(BT->isInteger()); 10532 10533 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10534 } 10535 10536 /// Returns the "target" range of a canonical integral type, i.e. 10537 /// the range of values expressible in the type. 10538 /// 10539 /// This matches forValueOfCanonicalType except that enums have the 10540 /// full range of their type, not the range of their enumerators. 10541 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10542 assert(T->isCanonicalUnqualified()); 10543 10544 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10545 T = VT->getElementType().getTypePtr(); 10546 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10547 T = CT->getElementType().getTypePtr(); 10548 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10549 T = AT->getValueType().getTypePtr(); 10550 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10551 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10552 10553 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10554 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10555 10556 const BuiltinType *BT = cast<BuiltinType>(T); 10557 assert(BT->isInteger()); 10558 10559 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10560 } 10561 10562 /// Returns the supremum of two ranges: i.e. their conservative merge. 10563 static IntRange join(IntRange L, IntRange R) { 10564 bool Unsigned = L.NonNegative && R.NonNegative; 10565 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10566 L.NonNegative && R.NonNegative); 10567 } 10568 10569 /// Return the range of a bitwise-AND of the two ranges. 10570 static IntRange bit_and(IntRange L, IntRange R) { 10571 unsigned Bits = std::max(L.Width, R.Width); 10572 bool NonNegative = false; 10573 if (L.NonNegative) { 10574 Bits = std::min(Bits, L.Width); 10575 NonNegative = true; 10576 } 10577 if (R.NonNegative) { 10578 Bits = std::min(Bits, R.Width); 10579 NonNegative = true; 10580 } 10581 return IntRange(Bits, NonNegative); 10582 } 10583 10584 /// Return the range of a sum of the two ranges. 10585 static IntRange sum(IntRange L, IntRange R) { 10586 bool Unsigned = L.NonNegative && R.NonNegative; 10587 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10588 Unsigned); 10589 } 10590 10591 /// Return the range of a difference of the two ranges. 10592 static IntRange difference(IntRange L, IntRange R) { 10593 // We need a 1-bit-wider range if: 10594 // 1) LHS can be negative: least value can be reduced. 10595 // 2) RHS can be negative: greatest value can be increased. 10596 bool CanWiden = !L.NonNegative || !R.NonNegative; 10597 bool Unsigned = L.NonNegative && R.Width == 0; 10598 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10599 !Unsigned, 10600 Unsigned); 10601 } 10602 10603 /// Return the range of a product of the two ranges. 10604 static IntRange product(IntRange L, IntRange R) { 10605 // If both LHS and RHS can be negative, we can form 10606 // -2^L * -2^R = 2^(L + R) 10607 // which requires L + R + 1 value bits to represent. 10608 bool CanWiden = !L.NonNegative && !R.NonNegative; 10609 bool Unsigned = L.NonNegative && R.NonNegative; 10610 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10611 Unsigned); 10612 } 10613 10614 /// Return the range of a remainder operation between the two ranges. 10615 static IntRange rem(IntRange L, IntRange R) { 10616 // The result of a remainder can't be larger than the result of 10617 // either side. The sign of the result is the sign of the LHS. 10618 bool Unsigned = L.NonNegative; 10619 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10620 Unsigned); 10621 } 10622 }; 10623 10624 } // namespace 10625 10626 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10627 unsigned MaxWidth) { 10628 if (value.isSigned() && value.isNegative()) 10629 return IntRange(value.getMinSignedBits(), false); 10630 10631 if (value.getBitWidth() > MaxWidth) 10632 value = value.trunc(MaxWidth); 10633 10634 // isNonNegative() just checks the sign bit without considering 10635 // signedness. 10636 return IntRange(value.getActiveBits(), true); 10637 } 10638 10639 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10640 unsigned MaxWidth) { 10641 if (result.isInt()) 10642 return GetValueRange(C, result.getInt(), MaxWidth); 10643 10644 if (result.isVector()) { 10645 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10646 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10647 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10648 R = IntRange::join(R, El); 10649 } 10650 return R; 10651 } 10652 10653 if (result.isComplexInt()) { 10654 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10655 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10656 return IntRange::join(R, I); 10657 } 10658 10659 // This can happen with lossless casts to intptr_t of "based" lvalues. 10660 // Assume it might use arbitrary bits. 10661 // FIXME: The only reason we need to pass the type in here is to get 10662 // the sign right on this one case. It would be nice if APValue 10663 // preserved this. 10664 assert(result.isLValue() || result.isAddrLabelDiff()); 10665 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10666 } 10667 10668 static QualType GetExprType(const Expr *E) { 10669 QualType Ty = E->getType(); 10670 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10671 Ty = AtomicRHS->getValueType(); 10672 return Ty; 10673 } 10674 10675 /// Pseudo-evaluate the given integer expression, estimating the 10676 /// range of values it might take. 10677 /// 10678 /// \param MaxWidth The width to which the value will be truncated. 10679 /// \param Approximate If \c true, return a likely range for the result: in 10680 /// particular, assume that aritmetic on narrower types doesn't leave 10681 /// those types. If \c false, return a range including all possible 10682 /// result values. 10683 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10684 bool InConstantContext, bool Approximate) { 10685 E = E->IgnoreParens(); 10686 10687 // Try a full evaluation first. 10688 Expr::EvalResult result; 10689 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10690 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10691 10692 // I think we only want to look through implicit casts here; if the 10693 // user has an explicit widening cast, we should treat the value as 10694 // being of the new, wider type. 10695 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10696 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10697 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 10698 Approximate); 10699 10700 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10701 10702 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10703 CE->getCastKind() == CK_BooleanToSignedIntegral; 10704 10705 // Assume that non-integer casts can span the full range of the type. 10706 if (!isIntegerCast) 10707 return OutputTypeRange; 10708 10709 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10710 std::min(MaxWidth, OutputTypeRange.Width), 10711 InConstantContext, Approximate); 10712 10713 // Bail out if the subexpr's range is as wide as the cast type. 10714 if (SubRange.Width >= OutputTypeRange.Width) 10715 return OutputTypeRange; 10716 10717 // Otherwise, we take the smaller width, and we're non-negative if 10718 // either the output type or the subexpr is. 10719 return IntRange(SubRange.Width, 10720 SubRange.NonNegative || OutputTypeRange.NonNegative); 10721 } 10722 10723 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10724 // If we can fold the condition, just take that operand. 10725 bool CondResult; 10726 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10727 return GetExprRange(C, 10728 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10729 MaxWidth, InConstantContext, Approximate); 10730 10731 // Otherwise, conservatively merge. 10732 // GetExprRange requires an integer expression, but a throw expression 10733 // results in a void type. 10734 Expr *E = CO->getTrueExpr(); 10735 IntRange L = E->getType()->isVoidType() 10736 ? IntRange{0, true} 10737 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10738 E = CO->getFalseExpr(); 10739 IntRange R = E->getType()->isVoidType() 10740 ? IntRange{0, true} 10741 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10742 return IntRange::join(L, R); 10743 } 10744 10745 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10746 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 10747 10748 switch (BO->getOpcode()) { 10749 case BO_Cmp: 10750 llvm_unreachable("builtin <=> should have class type"); 10751 10752 // Boolean-valued operations are single-bit and positive. 10753 case BO_LAnd: 10754 case BO_LOr: 10755 case BO_LT: 10756 case BO_GT: 10757 case BO_LE: 10758 case BO_GE: 10759 case BO_EQ: 10760 case BO_NE: 10761 return IntRange::forBoolType(); 10762 10763 // The type of the assignments is the type of the LHS, so the RHS 10764 // is not necessarily the same type. 10765 case BO_MulAssign: 10766 case BO_DivAssign: 10767 case BO_RemAssign: 10768 case BO_AddAssign: 10769 case BO_SubAssign: 10770 case BO_XorAssign: 10771 case BO_OrAssign: 10772 // TODO: bitfields? 10773 return IntRange::forValueOfType(C, GetExprType(E)); 10774 10775 // Simple assignments just pass through the RHS, which will have 10776 // been coerced to the LHS type. 10777 case BO_Assign: 10778 // TODO: bitfields? 10779 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10780 Approximate); 10781 10782 // Operations with opaque sources are black-listed. 10783 case BO_PtrMemD: 10784 case BO_PtrMemI: 10785 return IntRange::forValueOfType(C, GetExprType(E)); 10786 10787 // Bitwise-and uses the *infinum* of the two source ranges. 10788 case BO_And: 10789 case BO_AndAssign: 10790 Combine = IntRange::bit_and; 10791 break; 10792 10793 // Left shift gets black-listed based on a judgement call. 10794 case BO_Shl: 10795 // ...except that we want to treat '1 << (blah)' as logically 10796 // positive. It's an important idiom. 10797 if (IntegerLiteral *I 10798 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10799 if (I->getValue() == 1) { 10800 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10801 return IntRange(R.Width, /*NonNegative*/ true); 10802 } 10803 } 10804 LLVM_FALLTHROUGH; 10805 10806 case BO_ShlAssign: 10807 return IntRange::forValueOfType(C, GetExprType(E)); 10808 10809 // Right shift by a constant can narrow its left argument. 10810 case BO_Shr: 10811 case BO_ShrAssign: { 10812 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 10813 Approximate); 10814 10815 // If the shift amount is a positive constant, drop the width by 10816 // that much. 10817 if (Optional<llvm::APSInt> shift = 10818 BO->getRHS()->getIntegerConstantExpr(C)) { 10819 if (shift->isNonNegative()) { 10820 unsigned zext = shift->getZExtValue(); 10821 if (zext >= L.Width) 10822 L.Width = (L.NonNegative ? 0 : 1); 10823 else 10824 L.Width -= zext; 10825 } 10826 } 10827 10828 return L; 10829 } 10830 10831 // Comma acts as its right operand. 10832 case BO_Comma: 10833 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10834 Approximate); 10835 10836 case BO_Add: 10837 if (!Approximate) 10838 Combine = IntRange::sum; 10839 break; 10840 10841 case BO_Sub: 10842 if (BO->getLHS()->getType()->isPointerType()) 10843 return IntRange::forValueOfType(C, GetExprType(E)); 10844 if (!Approximate) 10845 Combine = IntRange::difference; 10846 break; 10847 10848 case BO_Mul: 10849 if (!Approximate) 10850 Combine = IntRange::product; 10851 break; 10852 10853 // The width of a division result is mostly determined by the size 10854 // of the LHS. 10855 case BO_Div: { 10856 // Don't 'pre-truncate' the operands. 10857 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10858 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 10859 Approximate); 10860 10861 // If the divisor is constant, use that. 10862 if (Optional<llvm::APSInt> divisor = 10863 BO->getRHS()->getIntegerConstantExpr(C)) { 10864 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10865 if (log2 >= L.Width) 10866 L.Width = (L.NonNegative ? 0 : 1); 10867 else 10868 L.Width = std::min(L.Width - log2, MaxWidth); 10869 return L; 10870 } 10871 10872 // Otherwise, just use the LHS's width. 10873 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 10874 // could be -1. 10875 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 10876 Approximate); 10877 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10878 } 10879 10880 case BO_Rem: 10881 Combine = IntRange::rem; 10882 break; 10883 10884 // The default behavior is okay for these. 10885 case BO_Xor: 10886 case BO_Or: 10887 break; 10888 } 10889 10890 // Combine the two ranges, but limit the result to the type in which we 10891 // performed the computation. 10892 QualType T = GetExprType(E); 10893 unsigned opWidth = C.getIntWidth(T); 10894 IntRange L = 10895 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 10896 IntRange R = 10897 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 10898 IntRange C = Combine(L, R); 10899 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 10900 C.Width = std::min(C.Width, MaxWidth); 10901 return C; 10902 } 10903 10904 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10905 switch (UO->getOpcode()) { 10906 // Boolean-valued operations are white-listed. 10907 case UO_LNot: 10908 return IntRange::forBoolType(); 10909 10910 // Operations with opaque sources are black-listed. 10911 case UO_Deref: 10912 case UO_AddrOf: // should be impossible 10913 return IntRange::forValueOfType(C, GetExprType(E)); 10914 10915 default: 10916 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 10917 Approximate); 10918 } 10919 } 10920 10921 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10922 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 10923 Approximate); 10924 10925 if (const auto *BitField = E->getSourceBitField()) 10926 return IntRange(BitField->getBitWidthValue(C), 10927 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10928 10929 return IntRange::forValueOfType(C, GetExprType(E)); 10930 } 10931 10932 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10933 bool InConstantContext, bool Approximate) { 10934 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 10935 Approximate); 10936 } 10937 10938 /// Checks whether the given value, which currently has the given 10939 /// source semantics, has the same value when coerced through the 10940 /// target semantics. 10941 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10942 const llvm::fltSemantics &Src, 10943 const llvm::fltSemantics &Tgt) { 10944 llvm::APFloat truncated = value; 10945 10946 bool ignored; 10947 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10948 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10949 10950 return truncated.bitwiseIsEqual(value); 10951 } 10952 10953 /// Checks whether the given value, which currently has the given 10954 /// source semantics, has the same value when coerced through the 10955 /// target semantics. 10956 /// 10957 /// The value might be a vector of floats (or a complex number). 10958 static bool IsSameFloatAfterCast(const APValue &value, 10959 const llvm::fltSemantics &Src, 10960 const llvm::fltSemantics &Tgt) { 10961 if (value.isFloat()) 10962 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10963 10964 if (value.isVector()) { 10965 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10966 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10967 return false; 10968 return true; 10969 } 10970 10971 assert(value.isComplexFloat()); 10972 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10973 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10974 } 10975 10976 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10977 bool IsListInit = false); 10978 10979 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10980 // Suppress cases where we are comparing against an enum constant. 10981 if (const DeclRefExpr *DR = 10982 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10983 if (isa<EnumConstantDecl>(DR->getDecl())) 10984 return true; 10985 10986 // Suppress cases where the value is expanded from a macro, unless that macro 10987 // is how a language represents a boolean literal. This is the case in both C 10988 // and Objective-C. 10989 SourceLocation BeginLoc = E->getBeginLoc(); 10990 if (BeginLoc.isMacroID()) { 10991 StringRef MacroName = Lexer::getImmediateMacroName( 10992 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10993 return MacroName != "YES" && MacroName != "NO" && 10994 MacroName != "true" && MacroName != "false"; 10995 } 10996 10997 return false; 10998 } 10999 11000 static bool isKnownToHaveUnsignedValue(Expr *E) { 11001 return E->getType()->isIntegerType() && 11002 (!E->getType()->isSignedIntegerType() || 11003 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11004 } 11005 11006 namespace { 11007 /// The promoted range of values of a type. In general this has the 11008 /// following structure: 11009 /// 11010 /// |-----------| . . . |-----------| 11011 /// ^ ^ ^ ^ 11012 /// Min HoleMin HoleMax Max 11013 /// 11014 /// ... where there is only a hole if a signed type is promoted to unsigned 11015 /// (in which case Min and Max are the smallest and largest representable 11016 /// values). 11017 struct PromotedRange { 11018 // Min, or HoleMax if there is a hole. 11019 llvm::APSInt PromotedMin; 11020 // Max, or HoleMin if there is a hole. 11021 llvm::APSInt PromotedMax; 11022 11023 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11024 if (R.Width == 0) 11025 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11026 else if (R.Width >= BitWidth && !Unsigned) { 11027 // Promotion made the type *narrower*. This happens when promoting 11028 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11029 // Treat all values of 'signed int' as being in range for now. 11030 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11031 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11032 } else { 11033 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11034 .extOrTrunc(BitWidth); 11035 PromotedMin.setIsUnsigned(Unsigned); 11036 11037 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11038 .extOrTrunc(BitWidth); 11039 PromotedMax.setIsUnsigned(Unsigned); 11040 } 11041 } 11042 11043 // Determine whether this range is contiguous (has no hole). 11044 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11045 11046 // Where a constant value is within the range. 11047 enum ComparisonResult { 11048 LT = 0x1, 11049 LE = 0x2, 11050 GT = 0x4, 11051 GE = 0x8, 11052 EQ = 0x10, 11053 NE = 0x20, 11054 InRangeFlag = 0x40, 11055 11056 Less = LE | LT | NE, 11057 Min = LE | InRangeFlag, 11058 InRange = InRangeFlag, 11059 Max = GE | InRangeFlag, 11060 Greater = GE | GT | NE, 11061 11062 OnlyValue = LE | GE | EQ | InRangeFlag, 11063 InHole = NE 11064 }; 11065 11066 ComparisonResult compare(const llvm::APSInt &Value) const { 11067 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11068 Value.isUnsigned() == PromotedMin.isUnsigned()); 11069 if (!isContiguous()) { 11070 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11071 if (Value.isMinValue()) return Min; 11072 if (Value.isMaxValue()) return Max; 11073 if (Value >= PromotedMin) return InRange; 11074 if (Value <= PromotedMax) return InRange; 11075 return InHole; 11076 } 11077 11078 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11079 case -1: return Less; 11080 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11081 case 1: 11082 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11083 case -1: return InRange; 11084 case 0: return Max; 11085 case 1: return Greater; 11086 } 11087 } 11088 11089 llvm_unreachable("impossible compare result"); 11090 } 11091 11092 static llvm::Optional<StringRef> 11093 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11094 if (Op == BO_Cmp) { 11095 ComparisonResult LTFlag = LT, GTFlag = GT; 11096 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11097 11098 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11099 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11100 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11101 return llvm::None; 11102 } 11103 11104 ComparisonResult TrueFlag, FalseFlag; 11105 if (Op == BO_EQ) { 11106 TrueFlag = EQ; 11107 FalseFlag = NE; 11108 } else if (Op == BO_NE) { 11109 TrueFlag = NE; 11110 FalseFlag = EQ; 11111 } else { 11112 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11113 TrueFlag = LT; 11114 FalseFlag = GE; 11115 } else { 11116 TrueFlag = GT; 11117 FalseFlag = LE; 11118 } 11119 if (Op == BO_GE || Op == BO_LE) 11120 std::swap(TrueFlag, FalseFlag); 11121 } 11122 if (R & TrueFlag) 11123 return StringRef("true"); 11124 if (R & FalseFlag) 11125 return StringRef("false"); 11126 return llvm::None; 11127 } 11128 }; 11129 } 11130 11131 static bool HasEnumType(Expr *E) { 11132 // Strip off implicit integral promotions. 11133 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11134 if (ICE->getCastKind() != CK_IntegralCast && 11135 ICE->getCastKind() != CK_NoOp) 11136 break; 11137 E = ICE->getSubExpr(); 11138 } 11139 11140 return E->getType()->isEnumeralType(); 11141 } 11142 11143 static int classifyConstantValue(Expr *Constant) { 11144 // The values of this enumeration are used in the diagnostics 11145 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11146 enum ConstantValueKind { 11147 Miscellaneous = 0, 11148 LiteralTrue, 11149 LiteralFalse 11150 }; 11151 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11152 return BL->getValue() ? ConstantValueKind::LiteralTrue 11153 : ConstantValueKind::LiteralFalse; 11154 return ConstantValueKind::Miscellaneous; 11155 } 11156 11157 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11158 Expr *Constant, Expr *Other, 11159 const llvm::APSInt &Value, 11160 bool RhsConstant) { 11161 if (S.inTemplateInstantiation()) 11162 return false; 11163 11164 Expr *OriginalOther = Other; 11165 11166 Constant = Constant->IgnoreParenImpCasts(); 11167 Other = Other->IgnoreParenImpCasts(); 11168 11169 // Suppress warnings on tautological comparisons between values of the same 11170 // enumeration type. There are only two ways we could warn on this: 11171 // - If the constant is outside the range of representable values of 11172 // the enumeration. In such a case, we should warn about the cast 11173 // to enumeration type, not about the comparison. 11174 // - If the constant is the maximum / minimum in-range value. For an 11175 // enumeratin type, such comparisons can be meaningful and useful. 11176 if (Constant->getType()->isEnumeralType() && 11177 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11178 return false; 11179 11180 IntRange OtherValueRange = GetExprRange( 11181 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11182 11183 QualType OtherT = Other->getType(); 11184 if (const auto *AT = OtherT->getAs<AtomicType>()) 11185 OtherT = AT->getValueType(); 11186 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11187 11188 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11189 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11190 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11191 S.NSAPIObj->isObjCBOOLType(OtherT) && 11192 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11193 11194 // Whether we're treating Other as being a bool because of the form of 11195 // expression despite it having another type (typically 'int' in C). 11196 bool OtherIsBooleanDespiteType = 11197 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11198 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11199 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11200 11201 // Check if all values in the range of possible values of this expression 11202 // lead to the same comparison outcome. 11203 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11204 Value.isUnsigned()); 11205 auto Cmp = OtherPromotedValueRange.compare(Value); 11206 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11207 if (!Result) 11208 return false; 11209 11210 // Also consider the range determined by the type alone. This allows us to 11211 // classify the warning under the proper diagnostic group. 11212 bool TautologicalTypeCompare = false; 11213 { 11214 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11215 Value.isUnsigned()); 11216 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11217 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11218 RhsConstant)) { 11219 TautologicalTypeCompare = true; 11220 Cmp = TypeCmp; 11221 Result = TypeResult; 11222 } 11223 } 11224 11225 // Don't warn if the non-constant operand actually always evaluates to the 11226 // same value. 11227 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11228 return false; 11229 11230 // Suppress the diagnostic for an in-range comparison if the constant comes 11231 // from a macro or enumerator. We don't want to diagnose 11232 // 11233 // some_long_value <= INT_MAX 11234 // 11235 // when sizeof(int) == sizeof(long). 11236 bool InRange = Cmp & PromotedRange::InRangeFlag; 11237 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11238 return false; 11239 11240 // A comparison of an unsigned bit-field against 0 is really a type problem, 11241 // even though at the type level the bit-field might promote to 'signed int'. 11242 if (Other->refersToBitField() && InRange && Value == 0 && 11243 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11244 TautologicalTypeCompare = true; 11245 11246 // If this is a comparison to an enum constant, include that 11247 // constant in the diagnostic. 11248 const EnumConstantDecl *ED = nullptr; 11249 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11250 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11251 11252 // Should be enough for uint128 (39 decimal digits) 11253 SmallString<64> PrettySourceValue; 11254 llvm::raw_svector_ostream OS(PrettySourceValue); 11255 if (ED) { 11256 OS << '\'' << *ED << "' (" << Value << ")"; 11257 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11258 Constant->IgnoreParenImpCasts())) { 11259 OS << (BL->getValue() ? "YES" : "NO"); 11260 } else { 11261 OS << Value; 11262 } 11263 11264 if (!TautologicalTypeCompare) { 11265 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11266 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11267 << E->getOpcodeStr() << OS.str() << *Result 11268 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11269 return true; 11270 } 11271 11272 if (IsObjCSignedCharBool) { 11273 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11274 S.PDiag(diag::warn_tautological_compare_objc_bool) 11275 << OS.str() << *Result); 11276 return true; 11277 } 11278 11279 // FIXME: We use a somewhat different formatting for the in-range cases and 11280 // cases involving boolean values for historical reasons. We should pick a 11281 // consistent way of presenting these diagnostics. 11282 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11283 11284 S.DiagRuntimeBehavior( 11285 E->getOperatorLoc(), E, 11286 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11287 : diag::warn_tautological_bool_compare) 11288 << OS.str() << classifyConstantValue(Constant) << OtherT 11289 << OtherIsBooleanDespiteType << *Result 11290 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11291 } else { 11292 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11293 ? (HasEnumType(OriginalOther) 11294 ? diag::warn_unsigned_enum_always_true_comparison 11295 : diag::warn_unsigned_always_true_comparison) 11296 : diag::warn_tautological_constant_compare; 11297 11298 S.Diag(E->getOperatorLoc(), Diag) 11299 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11300 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11301 } 11302 11303 return true; 11304 } 11305 11306 /// Analyze the operands of the given comparison. Implements the 11307 /// fallback case from AnalyzeComparison. 11308 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11309 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11310 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11311 } 11312 11313 /// Implements -Wsign-compare. 11314 /// 11315 /// \param E the binary operator to check for warnings 11316 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11317 // The type the comparison is being performed in. 11318 QualType T = E->getLHS()->getType(); 11319 11320 // Only analyze comparison operators where both sides have been converted to 11321 // the same type. 11322 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11323 return AnalyzeImpConvsInComparison(S, E); 11324 11325 // Don't analyze value-dependent comparisons directly. 11326 if (E->isValueDependent()) 11327 return AnalyzeImpConvsInComparison(S, E); 11328 11329 Expr *LHS = E->getLHS(); 11330 Expr *RHS = E->getRHS(); 11331 11332 if (T->isIntegralType(S.Context)) { 11333 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11334 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11335 11336 // We don't care about expressions whose result is a constant. 11337 if (RHSValue && LHSValue) 11338 return AnalyzeImpConvsInComparison(S, E); 11339 11340 // We only care about expressions where just one side is literal 11341 if ((bool)RHSValue ^ (bool)LHSValue) { 11342 // Is the constant on the RHS or LHS? 11343 const bool RhsConstant = (bool)RHSValue; 11344 Expr *Const = RhsConstant ? RHS : LHS; 11345 Expr *Other = RhsConstant ? LHS : RHS; 11346 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11347 11348 // Check whether an integer constant comparison results in a value 11349 // of 'true' or 'false'. 11350 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11351 return AnalyzeImpConvsInComparison(S, E); 11352 } 11353 } 11354 11355 if (!T->hasUnsignedIntegerRepresentation()) { 11356 // We don't do anything special if this isn't an unsigned integral 11357 // comparison: we're only interested in integral comparisons, and 11358 // signed comparisons only happen in cases we don't care to warn about. 11359 return AnalyzeImpConvsInComparison(S, E); 11360 } 11361 11362 LHS = LHS->IgnoreParenImpCasts(); 11363 RHS = RHS->IgnoreParenImpCasts(); 11364 11365 if (!S.getLangOpts().CPlusPlus) { 11366 // Avoid warning about comparison of integers with different signs when 11367 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11368 // the type of `E`. 11369 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11370 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11371 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11372 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11373 } 11374 11375 // Check to see if one of the (unmodified) operands is of different 11376 // signedness. 11377 Expr *signedOperand, *unsignedOperand; 11378 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11379 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11380 "unsigned comparison between two signed integer expressions?"); 11381 signedOperand = LHS; 11382 unsignedOperand = RHS; 11383 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11384 signedOperand = RHS; 11385 unsignedOperand = LHS; 11386 } else { 11387 return AnalyzeImpConvsInComparison(S, E); 11388 } 11389 11390 // Otherwise, calculate the effective range of the signed operand. 11391 IntRange signedRange = GetExprRange( 11392 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11393 11394 // Go ahead and analyze implicit conversions in the operands. Note 11395 // that we skip the implicit conversions on both sides. 11396 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11397 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11398 11399 // If the signed range is non-negative, -Wsign-compare won't fire. 11400 if (signedRange.NonNegative) 11401 return; 11402 11403 // For (in)equality comparisons, if the unsigned operand is a 11404 // constant which cannot collide with a overflowed signed operand, 11405 // then reinterpreting the signed operand as unsigned will not 11406 // change the result of the comparison. 11407 if (E->isEqualityOp()) { 11408 unsigned comparisonWidth = S.Context.getIntWidth(T); 11409 IntRange unsignedRange = 11410 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11411 /*Approximate*/ true); 11412 11413 // We should never be unable to prove that the unsigned operand is 11414 // non-negative. 11415 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11416 11417 if (unsignedRange.Width < comparisonWidth) 11418 return; 11419 } 11420 11421 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11422 S.PDiag(diag::warn_mixed_sign_comparison) 11423 << LHS->getType() << RHS->getType() 11424 << LHS->getSourceRange() << RHS->getSourceRange()); 11425 } 11426 11427 /// Analyzes an attempt to assign the given value to a bitfield. 11428 /// 11429 /// Returns true if there was something fishy about the attempt. 11430 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11431 SourceLocation InitLoc) { 11432 assert(Bitfield->isBitField()); 11433 if (Bitfield->isInvalidDecl()) 11434 return false; 11435 11436 // White-list bool bitfields. 11437 QualType BitfieldType = Bitfield->getType(); 11438 if (BitfieldType->isBooleanType()) 11439 return false; 11440 11441 if (BitfieldType->isEnumeralType()) { 11442 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11443 // If the underlying enum type was not explicitly specified as an unsigned 11444 // type and the enum contain only positive values, MSVC++ will cause an 11445 // inconsistency by storing this as a signed type. 11446 if (S.getLangOpts().CPlusPlus11 && 11447 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11448 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11449 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11450 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11451 << BitfieldEnumDecl; 11452 } 11453 } 11454 11455 if (Bitfield->getType()->isBooleanType()) 11456 return false; 11457 11458 // Ignore value- or type-dependent expressions. 11459 if (Bitfield->getBitWidth()->isValueDependent() || 11460 Bitfield->getBitWidth()->isTypeDependent() || 11461 Init->isValueDependent() || 11462 Init->isTypeDependent()) 11463 return false; 11464 11465 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11466 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11467 11468 Expr::EvalResult Result; 11469 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11470 Expr::SE_AllowSideEffects)) { 11471 // The RHS is not constant. If the RHS has an enum type, make sure the 11472 // bitfield is wide enough to hold all the values of the enum without 11473 // truncation. 11474 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11475 EnumDecl *ED = EnumTy->getDecl(); 11476 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11477 11478 // Enum types are implicitly signed on Windows, so check if there are any 11479 // negative enumerators to see if the enum was intended to be signed or 11480 // not. 11481 bool SignedEnum = ED->getNumNegativeBits() > 0; 11482 11483 // Check for surprising sign changes when assigning enum values to a 11484 // bitfield of different signedness. If the bitfield is signed and we 11485 // have exactly the right number of bits to store this unsigned enum, 11486 // suggest changing the enum to an unsigned type. This typically happens 11487 // on Windows where unfixed enums always use an underlying type of 'int'. 11488 unsigned DiagID = 0; 11489 if (SignedEnum && !SignedBitfield) { 11490 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11491 } else if (SignedBitfield && !SignedEnum && 11492 ED->getNumPositiveBits() == FieldWidth) { 11493 DiagID = diag::warn_signed_bitfield_enum_conversion; 11494 } 11495 11496 if (DiagID) { 11497 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11498 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11499 SourceRange TypeRange = 11500 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11501 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11502 << SignedEnum << TypeRange; 11503 } 11504 11505 // Compute the required bitwidth. If the enum has negative values, we need 11506 // one more bit than the normal number of positive bits to represent the 11507 // sign bit. 11508 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11509 ED->getNumNegativeBits()) 11510 : ED->getNumPositiveBits(); 11511 11512 // Check the bitwidth. 11513 if (BitsNeeded > FieldWidth) { 11514 Expr *WidthExpr = Bitfield->getBitWidth(); 11515 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11516 << Bitfield << ED; 11517 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11518 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11519 } 11520 } 11521 11522 return false; 11523 } 11524 11525 llvm::APSInt Value = Result.Val.getInt(); 11526 11527 unsigned OriginalWidth = Value.getBitWidth(); 11528 11529 if (!Value.isSigned() || Value.isNegative()) 11530 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11531 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11532 OriginalWidth = Value.getMinSignedBits(); 11533 11534 if (OriginalWidth <= FieldWidth) 11535 return false; 11536 11537 // Compute the value which the bitfield will contain. 11538 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11539 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11540 11541 // Check whether the stored value is equal to the original value. 11542 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11543 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11544 return false; 11545 11546 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11547 // therefore don't strictly fit into a signed bitfield of width 1. 11548 if (FieldWidth == 1 && Value == 1) 11549 return false; 11550 11551 std::string PrettyValue = Value.toString(10); 11552 std::string PrettyTrunc = TruncatedValue.toString(10); 11553 11554 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11555 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11556 << Init->getSourceRange(); 11557 11558 return true; 11559 } 11560 11561 /// Analyze the given simple or compound assignment for warning-worthy 11562 /// operations. 11563 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11564 // Just recurse on the LHS. 11565 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11566 11567 // We want to recurse on the RHS as normal unless we're assigning to 11568 // a bitfield. 11569 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11570 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11571 E->getOperatorLoc())) { 11572 // Recurse, ignoring any implicit conversions on the RHS. 11573 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11574 E->getOperatorLoc()); 11575 } 11576 } 11577 11578 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11579 11580 // Diagnose implicitly sequentially-consistent atomic assignment. 11581 if (E->getLHS()->getType()->isAtomicType()) 11582 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11583 } 11584 11585 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11586 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11587 SourceLocation CContext, unsigned diag, 11588 bool pruneControlFlow = false) { 11589 if (pruneControlFlow) { 11590 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11591 S.PDiag(diag) 11592 << SourceType << T << E->getSourceRange() 11593 << SourceRange(CContext)); 11594 return; 11595 } 11596 S.Diag(E->getExprLoc(), diag) 11597 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11598 } 11599 11600 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11601 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11602 SourceLocation CContext, 11603 unsigned diag, bool pruneControlFlow = false) { 11604 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11605 } 11606 11607 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11608 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11609 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11610 } 11611 11612 static void adornObjCBoolConversionDiagWithTernaryFixit( 11613 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11614 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11615 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11616 Ignored = OVE->getSourceExpr(); 11617 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11618 isa<BinaryOperator>(Ignored) || 11619 isa<CXXOperatorCallExpr>(Ignored); 11620 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11621 if (NeedsParens) 11622 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11623 << FixItHint::CreateInsertion(EndLoc, ")"); 11624 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11625 } 11626 11627 /// Diagnose an implicit cast from a floating point value to an integer value. 11628 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11629 SourceLocation CContext) { 11630 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11631 const bool PruneWarnings = S.inTemplateInstantiation(); 11632 11633 Expr *InnerE = E->IgnoreParenImpCasts(); 11634 // We also want to warn on, e.g., "int i = -1.234" 11635 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11636 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11637 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11638 11639 const bool IsLiteral = 11640 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11641 11642 llvm::APFloat Value(0.0); 11643 bool IsConstant = 11644 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11645 if (!IsConstant) { 11646 if (isObjCSignedCharBool(S, T)) { 11647 return adornObjCBoolConversionDiagWithTernaryFixit( 11648 S, E, 11649 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11650 << E->getType()); 11651 } 11652 11653 return DiagnoseImpCast(S, E, T, CContext, 11654 diag::warn_impcast_float_integer, PruneWarnings); 11655 } 11656 11657 bool isExact = false; 11658 11659 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11660 T->hasUnsignedIntegerRepresentation()); 11661 llvm::APFloat::opStatus Result = Value.convertToInteger( 11662 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11663 11664 // FIXME: Force the precision of the source value down so we don't print 11665 // digits which are usually useless (we don't really care here if we 11666 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11667 // would automatically print the shortest representation, but it's a bit 11668 // tricky to implement. 11669 SmallString<16> PrettySourceValue; 11670 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11671 precision = (precision * 59 + 195) / 196; 11672 Value.toString(PrettySourceValue, precision); 11673 11674 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11675 return adornObjCBoolConversionDiagWithTernaryFixit( 11676 S, E, 11677 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11678 << PrettySourceValue); 11679 } 11680 11681 if (Result == llvm::APFloat::opOK && isExact) { 11682 if (IsLiteral) return; 11683 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11684 PruneWarnings); 11685 } 11686 11687 // Conversion of a floating-point value to a non-bool integer where the 11688 // integral part cannot be represented by the integer type is undefined. 11689 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11690 return DiagnoseImpCast( 11691 S, E, T, CContext, 11692 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11693 : diag::warn_impcast_float_to_integer_out_of_range, 11694 PruneWarnings); 11695 11696 unsigned DiagID = 0; 11697 if (IsLiteral) { 11698 // Warn on floating point literal to integer. 11699 DiagID = diag::warn_impcast_literal_float_to_integer; 11700 } else if (IntegerValue == 0) { 11701 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11702 return DiagnoseImpCast(S, E, T, CContext, 11703 diag::warn_impcast_float_integer, PruneWarnings); 11704 } 11705 // Warn on non-zero to zero conversion. 11706 DiagID = diag::warn_impcast_float_to_integer_zero; 11707 } else { 11708 if (IntegerValue.isUnsigned()) { 11709 if (!IntegerValue.isMaxValue()) { 11710 return DiagnoseImpCast(S, E, T, CContext, 11711 diag::warn_impcast_float_integer, PruneWarnings); 11712 } 11713 } else { // IntegerValue.isSigned() 11714 if (!IntegerValue.isMaxSignedValue() && 11715 !IntegerValue.isMinSignedValue()) { 11716 return DiagnoseImpCast(S, E, T, CContext, 11717 diag::warn_impcast_float_integer, PruneWarnings); 11718 } 11719 } 11720 // Warn on evaluatable floating point expression to integer conversion. 11721 DiagID = diag::warn_impcast_float_to_integer; 11722 } 11723 11724 SmallString<16> PrettyTargetValue; 11725 if (IsBool) 11726 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11727 else 11728 IntegerValue.toString(PrettyTargetValue); 11729 11730 if (PruneWarnings) { 11731 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11732 S.PDiag(DiagID) 11733 << E->getType() << T.getUnqualifiedType() 11734 << PrettySourceValue << PrettyTargetValue 11735 << E->getSourceRange() << SourceRange(CContext)); 11736 } else { 11737 S.Diag(E->getExprLoc(), DiagID) 11738 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11739 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11740 } 11741 } 11742 11743 /// Analyze the given compound assignment for the possible losing of 11744 /// floating-point precision. 11745 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11746 assert(isa<CompoundAssignOperator>(E) && 11747 "Must be compound assignment operation"); 11748 // Recurse on the LHS and RHS in here 11749 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11750 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11751 11752 if (E->getLHS()->getType()->isAtomicType()) 11753 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11754 11755 // Now check the outermost expression 11756 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11757 const auto *RBT = cast<CompoundAssignOperator>(E) 11758 ->getComputationResultType() 11759 ->getAs<BuiltinType>(); 11760 11761 // The below checks assume source is floating point. 11762 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11763 11764 // If source is floating point but target is an integer. 11765 if (ResultBT->isInteger()) 11766 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11767 E->getExprLoc(), diag::warn_impcast_float_integer); 11768 11769 if (!ResultBT->isFloatingPoint()) 11770 return; 11771 11772 // If both source and target are floating points, warn about losing precision. 11773 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11774 QualType(ResultBT, 0), QualType(RBT, 0)); 11775 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11776 // warn about dropping FP rank. 11777 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11778 diag::warn_impcast_float_result_precision); 11779 } 11780 11781 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11782 IntRange Range) { 11783 if (!Range.Width) return "0"; 11784 11785 llvm::APSInt ValueInRange = Value; 11786 ValueInRange.setIsSigned(!Range.NonNegative); 11787 ValueInRange = ValueInRange.trunc(Range.Width); 11788 return ValueInRange.toString(10); 11789 } 11790 11791 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11792 if (!isa<ImplicitCastExpr>(Ex)) 11793 return false; 11794 11795 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11796 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11797 const Type *Source = 11798 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11799 if (Target->isDependentType()) 11800 return false; 11801 11802 const BuiltinType *FloatCandidateBT = 11803 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11804 const Type *BoolCandidateType = ToBool ? Target : Source; 11805 11806 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11807 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11808 } 11809 11810 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11811 SourceLocation CC) { 11812 unsigned NumArgs = TheCall->getNumArgs(); 11813 for (unsigned i = 0; i < NumArgs; ++i) { 11814 Expr *CurrA = TheCall->getArg(i); 11815 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11816 continue; 11817 11818 bool IsSwapped = ((i > 0) && 11819 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11820 IsSwapped |= ((i < (NumArgs - 1)) && 11821 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11822 if (IsSwapped) { 11823 // Warn on this floating-point to bool conversion. 11824 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11825 CurrA->getType(), CC, 11826 diag::warn_impcast_floating_point_to_bool); 11827 } 11828 } 11829 } 11830 11831 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11832 SourceLocation CC) { 11833 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11834 E->getExprLoc())) 11835 return; 11836 11837 // Don't warn on functions which have return type nullptr_t. 11838 if (isa<CallExpr>(E)) 11839 return; 11840 11841 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11842 const Expr::NullPointerConstantKind NullKind = 11843 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11844 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11845 return; 11846 11847 // Return if target type is a safe conversion. 11848 if (T->isAnyPointerType() || T->isBlockPointerType() || 11849 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11850 return; 11851 11852 SourceLocation Loc = E->getSourceRange().getBegin(); 11853 11854 // Venture through the macro stacks to get to the source of macro arguments. 11855 // The new location is a better location than the complete location that was 11856 // passed in. 11857 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11858 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11859 11860 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11861 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11862 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11863 Loc, S.SourceMgr, S.getLangOpts()); 11864 if (MacroName == "NULL") 11865 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11866 } 11867 11868 // Only warn if the null and context location are in the same macro expansion. 11869 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11870 return; 11871 11872 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11873 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11874 << FixItHint::CreateReplacement(Loc, 11875 S.getFixItZeroLiteralForType(T, Loc)); 11876 } 11877 11878 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11879 ObjCArrayLiteral *ArrayLiteral); 11880 11881 static void 11882 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11883 ObjCDictionaryLiteral *DictionaryLiteral); 11884 11885 /// Check a single element within a collection literal against the 11886 /// target element type. 11887 static void checkObjCCollectionLiteralElement(Sema &S, 11888 QualType TargetElementType, 11889 Expr *Element, 11890 unsigned ElementKind) { 11891 // Skip a bitcast to 'id' or qualified 'id'. 11892 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11893 if (ICE->getCastKind() == CK_BitCast && 11894 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11895 Element = ICE->getSubExpr(); 11896 } 11897 11898 QualType ElementType = Element->getType(); 11899 ExprResult ElementResult(Element); 11900 if (ElementType->getAs<ObjCObjectPointerType>() && 11901 S.CheckSingleAssignmentConstraints(TargetElementType, 11902 ElementResult, 11903 false, false) 11904 != Sema::Compatible) { 11905 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11906 << ElementType << ElementKind << TargetElementType 11907 << Element->getSourceRange(); 11908 } 11909 11910 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11911 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11912 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11913 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11914 } 11915 11916 /// Check an Objective-C array literal being converted to the given 11917 /// target type. 11918 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11919 ObjCArrayLiteral *ArrayLiteral) { 11920 if (!S.NSArrayDecl) 11921 return; 11922 11923 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11924 if (!TargetObjCPtr) 11925 return; 11926 11927 if (TargetObjCPtr->isUnspecialized() || 11928 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11929 != S.NSArrayDecl->getCanonicalDecl()) 11930 return; 11931 11932 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11933 if (TypeArgs.size() != 1) 11934 return; 11935 11936 QualType TargetElementType = TypeArgs[0]; 11937 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11938 checkObjCCollectionLiteralElement(S, TargetElementType, 11939 ArrayLiteral->getElement(I), 11940 0); 11941 } 11942 } 11943 11944 /// Check an Objective-C dictionary literal being converted to the given 11945 /// target type. 11946 static void 11947 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11948 ObjCDictionaryLiteral *DictionaryLiteral) { 11949 if (!S.NSDictionaryDecl) 11950 return; 11951 11952 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11953 if (!TargetObjCPtr) 11954 return; 11955 11956 if (TargetObjCPtr->isUnspecialized() || 11957 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11958 != S.NSDictionaryDecl->getCanonicalDecl()) 11959 return; 11960 11961 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11962 if (TypeArgs.size() != 2) 11963 return; 11964 11965 QualType TargetKeyType = TypeArgs[0]; 11966 QualType TargetObjectType = TypeArgs[1]; 11967 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11968 auto Element = DictionaryLiteral->getKeyValueElement(I); 11969 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11970 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11971 } 11972 } 11973 11974 // Helper function to filter out cases for constant width constant conversion. 11975 // Don't warn on char array initialization or for non-decimal values. 11976 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11977 SourceLocation CC) { 11978 // If initializing from a constant, and the constant starts with '0', 11979 // then it is a binary, octal, or hexadecimal. Allow these constants 11980 // to fill all the bits, even if there is a sign change. 11981 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11982 const char FirstLiteralCharacter = 11983 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11984 if (FirstLiteralCharacter == '0') 11985 return false; 11986 } 11987 11988 // If the CC location points to a '{', and the type is char, then assume 11989 // assume it is an array initialization. 11990 if (CC.isValid() && T->isCharType()) { 11991 const char FirstContextCharacter = 11992 S.getSourceManager().getCharacterData(CC)[0]; 11993 if (FirstContextCharacter == '{') 11994 return false; 11995 } 11996 11997 return true; 11998 } 11999 12000 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12001 const auto *IL = dyn_cast<IntegerLiteral>(E); 12002 if (!IL) { 12003 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12004 if (UO->getOpcode() == UO_Minus) 12005 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12006 } 12007 } 12008 12009 return IL; 12010 } 12011 12012 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12013 E = E->IgnoreParenImpCasts(); 12014 SourceLocation ExprLoc = E->getExprLoc(); 12015 12016 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12017 BinaryOperator::Opcode Opc = BO->getOpcode(); 12018 Expr::EvalResult Result; 12019 // Do not diagnose unsigned shifts. 12020 if (Opc == BO_Shl) { 12021 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12022 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12023 if (LHS && LHS->getValue() == 0) 12024 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12025 else if (!E->isValueDependent() && LHS && RHS && 12026 RHS->getValue().isNonNegative() && 12027 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12028 S.Diag(ExprLoc, diag::warn_left_shift_always) 12029 << (Result.Val.getInt() != 0); 12030 else if (E->getType()->isSignedIntegerType()) 12031 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12032 } 12033 } 12034 12035 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12036 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12037 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12038 if (!LHS || !RHS) 12039 return; 12040 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12041 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12042 // Do not diagnose common idioms. 12043 return; 12044 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12045 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12046 } 12047 } 12048 12049 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12050 SourceLocation CC, 12051 bool *ICContext = nullptr, 12052 bool IsListInit = false) { 12053 if (E->isTypeDependent() || E->isValueDependent()) return; 12054 12055 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12056 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12057 if (Source == Target) return; 12058 if (Target->isDependentType()) return; 12059 12060 // If the conversion context location is invalid don't complain. We also 12061 // don't want to emit a warning if the issue occurs from the expansion of 12062 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12063 // delay this check as long as possible. Once we detect we are in that 12064 // scenario, we just return. 12065 if (CC.isInvalid()) 12066 return; 12067 12068 if (Source->isAtomicType()) 12069 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12070 12071 // Diagnose implicit casts to bool. 12072 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12073 if (isa<StringLiteral>(E)) 12074 // Warn on string literal to bool. Checks for string literals in logical 12075 // and expressions, for instance, assert(0 && "error here"), are 12076 // prevented by a check in AnalyzeImplicitConversions(). 12077 return DiagnoseImpCast(S, E, T, CC, 12078 diag::warn_impcast_string_literal_to_bool); 12079 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12080 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12081 // This covers the literal expressions that evaluate to Objective-C 12082 // objects. 12083 return DiagnoseImpCast(S, E, T, CC, 12084 diag::warn_impcast_objective_c_literal_to_bool); 12085 } 12086 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12087 // Warn on pointer to bool conversion that is always true. 12088 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12089 SourceRange(CC)); 12090 } 12091 } 12092 12093 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12094 // is a typedef for signed char (macOS), then that constant value has to be 1 12095 // or 0. 12096 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12097 Expr::EvalResult Result; 12098 if (E->EvaluateAsInt(Result, S.getASTContext(), 12099 Expr::SE_AllowSideEffects)) { 12100 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12101 adornObjCBoolConversionDiagWithTernaryFixit( 12102 S, E, 12103 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12104 << Result.Val.getInt().toString(10)); 12105 } 12106 return; 12107 } 12108 } 12109 12110 // Check implicit casts from Objective-C collection literals to specialized 12111 // collection types, e.g., NSArray<NSString *> *. 12112 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12113 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12114 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12115 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12116 12117 // Strip vector types. 12118 if (const auto *SourceVT = dyn_cast<VectorType>(Source)) { 12119 if (Target->isVLSTBuiltinType()) { 12120 auto SourceVectorKind = SourceVT->getVectorKind(); 12121 if (SourceVectorKind == VectorType::SveFixedLengthDataVector || 12122 SourceVectorKind == VectorType::SveFixedLengthPredicateVector || 12123 (SourceVectorKind == VectorType::GenericVector && 12124 S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits)) 12125 return; 12126 } 12127 12128 if (!isa<VectorType>(Target)) { 12129 if (S.SourceMgr.isInSystemMacro(CC)) 12130 return; 12131 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12132 } 12133 12134 // If the vector cast is cast between two vectors of the same size, it is 12135 // a bitcast, not a conversion. 12136 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12137 return; 12138 12139 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12140 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12141 } 12142 if (auto VecTy = dyn_cast<VectorType>(Target)) 12143 Target = VecTy->getElementType().getTypePtr(); 12144 12145 // Strip complex types. 12146 if (isa<ComplexType>(Source)) { 12147 if (!isa<ComplexType>(Target)) { 12148 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12149 return; 12150 12151 return DiagnoseImpCast(S, E, T, CC, 12152 S.getLangOpts().CPlusPlus 12153 ? diag::err_impcast_complex_scalar 12154 : diag::warn_impcast_complex_scalar); 12155 } 12156 12157 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12158 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12159 } 12160 12161 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12162 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12163 12164 // If the source is floating point... 12165 if (SourceBT && SourceBT->isFloatingPoint()) { 12166 // ...and the target is floating point... 12167 if (TargetBT && TargetBT->isFloatingPoint()) { 12168 // ...then warn if we're dropping FP rank. 12169 12170 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12171 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12172 if (Order > 0) { 12173 // Don't warn about float constants that are precisely 12174 // representable in the target type. 12175 Expr::EvalResult result; 12176 if (E->EvaluateAsRValue(result, S.Context)) { 12177 // Value might be a float, a float vector, or a float complex. 12178 if (IsSameFloatAfterCast(result.Val, 12179 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12180 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12181 return; 12182 } 12183 12184 if (S.SourceMgr.isInSystemMacro(CC)) 12185 return; 12186 12187 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12188 } 12189 // ... or possibly if we're increasing rank, too 12190 else if (Order < 0) { 12191 if (S.SourceMgr.isInSystemMacro(CC)) 12192 return; 12193 12194 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12195 } 12196 return; 12197 } 12198 12199 // If the target is integral, always warn. 12200 if (TargetBT && TargetBT->isInteger()) { 12201 if (S.SourceMgr.isInSystemMacro(CC)) 12202 return; 12203 12204 DiagnoseFloatingImpCast(S, E, T, CC); 12205 } 12206 12207 // Detect the case where a call result is converted from floating-point to 12208 // to bool, and the final argument to the call is converted from bool, to 12209 // discover this typo: 12210 // 12211 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12212 // 12213 // FIXME: This is an incredibly special case; is there some more general 12214 // way to detect this class of misplaced-parentheses bug? 12215 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12216 // Check last argument of function call to see if it is an 12217 // implicit cast from a type matching the type the result 12218 // is being cast to. 12219 CallExpr *CEx = cast<CallExpr>(E); 12220 if (unsigned NumArgs = CEx->getNumArgs()) { 12221 Expr *LastA = CEx->getArg(NumArgs - 1); 12222 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12223 if (isa<ImplicitCastExpr>(LastA) && 12224 InnerE->getType()->isBooleanType()) { 12225 // Warn on this floating-point to bool conversion 12226 DiagnoseImpCast(S, E, T, CC, 12227 diag::warn_impcast_floating_point_to_bool); 12228 } 12229 } 12230 } 12231 return; 12232 } 12233 12234 // Valid casts involving fixed point types should be accounted for here. 12235 if (Source->isFixedPointType()) { 12236 if (Target->isUnsaturatedFixedPointType()) { 12237 Expr::EvalResult Result; 12238 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12239 S.isConstantEvaluated())) { 12240 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12241 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12242 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12243 if (Value > MaxVal || Value < MinVal) { 12244 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12245 S.PDiag(diag::warn_impcast_fixed_point_range) 12246 << Value.toString() << T 12247 << E->getSourceRange() 12248 << clang::SourceRange(CC)); 12249 return; 12250 } 12251 } 12252 } else if (Target->isIntegerType()) { 12253 Expr::EvalResult Result; 12254 if (!S.isConstantEvaluated() && 12255 E->EvaluateAsFixedPoint(Result, S.Context, 12256 Expr::SE_AllowSideEffects)) { 12257 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12258 12259 bool Overflowed; 12260 llvm::APSInt IntResult = FXResult.convertToInt( 12261 S.Context.getIntWidth(T), 12262 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12263 12264 if (Overflowed) { 12265 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12266 S.PDiag(diag::warn_impcast_fixed_point_range) 12267 << FXResult.toString() << T 12268 << E->getSourceRange() 12269 << clang::SourceRange(CC)); 12270 return; 12271 } 12272 } 12273 } 12274 } else if (Target->isUnsaturatedFixedPointType()) { 12275 if (Source->isIntegerType()) { 12276 Expr::EvalResult Result; 12277 if (!S.isConstantEvaluated() && 12278 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12279 llvm::APSInt Value = Result.Val.getInt(); 12280 12281 bool Overflowed; 12282 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12283 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12284 12285 if (Overflowed) { 12286 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12287 S.PDiag(diag::warn_impcast_fixed_point_range) 12288 << Value.toString(/*Radix=*/10) << T 12289 << E->getSourceRange() 12290 << clang::SourceRange(CC)); 12291 return; 12292 } 12293 } 12294 } 12295 } 12296 12297 // If we are casting an integer type to a floating point type without 12298 // initialization-list syntax, we might lose accuracy if the floating 12299 // point type has a narrower significand than the integer type. 12300 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12301 TargetBT->isFloatingType() && !IsListInit) { 12302 // Determine the number of precision bits in the source integer type. 12303 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12304 /*Approximate*/ true); 12305 unsigned int SourcePrecision = SourceRange.Width; 12306 12307 // Determine the number of precision bits in the 12308 // target floating point type. 12309 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12310 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12311 12312 if (SourcePrecision > 0 && TargetPrecision > 0 && 12313 SourcePrecision > TargetPrecision) { 12314 12315 if (Optional<llvm::APSInt> SourceInt = 12316 E->getIntegerConstantExpr(S.Context)) { 12317 // If the source integer is a constant, convert it to the target 12318 // floating point type. Issue a warning if the value changes 12319 // during the whole conversion. 12320 llvm::APFloat TargetFloatValue( 12321 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12322 llvm::APFloat::opStatus ConversionStatus = 12323 TargetFloatValue.convertFromAPInt( 12324 *SourceInt, SourceBT->isSignedInteger(), 12325 llvm::APFloat::rmNearestTiesToEven); 12326 12327 if (ConversionStatus != llvm::APFloat::opOK) { 12328 std::string PrettySourceValue = SourceInt->toString(10); 12329 SmallString<32> PrettyTargetValue; 12330 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12331 12332 S.DiagRuntimeBehavior( 12333 E->getExprLoc(), E, 12334 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12335 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12336 << E->getSourceRange() << clang::SourceRange(CC)); 12337 } 12338 } else { 12339 // Otherwise, the implicit conversion may lose precision. 12340 DiagnoseImpCast(S, E, T, CC, 12341 diag::warn_impcast_integer_float_precision); 12342 } 12343 } 12344 } 12345 12346 DiagnoseNullConversion(S, E, T, CC); 12347 12348 S.DiscardMisalignedMemberAddress(Target, E); 12349 12350 if (Target->isBooleanType()) 12351 DiagnoseIntInBoolContext(S, E); 12352 12353 if (!Source->isIntegerType() || !Target->isIntegerType()) 12354 return; 12355 12356 // TODO: remove this early return once the false positives for constant->bool 12357 // in templates, macros, etc, are reduced or removed. 12358 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12359 return; 12360 12361 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12362 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12363 return adornObjCBoolConversionDiagWithTernaryFixit( 12364 S, E, 12365 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12366 << E->getType()); 12367 } 12368 12369 IntRange SourceTypeRange = 12370 IntRange::forTargetOfCanonicalType(S.Context, Source); 12371 IntRange LikelySourceRange = 12372 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12373 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12374 12375 if (LikelySourceRange.Width > TargetRange.Width) { 12376 // If the source is a constant, use a default-on diagnostic. 12377 // TODO: this should happen for bitfield stores, too. 12378 Expr::EvalResult Result; 12379 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12380 S.isConstantEvaluated())) { 12381 llvm::APSInt Value(32); 12382 Value = Result.Val.getInt(); 12383 12384 if (S.SourceMgr.isInSystemMacro(CC)) 12385 return; 12386 12387 std::string PrettySourceValue = Value.toString(10); 12388 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12389 12390 S.DiagRuntimeBehavior( 12391 E->getExprLoc(), E, 12392 S.PDiag(diag::warn_impcast_integer_precision_constant) 12393 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12394 << E->getSourceRange() << SourceRange(CC)); 12395 return; 12396 } 12397 12398 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12399 if (S.SourceMgr.isInSystemMacro(CC)) 12400 return; 12401 12402 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12403 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12404 /* pruneControlFlow */ true); 12405 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12406 } 12407 12408 if (TargetRange.Width > SourceTypeRange.Width) { 12409 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12410 if (UO->getOpcode() == UO_Minus) 12411 if (Source->isUnsignedIntegerType()) { 12412 if (Target->isUnsignedIntegerType()) 12413 return DiagnoseImpCast(S, E, T, CC, 12414 diag::warn_impcast_high_order_zero_bits); 12415 if (Target->isSignedIntegerType()) 12416 return DiagnoseImpCast(S, E, T, CC, 12417 diag::warn_impcast_nonnegative_result); 12418 } 12419 } 12420 12421 if (TargetRange.Width == LikelySourceRange.Width && 12422 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12423 Source->isSignedIntegerType()) { 12424 // Warn when doing a signed to signed conversion, warn if the positive 12425 // source value is exactly the width of the target type, which will 12426 // cause a negative value to be stored. 12427 12428 Expr::EvalResult Result; 12429 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12430 !S.SourceMgr.isInSystemMacro(CC)) { 12431 llvm::APSInt Value = Result.Val.getInt(); 12432 if (isSameWidthConstantConversion(S, E, T, CC)) { 12433 std::string PrettySourceValue = Value.toString(10); 12434 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12435 12436 S.DiagRuntimeBehavior( 12437 E->getExprLoc(), E, 12438 S.PDiag(diag::warn_impcast_integer_precision_constant) 12439 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12440 << E->getSourceRange() << SourceRange(CC)); 12441 return; 12442 } 12443 } 12444 12445 // Fall through for non-constants to give a sign conversion warning. 12446 } 12447 12448 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12449 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12450 LikelySourceRange.Width == TargetRange.Width)) { 12451 if (S.SourceMgr.isInSystemMacro(CC)) 12452 return; 12453 12454 unsigned DiagID = diag::warn_impcast_integer_sign; 12455 12456 // Traditionally, gcc has warned about this under -Wsign-compare. 12457 // We also want to warn about it in -Wconversion. 12458 // So if -Wconversion is off, use a completely identical diagnostic 12459 // in the sign-compare group. 12460 // The conditional-checking code will 12461 if (ICContext) { 12462 DiagID = diag::warn_impcast_integer_sign_conditional; 12463 *ICContext = true; 12464 } 12465 12466 return DiagnoseImpCast(S, E, T, CC, DiagID); 12467 } 12468 12469 // Diagnose conversions between different enumeration types. 12470 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12471 // type, to give us better diagnostics. 12472 QualType SourceType = E->getType(); 12473 if (!S.getLangOpts().CPlusPlus) { 12474 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12475 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12476 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12477 SourceType = S.Context.getTypeDeclType(Enum); 12478 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12479 } 12480 } 12481 12482 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12483 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12484 if (SourceEnum->getDecl()->hasNameForLinkage() && 12485 TargetEnum->getDecl()->hasNameForLinkage() && 12486 SourceEnum != TargetEnum) { 12487 if (S.SourceMgr.isInSystemMacro(CC)) 12488 return; 12489 12490 return DiagnoseImpCast(S, E, SourceType, T, CC, 12491 diag::warn_impcast_different_enum_types); 12492 } 12493 } 12494 12495 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12496 SourceLocation CC, QualType T); 12497 12498 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12499 SourceLocation CC, bool &ICContext) { 12500 E = E->IgnoreParenImpCasts(); 12501 12502 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12503 return CheckConditionalOperator(S, CO, CC, T); 12504 12505 AnalyzeImplicitConversions(S, E, CC); 12506 if (E->getType() != T) 12507 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12508 } 12509 12510 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12511 SourceLocation CC, QualType T) { 12512 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12513 12514 Expr *TrueExpr = E->getTrueExpr(); 12515 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12516 TrueExpr = BCO->getCommon(); 12517 12518 bool Suspicious = false; 12519 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12520 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12521 12522 if (T->isBooleanType()) 12523 DiagnoseIntInBoolContext(S, E); 12524 12525 // If -Wconversion would have warned about either of the candidates 12526 // for a signedness conversion to the context type... 12527 if (!Suspicious) return; 12528 12529 // ...but it's currently ignored... 12530 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12531 return; 12532 12533 // ...then check whether it would have warned about either of the 12534 // candidates for a signedness conversion to the condition type. 12535 if (E->getType() == T) return; 12536 12537 Suspicious = false; 12538 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12539 E->getType(), CC, &Suspicious); 12540 if (!Suspicious) 12541 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12542 E->getType(), CC, &Suspicious); 12543 } 12544 12545 /// Check conversion of given expression to boolean. 12546 /// Input argument E is a logical expression. 12547 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12548 if (S.getLangOpts().Bool) 12549 return; 12550 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12551 return; 12552 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12553 } 12554 12555 namespace { 12556 struct AnalyzeImplicitConversionsWorkItem { 12557 Expr *E; 12558 SourceLocation CC; 12559 bool IsListInit; 12560 }; 12561 } 12562 12563 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12564 /// that should be visited are added to WorkList. 12565 static void AnalyzeImplicitConversions( 12566 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12567 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12568 Expr *OrigE = Item.E; 12569 SourceLocation CC = Item.CC; 12570 12571 QualType T = OrigE->getType(); 12572 Expr *E = OrigE->IgnoreParenImpCasts(); 12573 12574 // Propagate whether we are in a C++ list initialization expression. 12575 // If so, we do not issue warnings for implicit int-float conversion 12576 // precision loss, because C++11 narrowing already handles it. 12577 bool IsListInit = Item.IsListInit || 12578 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12579 12580 if (E->isTypeDependent() || E->isValueDependent()) 12581 return; 12582 12583 Expr *SourceExpr = E; 12584 // Examine, but don't traverse into the source expression of an 12585 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12586 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12587 // evaluate it in the context of checking the specific conversion to T though. 12588 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12589 if (auto *Src = OVE->getSourceExpr()) 12590 SourceExpr = Src; 12591 12592 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12593 if (UO->getOpcode() == UO_Not && 12594 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12595 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12596 << OrigE->getSourceRange() << T->isBooleanType() 12597 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12598 12599 // For conditional operators, we analyze the arguments as if they 12600 // were being fed directly into the output. 12601 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12602 CheckConditionalOperator(S, CO, CC, T); 12603 return; 12604 } 12605 12606 // Check implicit argument conversions for function calls. 12607 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12608 CheckImplicitArgumentConversions(S, Call, CC); 12609 12610 // Go ahead and check any implicit conversions we might have skipped. 12611 // The non-canonical typecheck is just an optimization; 12612 // CheckImplicitConversion will filter out dead implicit conversions. 12613 if (SourceExpr->getType() != T) 12614 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12615 12616 // Now continue drilling into this expression. 12617 12618 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12619 // The bound subexpressions in a PseudoObjectExpr are not reachable 12620 // as transitive children. 12621 // FIXME: Use a more uniform representation for this. 12622 for (auto *SE : POE->semantics()) 12623 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12624 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12625 } 12626 12627 // Skip past explicit casts. 12628 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12629 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12630 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12631 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12632 WorkList.push_back({E, CC, IsListInit}); 12633 return; 12634 } 12635 12636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12637 // Do a somewhat different check with comparison operators. 12638 if (BO->isComparisonOp()) 12639 return AnalyzeComparison(S, BO); 12640 12641 // And with simple assignments. 12642 if (BO->getOpcode() == BO_Assign) 12643 return AnalyzeAssignment(S, BO); 12644 // And with compound assignments. 12645 if (BO->isAssignmentOp()) 12646 return AnalyzeCompoundAssignment(S, BO); 12647 } 12648 12649 // These break the otherwise-useful invariant below. Fortunately, 12650 // we don't really need to recurse into them, because any internal 12651 // expressions should have been analyzed already when they were 12652 // built into statements. 12653 if (isa<StmtExpr>(E)) return; 12654 12655 // Don't descend into unevaluated contexts. 12656 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12657 12658 // Now just recurse over the expression's children. 12659 CC = E->getExprLoc(); 12660 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12661 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12662 for (Stmt *SubStmt : E->children()) { 12663 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12664 if (!ChildExpr) 12665 continue; 12666 12667 if (IsLogicalAndOperator && 12668 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12669 // Ignore checking string literals that are in logical and operators. 12670 // This is a common pattern for asserts. 12671 continue; 12672 WorkList.push_back({ChildExpr, CC, IsListInit}); 12673 } 12674 12675 if (BO && BO->isLogicalOp()) { 12676 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12677 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12678 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12679 12680 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12681 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12682 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12683 } 12684 12685 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12686 if (U->getOpcode() == UO_LNot) { 12687 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12688 } else if (U->getOpcode() != UO_AddrOf) { 12689 if (U->getSubExpr()->getType()->isAtomicType()) 12690 S.Diag(U->getSubExpr()->getBeginLoc(), 12691 diag::warn_atomic_implicit_seq_cst); 12692 } 12693 } 12694 } 12695 12696 /// AnalyzeImplicitConversions - Find and report any interesting 12697 /// implicit conversions in the given expression. There are a couple 12698 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12699 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12700 bool IsListInit/*= false*/) { 12701 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12702 WorkList.push_back({OrigE, CC, IsListInit}); 12703 while (!WorkList.empty()) 12704 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12705 } 12706 12707 /// Diagnose integer type and any valid implicit conversion to it. 12708 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12709 // Taking into account implicit conversions, 12710 // allow any integer. 12711 if (!E->getType()->isIntegerType()) { 12712 S.Diag(E->getBeginLoc(), 12713 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12714 return true; 12715 } 12716 // Potentially emit standard warnings for implicit conversions if enabled 12717 // using -Wconversion. 12718 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12719 return false; 12720 } 12721 12722 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12723 // Returns true when emitting a warning about taking the address of a reference. 12724 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12725 const PartialDiagnostic &PD) { 12726 E = E->IgnoreParenImpCasts(); 12727 12728 const FunctionDecl *FD = nullptr; 12729 12730 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12731 if (!DRE->getDecl()->getType()->isReferenceType()) 12732 return false; 12733 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12734 if (!M->getMemberDecl()->getType()->isReferenceType()) 12735 return false; 12736 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12737 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12738 return false; 12739 FD = Call->getDirectCallee(); 12740 } else { 12741 return false; 12742 } 12743 12744 SemaRef.Diag(E->getExprLoc(), PD); 12745 12746 // If possible, point to location of function. 12747 if (FD) { 12748 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12749 } 12750 12751 return true; 12752 } 12753 12754 // Returns true if the SourceLocation is expanded from any macro body. 12755 // Returns false if the SourceLocation is invalid, is from not in a macro 12756 // expansion, or is from expanded from a top-level macro argument. 12757 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12758 if (Loc.isInvalid()) 12759 return false; 12760 12761 while (Loc.isMacroID()) { 12762 if (SM.isMacroBodyExpansion(Loc)) 12763 return true; 12764 Loc = SM.getImmediateMacroCallerLoc(Loc); 12765 } 12766 12767 return false; 12768 } 12769 12770 /// Diagnose pointers that are always non-null. 12771 /// \param E the expression containing the pointer 12772 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12773 /// compared to a null pointer 12774 /// \param IsEqual True when the comparison is equal to a null pointer 12775 /// \param Range Extra SourceRange to highlight in the diagnostic 12776 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12777 Expr::NullPointerConstantKind NullKind, 12778 bool IsEqual, SourceRange Range) { 12779 if (!E) 12780 return; 12781 12782 // Don't warn inside macros. 12783 if (E->getExprLoc().isMacroID()) { 12784 const SourceManager &SM = getSourceManager(); 12785 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12786 IsInAnyMacroBody(SM, Range.getBegin())) 12787 return; 12788 } 12789 E = E->IgnoreImpCasts(); 12790 12791 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12792 12793 if (isa<CXXThisExpr>(E)) { 12794 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12795 : diag::warn_this_bool_conversion; 12796 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12797 return; 12798 } 12799 12800 bool IsAddressOf = false; 12801 12802 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12803 if (UO->getOpcode() != UO_AddrOf) 12804 return; 12805 IsAddressOf = true; 12806 E = UO->getSubExpr(); 12807 } 12808 12809 if (IsAddressOf) { 12810 unsigned DiagID = IsCompare 12811 ? diag::warn_address_of_reference_null_compare 12812 : diag::warn_address_of_reference_bool_conversion; 12813 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12814 << IsEqual; 12815 if (CheckForReference(*this, E, PD)) { 12816 return; 12817 } 12818 } 12819 12820 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12821 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12822 std::string Str; 12823 llvm::raw_string_ostream S(Str); 12824 E->printPretty(S, nullptr, getPrintingPolicy()); 12825 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12826 : diag::warn_cast_nonnull_to_bool; 12827 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12828 << E->getSourceRange() << Range << IsEqual; 12829 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12830 }; 12831 12832 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12833 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12834 if (auto *Callee = Call->getDirectCallee()) { 12835 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12836 ComplainAboutNonnullParamOrCall(A); 12837 return; 12838 } 12839 } 12840 } 12841 12842 // Expect to find a single Decl. Skip anything more complicated. 12843 ValueDecl *D = nullptr; 12844 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12845 D = R->getDecl(); 12846 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12847 D = M->getMemberDecl(); 12848 } 12849 12850 // Weak Decls can be null. 12851 if (!D || D->isWeak()) 12852 return; 12853 12854 // Check for parameter decl with nonnull attribute 12855 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12856 if (getCurFunction() && 12857 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12858 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12859 ComplainAboutNonnullParamOrCall(A); 12860 return; 12861 } 12862 12863 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12864 // Skip function template not specialized yet. 12865 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12866 return; 12867 auto ParamIter = llvm::find(FD->parameters(), PV); 12868 assert(ParamIter != FD->param_end()); 12869 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12870 12871 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12872 if (!NonNull->args_size()) { 12873 ComplainAboutNonnullParamOrCall(NonNull); 12874 return; 12875 } 12876 12877 for (const ParamIdx &ArgNo : NonNull->args()) { 12878 if (ArgNo.getASTIndex() == ParamNo) { 12879 ComplainAboutNonnullParamOrCall(NonNull); 12880 return; 12881 } 12882 } 12883 } 12884 } 12885 } 12886 } 12887 12888 QualType T = D->getType(); 12889 const bool IsArray = T->isArrayType(); 12890 const bool IsFunction = T->isFunctionType(); 12891 12892 // Address of function is used to silence the function warning. 12893 if (IsAddressOf && IsFunction) { 12894 return; 12895 } 12896 12897 // Found nothing. 12898 if (!IsAddressOf && !IsFunction && !IsArray) 12899 return; 12900 12901 // Pretty print the expression for the diagnostic. 12902 std::string Str; 12903 llvm::raw_string_ostream S(Str); 12904 E->printPretty(S, nullptr, getPrintingPolicy()); 12905 12906 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12907 : diag::warn_impcast_pointer_to_bool; 12908 enum { 12909 AddressOf, 12910 FunctionPointer, 12911 ArrayPointer 12912 } DiagType; 12913 if (IsAddressOf) 12914 DiagType = AddressOf; 12915 else if (IsFunction) 12916 DiagType = FunctionPointer; 12917 else if (IsArray) 12918 DiagType = ArrayPointer; 12919 else 12920 llvm_unreachable("Could not determine diagnostic."); 12921 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12922 << Range << IsEqual; 12923 12924 if (!IsFunction) 12925 return; 12926 12927 // Suggest '&' to silence the function warning. 12928 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12929 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12930 12931 // Check to see if '()' fixit should be emitted. 12932 QualType ReturnType; 12933 UnresolvedSet<4> NonTemplateOverloads; 12934 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12935 if (ReturnType.isNull()) 12936 return; 12937 12938 if (IsCompare) { 12939 // There are two cases here. If there is null constant, the only suggest 12940 // for a pointer return type. If the null is 0, then suggest if the return 12941 // type is a pointer or an integer type. 12942 if (!ReturnType->isPointerType()) { 12943 if (NullKind == Expr::NPCK_ZeroExpression || 12944 NullKind == Expr::NPCK_ZeroLiteral) { 12945 if (!ReturnType->isIntegerType()) 12946 return; 12947 } else { 12948 return; 12949 } 12950 } 12951 } else { // !IsCompare 12952 // For function to bool, only suggest if the function pointer has bool 12953 // return type. 12954 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12955 return; 12956 } 12957 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12958 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12959 } 12960 12961 /// Diagnoses "dangerous" implicit conversions within the given 12962 /// expression (which is a full expression). Implements -Wconversion 12963 /// and -Wsign-compare. 12964 /// 12965 /// \param CC the "context" location of the implicit conversion, i.e. 12966 /// the most location of the syntactic entity requiring the implicit 12967 /// conversion 12968 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12969 // Don't diagnose in unevaluated contexts. 12970 if (isUnevaluatedContext()) 12971 return; 12972 12973 // Don't diagnose for value- or type-dependent expressions. 12974 if (E->isTypeDependent() || E->isValueDependent()) 12975 return; 12976 12977 // Check for array bounds violations in cases where the check isn't triggered 12978 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12979 // ArraySubscriptExpr is on the RHS of a variable initialization. 12980 CheckArrayAccess(E); 12981 12982 // This is not the right CC for (e.g.) a variable initialization. 12983 AnalyzeImplicitConversions(*this, E, CC); 12984 } 12985 12986 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12987 /// Input argument E is a logical expression. 12988 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12989 ::CheckBoolLikeConversion(*this, E, CC); 12990 } 12991 12992 /// Diagnose when expression is an integer constant expression and its evaluation 12993 /// results in integer overflow 12994 void Sema::CheckForIntOverflow (Expr *E) { 12995 // Use a work list to deal with nested struct initializers. 12996 SmallVector<Expr *, 2> Exprs(1, E); 12997 12998 do { 12999 Expr *OriginalE = Exprs.pop_back_val(); 13000 Expr *E = OriginalE->IgnoreParenCasts(); 13001 13002 if (isa<BinaryOperator>(E)) { 13003 E->EvaluateForOverflow(Context); 13004 continue; 13005 } 13006 13007 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13008 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13009 else if (isa<ObjCBoxedExpr>(OriginalE)) 13010 E->EvaluateForOverflow(Context); 13011 else if (auto Call = dyn_cast<CallExpr>(E)) 13012 Exprs.append(Call->arg_begin(), Call->arg_end()); 13013 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13014 Exprs.append(Message->arg_begin(), Message->arg_end()); 13015 } while (!Exprs.empty()); 13016 } 13017 13018 namespace { 13019 13020 /// Visitor for expressions which looks for unsequenced operations on the 13021 /// same object. 13022 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13023 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13024 13025 /// A tree of sequenced regions within an expression. Two regions are 13026 /// unsequenced if one is an ancestor or a descendent of the other. When we 13027 /// finish processing an expression with sequencing, such as a comma 13028 /// expression, we fold its tree nodes into its parent, since they are 13029 /// unsequenced with respect to nodes we will visit later. 13030 class SequenceTree { 13031 struct Value { 13032 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13033 unsigned Parent : 31; 13034 unsigned Merged : 1; 13035 }; 13036 SmallVector<Value, 8> Values; 13037 13038 public: 13039 /// A region within an expression which may be sequenced with respect 13040 /// to some other region. 13041 class Seq { 13042 friend class SequenceTree; 13043 13044 unsigned Index; 13045 13046 explicit Seq(unsigned N) : Index(N) {} 13047 13048 public: 13049 Seq() : Index(0) {} 13050 }; 13051 13052 SequenceTree() { Values.push_back(Value(0)); } 13053 Seq root() const { return Seq(0); } 13054 13055 /// Create a new sequence of operations, which is an unsequenced 13056 /// subset of \p Parent. This sequence of operations is sequenced with 13057 /// respect to other children of \p Parent. 13058 Seq allocate(Seq Parent) { 13059 Values.push_back(Value(Parent.Index)); 13060 return Seq(Values.size() - 1); 13061 } 13062 13063 /// Merge a sequence of operations into its parent. 13064 void merge(Seq S) { 13065 Values[S.Index].Merged = true; 13066 } 13067 13068 /// Determine whether two operations are unsequenced. This operation 13069 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13070 /// should have been merged into its parent as appropriate. 13071 bool isUnsequenced(Seq Cur, Seq Old) { 13072 unsigned C = representative(Cur.Index); 13073 unsigned Target = representative(Old.Index); 13074 while (C >= Target) { 13075 if (C == Target) 13076 return true; 13077 C = Values[C].Parent; 13078 } 13079 return false; 13080 } 13081 13082 private: 13083 /// Pick a representative for a sequence. 13084 unsigned representative(unsigned K) { 13085 if (Values[K].Merged) 13086 // Perform path compression as we go. 13087 return Values[K].Parent = representative(Values[K].Parent); 13088 return K; 13089 } 13090 }; 13091 13092 /// An object for which we can track unsequenced uses. 13093 using Object = const NamedDecl *; 13094 13095 /// Different flavors of object usage which we track. We only track the 13096 /// least-sequenced usage of each kind. 13097 enum UsageKind { 13098 /// A read of an object. Multiple unsequenced reads are OK. 13099 UK_Use, 13100 13101 /// A modification of an object which is sequenced before the value 13102 /// computation of the expression, such as ++n in C++. 13103 UK_ModAsValue, 13104 13105 /// A modification of an object which is not sequenced before the value 13106 /// computation of the expression, such as n++. 13107 UK_ModAsSideEffect, 13108 13109 UK_Count = UK_ModAsSideEffect + 1 13110 }; 13111 13112 /// Bundle together a sequencing region and the expression corresponding 13113 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13114 struct Usage { 13115 const Expr *UsageExpr; 13116 SequenceTree::Seq Seq; 13117 13118 Usage() : UsageExpr(nullptr), Seq() {} 13119 }; 13120 13121 struct UsageInfo { 13122 Usage Uses[UK_Count]; 13123 13124 /// Have we issued a diagnostic for this object already? 13125 bool Diagnosed; 13126 13127 UsageInfo() : Uses(), Diagnosed(false) {} 13128 }; 13129 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13130 13131 Sema &SemaRef; 13132 13133 /// Sequenced regions within the expression. 13134 SequenceTree Tree; 13135 13136 /// Declaration modifications and references which we have seen. 13137 UsageInfoMap UsageMap; 13138 13139 /// The region we are currently within. 13140 SequenceTree::Seq Region; 13141 13142 /// Filled in with declarations which were modified as a side-effect 13143 /// (that is, post-increment operations). 13144 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13145 13146 /// Expressions to check later. We defer checking these to reduce 13147 /// stack usage. 13148 SmallVectorImpl<const Expr *> &WorkList; 13149 13150 /// RAII object wrapping the visitation of a sequenced subexpression of an 13151 /// expression. At the end of this process, the side-effects of the evaluation 13152 /// become sequenced with respect to the value computation of the result, so 13153 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13154 /// UK_ModAsValue. 13155 struct SequencedSubexpression { 13156 SequencedSubexpression(SequenceChecker &Self) 13157 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13158 Self.ModAsSideEffect = &ModAsSideEffect; 13159 } 13160 13161 ~SequencedSubexpression() { 13162 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13163 // Add a new usage with usage kind UK_ModAsValue, and then restore 13164 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13165 // the previous one was empty). 13166 UsageInfo &UI = Self.UsageMap[M.first]; 13167 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13168 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13169 SideEffectUsage = M.second; 13170 } 13171 Self.ModAsSideEffect = OldModAsSideEffect; 13172 } 13173 13174 SequenceChecker &Self; 13175 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13176 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13177 }; 13178 13179 /// RAII object wrapping the visitation of a subexpression which we might 13180 /// choose to evaluate as a constant. If any subexpression is evaluated and 13181 /// found to be non-constant, this allows us to suppress the evaluation of 13182 /// the outer expression. 13183 class EvaluationTracker { 13184 public: 13185 EvaluationTracker(SequenceChecker &Self) 13186 : Self(Self), Prev(Self.EvalTracker) { 13187 Self.EvalTracker = this; 13188 } 13189 13190 ~EvaluationTracker() { 13191 Self.EvalTracker = Prev; 13192 if (Prev) 13193 Prev->EvalOK &= EvalOK; 13194 } 13195 13196 bool evaluate(const Expr *E, bool &Result) { 13197 if (!EvalOK || E->isValueDependent()) 13198 return false; 13199 EvalOK = E->EvaluateAsBooleanCondition( 13200 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13201 return EvalOK; 13202 } 13203 13204 private: 13205 SequenceChecker &Self; 13206 EvaluationTracker *Prev; 13207 bool EvalOK = true; 13208 } *EvalTracker = nullptr; 13209 13210 /// Find the object which is produced by the specified expression, 13211 /// if any. 13212 Object getObject(const Expr *E, bool Mod) const { 13213 E = E->IgnoreParenCasts(); 13214 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13215 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13216 return getObject(UO->getSubExpr(), Mod); 13217 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13218 if (BO->getOpcode() == BO_Comma) 13219 return getObject(BO->getRHS(), Mod); 13220 if (Mod && BO->isAssignmentOp()) 13221 return getObject(BO->getLHS(), Mod); 13222 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13223 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13224 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13225 return ME->getMemberDecl(); 13226 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13227 // FIXME: If this is a reference, map through to its value. 13228 return DRE->getDecl(); 13229 return nullptr; 13230 } 13231 13232 /// Note that an object \p O was modified or used by an expression 13233 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13234 /// the object \p O as obtained via the \p UsageMap. 13235 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13236 // Get the old usage for the given object and usage kind. 13237 Usage &U = UI.Uses[UK]; 13238 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13239 // If we have a modification as side effect and are in a sequenced 13240 // subexpression, save the old Usage so that we can restore it later 13241 // in SequencedSubexpression::~SequencedSubexpression. 13242 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13243 ModAsSideEffect->push_back(std::make_pair(O, U)); 13244 // Then record the new usage with the current sequencing region. 13245 U.UsageExpr = UsageExpr; 13246 U.Seq = Region; 13247 } 13248 } 13249 13250 /// Check whether a modification or use of an object \p O in an expression 13251 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13252 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13253 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13254 /// usage and false we are checking for a mod-use unsequenced usage. 13255 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13256 UsageKind OtherKind, bool IsModMod) { 13257 if (UI.Diagnosed) 13258 return; 13259 13260 const Usage &U = UI.Uses[OtherKind]; 13261 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13262 return; 13263 13264 const Expr *Mod = U.UsageExpr; 13265 const Expr *ModOrUse = UsageExpr; 13266 if (OtherKind == UK_Use) 13267 std::swap(Mod, ModOrUse); 13268 13269 SemaRef.DiagRuntimeBehavior( 13270 Mod->getExprLoc(), {Mod, ModOrUse}, 13271 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13272 : diag::warn_unsequenced_mod_use) 13273 << O << SourceRange(ModOrUse->getExprLoc())); 13274 UI.Diagnosed = true; 13275 } 13276 13277 // A note on note{Pre, Post}{Use, Mod}: 13278 // 13279 // (It helps to follow the algorithm with an expression such as 13280 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13281 // operations before C++17 and both are well-defined in C++17). 13282 // 13283 // When visiting a node which uses/modify an object we first call notePreUse 13284 // or notePreMod before visiting its sub-expression(s). At this point the 13285 // children of the current node have not yet been visited and so the eventual 13286 // uses/modifications resulting from the children of the current node have not 13287 // been recorded yet. 13288 // 13289 // We then visit the children of the current node. After that notePostUse or 13290 // notePostMod is called. These will 1) detect an unsequenced modification 13291 // as side effect (as in "k++ + k") and 2) add a new usage with the 13292 // appropriate usage kind. 13293 // 13294 // We also have to be careful that some operation sequences modification as 13295 // side effect as well (for example: || or ,). To account for this we wrap 13296 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13297 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13298 // which record usages which are modifications as side effect, and then 13299 // downgrade them (or more accurately restore the previous usage which was a 13300 // modification as side effect) when exiting the scope of the sequenced 13301 // subexpression. 13302 13303 void notePreUse(Object O, const Expr *UseExpr) { 13304 UsageInfo &UI = UsageMap[O]; 13305 // Uses conflict with other modifications. 13306 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13307 } 13308 13309 void notePostUse(Object O, const Expr *UseExpr) { 13310 UsageInfo &UI = UsageMap[O]; 13311 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13312 /*IsModMod=*/false); 13313 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13314 } 13315 13316 void notePreMod(Object O, const Expr *ModExpr) { 13317 UsageInfo &UI = UsageMap[O]; 13318 // Modifications conflict with other modifications and with uses. 13319 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13320 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13321 } 13322 13323 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13324 UsageInfo &UI = UsageMap[O]; 13325 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13326 /*IsModMod=*/true); 13327 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13328 } 13329 13330 public: 13331 SequenceChecker(Sema &S, const Expr *E, 13332 SmallVectorImpl<const Expr *> &WorkList) 13333 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13334 Visit(E); 13335 // Silence a -Wunused-private-field since WorkList is now unused. 13336 // TODO: Evaluate if it can be used, and if not remove it. 13337 (void)this->WorkList; 13338 } 13339 13340 void VisitStmt(const Stmt *S) { 13341 // Skip all statements which aren't expressions for now. 13342 } 13343 13344 void VisitExpr(const Expr *E) { 13345 // By default, just recurse to evaluated subexpressions. 13346 Base::VisitStmt(E); 13347 } 13348 13349 void VisitCastExpr(const CastExpr *E) { 13350 Object O = Object(); 13351 if (E->getCastKind() == CK_LValueToRValue) 13352 O = getObject(E->getSubExpr(), false); 13353 13354 if (O) 13355 notePreUse(O, E); 13356 VisitExpr(E); 13357 if (O) 13358 notePostUse(O, E); 13359 } 13360 13361 void VisitSequencedExpressions(const Expr *SequencedBefore, 13362 const Expr *SequencedAfter) { 13363 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13364 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13365 SequenceTree::Seq OldRegion = Region; 13366 13367 { 13368 SequencedSubexpression SeqBefore(*this); 13369 Region = BeforeRegion; 13370 Visit(SequencedBefore); 13371 } 13372 13373 Region = AfterRegion; 13374 Visit(SequencedAfter); 13375 13376 Region = OldRegion; 13377 13378 Tree.merge(BeforeRegion); 13379 Tree.merge(AfterRegion); 13380 } 13381 13382 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13383 // C++17 [expr.sub]p1: 13384 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13385 // expression E1 is sequenced before the expression E2. 13386 if (SemaRef.getLangOpts().CPlusPlus17) 13387 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13388 else { 13389 Visit(ASE->getLHS()); 13390 Visit(ASE->getRHS()); 13391 } 13392 } 13393 13394 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13395 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13396 void VisitBinPtrMem(const BinaryOperator *BO) { 13397 // C++17 [expr.mptr.oper]p4: 13398 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13399 // the expression E1 is sequenced before the expression E2. 13400 if (SemaRef.getLangOpts().CPlusPlus17) 13401 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13402 else { 13403 Visit(BO->getLHS()); 13404 Visit(BO->getRHS()); 13405 } 13406 } 13407 13408 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13409 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13410 void VisitBinShlShr(const BinaryOperator *BO) { 13411 // C++17 [expr.shift]p4: 13412 // The expression E1 is sequenced before the expression E2. 13413 if (SemaRef.getLangOpts().CPlusPlus17) 13414 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13415 else { 13416 Visit(BO->getLHS()); 13417 Visit(BO->getRHS()); 13418 } 13419 } 13420 13421 void VisitBinComma(const BinaryOperator *BO) { 13422 // C++11 [expr.comma]p1: 13423 // Every value computation and side effect associated with the left 13424 // expression is sequenced before every value computation and side 13425 // effect associated with the right expression. 13426 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13427 } 13428 13429 void VisitBinAssign(const BinaryOperator *BO) { 13430 SequenceTree::Seq RHSRegion; 13431 SequenceTree::Seq LHSRegion; 13432 if (SemaRef.getLangOpts().CPlusPlus17) { 13433 RHSRegion = Tree.allocate(Region); 13434 LHSRegion = Tree.allocate(Region); 13435 } else { 13436 RHSRegion = Region; 13437 LHSRegion = Region; 13438 } 13439 SequenceTree::Seq OldRegion = Region; 13440 13441 // C++11 [expr.ass]p1: 13442 // [...] the assignment is sequenced after the value computation 13443 // of the right and left operands, [...] 13444 // 13445 // so check it before inspecting the operands and update the 13446 // map afterwards. 13447 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13448 if (O) 13449 notePreMod(O, BO); 13450 13451 if (SemaRef.getLangOpts().CPlusPlus17) { 13452 // C++17 [expr.ass]p1: 13453 // [...] The right operand is sequenced before the left operand. [...] 13454 { 13455 SequencedSubexpression SeqBefore(*this); 13456 Region = RHSRegion; 13457 Visit(BO->getRHS()); 13458 } 13459 13460 Region = LHSRegion; 13461 Visit(BO->getLHS()); 13462 13463 if (O && isa<CompoundAssignOperator>(BO)) 13464 notePostUse(O, BO); 13465 13466 } else { 13467 // C++11 does not specify any sequencing between the LHS and RHS. 13468 Region = LHSRegion; 13469 Visit(BO->getLHS()); 13470 13471 if (O && isa<CompoundAssignOperator>(BO)) 13472 notePostUse(O, BO); 13473 13474 Region = RHSRegion; 13475 Visit(BO->getRHS()); 13476 } 13477 13478 // C++11 [expr.ass]p1: 13479 // the assignment is sequenced [...] before the value computation of the 13480 // assignment expression. 13481 // C11 6.5.16/3 has no such rule. 13482 Region = OldRegion; 13483 if (O) 13484 notePostMod(O, BO, 13485 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13486 : UK_ModAsSideEffect); 13487 if (SemaRef.getLangOpts().CPlusPlus17) { 13488 Tree.merge(RHSRegion); 13489 Tree.merge(LHSRegion); 13490 } 13491 } 13492 13493 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13494 VisitBinAssign(CAO); 13495 } 13496 13497 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13498 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13499 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13500 Object O = getObject(UO->getSubExpr(), true); 13501 if (!O) 13502 return VisitExpr(UO); 13503 13504 notePreMod(O, UO); 13505 Visit(UO->getSubExpr()); 13506 // C++11 [expr.pre.incr]p1: 13507 // the expression ++x is equivalent to x+=1 13508 notePostMod(O, UO, 13509 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13510 : UK_ModAsSideEffect); 13511 } 13512 13513 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13514 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13515 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13516 Object O = getObject(UO->getSubExpr(), true); 13517 if (!O) 13518 return VisitExpr(UO); 13519 13520 notePreMod(O, UO); 13521 Visit(UO->getSubExpr()); 13522 notePostMod(O, UO, UK_ModAsSideEffect); 13523 } 13524 13525 void VisitBinLOr(const BinaryOperator *BO) { 13526 // C++11 [expr.log.or]p2: 13527 // If the second expression is evaluated, every value computation and 13528 // side effect associated with the first expression is sequenced before 13529 // every value computation and side effect associated with the 13530 // second expression. 13531 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13532 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13533 SequenceTree::Seq OldRegion = Region; 13534 13535 EvaluationTracker Eval(*this); 13536 { 13537 SequencedSubexpression Sequenced(*this); 13538 Region = LHSRegion; 13539 Visit(BO->getLHS()); 13540 } 13541 13542 // C++11 [expr.log.or]p1: 13543 // [...] the second operand is not evaluated if the first operand 13544 // evaluates to true. 13545 bool EvalResult = false; 13546 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13547 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13548 if (ShouldVisitRHS) { 13549 Region = RHSRegion; 13550 Visit(BO->getRHS()); 13551 } 13552 13553 Region = OldRegion; 13554 Tree.merge(LHSRegion); 13555 Tree.merge(RHSRegion); 13556 } 13557 13558 void VisitBinLAnd(const BinaryOperator *BO) { 13559 // C++11 [expr.log.and]p2: 13560 // If the second expression is evaluated, every value computation and 13561 // side effect associated with the first expression is sequenced before 13562 // every value computation and side effect associated with the 13563 // second expression. 13564 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13565 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13566 SequenceTree::Seq OldRegion = Region; 13567 13568 EvaluationTracker Eval(*this); 13569 { 13570 SequencedSubexpression Sequenced(*this); 13571 Region = LHSRegion; 13572 Visit(BO->getLHS()); 13573 } 13574 13575 // C++11 [expr.log.and]p1: 13576 // [...] the second operand is not evaluated if the first operand is false. 13577 bool EvalResult = false; 13578 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13579 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13580 if (ShouldVisitRHS) { 13581 Region = RHSRegion; 13582 Visit(BO->getRHS()); 13583 } 13584 13585 Region = OldRegion; 13586 Tree.merge(LHSRegion); 13587 Tree.merge(RHSRegion); 13588 } 13589 13590 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13591 // C++11 [expr.cond]p1: 13592 // [...] Every value computation and side effect associated with the first 13593 // expression is sequenced before every value computation and side effect 13594 // associated with the second or third expression. 13595 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13596 13597 // No sequencing is specified between the true and false expression. 13598 // However since exactly one of both is going to be evaluated we can 13599 // consider them to be sequenced. This is needed to avoid warning on 13600 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13601 // both the true and false expressions because we can't evaluate x. 13602 // This will still allow us to detect an expression like (pre C++17) 13603 // "(x ? y += 1 : y += 2) = y". 13604 // 13605 // We don't wrap the visitation of the true and false expression with 13606 // SequencedSubexpression because we don't want to downgrade modifications 13607 // as side effect in the true and false expressions after the visition 13608 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13609 // not warn between the two "y++", but we should warn between the "y++" 13610 // and the "y". 13611 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13612 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13613 SequenceTree::Seq OldRegion = Region; 13614 13615 EvaluationTracker Eval(*this); 13616 { 13617 SequencedSubexpression Sequenced(*this); 13618 Region = ConditionRegion; 13619 Visit(CO->getCond()); 13620 } 13621 13622 // C++11 [expr.cond]p1: 13623 // [...] The first expression is contextually converted to bool (Clause 4). 13624 // It is evaluated and if it is true, the result of the conditional 13625 // expression is the value of the second expression, otherwise that of the 13626 // third expression. Only one of the second and third expressions is 13627 // evaluated. [...] 13628 bool EvalResult = false; 13629 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13630 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13631 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13632 if (ShouldVisitTrueExpr) { 13633 Region = TrueRegion; 13634 Visit(CO->getTrueExpr()); 13635 } 13636 if (ShouldVisitFalseExpr) { 13637 Region = FalseRegion; 13638 Visit(CO->getFalseExpr()); 13639 } 13640 13641 Region = OldRegion; 13642 Tree.merge(ConditionRegion); 13643 Tree.merge(TrueRegion); 13644 Tree.merge(FalseRegion); 13645 } 13646 13647 void VisitCallExpr(const CallExpr *CE) { 13648 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13649 13650 if (CE->isUnevaluatedBuiltinCall(Context)) 13651 return; 13652 13653 // C++11 [intro.execution]p15: 13654 // When calling a function [...], every value computation and side effect 13655 // associated with any argument expression, or with the postfix expression 13656 // designating the called function, is sequenced before execution of every 13657 // expression or statement in the body of the function [and thus before 13658 // the value computation of its result]. 13659 SequencedSubexpression Sequenced(*this); 13660 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13661 // C++17 [expr.call]p5 13662 // The postfix-expression is sequenced before each expression in the 13663 // expression-list and any default argument. [...] 13664 SequenceTree::Seq CalleeRegion; 13665 SequenceTree::Seq OtherRegion; 13666 if (SemaRef.getLangOpts().CPlusPlus17) { 13667 CalleeRegion = Tree.allocate(Region); 13668 OtherRegion = Tree.allocate(Region); 13669 } else { 13670 CalleeRegion = Region; 13671 OtherRegion = Region; 13672 } 13673 SequenceTree::Seq OldRegion = Region; 13674 13675 // Visit the callee expression first. 13676 Region = CalleeRegion; 13677 if (SemaRef.getLangOpts().CPlusPlus17) { 13678 SequencedSubexpression Sequenced(*this); 13679 Visit(CE->getCallee()); 13680 } else { 13681 Visit(CE->getCallee()); 13682 } 13683 13684 // Then visit the argument expressions. 13685 Region = OtherRegion; 13686 for (const Expr *Argument : CE->arguments()) 13687 Visit(Argument); 13688 13689 Region = OldRegion; 13690 if (SemaRef.getLangOpts().CPlusPlus17) { 13691 Tree.merge(CalleeRegion); 13692 Tree.merge(OtherRegion); 13693 } 13694 }); 13695 } 13696 13697 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13698 // C++17 [over.match.oper]p2: 13699 // [...] the operator notation is first transformed to the equivalent 13700 // function-call notation as summarized in Table 12 (where @ denotes one 13701 // of the operators covered in the specified subclause). However, the 13702 // operands are sequenced in the order prescribed for the built-in 13703 // operator (Clause 8). 13704 // 13705 // From the above only overloaded binary operators and overloaded call 13706 // operators have sequencing rules in C++17 that we need to handle 13707 // separately. 13708 if (!SemaRef.getLangOpts().CPlusPlus17 || 13709 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13710 return VisitCallExpr(CXXOCE); 13711 13712 enum { 13713 NoSequencing, 13714 LHSBeforeRHS, 13715 RHSBeforeLHS, 13716 LHSBeforeRest 13717 } SequencingKind; 13718 switch (CXXOCE->getOperator()) { 13719 case OO_Equal: 13720 case OO_PlusEqual: 13721 case OO_MinusEqual: 13722 case OO_StarEqual: 13723 case OO_SlashEqual: 13724 case OO_PercentEqual: 13725 case OO_CaretEqual: 13726 case OO_AmpEqual: 13727 case OO_PipeEqual: 13728 case OO_LessLessEqual: 13729 case OO_GreaterGreaterEqual: 13730 SequencingKind = RHSBeforeLHS; 13731 break; 13732 13733 case OO_LessLess: 13734 case OO_GreaterGreater: 13735 case OO_AmpAmp: 13736 case OO_PipePipe: 13737 case OO_Comma: 13738 case OO_ArrowStar: 13739 case OO_Subscript: 13740 SequencingKind = LHSBeforeRHS; 13741 break; 13742 13743 case OO_Call: 13744 SequencingKind = LHSBeforeRest; 13745 break; 13746 13747 default: 13748 SequencingKind = NoSequencing; 13749 break; 13750 } 13751 13752 if (SequencingKind == NoSequencing) 13753 return VisitCallExpr(CXXOCE); 13754 13755 // This is a call, so all subexpressions are sequenced before the result. 13756 SequencedSubexpression Sequenced(*this); 13757 13758 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13759 assert(SemaRef.getLangOpts().CPlusPlus17 && 13760 "Should only get there with C++17 and above!"); 13761 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13762 "Should only get there with an overloaded binary operator" 13763 " or an overloaded call operator!"); 13764 13765 if (SequencingKind == LHSBeforeRest) { 13766 assert(CXXOCE->getOperator() == OO_Call && 13767 "We should only have an overloaded call operator here!"); 13768 13769 // This is very similar to VisitCallExpr, except that we only have the 13770 // C++17 case. The postfix-expression is the first argument of the 13771 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13772 // are in the following arguments. 13773 // 13774 // Note that we intentionally do not visit the callee expression since 13775 // it is just a decayed reference to a function. 13776 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13777 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13778 SequenceTree::Seq OldRegion = Region; 13779 13780 assert(CXXOCE->getNumArgs() >= 1 && 13781 "An overloaded call operator must have at least one argument" 13782 " for the postfix-expression!"); 13783 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13784 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13785 CXXOCE->getNumArgs() - 1); 13786 13787 // Visit the postfix-expression first. 13788 { 13789 Region = PostfixExprRegion; 13790 SequencedSubexpression Sequenced(*this); 13791 Visit(PostfixExpr); 13792 } 13793 13794 // Then visit the argument expressions. 13795 Region = ArgsRegion; 13796 for (const Expr *Arg : Args) 13797 Visit(Arg); 13798 13799 Region = OldRegion; 13800 Tree.merge(PostfixExprRegion); 13801 Tree.merge(ArgsRegion); 13802 } else { 13803 assert(CXXOCE->getNumArgs() == 2 && 13804 "Should only have two arguments here!"); 13805 assert((SequencingKind == LHSBeforeRHS || 13806 SequencingKind == RHSBeforeLHS) && 13807 "Unexpected sequencing kind!"); 13808 13809 // We do not visit the callee expression since it is just a decayed 13810 // reference to a function. 13811 const Expr *E1 = CXXOCE->getArg(0); 13812 const Expr *E2 = CXXOCE->getArg(1); 13813 if (SequencingKind == RHSBeforeLHS) 13814 std::swap(E1, E2); 13815 13816 return VisitSequencedExpressions(E1, E2); 13817 } 13818 }); 13819 } 13820 13821 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13822 // This is a call, so all subexpressions are sequenced before the result. 13823 SequencedSubexpression Sequenced(*this); 13824 13825 if (!CCE->isListInitialization()) 13826 return VisitExpr(CCE); 13827 13828 // In C++11, list initializations are sequenced. 13829 SmallVector<SequenceTree::Seq, 32> Elts; 13830 SequenceTree::Seq Parent = Region; 13831 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13832 E = CCE->arg_end(); 13833 I != E; ++I) { 13834 Region = Tree.allocate(Parent); 13835 Elts.push_back(Region); 13836 Visit(*I); 13837 } 13838 13839 // Forget that the initializers are sequenced. 13840 Region = Parent; 13841 for (unsigned I = 0; I < Elts.size(); ++I) 13842 Tree.merge(Elts[I]); 13843 } 13844 13845 void VisitInitListExpr(const InitListExpr *ILE) { 13846 if (!SemaRef.getLangOpts().CPlusPlus11) 13847 return VisitExpr(ILE); 13848 13849 // In C++11, list initializations are sequenced. 13850 SmallVector<SequenceTree::Seq, 32> Elts; 13851 SequenceTree::Seq Parent = Region; 13852 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13853 const Expr *E = ILE->getInit(I); 13854 if (!E) 13855 continue; 13856 Region = Tree.allocate(Parent); 13857 Elts.push_back(Region); 13858 Visit(E); 13859 } 13860 13861 // Forget that the initializers are sequenced. 13862 Region = Parent; 13863 for (unsigned I = 0; I < Elts.size(); ++I) 13864 Tree.merge(Elts[I]); 13865 } 13866 }; 13867 13868 } // namespace 13869 13870 void Sema::CheckUnsequencedOperations(const Expr *E) { 13871 SmallVector<const Expr *, 8> WorkList; 13872 WorkList.push_back(E); 13873 while (!WorkList.empty()) { 13874 const Expr *Item = WorkList.pop_back_val(); 13875 SequenceChecker(*this, Item, WorkList); 13876 } 13877 } 13878 13879 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13880 bool IsConstexpr) { 13881 llvm::SaveAndRestore<bool> ConstantContext( 13882 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13883 CheckImplicitConversions(E, CheckLoc); 13884 if (!E->isInstantiationDependent()) 13885 CheckUnsequencedOperations(E); 13886 if (!IsConstexpr && !E->isValueDependent()) 13887 CheckForIntOverflow(E); 13888 DiagnoseMisalignedMembers(); 13889 } 13890 13891 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13892 FieldDecl *BitField, 13893 Expr *Init) { 13894 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13895 } 13896 13897 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13898 SourceLocation Loc) { 13899 if (!PType->isVariablyModifiedType()) 13900 return; 13901 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13902 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13903 return; 13904 } 13905 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13906 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13907 return; 13908 } 13909 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13910 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13911 return; 13912 } 13913 13914 const ArrayType *AT = S.Context.getAsArrayType(PType); 13915 if (!AT) 13916 return; 13917 13918 if (AT->getSizeModifier() != ArrayType::Star) { 13919 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13920 return; 13921 } 13922 13923 S.Diag(Loc, diag::err_array_star_in_function_definition); 13924 } 13925 13926 /// CheckParmsForFunctionDef - Check that the parameters of the given 13927 /// function are appropriate for the definition of a function. This 13928 /// takes care of any checks that cannot be performed on the 13929 /// declaration itself, e.g., that the types of each of the function 13930 /// parameters are complete. 13931 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13932 bool CheckParameterNames) { 13933 bool HasInvalidParm = false; 13934 for (ParmVarDecl *Param : Parameters) { 13935 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13936 // function declarator that is part of a function definition of 13937 // that function shall not have incomplete type. 13938 // 13939 // This is also C++ [dcl.fct]p6. 13940 if (!Param->isInvalidDecl() && 13941 RequireCompleteType(Param->getLocation(), Param->getType(), 13942 diag::err_typecheck_decl_incomplete_type)) { 13943 Param->setInvalidDecl(); 13944 HasInvalidParm = true; 13945 } 13946 13947 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13948 // declaration of each parameter shall include an identifier. 13949 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13950 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13951 // Diagnose this as an extension in C17 and earlier. 13952 if (!getLangOpts().C2x) 13953 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13954 } 13955 13956 // C99 6.7.5.3p12: 13957 // If the function declarator is not part of a definition of that 13958 // function, parameters may have incomplete type and may use the [*] 13959 // notation in their sequences of declarator specifiers to specify 13960 // variable length array types. 13961 QualType PType = Param->getOriginalType(); 13962 // FIXME: This diagnostic should point the '[*]' if source-location 13963 // information is added for it. 13964 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13965 13966 // If the parameter is a c++ class type and it has to be destructed in the 13967 // callee function, declare the destructor so that it can be called by the 13968 // callee function. Do not perform any direct access check on the dtor here. 13969 if (!Param->isInvalidDecl()) { 13970 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13971 if (!ClassDecl->isInvalidDecl() && 13972 !ClassDecl->hasIrrelevantDestructor() && 13973 !ClassDecl->isDependentContext() && 13974 ClassDecl->isParamDestroyedInCallee()) { 13975 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13976 MarkFunctionReferenced(Param->getLocation(), Destructor); 13977 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13978 } 13979 } 13980 } 13981 13982 // Parameters with the pass_object_size attribute only need to be marked 13983 // constant at function definitions. Because we lack information about 13984 // whether we're on a declaration or definition when we're instantiating the 13985 // attribute, we need to check for constness here. 13986 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13987 if (!Param->getType().isConstQualified()) 13988 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13989 << Attr->getSpelling() << 1; 13990 13991 // Check for parameter names shadowing fields from the class. 13992 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13993 // The owning context for the parameter should be the function, but we 13994 // want to see if this function's declaration context is a record. 13995 DeclContext *DC = Param->getDeclContext(); 13996 if (DC && DC->isFunctionOrMethod()) { 13997 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13998 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13999 RD, /*DeclIsField*/ false); 14000 } 14001 } 14002 } 14003 14004 return HasInvalidParm; 14005 } 14006 14007 Optional<std::pair<CharUnits, CharUnits>> 14008 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14009 14010 /// Compute the alignment and offset of the base class object given the 14011 /// derived-to-base cast expression and the alignment and offset of the derived 14012 /// class object. 14013 static std::pair<CharUnits, CharUnits> 14014 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14015 CharUnits BaseAlignment, CharUnits Offset, 14016 ASTContext &Ctx) { 14017 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14018 ++PathI) { 14019 const CXXBaseSpecifier *Base = *PathI; 14020 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14021 if (Base->isVirtual()) { 14022 // The complete object may have a lower alignment than the non-virtual 14023 // alignment of the base, in which case the base may be misaligned. Choose 14024 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14025 // conservative lower bound of the complete object alignment. 14026 CharUnits NonVirtualAlignment = 14027 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14028 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14029 Offset = CharUnits::Zero(); 14030 } else { 14031 const ASTRecordLayout &RL = 14032 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14033 Offset += RL.getBaseClassOffset(BaseDecl); 14034 } 14035 DerivedType = Base->getType(); 14036 } 14037 14038 return std::make_pair(BaseAlignment, Offset); 14039 } 14040 14041 /// Compute the alignment and offset of a binary additive operator. 14042 static Optional<std::pair<CharUnits, CharUnits>> 14043 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14044 bool IsSub, ASTContext &Ctx) { 14045 QualType PointeeType = PtrE->getType()->getPointeeType(); 14046 14047 if (!PointeeType->isConstantSizeType()) 14048 return llvm::None; 14049 14050 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14051 14052 if (!P) 14053 return llvm::None; 14054 14055 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14056 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14057 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14058 if (IsSub) 14059 Offset = -Offset; 14060 return std::make_pair(P->first, P->second + Offset); 14061 } 14062 14063 // If the integer expression isn't a constant expression, compute the lower 14064 // bound of the alignment using the alignment and offset of the pointer 14065 // expression and the element size. 14066 return std::make_pair( 14067 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14068 CharUnits::Zero()); 14069 } 14070 14071 /// This helper function takes an lvalue expression and returns the alignment of 14072 /// a VarDecl and a constant offset from the VarDecl. 14073 Optional<std::pair<CharUnits, CharUnits>> 14074 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14075 E = E->IgnoreParens(); 14076 switch (E->getStmtClass()) { 14077 default: 14078 break; 14079 case Stmt::CStyleCastExprClass: 14080 case Stmt::CXXStaticCastExprClass: 14081 case Stmt::ImplicitCastExprClass: { 14082 auto *CE = cast<CastExpr>(E); 14083 const Expr *From = CE->getSubExpr(); 14084 switch (CE->getCastKind()) { 14085 default: 14086 break; 14087 case CK_NoOp: 14088 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14089 case CK_UncheckedDerivedToBase: 14090 case CK_DerivedToBase: { 14091 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14092 if (!P) 14093 break; 14094 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14095 P->second, Ctx); 14096 } 14097 } 14098 break; 14099 } 14100 case Stmt::ArraySubscriptExprClass: { 14101 auto *ASE = cast<ArraySubscriptExpr>(E); 14102 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14103 false, Ctx); 14104 } 14105 case Stmt::DeclRefExprClass: { 14106 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14107 // FIXME: If VD is captured by copy or is an escaping __block variable, 14108 // use the alignment of VD's type. 14109 if (!VD->getType()->isReferenceType()) 14110 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14111 if (VD->hasInit()) 14112 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14113 } 14114 break; 14115 } 14116 case Stmt::MemberExprClass: { 14117 auto *ME = cast<MemberExpr>(E); 14118 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14119 if (!FD || FD->getType()->isReferenceType()) 14120 break; 14121 Optional<std::pair<CharUnits, CharUnits>> P; 14122 if (ME->isArrow()) 14123 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14124 else 14125 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14126 if (!P) 14127 break; 14128 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14129 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14130 return std::make_pair(P->first, 14131 P->second + CharUnits::fromQuantity(Offset)); 14132 } 14133 case Stmt::UnaryOperatorClass: { 14134 auto *UO = cast<UnaryOperator>(E); 14135 switch (UO->getOpcode()) { 14136 default: 14137 break; 14138 case UO_Deref: 14139 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14140 } 14141 break; 14142 } 14143 case Stmt::BinaryOperatorClass: { 14144 auto *BO = cast<BinaryOperator>(E); 14145 auto Opcode = BO->getOpcode(); 14146 switch (Opcode) { 14147 default: 14148 break; 14149 case BO_Comma: 14150 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14151 } 14152 break; 14153 } 14154 } 14155 return llvm::None; 14156 } 14157 14158 /// This helper function takes a pointer expression and returns the alignment of 14159 /// a VarDecl and a constant offset from the VarDecl. 14160 Optional<std::pair<CharUnits, CharUnits>> 14161 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14162 E = E->IgnoreParens(); 14163 switch (E->getStmtClass()) { 14164 default: 14165 break; 14166 case Stmt::CStyleCastExprClass: 14167 case Stmt::CXXStaticCastExprClass: 14168 case Stmt::ImplicitCastExprClass: { 14169 auto *CE = cast<CastExpr>(E); 14170 const Expr *From = CE->getSubExpr(); 14171 switch (CE->getCastKind()) { 14172 default: 14173 break; 14174 case CK_NoOp: 14175 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14176 case CK_ArrayToPointerDecay: 14177 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14178 case CK_UncheckedDerivedToBase: 14179 case CK_DerivedToBase: { 14180 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14181 if (!P) 14182 break; 14183 return getDerivedToBaseAlignmentAndOffset( 14184 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14185 } 14186 } 14187 break; 14188 } 14189 case Stmt::CXXThisExprClass: { 14190 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14191 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14192 return std::make_pair(Alignment, CharUnits::Zero()); 14193 } 14194 case Stmt::UnaryOperatorClass: { 14195 auto *UO = cast<UnaryOperator>(E); 14196 if (UO->getOpcode() == UO_AddrOf) 14197 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14198 break; 14199 } 14200 case Stmt::BinaryOperatorClass: { 14201 auto *BO = cast<BinaryOperator>(E); 14202 auto Opcode = BO->getOpcode(); 14203 switch (Opcode) { 14204 default: 14205 break; 14206 case BO_Add: 14207 case BO_Sub: { 14208 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14209 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14210 std::swap(LHS, RHS); 14211 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14212 Ctx); 14213 } 14214 case BO_Comma: 14215 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14216 } 14217 break; 14218 } 14219 } 14220 return llvm::None; 14221 } 14222 14223 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14224 // See if we can compute the alignment of a VarDecl and an offset from it. 14225 Optional<std::pair<CharUnits, CharUnits>> P = 14226 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14227 14228 if (P) 14229 return P->first.alignmentAtOffset(P->second); 14230 14231 // If that failed, return the type's alignment. 14232 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14233 } 14234 14235 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14236 /// pointer cast increases the alignment requirements. 14237 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14238 // This is actually a lot of work to potentially be doing on every 14239 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14240 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14241 return; 14242 14243 // Ignore dependent types. 14244 if (T->isDependentType() || Op->getType()->isDependentType()) 14245 return; 14246 14247 // Require that the destination be a pointer type. 14248 const PointerType *DestPtr = T->getAs<PointerType>(); 14249 if (!DestPtr) return; 14250 14251 // If the destination has alignment 1, we're done. 14252 QualType DestPointee = DestPtr->getPointeeType(); 14253 if (DestPointee->isIncompleteType()) return; 14254 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14255 if (DestAlign.isOne()) return; 14256 14257 // Require that the source be a pointer type. 14258 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14259 if (!SrcPtr) return; 14260 QualType SrcPointee = SrcPtr->getPointeeType(); 14261 14262 // Explicitly allow casts from cv void*. We already implicitly 14263 // allowed casts to cv void*, since they have alignment 1. 14264 // Also allow casts involving incomplete types, which implicitly 14265 // includes 'void'. 14266 if (SrcPointee->isIncompleteType()) return; 14267 14268 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14269 14270 if (SrcAlign >= DestAlign) return; 14271 14272 Diag(TRange.getBegin(), diag::warn_cast_align) 14273 << Op->getType() << T 14274 << static_cast<unsigned>(SrcAlign.getQuantity()) 14275 << static_cast<unsigned>(DestAlign.getQuantity()) 14276 << TRange << Op->getSourceRange(); 14277 } 14278 14279 /// Check whether this array fits the idiom of a size-one tail padded 14280 /// array member of a struct. 14281 /// 14282 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14283 /// commonly used to emulate flexible arrays in C89 code. 14284 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14285 const NamedDecl *ND) { 14286 if (Size != 1 || !ND) return false; 14287 14288 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14289 if (!FD) return false; 14290 14291 // Don't consider sizes resulting from macro expansions or template argument 14292 // substitution to form C89 tail-padded arrays. 14293 14294 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14295 while (TInfo) { 14296 TypeLoc TL = TInfo->getTypeLoc(); 14297 // Look through typedefs. 14298 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14299 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14300 TInfo = TDL->getTypeSourceInfo(); 14301 continue; 14302 } 14303 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14304 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14305 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14306 return false; 14307 } 14308 break; 14309 } 14310 14311 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14312 if (!RD) return false; 14313 if (RD->isUnion()) return false; 14314 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14315 if (!CRD->isStandardLayout()) return false; 14316 } 14317 14318 // See if this is the last field decl in the record. 14319 const Decl *D = FD; 14320 while ((D = D->getNextDeclInContext())) 14321 if (isa<FieldDecl>(D)) 14322 return false; 14323 return true; 14324 } 14325 14326 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14327 const ArraySubscriptExpr *ASE, 14328 bool AllowOnePastEnd, bool IndexNegated) { 14329 // Already diagnosed by the constant evaluator. 14330 if (isConstantEvaluated()) 14331 return; 14332 14333 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14334 if (IndexExpr->isValueDependent()) 14335 return; 14336 14337 const Type *EffectiveType = 14338 BaseExpr->getType()->getPointeeOrArrayElementType(); 14339 BaseExpr = BaseExpr->IgnoreParenCasts(); 14340 const ConstantArrayType *ArrayTy = 14341 Context.getAsConstantArrayType(BaseExpr->getType()); 14342 14343 if (!ArrayTy) 14344 return; 14345 14346 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 14347 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 14348 return; 14349 14350 Expr::EvalResult Result; 14351 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14352 return; 14353 14354 llvm::APSInt index = Result.Val.getInt(); 14355 if (IndexNegated) 14356 index = -index; 14357 14358 const NamedDecl *ND = nullptr; 14359 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14360 ND = DRE->getDecl(); 14361 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14362 ND = ME->getMemberDecl(); 14363 14364 if (index.isUnsigned() || !index.isNegative()) { 14365 // It is possible that the type of the base expression after 14366 // IgnoreParenCasts is incomplete, even though the type of the base 14367 // expression before IgnoreParenCasts is complete (see PR39746 for an 14368 // example). In this case we have no information about whether the array 14369 // access exceeds the array bounds. However we can still diagnose an array 14370 // access which precedes the array bounds. 14371 if (BaseType->isIncompleteType()) 14372 return; 14373 14374 llvm::APInt size = ArrayTy->getSize(); 14375 if (!size.isStrictlyPositive()) 14376 return; 14377 14378 if (BaseType != EffectiveType) { 14379 // Make sure we're comparing apples to apples when comparing index to size 14380 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14381 uint64_t array_typesize = Context.getTypeSize(BaseType); 14382 // Handle ptrarith_typesize being zero, such as when casting to void* 14383 if (!ptrarith_typesize) ptrarith_typesize = 1; 14384 if (ptrarith_typesize != array_typesize) { 14385 // There's a cast to a different size type involved 14386 uint64_t ratio = array_typesize / ptrarith_typesize; 14387 // TODO: Be smarter about handling cases where array_typesize is not a 14388 // multiple of ptrarith_typesize 14389 if (ptrarith_typesize * ratio == array_typesize) 14390 size *= llvm::APInt(size.getBitWidth(), ratio); 14391 } 14392 } 14393 14394 if (size.getBitWidth() > index.getBitWidth()) 14395 index = index.zext(size.getBitWidth()); 14396 else if (size.getBitWidth() < index.getBitWidth()) 14397 size = size.zext(index.getBitWidth()); 14398 14399 // For array subscripting the index must be less than size, but for pointer 14400 // arithmetic also allow the index (offset) to be equal to size since 14401 // computing the next address after the end of the array is legal and 14402 // commonly done e.g. in C++ iterators and range-based for loops. 14403 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14404 return; 14405 14406 // Also don't warn for arrays of size 1 which are members of some 14407 // structure. These are often used to approximate flexible arrays in C89 14408 // code. 14409 if (IsTailPaddedMemberArray(*this, size, ND)) 14410 return; 14411 14412 // Suppress the warning if the subscript expression (as identified by the 14413 // ']' location) and the index expression are both from macro expansions 14414 // within a system header. 14415 if (ASE) { 14416 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14417 ASE->getRBracketLoc()); 14418 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14419 SourceLocation IndexLoc = 14420 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14421 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14422 return; 14423 } 14424 } 14425 14426 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 14427 if (ASE) 14428 DiagID = diag::warn_array_index_exceeds_bounds; 14429 14430 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14431 PDiag(DiagID) << index.toString(10, true) 14432 << size.toString(10, true) 14433 << (unsigned)size.getLimitedValue(~0U) 14434 << IndexExpr->getSourceRange()); 14435 } else { 14436 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14437 if (!ASE) { 14438 DiagID = diag::warn_ptr_arith_precedes_bounds; 14439 if (index.isNegative()) index = -index; 14440 } 14441 14442 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14443 PDiag(DiagID) << index.toString(10, true) 14444 << IndexExpr->getSourceRange()); 14445 } 14446 14447 if (!ND) { 14448 // Try harder to find a NamedDecl to point at in the note. 14449 while (const ArraySubscriptExpr *ASE = 14450 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14451 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14452 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14453 ND = DRE->getDecl(); 14454 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14455 ND = ME->getMemberDecl(); 14456 } 14457 14458 if (ND) 14459 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14460 PDiag(diag::note_array_declared_here) << ND); 14461 } 14462 14463 void Sema::CheckArrayAccess(const Expr *expr) { 14464 int AllowOnePastEnd = 0; 14465 while (expr) { 14466 expr = expr->IgnoreParenImpCasts(); 14467 switch (expr->getStmtClass()) { 14468 case Stmt::ArraySubscriptExprClass: { 14469 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14470 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14471 AllowOnePastEnd > 0); 14472 expr = ASE->getBase(); 14473 break; 14474 } 14475 case Stmt::MemberExprClass: { 14476 expr = cast<MemberExpr>(expr)->getBase(); 14477 break; 14478 } 14479 case Stmt::OMPArraySectionExprClass: { 14480 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14481 if (ASE->getLowerBound()) 14482 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14483 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14484 return; 14485 } 14486 case Stmt::UnaryOperatorClass: { 14487 // Only unwrap the * and & unary operators 14488 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14489 expr = UO->getSubExpr(); 14490 switch (UO->getOpcode()) { 14491 case UO_AddrOf: 14492 AllowOnePastEnd++; 14493 break; 14494 case UO_Deref: 14495 AllowOnePastEnd--; 14496 break; 14497 default: 14498 return; 14499 } 14500 break; 14501 } 14502 case Stmt::ConditionalOperatorClass: { 14503 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14504 if (const Expr *lhs = cond->getLHS()) 14505 CheckArrayAccess(lhs); 14506 if (const Expr *rhs = cond->getRHS()) 14507 CheckArrayAccess(rhs); 14508 return; 14509 } 14510 case Stmt::CXXOperatorCallExprClass: { 14511 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14512 for (const auto *Arg : OCE->arguments()) 14513 CheckArrayAccess(Arg); 14514 return; 14515 } 14516 default: 14517 return; 14518 } 14519 } 14520 } 14521 14522 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14523 14524 namespace { 14525 14526 struct RetainCycleOwner { 14527 VarDecl *Variable = nullptr; 14528 SourceRange Range; 14529 SourceLocation Loc; 14530 bool Indirect = false; 14531 14532 RetainCycleOwner() = default; 14533 14534 void setLocsFrom(Expr *e) { 14535 Loc = e->getExprLoc(); 14536 Range = e->getSourceRange(); 14537 } 14538 }; 14539 14540 } // namespace 14541 14542 /// Consider whether capturing the given variable can possibly lead to 14543 /// a retain cycle. 14544 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14545 // In ARC, it's captured strongly iff the variable has __strong 14546 // lifetime. In MRR, it's captured strongly if the variable is 14547 // __block and has an appropriate type. 14548 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14549 return false; 14550 14551 owner.Variable = var; 14552 if (ref) 14553 owner.setLocsFrom(ref); 14554 return true; 14555 } 14556 14557 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14558 while (true) { 14559 e = e->IgnoreParens(); 14560 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14561 switch (cast->getCastKind()) { 14562 case CK_BitCast: 14563 case CK_LValueBitCast: 14564 case CK_LValueToRValue: 14565 case CK_ARCReclaimReturnedObject: 14566 e = cast->getSubExpr(); 14567 continue; 14568 14569 default: 14570 return false; 14571 } 14572 } 14573 14574 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14575 ObjCIvarDecl *ivar = ref->getDecl(); 14576 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14577 return false; 14578 14579 // Try to find a retain cycle in the base. 14580 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14581 return false; 14582 14583 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14584 owner.Indirect = true; 14585 return true; 14586 } 14587 14588 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14589 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14590 if (!var) return false; 14591 return considerVariable(var, ref, owner); 14592 } 14593 14594 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14595 if (member->isArrow()) return false; 14596 14597 // Don't count this as an indirect ownership. 14598 e = member->getBase(); 14599 continue; 14600 } 14601 14602 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14603 // Only pay attention to pseudo-objects on property references. 14604 ObjCPropertyRefExpr *pre 14605 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14606 ->IgnoreParens()); 14607 if (!pre) return false; 14608 if (pre->isImplicitProperty()) return false; 14609 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14610 if (!property->isRetaining() && 14611 !(property->getPropertyIvarDecl() && 14612 property->getPropertyIvarDecl()->getType() 14613 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14614 return false; 14615 14616 owner.Indirect = true; 14617 if (pre->isSuperReceiver()) { 14618 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14619 if (!owner.Variable) 14620 return false; 14621 owner.Loc = pre->getLocation(); 14622 owner.Range = pre->getSourceRange(); 14623 return true; 14624 } 14625 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14626 ->getSourceExpr()); 14627 continue; 14628 } 14629 14630 // Array ivars? 14631 14632 return false; 14633 } 14634 } 14635 14636 namespace { 14637 14638 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14639 ASTContext &Context; 14640 VarDecl *Variable; 14641 Expr *Capturer = nullptr; 14642 bool VarWillBeReased = false; 14643 14644 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14645 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14646 Context(Context), Variable(variable) {} 14647 14648 void VisitDeclRefExpr(DeclRefExpr *ref) { 14649 if (ref->getDecl() == Variable && !Capturer) 14650 Capturer = ref; 14651 } 14652 14653 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14654 if (Capturer) return; 14655 Visit(ref->getBase()); 14656 if (Capturer && ref->isFreeIvar()) 14657 Capturer = ref; 14658 } 14659 14660 void VisitBlockExpr(BlockExpr *block) { 14661 // Look inside nested blocks 14662 if (block->getBlockDecl()->capturesVariable(Variable)) 14663 Visit(block->getBlockDecl()->getBody()); 14664 } 14665 14666 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14667 if (Capturer) return; 14668 if (OVE->getSourceExpr()) 14669 Visit(OVE->getSourceExpr()); 14670 } 14671 14672 void VisitBinaryOperator(BinaryOperator *BinOp) { 14673 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14674 return; 14675 Expr *LHS = BinOp->getLHS(); 14676 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14677 if (DRE->getDecl() != Variable) 14678 return; 14679 if (Expr *RHS = BinOp->getRHS()) { 14680 RHS = RHS->IgnoreParenCasts(); 14681 Optional<llvm::APSInt> Value; 14682 VarWillBeReased = 14683 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14684 *Value == 0); 14685 } 14686 } 14687 } 14688 }; 14689 14690 } // namespace 14691 14692 /// Check whether the given argument is a block which captures a 14693 /// variable. 14694 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14695 assert(owner.Variable && owner.Loc.isValid()); 14696 14697 e = e->IgnoreParenCasts(); 14698 14699 // Look through [^{...} copy] and Block_copy(^{...}). 14700 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14701 Selector Cmd = ME->getSelector(); 14702 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14703 e = ME->getInstanceReceiver(); 14704 if (!e) 14705 return nullptr; 14706 e = e->IgnoreParenCasts(); 14707 } 14708 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14709 if (CE->getNumArgs() == 1) { 14710 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14711 if (Fn) { 14712 const IdentifierInfo *FnI = Fn->getIdentifier(); 14713 if (FnI && FnI->isStr("_Block_copy")) { 14714 e = CE->getArg(0)->IgnoreParenCasts(); 14715 } 14716 } 14717 } 14718 } 14719 14720 BlockExpr *block = dyn_cast<BlockExpr>(e); 14721 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14722 return nullptr; 14723 14724 FindCaptureVisitor visitor(S.Context, owner.Variable); 14725 visitor.Visit(block->getBlockDecl()->getBody()); 14726 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14727 } 14728 14729 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14730 RetainCycleOwner &owner) { 14731 assert(capturer); 14732 assert(owner.Variable && owner.Loc.isValid()); 14733 14734 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14735 << owner.Variable << capturer->getSourceRange(); 14736 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14737 << owner.Indirect << owner.Range; 14738 } 14739 14740 /// Check for a keyword selector that starts with the word 'add' or 14741 /// 'set'. 14742 static bool isSetterLikeSelector(Selector sel) { 14743 if (sel.isUnarySelector()) return false; 14744 14745 StringRef str = sel.getNameForSlot(0); 14746 while (!str.empty() && str.front() == '_') str = str.substr(1); 14747 if (str.startswith("set")) 14748 str = str.substr(3); 14749 else if (str.startswith("add")) { 14750 // Specially allow 'addOperationWithBlock:'. 14751 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14752 return false; 14753 str = str.substr(3); 14754 } 14755 else 14756 return false; 14757 14758 if (str.empty()) return true; 14759 return !isLowercase(str.front()); 14760 } 14761 14762 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14763 ObjCMessageExpr *Message) { 14764 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14765 Message->getReceiverInterface(), 14766 NSAPI::ClassId_NSMutableArray); 14767 if (!IsMutableArray) { 14768 return None; 14769 } 14770 14771 Selector Sel = Message->getSelector(); 14772 14773 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14774 S.NSAPIObj->getNSArrayMethodKind(Sel); 14775 if (!MKOpt) { 14776 return None; 14777 } 14778 14779 NSAPI::NSArrayMethodKind MK = *MKOpt; 14780 14781 switch (MK) { 14782 case NSAPI::NSMutableArr_addObject: 14783 case NSAPI::NSMutableArr_insertObjectAtIndex: 14784 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14785 return 0; 14786 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14787 return 1; 14788 14789 default: 14790 return None; 14791 } 14792 14793 return None; 14794 } 14795 14796 static 14797 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14798 ObjCMessageExpr *Message) { 14799 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14800 Message->getReceiverInterface(), 14801 NSAPI::ClassId_NSMutableDictionary); 14802 if (!IsMutableDictionary) { 14803 return None; 14804 } 14805 14806 Selector Sel = Message->getSelector(); 14807 14808 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14809 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14810 if (!MKOpt) { 14811 return None; 14812 } 14813 14814 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14815 14816 switch (MK) { 14817 case NSAPI::NSMutableDict_setObjectForKey: 14818 case NSAPI::NSMutableDict_setValueForKey: 14819 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14820 return 0; 14821 14822 default: 14823 return None; 14824 } 14825 14826 return None; 14827 } 14828 14829 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14830 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14831 Message->getReceiverInterface(), 14832 NSAPI::ClassId_NSMutableSet); 14833 14834 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14835 Message->getReceiverInterface(), 14836 NSAPI::ClassId_NSMutableOrderedSet); 14837 if (!IsMutableSet && !IsMutableOrderedSet) { 14838 return None; 14839 } 14840 14841 Selector Sel = Message->getSelector(); 14842 14843 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14844 if (!MKOpt) { 14845 return None; 14846 } 14847 14848 NSAPI::NSSetMethodKind MK = *MKOpt; 14849 14850 switch (MK) { 14851 case NSAPI::NSMutableSet_addObject: 14852 case NSAPI::NSOrderedSet_setObjectAtIndex: 14853 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14854 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14855 return 0; 14856 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14857 return 1; 14858 } 14859 14860 return None; 14861 } 14862 14863 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14864 if (!Message->isInstanceMessage()) { 14865 return; 14866 } 14867 14868 Optional<int> ArgOpt; 14869 14870 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14871 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14872 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14873 return; 14874 } 14875 14876 int ArgIndex = *ArgOpt; 14877 14878 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14879 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14880 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14881 } 14882 14883 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14884 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14885 if (ArgRE->isObjCSelfExpr()) { 14886 Diag(Message->getSourceRange().getBegin(), 14887 diag::warn_objc_circular_container) 14888 << ArgRE->getDecl() << StringRef("'super'"); 14889 } 14890 } 14891 } else { 14892 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14893 14894 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14895 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14896 } 14897 14898 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14899 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14900 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14901 ValueDecl *Decl = ReceiverRE->getDecl(); 14902 Diag(Message->getSourceRange().getBegin(), 14903 diag::warn_objc_circular_container) 14904 << Decl << Decl; 14905 if (!ArgRE->isObjCSelfExpr()) { 14906 Diag(Decl->getLocation(), 14907 diag::note_objc_circular_container_declared_here) 14908 << Decl; 14909 } 14910 } 14911 } 14912 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14913 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14914 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14915 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14916 Diag(Message->getSourceRange().getBegin(), 14917 diag::warn_objc_circular_container) 14918 << Decl << Decl; 14919 Diag(Decl->getLocation(), 14920 diag::note_objc_circular_container_declared_here) 14921 << Decl; 14922 } 14923 } 14924 } 14925 } 14926 } 14927 14928 /// Check a message send to see if it's likely to cause a retain cycle. 14929 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14930 // Only check instance methods whose selector looks like a setter. 14931 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14932 return; 14933 14934 // Try to find a variable that the receiver is strongly owned by. 14935 RetainCycleOwner owner; 14936 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14937 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14938 return; 14939 } else { 14940 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14941 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14942 owner.Loc = msg->getSuperLoc(); 14943 owner.Range = msg->getSuperLoc(); 14944 } 14945 14946 // Check whether the receiver is captured by any of the arguments. 14947 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14948 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14949 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14950 // noescape blocks should not be retained by the method. 14951 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14952 continue; 14953 return diagnoseRetainCycle(*this, capturer, owner); 14954 } 14955 } 14956 } 14957 14958 /// Check a property assign to see if it's likely to cause a retain cycle. 14959 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14960 RetainCycleOwner owner; 14961 if (!findRetainCycleOwner(*this, receiver, owner)) 14962 return; 14963 14964 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14965 diagnoseRetainCycle(*this, capturer, owner); 14966 } 14967 14968 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14969 RetainCycleOwner Owner; 14970 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14971 return; 14972 14973 // Because we don't have an expression for the variable, we have to set the 14974 // location explicitly here. 14975 Owner.Loc = Var->getLocation(); 14976 Owner.Range = Var->getSourceRange(); 14977 14978 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14979 diagnoseRetainCycle(*this, Capturer, Owner); 14980 } 14981 14982 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14983 Expr *RHS, bool isProperty) { 14984 // Check if RHS is an Objective-C object literal, which also can get 14985 // immediately zapped in a weak reference. Note that we explicitly 14986 // allow ObjCStringLiterals, since those are designed to never really die. 14987 RHS = RHS->IgnoreParenImpCasts(); 14988 14989 // This enum needs to match with the 'select' in 14990 // warn_objc_arc_literal_assign (off-by-1). 14991 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14992 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14993 return false; 14994 14995 S.Diag(Loc, diag::warn_arc_literal_assign) 14996 << (unsigned) Kind 14997 << (isProperty ? 0 : 1) 14998 << RHS->getSourceRange(); 14999 15000 return true; 15001 } 15002 15003 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15004 Qualifiers::ObjCLifetime LT, 15005 Expr *RHS, bool isProperty) { 15006 // Strip off any implicit cast added to get to the one ARC-specific. 15007 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15008 if (cast->getCastKind() == CK_ARCConsumeObject) { 15009 S.Diag(Loc, diag::warn_arc_retained_assign) 15010 << (LT == Qualifiers::OCL_ExplicitNone) 15011 << (isProperty ? 0 : 1) 15012 << RHS->getSourceRange(); 15013 return true; 15014 } 15015 RHS = cast->getSubExpr(); 15016 } 15017 15018 if (LT == Qualifiers::OCL_Weak && 15019 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15020 return true; 15021 15022 return false; 15023 } 15024 15025 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15026 QualType LHS, Expr *RHS) { 15027 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15028 15029 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15030 return false; 15031 15032 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15033 return true; 15034 15035 return false; 15036 } 15037 15038 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15039 Expr *LHS, Expr *RHS) { 15040 QualType LHSType; 15041 // PropertyRef on LHS type need be directly obtained from 15042 // its declaration as it has a PseudoType. 15043 ObjCPropertyRefExpr *PRE 15044 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15045 if (PRE && !PRE->isImplicitProperty()) { 15046 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15047 if (PD) 15048 LHSType = PD->getType(); 15049 } 15050 15051 if (LHSType.isNull()) 15052 LHSType = LHS->getType(); 15053 15054 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15055 15056 if (LT == Qualifiers::OCL_Weak) { 15057 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15058 getCurFunction()->markSafeWeakUse(LHS); 15059 } 15060 15061 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15062 return; 15063 15064 // FIXME. Check for other life times. 15065 if (LT != Qualifiers::OCL_None) 15066 return; 15067 15068 if (PRE) { 15069 if (PRE->isImplicitProperty()) 15070 return; 15071 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15072 if (!PD) 15073 return; 15074 15075 unsigned Attributes = PD->getPropertyAttributes(); 15076 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15077 // when 'assign' attribute was not explicitly specified 15078 // by user, ignore it and rely on property type itself 15079 // for lifetime info. 15080 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15081 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15082 LHSType->isObjCRetainableType()) 15083 return; 15084 15085 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15086 if (cast->getCastKind() == CK_ARCConsumeObject) { 15087 Diag(Loc, diag::warn_arc_retained_property_assign) 15088 << RHS->getSourceRange(); 15089 return; 15090 } 15091 RHS = cast->getSubExpr(); 15092 } 15093 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15094 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15095 return; 15096 } 15097 } 15098 } 15099 15100 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15101 15102 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15103 SourceLocation StmtLoc, 15104 const NullStmt *Body) { 15105 // Do not warn if the body is a macro that expands to nothing, e.g: 15106 // 15107 // #define CALL(x) 15108 // if (condition) 15109 // CALL(0); 15110 if (Body->hasLeadingEmptyMacro()) 15111 return false; 15112 15113 // Get line numbers of statement and body. 15114 bool StmtLineInvalid; 15115 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15116 &StmtLineInvalid); 15117 if (StmtLineInvalid) 15118 return false; 15119 15120 bool BodyLineInvalid; 15121 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15122 &BodyLineInvalid); 15123 if (BodyLineInvalid) 15124 return false; 15125 15126 // Warn if null statement and body are on the same line. 15127 if (StmtLine != BodyLine) 15128 return false; 15129 15130 return true; 15131 } 15132 15133 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15134 const Stmt *Body, 15135 unsigned DiagID) { 15136 // Since this is a syntactic check, don't emit diagnostic for template 15137 // instantiations, this just adds noise. 15138 if (CurrentInstantiationScope) 15139 return; 15140 15141 // The body should be a null statement. 15142 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15143 if (!NBody) 15144 return; 15145 15146 // Do the usual checks. 15147 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15148 return; 15149 15150 Diag(NBody->getSemiLoc(), DiagID); 15151 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15152 } 15153 15154 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15155 const Stmt *PossibleBody) { 15156 assert(!CurrentInstantiationScope); // Ensured by caller 15157 15158 SourceLocation StmtLoc; 15159 const Stmt *Body; 15160 unsigned DiagID; 15161 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15162 StmtLoc = FS->getRParenLoc(); 15163 Body = FS->getBody(); 15164 DiagID = diag::warn_empty_for_body; 15165 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15166 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15167 Body = WS->getBody(); 15168 DiagID = diag::warn_empty_while_body; 15169 } else 15170 return; // Neither `for' nor `while'. 15171 15172 // The body should be a null statement. 15173 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15174 if (!NBody) 15175 return; 15176 15177 // Skip expensive checks if diagnostic is disabled. 15178 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15179 return; 15180 15181 // Do the usual checks. 15182 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15183 return; 15184 15185 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15186 // noise level low, emit diagnostics only if for/while is followed by a 15187 // CompoundStmt, e.g.: 15188 // for (int i = 0; i < n; i++); 15189 // { 15190 // a(i); 15191 // } 15192 // or if for/while is followed by a statement with more indentation 15193 // than for/while itself: 15194 // for (int i = 0; i < n; i++); 15195 // a(i); 15196 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15197 if (!ProbableTypo) { 15198 bool BodyColInvalid; 15199 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15200 PossibleBody->getBeginLoc(), &BodyColInvalid); 15201 if (BodyColInvalid) 15202 return; 15203 15204 bool StmtColInvalid; 15205 unsigned StmtCol = 15206 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15207 if (StmtColInvalid) 15208 return; 15209 15210 if (BodyCol > StmtCol) 15211 ProbableTypo = true; 15212 } 15213 15214 if (ProbableTypo) { 15215 Diag(NBody->getSemiLoc(), DiagID); 15216 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15217 } 15218 } 15219 15220 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15221 15222 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15223 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15224 SourceLocation OpLoc) { 15225 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15226 return; 15227 15228 if (inTemplateInstantiation()) 15229 return; 15230 15231 // Strip parens and casts away. 15232 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15233 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15234 15235 // Check for a call expression 15236 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15237 if (!CE || CE->getNumArgs() != 1) 15238 return; 15239 15240 // Check for a call to std::move 15241 if (!CE->isCallToStdMove()) 15242 return; 15243 15244 // Get argument from std::move 15245 RHSExpr = CE->getArg(0); 15246 15247 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15248 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15249 15250 // Two DeclRefExpr's, check that the decls are the same. 15251 if (LHSDeclRef && RHSDeclRef) { 15252 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15253 return; 15254 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15255 RHSDeclRef->getDecl()->getCanonicalDecl()) 15256 return; 15257 15258 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15259 << LHSExpr->getSourceRange() 15260 << RHSExpr->getSourceRange(); 15261 return; 15262 } 15263 15264 // Member variables require a different approach to check for self moves. 15265 // MemberExpr's are the same if every nested MemberExpr refers to the same 15266 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15267 // the base Expr's are CXXThisExpr's. 15268 const Expr *LHSBase = LHSExpr; 15269 const Expr *RHSBase = RHSExpr; 15270 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15271 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15272 if (!LHSME || !RHSME) 15273 return; 15274 15275 while (LHSME && RHSME) { 15276 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15277 RHSME->getMemberDecl()->getCanonicalDecl()) 15278 return; 15279 15280 LHSBase = LHSME->getBase(); 15281 RHSBase = RHSME->getBase(); 15282 LHSME = dyn_cast<MemberExpr>(LHSBase); 15283 RHSME = dyn_cast<MemberExpr>(RHSBase); 15284 } 15285 15286 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15287 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15288 if (LHSDeclRef && RHSDeclRef) { 15289 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15290 return; 15291 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15292 RHSDeclRef->getDecl()->getCanonicalDecl()) 15293 return; 15294 15295 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15296 << LHSExpr->getSourceRange() 15297 << RHSExpr->getSourceRange(); 15298 return; 15299 } 15300 15301 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15302 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15303 << LHSExpr->getSourceRange() 15304 << RHSExpr->getSourceRange(); 15305 } 15306 15307 //===--- Layout compatibility ----------------------------------------------// 15308 15309 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15310 15311 /// Check if two enumeration types are layout-compatible. 15312 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15313 // C++11 [dcl.enum] p8: 15314 // Two enumeration types are layout-compatible if they have the same 15315 // underlying type. 15316 return ED1->isComplete() && ED2->isComplete() && 15317 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15318 } 15319 15320 /// Check if two fields are layout-compatible. 15321 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15322 FieldDecl *Field2) { 15323 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15324 return false; 15325 15326 if (Field1->isBitField() != Field2->isBitField()) 15327 return false; 15328 15329 if (Field1->isBitField()) { 15330 // Make sure that the bit-fields are the same length. 15331 unsigned Bits1 = Field1->getBitWidthValue(C); 15332 unsigned Bits2 = Field2->getBitWidthValue(C); 15333 15334 if (Bits1 != Bits2) 15335 return false; 15336 } 15337 15338 return true; 15339 } 15340 15341 /// Check if two standard-layout structs are layout-compatible. 15342 /// (C++11 [class.mem] p17) 15343 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15344 RecordDecl *RD2) { 15345 // If both records are C++ classes, check that base classes match. 15346 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15347 // If one of records is a CXXRecordDecl we are in C++ mode, 15348 // thus the other one is a CXXRecordDecl, too. 15349 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15350 // Check number of base classes. 15351 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15352 return false; 15353 15354 // Check the base classes. 15355 for (CXXRecordDecl::base_class_const_iterator 15356 Base1 = D1CXX->bases_begin(), 15357 BaseEnd1 = D1CXX->bases_end(), 15358 Base2 = D2CXX->bases_begin(); 15359 Base1 != BaseEnd1; 15360 ++Base1, ++Base2) { 15361 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15362 return false; 15363 } 15364 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15365 // If only RD2 is a C++ class, it should have zero base classes. 15366 if (D2CXX->getNumBases() > 0) 15367 return false; 15368 } 15369 15370 // Check the fields. 15371 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15372 Field2End = RD2->field_end(), 15373 Field1 = RD1->field_begin(), 15374 Field1End = RD1->field_end(); 15375 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15376 if (!isLayoutCompatible(C, *Field1, *Field2)) 15377 return false; 15378 } 15379 if (Field1 != Field1End || Field2 != Field2End) 15380 return false; 15381 15382 return true; 15383 } 15384 15385 /// Check if two standard-layout unions are layout-compatible. 15386 /// (C++11 [class.mem] p18) 15387 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15388 RecordDecl *RD2) { 15389 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15390 for (auto *Field2 : RD2->fields()) 15391 UnmatchedFields.insert(Field2); 15392 15393 for (auto *Field1 : RD1->fields()) { 15394 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15395 I = UnmatchedFields.begin(), 15396 E = UnmatchedFields.end(); 15397 15398 for ( ; I != E; ++I) { 15399 if (isLayoutCompatible(C, Field1, *I)) { 15400 bool Result = UnmatchedFields.erase(*I); 15401 (void) Result; 15402 assert(Result); 15403 break; 15404 } 15405 } 15406 if (I == E) 15407 return false; 15408 } 15409 15410 return UnmatchedFields.empty(); 15411 } 15412 15413 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15414 RecordDecl *RD2) { 15415 if (RD1->isUnion() != RD2->isUnion()) 15416 return false; 15417 15418 if (RD1->isUnion()) 15419 return isLayoutCompatibleUnion(C, RD1, RD2); 15420 else 15421 return isLayoutCompatibleStruct(C, RD1, RD2); 15422 } 15423 15424 /// Check if two types are layout-compatible in C++11 sense. 15425 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15426 if (T1.isNull() || T2.isNull()) 15427 return false; 15428 15429 // C++11 [basic.types] p11: 15430 // If two types T1 and T2 are the same type, then T1 and T2 are 15431 // layout-compatible types. 15432 if (C.hasSameType(T1, T2)) 15433 return true; 15434 15435 T1 = T1.getCanonicalType().getUnqualifiedType(); 15436 T2 = T2.getCanonicalType().getUnqualifiedType(); 15437 15438 const Type::TypeClass TC1 = T1->getTypeClass(); 15439 const Type::TypeClass TC2 = T2->getTypeClass(); 15440 15441 if (TC1 != TC2) 15442 return false; 15443 15444 if (TC1 == Type::Enum) { 15445 return isLayoutCompatible(C, 15446 cast<EnumType>(T1)->getDecl(), 15447 cast<EnumType>(T2)->getDecl()); 15448 } else if (TC1 == Type::Record) { 15449 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15450 return false; 15451 15452 return isLayoutCompatible(C, 15453 cast<RecordType>(T1)->getDecl(), 15454 cast<RecordType>(T2)->getDecl()); 15455 } 15456 15457 return false; 15458 } 15459 15460 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15461 15462 /// Given a type tag expression find the type tag itself. 15463 /// 15464 /// \param TypeExpr Type tag expression, as it appears in user's code. 15465 /// 15466 /// \param VD Declaration of an identifier that appears in a type tag. 15467 /// 15468 /// \param MagicValue Type tag magic value. 15469 /// 15470 /// \param isConstantEvaluated wether the evalaution should be performed in 15471 15472 /// constant context. 15473 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15474 const ValueDecl **VD, uint64_t *MagicValue, 15475 bool isConstantEvaluated) { 15476 while(true) { 15477 if (!TypeExpr) 15478 return false; 15479 15480 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15481 15482 switch (TypeExpr->getStmtClass()) { 15483 case Stmt::UnaryOperatorClass: { 15484 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15485 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15486 TypeExpr = UO->getSubExpr(); 15487 continue; 15488 } 15489 return false; 15490 } 15491 15492 case Stmt::DeclRefExprClass: { 15493 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15494 *VD = DRE->getDecl(); 15495 return true; 15496 } 15497 15498 case Stmt::IntegerLiteralClass: { 15499 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15500 llvm::APInt MagicValueAPInt = IL->getValue(); 15501 if (MagicValueAPInt.getActiveBits() <= 64) { 15502 *MagicValue = MagicValueAPInt.getZExtValue(); 15503 return true; 15504 } else 15505 return false; 15506 } 15507 15508 case Stmt::BinaryConditionalOperatorClass: 15509 case Stmt::ConditionalOperatorClass: { 15510 const AbstractConditionalOperator *ACO = 15511 cast<AbstractConditionalOperator>(TypeExpr); 15512 bool Result; 15513 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15514 isConstantEvaluated)) { 15515 if (Result) 15516 TypeExpr = ACO->getTrueExpr(); 15517 else 15518 TypeExpr = ACO->getFalseExpr(); 15519 continue; 15520 } 15521 return false; 15522 } 15523 15524 case Stmt::BinaryOperatorClass: { 15525 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15526 if (BO->getOpcode() == BO_Comma) { 15527 TypeExpr = BO->getRHS(); 15528 continue; 15529 } 15530 return false; 15531 } 15532 15533 default: 15534 return false; 15535 } 15536 } 15537 } 15538 15539 /// Retrieve the C type corresponding to type tag TypeExpr. 15540 /// 15541 /// \param TypeExpr Expression that specifies a type tag. 15542 /// 15543 /// \param MagicValues Registered magic values. 15544 /// 15545 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15546 /// kind. 15547 /// 15548 /// \param TypeInfo Information about the corresponding C type. 15549 /// 15550 /// \param isConstantEvaluated wether the evalaution should be performed in 15551 /// constant context. 15552 /// 15553 /// \returns true if the corresponding C type was found. 15554 static bool GetMatchingCType( 15555 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15556 const ASTContext &Ctx, 15557 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15558 *MagicValues, 15559 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15560 bool isConstantEvaluated) { 15561 FoundWrongKind = false; 15562 15563 // Variable declaration that has type_tag_for_datatype attribute. 15564 const ValueDecl *VD = nullptr; 15565 15566 uint64_t MagicValue; 15567 15568 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15569 return false; 15570 15571 if (VD) { 15572 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15573 if (I->getArgumentKind() != ArgumentKind) { 15574 FoundWrongKind = true; 15575 return false; 15576 } 15577 TypeInfo.Type = I->getMatchingCType(); 15578 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15579 TypeInfo.MustBeNull = I->getMustBeNull(); 15580 return true; 15581 } 15582 return false; 15583 } 15584 15585 if (!MagicValues) 15586 return false; 15587 15588 llvm::DenseMap<Sema::TypeTagMagicValue, 15589 Sema::TypeTagData>::const_iterator I = 15590 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15591 if (I == MagicValues->end()) 15592 return false; 15593 15594 TypeInfo = I->second; 15595 return true; 15596 } 15597 15598 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15599 uint64_t MagicValue, QualType Type, 15600 bool LayoutCompatible, 15601 bool MustBeNull) { 15602 if (!TypeTagForDatatypeMagicValues) 15603 TypeTagForDatatypeMagicValues.reset( 15604 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15605 15606 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15607 (*TypeTagForDatatypeMagicValues)[Magic] = 15608 TypeTagData(Type, LayoutCompatible, MustBeNull); 15609 } 15610 15611 static bool IsSameCharType(QualType T1, QualType T2) { 15612 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15613 if (!BT1) 15614 return false; 15615 15616 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15617 if (!BT2) 15618 return false; 15619 15620 BuiltinType::Kind T1Kind = BT1->getKind(); 15621 BuiltinType::Kind T2Kind = BT2->getKind(); 15622 15623 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15624 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15625 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15626 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15627 } 15628 15629 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15630 const ArrayRef<const Expr *> ExprArgs, 15631 SourceLocation CallSiteLoc) { 15632 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15633 bool IsPointerAttr = Attr->getIsPointer(); 15634 15635 // Retrieve the argument representing the 'type_tag'. 15636 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15637 if (TypeTagIdxAST >= ExprArgs.size()) { 15638 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15639 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15640 return; 15641 } 15642 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15643 bool FoundWrongKind; 15644 TypeTagData TypeInfo; 15645 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15646 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15647 TypeInfo, isConstantEvaluated())) { 15648 if (FoundWrongKind) 15649 Diag(TypeTagExpr->getExprLoc(), 15650 diag::warn_type_tag_for_datatype_wrong_kind) 15651 << TypeTagExpr->getSourceRange(); 15652 return; 15653 } 15654 15655 // Retrieve the argument representing the 'arg_idx'. 15656 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15657 if (ArgumentIdxAST >= ExprArgs.size()) { 15658 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15659 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15660 return; 15661 } 15662 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15663 if (IsPointerAttr) { 15664 // Skip implicit cast of pointer to `void *' (as a function argument). 15665 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15666 if (ICE->getType()->isVoidPointerType() && 15667 ICE->getCastKind() == CK_BitCast) 15668 ArgumentExpr = ICE->getSubExpr(); 15669 } 15670 QualType ArgumentType = ArgumentExpr->getType(); 15671 15672 // Passing a `void*' pointer shouldn't trigger a warning. 15673 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15674 return; 15675 15676 if (TypeInfo.MustBeNull) { 15677 // Type tag with matching void type requires a null pointer. 15678 if (!ArgumentExpr->isNullPointerConstant(Context, 15679 Expr::NPC_ValueDependentIsNotNull)) { 15680 Diag(ArgumentExpr->getExprLoc(), 15681 diag::warn_type_safety_null_pointer_required) 15682 << ArgumentKind->getName() 15683 << ArgumentExpr->getSourceRange() 15684 << TypeTagExpr->getSourceRange(); 15685 } 15686 return; 15687 } 15688 15689 QualType RequiredType = TypeInfo.Type; 15690 if (IsPointerAttr) 15691 RequiredType = Context.getPointerType(RequiredType); 15692 15693 bool mismatch = false; 15694 if (!TypeInfo.LayoutCompatible) { 15695 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15696 15697 // C++11 [basic.fundamental] p1: 15698 // Plain char, signed char, and unsigned char are three distinct types. 15699 // 15700 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15701 // char' depending on the current char signedness mode. 15702 if (mismatch) 15703 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15704 RequiredType->getPointeeType())) || 15705 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15706 mismatch = false; 15707 } else 15708 if (IsPointerAttr) 15709 mismatch = !isLayoutCompatible(Context, 15710 ArgumentType->getPointeeType(), 15711 RequiredType->getPointeeType()); 15712 else 15713 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15714 15715 if (mismatch) 15716 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15717 << ArgumentType << ArgumentKind 15718 << TypeInfo.LayoutCompatible << RequiredType 15719 << ArgumentExpr->getSourceRange() 15720 << TypeTagExpr->getSourceRange(); 15721 } 15722 15723 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15724 CharUnits Alignment) { 15725 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15726 } 15727 15728 void Sema::DiagnoseMisalignedMembers() { 15729 for (MisalignedMember &m : MisalignedMembers) { 15730 const NamedDecl *ND = m.RD; 15731 if (ND->getName().empty()) { 15732 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15733 ND = TD; 15734 } 15735 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15736 << m.MD << ND << m.E->getSourceRange(); 15737 } 15738 MisalignedMembers.clear(); 15739 } 15740 15741 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15742 E = E->IgnoreParens(); 15743 if (!T->isPointerType() && !T->isIntegerType()) 15744 return; 15745 if (isa<UnaryOperator>(E) && 15746 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15747 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15748 if (isa<MemberExpr>(Op)) { 15749 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15750 if (MA != MisalignedMembers.end() && 15751 (T->isIntegerType() || 15752 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15753 Context.getTypeAlignInChars( 15754 T->getPointeeType()) <= MA->Alignment)))) 15755 MisalignedMembers.erase(MA); 15756 } 15757 } 15758 } 15759 15760 void Sema::RefersToMemberWithReducedAlignment( 15761 Expr *E, 15762 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15763 Action) { 15764 const auto *ME = dyn_cast<MemberExpr>(E); 15765 if (!ME) 15766 return; 15767 15768 // No need to check expressions with an __unaligned-qualified type. 15769 if (E->getType().getQualifiers().hasUnaligned()) 15770 return; 15771 15772 // For a chain of MemberExpr like "a.b.c.d" this list 15773 // will keep FieldDecl's like [d, c, b]. 15774 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15775 const MemberExpr *TopME = nullptr; 15776 bool AnyIsPacked = false; 15777 do { 15778 QualType BaseType = ME->getBase()->getType(); 15779 if (BaseType->isDependentType()) 15780 return; 15781 if (ME->isArrow()) 15782 BaseType = BaseType->getPointeeType(); 15783 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15784 if (RD->isInvalidDecl()) 15785 return; 15786 15787 ValueDecl *MD = ME->getMemberDecl(); 15788 auto *FD = dyn_cast<FieldDecl>(MD); 15789 // We do not care about non-data members. 15790 if (!FD || FD->isInvalidDecl()) 15791 return; 15792 15793 AnyIsPacked = 15794 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15795 ReverseMemberChain.push_back(FD); 15796 15797 TopME = ME; 15798 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15799 } while (ME); 15800 assert(TopME && "We did not compute a topmost MemberExpr!"); 15801 15802 // Not the scope of this diagnostic. 15803 if (!AnyIsPacked) 15804 return; 15805 15806 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15807 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15808 // TODO: The innermost base of the member expression may be too complicated. 15809 // For now, just disregard these cases. This is left for future 15810 // improvement. 15811 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15812 return; 15813 15814 // Alignment expected by the whole expression. 15815 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15816 15817 // No need to do anything else with this case. 15818 if (ExpectedAlignment.isOne()) 15819 return; 15820 15821 // Synthesize offset of the whole access. 15822 CharUnits Offset; 15823 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15824 I++) { 15825 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15826 } 15827 15828 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15829 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15830 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15831 15832 // The base expression of the innermost MemberExpr may give 15833 // stronger guarantees than the class containing the member. 15834 if (DRE && !TopME->isArrow()) { 15835 const ValueDecl *VD = DRE->getDecl(); 15836 if (!VD->getType()->isReferenceType()) 15837 CompleteObjectAlignment = 15838 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15839 } 15840 15841 // Check if the synthesized offset fulfills the alignment. 15842 if (Offset % ExpectedAlignment != 0 || 15843 // It may fulfill the offset it but the effective alignment may still be 15844 // lower than the expected expression alignment. 15845 CompleteObjectAlignment < ExpectedAlignment) { 15846 // If this happens, we want to determine a sensible culprit of this. 15847 // Intuitively, watching the chain of member expressions from right to 15848 // left, we start with the required alignment (as required by the field 15849 // type) but some packed attribute in that chain has reduced the alignment. 15850 // It may happen that another packed structure increases it again. But if 15851 // we are here such increase has not been enough. So pointing the first 15852 // FieldDecl that either is packed or else its RecordDecl is, 15853 // seems reasonable. 15854 FieldDecl *FD = nullptr; 15855 CharUnits Alignment; 15856 for (FieldDecl *FDI : ReverseMemberChain) { 15857 if (FDI->hasAttr<PackedAttr>() || 15858 FDI->getParent()->hasAttr<PackedAttr>()) { 15859 FD = FDI; 15860 Alignment = std::min( 15861 Context.getTypeAlignInChars(FD->getType()), 15862 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15863 break; 15864 } 15865 } 15866 assert(FD && "We did not find a packed FieldDecl!"); 15867 Action(E, FD->getParent(), FD, Alignment); 15868 } 15869 } 15870 15871 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15872 using namespace std::placeholders; 15873 15874 RefersToMemberWithReducedAlignment( 15875 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15876 _2, _3, _4)); 15877 } 15878 15879 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15880 ExprResult CallResult) { 15881 if (checkArgCount(*this, TheCall, 1)) 15882 return ExprError(); 15883 15884 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15885 if (MatrixArg.isInvalid()) 15886 return MatrixArg; 15887 Expr *Matrix = MatrixArg.get(); 15888 15889 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15890 if (!MType) { 15891 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15892 return ExprError(); 15893 } 15894 15895 // Create returned matrix type by swapping rows and columns of the argument 15896 // matrix type. 15897 QualType ResultType = Context.getConstantMatrixType( 15898 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15899 15900 // Change the return type to the type of the returned matrix. 15901 TheCall->setType(ResultType); 15902 15903 // Update call argument to use the possibly converted matrix argument. 15904 TheCall->setArg(0, Matrix); 15905 return CallResult; 15906 } 15907 15908 // Get and verify the matrix dimensions. 15909 static llvm::Optional<unsigned> 15910 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15911 SourceLocation ErrorPos; 15912 Optional<llvm::APSInt> Value = 15913 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 15914 if (!Value) { 15915 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 15916 << Name; 15917 return {}; 15918 } 15919 uint64_t Dim = Value->getZExtValue(); 15920 if (!ConstantMatrixType::isDimensionValid(Dim)) { 15921 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 15922 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 15923 return {}; 15924 } 15925 return Dim; 15926 } 15927 15928 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 15929 ExprResult CallResult) { 15930 if (!getLangOpts().MatrixTypes) { 15931 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 15932 return ExprError(); 15933 } 15934 15935 if (checkArgCount(*this, TheCall, 4)) 15936 return ExprError(); 15937 15938 unsigned PtrArgIdx = 0; 15939 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15940 Expr *RowsExpr = TheCall->getArg(1); 15941 Expr *ColumnsExpr = TheCall->getArg(2); 15942 Expr *StrideExpr = TheCall->getArg(3); 15943 15944 bool ArgError = false; 15945 15946 // Check pointer argument. 15947 { 15948 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15949 if (PtrConv.isInvalid()) 15950 return PtrConv; 15951 PtrExpr = PtrConv.get(); 15952 TheCall->setArg(0, PtrExpr); 15953 if (PtrExpr->isTypeDependent()) { 15954 TheCall->setType(Context.DependentTy); 15955 return TheCall; 15956 } 15957 } 15958 15959 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15960 QualType ElementTy; 15961 if (!PtrTy) { 15962 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15963 << PtrArgIdx + 1; 15964 ArgError = true; 15965 } else { 15966 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 15967 15968 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 15969 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15970 << PtrArgIdx + 1; 15971 ArgError = true; 15972 } 15973 } 15974 15975 // Apply default Lvalue conversions and convert the expression to size_t. 15976 auto ApplyArgumentConversions = [this](Expr *E) { 15977 ExprResult Conv = DefaultLvalueConversion(E); 15978 if (Conv.isInvalid()) 15979 return Conv; 15980 15981 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 15982 }; 15983 15984 // Apply conversion to row and column expressions. 15985 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 15986 if (!RowsConv.isInvalid()) { 15987 RowsExpr = RowsConv.get(); 15988 TheCall->setArg(1, RowsExpr); 15989 } else 15990 RowsExpr = nullptr; 15991 15992 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 15993 if (!ColumnsConv.isInvalid()) { 15994 ColumnsExpr = ColumnsConv.get(); 15995 TheCall->setArg(2, ColumnsExpr); 15996 } else 15997 ColumnsExpr = nullptr; 15998 15999 // If any any part of the result matrix type is still pending, just use 16000 // Context.DependentTy, until all parts are resolved. 16001 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16002 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16003 TheCall->setType(Context.DependentTy); 16004 return CallResult; 16005 } 16006 16007 // Check row and column dimenions. 16008 llvm::Optional<unsigned> MaybeRows; 16009 if (RowsExpr) 16010 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16011 16012 llvm::Optional<unsigned> MaybeColumns; 16013 if (ColumnsExpr) 16014 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16015 16016 // Check stride argument. 16017 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16018 if (StrideConv.isInvalid()) 16019 return ExprError(); 16020 StrideExpr = StrideConv.get(); 16021 TheCall->setArg(3, StrideExpr); 16022 16023 if (MaybeRows) { 16024 if (Optional<llvm::APSInt> Value = 16025 StrideExpr->getIntegerConstantExpr(Context)) { 16026 uint64_t Stride = Value->getZExtValue(); 16027 if (Stride < *MaybeRows) { 16028 Diag(StrideExpr->getBeginLoc(), 16029 diag::err_builtin_matrix_stride_too_small); 16030 ArgError = true; 16031 } 16032 } 16033 } 16034 16035 if (ArgError || !MaybeRows || !MaybeColumns) 16036 return ExprError(); 16037 16038 TheCall->setType( 16039 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16040 return CallResult; 16041 } 16042 16043 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16044 ExprResult CallResult) { 16045 if (checkArgCount(*this, TheCall, 3)) 16046 return ExprError(); 16047 16048 unsigned PtrArgIdx = 1; 16049 Expr *MatrixExpr = TheCall->getArg(0); 16050 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16051 Expr *StrideExpr = TheCall->getArg(2); 16052 16053 bool ArgError = false; 16054 16055 { 16056 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16057 if (MatrixConv.isInvalid()) 16058 return MatrixConv; 16059 MatrixExpr = MatrixConv.get(); 16060 TheCall->setArg(0, MatrixExpr); 16061 } 16062 if (MatrixExpr->isTypeDependent()) { 16063 TheCall->setType(Context.DependentTy); 16064 return TheCall; 16065 } 16066 16067 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16068 if (!MatrixTy) { 16069 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16070 ArgError = true; 16071 } 16072 16073 { 16074 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16075 if (PtrConv.isInvalid()) 16076 return PtrConv; 16077 PtrExpr = PtrConv.get(); 16078 TheCall->setArg(1, PtrExpr); 16079 if (PtrExpr->isTypeDependent()) { 16080 TheCall->setType(Context.DependentTy); 16081 return TheCall; 16082 } 16083 } 16084 16085 // Check pointer argument. 16086 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16087 if (!PtrTy) { 16088 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16089 << PtrArgIdx + 1; 16090 ArgError = true; 16091 } else { 16092 QualType ElementTy = PtrTy->getPointeeType(); 16093 if (ElementTy.isConstQualified()) { 16094 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16095 ArgError = true; 16096 } 16097 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16098 if (MatrixTy && 16099 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16100 Diag(PtrExpr->getBeginLoc(), 16101 diag::err_builtin_matrix_pointer_arg_mismatch) 16102 << ElementTy << MatrixTy->getElementType(); 16103 ArgError = true; 16104 } 16105 } 16106 16107 // Apply default Lvalue conversions and convert the stride expression to 16108 // size_t. 16109 { 16110 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16111 if (StrideConv.isInvalid()) 16112 return StrideConv; 16113 16114 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16115 if (StrideConv.isInvalid()) 16116 return StrideConv; 16117 StrideExpr = StrideConv.get(); 16118 TheCall->setArg(2, StrideExpr); 16119 } 16120 16121 // Check stride argument. 16122 if (MatrixTy) { 16123 if (Optional<llvm::APSInt> Value = 16124 StrideExpr->getIntegerConstantExpr(Context)) { 16125 uint64_t Stride = Value->getZExtValue(); 16126 if (Stride < MatrixTy->getNumRows()) { 16127 Diag(StrideExpr->getBeginLoc(), 16128 diag::err_builtin_matrix_stride_too_small); 16129 ArgError = true; 16130 } 16131 } 16132 } 16133 16134 if (ArgError) 16135 return ExprError(); 16136 16137 return CallResult; 16138 } 16139 16140 /// \brief Enforce the bounds of a TCB 16141 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16142 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16143 /// and enforce_tcb_leaf attributes. 16144 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16145 const FunctionDecl *Callee) { 16146 const FunctionDecl *Caller = getCurFunctionDecl(); 16147 16148 // Calls to builtins are not enforced. 16149 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16150 Callee->getBuiltinID() != 0) 16151 return; 16152 16153 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16154 // all TCBs the callee is a part of. 16155 llvm::StringSet<> CalleeTCBs; 16156 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16157 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16158 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16159 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16160 16161 // Go through the TCBs the caller is a part of and emit warnings if Caller 16162 // is in a TCB that the Callee is not. 16163 for_each( 16164 Caller->specific_attrs<EnforceTCBAttr>(), 16165 [&](const auto *A) { 16166 StringRef CallerTCB = A->getTCBName(); 16167 if (CalleeTCBs.count(CallerTCB) == 0) { 16168 this->Diag(TheCall->getExprLoc(), 16169 diag::warn_tcb_enforcement_violation) << Callee 16170 << CallerTCB; 16171 } 16172 }); 16173 } 16174