1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class ScanfDiagnosticFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 // Accepts the argument index (relative to the first destination index) of the 414 // argument whose size we want. 415 using ComputeSizeFunction = 416 llvm::function_ref<Optional<llvm::APSInt>(unsigned)>; 417 418 // Accepts the argument index (relative to the first destination index), the 419 // destination size, and the source size). 420 using DiagnoseFunction = 421 llvm::function_ref<void(unsigned, unsigned, unsigned)>; 422 423 ComputeSizeFunction ComputeSizeArgument; 424 DiagnoseFunction Diagnose; 425 426 public: 427 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument, 428 DiagnoseFunction Diagnose) 429 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {} 430 431 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 432 const char *StartSpecifier, 433 unsigned specifierLen) override { 434 if (!FS.consumesDataArgument()) 435 return true; 436 437 unsigned NulByte = 0; 438 switch ((FS.getConversionSpecifier().getKind())) { 439 default: 440 return true; 441 case analyze_format_string::ConversionSpecifier::sArg: 442 case analyze_format_string::ConversionSpecifier::ScanListArg: 443 NulByte = 1; 444 break; 445 case analyze_format_string::ConversionSpecifier::cArg: 446 break; 447 } 448 449 auto OptionalFW = FS.getFieldWidth(); 450 if (OptionalFW.getHowSpecified() != 451 analyze_format_string::OptionalAmount::HowSpecified::Constant) 452 return true; 453 454 unsigned SourceSize = OptionalFW.getConstantAmount() + NulByte; 455 456 auto DestSizeAPS = ComputeSizeArgument(FS.getArgIndex()); 457 if (!DestSizeAPS) 458 return true; 459 460 unsigned DestSize = DestSizeAPS->getZExtValue(); 461 462 if (DestSize < SourceSize) 463 Diagnose(FS.getArgIndex(), DestSize, SourceSize); 464 465 return true; 466 } 467 }; 468 469 class EstimateSizeFormatHandler 470 : public analyze_format_string::FormatStringHandler { 471 size_t Size; 472 473 public: 474 EstimateSizeFormatHandler(StringRef Format) 475 : Size(std::min(Format.find(0), Format.size()) + 476 1 /* null byte always written by sprintf */) {} 477 478 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 479 const char *, unsigned SpecifierLen) override { 480 481 const size_t FieldWidth = computeFieldWidth(FS); 482 const size_t Precision = computePrecision(FS); 483 484 // The actual format. 485 switch (FS.getConversionSpecifier().getKind()) { 486 // Just a char. 487 case analyze_format_string::ConversionSpecifier::cArg: 488 case analyze_format_string::ConversionSpecifier::CArg: 489 Size += std::max(FieldWidth, (size_t)1); 490 break; 491 // Just an integer. 492 case analyze_format_string::ConversionSpecifier::dArg: 493 case analyze_format_string::ConversionSpecifier::DArg: 494 case analyze_format_string::ConversionSpecifier::iArg: 495 case analyze_format_string::ConversionSpecifier::oArg: 496 case analyze_format_string::ConversionSpecifier::OArg: 497 case analyze_format_string::ConversionSpecifier::uArg: 498 case analyze_format_string::ConversionSpecifier::UArg: 499 case analyze_format_string::ConversionSpecifier::xArg: 500 case analyze_format_string::ConversionSpecifier::XArg: 501 Size += std::max(FieldWidth, Precision); 502 break; 503 504 // %g style conversion switches between %f or %e style dynamically. 505 // %f always takes less space, so default to it. 506 case analyze_format_string::ConversionSpecifier::gArg: 507 case analyze_format_string::ConversionSpecifier::GArg: 508 509 // Floating point number in the form '[+]ddd.ddd'. 510 case analyze_format_string::ConversionSpecifier::fArg: 511 case analyze_format_string::ConversionSpecifier::FArg: 512 Size += std::max(FieldWidth, 1 /* integer part */ + 513 (Precision ? 1 + Precision 514 : 0) /* period + decimal */); 515 break; 516 517 // Floating point number in the form '[-]d.ddde[+-]dd'. 518 case analyze_format_string::ConversionSpecifier::eArg: 519 case analyze_format_string::ConversionSpecifier::EArg: 520 Size += 521 std::max(FieldWidth, 522 1 /* integer part */ + 523 (Precision ? 1 + Precision : 0) /* period + decimal */ + 524 1 /* e or E letter */ + 2 /* exponent */); 525 break; 526 527 // Floating point number in the form '[-]0xh.hhhhp±dd'. 528 case analyze_format_string::ConversionSpecifier::aArg: 529 case analyze_format_string::ConversionSpecifier::AArg: 530 Size += 531 std::max(FieldWidth, 532 2 /* 0x */ + 1 /* integer part */ + 533 (Precision ? 1 + Precision : 0) /* period + decimal */ + 534 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 535 break; 536 537 // Just a string. 538 case analyze_format_string::ConversionSpecifier::sArg: 539 case analyze_format_string::ConversionSpecifier::SArg: 540 Size += FieldWidth; 541 break; 542 543 // Just a pointer in the form '0xddd'. 544 case analyze_format_string::ConversionSpecifier::pArg: 545 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 546 break; 547 548 // A plain percent. 549 case analyze_format_string::ConversionSpecifier::PercentArg: 550 Size += 1; 551 break; 552 553 default: 554 break; 555 } 556 557 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 558 559 if (FS.hasAlternativeForm()) { 560 switch (FS.getConversionSpecifier().getKind()) { 561 default: 562 break; 563 // Force a leading '0'. 564 case analyze_format_string::ConversionSpecifier::oArg: 565 Size += 1; 566 break; 567 // Force a leading '0x'. 568 case analyze_format_string::ConversionSpecifier::xArg: 569 case analyze_format_string::ConversionSpecifier::XArg: 570 Size += 2; 571 break; 572 // Force a period '.' before decimal, even if precision is 0. 573 case analyze_format_string::ConversionSpecifier::aArg: 574 case analyze_format_string::ConversionSpecifier::AArg: 575 case analyze_format_string::ConversionSpecifier::eArg: 576 case analyze_format_string::ConversionSpecifier::EArg: 577 case analyze_format_string::ConversionSpecifier::fArg: 578 case analyze_format_string::ConversionSpecifier::FArg: 579 case analyze_format_string::ConversionSpecifier::gArg: 580 case analyze_format_string::ConversionSpecifier::GArg: 581 Size += (Precision ? 0 : 1); 582 break; 583 } 584 } 585 assert(SpecifierLen <= Size && "no underflow"); 586 Size -= SpecifierLen; 587 return true; 588 } 589 590 size_t getSizeLowerBound() const { return Size; } 591 592 private: 593 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 594 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 595 size_t FieldWidth = 0; 596 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 597 FieldWidth = FW.getConstantAmount(); 598 return FieldWidth; 599 } 600 601 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 602 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 603 size_t Precision = 0; 604 605 // See man 3 printf for default precision value based on the specifier. 606 switch (FW.getHowSpecified()) { 607 case analyze_format_string::OptionalAmount::NotSpecified: 608 switch (FS.getConversionSpecifier().getKind()) { 609 default: 610 break; 611 case analyze_format_string::ConversionSpecifier::dArg: // %d 612 case analyze_format_string::ConversionSpecifier::DArg: // %D 613 case analyze_format_string::ConversionSpecifier::iArg: // %i 614 Precision = 1; 615 break; 616 case analyze_format_string::ConversionSpecifier::oArg: // %d 617 case analyze_format_string::ConversionSpecifier::OArg: // %D 618 case analyze_format_string::ConversionSpecifier::uArg: // %d 619 case analyze_format_string::ConversionSpecifier::UArg: // %D 620 case analyze_format_string::ConversionSpecifier::xArg: // %d 621 case analyze_format_string::ConversionSpecifier::XArg: // %D 622 Precision = 1; 623 break; 624 case analyze_format_string::ConversionSpecifier::fArg: // %f 625 case analyze_format_string::ConversionSpecifier::FArg: // %F 626 case analyze_format_string::ConversionSpecifier::eArg: // %e 627 case analyze_format_string::ConversionSpecifier::EArg: // %E 628 case analyze_format_string::ConversionSpecifier::gArg: // %g 629 case analyze_format_string::ConversionSpecifier::GArg: // %G 630 Precision = 6; 631 break; 632 case analyze_format_string::ConversionSpecifier::pArg: // %d 633 Precision = 1; 634 break; 635 } 636 break; 637 case analyze_format_string::OptionalAmount::Constant: 638 Precision = FW.getConstantAmount(); 639 break; 640 default: 641 break; 642 } 643 return Precision; 644 } 645 }; 646 647 } // namespace 648 649 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 650 CallExpr *TheCall) { 651 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 652 isConstantEvaluated()) 653 return; 654 655 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 656 if (!BuiltinID) 657 return; 658 659 const TargetInfo &TI = getASTContext().getTargetInfo(); 660 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 661 662 auto ComputeExplicitObjectSizeArgument = 663 [&](unsigned Index) -> Optional<llvm::APSInt> { 664 Expr::EvalResult Result; 665 Expr *SizeArg = TheCall->getArg(Index); 666 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 667 return llvm::None; 668 return Result.Val.getInt(); 669 }; 670 671 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 672 // If the parameter has a pass_object_size attribute, then we should use its 673 // (potentially) more strict checking mode. Otherwise, conservatively assume 674 // type 0. 675 int BOSType = 0; 676 // This check can fail for variadic functions. 677 if (Index < FD->getNumParams()) { 678 if (const auto *POS = 679 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 680 BOSType = POS->getType(); 681 } 682 683 const Expr *ObjArg = TheCall->getArg(Index); 684 uint64_t Result; 685 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 686 return llvm::None; 687 688 // Get the object size in the target's size_t width. 689 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 690 }; 691 692 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 693 Expr *ObjArg = TheCall->getArg(Index); 694 uint64_t Result; 695 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 696 return llvm::None; 697 // Add 1 for null byte. 698 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 699 }; 700 701 Optional<llvm::APSInt> SourceSize; 702 Optional<llvm::APSInt> DestinationSize; 703 unsigned DiagID = 0; 704 bool IsChkVariant = false; 705 706 auto GetFunctionName = [&]() { 707 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 708 // Skim off the details of whichever builtin was called to produce a better 709 // diagnostic, as it's unlikely that the user wrote the __builtin 710 // explicitly. 711 if (IsChkVariant) { 712 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 713 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 714 } else if (FunctionName.startswith("__builtin_")) { 715 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 716 } 717 return FunctionName; 718 }; 719 720 switch (BuiltinID) { 721 default: 722 return; 723 case Builtin::BI__builtin_strcpy: 724 case Builtin::BIstrcpy: { 725 DiagID = diag::warn_fortify_strlen_overflow; 726 SourceSize = ComputeStrLenArgument(1); 727 DestinationSize = ComputeSizeArgument(0); 728 break; 729 } 730 731 case Builtin::BI__builtin___strcpy_chk: { 732 DiagID = diag::warn_fortify_strlen_overflow; 733 SourceSize = ComputeStrLenArgument(1); 734 DestinationSize = ComputeExplicitObjectSizeArgument(2); 735 IsChkVariant = true; 736 break; 737 } 738 739 case Builtin::BIscanf: 740 case Builtin::BIfscanf: 741 case Builtin::BIsscanf: { 742 unsigned FormatIndex = 1; 743 unsigned DataIndex = 2; 744 if (BuiltinID == Builtin::BIscanf) { 745 FormatIndex = 0; 746 DataIndex = 1; 747 } 748 749 const auto *FormatExpr = 750 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 751 752 const auto *Format = dyn_cast<StringLiteral>(FormatExpr); 753 if (!Format) 754 return; 755 756 if (!Format->isAscii() && !Format->isUTF8()) 757 return; 758 759 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize, 760 unsigned SourceSize) { 761 DiagID = diag::warn_fortify_scanf_overflow; 762 unsigned Index = ArgIndex + DataIndex; 763 StringRef FunctionName = GetFunctionName(); 764 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall, 765 PDiag(DiagID) << FunctionName << (Index + 1) 766 << DestSize << SourceSize); 767 }; 768 769 StringRef FormatStrRef = Format->getString(); 770 auto ShiftedComputeSizeArgument = [&](unsigned Index) { 771 return ComputeSizeArgument(Index + DataIndex); 772 }; 773 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose); 774 const char *FormatBytes = FormatStrRef.data(); 775 const ConstantArrayType *T = 776 Context.getAsConstantArrayType(Format->getType()); 777 assert(T && "String literal not of constant array type!"); 778 size_t TypeSize = T->getSize().getZExtValue(); 779 780 // In case there's a null byte somewhere. 781 size_t StrLen = 782 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 783 784 analyze_format_string::ParseScanfString(H, FormatBytes, 785 FormatBytes + StrLen, getLangOpts(), 786 Context.getTargetInfo()); 787 788 // Unlike the other cases, in this one we have already issued the diagnostic 789 // here, so no need to continue (because unlike the other cases, here the 790 // diagnostic refers to the argument number). 791 return; 792 } 793 794 case Builtin::BIsprintf: 795 case Builtin::BI__builtin___sprintf_chk: { 796 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 797 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 798 799 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 800 801 if (!Format->isAscii() && !Format->isUTF8()) 802 return; 803 804 StringRef FormatStrRef = Format->getString(); 805 EstimateSizeFormatHandler H(FormatStrRef); 806 const char *FormatBytes = FormatStrRef.data(); 807 const ConstantArrayType *T = 808 Context.getAsConstantArrayType(Format->getType()); 809 assert(T && "String literal not of constant array type!"); 810 size_t TypeSize = T->getSize().getZExtValue(); 811 812 // In case there's a null byte somewhere. 813 size_t StrLen = 814 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 815 if (!analyze_format_string::ParsePrintfString( 816 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 817 Context.getTargetInfo(), false)) { 818 DiagID = diag::warn_fortify_source_format_overflow; 819 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 820 .extOrTrunc(SizeTypeWidth); 821 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 822 DestinationSize = ComputeExplicitObjectSizeArgument(2); 823 IsChkVariant = true; 824 } else { 825 DestinationSize = ComputeSizeArgument(0); 826 } 827 break; 828 } 829 } 830 return; 831 } 832 case Builtin::BI__builtin___memcpy_chk: 833 case Builtin::BI__builtin___memmove_chk: 834 case Builtin::BI__builtin___memset_chk: 835 case Builtin::BI__builtin___strlcat_chk: 836 case Builtin::BI__builtin___strlcpy_chk: 837 case Builtin::BI__builtin___strncat_chk: 838 case Builtin::BI__builtin___strncpy_chk: 839 case Builtin::BI__builtin___stpncpy_chk: 840 case Builtin::BI__builtin___memccpy_chk: 841 case Builtin::BI__builtin___mempcpy_chk: { 842 DiagID = diag::warn_builtin_chk_overflow; 843 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 844 DestinationSize = 845 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 846 IsChkVariant = true; 847 break; 848 } 849 850 case Builtin::BI__builtin___snprintf_chk: 851 case Builtin::BI__builtin___vsnprintf_chk: { 852 DiagID = diag::warn_builtin_chk_overflow; 853 SourceSize = ComputeExplicitObjectSizeArgument(1); 854 DestinationSize = ComputeExplicitObjectSizeArgument(3); 855 IsChkVariant = true; 856 break; 857 } 858 859 case Builtin::BIstrncat: 860 case Builtin::BI__builtin_strncat: 861 case Builtin::BIstrncpy: 862 case Builtin::BI__builtin_strncpy: 863 case Builtin::BIstpncpy: 864 case Builtin::BI__builtin_stpncpy: { 865 // Whether these functions overflow depends on the runtime strlen of the 866 // string, not just the buffer size, so emitting the "always overflow" 867 // diagnostic isn't quite right. We should still diagnose passing a buffer 868 // size larger than the destination buffer though; this is a runtime abort 869 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 870 DiagID = diag::warn_fortify_source_size_mismatch; 871 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 872 DestinationSize = ComputeSizeArgument(0); 873 break; 874 } 875 876 case Builtin::BImemcpy: 877 case Builtin::BI__builtin_memcpy: 878 case Builtin::BImemmove: 879 case Builtin::BI__builtin_memmove: 880 case Builtin::BImemset: 881 case Builtin::BI__builtin_memset: 882 case Builtin::BImempcpy: 883 case Builtin::BI__builtin_mempcpy: { 884 DiagID = diag::warn_fortify_source_overflow; 885 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 886 DestinationSize = ComputeSizeArgument(0); 887 break; 888 } 889 case Builtin::BIsnprintf: 890 case Builtin::BI__builtin_snprintf: 891 case Builtin::BIvsnprintf: 892 case Builtin::BI__builtin_vsnprintf: { 893 DiagID = diag::warn_fortify_source_size_mismatch; 894 SourceSize = ComputeExplicitObjectSizeArgument(1); 895 DestinationSize = ComputeSizeArgument(0); 896 break; 897 } 898 } 899 900 if (!SourceSize || !DestinationSize || 901 SourceSize.getValue().ule(DestinationSize.getValue())) 902 return; 903 904 StringRef FunctionName = GetFunctionName(); 905 906 SmallString<16> DestinationStr; 907 SmallString<16> SourceStr; 908 DestinationSize->toString(DestinationStr, /*Radix=*/10); 909 SourceSize->toString(SourceStr, /*Radix=*/10); 910 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 911 PDiag(DiagID) 912 << FunctionName << DestinationStr << SourceStr); 913 } 914 915 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 916 Scope::ScopeFlags NeededScopeFlags, 917 unsigned DiagID) { 918 // Scopes aren't available during instantiation. Fortunately, builtin 919 // functions cannot be template args so they cannot be formed through template 920 // instantiation. Therefore checking once during the parse is sufficient. 921 if (SemaRef.inTemplateInstantiation()) 922 return false; 923 924 Scope *S = SemaRef.getCurScope(); 925 while (S && !S->isSEHExceptScope()) 926 S = S->getParent(); 927 if (!S || !(S->getFlags() & NeededScopeFlags)) { 928 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 929 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 930 << DRE->getDecl()->getIdentifier(); 931 return true; 932 } 933 934 return false; 935 } 936 937 static inline bool isBlockPointer(Expr *Arg) { 938 return Arg->getType()->isBlockPointerType(); 939 } 940 941 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 942 /// void*, which is a requirement of device side enqueue. 943 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 944 const BlockPointerType *BPT = 945 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 946 ArrayRef<QualType> Params = 947 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 948 unsigned ArgCounter = 0; 949 bool IllegalParams = false; 950 // Iterate through the block parameters until either one is found that is not 951 // a local void*, or the block is valid. 952 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 953 I != E; ++I, ++ArgCounter) { 954 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 955 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 956 LangAS::opencl_local) { 957 // Get the location of the error. If a block literal has been passed 958 // (BlockExpr) then we can point straight to the offending argument, 959 // else we just point to the variable reference. 960 SourceLocation ErrorLoc; 961 if (isa<BlockExpr>(BlockArg)) { 962 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 963 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 964 } else if (isa<DeclRefExpr>(BlockArg)) { 965 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 966 } 967 S.Diag(ErrorLoc, 968 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 969 IllegalParams = true; 970 } 971 } 972 973 return IllegalParams; 974 } 975 976 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 977 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 978 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 979 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 980 return true; 981 } 982 return false; 983 } 984 985 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 986 if (checkArgCount(S, TheCall, 2)) 987 return true; 988 989 if (checkOpenCLSubgroupExt(S, TheCall)) 990 return true; 991 992 // First argument is an ndrange_t type. 993 Expr *NDRangeArg = TheCall->getArg(0); 994 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 995 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 996 << TheCall->getDirectCallee() << "'ndrange_t'"; 997 return true; 998 } 999 1000 Expr *BlockArg = TheCall->getArg(1); 1001 if (!isBlockPointer(BlockArg)) { 1002 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1003 << TheCall->getDirectCallee() << "block"; 1004 return true; 1005 } 1006 return checkOpenCLBlockArgs(S, BlockArg); 1007 } 1008 1009 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 1010 /// get_kernel_work_group_size 1011 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 1012 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 1013 if (checkArgCount(S, TheCall, 1)) 1014 return true; 1015 1016 Expr *BlockArg = TheCall->getArg(0); 1017 if (!isBlockPointer(BlockArg)) { 1018 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1019 << TheCall->getDirectCallee() << "block"; 1020 return true; 1021 } 1022 return checkOpenCLBlockArgs(S, BlockArg); 1023 } 1024 1025 /// Diagnose integer type and any valid implicit conversion to it. 1026 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 1027 const QualType &IntType); 1028 1029 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 1030 unsigned Start, unsigned End) { 1031 bool IllegalParams = false; 1032 for (unsigned I = Start; I <= End; ++I) 1033 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 1034 S.Context.getSizeType()); 1035 return IllegalParams; 1036 } 1037 1038 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 1039 /// 'local void*' parameter of passed block. 1040 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 1041 Expr *BlockArg, 1042 unsigned NumNonVarArgs) { 1043 const BlockPointerType *BPT = 1044 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1045 unsigned NumBlockParams = 1046 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 1047 unsigned TotalNumArgs = TheCall->getNumArgs(); 1048 1049 // For each argument passed to the block, a corresponding uint needs to 1050 // be passed to describe the size of the local memory. 1051 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 1052 S.Diag(TheCall->getBeginLoc(), 1053 diag::err_opencl_enqueue_kernel_local_size_args); 1054 return true; 1055 } 1056 1057 // Check that the sizes of the local memory are specified by integers. 1058 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 1059 TotalNumArgs - 1); 1060 } 1061 1062 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 1063 /// overload formats specified in Table 6.13.17.1. 1064 /// int enqueue_kernel(queue_t queue, 1065 /// kernel_enqueue_flags_t flags, 1066 /// const ndrange_t ndrange, 1067 /// void (^block)(void)) 1068 /// int enqueue_kernel(queue_t queue, 1069 /// kernel_enqueue_flags_t flags, 1070 /// const ndrange_t ndrange, 1071 /// uint num_events_in_wait_list, 1072 /// clk_event_t *event_wait_list, 1073 /// clk_event_t *event_ret, 1074 /// void (^block)(void)) 1075 /// int enqueue_kernel(queue_t queue, 1076 /// kernel_enqueue_flags_t flags, 1077 /// const ndrange_t ndrange, 1078 /// void (^block)(local void*, ...), 1079 /// uint size0, ...) 1080 /// int enqueue_kernel(queue_t queue, 1081 /// kernel_enqueue_flags_t flags, 1082 /// const ndrange_t ndrange, 1083 /// uint num_events_in_wait_list, 1084 /// clk_event_t *event_wait_list, 1085 /// clk_event_t *event_ret, 1086 /// void (^block)(local void*, ...), 1087 /// uint size0, ...) 1088 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 1089 unsigned NumArgs = TheCall->getNumArgs(); 1090 1091 if (NumArgs < 4) { 1092 S.Diag(TheCall->getBeginLoc(), 1093 diag::err_typecheck_call_too_few_args_at_least) 1094 << 0 << 4 << NumArgs; 1095 return true; 1096 } 1097 1098 Expr *Arg0 = TheCall->getArg(0); 1099 Expr *Arg1 = TheCall->getArg(1); 1100 Expr *Arg2 = TheCall->getArg(2); 1101 Expr *Arg3 = TheCall->getArg(3); 1102 1103 // First argument always needs to be a queue_t type. 1104 if (!Arg0->getType()->isQueueT()) { 1105 S.Diag(TheCall->getArg(0)->getBeginLoc(), 1106 diag::err_opencl_builtin_expected_type) 1107 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 1108 return true; 1109 } 1110 1111 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 1112 if (!Arg1->getType()->isIntegerType()) { 1113 S.Diag(TheCall->getArg(1)->getBeginLoc(), 1114 diag::err_opencl_builtin_expected_type) 1115 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 1116 return true; 1117 } 1118 1119 // Third argument is always an ndrange_t type. 1120 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1121 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1122 diag::err_opencl_builtin_expected_type) 1123 << TheCall->getDirectCallee() << "'ndrange_t'"; 1124 return true; 1125 } 1126 1127 // With four arguments, there is only one form that the function could be 1128 // called in: no events and no variable arguments. 1129 if (NumArgs == 4) { 1130 // check that the last argument is the right block type. 1131 if (!isBlockPointer(Arg3)) { 1132 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1133 << TheCall->getDirectCallee() << "block"; 1134 return true; 1135 } 1136 // we have a block type, check the prototype 1137 const BlockPointerType *BPT = 1138 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1139 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1140 S.Diag(Arg3->getBeginLoc(), 1141 diag::err_opencl_enqueue_kernel_blocks_no_args); 1142 return true; 1143 } 1144 return false; 1145 } 1146 // we can have block + varargs. 1147 if (isBlockPointer(Arg3)) 1148 return (checkOpenCLBlockArgs(S, Arg3) || 1149 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1150 // last two cases with either exactly 7 args or 7 args and varargs. 1151 if (NumArgs >= 7) { 1152 // check common block argument. 1153 Expr *Arg6 = TheCall->getArg(6); 1154 if (!isBlockPointer(Arg6)) { 1155 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1156 << TheCall->getDirectCallee() << "block"; 1157 return true; 1158 } 1159 if (checkOpenCLBlockArgs(S, Arg6)) 1160 return true; 1161 1162 // Forth argument has to be any integer type. 1163 if (!Arg3->getType()->isIntegerType()) { 1164 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1165 diag::err_opencl_builtin_expected_type) 1166 << TheCall->getDirectCallee() << "integer"; 1167 return true; 1168 } 1169 // check remaining common arguments. 1170 Expr *Arg4 = TheCall->getArg(4); 1171 Expr *Arg5 = TheCall->getArg(5); 1172 1173 // Fifth argument is always passed as a pointer to clk_event_t. 1174 if (!Arg4->isNullPointerConstant(S.Context, 1175 Expr::NPC_ValueDependentIsNotNull) && 1176 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1177 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1178 diag::err_opencl_builtin_expected_type) 1179 << TheCall->getDirectCallee() 1180 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1181 return true; 1182 } 1183 1184 // Sixth argument is always passed as a pointer to clk_event_t. 1185 if (!Arg5->isNullPointerConstant(S.Context, 1186 Expr::NPC_ValueDependentIsNotNull) && 1187 !(Arg5->getType()->isPointerType() && 1188 Arg5->getType()->getPointeeType()->isClkEventT())) { 1189 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1190 diag::err_opencl_builtin_expected_type) 1191 << TheCall->getDirectCallee() 1192 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1193 return true; 1194 } 1195 1196 if (NumArgs == 7) 1197 return false; 1198 1199 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1200 } 1201 1202 // None of the specific case has been detected, give generic error 1203 S.Diag(TheCall->getBeginLoc(), 1204 diag::err_opencl_enqueue_kernel_incorrect_args); 1205 return true; 1206 } 1207 1208 /// Returns OpenCL access qual. 1209 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1210 return D->getAttr<OpenCLAccessAttr>(); 1211 } 1212 1213 /// Returns true if pipe element type is different from the pointer. 1214 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1215 const Expr *Arg0 = Call->getArg(0); 1216 // First argument type should always be pipe. 1217 if (!Arg0->getType()->isPipeType()) { 1218 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1219 << Call->getDirectCallee() << Arg0->getSourceRange(); 1220 return true; 1221 } 1222 OpenCLAccessAttr *AccessQual = 1223 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1224 // Validates the access qualifier is compatible with the call. 1225 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1226 // read_only and write_only, and assumed to be read_only if no qualifier is 1227 // specified. 1228 switch (Call->getDirectCallee()->getBuiltinID()) { 1229 case Builtin::BIread_pipe: 1230 case Builtin::BIreserve_read_pipe: 1231 case Builtin::BIcommit_read_pipe: 1232 case Builtin::BIwork_group_reserve_read_pipe: 1233 case Builtin::BIsub_group_reserve_read_pipe: 1234 case Builtin::BIwork_group_commit_read_pipe: 1235 case Builtin::BIsub_group_commit_read_pipe: 1236 if (!(!AccessQual || AccessQual->isReadOnly())) { 1237 S.Diag(Arg0->getBeginLoc(), 1238 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1239 << "read_only" << Arg0->getSourceRange(); 1240 return true; 1241 } 1242 break; 1243 case Builtin::BIwrite_pipe: 1244 case Builtin::BIreserve_write_pipe: 1245 case Builtin::BIcommit_write_pipe: 1246 case Builtin::BIwork_group_reserve_write_pipe: 1247 case Builtin::BIsub_group_reserve_write_pipe: 1248 case Builtin::BIwork_group_commit_write_pipe: 1249 case Builtin::BIsub_group_commit_write_pipe: 1250 if (!(AccessQual && AccessQual->isWriteOnly())) { 1251 S.Diag(Arg0->getBeginLoc(), 1252 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1253 << "write_only" << Arg0->getSourceRange(); 1254 return true; 1255 } 1256 break; 1257 default: 1258 break; 1259 } 1260 return false; 1261 } 1262 1263 /// Returns true if pipe element type is different from the pointer. 1264 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1265 const Expr *Arg0 = Call->getArg(0); 1266 const Expr *ArgIdx = Call->getArg(Idx); 1267 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1268 const QualType EltTy = PipeTy->getElementType(); 1269 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1270 // The Idx argument should be a pointer and the type of the pointer and 1271 // the type of pipe element should also be the same. 1272 if (!ArgTy || 1273 !S.Context.hasSameType( 1274 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1275 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1276 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1277 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1278 return true; 1279 } 1280 return false; 1281 } 1282 1283 // Performs semantic analysis for the read/write_pipe call. 1284 // \param S Reference to the semantic analyzer. 1285 // \param Call A pointer to the builtin call. 1286 // \return True if a semantic error has been found, false otherwise. 1287 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1288 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1289 // functions have two forms. 1290 switch (Call->getNumArgs()) { 1291 case 2: 1292 if (checkOpenCLPipeArg(S, Call)) 1293 return true; 1294 // The call with 2 arguments should be 1295 // read/write_pipe(pipe T, T*). 1296 // Check packet type T. 1297 if (checkOpenCLPipePacketType(S, Call, 1)) 1298 return true; 1299 break; 1300 1301 case 4: { 1302 if (checkOpenCLPipeArg(S, Call)) 1303 return true; 1304 // The call with 4 arguments should be 1305 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1306 // Check reserve_id_t. 1307 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1308 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1309 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1310 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1311 return true; 1312 } 1313 1314 // Check the index. 1315 const Expr *Arg2 = Call->getArg(2); 1316 if (!Arg2->getType()->isIntegerType() && 1317 !Arg2->getType()->isUnsignedIntegerType()) { 1318 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1319 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1320 << Arg2->getType() << Arg2->getSourceRange(); 1321 return true; 1322 } 1323 1324 // Check packet type T. 1325 if (checkOpenCLPipePacketType(S, Call, 3)) 1326 return true; 1327 } break; 1328 default: 1329 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1330 << Call->getDirectCallee() << Call->getSourceRange(); 1331 return true; 1332 } 1333 1334 return false; 1335 } 1336 1337 // Performs a semantic analysis on the {work_group_/sub_group_ 1338 // /_}reserve_{read/write}_pipe 1339 // \param S Reference to the semantic analyzer. 1340 // \param Call The call to the builtin function to be analyzed. 1341 // \return True if a semantic error was found, false otherwise. 1342 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1343 if (checkArgCount(S, Call, 2)) 1344 return true; 1345 1346 if (checkOpenCLPipeArg(S, Call)) 1347 return true; 1348 1349 // Check the reserve size. 1350 if (!Call->getArg(1)->getType()->isIntegerType() && 1351 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1352 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1353 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1354 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1355 return true; 1356 } 1357 1358 // Since return type of reserve_read/write_pipe built-in function is 1359 // reserve_id_t, which is not defined in the builtin def file , we used int 1360 // as return type and need to override the return type of these functions. 1361 Call->setType(S.Context.OCLReserveIDTy); 1362 1363 return false; 1364 } 1365 1366 // Performs a semantic analysis on {work_group_/sub_group_ 1367 // /_}commit_{read/write}_pipe 1368 // \param S Reference to the semantic analyzer. 1369 // \param Call The call to the builtin function to be analyzed. 1370 // \return True if a semantic error was found, false otherwise. 1371 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1372 if (checkArgCount(S, Call, 2)) 1373 return true; 1374 1375 if (checkOpenCLPipeArg(S, Call)) 1376 return true; 1377 1378 // Check reserve_id_t. 1379 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1380 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1381 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1382 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1383 return true; 1384 } 1385 1386 return false; 1387 } 1388 1389 // Performs a semantic analysis on the call to built-in Pipe 1390 // Query Functions. 1391 // \param S Reference to the semantic analyzer. 1392 // \param Call The call to the builtin function to be analyzed. 1393 // \return True if a semantic error was found, false otherwise. 1394 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1395 if (checkArgCount(S, Call, 1)) 1396 return true; 1397 1398 if (!Call->getArg(0)->getType()->isPipeType()) { 1399 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1400 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1401 return true; 1402 } 1403 1404 return false; 1405 } 1406 1407 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1408 // Performs semantic analysis for the to_global/local/private call. 1409 // \param S Reference to the semantic analyzer. 1410 // \param BuiltinID ID of the builtin function. 1411 // \param Call A pointer to the builtin call. 1412 // \return True if a semantic error has been found, false otherwise. 1413 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1414 CallExpr *Call) { 1415 if (checkArgCount(S, Call, 1)) 1416 return true; 1417 1418 auto RT = Call->getArg(0)->getType(); 1419 if (!RT->isPointerType() || RT->getPointeeType() 1420 .getAddressSpace() == LangAS::opencl_constant) { 1421 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1422 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1423 return true; 1424 } 1425 1426 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1427 S.Diag(Call->getArg(0)->getBeginLoc(), 1428 diag::warn_opencl_generic_address_space_arg) 1429 << Call->getDirectCallee()->getNameInfo().getAsString() 1430 << Call->getArg(0)->getSourceRange(); 1431 } 1432 1433 RT = RT->getPointeeType(); 1434 auto Qual = RT.getQualifiers(); 1435 switch (BuiltinID) { 1436 case Builtin::BIto_global: 1437 Qual.setAddressSpace(LangAS::opencl_global); 1438 break; 1439 case Builtin::BIto_local: 1440 Qual.setAddressSpace(LangAS::opencl_local); 1441 break; 1442 case Builtin::BIto_private: 1443 Qual.setAddressSpace(LangAS::opencl_private); 1444 break; 1445 default: 1446 llvm_unreachable("Invalid builtin function"); 1447 } 1448 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1449 RT.getUnqualifiedType(), Qual))); 1450 1451 return false; 1452 } 1453 1454 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1455 if (checkArgCount(S, TheCall, 1)) 1456 return ExprError(); 1457 1458 // Compute __builtin_launder's parameter type from the argument. 1459 // The parameter type is: 1460 // * The type of the argument if it's not an array or function type, 1461 // Otherwise, 1462 // * The decayed argument type. 1463 QualType ParamTy = [&]() { 1464 QualType ArgTy = TheCall->getArg(0)->getType(); 1465 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1466 return S.Context.getPointerType(Ty->getElementType()); 1467 if (ArgTy->isFunctionType()) { 1468 return S.Context.getPointerType(ArgTy); 1469 } 1470 return ArgTy; 1471 }(); 1472 1473 TheCall->setType(ParamTy); 1474 1475 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1476 if (!ParamTy->isPointerType()) 1477 return 0; 1478 if (ParamTy->isFunctionPointerType()) 1479 return 1; 1480 if (ParamTy->isVoidPointerType()) 1481 return 2; 1482 return llvm::Optional<unsigned>{}; 1483 }(); 1484 if (DiagSelect.hasValue()) { 1485 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1486 << DiagSelect.getValue() << TheCall->getSourceRange(); 1487 return ExprError(); 1488 } 1489 1490 // We either have an incomplete class type, or we have a class template 1491 // whose instantiation has not been forced. Example: 1492 // 1493 // template <class T> struct Foo { T value; }; 1494 // Foo<int> *p = nullptr; 1495 // auto *d = __builtin_launder(p); 1496 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1497 diag::err_incomplete_type)) 1498 return ExprError(); 1499 1500 assert(ParamTy->getPointeeType()->isObjectType() && 1501 "Unhandled non-object pointer case"); 1502 1503 InitializedEntity Entity = 1504 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1505 ExprResult Arg = 1506 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1507 if (Arg.isInvalid()) 1508 return ExprError(); 1509 TheCall->setArg(0, Arg.get()); 1510 1511 return TheCall; 1512 } 1513 1514 // Emit an error and return true if the current architecture is not in the list 1515 // of supported architectures. 1516 static bool 1517 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1518 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1519 llvm::Triple::ArchType CurArch = 1520 S.getASTContext().getTargetInfo().getTriple().getArch(); 1521 if (llvm::is_contained(SupportedArchs, CurArch)) 1522 return false; 1523 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1524 << TheCall->getSourceRange(); 1525 return true; 1526 } 1527 1528 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1529 SourceLocation CallSiteLoc); 1530 1531 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1532 CallExpr *TheCall) { 1533 switch (TI.getTriple().getArch()) { 1534 default: 1535 // Some builtins don't require additional checking, so just consider these 1536 // acceptable. 1537 return false; 1538 case llvm::Triple::arm: 1539 case llvm::Triple::armeb: 1540 case llvm::Triple::thumb: 1541 case llvm::Triple::thumbeb: 1542 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1543 case llvm::Triple::aarch64: 1544 case llvm::Triple::aarch64_32: 1545 case llvm::Triple::aarch64_be: 1546 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1547 case llvm::Triple::bpfeb: 1548 case llvm::Triple::bpfel: 1549 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1550 case llvm::Triple::hexagon: 1551 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1552 case llvm::Triple::mips: 1553 case llvm::Triple::mipsel: 1554 case llvm::Triple::mips64: 1555 case llvm::Triple::mips64el: 1556 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1557 case llvm::Triple::systemz: 1558 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1559 case llvm::Triple::x86: 1560 case llvm::Triple::x86_64: 1561 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1562 case llvm::Triple::ppc: 1563 case llvm::Triple::ppcle: 1564 case llvm::Triple::ppc64: 1565 case llvm::Triple::ppc64le: 1566 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1567 case llvm::Triple::amdgcn: 1568 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1569 case llvm::Triple::riscv32: 1570 case llvm::Triple::riscv64: 1571 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1572 } 1573 } 1574 1575 ExprResult 1576 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1577 CallExpr *TheCall) { 1578 ExprResult TheCallResult(TheCall); 1579 1580 // Find out if any arguments are required to be integer constant expressions. 1581 unsigned ICEArguments = 0; 1582 ASTContext::GetBuiltinTypeError Error; 1583 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1584 if (Error != ASTContext::GE_None) 1585 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1586 1587 // If any arguments are required to be ICE's, check and diagnose. 1588 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1589 // Skip arguments not required to be ICE's. 1590 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1591 1592 llvm::APSInt Result; 1593 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1594 return true; 1595 ICEArguments &= ~(1 << ArgNo); 1596 } 1597 1598 switch (BuiltinID) { 1599 case Builtin::BI__builtin___CFStringMakeConstantString: 1600 assert(TheCall->getNumArgs() == 1 && 1601 "Wrong # arguments to builtin CFStringMakeConstantString"); 1602 if (CheckObjCString(TheCall->getArg(0))) 1603 return ExprError(); 1604 break; 1605 case Builtin::BI__builtin_ms_va_start: 1606 case Builtin::BI__builtin_stdarg_start: 1607 case Builtin::BI__builtin_va_start: 1608 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1609 return ExprError(); 1610 break; 1611 case Builtin::BI__va_start: { 1612 switch (Context.getTargetInfo().getTriple().getArch()) { 1613 case llvm::Triple::aarch64: 1614 case llvm::Triple::arm: 1615 case llvm::Triple::thumb: 1616 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1617 return ExprError(); 1618 break; 1619 default: 1620 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1621 return ExprError(); 1622 break; 1623 } 1624 break; 1625 } 1626 1627 // The acquire, release, and no fence variants are ARM and AArch64 only. 1628 case Builtin::BI_interlockedbittestandset_acq: 1629 case Builtin::BI_interlockedbittestandset_rel: 1630 case Builtin::BI_interlockedbittestandset_nf: 1631 case Builtin::BI_interlockedbittestandreset_acq: 1632 case Builtin::BI_interlockedbittestandreset_rel: 1633 case Builtin::BI_interlockedbittestandreset_nf: 1634 if (CheckBuiltinTargetSupport( 1635 *this, BuiltinID, TheCall, 1636 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1637 return ExprError(); 1638 break; 1639 1640 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1641 case Builtin::BI_bittest64: 1642 case Builtin::BI_bittestandcomplement64: 1643 case Builtin::BI_bittestandreset64: 1644 case Builtin::BI_bittestandset64: 1645 case Builtin::BI_interlockedbittestandreset64: 1646 case Builtin::BI_interlockedbittestandset64: 1647 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1648 {llvm::Triple::x86_64, llvm::Triple::arm, 1649 llvm::Triple::thumb, llvm::Triple::aarch64})) 1650 return ExprError(); 1651 break; 1652 1653 case Builtin::BI__builtin_isgreater: 1654 case Builtin::BI__builtin_isgreaterequal: 1655 case Builtin::BI__builtin_isless: 1656 case Builtin::BI__builtin_islessequal: 1657 case Builtin::BI__builtin_islessgreater: 1658 case Builtin::BI__builtin_isunordered: 1659 if (SemaBuiltinUnorderedCompare(TheCall)) 1660 return ExprError(); 1661 break; 1662 case Builtin::BI__builtin_fpclassify: 1663 if (SemaBuiltinFPClassification(TheCall, 6)) 1664 return ExprError(); 1665 break; 1666 case Builtin::BI__builtin_isfinite: 1667 case Builtin::BI__builtin_isinf: 1668 case Builtin::BI__builtin_isinf_sign: 1669 case Builtin::BI__builtin_isnan: 1670 case Builtin::BI__builtin_isnormal: 1671 case Builtin::BI__builtin_signbit: 1672 case Builtin::BI__builtin_signbitf: 1673 case Builtin::BI__builtin_signbitl: 1674 if (SemaBuiltinFPClassification(TheCall, 1)) 1675 return ExprError(); 1676 break; 1677 case Builtin::BI__builtin_shufflevector: 1678 return SemaBuiltinShuffleVector(TheCall); 1679 // TheCall will be freed by the smart pointer here, but that's fine, since 1680 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1681 case Builtin::BI__builtin_prefetch: 1682 if (SemaBuiltinPrefetch(TheCall)) 1683 return ExprError(); 1684 break; 1685 case Builtin::BI__builtin_alloca_with_align: 1686 if (SemaBuiltinAllocaWithAlign(TheCall)) 1687 return ExprError(); 1688 LLVM_FALLTHROUGH; 1689 case Builtin::BI__builtin_alloca: 1690 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1691 << TheCall->getDirectCallee(); 1692 break; 1693 case Builtin::BI__arithmetic_fence: 1694 if (SemaBuiltinArithmeticFence(TheCall)) 1695 return ExprError(); 1696 break; 1697 case Builtin::BI__assume: 1698 case Builtin::BI__builtin_assume: 1699 if (SemaBuiltinAssume(TheCall)) 1700 return ExprError(); 1701 break; 1702 case Builtin::BI__builtin_assume_aligned: 1703 if (SemaBuiltinAssumeAligned(TheCall)) 1704 return ExprError(); 1705 break; 1706 case Builtin::BI__builtin_dynamic_object_size: 1707 case Builtin::BI__builtin_object_size: 1708 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1709 return ExprError(); 1710 break; 1711 case Builtin::BI__builtin_longjmp: 1712 if (SemaBuiltinLongjmp(TheCall)) 1713 return ExprError(); 1714 break; 1715 case Builtin::BI__builtin_setjmp: 1716 if (SemaBuiltinSetjmp(TheCall)) 1717 return ExprError(); 1718 break; 1719 case Builtin::BI__builtin_classify_type: 1720 if (checkArgCount(*this, TheCall, 1)) return true; 1721 TheCall->setType(Context.IntTy); 1722 break; 1723 case Builtin::BI__builtin_complex: 1724 if (SemaBuiltinComplex(TheCall)) 1725 return ExprError(); 1726 break; 1727 case Builtin::BI__builtin_constant_p: { 1728 if (checkArgCount(*this, TheCall, 1)) return true; 1729 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1730 if (Arg.isInvalid()) return true; 1731 TheCall->setArg(0, Arg.get()); 1732 TheCall->setType(Context.IntTy); 1733 break; 1734 } 1735 case Builtin::BI__builtin_launder: 1736 return SemaBuiltinLaunder(*this, TheCall); 1737 case Builtin::BI__sync_fetch_and_add: 1738 case Builtin::BI__sync_fetch_and_add_1: 1739 case Builtin::BI__sync_fetch_and_add_2: 1740 case Builtin::BI__sync_fetch_and_add_4: 1741 case Builtin::BI__sync_fetch_and_add_8: 1742 case Builtin::BI__sync_fetch_and_add_16: 1743 case Builtin::BI__sync_fetch_and_sub: 1744 case Builtin::BI__sync_fetch_and_sub_1: 1745 case Builtin::BI__sync_fetch_and_sub_2: 1746 case Builtin::BI__sync_fetch_and_sub_4: 1747 case Builtin::BI__sync_fetch_and_sub_8: 1748 case Builtin::BI__sync_fetch_and_sub_16: 1749 case Builtin::BI__sync_fetch_and_or: 1750 case Builtin::BI__sync_fetch_and_or_1: 1751 case Builtin::BI__sync_fetch_and_or_2: 1752 case Builtin::BI__sync_fetch_and_or_4: 1753 case Builtin::BI__sync_fetch_and_or_8: 1754 case Builtin::BI__sync_fetch_and_or_16: 1755 case Builtin::BI__sync_fetch_and_and: 1756 case Builtin::BI__sync_fetch_and_and_1: 1757 case Builtin::BI__sync_fetch_and_and_2: 1758 case Builtin::BI__sync_fetch_and_and_4: 1759 case Builtin::BI__sync_fetch_and_and_8: 1760 case Builtin::BI__sync_fetch_and_and_16: 1761 case Builtin::BI__sync_fetch_and_xor: 1762 case Builtin::BI__sync_fetch_and_xor_1: 1763 case Builtin::BI__sync_fetch_and_xor_2: 1764 case Builtin::BI__sync_fetch_and_xor_4: 1765 case Builtin::BI__sync_fetch_and_xor_8: 1766 case Builtin::BI__sync_fetch_and_xor_16: 1767 case Builtin::BI__sync_fetch_and_nand: 1768 case Builtin::BI__sync_fetch_and_nand_1: 1769 case Builtin::BI__sync_fetch_and_nand_2: 1770 case Builtin::BI__sync_fetch_and_nand_4: 1771 case Builtin::BI__sync_fetch_and_nand_8: 1772 case Builtin::BI__sync_fetch_and_nand_16: 1773 case Builtin::BI__sync_add_and_fetch: 1774 case Builtin::BI__sync_add_and_fetch_1: 1775 case Builtin::BI__sync_add_and_fetch_2: 1776 case Builtin::BI__sync_add_and_fetch_4: 1777 case Builtin::BI__sync_add_and_fetch_8: 1778 case Builtin::BI__sync_add_and_fetch_16: 1779 case Builtin::BI__sync_sub_and_fetch: 1780 case Builtin::BI__sync_sub_and_fetch_1: 1781 case Builtin::BI__sync_sub_and_fetch_2: 1782 case Builtin::BI__sync_sub_and_fetch_4: 1783 case Builtin::BI__sync_sub_and_fetch_8: 1784 case Builtin::BI__sync_sub_and_fetch_16: 1785 case Builtin::BI__sync_and_and_fetch: 1786 case Builtin::BI__sync_and_and_fetch_1: 1787 case Builtin::BI__sync_and_and_fetch_2: 1788 case Builtin::BI__sync_and_and_fetch_4: 1789 case Builtin::BI__sync_and_and_fetch_8: 1790 case Builtin::BI__sync_and_and_fetch_16: 1791 case Builtin::BI__sync_or_and_fetch: 1792 case Builtin::BI__sync_or_and_fetch_1: 1793 case Builtin::BI__sync_or_and_fetch_2: 1794 case Builtin::BI__sync_or_and_fetch_4: 1795 case Builtin::BI__sync_or_and_fetch_8: 1796 case Builtin::BI__sync_or_and_fetch_16: 1797 case Builtin::BI__sync_xor_and_fetch: 1798 case Builtin::BI__sync_xor_and_fetch_1: 1799 case Builtin::BI__sync_xor_and_fetch_2: 1800 case Builtin::BI__sync_xor_and_fetch_4: 1801 case Builtin::BI__sync_xor_and_fetch_8: 1802 case Builtin::BI__sync_xor_and_fetch_16: 1803 case Builtin::BI__sync_nand_and_fetch: 1804 case Builtin::BI__sync_nand_and_fetch_1: 1805 case Builtin::BI__sync_nand_and_fetch_2: 1806 case Builtin::BI__sync_nand_and_fetch_4: 1807 case Builtin::BI__sync_nand_and_fetch_8: 1808 case Builtin::BI__sync_nand_and_fetch_16: 1809 case Builtin::BI__sync_val_compare_and_swap: 1810 case Builtin::BI__sync_val_compare_and_swap_1: 1811 case Builtin::BI__sync_val_compare_and_swap_2: 1812 case Builtin::BI__sync_val_compare_and_swap_4: 1813 case Builtin::BI__sync_val_compare_and_swap_8: 1814 case Builtin::BI__sync_val_compare_and_swap_16: 1815 case Builtin::BI__sync_bool_compare_and_swap: 1816 case Builtin::BI__sync_bool_compare_and_swap_1: 1817 case Builtin::BI__sync_bool_compare_and_swap_2: 1818 case Builtin::BI__sync_bool_compare_and_swap_4: 1819 case Builtin::BI__sync_bool_compare_and_swap_8: 1820 case Builtin::BI__sync_bool_compare_and_swap_16: 1821 case Builtin::BI__sync_lock_test_and_set: 1822 case Builtin::BI__sync_lock_test_and_set_1: 1823 case Builtin::BI__sync_lock_test_and_set_2: 1824 case Builtin::BI__sync_lock_test_and_set_4: 1825 case Builtin::BI__sync_lock_test_and_set_8: 1826 case Builtin::BI__sync_lock_test_and_set_16: 1827 case Builtin::BI__sync_lock_release: 1828 case Builtin::BI__sync_lock_release_1: 1829 case Builtin::BI__sync_lock_release_2: 1830 case Builtin::BI__sync_lock_release_4: 1831 case Builtin::BI__sync_lock_release_8: 1832 case Builtin::BI__sync_lock_release_16: 1833 case Builtin::BI__sync_swap: 1834 case Builtin::BI__sync_swap_1: 1835 case Builtin::BI__sync_swap_2: 1836 case Builtin::BI__sync_swap_4: 1837 case Builtin::BI__sync_swap_8: 1838 case Builtin::BI__sync_swap_16: 1839 return SemaBuiltinAtomicOverloaded(TheCallResult); 1840 case Builtin::BI__sync_synchronize: 1841 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1842 << TheCall->getCallee()->getSourceRange(); 1843 break; 1844 case Builtin::BI__builtin_nontemporal_load: 1845 case Builtin::BI__builtin_nontemporal_store: 1846 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1847 case Builtin::BI__builtin_memcpy_inline: { 1848 clang::Expr *SizeOp = TheCall->getArg(2); 1849 // We warn about copying to or from `nullptr` pointers when `size` is 1850 // greater than 0. When `size` is value dependent we cannot evaluate its 1851 // value so we bail out. 1852 if (SizeOp->isValueDependent()) 1853 break; 1854 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 1855 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1856 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1857 } 1858 break; 1859 } 1860 #define BUILTIN(ID, TYPE, ATTRS) 1861 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1862 case Builtin::BI##ID: \ 1863 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1864 #include "clang/Basic/Builtins.def" 1865 case Builtin::BI__annotation: 1866 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1867 return ExprError(); 1868 break; 1869 case Builtin::BI__builtin_annotation: 1870 if (SemaBuiltinAnnotation(*this, TheCall)) 1871 return ExprError(); 1872 break; 1873 case Builtin::BI__builtin_addressof: 1874 if (SemaBuiltinAddressof(*this, TheCall)) 1875 return ExprError(); 1876 break; 1877 case Builtin::BI__builtin_is_aligned: 1878 case Builtin::BI__builtin_align_up: 1879 case Builtin::BI__builtin_align_down: 1880 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1881 return ExprError(); 1882 break; 1883 case Builtin::BI__builtin_add_overflow: 1884 case Builtin::BI__builtin_sub_overflow: 1885 case Builtin::BI__builtin_mul_overflow: 1886 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1887 return ExprError(); 1888 break; 1889 case Builtin::BI__builtin_operator_new: 1890 case Builtin::BI__builtin_operator_delete: { 1891 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1892 ExprResult Res = 1893 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1894 if (Res.isInvalid()) 1895 CorrectDelayedTyposInExpr(TheCallResult.get()); 1896 return Res; 1897 } 1898 case Builtin::BI__builtin_dump_struct: { 1899 // We first want to ensure we are called with 2 arguments 1900 if (checkArgCount(*this, TheCall, 2)) 1901 return ExprError(); 1902 // Ensure that the first argument is of type 'struct XX *' 1903 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1904 const QualType PtrArgType = PtrArg->getType(); 1905 if (!PtrArgType->isPointerType() || 1906 !PtrArgType->getPointeeType()->isRecordType()) { 1907 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1908 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1909 << "structure pointer"; 1910 return ExprError(); 1911 } 1912 1913 // Ensure that the second argument is of type 'FunctionType' 1914 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1915 const QualType FnPtrArgType = FnPtrArg->getType(); 1916 if (!FnPtrArgType->isPointerType()) { 1917 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1918 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1919 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1920 return ExprError(); 1921 } 1922 1923 const auto *FuncType = 1924 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1925 1926 if (!FuncType) { 1927 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1928 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1929 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1930 return ExprError(); 1931 } 1932 1933 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1934 if (!FT->getNumParams()) { 1935 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1936 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1937 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1938 return ExprError(); 1939 } 1940 QualType PT = FT->getParamType(0); 1941 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1942 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1943 !PT->getPointeeType().isConstQualified()) { 1944 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1945 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1946 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1947 return ExprError(); 1948 } 1949 } 1950 1951 TheCall->setType(Context.IntTy); 1952 break; 1953 } 1954 case Builtin::BI__builtin_expect_with_probability: { 1955 // We first want to ensure we are called with 3 arguments 1956 if (checkArgCount(*this, TheCall, 3)) 1957 return ExprError(); 1958 // then check probability is constant float in range [0.0, 1.0] 1959 const Expr *ProbArg = TheCall->getArg(2); 1960 SmallVector<PartialDiagnosticAt, 8> Notes; 1961 Expr::EvalResult Eval; 1962 Eval.Diag = &Notes; 1963 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1964 !Eval.Val.isFloat()) { 1965 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1966 << ProbArg->getSourceRange(); 1967 for (const PartialDiagnosticAt &PDiag : Notes) 1968 Diag(PDiag.first, PDiag.second); 1969 return ExprError(); 1970 } 1971 llvm::APFloat Probability = Eval.Val.getFloat(); 1972 bool LoseInfo = false; 1973 Probability.convert(llvm::APFloat::IEEEdouble(), 1974 llvm::RoundingMode::Dynamic, &LoseInfo); 1975 if (!(Probability >= llvm::APFloat(0.0) && 1976 Probability <= llvm::APFloat(1.0))) { 1977 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1978 << ProbArg->getSourceRange(); 1979 return ExprError(); 1980 } 1981 break; 1982 } 1983 case Builtin::BI__builtin_preserve_access_index: 1984 if (SemaBuiltinPreserveAI(*this, TheCall)) 1985 return ExprError(); 1986 break; 1987 case Builtin::BI__builtin_call_with_static_chain: 1988 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1989 return ExprError(); 1990 break; 1991 case Builtin::BI__exception_code: 1992 case Builtin::BI_exception_code: 1993 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1994 diag::err_seh___except_block)) 1995 return ExprError(); 1996 break; 1997 case Builtin::BI__exception_info: 1998 case Builtin::BI_exception_info: 1999 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 2000 diag::err_seh___except_filter)) 2001 return ExprError(); 2002 break; 2003 case Builtin::BI__GetExceptionInfo: 2004 if (checkArgCount(*this, TheCall, 1)) 2005 return ExprError(); 2006 2007 if (CheckCXXThrowOperand( 2008 TheCall->getBeginLoc(), 2009 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 2010 TheCall)) 2011 return ExprError(); 2012 2013 TheCall->setType(Context.VoidPtrTy); 2014 break; 2015 // OpenCL v2.0, s6.13.16 - Pipe functions 2016 case Builtin::BIread_pipe: 2017 case Builtin::BIwrite_pipe: 2018 // Since those two functions are declared with var args, we need a semantic 2019 // check for the argument. 2020 if (SemaBuiltinRWPipe(*this, TheCall)) 2021 return ExprError(); 2022 break; 2023 case Builtin::BIreserve_read_pipe: 2024 case Builtin::BIreserve_write_pipe: 2025 case Builtin::BIwork_group_reserve_read_pipe: 2026 case Builtin::BIwork_group_reserve_write_pipe: 2027 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 2028 return ExprError(); 2029 break; 2030 case Builtin::BIsub_group_reserve_read_pipe: 2031 case Builtin::BIsub_group_reserve_write_pipe: 2032 if (checkOpenCLSubgroupExt(*this, TheCall) || 2033 SemaBuiltinReserveRWPipe(*this, TheCall)) 2034 return ExprError(); 2035 break; 2036 case Builtin::BIcommit_read_pipe: 2037 case Builtin::BIcommit_write_pipe: 2038 case Builtin::BIwork_group_commit_read_pipe: 2039 case Builtin::BIwork_group_commit_write_pipe: 2040 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 2041 return ExprError(); 2042 break; 2043 case Builtin::BIsub_group_commit_read_pipe: 2044 case Builtin::BIsub_group_commit_write_pipe: 2045 if (checkOpenCLSubgroupExt(*this, TheCall) || 2046 SemaBuiltinCommitRWPipe(*this, TheCall)) 2047 return ExprError(); 2048 break; 2049 case Builtin::BIget_pipe_num_packets: 2050 case Builtin::BIget_pipe_max_packets: 2051 if (SemaBuiltinPipePackets(*this, TheCall)) 2052 return ExprError(); 2053 break; 2054 case Builtin::BIto_global: 2055 case Builtin::BIto_local: 2056 case Builtin::BIto_private: 2057 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 2058 return ExprError(); 2059 break; 2060 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 2061 case Builtin::BIenqueue_kernel: 2062 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 2063 return ExprError(); 2064 break; 2065 case Builtin::BIget_kernel_work_group_size: 2066 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 2067 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 2068 return ExprError(); 2069 break; 2070 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 2071 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 2072 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 2073 return ExprError(); 2074 break; 2075 case Builtin::BI__builtin_os_log_format: 2076 Cleanup.setExprNeedsCleanups(true); 2077 LLVM_FALLTHROUGH; 2078 case Builtin::BI__builtin_os_log_format_buffer_size: 2079 if (SemaBuiltinOSLogFormat(TheCall)) 2080 return ExprError(); 2081 break; 2082 case Builtin::BI__builtin_frame_address: 2083 case Builtin::BI__builtin_return_address: { 2084 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 2085 return ExprError(); 2086 2087 // -Wframe-address warning if non-zero passed to builtin 2088 // return/frame address. 2089 Expr::EvalResult Result; 2090 if (!TheCall->getArg(0)->isValueDependent() && 2091 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 2092 Result.Val.getInt() != 0) 2093 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 2094 << ((BuiltinID == Builtin::BI__builtin_return_address) 2095 ? "__builtin_return_address" 2096 : "__builtin_frame_address") 2097 << TheCall->getSourceRange(); 2098 break; 2099 } 2100 2101 case Builtin::BI__builtin_elementwise_abs: 2102 if (SemaBuiltinElementwiseMathOneArg(TheCall)) 2103 return ExprError(); 2104 break; 2105 case Builtin::BI__builtin_elementwise_min: 2106 case Builtin::BI__builtin_elementwise_max: 2107 if (SemaBuiltinElementwiseMath(TheCall)) 2108 return ExprError(); 2109 break; 2110 case Builtin::BI__builtin_reduce_max: 2111 case Builtin::BI__builtin_reduce_min: 2112 if (SemaBuiltinReduceMath(TheCall)) 2113 return ExprError(); 2114 break; 2115 case Builtin::BI__builtin_matrix_transpose: 2116 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 2117 2118 case Builtin::BI__builtin_matrix_column_major_load: 2119 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 2120 2121 case Builtin::BI__builtin_matrix_column_major_store: 2122 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 2123 2124 case Builtin::BI__builtin_get_device_side_mangled_name: { 2125 auto Check = [](CallExpr *TheCall) { 2126 if (TheCall->getNumArgs() != 1) 2127 return false; 2128 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 2129 if (!DRE) 2130 return false; 2131 auto *D = DRE->getDecl(); 2132 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 2133 return false; 2134 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 2135 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2136 }; 2137 if (!Check(TheCall)) { 2138 Diag(TheCall->getBeginLoc(), 2139 diag::err_hip_invalid_args_builtin_mangled_name); 2140 return ExprError(); 2141 } 2142 } 2143 } 2144 2145 // Since the target specific builtins for each arch overlap, only check those 2146 // of the arch we are compiling for. 2147 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2148 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2149 assert(Context.getAuxTargetInfo() && 2150 "Aux Target Builtin, but not an aux target?"); 2151 2152 if (CheckTSBuiltinFunctionCall( 2153 *Context.getAuxTargetInfo(), 2154 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2155 return ExprError(); 2156 } else { 2157 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2158 TheCall)) 2159 return ExprError(); 2160 } 2161 } 2162 2163 return TheCallResult; 2164 } 2165 2166 // Get the valid immediate range for the specified NEON type code. 2167 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2168 NeonTypeFlags Type(t); 2169 int IsQuad = ForceQuad ? true : Type.isQuad(); 2170 switch (Type.getEltType()) { 2171 case NeonTypeFlags::Int8: 2172 case NeonTypeFlags::Poly8: 2173 return shift ? 7 : (8 << IsQuad) - 1; 2174 case NeonTypeFlags::Int16: 2175 case NeonTypeFlags::Poly16: 2176 return shift ? 15 : (4 << IsQuad) - 1; 2177 case NeonTypeFlags::Int32: 2178 return shift ? 31 : (2 << IsQuad) - 1; 2179 case NeonTypeFlags::Int64: 2180 case NeonTypeFlags::Poly64: 2181 return shift ? 63 : (1 << IsQuad) - 1; 2182 case NeonTypeFlags::Poly128: 2183 return shift ? 127 : (1 << IsQuad) - 1; 2184 case NeonTypeFlags::Float16: 2185 assert(!shift && "cannot shift float types!"); 2186 return (4 << IsQuad) - 1; 2187 case NeonTypeFlags::Float32: 2188 assert(!shift && "cannot shift float types!"); 2189 return (2 << IsQuad) - 1; 2190 case NeonTypeFlags::Float64: 2191 assert(!shift && "cannot shift float types!"); 2192 return (1 << IsQuad) - 1; 2193 case NeonTypeFlags::BFloat16: 2194 assert(!shift && "cannot shift float types!"); 2195 return (4 << IsQuad) - 1; 2196 } 2197 llvm_unreachable("Invalid NeonTypeFlag!"); 2198 } 2199 2200 /// getNeonEltType - Return the QualType corresponding to the elements of 2201 /// the vector type specified by the NeonTypeFlags. This is used to check 2202 /// the pointer arguments for Neon load/store intrinsics. 2203 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2204 bool IsPolyUnsigned, bool IsInt64Long) { 2205 switch (Flags.getEltType()) { 2206 case NeonTypeFlags::Int8: 2207 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2208 case NeonTypeFlags::Int16: 2209 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2210 case NeonTypeFlags::Int32: 2211 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2212 case NeonTypeFlags::Int64: 2213 if (IsInt64Long) 2214 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2215 else 2216 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2217 : Context.LongLongTy; 2218 case NeonTypeFlags::Poly8: 2219 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2220 case NeonTypeFlags::Poly16: 2221 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2222 case NeonTypeFlags::Poly64: 2223 if (IsInt64Long) 2224 return Context.UnsignedLongTy; 2225 else 2226 return Context.UnsignedLongLongTy; 2227 case NeonTypeFlags::Poly128: 2228 break; 2229 case NeonTypeFlags::Float16: 2230 return Context.HalfTy; 2231 case NeonTypeFlags::Float32: 2232 return Context.FloatTy; 2233 case NeonTypeFlags::Float64: 2234 return Context.DoubleTy; 2235 case NeonTypeFlags::BFloat16: 2236 return Context.BFloat16Ty; 2237 } 2238 llvm_unreachable("Invalid NeonTypeFlag!"); 2239 } 2240 2241 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2242 // Range check SVE intrinsics that take immediate values. 2243 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2244 2245 switch (BuiltinID) { 2246 default: 2247 return false; 2248 #define GET_SVE_IMMEDIATE_CHECK 2249 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2250 #undef GET_SVE_IMMEDIATE_CHECK 2251 } 2252 2253 // Perform all the immediate checks for this builtin call. 2254 bool HasError = false; 2255 for (auto &I : ImmChecks) { 2256 int ArgNum, CheckTy, ElementSizeInBits; 2257 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2258 2259 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2260 2261 // Function that checks whether the operand (ArgNum) is an immediate 2262 // that is one of the predefined values. 2263 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2264 int ErrDiag) -> bool { 2265 // We can't check the value of a dependent argument. 2266 Expr *Arg = TheCall->getArg(ArgNum); 2267 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2268 return false; 2269 2270 // Check constant-ness first. 2271 llvm::APSInt Imm; 2272 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2273 return true; 2274 2275 if (!CheckImm(Imm.getSExtValue())) 2276 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2277 return false; 2278 }; 2279 2280 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2281 case SVETypeFlags::ImmCheck0_31: 2282 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2283 HasError = true; 2284 break; 2285 case SVETypeFlags::ImmCheck0_13: 2286 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2287 HasError = true; 2288 break; 2289 case SVETypeFlags::ImmCheck1_16: 2290 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2291 HasError = true; 2292 break; 2293 case SVETypeFlags::ImmCheck0_7: 2294 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2295 HasError = true; 2296 break; 2297 case SVETypeFlags::ImmCheckExtract: 2298 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2299 (2048 / ElementSizeInBits) - 1)) 2300 HasError = true; 2301 break; 2302 case SVETypeFlags::ImmCheckShiftRight: 2303 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2304 HasError = true; 2305 break; 2306 case SVETypeFlags::ImmCheckShiftRightNarrow: 2307 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2308 ElementSizeInBits / 2)) 2309 HasError = true; 2310 break; 2311 case SVETypeFlags::ImmCheckShiftLeft: 2312 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2313 ElementSizeInBits - 1)) 2314 HasError = true; 2315 break; 2316 case SVETypeFlags::ImmCheckLaneIndex: 2317 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2318 (128 / (1 * ElementSizeInBits)) - 1)) 2319 HasError = true; 2320 break; 2321 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2322 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2323 (128 / (2 * ElementSizeInBits)) - 1)) 2324 HasError = true; 2325 break; 2326 case SVETypeFlags::ImmCheckLaneIndexDot: 2327 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2328 (128 / (4 * ElementSizeInBits)) - 1)) 2329 HasError = true; 2330 break; 2331 case SVETypeFlags::ImmCheckComplexRot90_270: 2332 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2333 diag::err_rotation_argument_to_cadd)) 2334 HasError = true; 2335 break; 2336 case SVETypeFlags::ImmCheckComplexRotAll90: 2337 if (CheckImmediateInSet( 2338 [](int64_t V) { 2339 return V == 0 || V == 90 || V == 180 || V == 270; 2340 }, 2341 diag::err_rotation_argument_to_cmla)) 2342 HasError = true; 2343 break; 2344 case SVETypeFlags::ImmCheck0_1: 2345 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2346 HasError = true; 2347 break; 2348 case SVETypeFlags::ImmCheck0_2: 2349 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2350 HasError = true; 2351 break; 2352 case SVETypeFlags::ImmCheck0_3: 2353 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2354 HasError = true; 2355 break; 2356 } 2357 } 2358 2359 return HasError; 2360 } 2361 2362 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2363 unsigned BuiltinID, CallExpr *TheCall) { 2364 llvm::APSInt Result; 2365 uint64_t mask = 0; 2366 unsigned TV = 0; 2367 int PtrArgNum = -1; 2368 bool HasConstPtr = false; 2369 switch (BuiltinID) { 2370 #define GET_NEON_OVERLOAD_CHECK 2371 #include "clang/Basic/arm_neon.inc" 2372 #include "clang/Basic/arm_fp16.inc" 2373 #undef GET_NEON_OVERLOAD_CHECK 2374 } 2375 2376 // For NEON intrinsics which are overloaded on vector element type, validate 2377 // the immediate which specifies which variant to emit. 2378 unsigned ImmArg = TheCall->getNumArgs()-1; 2379 if (mask) { 2380 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2381 return true; 2382 2383 TV = Result.getLimitedValue(64); 2384 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2385 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2386 << TheCall->getArg(ImmArg)->getSourceRange(); 2387 } 2388 2389 if (PtrArgNum >= 0) { 2390 // Check that pointer arguments have the specified type. 2391 Expr *Arg = TheCall->getArg(PtrArgNum); 2392 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2393 Arg = ICE->getSubExpr(); 2394 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2395 QualType RHSTy = RHS.get()->getType(); 2396 2397 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2398 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2399 Arch == llvm::Triple::aarch64_32 || 2400 Arch == llvm::Triple::aarch64_be; 2401 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2402 QualType EltTy = 2403 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2404 if (HasConstPtr) 2405 EltTy = EltTy.withConst(); 2406 QualType LHSTy = Context.getPointerType(EltTy); 2407 AssignConvertType ConvTy; 2408 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2409 if (RHS.isInvalid()) 2410 return true; 2411 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2412 RHS.get(), AA_Assigning)) 2413 return true; 2414 } 2415 2416 // For NEON intrinsics which take an immediate value as part of the 2417 // instruction, range check them here. 2418 unsigned i = 0, l = 0, u = 0; 2419 switch (BuiltinID) { 2420 default: 2421 return false; 2422 #define GET_NEON_IMMEDIATE_CHECK 2423 #include "clang/Basic/arm_neon.inc" 2424 #include "clang/Basic/arm_fp16.inc" 2425 #undef GET_NEON_IMMEDIATE_CHECK 2426 } 2427 2428 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2429 } 2430 2431 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2432 switch (BuiltinID) { 2433 default: 2434 return false; 2435 #include "clang/Basic/arm_mve_builtin_sema.inc" 2436 } 2437 } 2438 2439 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2440 CallExpr *TheCall) { 2441 bool Err = false; 2442 switch (BuiltinID) { 2443 default: 2444 return false; 2445 #include "clang/Basic/arm_cde_builtin_sema.inc" 2446 } 2447 2448 if (Err) 2449 return true; 2450 2451 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2452 } 2453 2454 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2455 const Expr *CoprocArg, bool WantCDE) { 2456 if (isConstantEvaluated()) 2457 return false; 2458 2459 // We can't check the value of a dependent argument. 2460 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2461 return false; 2462 2463 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2464 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2465 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2466 2467 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2468 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2469 2470 if (IsCDECoproc != WantCDE) 2471 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2472 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2473 2474 return false; 2475 } 2476 2477 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2478 unsigned MaxWidth) { 2479 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2480 BuiltinID == ARM::BI__builtin_arm_ldaex || 2481 BuiltinID == ARM::BI__builtin_arm_strex || 2482 BuiltinID == ARM::BI__builtin_arm_stlex || 2483 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2484 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2485 BuiltinID == AArch64::BI__builtin_arm_strex || 2486 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2487 "unexpected ARM builtin"); 2488 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2489 BuiltinID == ARM::BI__builtin_arm_ldaex || 2490 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2491 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2492 2493 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2494 2495 // Ensure that we have the proper number of arguments. 2496 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2497 return true; 2498 2499 // Inspect the pointer argument of the atomic builtin. This should always be 2500 // a pointer type, whose element is an integral scalar or pointer type. 2501 // Because it is a pointer type, we don't have to worry about any implicit 2502 // casts here. 2503 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2504 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2505 if (PointerArgRes.isInvalid()) 2506 return true; 2507 PointerArg = PointerArgRes.get(); 2508 2509 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2510 if (!pointerType) { 2511 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2512 << PointerArg->getType() << PointerArg->getSourceRange(); 2513 return true; 2514 } 2515 2516 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2517 // task is to insert the appropriate casts into the AST. First work out just 2518 // what the appropriate type is. 2519 QualType ValType = pointerType->getPointeeType(); 2520 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2521 if (IsLdrex) 2522 AddrType.addConst(); 2523 2524 // Issue a warning if the cast is dodgy. 2525 CastKind CastNeeded = CK_NoOp; 2526 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2527 CastNeeded = CK_BitCast; 2528 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2529 << PointerArg->getType() << Context.getPointerType(AddrType) 2530 << AA_Passing << PointerArg->getSourceRange(); 2531 } 2532 2533 // Finally, do the cast and replace the argument with the corrected version. 2534 AddrType = Context.getPointerType(AddrType); 2535 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2536 if (PointerArgRes.isInvalid()) 2537 return true; 2538 PointerArg = PointerArgRes.get(); 2539 2540 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2541 2542 // In general, we allow ints, floats and pointers to be loaded and stored. 2543 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2544 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2545 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2546 << PointerArg->getType() << PointerArg->getSourceRange(); 2547 return true; 2548 } 2549 2550 // But ARM doesn't have instructions to deal with 128-bit versions. 2551 if (Context.getTypeSize(ValType) > MaxWidth) { 2552 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2553 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2554 << PointerArg->getType() << PointerArg->getSourceRange(); 2555 return true; 2556 } 2557 2558 switch (ValType.getObjCLifetime()) { 2559 case Qualifiers::OCL_None: 2560 case Qualifiers::OCL_ExplicitNone: 2561 // okay 2562 break; 2563 2564 case Qualifiers::OCL_Weak: 2565 case Qualifiers::OCL_Strong: 2566 case Qualifiers::OCL_Autoreleasing: 2567 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2568 << ValType << PointerArg->getSourceRange(); 2569 return true; 2570 } 2571 2572 if (IsLdrex) { 2573 TheCall->setType(ValType); 2574 return false; 2575 } 2576 2577 // Initialize the argument to be stored. 2578 ExprResult ValArg = TheCall->getArg(0); 2579 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2580 Context, ValType, /*consume*/ false); 2581 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2582 if (ValArg.isInvalid()) 2583 return true; 2584 TheCall->setArg(0, ValArg.get()); 2585 2586 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2587 // but the custom checker bypasses all default analysis. 2588 TheCall->setType(Context.IntTy); 2589 return false; 2590 } 2591 2592 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2593 CallExpr *TheCall) { 2594 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2595 BuiltinID == ARM::BI__builtin_arm_ldaex || 2596 BuiltinID == ARM::BI__builtin_arm_strex || 2597 BuiltinID == ARM::BI__builtin_arm_stlex) { 2598 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2599 } 2600 2601 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2602 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2603 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2604 } 2605 2606 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2607 BuiltinID == ARM::BI__builtin_arm_wsr64) 2608 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2609 2610 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2611 BuiltinID == ARM::BI__builtin_arm_rsrp || 2612 BuiltinID == ARM::BI__builtin_arm_wsr || 2613 BuiltinID == ARM::BI__builtin_arm_wsrp) 2614 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2615 2616 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2617 return true; 2618 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2619 return true; 2620 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2621 return true; 2622 2623 // For intrinsics which take an immediate value as part of the instruction, 2624 // range check them here. 2625 // FIXME: VFP Intrinsics should error if VFP not present. 2626 switch (BuiltinID) { 2627 default: return false; 2628 case ARM::BI__builtin_arm_ssat: 2629 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2630 case ARM::BI__builtin_arm_usat: 2631 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2632 case ARM::BI__builtin_arm_ssat16: 2633 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2634 case ARM::BI__builtin_arm_usat16: 2635 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2636 case ARM::BI__builtin_arm_vcvtr_f: 2637 case ARM::BI__builtin_arm_vcvtr_d: 2638 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2639 case ARM::BI__builtin_arm_dmb: 2640 case ARM::BI__builtin_arm_dsb: 2641 case ARM::BI__builtin_arm_isb: 2642 case ARM::BI__builtin_arm_dbg: 2643 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2644 case ARM::BI__builtin_arm_cdp: 2645 case ARM::BI__builtin_arm_cdp2: 2646 case ARM::BI__builtin_arm_mcr: 2647 case ARM::BI__builtin_arm_mcr2: 2648 case ARM::BI__builtin_arm_mrc: 2649 case ARM::BI__builtin_arm_mrc2: 2650 case ARM::BI__builtin_arm_mcrr: 2651 case ARM::BI__builtin_arm_mcrr2: 2652 case ARM::BI__builtin_arm_mrrc: 2653 case ARM::BI__builtin_arm_mrrc2: 2654 case ARM::BI__builtin_arm_ldc: 2655 case ARM::BI__builtin_arm_ldcl: 2656 case ARM::BI__builtin_arm_ldc2: 2657 case ARM::BI__builtin_arm_ldc2l: 2658 case ARM::BI__builtin_arm_stc: 2659 case ARM::BI__builtin_arm_stcl: 2660 case ARM::BI__builtin_arm_stc2: 2661 case ARM::BI__builtin_arm_stc2l: 2662 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2663 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2664 /*WantCDE*/ false); 2665 } 2666 } 2667 2668 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2669 unsigned BuiltinID, 2670 CallExpr *TheCall) { 2671 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2672 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2673 BuiltinID == AArch64::BI__builtin_arm_strex || 2674 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2675 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2676 } 2677 2678 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2679 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2680 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2681 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2682 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2683 } 2684 2685 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2686 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2687 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2688 2689 // Memory Tagging Extensions (MTE) Intrinsics 2690 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2691 BuiltinID == AArch64::BI__builtin_arm_addg || 2692 BuiltinID == AArch64::BI__builtin_arm_gmi || 2693 BuiltinID == AArch64::BI__builtin_arm_ldg || 2694 BuiltinID == AArch64::BI__builtin_arm_stg || 2695 BuiltinID == AArch64::BI__builtin_arm_subp) { 2696 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2697 } 2698 2699 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2700 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2701 BuiltinID == AArch64::BI__builtin_arm_wsr || 2702 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2703 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2704 2705 // Only check the valid encoding range. Any constant in this range would be 2706 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2707 // an exception for incorrect registers. This matches MSVC behavior. 2708 if (BuiltinID == AArch64::BI_ReadStatusReg || 2709 BuiltinID == AArch64::BI_WriteStatusReg) 2710 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2711 2712 if (BuiltinID == AArch64::BI__getReg) 2713 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2714 2715 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2716 return true; 2717 2718 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2719 return true; 2720 2721 // For intrinsics which take an immediate value as part of the instruction, 2722 // range check them here. 2723 unsigned i = 0, l = 0, u = 0; 2724 switch (BuiltinID) { 2725 default: return false; 2726 case AArch64::BI__builtin_arm_dmb: 2727 case AArch64::BI__builtin_arm_dsb: 2728 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2729 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2730 } 2731 2732 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2733 } 2734 2735 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2736 if (Arg->getType()->getAsPlaceholderType()) 2737 return false; 2738 2739 // The first argument needs to be a record field access. 2740 // If it is an array element access, we delay decision 2741 // to BPF backend to check whether the access is a 2742 // field access or not. 2743 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2744 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2745 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2746 } 2747 2748 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2749 QualType VectorTy, QualType EltTy) { 2750 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2751 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2752 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2753 << Call->getSourceRange() << VectorEltTy << EltTy; 2754 return false; 2755 } 2756 return true; 2757 } 2758 2759 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2760 QualType ArgType = Arg->getType(); 2761 if (ArgType->getAsPlaceholderType()) 2762 return false; 2763 2764 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2765 // format: 2766 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2767 // 2. <type> var; 2768 // __builtin_preserve_type_info(var, flag); 2769 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2770 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2771 return false; 2772 2773 // Typedef type. 2774 if (ArgType->getAs<TypedefType>()) 2775 return true; 2776 2777 // Record type or Enum type. 2778 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2779 if (const auto *RT = Ty->getAs<RecordType>()) { 2780 if (!RT->getDecl()->getDeclName().isEmpty()) 2781 return true; 2782 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2783 if (!ET->getDecl()->getDeclName().isEmpty()) 2784 return true; 2785 } 2786 2787 return false; 2788 } 2789 2790 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2791 QualType ArgType = Arg->getType(); 2792 if (ArgType->getAsPlaceholderType()) 2793 return false; 2794 2795 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2796 // format: 2797 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2798 // flag); 2799 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2800 if (!UO) 2801 return false; 2802 2803 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2804 if (!CE) 2805 return false; 2806 if (CE->getCastKind() != CK_IntegralToPointer && 2807 CE->getCastKind() != CK_NullToPointer) 2808 return false; 2809 2810 // The integer must be from an EnumConstantDecl. 2811 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2812 if (!DR) 2813 return false; 2814 2815 const EnumConstantDecl *Enumerator = 2816 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2817 if (!Enumerator) 2818 return false; 2819 2820 // The type must be EnumType. 2821 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2822 const auto *ET = Ty->getAs<EnumType>(); 2823 if (!ET) 2824 return false; 2825 2826 // The enum value must be supported. 2827 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator); 2828 } 2829 2830 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2831 CallExpr *TheCall) { 2832 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2833 BuiltinID == BPF::BI__builtin_btf_type_id || 2834 BuiltinID == BPF::BI__builtin_preserve_type_info || 2835 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2836 "unexpected BPF builtin"); 2837 2838 if (checkArgCount(*this, TheCall, 2)) 2839 return true; 2840 2841 // The second argument needs to be a constant int 2842 Expr *Arg = TheCall->getArg(1); 2843 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2844 diag::kind kind; 2845 if (!Value) { 2846 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2847 kind = diag::err_preserve_field_info_not_const; 2848 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2849 kind = diag::err_btf_type_id_not_const; 2850 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2851 kind = diag::err_preserve_type_info_not_const; 2852 else 2853 kind = diag::err_preserve_enum_value_not_const; 2854 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2855 return true; 2856 } 2857 2858 // The first argument 2859 Arg = TheCall->getArg(0); 2860 bool InvalidArg = false; 2861 bool ReturnUnsignedInt = true; 2862 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2863 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2864 InvalidArg = true; 2865 kind = diag::err_preserve_field_info_not_field; 2866 } 2867 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2868 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2869 InvalidArg = true; 2870 kind = diag::err_preserve_type_info_invalid; 2871 } 2872 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2873 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2874 InvalidArg = true; 2875 kind = diag::err_preserve_enum_value_invalid; 2876 } 2877 ReturnUnsignedInt = false; 2878 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2879 ReturnUnsignedInt = false; 2880 } 2881 2882 if (InvalidArg) { 2883 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2884 return true; 2885 } 2886 2887 if (ReturnUnsignedInt) 2888 TheCall->setType(Context.UnsignedIntTy); 2889 else 2890 TheCall->setType(Context.UnsignedLongTy); 2891 return false; 2892 } 2893 2894 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2895 struct ArgInfo { 2896 uint8_t OpNum; 2897 bool IsSigned; 2898 uint8_t BitWidth; 2899 uint8_t Align; 2900 }; 2901 struct BuiltinInfo { 2902 unsigned BuiltinID; 2903 ArgInfo Infos[2]; 2904 }; 2905 2906 static BuiltinInfo Infos[] = { 2907 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2908 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2909 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2910 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2911 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2912 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2913 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2914 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2915 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2916 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2917 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2918 2919 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2930 2931 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2948 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2950 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2953 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2955 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2956 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2957 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2958 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2959 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2960 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2961 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2962 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2963 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2964 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2965 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2966 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2967 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2968 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2969 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2970 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2971 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2972 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2973 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2974 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2975 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2976 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2977 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2978 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2979 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2980 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2981 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2982 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2983 {{ 1, false, 6, 0 }} }, 2984 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2985 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2986 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2987 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2988 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2989 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2990 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2991 {{ 1, false, 5, 0 }} }, 2992 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2993 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2994 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2995 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2996 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2997 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2998 { 2, false, 5, 0 }} }, 2999 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 3000 { 2, false, 6, 0 }} }, 3001 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 3002 { 3, false, 5, 0 }} }, 3003 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 3004 { 3, false, 6, 0 }} }, 3005 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 3006 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 3007 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 3008 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 3009 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 3010 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 3011 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 3012 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 3013 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 3014 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 3015 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 3016 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 3017 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 3018 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 3019 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 3020 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 3021 {{ 2, false, 4, 0 }, 3022 { 3, false, 5, 0 }} }, 3023 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 3024 {{ 2, false, 4, 0 }, 3025 { 3, false, 5, 0 }} }, 3026 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 3027 {{ 2, false, 4, 0 }, 3028 { 3, false, 5, 0 }} }, 3029 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 3030 {{ 2, false, 4, 0 }, 3031 { 3, false, 5, 0 }} }, 3032 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 3033 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 3034 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 3035 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 3036 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 3037 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 3038 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 3039 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 3040 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 3041 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 3042 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 3043 { 2, false, 5, 0 }} }, 3044 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 3045 { 2, false, 6, 0 }} }, 3046 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 3047 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 3048 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 3049 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 3050 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 3051 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 3052 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 3053 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 3054 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 3055 {{ 1, false, 4, 0 }} }, 3056 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 3057 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 3058 {{ 1, false, 4, 0 }} }, 3059 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 3060 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 3061 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 3062 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 3063 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 3064 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 3065 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 3066 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 3067 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 3068 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 3069 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 3070 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 3071 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 3072 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 3073 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 3074 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 3075 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 3076 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 3077 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 3078 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 3079 {{ 3, false, 1, 0 }} }, 3080 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 3081 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 3082 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 3083 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 3084 {{ 3, false, 1, 0 }} }, 3085 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 3086 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 3087 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 3088 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 3089 {{ 3, false, 1, 0 }} }, 3090 }; 3091 3092 // Use a dynamically initialized static to sort the table exactly once on 3093 // first run. 3094 static const bool SortOnce = 3095 (llvm::sort(Infos, 3096 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 3097 return LHS.BuiltinID < RHS.BuiltinID; 3098 }), 3099 true); 3100 (void)SortOnce; 3101 3102 const BuiltinInfo *F = llvm::partition_point( 3103 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 3104 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 3105 return false; 3106 3107 bool Error = false; 3108 3109 for (const ArgInfo &A : F->Infos) { 3110 // Ignore empty ArgInfo elements. 3111 if (A.BitWidth == 0) 3112 continue; 3113 3114 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 3115 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 3116 if (!A.Align) { 3117 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3118 } else { 3119 unsigned M = 1 << A.Align; 3120 Min *= M; 3121 Max *= M; 3122 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3123 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 3124 } 3125 } 3126 return Error; 3127 } 3128 3129 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3130 CallExpr *TheCall) { 3131 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3132 } 3133 3134 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3135 unsigned BuiltinID, CallExpr *TheCall) { 3136 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3137 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3138 } 3139 3140 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3141 CallExpr *TheCall) { 3142 3143 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3144 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3145 if (!TI.hasFeature("dsp")) 3146 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3147 } 3148 3149 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3150 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3151 if (!TI.hasFeature("dspr2")) 3152 return Diag(TheCall->getBeginLoc(), 3153 diag::err_mips_builtin_requires_dspr2); 3154 } 3155 3156 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3157 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3158 if (!TI.hasFeature("msa")) 3159 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3160 } 3161 3162 return false; 3163 } 3164 3165 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3166 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3167 // ordering for DSP is unspecified. MSA is ordered by the data format used 3168 // by the underlying instruction i.e., df/m, df/n and then by size. 3169 // 3170 // FIXME: The size tests here should instead be tablegen'd along with the 3171 // definitions from include/clang/Basic/BuiltinsMips.def. 3172 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3173 // be too. 3174 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3175 unsigned i = 0, l = 0, u = 0, m = 0; 3176 switch (BuiltinID) { 3177 default: return false; 3178 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3179 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3180 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3181 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3182 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3183 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3184 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3185 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3186 // df/m field. 3187 // These intrinsics take an unsigned 3 bit immediate. 3188 case Mips::BI__builtin_msa_bclri_b: 3189 case Mips::BI__builtin_msa_bnegi_b: 3190 case Mips::BI__builtin_msa_bseti_b: 3191 case Mips::BI__builtin_msa_sat_s_b: 3192 case Mips::BI__builtin_msa_sat_u_b: 3193 case Mips::BI__builtin_msa_slli_b: 3194 case Mips::BI__builtin_msa_srai_b: 3195 case Mips::BI__builtin_msa_srari_b: 3196 case Mips::BI__builtin_msa_srli_b: 3197 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3198 case Mips::BI__builtin_msa_binsli_b: 3199 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3200 // These intrinsics take an unsigned 4 bit immediate. 3201 case Mips::BI__builtin_msa_bclri_h: 3202 case Mips::BI__builtin_msa_bnegi_h: 3203 case Mips::BI__builtin_msa_bseti_h: 3204 case Mips::BI__builtin_msa_sat_s_h: 3205 case Mips::BI__builtin_msa_sat_u_h: 3206 case Mips::BI__builtin_msa_slli_h: 3207 case Mips::BI__builtin_msa_srai_h: 3208 case Mips::BI__builtin_msa_srari_h: 3209 case Mips::BI__builtin_msa_srli_h: 3210 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3211 case Mips::BI__builtin_msa_binsli_h: 3212 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3213 // These intrinsics take an unsigned 5 bit immediate. 3214 // The first block of intrinsics actually have an unsigned 5 bit field, 3215 // not a df/n field. 3216 case Mips::BI__builtin_msa_cfcmsa: 3217 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3218 case Mips::BI__builtin_msa_clei_u_b: 3219 case Mips::BI__builtin_msa_clei_u_h: 3220 case Mips::BI__builtin_msa_clei_u_w: 3221 case Mips::BI__builtin_msa_clei_u_d: 3222 case Mips::BI__builtin_msa_clti_u_b: 3223 case Mips::BI__builtin_msa_clti_u_h: 3224 case Mips::BI__builtin_msa_clti_u_w: 3225 case Mips::BI__builtin_msa_clti_u_d: 3226 case Mips::BI__builtin_msa_maxi_u_b: 3227 case Mips::BI__builtin_msa_maxi_u_h: 3228 case Mips::BI__builtin_msa_maxi_u_w: 3229 case Mips::BI__builtin_msa_maxi_u_d: 3230 case Mips::BI__builtin_msa_mini_u_b: 3231 case Mips::BI__builtin_msa_mini_u_h: 3232 case Mips::BI__builtin_msa_mini_u_w: 3233 case Mips::BI__builtin_msa_mini_u_d: 3234 case Mips::BI__builtin_msa_addvi_b: 3235 case Mips::BI__builtin_msa_addvi_h: 3236 case Mips::BI__builtin_msa_addvi_w: 3237 case Mips::BI__builtin_msa_addvi_d: 3238 case Mips::BI__builtin_msa_bclri_w: 3239 case Mips::BI__builtin_msa_bnegi_w: 3240 case Mips::BI__builtin_msa_bseti_w: 3241 case Mips::BI__builtin_msa_sat_s_w: 3242 case Mips::BI__builtin_msa_sat_u_w: 3243 case Mips::BI__builtin_msa_slli_w: 3244 case Mips::BI__builtin_msa_srai_w: 3245 case Mips::BI__builtin_msa_srari_w: 3246 case Mips::BI__builtin_msa_srli_w: 3247 case Mips::BI__builtin_msa_srlri_w: 3248 case Mips::BI__builtin_msa_subvi_b: 3249 case Mips::BI__builtin_msa_subvi_h: 3250 case Mips::BI__builtin_msa_subvi_w: 3251 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3252 case Mips::BI__builtin_msa_binsli_w: 3253 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3254 // These intrinsics take an unsigned 6 bit immediate. 3255 case Mips::BI__builtin_msa_bclri_d: 3256 case Mips::BI__builtin_msa_bnegi_d: 3257 case Mips::BI__builtin_msa_bseti_d: 3258 case Mips::BI__builtin_msa_sat_s_d: 3259 case Mips::BI__builtin_msa_sat_u_d: 3260 case Mips::BI__builtin_msa_slli_d: 3261 case Mips::BI__builtin_msa_srai_d: 3262 case Mips::BI__builtin_msa_srari_d: 3263 case Mips::BI__builtin_msa_srli_d: 3264 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3265 case Mips::BI__builtin_msa_binsli_d: 3266 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3267 // These intrinsics take a signed 5 bit immediate. 3268 case Mips::BI__builtin_msa_ceqi_b: 3269 case Mips::BI__builtin_msa_ceqi_h: 3270 case Mips::BI__builtin_msa_ceqi_w: 3271 case Mips::BI__builtin_msa_ceqi_d: 3272 case Mips::BI__builtin_msa_clti_s_b: 3273 case Mips::BI__builtin_msa_clti_s_h: 3274 case Mips::BI__builtin_msa_clti_s_w: 3275 case Mips::BI__builtin_msa_clti_s_d: 3276 case Mips::BI__builtin_msa_clei_s_b: 3277 case Mips::BI__builtin_msa_clei_s_h: 3278 case Mips::BI__builtin_msa_clei_s_w: 3279 case Mips::BI__builtin_msa_clei_s_d: 3280 case Mips::BI__builtin_msa_maxi_s_b: 3281 case Mips::BI__builtin_msa_maxi_s_h: 3282 case Mips::BI__builtin_msa_maxi_s_w: 3283 case Mips::BI__builtin_msa_maxi_s_d: 3284 case Mips::BI__builtin_msa_mini_s_b: 3285 case Mips::BI__builtin_msa_mini_s_h: 3286 case Mips::BI__builtin_msa_mini_s_w: 3287 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3288 // These intrinsics take an unsigned 8 bit immediate. 3289 case Mips::BI__builtin_msa_andi_b: 3290 case Mips::BI__builtin_msa_nori_b: 3291 case Mips::BI__builtin_msa_ori_b: 3292 case Mips::BI__builtin_msa_shf_b: 3293 case Mips::BI__builtin_msa_shf_h: 3294 case Mips::BI__builtin_msa_shf_w: 3295 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3296 case Mips::BI__builtin_msa_bseli_b: 3297 case Mips::BI__builtin_msa_bmnzi_b: 3298 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3299 // df/n format 3300 // These intrinsics take an unsigned 4 bit immediate. 3301 case Mips::BI__builtin_msa_copy_s_b: 3302 case Mips::BI__builtin_msa_copy_u_b: 3303 case Mips::BI__builtin_msa_insve_b: 3304 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3305 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3306 // These intrinsics take an unsigned 3 bit immediate. 3307 case Mips::BI__builtin_msa_copy_s_h: 3308 case Mips::BI__builtin_msa_copy_u_h: 3309 case Mips::BI__builtin_msa_insve_h: 3310 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3311 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3312 // These intrinsics take an unsigned 2 bit immediate. 3313 case Mips::BI__builtin_msa_copy_s_w: 3314 case Mips::BI__builtin_msa_copy_u_w: 3315 case Mips::BI__builtin_msa_insve_w: 3316 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3317 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3318 // These intrinsics take an unsigned 1 bit immediate. 3319 case Mips::BI__builtin_msa_copy_s_d: 3320 case Mips::BI__builtin_msa_copy_u_d: 3321 case Mips::BI__builtin_msa_insve_d: 3322 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3323 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3324 // Memory offsets and immediate loads. 3325 // These intrinsics take a signed 10 bit immediate. 3326 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3327 case Mips::BI__builtin_msa_ldi_h: 3328 case Mips::BI__builtin_msa_ldi_w: 3329 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3330 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3331 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3332 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3333 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3334 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3335 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3336 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3337 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3338 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3339 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3340 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3341 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3342 } 3343 3344 if (!m) 3345 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3346 3347 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3348 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3349 } 3350 3351 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3352 /// advancing the pointer over the consumed characters. The decoded type is 3353 /// returned. If the decoded type represents a constant integer with a 3354 /// constraint on its value then Mask is set to that value. The type descriptors 3355 /// used in Str are specific to PPC MMA builtins and are documented in the file 3356 /// defining the PPC builtins. 3357 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3358 unsigned &Mask) { 3359 bool RequireICE = false; 3360 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3361 switch (*Str++) { 3362 case 'V': 3363 return Context.getVectorType(Context.UnsignedCharTy, 16, 3364 VectorType::VectorKind::AltiVecVector); 3365 case 'i': { 3366 char *End; 3367 unsigned size = strtoul(Str, &End, 10); 3368 assert(End != Str && "Missing constant parameter constraint"); 3369 Str = End; 3370 Mask = size; 3371 return Context.IntTy; 3372 } 3373 case 'W': { 3374 char *End; 3375 unsigned size = strtoul(Str, &End, 10); 3376 assert(End != Str && "Missing PowerPC MMA type size"); 3377 Str = End; 3378 QualType Type; 3379 switch (size) { 3380 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3381 case size: Type = Context.Id##Ty; break; 3382 #include "clang/Basic/PPCTypes.def" 3383 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3384 } 3385 bool CheckVectorArgs = false; 3386 while (!CheckVectorArgs) { 3387 switch (*Str++) { 3388 case '*': 3389 Type = Context.getPointerType(Type); 3390 break; 3391 case 'C': 3392 Type = Type.withConst(); 3393 break; 3394 default: 3395 CheckVectorArgs = true; 3396 --Str; 3397 break; 3398 } 3399 } 3400 return Type; 3401 } 3402 default: 3403 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3404 } 3405 } 3406 3407 static bool isPPC_64Builtin(unsigned BuiltinID) { 3408 // These builtins only work on PPC 64bit targets. 3409 switch (BuiltinID) { 3410 case PPC::BI__builtin_divde: 3411 case PPC::BI__builtin_divdeu: 3412 case PPC::BI__builtin_bpermd: 3413 case PPC::BI__builtin_ppc_ldarx: 3414 case PPC::BI__builtin_ppc_stdcx: 3415 case PPC::BI__builtin_ppc_tdw: 3416 case PPC::BI__builtin_ppc_trapd: 3417 case PPC::BI__builtin_ppc_cmpeqb: 3418 case PPC::BI__builtin_ppc_setb: 3419 case PPC::BI__builtin_ppc_mulhd: 3420 case PPC::BI__builtin_ppc_mulhdu: 3421 case PPC::BI__builtin_ppc_maddhd: 3422 case PPC::BI__builtin_ppc_maddhdu: 3423 case PPC::BI__builtin_ppc_maddld: 3424 case PPC::BI__builtin_ppc_load8r: 3425 case PPC::BI__builtin_ppc_store8r: 3426 case PPC::BI__builtin_ppc_insert_exp: 3427 case PPC::BI__builtin_ppc_extract_sig: 3428 case PPC::BI__builtin_ppc_addex: 3429 case PPC::BI__builtin_darn: 3430 case PPC::BI__builtin_darn_raw: 3431 case PPC::BI__builtin_ppc_compare_and_swaplp: 3432 case PPC::BI__builtin_ppc_fetch_and_addlp: 3433 case PPC::BI__builtin_ppc_fetch_and_andlp: 3434 case PPC::BI__builtin_ppc_fetch_and_orlp: 3435 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3436 return true; 3437 } 3438 return false; 3439 } 3440 3441 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3442 StringRef FeatureToCheck, unsigned DiagID, 3443 StringRef DiagArg = "") { 3444 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3445 return false; 3446 3447 if (DiagArg.empty()) 3448 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3449 else 3450 S.Diag(TheCall->getBeginLoc(), DiagID) 3451 << DiagArg << TheCall->getSourceRange(); 3452 3453 return true; 3454 } 3455 3456 /// Returns true if the argument consists of one contiguous run of 1s with any 3457 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3458 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3459 /// since all 1s are not contiguous. 3460 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3461 llvm::APSInt Result; 3462 // We can't check the value of a dependent argument. 3463 Expr *Arg = TheCall->getArg(ArgNum); 3464 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3465 return false; 3466 3467 // Check constant-ness first. 3468 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3469 return true; 3470 3471 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3472 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3473 return false; 3474 3475 return Diag(TheCall->getBeginLoc(), 3476 diag::err_argument_not_contiguous_bit_field) 3477 << ArgNum << Arg->getSourceRange(); 3478 } 3479 3480 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3481 CallExpr *TheCall) { 3482 unsigned i = 0, l = 0, u = 0; 3483 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3484 llvm::APSInt Result; 3485 3486 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3487 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3488 << TheCall->getSourceRange(); 3489 3490 switch (BuiltinID) { 3491 default: return false; 3492 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3493 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3494 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3495 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3496 case PPC::BI__builtin_altivec_dss: 3497 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3498 case PPC::BI__builtin_tbegin: 3499 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3500 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3501 case PPC::BI__builtin_tabortwc: 3502 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3503 case PPC::BI__builtin_tabortwci: 3504 case PPC::BI__builtin_tabortdci: 3505 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3506 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3507 // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05', 3508 // __builtin_(un)pack_longdouble are available only if long double uses IBM 3509 // extended double representation. 3510 case PPC::BI__builtin_unpack_longdouble: 3511 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1)) 3512 return true; 3513 LLVM_FALLTHROUGH; 3514 case PPC::BI__builtin_pack_longdouble: 3515 if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble()) 3516 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi) 3517 << "ibmlongdouble"; 3518 return false; 3519 case PPC::BI__builtin_altivec_dst: 3520 case PPC::BI__builtin_altivec_dstt: 3521 case PPC::BI__builtin_altivec_dstst: 3522 case PPC::BI__builtin_altivec_dststt: 3523 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3524 case PPC::BI__builtin_vsx_xxpermdi: 3525 case PPC::BI__builtin_vsx_xxsldwi: 3526 return SemaBuiltinVSX(TheCall); 3527 case PPC::BI__builtin_divwe: 3528 case PPC::BI__builtin_divweu: 3529 case PPC::BI__builtin_divde: 3530 case PPC::BI__builtin_divdeu: 3531 return SemaFeatureCheck(*this, TheCall, "extdiv", 3532 diag::err_ppc_builtin_only_on_arch, "7"); 3533 case PPC::BI__builtin_bpermd: 3534 return SemaFeatureCheck(*this, TheCall, "bpermd", 3535 diag::err_ppc_builtin_only_on_arch, "7"); 3536 case PPC::BI__builtin_unpack_vector_int128: 3537 return SemaFeatureCheck(*this, TheCall, "vsx", 3538 diag::err_ppc_builtin_only_on_arch, "7") || 3539 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3540 case PPC::BI__builtin_pack_vector_int128: 3541 return SemaFeatureCheck(*this, TheCall, "vsx", 3542 diag::err_ppc_builtin_only_on_arch, "7"); 3543 case PPC::BI__builtin_altivec_vgnb: 3544 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3545 case PPC::BI__builtin_altivec_vec_replace_elt: 3546 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3547 QualType VecTy = TheCall->getArg(0)->getType(); 3548 QualType EltTy = TheCall->getArg(1)->getType(); 3549 unsigned Width = Context.getIntWidth(EltTy); 3550 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3551 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3552 } 3553 case PPC::BI__builtin_vsx_xxeval: 3554 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3555 case PPC::BI__builtin_altivec_vsldbi: 3556 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3557 case PPC::BI__builtin_altivec_vsrdbi: 3558 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3559 case PPC::BI__builtin_vsx_xxpermx: 3560 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3561 case PPC::BI__builtin_ppc_tw: 3562 case PPC::BI__builtin_ppc_tdw: 3563 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3564 case PPC::BI__builtin_ppc_cmpeqb: 3565 case PPC::BI__builtin_ppc_setb: 3566 case PPC::BI__builtin_ppc_maddhd: 3567 case PPC::BI__builtin_ppc_maddhdu: 3568 case PPC::BI__builtin_ppc_maddld: 3569 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3570 diag::err_ppc_builtin_only_on_arch, "9"); 3571 case PPC::BI__builtin_ppc_cmprb: 3572 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3573 diag::err_ppc_builtin_only_on_arch, "9") || 3574 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3575 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3576 // be a constant that represents a contiguous bit field. 3577 case PPC::BI__builtin_ppc_rlwnm: 3578 return SemaValueIsRunOfOnes(TheCall, 2); 3579 case PPC::BI__builtin_ppc_rlwimi: 3580 case PPC::BI__builtin_ppc_rldimi: 3581 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3582 SemaValueIsRunOfOnes(TheCall, 3); 3583 case PPC::BI__builtin_ppc_extract_exp: 3584 case PPC::BI__builtin_ppc_extract_sig: 3585 case PPC::BI__builtin_ppc_insert_exp: 3586 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3587 diag::err_ppc_builtin_only_on_arch, "9"); 3588 case PPC::BI__builtin_ppc_addex: { 3589 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3590 diag::err_ppc_builtin_only_on_arch, "9") || 3591 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3592 return true; 3593 // Output warning for reserved values 1 to 3. 3594 int ArgValue = 3595 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3596 if (ArgValue != 0) 3597 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3598 << ArgValue; 3599 return false; 3600 } 3601 case PPC::BI__builtin_ppc_mtfsb0: 3602 case PPC::BI__builtin_ppc_mtfsb1: 3603 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3604 case PPC::BI__builtin_ppc_mtfsf: 3605 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3606 case PPC::BI__builtin_ppc_mtfsfi: 3607 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3608 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3609 case PPC::BI__builtin_ppc_alignx: 3610 return SemaBuiltinConstantArgPower2(TheCall, 0); 3611 case PPC::BI__builtin_ppc_rdlam: 3612 return SemaValueIsRunOfOnes(TheCall, 2); 3613 case PPC::BI__builtin_ppc_icbt: 3614 case PPC::BI__builtin_ppc_sthcx: 3615 case PPC::BI__builtin_ppc_stbcx: 3616 case PPC::BI__builtin_ppc_lharx: 3617 case PPC::BI__builtin_ppc_lbarx: 3618 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3619 diag::err_ppc_builtin_only_on_arch, "8"); 3620 case PPC::BI__builtin_vsx_ldrmb: 3621 case PPC::BI__builtin_vsx_strmb: 3622 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3623 diag::err_ppc_builtin_only_on_arch, "8") || 3624 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3625 case PPC::BI__builtin_altivec_vcntmbb: 3626 case PPC::BI__builtin_altivec_vcntmbh: 3627 case PPC::BI__builtin_altivec_vcntmbw: 3628 case PPC::BI__builtin_altivec_vcntmbd: 3629 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3630 case PPC::BI__builtin_darn: 3631 case PPC::BI__builtin_darn_raw: 3632 case PPC::BI__builtin_darn_32: 3633 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3634 diag::err_ppc_builtin_only_on_arch, "9"); 3635 case PPC::BI__builtin_vsx_xxgenpcvbm: 3636 case PPC::BI__builtin_vsx_xxgenpcvhm: 3637 case PPC::BI__builtin_vsx_xxgenpcvwm: 3638 case PPC::BI__builtin_vsx_xxgenpcvdm: 3639 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3640 case PPC::BI__builtin_ppc_compare_exp_uo: 3641 case PPC::BI__builtin_ppc_compare_exp_lt: 3642 case PPC::BI__builtin_ppc_compare_exp_gt: 3643 case PPC::BI__builtin_ppc_compare_exp_eq: 3644 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3645 diag::err_ppc_builtin_only_on_arch, "9") || 3646 SemaFeatureCheck(*this, TheCall, "vsx", 3647 diag::err_ppc_builtin_requires_vsx); 3648 case PPC::BI__builtin_ppc_test_data_class: { 3649 // Check if the first argument of the __builtin_ppc_test_data_class call is 3650 // valid. The argument must be either a 'float' or a 'double'. 3651 QualType ArgType = TheCall->getArg(0)->getType(); 3652 if (ArgType != QualType(Context.FloatTy) && 3653 ArgType != QualType(Context.DoubleTy)) 3654 return Diag(TheCall->getBeginLoc(), 3655 diag::err_ppc_invalid_test_data_class_type); 3656 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3657 diag::err_ppc_builtin_only_on_arch, "9") || 3658 SemaFeatureCheck(*this, TheCall, "vsx", 3659 diag::err_ppc_builtin_requires_vsx) || 3660 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3661 } 3662 case PPC::BI__builtin_ppc_load8r: 3663 case PPC::BI__builtin_ppc_store8r: 3664 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 3665 diag::err_ppc_builtin_only_on_arch, "7"); 3666 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3667 case PPC::BI__builtin_##Name: \ 3668 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types); 3669 #include "clang/Basic/BuiltinsPPC.def" 3670 } 3671 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3672 } 3673 3674 // Check if the given type is a non-pointer PPC MMA type. This function is used 3675 // in Sema to prevent invalid uses of restricted PPC MMA types. 3676 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3677 if (Type->isPointerType() || Type->isArrayType()) 3678 return false; 3679 3680 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3681 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3682 if (false 3683 #include "clang/Basic/PPCTypes.def" 3684 ) { 3685 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3686 return true; 3687 } 3688 return false; 3689 } 3690 3691 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3692 CallExpr *TheCall) { 3693 // position of memory order and scope arguments in the builtin 3694 unsigned OrderIndex, ScopeIndex; 3695 switch (BuiltinID) { 3696 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3697 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3698 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3699 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3700 OrderIndex = 2; 3701 ScopeIndex = 3; 3702 break; 3703 case AMDGPU::BI__builtin_amdgcn_fence: 3704 OrderIndex = 0; 3705 ScopeIndex = 1; 3706 break; 3707 default: 3708 return false; 3709 } 3710 3711 ExprResult Arg = TheCall->getArg(OrderIndex); 3712 auto ArgExpr = Arg.get(); 3713 Expr::EvalResult ArgResult; 3714 3715 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3716 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3717 << ArgExpr->getType(); 3718 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3719 3720 // Check validity of memory ordering as per C11 / C++11's memody model. 3721 // Only fence needs check. Atomic dec/inc allow all memory orders. 3722 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3723 return Diag(ArgExpr->getBeginLoc(), 3724 diag::warn_atomic_op_has_invalid_memory_order) 3725 << ArgExpr->getSourceRange(); 3726 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3727 case llvm::AtomicOrderingCABI::relaxed: 3728 case llvm::AtomicOrderingCABI::consume: 3729 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3730 return Diag(ArgExpr->getBeginLoc(), 3731 diag::warn_atomic_op_has_invalid_memory_order) 3732 << ArgExpr->getSourceRange(); 3733 break; 3734 case llvm::AtomicOrderingCABI::acquire: 3735 case llvm::AtomicOrderingCABI::release: 3736 case llvm::AtomicOrderingCABI::acq_rel: 3737 case llvm::AtomicOrderingCABI::seq_cst: 3738 break; 3739 } 3740 3741 Arg = TheCall->getArg(ScopeIndex); 3742 ArgExpr = Arg.get(); 3743 Expr::EvalResult ArgResult1; 3744 // Check that sync scope is a constant literal 3745 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3746 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3747 << ArgExpr->getType(); 3748 3749 return false; 3750 } 3751 3752 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3753 llvm::APSInt Result; 3754 3755 // We can't check the value of a dependent argument. 3756 Expr *Arg = TheCall->getArg(ArgNum); 3757 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3758 return false; 3759 3760 // Check constant-ness first. 3761 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3762 return true; 3763 3764 int64_t Val = Result.getSExtValue(); 3765 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3766 return false; 3767 3768 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3769 << Arg->getSourceRange(); 3770 } 3771 3772 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3773 unsigned BuiltinID, 3774 CallExpr *TheCall) { 3775 // CodeGenFunction can also detect this, but this gives a better error 3776 // message. 3777 bool FeatureMissing = false; 3778 SmallVector<StringRef> ReqFeatures; 3779 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3780 Features.split(ReqFeatures, ','); 3781 3782 // Check if each required feature is included 3783 for (StringRef F : ReqFeatures) { 3784 if (TI.hasFeature(F)) 3785 continue; 3786 3787 // If the feature is 64bit, alter the string so it will print better in 3788 // the diagnostic. 3789 if (F == "64bit") 3790 F = "RV64"; 3791 3792 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3793 F.consume_front("experimental-"); 3794 std::string FeatureStr = F.str(); 3795 FeatureStr[0] = std::toupper(FeatureStr[0]); 3796 3797 // Error message 3798 FeatureMissing = true; 3799 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3800 << TheCall->getSourceRange() << StringRef(FeatureStr); 3801 } 3802 3803 if (FeatureMissing) 3804 return true; 3805 3806 switch (BuiltinID) { 3807 case RISCVVector::BI__builtin_rvv_vsetvli: 3808 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3809 CheckRISCVLMUL(TheCall, 2); 3810 case RISCVVector::BI__builtin_rvv_vsetvlimax: 3811 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3812 CheckRISCVLMUL(TheCall, 1); 3813 } 3814 3815 return false; 3816 } 3817 3818 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3819 CallExpr *TheCall) { 3820 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3821 Expr *Arg = TheCall->getArg(0); 3822 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3823 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3824 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3825 << Arg->getSourceRange(); 3826 } 3827 3828 // For intrinsics which take an immediate value as part of the instruction, 3829 // range check them here. 3830 unsigned i = 0, l = 0, u = 0; 3831 switch (BuiltinID) { 3832 default: return false; 3833 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3834 case SystemZ::BI__builtin_s390_verimb: 3835 case SystemZ::BI__builtin_s390_verimh: 3836 case SystemZ::BI__builtin_s390_verimf: 3837 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3838 case SystemZ::BI__builtin_s390_vfaeb: 3839 case SystemZ::BI__builtin_s390_vfaeh: 3840 case SystemZ::BI__builtin_s390_vfaef: 3841 case SystemZ::BI__builtin_s390_vfaebs: 3842 case SystemZ::BI__builtin_s390_vfaehs: 3843 case SystemZ::BI__builtin_s390_vfaefs: 3844 case SystemZ::BI__builtin_s390_vfaezb: 3845 case SystemZ::BI__builtin_s390_vfaezh: 3846 case SystemZ::BI__builtin_s390_vfaezf: 3847 case SystemZ::BI__builtin_s390_vfaezbs: 3848 case SystemZ::BI__builtin_s390_vfaezhs: 3849 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3850 case SystemZ::BI__builtin_s390_vfisb: 3851 case SystemZ::BI__builtin_s390_vfidb: 3852 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3853 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3854 case SystemZ::BI__builtin_s390_vftcisb: 3855 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3856 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3857 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3858 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3859 case SystemZ::BI__builtin_s390_vstrcb: 3860 case SystemZ::BI__builtin_s390_vstrch: 3861 case SystemZ::BI__builtin_s390_vstrcf: 3862 case SystemZ::BI__builtin_s390_vstrczb: 3863 case SystemZ::BI__builtin_s390_vstrczh: 3864 case SystemZ::BI__builtin_s390_vstrczf: 3865 case SystemZ::BI__builtin_s390_vstrcbs: 3866 case SystemZ::BI__builtin_s390_vstrchs: 3867 case SystemZ::BI__builtin_s390_vstrcfs: 3868 case SystemZ::BI__builtin_s390_vstrczbs: 3869 case SystemZ::BI__builtin_s390_vstrczhs: 3870 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3871 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3872 case SystemZ::BI__builtin_s390_vfminsb: 3873 case SystemZ::BI__builtin_s390_vfmaxsb: 3874 case SystemZ::BI__builtin_s390_vfmindb: 3875 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3876 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3877 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3878 case SystemZ::BI__builtin_s390_vclfnhs: 3879 case SystemZ::BI__builtin_s390_vclfnls: 3880 case SystemZ::BI__builtin_s390_vcfn: 3881 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 3882 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 3883 } 3884 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3885 } 3886 3887 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3888 /// This checks that the target supports __builtin_cpu_supports and 3889 /// that the string argument is constant and valid. 3890 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3891 CallExpr *TheCall) { 3892 Expr *Arg = TheCall->getArg(0); 3893 3894 // Check if the argument is a string literal. 3895 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3896 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3897 << Arg->getSourceRange(); 3898 3899 // Check the contents of the string. 3900 StringRef Feature = 3901 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3902 if (!TI.validateCpuSupports(Feature)) 3903 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3904 << Arg->getSourceRange(); 3905 return false; 3906 } 3907 3908 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3909 /// This checks that the target supports __builtin_cpu_is and 3910 /// that the string argument is constant and valid. 3911 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3912 Expr *Arg = TheCall->getArg(0); 3913 3914 // Check if the argument is a string literal. 3915 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3916 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3917 << Arg->getSourceRange(); 3918 3919 // Check the contents of the string. 3920 StringRef Feature = 3921 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3922 if (!TI.validateCpuIs(Feature)) 3923 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3924 << Arg->getSourceRange(); 3925 return false; 3926 } 3927 3928 // Check if the rounding mode is legal. 3929 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3930 // Indicates if this instruction has rounding control or just SAE. 3931 bool HasRC = false; 3932 3933 unsigned ArgNum = 0; 3934 switch (BuiltinID) { 3935 default: 3936 return false; 3937 case X86::BI__builtin_ia32_vcvttsd2si32: 3938 case X86::BI__builtin_ia32_vcvttsd2si64: 3939 case X86::BI__builtin_ia32_vcvttsd2usi32: 3940 case X86::BI__builtin_ia32_vcvttsd2usi64: 3941 case X86::BI__builtin_ia32_vcvttss2si32: 3942 case X86::BI__builtin_ia32_vcvttss2si64: 3943 case X86::BI__builtin_ia32_vcvttss2usi32: 3944 case X86::BI__builtin_ia32_vcvttss2usi64: 3945 case X86::BI__builtin_ia32_vcvttsh2si32: 3946 case X86::BI__builtin_ia32_vcvttsh2si64: 3947 case X86::BI__builtin_ia32_vcvttsh2usi32: 3948 case X86::BI__builtin_ia32_vcvttsh2usi64: 3949 ArgNum = 1; 3950 break; 3951 case X86::BI__builtin_ia32_maxpd512: 3952 case X86::BI__builtin_ia32_maxps512: 3953 case X86::BI__builtin_ia32_minpd512: 3954 case X86::BI__builtin_ia32_minps512: 3955 case X86::BI__builtin_ia32_maxph512: 3956 case X86::BI__builtin_ia32_minph512: 3957 ArgNum = 2; 3958 break; 3959 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 3960 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 3961 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3962 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3963 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3964 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3965 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3966 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3967 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3968 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3969 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3970 case X86::BI__builtin_ia32_vcvttph2w512_mask: 3971 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 3972 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 3973 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 3974 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 3975 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 3976 case X86::BI__builtin_ia32_exp2pd_mask: 3977 case X86::BI__builtin_ia32_exp2ps_mask: 3978 case X86::BI__builtin_ia32_getexppd512_mask: 3979 case X86::BI__builtin_ia32_getexpps512_mask: 3980 case X86::BI__builtin_ia32_getexpph512_mask: 3981 case X86::BI__builtin_ia32_rcp28pd_mask: 3982 case X86::BI__builtin_ia32_rcp28ps_mask: 3983 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3984 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3985 case X86::BI__builtin_ia32_vcomisd: 3986 case X86::BI__builtin_ia32_vcomiss: 3987 case X86::BI__builtin_ia32_vcomish: 3988 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3989 ArgNum = 3; 3990 break; 3991 case X86::BI__builtin_ia32_cmppd512_mask: 3992 case X86::BI__builtin_ia32_cmpps512_mask: 3993 case X86::BI__builtin_ia32_cmpsd_mask: 3994 case X86::BI__builtin_ia32_cmpss_mask: 3995 case X86::BI__builtin_ia32_cmpsh_mask: 3996 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 3997 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 3998 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3999 case X86::BI__builtin_ia32_getexpsd128_round_mask: 4000 case X86::BI__builtin_ia32_getexpss128_round_mask: 4001 case X86::BI__builtin_ia32_getexpsh128_round_mask: 4002 case X86::BI__builtin_ia32_getmantpd512_mask: 4003 case X86::BI__builtin_ia32_getmantps512_mask: 4004 case X86::BI__builtin_ia32_getmantph512_mask: 4005 case X86::BI__builtin_ia32_maxsd_round_mask: 4006 case X86::BI__builtin_ia32_maxss_round_mask: 4007 case X86::BI__builtin_ia32_maxsh_round_mask: 4008 case X86::BI__builtin_ia32_minsd_round_mask: 4009 case X86::BI__builtin_ia32_minss_round_mask: 4010 case X86::BI__builtin_ia32_minsh_round_mask: 4011 case X86::BI__builtin_ia32_rcp28sd_round_mask: 4012 case X86::BI__builtin_ia32_rcp28ss_round_mask: 4013 case X86::BI__builtin_ia32_reducepd512_mask: 4014 case X86::BI__builtin_ia32_reduceps512_mask: 4015 case X86::BI__builtin_ia32_reduceph512_mask: 4016 case X86::BI__builtin_ia32_rndscalepd_mask: 4017 case X86::BI__builtin_ia32_rndscaleps_mask: 4018 case X86::BI__builtin_ia32_rndscaleph_mask: 4019 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 4020 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 4021 ArgNum = 4; 4022 break; 4023 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4024 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4025 case X86::BI__builtin_ia32_fixupimmps512_mask: 4026 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4027 case X86::BI__builtin_ia32_fixupimmsd_mask: 4028 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4029 case X86::BI__builtin_ia32_fixupimmss_mask: 4030 case X86::BI__builtin_ia32_fixupimmss_maskz: 4031 case X86::BI__builtin_ia32_getmantsd_round_mask: 4032 case X86::BI__builtin_ia32_getmantss_round_mask: 4033 case X86::BI__builtin_ia32_getmantsh_round_mask: 4034 case X86::BI__builtin_ia32_rangepd512_mask: 4035 case X86::BI__builtin_ia32_rangeps512_mask: 4036 case X86::BI__builtin_ia32_rangesd128_round_mask: 4037 case X86::BI__builtin_ia32_rangess128_round_mask: 4038 case X86::BI__builtin_ia32_reducesd_mask: 4039 case X86::BI__builtin_ia32_reducess_mask: 4040 case X86::BI__builtin_ia32_reducesh_mask: 4041 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4042 case X86::BI__builtin_ia32_rndscaless_round_mask: 4043 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4044 ArgNum = 5; 4045 break; 4046 case X86::BI__builtin_ia32_vcvtsd2si64: 4047 case X86::BI__builtin_ia32_vcvtsd2si32: 4048 case X86::BI__builtin_ia32_vcvtsd2usi32: 4049 case X86::BI__builtin_ia32_vcvtsd2usi64: 4050 case X86::BI__builtin_ia32_vcvtss2si32: 4051 case X86::BI__builtin_ia32_vcvtss2si64: 4052 case X86::BI__builtin_ia32_vcvtss2usi32: 4053 case X86::BI__builtin_ia32_vcvtss2usi64: 4054 case X86::BI__builtin_ia32_vcvtsh2si32: 4055 case X86::BI__builtin_ia32_vcvtsh2si64: 4056 case X86::BI__builtin_ia32_vcvtsh2usi32: 4057 case X86::BI__builtin_ia32_vcvtsh2usi64: 4058 case X86::BI__builtin_ia32_sqrtpd512: 4059 case X86::BI__builtin_ia32_sqrtps512: 4060 case X86::BI__builtin_ia32_sqrtph512: 4061 ArgNum = 1; 4062 HasRC = true; 4063 break; 4064 case X86::BI__builtin_ia32_addph512: 4065 case X86::BI__builtin_ia32_divph512: 4066 case X86::BI__builtin_ia32_mulph512: 4067 case X86::BI__builtin_ia32_subph512: 4068 case X86::BI__builtin_ia32_addpd512: 4069 case X86::BI__builtin_ia32_addps512: 4070 case X86::BI__builtin_ia32_divpd512: 4071 case X86::BI__builtin_ia32_divps512: 4072 case X86::BI__builtin_ia32_mulpd512: 4073 case X86::BI__builtin_ia32_mulps512: 4074 case X86::BI__builtin_ia32_subpd512: 4075 case X86::BI__builtin_ia32_subps512: 4076 case X86::BI__builtin_ia32_cvtsi2sd64: 4077 case X86::BI__builtin_ia32_cvtsi2ss32: 4078 case X86::BI__builtin_ia32_cvtsi2ss64: 4079 case X86::BI__builtin_ia32_cvtusi2sd64: 4080 case X86::BI__builtin_ia32_cvtusi2ss32: 4081 case X86::BI__builtin_ia32_cvtusi2ss64: 4082 case X86::BI__builtin_ia32_vcvtusi2sh: 4083 case X86::BI__builtin_ia32_vcvtusi642sh: 4084 case X86::BI__builtin_ia32_vcvtsi2sh: 4085 case X86::BI__builtin_ia32_vcvtsi642sh: 4086 ArgNum = 2; 4087 HasRC = true; 4088 break; 4089 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4090 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4091 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4092 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4093 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4094 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4095 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4096 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4097 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4098 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4099 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4100 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4101 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4102 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4103 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4104 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4105 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4106 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4107 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4108 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4109 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4110 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4111 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4112 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4113 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4114 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4115 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4116 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4117 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4118 ArgNum = 3; 4119 HasRC = true; 4120 break; 4121 case X86::BI__builtin_ia32_addsh_round_mask: 4122 case X86::BI__builtin_ia32_addss_round_mask: 4123 case X86::BI__builtin_ia32_addsd_round_mask: 4124 case X86::BI__builtin_ia32_divsh_round_mask: 4125 case X86::BI__builtin_ia32_divss_round_mask: 4126 case X86::BI__builtin_ia32_divsd_round_mask: 4127 case X86::BI__builtin_ia32_mulsh_round_mask: 4128 case X86::BI__builtin_ia32_mulss_round_mask: 4129 case X86::BI__builtin_ia32_mulsd_round_mask: 4130 case X86::BI__builtin_ia32_subsh_round_mask: 4131 case X86::BI__builtin_ia32_subss_round_mask: 4132 case X86::BI__builtin_ia32_subsd_round_mask: 4133 case X86::BI__builtin_ia32_scalefph512_mask: 4134 case X86::BI__builtin_ia32_scalefpd512_mask: 4135 case X86::BI__builtin_ia32_scalefps512_mask: 4136 case X86::BI__builtin_ia32_scalefsd_round_mask: 4137 case X86::BI__builtin_ia32_scalefss_round_mask: 4138 case X86::BI__builtin_ia32_scalefsh_round_mask: 4139 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4140 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4141 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4142 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4143 case X86::BI__builtin_ia32_sqrtss_round_mask: 4144 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4145 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4146 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4147 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4148 case X86::BI__builtin_ia32_vfmaddss3_mask: 4149 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4150 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4151 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4152 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4153 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4154 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4155 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4156 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4157 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4158 case X86::BI__builtin_ia32_vfmaddps512_mask: 4159 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4160 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4161 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4162 case X86::BI__builtin_ia32_vfmaddph512_mask: 4163 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4164 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4165 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4166 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4167 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4168 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4169 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4170 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4171 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4172 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4173 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4174 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4175 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4176 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4177 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4178 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4179 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4180 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4181 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4182 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4183 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4184 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4185 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4186 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4187 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4188 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4189 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4190 case X86::BI__builtin_ia32_vfmulcsh_mask: 4191 case X86::BI__builtin_ia32_vfmulcph512_mask: 4192 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4193 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4194 ArgNum = 4; 4195 HasRC = true; 4196 break; 4197 } 4198 4199 llvm::APSInt Result; 4200 4201 // We can't check the value of a dependent argument. 4202 Expr *Arg = TheCall->getArg(ArgNum); 4203 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4204 return false; 4205 4206 // Check constant-ness first. 4207 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4208 return true; 4209 4210 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4211 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4212 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4213 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4214 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4215 Result == 8/*ROUND_NO_EXC*/ || 4216 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4217 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4218 return false; 4219 4220 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4221 << Arg->getSourceRange(); 4222 } 4223 4224 // Check if the gather/scatter scale is legal. 4225 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4226 CallExpr *TheCall) { 4227 unsigned ArgNum = 0; 4228 switch (BuiltinID) { 4229 default: 4230 return false; 4231 case X86::BI__builtin_ia32_gatherpfdpd: 4232 case X86::BI__builtin_ia32_gatherpfdps: 4233 case X86::BI__builtin_ia32_gatherpfqpd: 4234 case X86::BI__builtin_ia32_gatherpfqps: 4235 case X86::BI__builtin_ia32_scatterpfdpd: 4236 case X86::BI__builtin_ia32_scatterpfdps: 4237 case X86::BI__builtin_ia32_scatterpfqpd: 4238 case X86::BI__builtin_ia32_scatterpfqps: 4239 ArgNum = 3; 4240 break; 4241 case X86::BI__builtin_ia32_gatherd_pd: 4242 case X86::BI__builtin_ia32_gatherd_pd256: 4243 case X86::BI__builtin_ia32_gatherq_pd: 4244 case X86::BI__builtin_ia32_gatherq_pd256: 4245 case X86::BI__builtin_ia32_gatherd_ps: 4246 case X86::BI__builtin_ia32_gatherd_ps256: 4247 case X86::BI__builtin_ia32_gatherq_ps: 4248 case X86::BI__builtin_ia32_gatherq_ps256: 4249 case X86::BI__builtin_ia32_gatherd_q: 4250 case X86::BI__builtin_ia32_gatherd_q256: 4251 case X86::BI__builtin_ia32_gatherq_q: 4252 case X86::BI__builtin_ia32_gatherq_q256: 4253 case X86::BI__builtin_ia32_gatherd_d: 4254 case X86::BI__builtin_ia32_gatherd_d256: 4255 case X86::BI__builtin_ia32_gatherq_d: 4256 case X86::BI__builtin_ia32_gatherq_d256: 4257 case X86::BI__builtin_ia32_gather3div2df: 4258 case X86::BI__builtin_ia32_gather3div2di: 4259 case X86::BI__builtin_ia32_gather3div4df: 4260 case X86::BI__builtin_ia32_gather3div4di: 4261 case X86::BI__builtin_ia32_gather3div4sf: 4262 case X86::BI__builtin_ia32_gather3div4si: 4263 case X86::BI__builtin_ia32_gather3div8sf: 4264 case X86::BI__builtin_ia32_gather3div8si: 4265 case X86::BI__builtin_ia32_gather3siv2df: 4266 case X86::BI__builtin_ia32_gather3siv2di: 4267 case X86::BI__builtin_ia32_gather3siv4df: 4268 case X86::BI__builtin_ia32_gather3siv4di: 4269 case X86::BI__builtin_ia32_gather3siv4sf: 4270 case X86::BI__builtin_ia32_gather3siv4si: 4271 case X86::BI__builtin_ia32_gather3siv8sf: 4272 case X86::BI__builtin_ia32_gather3siv8si: 4273 case X86::BI__builtin_ia32_gathersiv8df: 4274 case X86::BI__builtin_ia32_gathersiv16sf: 4275 case X86::BI__builtin_ia32_gatherdiv8df: 4276 case X86::BI__builtin_ia32_gatherdiv16sf: 4277 case X86::BI__builtin_ia32_gathersiv8di: 4278 case X86::BI__builtin_ia32_gathersiv16si: 4279 case X86::BI__builtin_ia32_gatherdiv8di: 4280 case X86::BI__builtin_ia32_gatherdiv16si: 4281 case X86::BI__builtin_ia32_scatterdiv2df: 4282 case X86::BI__builtin_ia32_scatterdiv2di: 4283 case X86::BI__builtin_ia32_scatterdiv4df: 4284 case X86::BI__builtin_ia32_scatterdiv4di: 4285 case X86::BI__builtin_ia32_scatterdiv4sf: 4286 case X86::BI__builtin_ia32_scatterdiv4si: 4287 case X86::BI__builtin_ia32_scatterdiv8sf: 4288 case X86::BI__builtin_ia32_scatterdiv8si: 4289 case X86::BI__builtin_ia32_scattersiv2df: 4290 case X86::BI__builtin_ia32_scattersiv2di: 4291 case X86::BI__builtin_ia32_scattersiv4df: 4292 case X86::BI__builtin_ia32_scattersiv4di: 4293 case X86::BI__builtin_ia32_scattersiv4sf: 4294 case X86::BI__builtin_ia32_scattersiv4si: 4295 case X86::BI__builtin_ia32_scattersiv8sf: 4296 case X86::BI__builtin_ia32_scattersiv8si: 4297 case X86::BI__builtin_ia32_scattersiv8df: 4298 case X86::BI__builtin_ia32_scattersiv16sf: 4299 case X86::BI__builtin_ia32_scatterdiv8df: 4300 case X86::BI__builtin_ia32_scatterdiv16sf: 4301 case X86::BI__builtin_ia32_scattersiv8di: 4302 case X86::BI__builtin_ia32_scattersiv16si: 4303 case X86::BI__builtin_ia32_scatterdiv8di: 4304 case X86::BI__builtin_ia32_scatterdiv16si: 4305 ArgNum = 4; 4306 break; 4307 } 4308 4309 llvm::APSInt Result; 4310 4311 // We can't check the value of a dependent argument. 4312 Expr *Arg = TheCall->getArg(ArgNum); 4313 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4314 return false; 4315 4316 // Check constant-ness first. 4317 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4318 return true; 4319 4320 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4321 return false; 4322 4323 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4324 << Arg->getSourceRange(); 4325 } 4326 4327 enum { TileRegLow = 0, TileRegHigh = 7 }; 4328 4329 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4330 ArrayRef<int> ArgNums) { 4331 for (int ArgNum : ArgNums) { 4332 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4333 return true; 4334 } 4335 return false; 4336 } 4337 4338 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4339 ArrayRef<int> ArgNums) { 4340 // Because the max number of tile register is TileRegHigh + 1, so here we use 4341 // each bit to represent the usage of them in bitset. 4342 std::bitset<TileRegHigh + 1> ArgValues; 4343 for (int ArgNum : ArgNums) { 4344 Expr *Arg = TheCall->getArg(ArgNum); 4345 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4346 continue; 4347 4348 llvm::APSInt Result; 4349 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4350 return true; 4351 int ArgExtValue = Result.getExtValue(); 4352 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4353 "Incorrect tile register num."); 4354 if (ArgValues.test(ArgExtValue)) 4355 return Diag(TheCall->getBeginLoc(), 4356 diag::err_x86_builtin_tile_arg_duplicate) 4357 << TheCall->getArg(ArgNum)->getSourceRange(); 4358 ArgValues.set(ArgExtValue); 4359 } 4360 return false; 4361 } 4362 4363 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4364 ArrayRef<int> ArgNums) { 4365 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4366 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4367 } 4368 4369 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4370 switch (BuiltinID) { 4371 default: 4372 return false; 4373 case X86::BI__builtin_ia32_tileloadd64: 4374 case X86::BI__builtin_ia32_tileloaddt164: 4375 case X86::BI__builtin_ia32_tilestored64: 4376 case X86::BI__builtin_ia32_tilezero: 4377 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4378 case X86::BI__builtin_ia32_tdpbssd: 4379 case X86::BI__builtin_ia32_tdpbsud: 4380 case X86::BI__builtin_ia32_tdpbusd: 4381 case X86::BI__builtin_ia32_tdpbuud: 4382 case X86::BI__builtin_ia32_tdpbf16ps: 4383 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4384 } 4385 } 4386 static bool isX86_32Builtin(unsigned BuiltinID) { 4387 // These builtins only work on x86-32 targets. 4388 switch (BuiltinID) { 4389 case X86::BI__builtin_ia32_readeflags_u32: 4390 case X86::BI__builtin_ia32_writeeflags_u32: 4391 return true; 4392 } 4393 4394 return false; 4395 } 4396 4397 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4398 CallExpr *TheCall) { 4399 if (BuiltinID == X86::BI__builtin_cpu_supports) 4400 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4401 4402 if (BuiltinID == X86::BI__builtin_cpu_is) 4403 return SemaBuiltinCpuIs(*this, TI, TheCall); 4404 4405 // Check for 32-bit only builtins on a 64-bit target. 4406 const llvm::Triple &TT = TI.getTriple(); 4407 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4408 return Diag(TheCall->getCallee()->getBeginLoc(), 4409 diag::err_32_bit_builtin_64_bit_tgt); 4410 4411 // If the intrinsic has rounding or SAE make sure its valid. 4412 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4413 return true; 4414 4415 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4416 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4417 return true; 4418 4419 // If the intrinsic has a tile arguments, make sure they are valid. 4420 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4421 return true; 4422 4423 // For intrinsics which take an immediate value as part of the instruction, 4424 // range check them here. 4425 int i = 0, l = 0, u = 0; 4426 switch (BuiltinID) { 4427 default: 4428 return false; 4429 case X86::BI__builtin_ia32_vec_ext_v2si: 4430 case X86::BI__builtin_ia32_vec_ext_v2di: 4431 case X86::BI__builtin_ia32_vextractf128_pd256: 4432 case X86::BI__builtin_ia32_vextractf128_ps256: 4433 case X86::BI__builtin_ia32_vextractf128_si256: 4434 case X86::BI__builtin_ia32_extract128i256: 4435 case X86::BI__builtin_ia32_extractf64x4_mask: 4436 case X86::BI__builtin_ia32_extracti64x4_mask: 4437 case X86::BI__builtin_ia32_extractf32x8_mask: 4438 case X86::BI__builtin_ia32_extracti32x8_mask: 4439 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4440 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4441 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4442 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4443 i = 1; l = 0; u = 1; 4444 break; 4445 case X86::BI__builtin_ia32_vec_set_v2di: 4446 case X86::BI__builtin_ia32_vinsertf128_pd256: 4447 case X86::BI__builtin_ia32_vinsertf128_ps256: 4448 case X86::BI__builtin_ia32_vinsertf128_si256: 4449 case X86::BI__builtin_ia32_insert128i256: 4450 case X86::BI__builtin_ia32_insertf32x8: 4451 case X86::BI__builtin_ia32_inserti32x8: 4452 case X86::BI__builtin_ia32_insertf64x4: 4453 case X86::BI__builtin_ia32_inserti64x4: 4454 case X86::BI__builtin_ia32_insertf64x2_256: 4455 case X86::BI__builtin_ia32_inserti64x2_256: 4456 case X86::BI__builtin_ia32_insertf32x4_256: 4457 case X86::BI__builtin_ia32_inserti32x4_256: 4458 i = 2; l = 0; u = 1; 4459 break; 4460 case X86::BI__builtin_ia32_vpermilpd: 4461 case X86::BI__builtin_ia32_vec_ext_v4hi: 4462 case X86::BI__builtin_ia32_vec_ext_v4si: 4463 case X86::BI__builtin_ia32_vec_ext_v4sf: 4464 case X86::BI__builtin_ia32_vec_ext_v4di: 4465 case X86::BI__builtin_ia32_extractf32x4_mask: 4466 case X86::BI__builtin_ia32_extracti32x4_mask: 4467 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4468 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4469 i = 1; l = 0; u = 3; 4470 break; 4471 case X86::BI_mm_prefetch: 4472 case X86::BI__builtin_ia32_vec_ext_v8hi: 4473 case X86::BI__builtin_ia32_vec_ext_v8si: 4474 i = 1; l = 0; u = 7; 4475 break; 4476 case X86::BI__builtin_ia32_sha1rnds4: 4477 case X86::BI__builtin_ia32_blendpd: 4478 case X86::BI__builtin_ia32_shufpd: 4479 case X86::BI__builtin_ia32_vec_set_v4hi: 4480 case X86::BI__builtin_ia32_vec_set_v4si: 4481 case X86::BI__builtin_ia32_vec_set_v4di: 4482 case X86::BI__builtin_ia32_shuf_f32x4_256: 4483 case X86::BI__builtin_ia32_shuf_f64x2_256: 4484 case X86::BI__builtin_ia32_shuf_i32x4_256: 4485 case X86::BI__builtin_ia32_shuf_i64x2_256: 4486 case X86::BI__builtin_ia32_insertf64x2_512: 4487 case X86::BI__builtin_ia32_inserti64x2_512: 4488 case X86::BI__builtin_ia32_insertf32x4: 4489 case X86::BI__builtin_ia32_inserti32x4: 4490 i = 2; l = 0; u = 3; 4491 break; 4492 case X86::BI__builtin_ia32_vpermil2pd: 4493 case X86::BI__builtin_ia32_vpermil2pd256: 4494 case X86::BI__builtin_ia32_vpermil2ps: 4495 case X86::BI__builtin_ia32_vpermil2ps256: 4496 i = 3; l = 0; u = 3; 4497 break; 4498 case X86::BI__builtin_ia32_cmpb128_mask: 4499 case X86::BI__builtin_ia32_cmpw128_mask: 4500 case X86::BI__builtin_ia32_cmpd128_mask: 4501 case X86::BI__builtin_ia32_cmpq128_mask: 4502 case X86::BI__builtin_ia32_cmpb256_mask: 4503 case X86::BI__builtin_ia32_cmpw256_mask: 4504 case X86::BI__builtin_ia32_cmpd256_mask: 4505 case X86::BI__builtin_ia32_cmpq256_mask: 4506 case X86::BI__builtin_ia32_cmpb512_mask: 4507 case X86::BI__builtin_ia32_cmpw512_mask: 4508 case X86::BI__builtin_ia32_cmpd512_mask: 4509 case X86::BI__builtin_ia32_cmpq512_mask: 4510 case X86::BI__builtin_ia32_ucmpb128_mask: 4511 case X86::BI__builtin_ia32_ucmpw128_mask: 4512 case X86::BI__builtin_ia32_ucmpd128_mask: 4513 case X86::BI__builtin_ia32_ucmpq128_mask: 4514 case X86::BI__builtin_ia32_ucmpb256_mask: 4515 case X86::BI__builtin_ia32_ucmpw256_mask: 4516 case X86::BI__builtin_ia32_ucmpd256_mask: 4517 case X86::BI__builtin_ia32_ucmpq256_mask: 4518 case X86::BI__builtin_ia32_ucmpb512_mask: 4519 case X86::BI__builtin_ia32_ucmpw512_mask: 4520 case X86::BI__builtin_ia32_ucmpd512_mask: 4521 case X86::BI__builtin_ia32_ucmpq512_mask: 4522 case X86::BI__builtin_ia32_vpcomub: 4523 case X86::BI__builtin_ia32_vpcomuw: 4524 case X86::BI__builtin_ia32_vpcomud: 4525 case X86::BI__builtin_ia32_vpcomuq: 4526 case X86::BI__builtin_ia32_vpcomb: 4527 case X86::BI__builtin_ia32_vpcomw: 4528 case X86::BI__builtin_ia32_vpcomd: 4529 case X86::BI__builtin_ia32_vpcomq: 4530 case X86::BI__builtin_ia32_vec_set_v8hi: 4531 case X86::BI__builtin_ia32_vec_set_v8si: 4532 i = 2; l = 0; u = 7; 4533 break; 4534 case X86::BI__builtin_ia32_vpermilpd256: 4535 case X86::BI__builtin_ia32_roundps: 4536 case X86::BI__builtin_ia32_roundpd: 4537 case X86::BI__builtin_ia32_roundps256: 4538 case X86::BI__builtin_ia32_roundpd256: 4539 case X86::BI__builtin_ia32_getmantpd128_mask: 4540 case X86::BI__builtin_ia32_getmantpd256_mask: 4541 case X86::BI__builtin_ia32_getmantps128_mask: 4542 case X86::BI__builtin_ia32_getmantps256_mask: 4543 case X86::BI__builtin_ia32_getmantpd512_mask: 4544 case X86::BI__builtin_ia32_getmantps512_mask: 4545 case X86::BI__builtin_ia32_getmantph128_mask: 4546 case X86::BI__builtin_ia32_getmantph256_mask: 4547 case X86::BI__builtin_ia32_getmantph512_mask: 4548 case X86::BI__builtin_ia32_vec_ext_v16qi: 4549 case X86::BI__builtin_ia32_vec_ext_v16hi: 4550 i = 1; l = 0; u = 15; 4551 break; 4552 case X86::BI__builtin_ia32_pblendd128: 4553 case X86::BI__builtin_ia32_blendps: 4554 case X86::BI__builtin_ia32_blendpd256: 4555 case X86::BI__builtin_ia32_shufpd256: 4556 case X86::BI__builtin_ia32_roundss: 4557 case X86::BI__builtin_ia32_roundsd: 4558 case X86::BI__builtin_ia32_rangepd128_mask: 4559 case X86::BI__builtin_ia32_rangepd256_mask: 4560 case X86::BI__builtin_ia32_rangepd512_mask: 4561 case X86::BI__builtin_ia32_rangeps128_mask: 4562 case X86::BI__builtin_ia32_rangeps256_mask: 4563 case X86::BI__builtin_ia32_rangeps512_mask: 4564 case X86::BI__builtin_ia32_getmantsd_round_mask: 4565 case X86::BI__builtin_ia32_getmantss_round_mask: 4566 case X86::BI__builtin_ia32_getmantsh_round_mask: 4567 case X86::BI__builtin_ia32_vec_set_v16qi: 4568 case X86::BI__builtin_ia32_vec_set_v16hi: 4569 i = 2; l = 0; u = 15; 4570 break; 4571 case X86::BI__builtin_ia32_vec_ext_v32qi: 4572 i = 1; l = 0; u = 31; 4573 break; 4574 case X86::BI__builtin_ia32_cmpps: 4575 case X86::BI__builtin_ia32_cmpss: 4576 case X86::BI__builtin_ia32_cmppd: 4577 case X86::BI__builtin_ia32_cmpsd: 4578 case X86::BI__builtin_ia32_cmpps256: 4579 case X86::BI__builtin_ia32_cmppd256: 4580 case X86::BI__builtin_ia32_cmpps128_mask: 4581 case X86::BI__builtin_ia32_cmppd128_mask: 4582 case X86::BI__builtin_ia32_cmpps256_mask: 4583 case X86::BI__builtin_ia32_cmppd256_mask: 4584 case X86::BI__builtin_ia32_cmpps512_mask: 4585 case X86::BI__builtin_ia32_cmppd512_mask: 4586 case X86::BI__builtin_ia32_cmpsd_mask: 4587 case X86::BI__builtin_ia32_cmpss_mask: 4588 case X86::BI__builtin_ia32_vec_set_v32qi: 4589 i = 2; l = 0; u = 31; 4590 break; 4591 case X86::BI__builtin_ia32_permdf256: 4592 case X86::BI__builtin_ia32_permdi256: 4593 case X86::BI__builtin_ia32_permdf512: 4594 case X86::BI__builtin_ia32_permdi512: 4595 case X86::BI__builtin_ia32_vpermilps: 4596 case X86::BI__builtin_ia32_vpermilps256: 4597 case X86::BI__builtin_ia32_vpermilpd512: 4598 case X86::BI__builtin_ia32_vpermilps512: 4599 case X86::BI__builtin_ia32_pshufd: 4600 case X86::BI__builtin_ia32_pshufd256: 4601 case X86::BI__builtin_ia32_pshufd512: 4602 case X86::BI__builtin_ia32_pshufhw: 4603 case X86::BI__builtin_ia32_pshufhw256: 4604 case X86::BI__builtin_ia32_pshufhw512: 4605 case X86::BI__builtin_ia32_pshuflw: 4606 case X86::BI__builtin_ia32_pshuflw256: 4607 case X86::BI__builtin_ia32_pshuflw512: 4608 case X86::BI__builtin_ia32_vcvtps2ph: 4609 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4610 case X86::BI__builtin_ia32_vcvtps2ph256: 4611 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4612 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4613 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4614 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4615 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4616 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4617 case X86::BI__builtin_ia32_rndscaleps_mask: 4618 case X86::BI__builtin_ia32_rndscalepd_mask: 4619 case X86::BI__builtin_ia32_rndscaleph_mask: 4620 case X86::BI__builtin_ia32_reducepd128_mask: 4621 case X86::BI__builtin_ia32_reducepd256_mask: 4622 case X86::BI__builtin_ia32_reducepd512_mask: 4623 case X86::BI__builtin_ia32_reduceps128_mask: 4624 case X86::BI__builtin_ia32_reduceps256_mask: 4625 case X86::BI__builtin_ia32_reduceps512_mask: 4626 case X86::BI__builtin_ia32_reduceph128_mask: 4627 case X86::BI__builtin_ia32_reduceph256_mask: 4628 case X86::BI__builtin_ia32_reduceph512_mask: 4629 case X86::BI__builtin_ia32_prold512: 4630 case X86::BI__builtin_ia32_prolq512: 4631 case X86::BI__builtin_ia32_prold128: 4632 case X86::BI__builtin_ia32_prold256: 4633 case X86::BI__builtin_ia32_prolq128: 4634 case X86::BI__builtin_ia32_prolq256: 4635 case X86::BI__builtin_ia32_prord512: 4636 case X86::BI__builtin_ia32_prorq512: 4637 case X86::BI__builtin_ia32_prord128: 4638 case X86::BI__builtin_ia32_prord256: 4639 case X86::BI__builtin_ia32_prorq128: 4640 case X86::BI__builtin_ia32_prorq256: 4641 case X86::BI__builtin_ia32_fpclasspd128_mask: 4642 case X86::BI__builtin_ia32_fpclasspd256_mask: 4643 case X86::BI__builtin_ia32_fpclassps128_mask: 4644 case X86::BI__builtin_ia32_fpclassps256_mask: 4645 case X86::BI__builtin_ia32_fpclassps512_mask: 4646 case X86::BI__builtin_ia32_fpclasspd512_mask: 4647 case X86::BI__builtin_ia32_fpclassph128_mask: 4648 case X86::BI__builtin_ia32_fpclassph256_mask: 4649 case X86::BI__builtin_ia32_fpclassph512_mask: 4650 case X86::BI__builtin_ia32_fpclasssd_mask: 4651 case X86::BI__builtin_ia32_fpclassss_mask: 4652 case X86::BI__builtin_ia32_fpclasssh_mask: 4653 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4654 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4655 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4656 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4657 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4658 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4659 case X86::BI__builtin_ia32_kshiftliqi: 4660 case X86::BI__builtin_ia32_kshiftlihi: 4661 case X86::BI__builtin_ia32_kshiftlisi: 4662 case X86::BI__builtin_ia32_kshiftlidi: 4663 case X86::BI__builtin_ia32_kshiftriqi: 4664 case X86::BI__builtin_ia32_kshiftrihi: 4665 case X86::BI__builtin_ia32_kshiftrisi: 4666 case X86::BI__builtin_ia32_kshiftridi: 4667 i = 1; l = 0; u = 255; 4668 break; 4669 case X86::BI__builtin_ia32_vperm2f128_pd256: 4670 case X86::BI__builtin_ia32_vperm2f128_ps256: 4671 case X86::BI__builtin_ia32_vperm2f128_si256: 4672 case X86::BI__builtin_ia32_permti256: 4673 case X86::BI__builtin_ia32_pblendw128: 4674 case X86::BI__builtin_ia32_pblendw256: 4675 case X86::BI__builtin_ia32_blendps256: 4676 case X86::BI__builtin_ia32_pblendd256: 4677 case X86::BI__builtin_ia32_palignr128: 4678 case X86::BI__builtin_ia32_palignr256: 4679 case X86::BI__builtin_ia32_palignr512: 4680 case X86::BI__builtin_ia32_alignq512: 4681 case X86::BI__builtin_ia32_alignd512: 4682 case X86::BI__builtin_ia32_alignd128: 4683 case X86::BI__builtin_ia32_alignd256: 4684 case X86::BI__builtin_ia32_alignq128: 4685 case X86::BI__builtin_ia32_alignq256: 4686 case X86::BI__builtin_ia32_vcomisd: 4687 case X86::BI__builtin_ia32_vcomiss: 4688 case X86::BI__builtin_ia32_shuf_f32x4: 4689 case X86::BI__builtin_ia32_shuf_f64x2: 4690 case X86::BI__builtin_ia32_shuf_i32x4: 4691 case X86::BI__builtin_ia32_shuf_i64x2: 4692 case X86::BI__builtin_ia32_shufpd512: 4693 case X86::BI__builtin_ia32_shufps: 4694 case X86::BI__builtin_ia32_shufps256: 4695 case X86::BI__builtin_ia32_shufps512: 4696 case X86::BI__builtin_ia32_dbpsadbw128: 4697 case X86::BI__builtin_ia32_dbpsadbw256: 4698 case X86::BI__builtin_ia32_dbpsadbw512: 4699 case X86::BI__builtin_ia32_vpshldd128: 4700 case X86::BI__builtin_ia32_vpshldd256: 4701 case X86::BI__builtin_ia32_vpshldd512: 4702 case X86::BI__builtin_ia32_vpshldq128: 4703 case X86::BI__builtin_ia32_vpshldq256: 4704 case X86::BI__builtin_ia32_vpshldq512: 4705 case X86::BI__builtin_ia32_vpshldw128: 4706 case X86::BI__builtin_ia32_vpshldw256: 4707 case X86::BI__builtin_ia32_vpshldw512: 4708 case X86::BI__builtin_ia32_vpshrdd128: 4709 case X86::BI__builtin_ia32_vpshrdd256: 4710 case X86::BI__builtin_ia32_vpshrdd512: 4711 case X86::BI__builtin_ia32_vpshrdq128: 4712 case X86::BI__builtin_ia32_vpshrdq256: 4713 case X86::BI__builtin_ia32_vpshrdq512: 4714 case X86::BI__builtin_ia32_vpshrdw128: 4715 case X86::BI__builtin_ia32_vpshrdw256: 4716 case X86::BI__builtin_ia32_vpshrdw512: 4717 i = 2; l = 0; u = 255; 4718 break; 4719 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4720 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4721 case X86::BI__builtin_ia32_fixupimmps512_mask: 4722 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4723 case X86::BI__builtin_ia32_fixupimmsd_mask: 4724 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4725 case X86::BI__builtin_ia32_fixupimmss_mask: 4726 case X86::BI__builtin_ia32_fixupimmss_maskz: 4727 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4728 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4729 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4730 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4731 case X86::BI__builtin_ia32_fixupimmps128_mask: 4732 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4733 case X86::BI__builtin_ia32_fixupimmps256_mask: 4734 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4735 case X86::BI__builtin_ia32_pternlogd512_mask: 4736 case X86::BI__builtin_ia32_pternlogd512_maskz: 4737 case X86::BI__builtin_ia32_pternlogq512_mask: 4738 case X86::BI__builtin_ia32_pternlogq512_maskz: 4739 case X86::BI__builtin_ia32_pternlogd128_mask: 4740 case X86::BI__builtin_ia32_pternlogd128_maskz: 4741 case X86::BI__builtin_ia32_pternlogd256_mask: 4742 case X86::BI__builtin_ia32_pternlogd256_maskz: 4743 case X86::BI__builtin_ia32_pternlogq128_mask: 4744 case X86::BI__builtin_ia32_pternlogq128_maskz: 4745 case X86::BI__builtin_ia32_pternlogq256_mask: 4746 case X86::BI__builtin_ia32_pternlogq256_maskz: 4747 i = 3; l = 0; u = 255; 4748 break; 4749 case X86::BI__builtin_ia32_gatherpfdpd: 4750 case X86::BI__builtin_ia32_gatherpfdps: 4751 case X86::BI__builtin_ia32_gatherpfqpd: 4752 case X86::BI__builtin_ia32_gatherpfqps: 4753 case X86::BI__builtin_ia32_scatterpfdpd: 4754 case X86::BI__builtin_ia32_scatterpfdps: 4755 case X86::BI__builtin_ia32_scatterpfqpd: 4756 case X86::BI__builtin_ia32_scatterpfqps: 4757 i = 4; l = 2; u = 3; 4758 break; 4759 case X86::BI__builtin_ia32_reducesd_mask: 4760 case X86::BI__builtin_ia32_reducess_mask: 4761 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4762 case X86::BI__builtin_ia32_rndscaless_round_mask: 4763 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4764 case X86::BI__builtin_ia32_reducesh_mask: 4765 i = 4; l = 0; u = 255; 4766 break; 4767 } 4768 4769 // Note that we don't force a hard error on the range check here, allowing 4770 // template-generated or macro-generated dead code to potentially have out-of- 4771 // range values. These need to code generate, but don't need to necessarily 4772 // make any sense. We use a warning that defaults to an error. 4773 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4774 } 4775 4776 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4777 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4778 /// Returns true when the format fits the function and the FormatStringInfo has 4779 /// been populated. 4780 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4781 FormatStringInfo *FSI) { 4782 FSI->HasVAListArg = Format->getFirstArg() == 0; 4783 FSI->FormatIdx = Format->getFormatIdx() - 1; 4784 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4785 4786 // The way the format attribute works in GCC, the implicit this argument 4787 // of member functions is counted. However, it doesn't appear in our own 4788 // lists, so decrement format_idx in that case. 4789 if (IsCXXMember) { 4790 if(FSI->FormatIdx == 0) 4791 return false; 4792 --FSI->FormatIdx; 4793 if (FSI->FirstDataArg != 0) 4794 --FSI->FirstDataArg; 4795 } 4796 return true; 4797 } 4798 4799 /// Checks if a the given expression evaluates to null. 4800 /// 4801 /// Returns true if the value evaluates to null. 4802 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4803 // If the expression has non-null type, it doesn't evaluate to null. 4804 if (auto nullability 4805 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4806 if (*nullability == NullabilityKind::NonNull) 4807 return false; 4808 } 4809 4810 // As a special case, transparent unions initialized with zero are 4811 // considered null for the purposes of the nonnull attribute. 4812 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4813 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4814 if (const CompoundLiteralExpr *CLE = 4815 dyn_cast<CompoundLiteralExpr>(Expr)) 4816 if (const InitListExpr *ILE = 4817 dyn_cast<InitListExpr>(CLE->getInitializer())) 4818 Expr = ILE->getInit(0); 4819 } 4820 4821 bool Result; 4822 return (!Expr->isValueDependent() && 4823 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4824 !Result); 4825 } 4826 4827 static void CheckNonNullArgument(Sema &S, 4828 const Expr *ArgExpr, 4829 SourceLocation CallSiteLoc) { 4830 if (CheckNonNullExpr(S, ArgExpr)) 4831 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4832 S.PDiag(diag::warn_null_arg) 4833 << ArgExpr->getSourceRange()); 4834 } 4835 4836 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4837 FormatStringInfo FSI; 4838 if ((GetFormatStringType(Format) == FST_NSString) && 4839 getFormatStringInfo(Format, false, &FSI)) { 4840 Idx = FSI.FormatIdx; 4841 return true; 4842 } 4843 return false; 4844 } 4845 4846 /// Diagnose use of %s directive in an NSString which is being passed 4847 /// as formatting string to formatting method. 4848 static void 4849 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4850 const NamedDecl *FDecl, 4851 Expr **Args, 4852 unsigned NumArgs) { 4853 unsigned Idx = 0; 4854 bool Format = false; 4855 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4856 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4857 Idx = 2; 4858 Format = true; 4859 } 4860 else 4861 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4862 if (S.GetFormatNSStringIdx(I, Idx)) { 4863 Format = true; 4864 break; 4865 } 4866 } 4867 if (!Format || NumArgs <= Idx) 4868 return; 4869 const Expr *FormatExpr = Args[Idx]; 4870 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4871 FormatExpr = CSCE->getSubExpr(); 4872 const StringLiteral *FormatString; 4873 if (const ObjCStringLiteral *OSL = 4874 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4875 FormatString = OSL->getString(); 4876 else 4877 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4878 if (!FormatString) 4879 return; 4880 if (S.FormatStringHasSArg(FormatString)) { 4881 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4882 << "%s" << 1 << 1; 4883 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4884 << FDecl->getDeclName(); 4885 } 4886 } 4887 4888 /// Determine whether the given type has a non-null nullability annotation. 4889 static bool isNonNullType(ASTContext &ctx, QualType type) { 4890 if (auto nullability = type->getNullability(ctx)) 4891 return *nullability == NullabilityKind::NonNull; 4892 4893 return false; 4894 } 4895 4896 static void CheckNonNullArguments(Sema &S, 4897 const NamedDecl *FDecl, 4898 const FunctionProtoType *Proto, 4899 ArrayRef<const Expr *> Args, 4900 SourceLocation CallSiteLoc) { 4901 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4902 4903 // Already checked by by constant evaluator. 4904 if (S.isConstantEvaluated()) 4905 return; 4906 // Check the attributes attached to the method/function itself. 4907 llvm::SmallBitVector NonNullArgs; 4908 if (FDecl) { 4909 // Handle the nonnull attribute on the function/method declaration itself. 4910 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4911 if (!NonNull->args_size()) { 4912 // Easy case: all pointer arguments are nonnull. 4913 for (const auto *Arg : Args) 4914 if (S.isValidPointerAttrType(Arg->getType())) 4915 CheckNonNullArgument(S, Arg, CallSiteLoc); 4916 return; 4917 } 4918 4919 for (const ParamIdx &Idx : NonNull->args()) { 4920 unsigned IdxAST = Idx.getASTIndex(); 4921 if (IdxAST >= Args.size()) 4922 continue; 4923 if (NonNullArgs.empty()) 4924 NonNullArgs.resize(Args.size()); 4925 NonNullArgs.set(IdxAST); 4926 } 4927 } 4928 } 4929 4930 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4931 // Handle the nonnull attribute on the parameters of the 4932 // function/method. 4933 ArrayRef<ParmVarDecl*> parms; 4934 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4935 parms = FD->parameters(); 4936 else 4937 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4938 4939 unsigned ParamIndex = 0; 4940 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4941 I != E; ++I, ++ParamIndex) { 4942 const ParmVarDecl *PVD = *I; 4943 if (PVD->hasAttr<NonNullAttr>() || 4944 isNonNullType(S.Context, PVD->getType())) { 4945 if (NonNullArgs.empty()) 4946 NonNullArgs.resize(Args.size()); 4947 4948 NonNullArgs.set(ParamIndex); 4949 } 4950 } 4951 } else { 4952 // If we have a non-function, non-method declaration but no 4953 // function prototype, try to dig out the function prototype. 4954 if (!Proto) { 4955 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4956 QualType type = VD->getType().getNonReferenceType(); 4957 if (auto pointerType = type->getAs<PointerType>()) 4958 type = pointerType->getPointeeType(); 4959 else if (auto blockType = type->getAs<BlockPointerType>()) 4960 type = blockType->getPointeeType(); 4961 // FIXME: data member pointers? 4962 4963 // Dig out the function prototype, if there is one. 4964 Proto = type->getAs<FunctionProtoType>(); 4965 } 4966 } 4967 4968 // Fill in non-null argument information from the nullability 4969 // information on the parameter types (if we have them). 4970 if (Proto) { 4971 unsigned Index = 0; 4972 for (auto paramType : Proto->getParamTypes()) { 4973 if (isNonNullType(S.Context, paramType)) { 4974 if (NonNullArgs.empty()) 4975 NonNullArgs.resize(Args.size()); 4976 4977 NonNullArgs.set(Index); 4978 } 4979 4980 ++Index; 4981 } 4982 } 4983 } 4984 4985 // Check for non-null arguments. 4986 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4987 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4988 if (NonNullArgs[ArgIndex]) 4989 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4990 } 4991 } 4992 4993 /// Warn if a pointer or reference argument passed to a function points to an 4994 /// object that is less aligned than the parameter. This can happen when 4995 /// creating a typedef with a lower alignment than the original type and then 4996 /// calling functions defined in terms of the original type. 4997 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4998 StringRef ParamName, QualType ArgTy, 4999 QualType ParamTy) { 5000 5001 // If a function accepts a pointer or reference type 5002 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 5003 return; 5004 5005 // If the parameter is a pointer type, get the pointee type for the 5006 // argument too. If the parameter is a reference type, don't try to get 5007 // the pointee type for the argument. 5008 if (ParamTy->isPointerType()) 5009 ArgTy = ArgTy->getPointeeType(); 5010 5011 // Remove reference or pointer 5012 ParamTy = ParamTy->getPointeeType(); 5013 5014 // Find expected alignment, and the actual alignment of the passed object. 5015 // getTypeAlignInChars requires complete types 5016 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 5017 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 5018 ArgTy->isUndeducedType()) 5019 return; 5020 5021 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 5022 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 5023 5024 // If the argument is less aligned than the parameter, there is a 5025 // potential alignment issue. 5026 if (ArgAlign < ParamAlign) 5027 Diag(Loc, diag::warn_param_mismatched_alignment) 5028 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5029 << ParamName << (FDecl != nullptr) << FDecl; 5030 } 5031 5032 /// Handles the checks for format strings, non-POD arguments to vararg 5033 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5034 /// attributes. 5035 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5036 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5037 bool IsMemberFunction, SourceLocation Loc, 5038 SourceRange Range, VariadicCallType CallType) { 5039 // FIXME: We should check as much as we can in the template definition. 5040 if (CurContext->isDependentContext()) 5041 return; 5042 5043 // Printf and scanf checking. 5044 llvm::SmallBitVector CheckedVarArgs; 5045 if (FDecl) { 5046 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5047 // Only create vector if there are format attributes. 5048 CheckedVarArgs.resize(Args.size()); 5049 5050 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5051 CheckedVarArgs); 5052 } 5053 } 5054 5055 // Refuse POD arguments that weren't caught by the format string 5056 // checks above. 5057 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5058 if (CallType != VariadicDoesNotApply && 5059 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5060 unsigned NumParams = Proto ? Proto->getNumParams() 5061 : FDecl && isa<FunctionDecl>(FDecl) 5062 ? cast<FunctionDecl>(FDecl)->getNumParams() 5063 : FDecl && isa<ObjCMethodDecl>(FDecl) 5064 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5065 : 0; 5066 5067 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5068 // Args[ArgIdx] can be null in malformed code. 5069 if (const Expr *Arg = Args[ArgIdx]) { 5070 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5071 checkVariadicArgument(Arg, CallType); 5072 } 5073 } 5074 } 5075 5076 if (FDecl || Proto) { 5077 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5078 5079 // Type safety checking. 5080 if (FDecl) { 5081 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5082 CheckArgumentWithTypeTag(I, Args, Loc); 5083 } 5084 } 5085 5086 // Check that passed arguments match the alignment of original arguments. 5087 // Try to get the missing prototype from the declaration. 5088 if (!Proto && FDecl) { 5089 const auto *FT = FDecl->getFunctionType(); 5090 if (isa_and_nonnull<FunctionProtoType>(FT)) 5091 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5092 } 5093 if (Proto) { 5094 // For variadic functions, we may have more args than parameters. 5095 // For some K&R functions, we may have less args than parameters. 5096 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5097 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5098 // Args[ArgIdx] can be null in malformed code. 5099 if (const Expr *Arg = Args[ArgIdx]) { 5100 if (Arg->containsErrors()) 5101 continue; 5102 5103 QualType ParamTy = Proto->getParamType(ArgIdx); 5104 QualType ArgTy = Arg->getType(); 5105 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5106 ArgTy, ParamTy); 5107 } 5108 } 5109 } 5110 5111 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5112 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5113 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5114 if (!Arg->isValueDependent()) { 5115 Expr::EvalResult Align; 5116 if (Arg->EvaluateAsInt(Align, Context)) { 5117 const llvm::APSInt &I = Align.Val.getInt(); 5118 if (!I.isPowerOf2()) 5119 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5120 << Arg->getSourceRange(); 5121 5122 if (I > Sema::MaximumAlignment) 5123 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5124 << Arg->getSourceRange() << Sema::MaximumAlignment; 5125 } 5126 } 5127 } 5128 5129 if (FD) 5130 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5131 } 5132 5133 /// CheckConstructorCall - Check a constructor call for correctness and safety 5134 /// properties not enforced by the C type system. 5135 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5136 ArrayRef<const Expr *> Args, 5137 const FunctionProtoType *Proto, 5138 SourceLocation Loc) { 5139 VariadicCallType CallType = 5140 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5141 5142 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5143 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5144 Context.getPointerType(Ctor->getThisObjectType())); 5145 5146 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5147 Loc, SourceRange(), CallType); 5148 } 5149 5150 /// CheckFunctionCall - Check a direct function call for various correctness 5151 /// and safety properties not strictly enforced by the C type system. 5152 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5153 const FunctionProtoType *Proto) { 5154 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5155 isa<CXXMethodDecl>(FDecl); 5156 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5157 IsMemberOperatorCall; 5158 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5159 TheCall->getCallee()); 5160 Expr** Args = TheCall->getArgs(); 5161 unsigned NumArgs = TheCall->getNumArgs(); 5162 5163 Expr *ImplicitThis = nullptr; 5164 if (IsMemberOperatorCall) { 5165 // If this is a call to a member operator, hide the first argument 5166 // from checkCall. 5167 // FIXME: Our choice of AST representation here is less than ideal. 5168 ImplicitThis = Args[0]; 5169 ++Args; 5170 --NumArgs; 5171 } else if (IsMemberFunction) 5172 ImplicitThis = 5173 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5174 5175 if (ImplicitThis) { 5176 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5177 // used. 5178 QualType ThisType = ImplicitThis->getType(); 5179 if (!ThisType->isPointerType()) { 5180 assert(!ThisType->isReferenceType()); 5181 ThisType = Context.getPointerType(ThisType); 5182 } 5183 5184 QualType ThisTypeFromDecl = 5185 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5186 5187 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5188 ThisTypeFromDecl); 5189 } 5190 5191 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5192 IsMemberFunction, TheCall->getRParenLoc(), 5193 TheCall->getCallee()->getSourceRange(), CallType); 5194 5195 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5196 // None of the checks below are needed for functions that don't have 5197 // simple names (e.g., C++ conversion functions). 5198 if (!FnInfo) 5199 return false; 5200 5201 CheckTCBEnforcement(TheCall, FDecl); 5202 5203 CheckAbsoluteValueFunction(TheCall, FDecl); 5204 CheckMaxUnsignedZero(TheCall, FDecl); 5205 5206 if (getLangOpts().ObjC) 5207 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5208 5209 unsigned CMId = FDecl->getMemoryFunctionKind(); 5210 5211 // Handle memory setting and copying functions. 5212 switch (CMId) { 5213 case 0: 5214 return false; 5215 case Builtin::BIstrlcpy: // fallthrough 5216 case Builtin::BIstrlcat: 5217 CheckStrlcpycatArguments(TheCall, FnInfo); 5218 break; 5219 case Builtin::BIstrncat: 5220 CheckStrncatArguments(TheCall, FnInfo); 5221 break; 5222 case Builtin::BIfree: 5223 CheckFreeArguments(TheCall); 5224 break; 5225 default: 5226 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5227 } 5228 5229 return false; 5230 } 5231 5232 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5233 ArrayRef<const Expr *> Args) { 5234 VariadicCallType CallType = 5235 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5236 5237 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5238 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5239 CallType); 5240 5241 return false; 5242 } 5243 5244 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5245 const FunctionProtoType *Proto) { 5246 QualType Ty; 5247 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5248 Ty = V->getType().getNonReferenceType(); 5249 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5250 Ty = F->getType().getNonReferenceType(); 5251 else 5252 return false; 5253 5254 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5255 !Ty->isFunctionProtoType()) 5256 return false; 5257 5258 VariadicCallType CallType; 5259 if (!Proto || !Proto->isVariadic()) { 5260 CallType = VariadicDoesNotApply; 5261 } else if (Ty->isBlockPointerType()) { 5262 CallType = VariadicBlock; 5263 } else { // Ty->isFunctionPointerType() 5264 CallType = VariadicFunction; 5265 } 5266 5267 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5268 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5269 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5270 TheCall->getCallee()->getSourceRange(), CallType); 5271 5272 return false; 5273 } 5274 5275 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5276 /// such as function pointers returned from functions. 5277 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5278 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5279 TheCall->getCallee()); 5280 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5281 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5282 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5283 TheCall->getCallee()->getSourceRange(), CallType); 5284 5285 return false; 5286 } 5287 5288 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5289 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5290 return false; 5291 5292 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5293 switch (Op) { 5294 case AtomicExpr::AO__c11_atomic_init: 5295 case AtomicExpr::AO__opencl_atomic_init: 5296 llvm_unreachable("There is no ordering argument for an init"); 5297 5298 case AtomicExpr::AO__c11_atomic_load: 5299 case AtomicExpr::AO__opencl_atomic_load: 5300 case AtomicExpr::AO__atomic_load_n: 5301 case AtomicExpr::AO__atomic_load: 5302 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5303 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5304 5305 case AtomicExpr::AO__c11_atomic_store: 5306 case AtomicExpr::AO__opencl_atomic_store: 5307 case AtomicExpr::AO__atomic_store: 5308 case AtomicExpr::AO__atomic_store_n: 5309 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5310 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5311 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5312 5313 default: 5314 return true; 5315 } 5316 } 5317 5318 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5319 AtomicExpr::AtomicOp Op) { 5320 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5321 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5322 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5323 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5324 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5325 Op); 5326 } 5327 5328 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5329 SourceLocation RParenLoc, MultiExprArg Args, 5330 AtomicExpr::AtomicOp Op, 5331 AtomicArgumentOrder ArgOrder) { 5332 // All the non-OpenCL operations take one of the following forms. 5333 // The OpenCL operations take the __c11 forms with one extra argument for 5334 // synchronization scope. 5335 enum { 5336 // C __c11_atomic_init(A *, C) 5337 Init, 5338 5339 // C __c11_atomic_load(A *, int) 5340 Load, 5341 5342 // void __atomic_load(A *, CP, int) 5343 LoadCopy, 5344 5345 // void __atomic_store(A *, CP, int) 5346 Copy, 5347 5348 // C __c11_atomic_add(A *, M, int) 5349 Arithmetic, 5350 5351 // C __atomic_exchange_n(A *, CP, int) 5352 Xchg, 5353 5354 // void __atomic_exchange(A *, C *, CP, int) 5355 GNUXchg, 5356 5357 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5358 C11CmpXchg, 5359 5360 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5361 GNUCmpXchg 5362 } Form = Init; 5363 5364 const unsigned NumForm = GNUCmpXchg + 1; 5365 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5366 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5367 // where: 5368 // C is an appropriate type, 5369 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5370 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5371 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5372 // the int parameters are for orderings. 5373 5374 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5375 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5376 "need to update code for modified forms"); 5377 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5378 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5379 AtomicExpr::AO__atomic_load, 5380 "need to update code for modified C11 atomics"); 5381 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5382 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5383 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5384 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5385 IsOpenCL; 5386 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5387 Op == AtomicExpr::AO__atomic_store_n || 5388 Op == AtomicExpr::AO__atomic_exchange_n || 5389 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5390 bool IsAddSub = false; 5391 5392 switch (Op) { 5393 case AtomicExpr::AO__c11_atomic_init: 5394 case AtomicExpr::AO__opencl_atomic_init: 5395 Form = Init; 5396 break; 5397 5398 case AtomicExpr::AO__c11_atomic_load: 5399 case AtomicExpr::AO__opencl_atomic_load: 5400 case AtomicExpr::AO__atomic_load_n: 5401 Form = Load; 5402 break; 5403 5404 case AtomicExpr::AO__atomic_load: 5405 Form = LoadCopy; 5406 break; 5407 5408 case AtomicExpr::AO__c11_atomic_store: 5409 case AtomicExpr::AO__opencl_atomic_store: 5410 case AtomicExpr::AO__atomic_store: 5411 case AtomicExpr::AO__atomic_store_n: 5412 Form = Copy; 5413 break; 5414 5415 case AtomicExpr::AO__c11_atomic_fetch_add: 5416 case AtomicExpr::AO__c11_atomic_fetch_sub: 5417 case AtomicExpr::AO__opencl_atomic_fetch_add: 5418 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5419 case AtomicExpr::AO__atomic_fetch_add: 5420 case AtomicExpr::AO__atomic_fetch_sub: 5421 case AtomicExpr::AO__atomic_add_fetch: 5422 case AtomicExpr::AO__atomic_sub_fetch: 5423 IsAddSub = true; 5424 Form = Arithmetic; 5425 break; 5426 case AtomicExpr::AO__c11_atomic_fetch_and: 5427 case AtomicExpr::AO__c11_atomic_fetch_or: 5428 case AtomicExpr::AO__c11_atomic_fetch_xor: 5429 case AtomicExpr::AO__c11_atomic_fetch_nand: 5430 case AtomicExpr::AO__opencl_atomic_fetch_and: 5431 case AtomicExpr::AO__opencl_atomic_fetch_or: 5432 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5433 case AtomicExpr::AO__atomic_fetch_and: 5434 case AtomicExpr::AO__atomic_fetch_or: 5435 case AtomicExpr::AO__atomic_fetch_xor: 5436 case AtomicExpr::AO__atomic_fetch_nand: 5437 case AtomicExpr::AO__atomic_and_fetch: 5438 case AtomicExpr::AO__atomic_or_fetch: 5439 case AtomicExpr::AO__atomic_xor_fetch: 5440 case AtomicExpr::AO__atomic_nand_fetch: 5441 Form = Arithmetic; 5442 break; 5443 case AtomicExpr::AO__c11_atomic_fetch_min: 5444 case AtomicExpr::AO__c11_atomic_fetch_max: 5445 case AtomicExpr::AO__opencl_atomic_fetch_min: 5446 case AtomicExpr::AO__opencl_atomic_fetch_max: 5447 case AtomicExpr::AO__atomic_min_fetch: 5448 case AtomicExpr::AO__atomic_max_fetch: 5449 case AtomicExpr::AO__atomic_fetch_min: 5450 case AtomicExpr::AO__atomic_fetch_max: 5451 Form = Arithmetic; 5452 break; 5453 5454 case AtomicExpr::AO__c11_atomic_exchange: 5455 case AtomicExpr::AO__opencl_atomic_exchange: 5456 case AtomicExpr::AO__atomic_exchange_n: 5457 Form = Xchg; 5458 break; 5459 5460 case AtomicExpr::AO__atomic_exchange: 5461 Form = GNUXchg; 5462 break; 5463 5464 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5465 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5466 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5467 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5468 Form = C11CmpXchg; 5469 break; 5470 5471 case AtomicExpr::AO__atomic_compare_exchange: 5472 case AtomicExpr::AO__atomic_compare_exchange_n: 5473 Form = GNUCmpXchg; 5474 break; 5475 } 5476 5477 unsigned AdjustedNumArgs = NumArgs[Form]; 5478 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5479 ++AdjustedNumArgs; 5480 // Check we have the right number of arguments. 5481 if (Args.size() < AdjustedNumArgs) { 5482 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5483 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5484 << ExprRange; 5485 return ExprError(); 5486 } else if (Args.size() > AdjustedNumArgs) { 5487 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5488 diag::err_typecheck_call_too_many_args) 5489 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5490 << ExprRange; 5491 return ExprError(); 5492 } 5493 5494 // Inspect the first argument of the atomic operation. 5495 Expr *Ptr = Args[0]; 5496 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5497 if (ConvertedPtr.isInvalid()) 5498 return ExprError(); 5499 5500 Ptr = ConvertedPtr.get(); 5501 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5502 if (!pointerType) { 5503 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5504 << Ptr->getType() << Ptr->getSourceRange(); 5505 return ExprError(); 5506 } 5507 5508 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5509 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5510 QualType ValType = AtomTy; // 'C' 5511 if (IsC11) { 5512 if (!AtomTy->isAtomicType()) { 5513 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5514 << Ptr->getType() << Ptr->getSourceRange(); 5515 return ExprError(); 5516 } 5517 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5518 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5519 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5520 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5521 << Ptr->getSourceRange(); 5522 return ExprError(); 5523 } 5524 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5525 } else if (Form != Load && Form != LoadCopy) { 5526 if (ValType.isConstQualified()) { 5527 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5528 << Ptr->getType() << Ptr->getSourceRange(); 5529 return ExprError(); 5530 } 5531 } 5532 5533 // For an arithmetic operation, the implied arithmetic must be well-formed. 5534 if (Form == Arithmetic) { 5535 // gcc does not enforce these rules for GNU atomics, but we do so for 5536 // sanity. 5537 auto IsAllowedValueType = [&](QualType ValType) { 5538 if (ValType->isIntegerType()) 5539 return true; 5540 if (ValType->isPointerType()) 5541 return true; 5542 if (!ValType->isFloatingType()) 5543 return false; 5544 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5545 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5546 &Context.getTargetInfo().getLongDoubleFormat() == 5547 &llvm::APFloat::x87DoubleExtended()) 5548 return false; 5549 return true; 5550 }; 5551 if (IsAddSub && !IsAllowedValueType(ValType)) { 5552 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5553 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5554 return ExprError(); 5555 } 5556 if (!IsAddSub && !ValType->isIntegerType()) { 5557 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5558 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5559 return ExprError(); 5560 } 5561 if (IsC11 && ValType->isPointerType() && 5562 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5563 diag::err_incomplete_type)) { 5564 return ExprError(); 5565 } 5566 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5567 // For __atomic_*_n operations, the value type must be a scalar integral or 5568 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5569 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5570 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5571 return ExprError(); 5572 } 5573 5574 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5575 !AtomTy->isScalarType()) { 5576 // For GNU atomics, require a trivially-copyable type. This is not part of 5577 // the GNU atomics specification, but we enforce it for sanity. 5578 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5579 << Ptr->getType() << Ptr->getSourceRange(); 5580 return ExprError(); 5581 } 5582 5583 switch (ValType.getObjCLifetime()) { 5584 case Qualifiers::OCL_None: 5585 case Qualifiers::OCL_ExplicitNone: 5586 // okay 5587 break; 5588 5589 case Qualifiers::OCL_Weak: 5590 case Qualifiers::OCL_Strong: 5591 case Qualifiers::OCL_Autoreleasing: 5592 // FIXME: Can this happen? By this point, ValType should be known 5593 // to be trivially copyable. 5594 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5595 << ValType << Ptr->getSourceRange(); 5596 return ExprError(); 5597 } 5598 5599 // All atomic operations have an overload which takes a pointer to a volatile 5600 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5601 // into the result or the other operands. Similarly atomic_load takes a 5602 // pointer to a const 'A'. 5603 ValType.removeLocalVolatile(); 5604 ValType.removeLocalConst(); 5605 QualType ResultType = ValType; 5606 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5607 Form == Init) 5608 ResultType = Context.VoidTy; 5609 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5610 ResultType = Context.BoolTy; 5611 5612 // The type of a parameter passed 'by value'. In the GNU atomics, such 5613 // arguments are actually passed as pointers. 5614 QualType ByValType = ValType; // 'CP' 5615 bool IsPassedByAddress = false; 5616 if (!IsC11 && !IsN) { 5617 ByValType = Ptr->getType(); 5618 IsPassedByAddress = true; 5619 } 5620 5621 SmallVector<Expr *, 5> APIOrderedArgs; 5622 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5623 APIOrderedArgs.push_back(Args[0]); 5624 switch (Form) { 5625 case Init: 5626 case Load: 5627 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5628 break; 5629 case LoadCopy: 5630 case Copy: 5631 case Arithmetic: 5632 case Xchg: 5633 APIOrderedArgs.push_back(Args[2]); // Val1 5634 APIOrderedArgs.push_back(Args[1]); // Order 5635 break; 5636 case GNUXchg: 5637 APIOrderedArgs.push_back(Args[2]); // Val1 5638 APIOrderedArgs.push_back(Args[3]); // Val2 5639 APIOrderedArgs.push_back(Args[1]); // Order 5640 break; 5641 case C11CmpXchg: 5642 APIOrderedArgs.push_back(Args[2]); // Val1 5643 APIOrderedArgs.push_back(Args[4]); // Val2 5644 APIOrderedArgs.push_back(Args[1]); // Order 5645 APIOrderedArgs.push_back(Args[3]); // OrderFail 5646 break; 5647 case GNUCmpXchg: 5648 APIOrderedArgs.push_back(Args[2]); // Val1 5649 APIOrderedArgs.push_back(Args[4]); // Val2 5650 APIOrderedArgs.push_back(Args[5]); // Weak 5651 APIOrderedArgs.push_back(Args[1]); // Order 5652 APIOrderedArgs.push_back(Args[3]); // OrderFail 5653 break; 5654 } 5655 } else 5656 APIOrderedArgs.append(Args.begin(), Args.end()); 5657 5658 // The first argument's non-CV pointer type is used to deduce the type of 5659 // subsequent arguments, except for: 5660 // - weak flag (always converted to bool) 5661 // - memory order (always converted to int) 5662 // - scope (always converted to int) 5663 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5664 QualType Ty; 5665 if (i < NumVals[Form] + 1) { 5666 switch (i) { 5667 case 0: 5668 // The first argument is always a pointer. It has a fixed type. 5669 // It is always dereferenced, a nullptr is undefined. 5670 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5671 // Nothing else to do: we already know all we want about this pointer. 5672 continue; 5673 case 1: 5674 // The second argument is the non-atomic operand. For arithmetic, this 5675 // is always passed by value, and for a compare_exchange it is always 5676 // passed by address. For the rest, GNU uses by-address and C11 uses 5677 // by-value. 5678 assert(Form != Load); 5679 if (Form == Arithmetic && ValType->isPointerType()) 5680 Ty = Context.getPointerDiffType(); 5681 else if (Form == Init || Form == Arithmetic) 5682 Ty = ValType; 5683 else if (Form == Copy || Form == Xchg) { 5684 if (IsPassedByAddress) { 5685 // The value pointer is always dereferenced, a nullptr is undefined. 5686 CheckNonNullArgument(*this, APIOrderedArgs[i], 5687 ExprRange.getBegin()); 5688 } 5689 Ty = ByValType; 5690 } else { 5691 Expr *ValArg = APIOrderedArgs[i]; 5692 // The value pointer is always dereferenced, a nullptr is undefined. 5693 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5694 LangAS AS = LangAS::Default; 5695 // Keep address space of non-atomic pointer type. 5696 if (const PointerType *PtrTy = 5697 ValArg->getType()->getAs<PointerType>()) { 5698 AS = PtrTy->getPointeeType().getAddressSpace(); 5699 } 5700 Ty = Context.getPointerType( 5701 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5702 } 5703 break; 5704 case 2: 5705 // The third argument to compare_exchange / GNU exchange is the desired 5706 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5707 if (IsPassedByAddress) 5708 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5709 Ty = ByValType; 5710 break; 5711 case 3: 5712 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5713 Ty = Context.BoolTy; 5714 break; 5715 } 5716 } else { 5717 // The order(s) and scope are always converted to int. 5718 Ty = Context.IntTy; 5719 } 5720 5721 InitializedEntity Entity = 5722 InitializedEntity::InitializeParameter(Context, Ty, false); 5723 ExprResult Arg = APIOrderedArgs[i]; 5724 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5725 if (Arg.isInvalid()) 5726 return true; 5727 APIOrderedArgs[i] = Arg.get(); 5728 } 5729 5730 // Permute the arguments into a 'consistent' order. 5731 SmallVector<Expr*, 5> SubExprs; 5732 SubExprs.push_back(Ptr); 5733 switch (Form) { 5734 case Init: 5735 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5736 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5737 break; 5738 case Load: 5739 SubExprs.push_back(APIOrderedArgs[1]); // Order 5740 break; 5741 case LoadCopy: 5742 case Copy: 5743 case Arithmetic: 5744 case Xchg: 5745 SubExprs.push_back(APIOrderedArgs[2]); // Order 5746 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5747 break; 5748 case GNUXchg: 5749 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5750 SubExprs.push_back(APIOrderedArgs[3]); // Order 5751 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5752 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5753 break; 5754 case C11CmpXchg: 5755 SubExprs.push_back(APIOrderedArgs[3]); // Order 5756 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5757 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5758 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5759 break; 5760 case GNUCmpXchg: 5761 SubExprs.push_back(APIOrderedArgs[4]); // Order 5762 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5763 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5764 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5765 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5766 break; 5767 } 5768 5769 if (SubExprs.size() >= 2 && Form != Init) { 5770 if (Optional<llvm::APSInt> Result = 5771 SubExprs[1]->getIntegerConstantExpr(Context)) 5772 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5773 Diag(SubExprs[1]->getBeginLoc(), 5774 diag::warn_atomic_op_has_invalid_memory_order) 5775 << SubExprs[1]->getSourceRange(); 5776 } 5777 5778 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5779 auto *Scope = Args[Args.size() - 1]; 5780 if (Optional<llvm::APSInt> Result = 5781 Scope->getIntegerConstantExpr(Context)) { 5782 if (!ScopeModel->isValid(Result->getZExtValue())) 5783 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5784 << Scope->getSourceRange(); 5785 } 5786 SubExprs.push_back(Scope); 5787 } 5788 5789 AtomicExpr *AE = new (Context) 5790 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5791 5792 if ((Op == AtomicExpr::AO__c11_atomic_load || 5793 Op == AtomicExpr::AO__c11_atomic_store || 5794 Op == AtomicExpr::AO__opencl_atomic_load || 5795 Op == AtomicExpr::AO__opencl_atomic_store ) && 5796 Context.AtomicUsesUnsupportedLibcall(AE)) 5797 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5798 << ((Op == AtomicExpr::AO__c11_atomic_load || 5799 Op == AtomicExpr::AO__opencl_atomic_load) 5800 ? 0 5801 : 1); 5802 5803 if (ValType->isExtIntType()) { 5804 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5805 return ExprError(); 5806 } 5807 5808 return AE; 5809 } 5810 5811 /// checkBuiltinArgument - Given a call to a builtin function, perform 5812 /// normal type-checking on the given argument, updating the call in 5813 /// place. This is useful when a builtin function requires custom 5814 /// type-checking for some of its arguments but not necessarily all of 5815 /// them. 5816 /// 5817 /// Returns true on error. 5818 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5819 FunctionDecl *Fn = E->getDirectCallee(); 5820 assert(Fn && "builtin call without direct callee!"); 5821 5822 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5823 InitializedEntity Entity = 5824 InitializedEntity::InitializeParameter(S.Context, Param); 5825 5826 ExprResult Arg = E->getArg(0); 5827 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5828 if (Arg.isInvalid()) 5829 return true; 5830 5831 E->setArg(ArgIndex, Arg.get()); 5832 return false; 5833 } 5834 5835 /// We have a call to a function like __sync_fetch_and_add, which is an 5836 /// overloaded function based on the pointer type of its first argument. 5837 /// The main BuildCallExpr routines have already promoted the types of 5838 /// arguments because all of these calls are prototyped as void(...). 5839 /// 5840 /// This function goes through and does final semantic checking for these 5841 /// builtins, as well as generating any warnings. 5842 ExprResult 5843 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5844 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5845 Expr *Callee = TheCall->getCallee(); 5846 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5847 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5848 5849 // Ensure that we have at least one argument to do type inference from. 5850 if (TheCall->getNumArgs() < 1) { 5851 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5852 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5853 return ExprError(); 5854 } 5855 5856 // Inspect the first argument of the atomic builtin. This should always be 5857 // a pointer type, whose element is an integral scalar or pointer type. 5858 // Because it is a pointer type, we don't have to worry about any implicit 5859 // casts here. 5860 // FIXME: We don't allow floating point scalars as input. 5861 Expr *FirstArg = TheCall->getArg(0); 5862 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5863 if (FirstArgResult.isInvalid()) 5864 return ExprError(); 5865 FirstArg = FirstArgResult.get(); 5866 TheCall->setArg(0, FirstArg); 5867 5868 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5869 if (!pointerType) { 5870 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5871 << FirstArg->getType() << FirstArg->getSourceRange(); 5872 return ExprError(); 5873 } 5874 5875 QualType ValType = pointerType->getPointeeType(); 5876 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5877 !ValType->isBlockPointerType()) { 5878 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5879 << FirstArg->getType() << FirstArg->getSourceRange(); 5880 return ExprError(); 5881 } 5882 5883 if (ValType.isConstQualified()) { 5884 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5885 << FirstArg->getType() << FirstArg->getSourceRange(); 5886 return ExprError(); 5887 } 5888 5889 switch (ValType.getObjCLifetime()) { 5890 case Qualifiers::OCL_None: 5891 case Qualifiers::OCL_ExplicitNone: 5892 // okay 5893 break; 5894 5895 case Qualifiers::OCL_Weak: 5896 case Qualifiers::OCL_Strong: 5897 case Qualifiers::OCL_Autoreleasing: 5898 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5899 << ValType << FirstArg->getSourceRange(); 5900 return ExprError(); 5901 } 5902 5903 // Strip any qualifiers off ValType. 5904 ValType = ValType.getUnqualifiedType(); 5905 5906 // The majority of builtins return a value, but a few have special return 5907 // types, so allow them to override appropriately below. 5908 QualType ResultType = ValType; 5909 5910 // We need to figure out which concrete builtin this maps onto. For example, 5911 // __sync_fetch_and_add with a 2 byte object turns into 5912 // __sync_fetch_and_add_2. 5913 #define BUILTIN_ROW(x) \ 5914 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5915 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5916 5917 static const unsigned BuiltinIndices[][5] = { 5918 BUILTIN_ROW(__sync_fetch_and_add), 5919 BUILTIN_ROW(__sync_fetch_and_sub), 5920 BUILTIN_ROW(__sync_fetch_and_or), 5921 BUILTIN_ROW(__sync_fetch_and_and), 5922 BUILTIN_ROW(__sync_fetch_and_xor), 5923 BUILTIN_ROW(__sync_fetch_and_nand), 5924 5925 BUILTIN_ROW(__sync_add_and_fetch), 5926 BUILTIN_ROW(__sync_sub_and_fetch), 5927 BUILTIN_ROW(__sync_and_and_fetch), 5928 BUILTIN_ROW(__sync_or_and_fetch), 5929 BUILTIN_ROW(__sync_xor_and_fetch), 5930 BUILTIN_ROW(__sync_nand_and_fetch), 5931 5932 BUILTIN_ROW(__sync_val_compare_and_swap), 5933 BUILTIN_ROW(__sync_bool_compare_and_swap), 5934 BUILTIN_ROW(__sync_lock_test_and_set), 5935 BUILTIN_ROW(__sync_lock_release), 5936 BUILTIN_ROW(__sync_swap) 5937 }; 5938 #undef BUILTIN_ROW 5939 5940 // Determine the index of the size. 5941 unsigned SizeIndex; 5942 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5943 case 1: SizeIndex = 0; break; 5944 case 2: SizeIndex = 1; break; 5945 case 4: SizeIndex = 2; break; 5946 case 8: SizeIndex = 3; break; 5947 case 16: SizeIndex = 4; break; 5948 default: 5949 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5950 << FirstArg->getType() << FirstArg->getSourceRange(); 5951 return ExprError(); 5952 } 5953 5954 // Each of these builtins has one pointer argument, followed by some number of 5955 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5956 // that we ignore. Find out which row of BuiltinIndices to read from as well 5957 // as the number of fixed args. 5958 unsigned BuiltinID = FDecl->getBuiltinID(); 5959 unsigned BuiltinIndex, NumFixed = 1; 5960 bool WarnAboutSemanticsChange = false; 5961 switch (BuiltinID) { 5962 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5963 case Builtin::BI__sync_fetch_and_add: 5964 case Builtin::BI__sync_fetch_and_add_1: 5965 case Builtin::BI__sync_fetch_and_add_2: 5966 case Builtin::BI__sync_fetch_and_add_4: 5967 case Builtin::BI__sync_fetch_and_add_8: 5968 case Builtin::BI__sync_fetch_and_add_16: 5969 BuiltinIndex = 0; 5970 break; 5971 5972 case Builtin::BI__sync_fetch_and_sub: 5973 case Builtin::BI__sync_fetch_and_sub_1: 5974 case Builtin::BI__sync_fetch_and_sub_2: 5975 case Builtin::BI__sync_fetch_and_sub_4: 5976 case Builtin::BI__sync_fetch_and_sub_8: 5977 case Builtin::BI__sync_fetch_and_sub_16: 5978 BuiltinIndex = 1; 5979 break; 5980 5981 case Builtin::BI__sync_fetch_and_or: 5982 case Builtin::BI__sync_fetch_and_or_1: 5983 case Builtin::BI__sync_fetch_and_or_2: 5984 case Builtin::BI__sync_fetch_and_or_4: 5985 case Builtin::BI__sync_fetch_and_or_8: 5986 case Builtin::BI__sync_fetch_and_or_16: 5987 BuiltinIndex = 2; 5988 break; 5989 5990 case Builtin::BI__sync_fetch_and_and: 5991 case Builtin::BI__sync_fetch_and_and_1: 5992 case Builtin::BI__sync_fetch_and_and_2: 5993 case Builtin::BI__sync_fetch_and_and_4: 5994 case Builtin::BI__sync_fetch_and_and_8: 5995 case Builtin::BI__sync_fetch_and_and_16: 5996 BuiltinIndex = 3; 5997 break; 5998 5999 case Builtin::BI__sync_fetch_and_xor: 6000 case Builtin::BI__sync_fetch_and_xor_1: 6001 case Builtin::BI__sync_fetch_and_xor_2: 6002 case Builtin::BI__sync_fetch_and_xor_4: 6003 case Builtin::BI__sync_fetch_and_xor_8: 6004 case Builtin::BI__sync_fetch_and_xor_16: 6005 BuiltinIndex = 4; 6006 break; 6007 6008 case Builtin::BI__sync_fetch_and_nand: 6009 case Builtin::BI__sync_fetch_and_nand_1: 6010 case Builtin::BI__sync_fetch_and_nand_2: 6011 case Builtin::BI__sync_fetch_and_nand_4: 6012 case Builtin::BI__sync_fetch_and_nand_8: 6013 case Builtin::BI__sync_fetch_and_nand_16: 6014 BuiltinIndex = 5; 6015 WarnAboutSemanticsChange = true; 6016 break; 6017 6018 case Builtin::BI__sync_add_and_fetch: 6019 case Builtin::BI__sync_add_and_fetch_1: 6020 case Builtin::BI__sync_add_and_fetch_2: 6021 case Builtin::BI__sync_add_and_fetch_4: 6022 case Builtin::BI__sync_add_and_fetch_8: 6023 case Builtin::BI__sync_add_and_fetch_16: 6024 BuiltinIndex = 6; 6025 break; 6026 6027 case Builtin::BI__sync_sub_and_fetch: 6028 case Builtin::BI__sync_sub_and_fetch_1: 6029 case Builtin::BI__sync_sub_and_fetch_2: 6030 case Builtin::BI__sync_sub_and_fetch_4: 6031 case Builtin::BI__sync_sub_and_fetch_8: 6032 case Builtin::BI__sync_sub_and_fetch_16: 6033 BuiltinIndex = 7; 6034 break; 6035 6036 case Builtin::BI__sync_and_and_fetch: 6037 case Builtin::BI__sync_and_and_fetch_1: 6038 case Builtin::BI__sync_and_and_fetch_2: 6039 case Builtin::BI__sync_and_and_fetch_4: 6040 case Builtin::BI__sync_and_and_fetch_8: 6041 case Builtin::BI__sync_and_and_fetch_16: 6042 BuiltinIndex = 8; 6043 break; 6044 6045 case Builtin::BI__sync_or_and_fetch: 6046 case Builtin::BI__sync_or_and_fetch_1: 6047 case Builtin::BI__sync_or_and_fetch_2: 6048 case Builtin::BI__sync_or_and_fetch_4: 6049 case Builtin::BI__sync_or_and_fetch_8: 6050 case Builtin::BI__sync_or_and_fetch_16: 6051 BuiltinIndex = 9; 6052 break; 6053 6054 case Builtin::BI__sync_xor_and_fetch: 6055 case Builtin::BI__sync_xor_and_fetch_1: 6056 case Builtin::BI__sync_xor_and_fetch_2: 6057 case Builtin::BI__sync_xor_and_fetch_4: 6058 case Builtin::BI__sync_xor_and_fetch_8: 6059 case Builtin::BI__sync_xor_and_fetch_16: 6060 BuiltinIndex = 10; 6061 break; 6062 6063 case Builtin::BI__sync_nand_and_fetch: 6064 case Builtin::BI__sync_nand_and_fetch_1: 6065 case Builtin::BI__sync_nand_and_fetch_2: 6066 case Builtin::BI__sync_nand_and_fetch_4: 6067 case Builtin::BI__sync_nand_and_fetch_8: 6068 case Builtin::BI__sync_nand_and_fetch_16: 6069 BuiltinIndex = 11; 6070 WarnAboutSemanticsChange = true; 6071 break; 6072 6073 case Builtin::BI__sync_val_compare_and_swap: 6074 case Builtin::BI__sync_val_compare_and_swap_1: 6075 case Builtin::BI__sync_val_compare_and_swap_2: 6076 case Builtin::BI__sync_val_compare_and_swap_4: 6077 case Builtin::BI__sync_val_compare_and_swap_8: 6078 case Builtin::BI__sync_val_compare_and_swap_16: 6079 BuiltinIndex = 12; 6080 NumFixed = 2; 6081 break; 6082 6083 case Builtin::BI__sync_bool_compare_and_swap: 6084 case Builtin::BI__sync_bool_compare_and_swap_1: 6085 case Builtin::BI__sync_bool_compare_and_swap_2: 6086 case Builtin::BI__sync_bool_compare_and_swap_4: 6087 case Builtin::BI__sync_bool_compare_and_swap_8: 6088 case Builtin::BI__sync_bool_compare_and_swap_16: 6089 BuiltinIndex = 13; 6090 NumFixed = 2; 6091 ResultType = Context.BoolTy; 6092 break; 6093 6094 case Builtin::BI__sync_lock_test_and_set: 6095 case Builtin::BI__sync_lock_test_and_set_1: 6096 case Builtin::BI__sync_lock_test_and_set_2: 6097 case Builtin::BI__sync_lock_test_and_set_4: 6098 case Builtin::BI__sync_lock_test_and_set_8: 6099 case Builtin::BI__sync_lock_test_and_set_16: 6100 BuiltinIndex = 14; 6101 break; 6102 6103 case Builtin::BI__sync_lock_release: 6104 case Builtin::BI__sync_lock_release_1: 6105 case Builtin::BI__sync_lock_release_2: 6106 case Builtin::BI__sync_lock_release_4: 6107 case Builtin::BI__sync_lock_release_8: 6108 case Builtin::BI__sync_lock_release_16: 6109 BuiltinIndex = 15; 6110 NumFixed = 0; 6111 ResultType = Context.VoidTy; 6112 break; 6113 6114 case Builtin::BI__sync_swap: 6115 case Builtin::BI__sync_swap_1: 6116 case Builtin::BI__sync_swap_2: 6117 case Builtin::BI__sync_swap_4: 6118 case Builtin::BI__sync_swap_8: 6119 case Builtin::BI__sync_swap_16: 6120 BuiltinIndex = 16; 6121 break; 6122 } 6123 6124 // Now that we know how many fixed arguments we expect, first check that we 6125 // have at least that many. 6126 if (TheCall->getNumArgs() < 1+NumFixed) { 6127 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6128 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6129 << Callee->getSourceRange(); 6130 return ExprError(); 6131 } 6132 6133 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6134 << Callee->getSourceRange(); 6135 6136 if (WarnAboutSemanticsChange) { 6137 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6138 << Callee->getSourceRange(); 6139 } 6140 6141 // Get the decl for the concrete builtin from this, we can tell what the 6142 // concrete integer type we should convert to is. 6143 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6144 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6145 FunctionDecl *NewBuiltinDecl; 6146 if (NewBuiltinID == BuiltinID) 6147 NewBuiltinDecl = FDecl; 6148 else { 6149 // Perform builtin lookup to avoid redeclaring it. 6150 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6151 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6152 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6153 assert(Res.getFoundDecl()); 6154 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6155 if (!NewBuiltinDecl) 6156 return ExprError(); 6157 } 6158 6159 // The first argument --- the pointer --- has a fixed type; we 6160 // deduce the types of the rest of the arguments accordingly. Walk 6161 // the remaining arguments, converting them to the deduced value type. 6162 for (unsigned i = 0; i != NumFixed; ++i) { 6163 ExprResult Arg = TheCall->getArg(i+1); 6164 6165 // GCC does an implicit conversion to the pointer or integer ValType. This 6166 // can fail in some cases (1i -> int**), check for this error case now. 6167 // Initialize the argument. 6168 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6169 ValType, /*consume*/ false); 6170 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6171 if (Arg.isInvalid()) 6172 return ExprError(); 6173 6174 // Okay, we have something that *can* be converted to the right type. Check 6175 // to see if there is a potentially weird extension going on here. This can 6176 // happen when you do an atomic operation on something like an char* and 6177 // pass in 42. The 42 gets converted to char. This is even more strange 6178 // for things like 45.123 -> char, etc. 6179 // FIXME: Do this check. 6180 TheCall->setArg(i+1, Arg.get()); 6181 } 6182 6183 // Create a new DeclRefExpr to refer to the new decl. 6184 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6185 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6186 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6187 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6188 6189 // Set the callee in the CallExpr. 6190 // FIXME: This loses syntactic information. 6191 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6192 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6193 CK_BuiltinFnToFnPtr); 6194 TheCall->setCallee(PromotedCall.get()); 6195 6196 // Change the result type of the call to match the original value type. This 6197 // is arbitrary, but the codegen for these builtins ins design to handle it 6198 // gracefully. 6199 TheCall->setType(ResultType); 6200 6201 // Prohibit use of _ExtInt with atomic builtins. 6202 // The arguments would have already been converted to the first argument's 6203 // type, so only need to check the first argument. 6204 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 6205 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 6206 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6207 return ExprError(); 6208 } 6209 6210 return TheCallResult; 6211 } 6212 6213 /// SemaBuiltinNontemporalOverloaded - We have a call to 6214 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6215 /// overloaded function based on the pointer type of its last argument. 6216 /// 6217 /// This function goes through and does final semantic checking for these 6218 /// builtins. 6219 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6220 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6221 DeclRefExpr *DRE = 6222 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6223 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6224 unsigned BuiltinID = FDecl->getBuiltinID(); 6225 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6226 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6227 "Unexpected nontemporal load/store builtin!"); 6228 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6229 unsigned numArgs = isStore ? 2 : 1; 6230 6231 // Ensure that we have the proper number of arguments. 6232 if (checkArgCount(*this, TheCall, numArgs)) 6233 return ExprError(); 6234 6235 // Inspect the last argument of the nontemporal builtin. This should always 6236 // be a pointer type, from which we imply the type of the memory access. 6237 // Because it is a pointer type, we don't have to worry about any implicit 6238 // casts here. 6239 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6240 ExprResult PointerArgResult = 6241 DefaultFunctionArrayLvalueConversion(PointerArg); 6242 6243 if (PointerArgResult.isInvalid()) 6244 return ExprError(); 6245 PointerArg = PointerArgResult.get(); 6246 TheCall->setArg(numArgs - 1, PointerArg); 6247 6248 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6249 if (!pointerType) { 6250 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6251 << PointerArg->getType() << PointerArg->getSourceRange(); 6252 return ExprError(); 6253 } 6254 6255 QualType ValType = pointerType->getPointeeType(); 6256 6257 // Strip any qualifiers off ValType. 6258 ValType = ValType.getUnqualifiedType(); 6259 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6260 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6261 !ValType->isVectorType()) { 6262 Diag(DRE->getBeginLoc(), 6263 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6264 << PointerArg->getType() << PointerArg->getSourceRange(); 6265 return ExprError(); 6266 } 6267 6268 if (!isStore) { 6269 TheCall->setType(ValType); 6270 return TheCallResult; 6271 } 6272 6273 ExprResult ValArg = TheCall->getArg(0); 6274 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6275 Context, ValType, /*consume*/ false); 6276 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6277 if (ValArg.isInvalid()) 6278 return ExprError(); 6279 6280 TheCall->setArg(0, ValArg.get()); 6281 TheCall->setType(Context.VoidTy); 6282 return TheCallResult; 6283 } 6284 6285 /// CheckObjCString - Checks that the argument to the builtin 6286 /// CFString constructor is correct 6287 /// Note: It might also make sense to do the UTF-16 conversion here (would 6288 /// simplify the backend). 6289 bool Sema::CheckObjCString(Expr *Arg) { 6290 Arg = Arg->IgnoreParenCasts(); 6291 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6292 6293 if (!Literal || !Literal->isAscii()) { 6294 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6295 << Arg->getSourceRange(); 6296 return true; 6297 } 6298 6299 if (Literal->containsNonAsciiOrNull()) { 6300 StringRef String = Literal->getString(); 6301 unsigned NumBytes = String.size(); 6302 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6303 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6304 llvm::UTF16 *ToPtr = &ToBuf[0]; 6305 6306 llvm::ConversionResult Result = 6307 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6308 ToPtr + NumBytes, llvm::strictConversion); 6309 // Check for conversion failure. 6310 if (Result != llvm::conversionOK) 6311 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6312 << Arg->getSourceRange(); 6313 } 6314 return false; 6315 } 6316 6317 /// CheckObjCString - Checks that the format string argument to the os_log() 6318 /// and os_trace() functions is correct, and converts it to const char *. 6319 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6320 Arg = Arg->IgnoreParenCasts(); 6321 auto *Literal = dyn_cast<StringLiteral>(Arg); 6322 if (!Literal) { 6323 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6324 Literal = ObjcLiteral->getString(); 6325 } 6326 } 6327 6328 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6329 return ExprError( 6330 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6331 << Arg->getSourceRange()); 6332 } 6333 6334 ExprResult Result(Literal); 6335 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6336 InitializedEntity Entity = 6337 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6338 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6339 return Result; 6340 } 6341 6342 /// Check that the user is calling the appropriate va_start builtin for the 6343 /// target and calling convention. 6344 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6345 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6346 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6347 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6348 TT.getArch() == llvm::Triple::aarch64_32); 6349 bool IsWindows = TT.isOSWindows(); 6350 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6351 if (IsX64 || IsAArch64) { 6352 CallingConv CC = CC_C; 6353 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6354 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6355 if (IsMSVAStart) { 6356 // Don't allow this in System V ABI functions. 6357 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6358 return S.Diag(Fn->getBeginLoc(), 6359 diag::err_ms_va_start_used_in_sysv_function); 6360 } else { 6361 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6362 // On x64 Windows, don't allow this in System V ABI functions. 6363 // (Yes, that means there's no corresponding way to support variadic 6364 // System V ABI functions on Windows.) 6365 if ((IsWindows && CC == CC_X86_64SysV) || 6366 (!IsWindows && CC == CC_Win64)) 6367 return S.Diag(Fn->getBeginLoc(), 6368 diag::err_va_start_used_in_wrong_abi_function) 6369 << !IsWindows; 6370 } 6371 return false; 6372 } 6373 6374 if (IsMSVAStart) 6375 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6376 return false; 6377 } 6378 6379 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6380 ParmVarDecl **LastParam = nullptr) { 6381 // Determine whether the current function, block, or obj-c method is variadic 6382 // and get its parameter list. 6383 bool IsVariadic = false; 6384 ArrayRef<ParmVarDecl *> Params; 6385 DeclContext *Caller = S.CurContext; 6386 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6387 IsVariadic = Block->isVariadic(); 6388 Params = Block->parameters(); 6389 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6390 IsVariadic = FD->isVariadic(); 6391 Params = FD->parameters(); 6392 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6393 IsVariadic = MD->isVariadic(); 6394 // FIXME: This isn't correct for methods (results in bogus warning). 6395 Params = MD->parameters(); 6396 } else if (isa<CapturedDecl>(Caller)) { 6397 // We don't support va_start in a CapturedDecl. 6398 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6399 return true; 6400 } else { 6401 // This must be some other declcontext that parses exprs. 6402 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6403 return true; 6404 } 6405 6406 if (!IsVariadic) { 6407 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6408 return true; 6409 } 6410 6411 if (LastParam) 6412 *LastParam = Params.empty() ? nullptr : Params.back(); 6413 6414 return false; 6415 } 6416 6417 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6418 /// for validity. Emit an error and return true on failure; return false 6419 /// on success. 6420 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6421 Expr *Fn = TheCall->getCallee(); 6422 6423 if (checkVAStartABI(*this, BuiltinID, Fn)) 6424 return true; 6425 6426 if (checkArgCount(*this, TheCall, 2)) 6427 return true; 6428 6429 // Type-check the first argument normally. 6430 if (checkBuiltinArgument(*this, TheCall, 0)) 6431 return true; 6432 6433 // Check that the current function is variadic, and get its last parameter. 6434 ParmVarDecl *LastParam; 6435 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6436 return true; 6437 6438 // Verify that the second argument to the builtin is the last argument of the 6439 // current function or method. 6440 bool SecondArgIsLastNamedArgument = false; 6441 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6442 6443 // These are valid if SecondArgIsLastNamedArgument is false after the next 6444 // block. 6445 QualType Type; 6446 SourceLocation ParamLoc; 6447 bool IsCRegister = false; 6448 6449 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6450 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6451 SecondArgIsLastNamedArgument = PV == LastParam; 6452 6453 Type = PV->getType(); 6454 ParamLoc = PV->getLocation(); 6455 IsCRegister = 6456 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6457 } 6458 } 6459 6460 if (!SecondArgIsLastNamedArgument) 6461 Diag(TheCall->getArg(1)->getBeginLoc(), 6462 diag::warn_second_arg_of_va_start_not_last_named_param); 6463 else if (IsCRegister || Type->isReferenceType() || 6464 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6465 // Promotable integers are UB, but enumerations need a bit of 6466 // extra checking to see what their promotable type actually is. 6467 if (!Type->isPromotableIntegerType()) 6468 return false; 6469 if (!Type->isEnumeralType()) 6470 return true; 6471 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6472 return !(ED && 6473 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6474 }()) { 6475 unsigned Reason = 0; 6476 if (Type->isReferenceType()) Reason = 1; 6477 else if (IsCRegister) Reason = 2; 6478 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6479 Diag(ParamLoc, diag::note_parameter_type) << Type; 6480 } 6481 6482 TheCall->setType(Context.VoidTy); 6483 return false; 6484 } 6485 6486 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6487 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6488 const LangOptions &LO = getLangOpts(); 6489 6490 if (LO.CPlusPlus) 6491 return Arg->getType() 6492 .getCanonicalType() 6493 .getTypePtr() 6494 ->getPointeeType() 6495 .withoutLocalFastQualifiers() == Context.CharTy; 6496 6497 // In C, allow aliasing through `char *`, this is required for AArch64 at 6498 // least. 6499 return true; 6500 }; 6501 6502 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6503 // const char *named_addr); 6504 6505 Expr *Func = Call->getCallee(); 6506 6507 if (Call->getNumArgs() < 3) 6508 return Diag(Call->getEndLoc(), 6509 diag::err_typecheck_call_too_few_args_at_least) 6510 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6511 6512 // Type-check the first argument normally. 6513 if (checkBuiltinArgument(*this, Call, 0)) 6514 return true; 6515 6516 // Check that the current function is variadic. 6517 if (checkVAStartIsInVariadicFunction(*this, Func)) 6518 return true; 6519 6520 // __va_start on Windows does not validate the parameter qualifiers 6521 6522 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6523 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6524 6525 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6526 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6527 6528 const QualType &ConstCharPtrTy = 6529 Context.getPointerType(Context.CharTy.withConst()); 6530 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6531 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6532 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6533 << 0 /* qualifier difference */ 6534 << 3 /* parameter mismatch */ 6535 << 2 << Arg1->getType() << ConstCharPtrTy; 6536 6537 const QualType SizeTy = Context.getSizeType(); 6538 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6539 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6540 << Arg2->getType() << SizeTy << 1 /* different class */ 6541 << 0 /* qualifier difference */ 6542 << 3 /* parameter mismatch */ 6543 << 3 << Arg2->getType() << SizeTy; 6544 6545 return false; 6546 } 6547 6548 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6549 /// friends. This is declared to take (...), so we have to check everything. 6550 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6551 if (checkArgCount(*this, TheCall, 2)) 6552 return true; 6553 6554 ExprResult OrigArg0 = TheCall->getArg(0); 6555 ExprResult OrigArg1 = TheCall->getArg(1); 6556 6557 // Do standard promotions between the two arguments, returning their common 6558 // type. 6559 QualType Res = UsualArithmeticConversions( 6560 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6561 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6562 return true; 6563 6564 // Make sure any conversions are pushed back into the call; this is 6565 // type safe since unordered compare builtins are declared as "_Bool 6566 // foo(...)". 6567 TheCall->setArg(0, OrigArg0.get()); 6568 TheCall->setArg(1, OrigArg1.get()); 6569 6570 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6571 return false; 6572 6573 // If the common type isn't a real floating type, then the arguments were 6574 // invalid for this operation. 6575 if (Res.isNull() || !Res->isRealFloatingType()) 6576 return Diag(OrigArg0.get()->getBeginLoc(), 6577 diag::err_typecheck_call_invalid_ordered_compare) 6578 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6579 << SourceRange(OrigArg0.get()->getBeginLoc(), 6580 OrigArg1.get()->getEndLoc()); 6581 6582 return false; 6583 } 6584 6585 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6586 /// __builtin_isnan and friends. This is declared to take (...), so we have 6587 /// to check everything. We expect the last argument to be a floating point 6588 /// value. 6589 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6590 if (checkArgCount(*this, TheCall, NumArgs)) 6591 return true; 6592 6593 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6594 // on all preceding parameters just being int. Try all of those. 6595 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6596 Expr *Arg = TheCall->getArg(i); 6597 6598 if (Arg->isTypeDependent()) 6599 return false; 6600 6601 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6602 6603 if (Res.isInvalid()) 6604 return true; 6605 TheCall->setArg(i, Res.get()); 6606 } 6607 6608 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6609 6610 if (OrigArg->isTypeDependent()) 6611 return false; 6612 6613 // Usual Unary Conversions will convert half to float, which we want for 6614 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6615 // type how it is, but do normal L->Rvalue conversions. 6616 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6617 OrigArg = UsualUnaryConversions(OrigArg).get(); 6618 else 6619 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6620 TheCall->setArg(NumArgs - 1, OrigArg); 6621 6622 // This operation requires a non-_Complex floating-point number. 6623 if (!OrigArg->getType()->isRealFloatingType()) 6624 return Diag(OrigArg->getBeginLoc(), 6625 diag::err_typecheck_call_invalid_unary_fp) 6626 << OrigArg->getType() << OrigArg->getSourceRange(); 6627 6628 return false; 6629 } 6630 6631 /// Perform semantic analysis for a call to __builtin_complex. 6632 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6633 if (checkArgCount(*this, TheCall, 2)) 6634 return true; 6635 6636 bool Dependent = false; 6637 for (unsigned I = 0; I != 2; ++I) { 6638 Expr *Arg = TheCall->getArg(I); 6639 QualType T = Arg->getType(); 6640 if (T->isDependentType()) { 6641 Dependent = true; 6642 continue; 6643 } 6644 6645 // Despite supporting _Complex int, GCC requires a real floating point type 6646 // for the operands of __builtin_complex. 6647 if (!T->isRealFloatingType()) { 6648 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6649 << Arg->getType() << Arg->getSourceRange(); 6650 } 6651 6652 ExprResult Converted = DefaultLvalueConversion(Arg); 6653 if (Converted.isInvalid()) 6654 return true; 6655 TheCall->setArg(I, Converted.get()); 6656 } 6657 6658 if (Dependent) { 6659 TheCall->setType(Context.DependentTy); 6660 return false; 6661 } 6662 6663 Expr *Real = TheCall->getArg(0); 6664 Expr *Imag = TheCall->getArg(1); 6665 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6666 return Diag(Real->getBeginLoc(), 6667 diag::err_typecheck_call_different_arg_types) 6668 << Real->getType() << Imag->getType() 6669 << Real->getSourceRange() << Imag->getSourceRange(); 6670 } 6671 6672 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6673 // don't allow this builtin to form those types either. 6674 // FIXME: Should we allow these types? 6675 if (Real->getType()->isFloat16Type()) 6676 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6677 << "_Float16"; 6678 if (Real->getType()->isHalfType()) 6679 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6680 << "half"; 6681 6682 TheCall->setType(Context.getComplexType(Real->getType())); 6683 return false; 6684 } 6685 6686 // Customized Sema Checking for VSX builtins that have the following signature: 6687 // vector [...] builtinName(vector [...], vector [...], const int); 6688 // Which takes the same type of vectors (any legal vector type) for the first 6689 // two arguments and takes compile time constant for the third argument. 6690 // Example builtins are : 6691 // vector double vec_xxpermdi(vector double, vector double, int); 6692 // vector short vec_xxsldwi(vector short, vector short, int); 6693 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6694 unsigned ExpectedNumArgs = 3; 6695 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6696 return true; 6697 6698 // Check the third argument is a compile time constant 6699 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6700 return Diag(TheCall->getBeginLoc(), 6701 diag::err_vsx_builtin_nonconstant_argument) 6702 << 3 /* argument index */ << TheCall->getDirectCallee() 6703 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6704 TheCall->getArg(2)->getEndLoc()); 6705 6706 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6707 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6708 6709 // Check the type of argument 1 and argument 2 are vectors. 6710 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6711 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6712 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6713 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6714 << TheCall->getDirectCallee() 6715 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6716 TheCall->getArg(1)->getEndLoc()); 6717 } 6718 6719 // Check the first two arguments are the same type. 6720 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6721 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6722 << TheCall->getDirectCallee() 6723 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6724 TheCall->getArg(1)->getEndLoc()); 6725 } 6726 6727 // When default clang type checking is turned off and the customized type 6728 // checking is used, the returning type of the function must be explicitly 6729 // set. Otherwise it is _Bool by default. 6730 TheCall->setType(Arg1Ty); 6731 6732 return false; 6733 } 6734 6735 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6736 // This is declared to take (...), so we have to check everything. 6737 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6738 if (TheCall->getNumArgs() < 2) 6739 return ExprError(Diag(TheCall->getEndLoc(), 6740 diag::err_typecheck_call_too_few_args_at_least) 6741 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6742 << TheCall->getSourceRange()); 6743 6744 // Determine which of the following types of shufflevector we're checking: 6745 // 1) unary, vector mask: (lhs, mask) 6746 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6747 QualType resType = TheCall->getArg(0)->getType(); 6748 unsigned numElements = 0; 6749 6750 if (!TheCall->getArg(0)->isTypeDependent() && 6751 !TheCall->getArg(1)->isTypeDependent()) { 6752 QualType LHSType = TheCall->getArg(0)->getType(); 6753 QualType RHSType = TheCall->getArg(1)->getType(); 6754 6755 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6756 return ExprError( 6757 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6758 << TheCall->getDirectCallee() 6759 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6760 TheCall->getArg(1)->getEndLoc())); 6761 6762 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6763 unsigned numResElements = TheCall->getNumArgs() - 2; 6764 6765 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6766 // with mask. If so, verify that RHS is an integer vector type with the 6767 // same number of elts as lhs. 6768 if (TheCall->getNumArgs() == 2) { 6769 if (!RHSType->hasIntegerRepresentation() || 6770 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6771 return ExprError(Diag(TheCall->getBeginLoc(), 6772 diag::err_vec_builtin_incompatible_vector) 6773 << TheCall->getDirectCallee() 6774 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6775 TheCall->getArg(1)->getEndLoc())); 6776 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6777 return ExprError(Diag(TheCall->getBeginLoc(), 6778 diag::err_vec_builtin_incompatible_vector) 6779 << TheCall->getDirectCallee() 6780 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6781 TheCall->getArg(1)->getEndLoc())); 6782 } else if (numElements != numResElements) { 6783 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6784 resType = Context.getVectorType(eltType, numResElements, 6785 VectorType::GenericVector); 6786 } 6787 } 6788 6789 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6790 if (TheCall->getArg(i)->isTypeDependent() || 6791 TheCall->getArg(i)->isValueDependent()) 6792 continue; 6793 6794 Optional<llvm::APSInt> Result; 6795 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6796 return ExprError(Diag(TheCall->getBeginLoc(), 6797 diag::err_shufflevector_nonconstant_argument) 6798 << TheCall->getArg(i)->getSourceRange()); 6799 6800 // Allow -1 which will be translated to undef in the IR. 6801 if (Result->isSigned() && Result->isAllOnes()) 6802 continue; 6803 6804 if (Result->getActiveBits() > 64 || 6805 Result->getZExtValue() >= numElements * 2) 6806 return ExprError(Diag(TheCall->getBeginLoc(), 6807 diag::err_shufflevector_argument_too_large) 6808 << TheCall->getArg(i)->getSourceRange()); 6809 } 6810 6811 SmallVector<Expr*, 32> exprs; 6812 6813 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6814 exprs.push_back(TheCall->getArg(i)); 6815 TheCall->setArg(i, nullptr); 6816 } 6817 6818 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6819 TheCall->getCallee()->getBeginLoc(), 6820 TheCall->getRParenLoc()); 6821 } 6822 6823 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6824 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6825 SourceLocation BuiltinLoc, 6826 SourceLocation RParenLoc) { 6827 ExprValueKind VK = VK_PRValue; 6828 ExprObjectKind OK = OK_Ordinary; 6829 QualType DstTy = TInfo->getType(); 6830 QualType SrcTy = E->getType(); 6831 6832 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6833 return ExprError(Diag(BuiltinLoc, 6834 diag::err_convertvector_non_vector) 6835 << E->getSourceRange()); 6836 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6837 return ExprError(Diag(BuiltinLoc, 6838 diag::err_convertvector_non_vector_type)); 6839 6840 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6841 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6842 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6843 if (SrcElts != DstElts) 6844 return ExprError(Diag(BuiltinLoc, 6845 diag::err_convertvector_incompatible_vector) 6846 << E->getSourceRange()); 6847 } 6848 6849 return new (Context) 6850 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6851 } 6852 6853 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6854 // This is declared to take (const void*, ...) and can take two 6855 // optional constant int args. 6856 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6857 unsigned NumArgs = TheCall->getNumArgs(); 6858 6859 if (NumArgs > 3) 6860 return Diag(TheCall->getEndLoc(), 6861 diag::err_typecheck_call_too_many_args_at_most) 6862 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6863 6864 // Argument 0 is checked for us and the remaining arguments must be 6865 // constant integers. 6866 for (unsigned i = 1; i != NumArgs; ++i) 6867 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6868 return true; 6869 6870 return false; 6871 } 6872 6873 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6874 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6875 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6876 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6877 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6878 if (checkArgCount(*this, TheCall, 1)) 6879 return true; 6880 Expr *Arg = TheCall->getArg(0); 6881 if (Arg->isInstantiationDependent()) 6882 return false; 6883 6884 QualType ArgTy = Arg->getType(); 6885 if (!ArgTy->hasFloatingRepresentation()) 6886 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6887 << ArgTy; 6888 if (Arg->isLValue()) { 6889 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6890 TheCall->setArg(0, FirstArg.get()); 6891 } 6892 TheCall->setType(TheCall->getArg(0)->getType()); 6893 return false; 6894 } 6895 6896 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6897 // __assume does not evaluate its arguments, and should warn if its argument 6898 // has side effects. 6899 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6900 Expr *Arg = TheCall->getArg(0); 6901 if (Arg->isInstantiationDependent()) return false; 6902 6903 if (Arg->HasSideEffects(Context)) 6904 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6905 << Arg->getSourceRange() 6906 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6907 6908 return false; 6909 } 6910 6911 /// Handle __builtin_alloca_with_align. This is declared 6912 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6913 /// than 8. 6914 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6915 // The alignment must be a constant integer. 6916 Expr *Arg = TheCall->getArg(1); 6917 6918 // We can't check the value of a dependent argument. 6919 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6920 if (const auto *UE = 6921 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6922 if (UE->getKind() == UETT_AlignOf || 6923 UE->getKind() == UETT_PreferredAlignOf) 6924 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6925 << Arg->getSourceRange(); 6926 6927 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6928 6929 if (!Result.isPowerOf2()) 6930 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6931 << Arg->getSourceRange(); 6932 6933 if (Result < Context.getCharWidth()) 6934 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6935 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6936 6937 if (Result > std::numeric_limits<int32_t>::max()) 6938 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6939 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6940 } 6941 6942 return false; 6943 } 6944 6945 /// Handle __builtin_assume_aligned. This is declared 6946 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6947 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6948 unsigned NumArgs = TheCall->getNumArgs(); 6949 6950 if (NumArgs > 3) 6951 return Diag(TheCall->getEndLoc(), 6952 diag::err_typecheck_call_too_many_args_at_most) 6953 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6954 6955 // The alignment must be a constant integer. 6956 Expr *Arg = TheCall->getArg(1); 6957 6958 // We can't check the value of a dependent argument. 6959 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6960 llvm::APSInt Result; 6961 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6962 return true; 6963 6964 if (!Result.isPowerOf2()) 6965 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6966 << Arg->getSourceRange(); 6967 6968 if (Result > Sema::MaximumAlignment) 6969 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6970 << Arg->getSourceRange() << Sema::MaximumAlignment; 6971 } 6972 6973 if (NumArgs > 2) { 6974 ExprResult Arg(TheCall->getArg(2)); 6975 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6976 Context.getSizeType(), false); 6977 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6978 if (Arg.isInvalid()) return true; 6979 TheCall->setArg(2, Arg.get()); 6980 } 6981 6982 return false; 6983 } 6984 6985 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6986 unsigned BuiltinID = 6987 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6988 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6989 6990 unsigned NumArgs = TheCall->getNumArgs(); 6991 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6992 if (NumArgs < NumRequiredArgs) { 6993 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6994 << 0 /* function call */ << NumRequiredArgs << NumArgs 6995 << TheCall->getSourceRange(); 6996 } 6997 if (NumArgs >= NumRequiredArgs + 0x100) { 6998 return Diag(TheCall->getEndLoc(), 6999 diag::err_typecheck_call_too_many_args_at_most) 7000 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 7001 << TheCall->getSourceRange(); 7002 } 7003 unsigned i = 0; 7004 7005 // For formatting call, check buffer arg. 7006 if (!IsSizeCall) { 7007 ExprResult Arg(TheCall->getArg(i)); 7008 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7009 Context, Context.VoidPtrTy, false); 7010 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7011 if (Arg.isInvalid()) 7012 return true; 7013 TheCall->setArg(i, Arg.get()); 7014 i++; 7015 } 7016 7017 // Check string literal arg. 7018 unsigned FormatIdx = i; 7019 { 7020 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 7021 if (Arg.isInvalid()) 7022 return true; 7023 TheCall->setArg(i, Arg.get()); 7024 i++; 7025 } 7026 7027 // Make sure variadic args are scalar. 7028 unsigned FirstDataArg = i; 7029 while (i < NumArgs) { 7030 ExprResult Arg = DefaultVariadicArgumentPromotion( 7031 TheCall->getArg(i), VariadicFunction, nullptr); 7032 if (Arg.isInvalid()) 7033 return true; 7034 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7035 if (ArgSize.getQuantity() >= 0x100) { 7036 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7037 << i << (int)ArgSize.getQuantity() << 0xff 7038 << TheCall->getSourceRange(); 7039 } 7040 TheCall->setArg(i, Arg.get()); 7041 i++; 7042 } 7043 7044 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7045 // call to avoid duplicate diagnostics. 7046 if (!IsSizeCall) { 7047 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7048 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7049 bool Success = CheckFormatArguments( 7050 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7051 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7052 CheckedVarArgs); 7053 if (!Success) 7054 return true; 7055 } 7056 7057 if (IsSizeCall) { 7058 TheCall->setType(Context.getSizeType()); 7059 } else { 7060 TheCall->setType(Context.VoidPtrTy); 7061 } 7062 return false; 7063 } 7064 7065 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7066 /// TheCall is a constant expression. 7067 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7068 llvm::APSInt &Result) { 7069 Expr *Arg = TheCall->getArg(ArgNum); 7070 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7071 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7072 7073 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7074 7075 Optional<llvm::APSInt> R; 7076 if (!(R = Arg->getIntegerConstantExpr(Context))) 7077 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7078 << FDecl->getDeclName() << Arg->getSourceRange(); 7079 Result = *R; 7080 return false; 7081 } 7082 7083 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7084 /// TheCall is a constant expression in the range [Low, High]. 7085 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7086 int Low, int High, bool RangeIsError) { 7087 if (isConstantEvaluated()) 7088 return false; 7089 llvm::APSInt Result; 7090 7091 // We can't check the value of a dependent argument. 7092 Expr *Arg = TheCall->getArg(ArgNum); 7093 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7094 return false; 7095 7096 // Check constant-ness first. 7097 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7098 return true; 7099 7100 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7101 if (RangeIsError) 7102 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7103 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7104 else 7105 // Defer the warning until we know if the code will be emitted so that 7106 // dead code can ignore this. 7107 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7108 PDiag(diag::warn_argument_invalid_range) 7109 << toString(Result, 10) << Low << High 7110 << Arg->getSourceRange()); 7111 } 7112 7113 return false; 7114 } 7115 7116 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7117 /// TheCall is a constant expression is a multiple of Num.. 7118 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7119 unsigned Num) { 7120 llvm::APSInt Result; 7121 7122 // We can't check the value of a dependent argument. 7123 Expr *Arg = TheCall->getArg(ArgNum); 7124 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7125 return false; 7126 7127 // Check constant-ness first. 7128 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7129 return true; 7130 7131 if (Result.getSExtValue() % Num != 0) 7132 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7133 << Num << Arg->getSourceRange(); 7134 7135 return false; 7136 } 7137 7138 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7139 /// constant expression representing a power of 2. 7140 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7141 llvm::APSInt Result; 7142 7143 // We can't check the value of a dependent argument. 7144 Expr *Arg = TheCall->getArg(ArgNum); 7145 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7146 return false; 7147 7148 // Check constant-ness first. 7149 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7150 return true; 7151 7152 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7153 // and only if x is a power of 2. 7154 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7155 return false; 7156 7157 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7158 << Arg->getSourceRange(); 7159 } 7160 7161 static bool IsShiftedByte(llvm::APSInt Value) { 7162 if (Value.isNegative()) 7163 return false; 7164 7165 // Check if it's a shifted byte, by shifting it down 7166 while (true) { 7167 // If the value fits in the bottom byte, the check passes. 7168 if (Value < 0x100) 7169 return true; 7170 7171 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7172 // fails. 7173 if ((Value & 0xFF) != 0) 7174 return false; 7175 7176 // If the bottom 8 bits are all 0, but something above that is nonzero, 7177 // then shifting the value right by 8 bits won't affect whether it's a 7178 // shifted byte or not. So do that, and go round again. 7179 Value >>= 8; 7180 } 7181 } 7182 7183 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7184 /// a constant expression representing an arbitrary byte value shifted left by 7185 /// a multiple of 8 bits. 7186 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7187 unsigned ArgBits) { 7188 llvm::APSInt Result; 7189 7190 // We can't check the value of a dependent argument. 7191 Expr *Arg = TheCall->getArg(ArgNum); 7192 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7193 return false; 7194 7195 // Check constant-ness first. 7196 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7197 return true; 7198 7199 // Truncate to the given size. 7200 Result = Result.getLoBits(ArgBits); 7201 Result.setIsUnsigned(true); 7202 7203 if (IsShiftedByte(Result)) 7204 return false; 7205 7206 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7207 << Arg->getSourceRange(); 7208 } 7209 7210 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7211 /// TheCall is a constant expression representing either a shifted byte value, 7212 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7213 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7214 /// Arm MVE intrinsics. 7215 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7216 int ArgNum, 7217 unsigned ArgBits) { 7218 llvm::APSInt Result; 7219 7220 // We can't check the value of a dependent argument. 7221 Expr *Arg = TheCall->getArg(ArgNum); 7222 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7223 return false; 7224 7225 // Check constant-ness first. 7226 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7227 return true; 7228 7229 // Truncate to the given size. 7230 Result = Result.getLoBits(ArgBits); 7231 Result.setIsUnsigned(true); 7232 7233 // Check to see if it's in either of the required forms. 7234 if (IsShiftedByte(Result) || 7235 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7236 return false; 7237 7238 return Diag(TheCall->getBeginLoc(), 7239 diag::err_argument_not_shifted_byte_or_xxff) 7240 << Arg->getSourceRange(); 7241 } 7242 7243 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7244 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7245 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7246 if (checkArgCount(*this, TheCall, 2)) 7247 return true; 7248 Expr *Arg0 = TheCall->getArg(0); 7249 Expr *Arg1 = TheCall->getArg(1); 7250 7251 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7252 if (FirstArg.isInvalid()) 7253 return true; 7254 QualType FirstArgType = FirstArg.get()->getType(); 7255 if (!FirstArgType->isAnyPointerType()) 7256 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7257 << "first" << FirstArgType << Arg0->getSourceRange(); 7258 TheCall->setArg(0, FirstArg.get()); 7259 7260 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7261 if (SecArg.isInvalid()) 7262 return true; 7263 QualType SecArgType = SecArg.get()->getType(); 7264 if (!SecArgType->isIntegerType()) 7265 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7266 << "second" << SecArgType << Arg1->getSourceRange(); 7267 7268 // Derive the return type from the pointer argument. 7269 TheCall->setType(FirstArgType); 7270 return false; 7271 } 7272 7273 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7274 if (checkArgCount(*this, TheCall, 2)) 7275 return true; 7276 7277 Expr *Arg0 = TheCall->getArg(0); 7278 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7279 if (FirstArg.isInvalid()) 7280 return true; 7281 QualType FirstArgType = FirstArg.get()->getType(); 7282 if (!FirstArgType->isAnyPointerType()) 7283 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7284 << "first" << FirstArgType << Arg0->getSourceRange(); 7285 TheCall->setArg(0, FirstArg.get()); 7286 7287 // Derive the return type from the pointer argument. 7288 TheCall->setType(FirstArgType); 7289 7290 // Second arg must be an constant in range [0,15] 7291 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7292 } 7293 7294 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7295 if (checkArgCount(*this, TheCall, 2)) 7296 return true; 7297 Expr *Arg0 = TheCall->getArg(0); 7298 Expr *Arg1 = TheCall->getArg(1); 7299 7300 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7301 if (FirstArg.isInvalid()) 7302 return true; 7303 QualType FirstArgType = FirstArg.get()->getType(); 7304 if (!FirstArgType->isAnyPointerType()) 7305 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7306 << "first" << FirstArgType << Arg0->getSourceRange(); 7307 7308 QualType SecArgType = Arg1->getType(); 7309 if (!SecArgType->isIntegerType()) 7310 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7311 << "second" << SecArgType << Arg1->getSourceRange(); 7312 TheCall->setType(Context.IntTy); 7313 return false; 7314 } 7315 7316 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7317 BuiltinID == AArch64::BI__builtin_arm_stg) { 7318 if (checkArgCount(*this, TheCall, 1)) 7319 return true; 7320 Expr *Arg0 = TheCall->getArg(0); 7321 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7322 if (FirstArg.isInvalid()) 7323 return true; 7324 7325 QualType FirstArgType = FirstArg.get()->getType(); 7326 if (!FirstArgType->isAnyPointerType()) 7327 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7328 << "first" << FirstArgType << Arg0->getSourceRange(); 7329 TheCall->setArg(0, FirstArg.get()); 7330 7331 // Derive the return type from the pointer argument. 7332 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7333 TheCall->setType(FirstArgType); 7334 return false; 7335 } 7336 7337 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7338 Expr *ArgA = TheCall->getArg(0); 7339 Expr *ArgB = TheCall->getArg(1); 7340 7341 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7342 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7343 7344 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7345 return true; 7346 7347 QualType ArgTypeA = ArgExprA.get()->getType(); 7348 QualType ArgTypeB = ArgExprB.get()->getType(); 7349 7350 auto isNull = [&] (Expr *E) -> bool { 7351 return E->isNullPointerConstant( 7352 Context, Expr::NPC_ValueDependentIsNotNull); }; 7353 7354 // argument should be either a pointer or null 7355 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7356 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7357 << "first" << ArgTypeA << ArgA->getSourceRange(); 7358 7359 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7360 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7361 << "second" << ArgTypeB << ArgB->getSourceRange(); 7362 7363 // Ensure Pointee types are compatible 7364 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7365 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7366 QualType pointeeA = ArgTypeA->getPointeeType(); 7367 QualType pointeeB = ArgTypeB->getPointeeType(); 7368 if (!Context.typesAreCompatible( 7369 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7370 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7371 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7372 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7373 << ArgB->getSourceRange(); 7374 } 7375 } 7376 7377 // at least one argument should be pointer type 7378 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7379 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7380 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7381 7382 if (isNull(ArgA)) // adopt type of the other pointer 7383 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7384 7385 if (isNull(ArgB)) 7386 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7387 7388 TheCall->setArg(0, ArgExprA.get()); 7389 TheCall->setArg(1, ArgExprB.get()); 7390 TheCall->setType(Context.LongLongTy); 7391 return false; 7392 } 7393 assert(false && "Unhandled ARM MTE intrinsic"); 7394 return true; 7395 } 7396 7397 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7398 /// TheCall is an ARM/AArch64 special register string literal. 7399 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7400 int ArgNum, unsigned ExpectedFieldNum, 7401 bool AllowName) { 7402 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7403 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7404 BuiltinID == ARM::BI__builtin_arm_rsr || 7405 BuiltinID == ARM::BI__builtin_arm_rsrp || 7406 BuiltinID == ARM::BI__builtin_arm_wsr || 7407 BuiltinID == ARM::BI__builtin_arm_wsrp; 7408 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7409 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7410 BuiltinID == AArch64::BI__builtin_arm_rsr || 7411 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7412 BuiltinID == AArch64::BI__builtin_arm_wsr || 7413 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7414 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7415 7416 // We can't check the value of a dependent argument. 7417 Expr *Arg = TheCall->getArg(ArgNum); 7418 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7419 return false; 7420 7421 // Check if the argument is a string literal. 7422 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7423 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7424 << Arg->getSourceRange(); 7425 7426 // Check the type of special register given. 7427 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7428 SmallVector<StringRef, 6> Fields; 7429 Reg.split(Fields, ":"); 7430 7431 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7432 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7433 << Arg->getSourceRange(); 7434 7435 // If the string is the name of a register then we cannot check that it is 7436 // valid here but if the string is of one the forms described in ACLE then we 7437 // can check that the supplied fields are integers and within the valid 7438 // ranges. 7439 if (Fields.size() > 1) { 7440 bool FiveFields = Fields.size() == 5; 7441 7442 bool ValidString = true; 7443 if (IsARMBuiltin) { 7444 ValidString &= Fields[0].startswith_insensitive("cp") || 7445 Fields[0].startswith_insensitive("p"); 7446 if (ValidString) 7447 Fields[0] = Fields[0].drop_front( 7448 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7449 7450 ValidString &= Fields[2].startswith_insensitive("c"); 7451 if (ValidString) 7452 Fields[2] = Fields[2].drop_front(1); 7453 7454 if (FiveFields) { 7455 ValidString &= Fields[3].startswith_insensitive("c"); 7456 if (ValidString) 7457 Fields[3] = Fields[3].drop_front(1); 7458 } 7459 } 7460 7461 SmallVector<int, 5> Ranges; 7462 if (FiveFields) 7463 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7464 else 7465 Ranges.append({15, 7, 15}); 7466 7467 for (unsigned i=0; i<Fields.size(); ++i) { 7468 int IntField; 7469 ValidString &= !Fields[i].getAsInteger(10, IntField); 7470 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7471 } 7472 7473 if (!ValidString) 7474 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7475 << Arg->getSourceRange(); 7476 } else if (IsAArch64Builtin && Fields.size() == 1) { 7477 // If the register name is one of those that appear in the condition below 7478 // and the special register builtin being used is one of the write builtins, 7479 // then we require that the argument provided for writing to the register 7480 // is an integer constant expression. This is because it will be lowered to 7481 // an MSR (immediate) instruction, so we need to know the immediate at 7482 // compile time. 7483 if (TheCall->getNumArgs() != 2) 7484 return false; 7485 7486 std::string RegLower = Reg.lower(); 7487 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7488 RegLower != "pan" && RegLower != "uao") 7489 return false; 7490 7491 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7492 } 7493 7494 return false; 7495 } 7496 7497 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7498 /// Emit an error and return true on failure; return false on success. 7499 /// TypeStr is a string containing the type descriptor of the value returned by 7500 /// the builtin and the descriptors of the expected type of the arguments. 7501 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 7502 const char *TypeStr) { 7503 7504 assert((TypeStr[0] != '\0') && 7505 "Invalid types in PPC MMA builtin declaration"); 7506 7507 switch (BuiltinID) { 7508 default: 7509 // This function is called in CheckPPCBuiltinFunctionCall where the 7510 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 7511 // we are isolating the pair vector memop builtins that can be used with mma 7512 // off so the default case is every builtin that requires mma and paired 7513 // vector memops. 7514 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7515 diag::err_ppc_builtin_only_on_arch, "10") || 7516 SemaFeatureCheck(*this, TheCall, "mma", 7517 diag::err_ppc_builtin_only_on_arch, "10")) 7518 return true; 7519 break; 7520 case PPC::BI__builtin_vsx_lxvp: 7521 case PPC::BI__builtin_vsx_stxvp: 7522 case PPC::BI__builtin_vsx_assemble_pair: 7523 case PPC::BI__builtin_vsx_disassemble_pair: 7524 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7525 diag::err_ppc_builtin_only_on_arch, "10")) 7526 return true; 7527 break; 7528 } 7529 7530 unsigned Mask = 0; 7531 unsigned ArgNum = 0; 7532 7533 // The first type in TypeStr is the type of the value returned by the 7534 // builtin. So we first read that type and change the type of TheCall. 7535 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7536 TheCall->setType(type); 7537 7538 while (*TypeStr != '\0') { 7539 Mask = 0; 7540 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7541 if (ArgNum >= TheCall->getNumArgs()) { 7542 ArgNum++; 7543 break; 7544 } 7545 7546 Expr *Arg = TheCall->getArg(ArgNum); 7547 QualType PassedType = Arg->getType(); 7548 QualType StrippedRVType = PassedType.getCanonicalType(); 7549 7550 // Strip Restrict/Volatile qualifiers. 7551 if (StrippedRVType.isRestrictQualified() || 7552 StrippedRVType.isVolatileQualified()) 7553 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 7554 7555 // The only case where the argument type and expected type are allowed to 7556 // mismatch is if the argument type is a non-void pointer and expected type 7557 // is a void pointer. 7558 if (StrippedRVType != ExpectedType) 7559 if (!(ExpectedType->isVoidPointerType() && 7560 StrippedRVType->isPointerType())) 7561 return Diag(Arg->getBeginLoc(), 7562 diag::err_typecheck_convert_incompatible) 7563 << PassedType << ExpectedType << 1 << 0 << 0; 7564 7565 // If the value of the Mask is not 0, we have a constraint in the size of 7566 // the integer argument so here we ensure the argument is a constant that 7567 // is in the valid range. 7568 if (Mask != 0 && 7569 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7570 return true; 7571 7572 ArgNum++; 7573 } 7574 7575 // In case we exited early from the previous loop, there are other types to 7576 // read from TypeStr. So we need to read them all to ensure we have the right 7577 // number of arguments in TheCall and if it is not the case, to display a 7578 // better error message. 7579 while (*TypeStr != '\0') { 7580 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7581 ArgNum++; 7582 } 7583 if (checkArgCount(*this, TheCall, ArgNum)) 7584 return true; 7585 7586 return false; 7587 } 7588 7589 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7590 /// This checks that the target supports __builtin_longjmp and 7591 /// that val is a constant 1. 7592 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7593 if (!Context.getTargetInfo().hasSjLjLowering()) 7594 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7595 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7596 7597 Expr *Arg = TheCall->getArg(1); 7598 llvm::APSInt Result; 7599 7600 // TODO: This is less than ideal. Overload this to take a value. 7601 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7602 return true; 7603 7604 if (Result != 1) 7605 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7606 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7607 7608 return false; 7609 } 7610 7611 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7612 /// This checks that the target supports __builtin_setjmp. 7613 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7614 if (!Context.getTargetInfo().hasSjLjLowering()) 7615 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7616 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7617 return false; 7618 } 7619 7620 namespace { 7621 7622 class UncoveredArgHandler { 7623 enum { Unknown = -1, AllCovered = -2 }; 7624 7625 signed FirstUncoveredArg = Unknown; 7626 SmallVector<const Expr *, 4> DiagnosticExprs; 7627 7628 public: 7629 UncoveredArgHandler() = default; 7630 7631 bool hasUncoveredArg() const { 7632 return (FirstUncoveredArg >= 0); 7633 } 7634 7635 unsigned getUncoveredArg() const { 7636 assert(hasUncoveredArg() && "no uncovered argument"); 7637 return FirstUncoveredArg; 7638 } 7639 7640 void setAllCovered() { 7641 // A string has been found with all arguments covered, so clear out 7642 // the diagnostics. 7643 DiagnosticExprs.clear(); 7644 FirstUncoveredArg = AllCovered; 7645 } 7646 7647 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7648 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7649 7650 // Don't update if a previous string covers all arguments. 7651 if (FirstUncoveredArg == AllCovered) 7652 return; 7653 7654 // UncoveredArgHandler tracks the highest uncovered argument index 7655 // and with it all the strings that match this index. 7656 if (NewFirstUncoveredArg == FirstUncoveredArg) 7657 DiagnosticExprs.push_back(StrExpr); 7658 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7659 DiagnosticExprs.clear(); 7660 DiagnosticExprs.push_back(StrExpr); 7661 FirstUncoveredArg = NewFirstUncoveredArg; 7662 } 7663 } 7664 7665 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7666 }; 7667 7668 enum StringLiteralCheckType { 7669 SLCT_NotALiteral, 7670 SLCT_UncheckedLiteral, 7671 SLCT_CheckedLiteral 7672 }; 7673 7674 } // namespace 7675 7676 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7677 BinaryOperatorKind BinOpKind, 7678 bool AddendIsRight) { 7679 unsigned BitWidth = Offset.getBitWidth(); 7680 unsigned AddendBitWidth = Addend.getBitWidth(); 7681 // There might be negative interim results. 7682 if (Addend.isUnsigned()) { 7683 Addend = Addend.zext(++AddendBitWidth); 7684 Addend.setIsSigned(true); 7685 } 7686 // Adjust the bit width of the APSInts. 7687 if (AddendBitWidth > BitWidth) { 7688 Offset = Offset.sext(AddendBitWidth); 7689 BitWidth = AddendBitWidth; 7690 } else if (BitWidth > AddendBitWidth) { 7691 Addend = Addend.sext(BitWidth); 7692 } 7693 7694 bool Ov = false; 7695 llvm::APSInt ResOffset = Offset; 7696 if (BinOpKind == BO_Add) 7697 ResOffset = Offset.sadd_ov(Addend, Ov); 7698 else { 7699 assert(AddendIsRight && BinOpKind == BO_Sub && 7700 "operator must be add or sub with addend on the right"); 7701 ResOffset = Offset.ssub_ov(Addend, Ov); 7702 } 7703 7704 // We add an offset to a pointer here so we should support an offset as big as 7705 // possible. 7706 if (Ov) { 7707 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7708 "index (intermediate) result too big"); 7709 Offset = Offset.sext(2 * BitWidth); 7710 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7711 return; 7712 } 7713 7714 Offset = ResOffset; 7715 } 7716 7717 namespace { 7718 7719 // This is a wrapper class around StringLiteral to support offsetted string 7720 // literals as format strings. It takes the offset into account when returning 7721 // the string and its length or the source locations to display notes correctly. 7722 class FormatStringLiteral { 7723 const StringLiteral *FExpr; 7724 int64_t Offset; 7725 7726 public: 7727 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7728 : FExpr(fexpr), Offset(Offset) {} 7729 7730 StringRef getString() const { 7731 return FExpr->getString().drop_front(Offset); 7732 } 7733 7734 unsigned getByteLength() const { 7735 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7736 } 7737 7738 unsigned getLength() const { return FExpr->getLength() - Offset; } 7739 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7740 7741 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7742 7743 QualType getType() const { return FExpr->getType(); } 7744 7745 bool isAscii() const { return FExpr->isAscii(); } 7746 bool isWide() const { return FExpr->isWide(); } 7747 bool isUTF8() const { return FExpr->isUTF8(); } 7748 bool isUTF16() const { return FExpr->isUTF16(); } 7749 bool isUTF32() const { return FExpr->isUTF32(); } 7750 bool isPascal() const { return FExpr->isPascal(); } 7751 7752 SourceLocation getLocationOfByte( 7753 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7754 const TargetInfo &Target, unsigned *StartToken = nullptr, 7755 unsigned *StartTokenByteOffset = nullptr) const { 7756 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7757 StartToken, StartTokenByteOffset); 7758 } 7759 7760 SourceLocation getBeginLoc() const LLVM_READONLY { 7761 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7762 } 7763 7764 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7765 }; 7766 7767 } // namespace 7768 7769 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7770 const Expr *OrigFormatExpr, 7771 ArrayRef<const Expr *> Args, 7772 bool HasVAListArg, unsigned format_idx, 7773 unsigned firstDataArg, 7774 Sema::FormatStringType Type, 7775 bool inFunctionCall, 7776 Sema::VariadicCallType CallType, 7777 llvm::SmallBitVector &CheckedVarArgs, 7778 UncoveredArgHandler &UncoveredArg, 7779 bool IgnoreStringsWithoutSpecifiers); 7780 7781 // Determine if an expression is a string literal or constant string. 7782 // If this function returns false on the arguments to a function expecting a 7783 // format string, we will usually need to emit a warning. 7784 // True string literals are then checked by CheckFormatString. 7785 static StringLiteralCheckType 7786 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7787 bool HasVAListArg, unsigned format_idx, 7788 unsigned firstDataArg, Sema::FormatStringType Type, 7789 Sema::VariadicCallType CallType, bool InFunctionCall, 7790 llvm::SmallBitVector &CheckedVarArgs, 7791 UncoveredArgHandler &UncoveredArg, 7792 llvm::APSInt Offset, 7793 bool IgnoreStringsWithoutSpecifiers = false) { 7794 if (S.isConstantEvaluated()) 7795 return SLCT_NotALiteral; 7796 tryAgain: 7797 assert(Offset.isSigned() && "invalid offset"); 7798 7799 if (E->isTypeDependent() || E->isValueDependent()) 7800 return SLCT_NotALiteral; 7801 7802 E = E->IgnoreParenCasts(); 7803 7804 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7805 // Technically -Wformat-nonliteral does not warn about this case. 7806 // The behavior of printf and friends in this case is implementation 7807 // dependent. Ideally if the format string cannot be null then 7808 // it should have a 'nonnull' attribute in the function prototype. 7809 return SLCT_UncheckedLiteral; 7810 7811 switch (E->getStmtClass()) { 7812 case Stmt::BinaryConditionalOperatorClass: 7813 case Stmt::ConditionalOperatorClass: { 7814 // The expression is a literal if both sub-expressions were, and it was 7815 // completely checked only if both sub-expressions were checked. 7816 const AbstractConditionalOperator *C = 7817 cast<AbstractConditionalOperator>(E); 7818 7819 // Determine whether it is necessary to check both sub-expressions, for 7820 // example, because the condition expression is a constant that can be 7821 // evaluated at compile time. 7822 bool CheckLeft = true, CheckRight = true; 7823 7824 bool Cond; 7825 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7826 S.isConstantEvaluated())) { 7827 if (Cond) 7828 CheckRight = false; 7829 else 7830 CheckLeft = false; 7831 } 7832 7833 // We need to maintain the offsets for the right and the left hand side 7834 // separately to check if every possible indexed expression is a valid 7835 // string literal. They might have different offsets for different string 7836 // literals in the end. 7837 StringLiteralCheckType Left; 7838 if (!CheckLeft) 7839 Left = SLCT_UncheckedLiteral; 7840 else { 7841 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7842 HasVAListArg, format_idx, firstDataArg, 7843 Type, CallType, InFunctionCall, 7844 CheckedVarArgs, UncoveredArg, Offset, 7845 IgnoreStringsWithoutSpecifiers); 7846 if (Left == SLCT_NotALiteral || !CheckRight) { 7847 return Left; 7848 } 7849 } 7850 7851 StringLiteralCheckType Right = checkFormatStringExpr( 7852 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7853 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7854 IgnoreStringsWithoutSpecifiers); 7855 7856 return (CheckLeft && Left < Right) ? Left : Right; 7857 } 7858 7859 case Stmt::ImplicitCastExprClass: 7860 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7861 goto tryAgain; 7862 7863 case Stmt::OpaqueValueExprClass: 7864 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7865 E = src; 7866 goto tryAgain; 7867 } 7868 return SLCT_NotALiteral; 7869 7870 case Stmt::PredefinedExprClass: 7871 // While __func__, etc., are technically not string literals, they 7872 // cannot contain format specifiers and thus are not a security 7873 // liability. 7874 return SLCT_UncheckedLiteral; 7875 7876 case Stmt::DeclRefExprClass: { 7877 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7878 7879 // As an exception, do not flag errors for variables binding to 7880 // const string literals. 7881 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7882 bool isConstant = false; 7883 QualType T = DR->getType(); 7884 7885 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7886 isConstant = AT->getElementType().isConstant(S.Context); 7887 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7888 isConstant = T.isConstant(S.Context) && 7889 PT->getPointeeType().isConstant(S.Context); 7890 } else if (T->isObjCObjectPointerType()) { 7891 // In ObjC, there is usually no "const ObjectPointer" type, 7892 // so don't check if the pointee type is constant. 7893 isConstant = T.isConstant(S.Context); 7894 } 7895 7896 if (isConstant) { 7897 if (const Expr *Init = VD->getAnyInitializer()) { 7898 // Look through initializers like const char c[] = { "foo" } 7899 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7900 if (InitList->isStringLiteralInit()) 7901 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7902 } 7903 return checkFormatStringExpr(S, Init, Args, 7904 HasVAListArg, format_idx, 7905 firstDataArg, Type, CallType, 7906 /*InFunctionCall*/ false, CheckedVarArgs, 7907 UncoveredArg, Offset); 7908 } 7909 } 7910 7911 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7912 // special check to see if the format string is a function parameter 7913 // of the function calling the printf function. If the function 7914 // has an attribute indicating it is a printf-like function, then we 7915 // should suppress warnings concerning non-literals being used in a call 7916 // to a vprintf function. For example: 7917 // 7918 // void 7919 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7920 // va_list ap; 7921 // va_start(ap, fmt); 7922 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7923 // ... 7924 // } 7925 if (HasVAListArg) { 7926 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7927 if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) { 7928 int PVIndex = PV->getFunctionScopeIndex() + 1; 7929 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) { 7930 // adjust for implicit parameter 7931 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 7932 if (MD->isInstance()) 7933 ++PVIndex; 7934 // We also check if the formats are compatible. 7935 // We can't pass a 'scanf' string to a 'printf' function. 7936 if (PVIndex == PVFormat->getFormatIdx() && 7937 Type == S.GetFormatStringType(PVFormat)) 7938 return SLCT_UncheckedLiteral; 7939 } 7940 } 7941 } 7942 } 7943 } 7944 7945 return SLCT_NotALiteral; 7946 } 7947 7948 case Stmt::CallExprClass: 7949 case Stmt::CXXMemberCallExprClass: { 7950 const CallExpr *CE = cast<CallExpr>(E); 7951 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7952 bool IsFirst = true; 7953 StringLiteralCheckType CommonResult; 7954 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7955 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7956 StringLiteralCheckType Result = checkFormatStringExpr( 7957 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7958 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7959 IgnoreStringsWithoutSpecifiers); 7960 if (IsFirst) { 7961 CommonResult = Result; 7962 IsFirst = false; 7963 } 7964 } 7965 if (!IsFirst) 7966 return CommonResult; 7967 7968 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7969 unsigned BuiltinID = FD->getBuiltinID(); 7970 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7971 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7972 const Expr *Arg = CE->getArg(0); 7973 return checkFormatStringExpr(S, Arg, Args, 7974 HasVAListArg, format_idx, 7975 firstDataArg, Type, CallType, 7976 InFunctionCall, CheckedVarArgs, 7977 UncoveredArg, Offset, 7978 IgnoreStringsWithoutSpecifiers); 7979 } 7980 } 7981 } 7982 7983 return SLCT_NotALiteral; 7984 } 7985 case Stmt::ObjCMessageExprClass: { 7986 const auto *ME = cast<ObjCMessageExpr>(E); 7987 if (const auto *MD = ME->getMethodDecl()) { 7988 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7989 // As a special case heuristic, if we're using the method -[NSBundle 7990 // localizedStringForKey:value:table:], ignore any key strings that lack 7991 // format specifiers. The idea is that if the key doesn't have any 7992 // format specifiers then its probably just a key to map to the 7993 // localized strings. If it does have format specifiers though, then its 7994 // likely that the text of the key is the format string in the 7995 // programmer's language, and should be checked. 7996 const ObjCInterfaceDecl *IFace; 7997 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7998 IFace->getIdentifier()->isStr("NSBundle") && 7999 MD->getSelector().isKeywordSelector( 8000 {"localizedStringForKey", "value", "table"})) { 8001 IgnoreStringsWithoutSpecifiers = true; 8002 } 8003 8004 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 8005 return checkFormatStringExpr( 8006 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8007 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8008 IgnoreStringsWithoutSpecifiers); 8009 } 8010 } 8011 8012 return SLCT_NotALiteral; 8013 } 8014 case Stmt::ObjCStringLiteralClass: 8015 case Stmt::StringLiteralClass: { 8016 const StringLiteral *StrE = nullptr; 8017 8018 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 8019 StrE = ObjCFExpr->getString(); 8020 else 8021 StrE = cast<StringLiteral>(E); 8022 8023 if (StrE) { 8024 if (Offset.isNegative() || Offset > StrE->getLength()) { 8025 // TODO: It would be better to have an explicit warning for out of 8026 // bounds literals. 8027 return SLCT_NotALiteral; 8028 } 8029 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 8030 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 8031 firstDataArg, Type, InFunctionCall, CallType, 8032 CheckedVarArgs, UncoveredArg, 8033 IgnoreStringsWithoutSpecifiers); 8034 return SLCT_CheckedLiteral; 8035 } 8036 8037 return SLCT_NotALiteral; 8038 } 8039 case Stmt::BinaryOperatorClass: { 8040 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 8041 8042 // A string literal + an int offset is still a string literal. 8043 if (BinOp->isAdditiveOp()) { 8044 Expr::EvalResult LResult, RResult; 8045 8046 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 8047 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8048 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 8049 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8050 8051 if (LIsInt != RIsInt) { 8052 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8053 8054 if (LIsInt) { 8055 if (BinOpKind == BO_Add) { 8056 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8057 E = BinOp->getRHS(); 8058 goto tryAgain; 8059 } 8060 } else { 8061 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8062 E = BinOp->getLHS(); 8063 goto tryAgain; 8064 } 8065 } 8066 } 8067 8068 return SLCT_NotALiteral; 8069 } 8070 case Stmt::UnaryOperatorClass: { 8071 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8072 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8073 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8074 Expr::EvalResult IndexResult; 8075 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8076 Expr::SE_NoSideEffects, 8077 S.isConstantEvaluated())) { 8078 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8079 /*RHS is int*/ true); 8080 E = ASE->getBase(); 8081 goto tryAgain; 8082 } 8083 } 8084 8085 return SLCT_NotALiteral; 8086 } 8087 8088 default: 8089 return SLCT_NotALiteral; 8090 } 8091 } 8092 8093 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8094 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8095 .Case("scanf", FST_Scanf) 8096 .Cases("printf", "printf0", FST_Printf) 8097 .Cases("NSString", "CFString", FST_NSString) 8098 .Case("strftime", FST_Strftime) 8099 .Case("strfmon", FST_Strfmon) 8100 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8101 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8102 .Case("os_trace", FST_OSLog) 8103 .Case("os_log", FST_OSLog) 8104 .Default(FST_Unknown); 8105 } 8106 8107 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8108 /// functions) for correct use of format strings. 8109 /// Returns true if a format string has been fully checked. 8110 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8111 ArrayRef<const Expr *> Args, 8112 bool IsCXXMember, 8113 VariadicCallType CallType, 8114 SourceLocation Loc, SourceRange Range, 8115 llvm::SmallBitVector &CheckedVarArgs) { 8116 FormatStringInfo FSI; 8117 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8118 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8119 FSI.FirstDataArg, GetFormatStringType(Format), 8120 CallType, Loc, Range, CheckedVarArgs); 8121 return false; 8122 } 8123 8124 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8125 bool HasVAListArg, unsigned format_idx, 8126 unsigned firstDataArg, FormatStringType Type, 8127 VariadicCallType CallType, 8128 SourceLocation Loc, SourceRange Range, 8129 llvm::SmallBitVector &CheckedVarArgs) { 8130 // CHECK: printf/scanf-like function is called with no format string. 8131 if (format_idx >= Args.size()) { 8132 Diag(Loc, diag::warn_missing_format_string) << Range; 8133 return false; 8134 } 8135 8136 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8137 8138 // CHECK: format string is not a string literal. 8139 // 8140 // Dynamically generated format strings are difficult to 8141 // automatically vet at compile time. Requiring that format strings 8142 // are string literals: (1) permits the checking of format strings by 8143 // the compiler and thereby (2) can practically remove the source of 8144 // many format string exploits. 8145 8146 // Format string can be either ObjC string (e.g. @"%d") or 8147 // C string (e.g. "%d") 8148 // ObjC string uses the same format specifiers as C string, so we can use 8149 // the same format string checking logic for both ObjC and C strings. 8150 UncoveredArgHandler UncoveredArg; 8151 StringLiteralCheckType CT = 8152 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8153 format_idx, firstDataArg, Type, CallType, 8154 /*IsFunctionCall*/ true, CheckedVarArgs, 8155 UncoveredArg, 8156 /*no string offset*/ llvm::APSInt(64, false) = 0); 8157 8158 // Generate a diagnostic where an uncovered argument is detected. 8159 if (UncoveredArg.hasUncoveredArg()) { 8160 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8161 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8162 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8163 } 8164 8165 if (CT != SLCT_NotALiteral) 8166 // Literal format string found, check done! 8167 return CT == SLCT_CheckedLiteral; 8168 8169 // Strftime is particular as it always uses a single 'time' argument, 8170 // so it is safe to pass a non-literal string. 8171 if (Type == FST_Strftime) 8172 return false; 8173 8174 // Do not emit diag when the string param is a macro expansion and the 8175 // format is either NSString or CFString. This is a hack to prevent 8176 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8177 // which are usually used in place of NS and CF string literals. 8178 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8179 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8180 return false; 8181 8182 // If there are no arguments specified, warn with -Wformat-security, otherwise 8183 // warn only with -Wformat-nonliteral. 8184 if (Args.size() == firstDataArg) { 8185 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8186 << OrigFormatExpr->getSourceRange(); 8187 switch (Type) { 8188 default: 8189 break; 8190 case FST_Kprintf: 8191 case FST_FreeBSDKPrintf: 8192 case FST_Printf: 8193 Diag(FormatLoc, diag::note_format_security_fixit) 8194 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8195 break; 8196 case FST_NSString: 8197 Diag(FormatLoc, diag::note_format_security_fixit) 8198 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8199 break; 8200 } 8201 } else { 8202 Diag(FormatLoc, diag::warn_format_nonliteral) 8203 << OrigFormatExpr->getSourceRange(); 8204 } 8205 return false; 8206 } 8207 8208 namespace { 8209 8210 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8211 protected: 8212 Sema &S; 8213 const FormatStringLiteral *FExpr; 8214 const Expr *OrigFormatExpr; 8215 const Sema::FormatStringType FSType; 8216 const unsigned FirstDataArg; 8217 const unsigned NumDataArgs; 8218 const char *Beg; // Start of format string. 8219 const bool HasVAListArg; 8220 ArrayRef<const Expr *> Args; 8221 unsigned FormatIdx; 8222 llvm::SmallBitVector CoveredArgs; 8223 bool usesPositionalArgs = false; 8224 bool atFirstArg = true; 8225 bool inFunctionCall; 8226 Sema::VariadicCallType CallType; 8227 llvm::SmallBitVector &CheckedVarArgs; 8228 UncoveredArgHandler &UncoveredArg; 8229 8230 public: 8231 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8232 const Expr *origFormatExpr, 8233 const Sema::FormatStringType type, unsigned firstDataArg, 8234 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8235 ArrayRef<const Expr *> Args, unsigned formatIdx, 8236 bool inFunctionCall, Sema::VariadicCallType callType, 8237 llvm::SmallBitVector &CheckedVarArgs, 8238 UncoveredArgHandler &UncoveredArg) 8239 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8240 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8241 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8242 inFunctionCall(inFunctionCall), CallType(callType), 8243 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8244 CoveredArgs.resize(numDataArgs); 8245 CoveredArgs.reset(); 8246 } 8247 8248 void DoneProcessing(); 8249 8250 void HandleIncompleteSpecifier(const char *startSpecifier, 8251 unsigned specifierLen) override; 8252 8253 void HandleInvalidLengthModifier( 8254 const analyze_format_string::FormatSpecifier &FS, 8255 const analyze_format_string::ConversionSpecifier &CS, 8256 const char *startSpecifier, unsigned specifierLen, 8257 unsigned DiagID); 8258 8259 void HandleNonStandardLengthModifier( 8260 const analyze_format_string::FormatSpecifier &FS, 8261 const char *startSpecifier, unsigned specifierLen); 8262 8263 void HandleNonStandardConversionSpecifier( 8264 const analyze_format_string::ConversionSpecifier &CS, 8265 const char *startSpecifier, unsigned specifierLen); 8266 8267 void HandlePosition(const char *startPos, unsigned posLen) override; 8268 8269 void HandleInvalidPosition(const char *startSpecifier, 8270 unsigned specifierLen, 8271 analyze_format_string::PositionContext p) override; 8272 8273 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8274 8275 void HandleNullChar(const char *nullCharacter) override; 8276 8277 template <typename Range> 8278 static void 8279 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8280 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8281 bool IsStringLocation, Range StringRange, 8282 ArrayRef<FixItHint> Fixit = None); 8283 8284 protected: 8285 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8286 const char *startSpec, 8287 unsigned specifierLen, 8288 const char *csStart, unsigned csLen); 8289 8290 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8291 const char *startSpec, 8292 unsigned specifierLen); 8293 8294 SourceRange getFormatStringRange(); 8295 CharSourceRange getSpecifierRange(const char *startSpecifier, 8296 unsigned specifierLen); 8297 SourceLocation getLocationOfByte(const char *x); 8298 8299 const Expr *getDataArg(unsigned i) const; 8300 8301 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8302 const analyze_format_string::ConversionSpecifier &CS, 8303 const char *startSpecifier, unsigned specifierLen, 8304 unsigned argIndex); 8305 8306 template <typename Range> 8307 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8308 bool IsStringLocation, Range StringRange, 8309 ArrayRef<FixItHint> Fixit = None); 8310 }; 8311 8312 } // namespace 8313 8314 SourceRange CheckFormatHandler::getFormatStringRange() { 8315 return OrigFormatExpr->getSourceRange(); 8316 } 8317 8318 CharSourceRange CheckFormatHandler:: 8319 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8320 SourceLocation Start = getLocationOfByte(startSpecifier); 8321 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8322 8323 // Advance the end SourceLocation by one due to half-open ranges. 8324 End = End.getLocWithOffset(1); 8325 8326 return CharSourceRange::getCharRange(Start, End); 8327 } 8328 8329 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8330 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8331 S.getLangOpts(), S.Context.getTargetInfo()); 8332 } 8333 8334 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8335 unsigned specifierLen){ 8336 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8337 getLocationOfByte(startSpecifier), 8338 /*IsStringLocation*/true, 8339 getSpecifierRange(startSpecifier, specifierLen)); 8340 } 8341 8342 void CheckFormatHandler::HandleInvalidLengthModifier( 8343 const analyze_format_string::FormatSpecifier &FS, 8344 const analyze_format_string::ConversionSpecifier &CS, 8345 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8346 using namespace analyze_format_string; 8347 8348 const LengthModifier &LM = FS.getLengthModifier(); 8349 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8350 8351 // See if we know how to fix this length modifier. 8352 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8353 if (FixedLM) { 8354 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8355 getLocationOfByte(LM.getStart()), 8356 /*IsStringLocation*/true, 8357 getSpecifierRange(startSpecifier, specifierLen)); 8358 8359 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8360 << FixedLM->toString() 8361 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8362 8363 } else { 8364 FixItHint Hint; 8365 if (DiagID == diag::warn_format_nonsensical_length) 8366 Hint = FixItHint::CreateRemoval(LMRange); 8367 8368 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8369 getLocationOfByte(LM.getStart()), 8370 /*IsStringLocation*/true, 8371 getSpecifierRange(startSpecifier, specifierLen), 8372 Hint); 8373 } 8374 } 8375 8376 void CheckFormatHandler::HandleNonStandardLengthModifier( 8377 const analyze_format_string::FormatSpecifier &FS, 8378 const char *startSpecifier, unsigned specifierLen) { 8379 using namespace analyze_format_string; 8380 8381 const LengthModifier &LM = FS.getLengthModifier(); 8382 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8383 8384 // See if we know how to fix this length modifier. 8385 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8386 if (FixedLM) { 8387 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8388 << LM.toString() << 0, 8389 getLocationOfByte(LM.getStart()), 8390 /*IsStringLocation*/true, 8391 getSpecifierRange(startSpecifier, specifierLen)); 8392 8393 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8394 << FixedLM->toString() 8395 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8396 8397 } else { 8398 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8399 << LM.toString() << 0, 8400 getLocationOfByte(LM.getStart()), 8401 /*IsStringLocation*/true, 8402 getSpecifierRange(startSpecifier, specifierLen)); 8403 } 8404 } 8405 8406 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8407 const analyze_format_string::ConversionSpecifier &CS, 8408 const char *startSpecifier, unsigned specifierLen) { 8409 using namespace analyze_format_string; 8410 8411 // See if we know how to fix this conversion specifier. 8412 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8413 if (FixedCS) { 8414 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8415 << CS.toString() << /*conversion specifier*/1, 8416 getLocationOfByte(CS.getStart()), 8417 /*IsStringLocation*/true, 8418 getSpecifierRange(startSpecifier, specifierLen)); 8419 8420 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8421 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8422 << FixedCS->toString() 8423 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8424 } else { 8425 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8426 << CS.toString() << /*conversion specifier*/1, 8427 getLocationOfByte(CS.getStart()), 8428 /*IsStringLocation*/true, 8429 getSpecifierRange(startSpecifier, specifierLen)); 8430 } 8431 } 8432 8433 void CheckFormatHandler::HandlePosition(const char *startPos, 8434 unsigned posLen) { 8435 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8436 getLocationOfByte(startPos), 8437 /*IsStringLocation*/true, 8438 getSpecifierRange(startPos, posLen)); 8439 } 8440 8441 void 8442 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8443 analyze_format_string::PositionContext p) { 8444 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8445 << (unsigned) p, 8446 getLocationOfByte(startPos), /*IsStringLocation*/true, 8447 getSpecifierRange(startPos, posLen)); 8448 } 8449 8450 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8451 unsigned posLen) { 8452 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8453 getLocationOfByte(startPos), 8454 /*IsStringLocation*/true, 8455 getSpecifierRange(startPos, posLen)); 8456 } 8457 8458 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8459 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8460 // The presence of a null character is likely an error. 8461 EmitFormatDiagnostic( 8462 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8463 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8464 getFormatStringRange()); 8465 } 8466 } 8467 8468 // Note that this may return NULL if there was an error parsing or building 8469 // one of the argument expressions. 8470 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8471 return Args[FirstDataArg + i]; 8472 } 8473 8474 void CheckFormatHandler::DoneProcessing() { 8475 // Does the number of data arguments exceed the number of 8476 // format conversions in the format string? 8477 if (!HasVAListArg) { 8478 // Find any arguments that weren't covered. 8479 CoveredArgs.flip(); 8480 signed notCoveredArg = CoveredArgs.find_first(); 8481 if (notCoveredArg >= 0) { 8482 assert((unsigned)notCoveredArg < NumDataArgs); 8483 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8484 } else { 8485 UncoveredArg.setAllCovered(); 8486 } 8487 } 8488 } 8489 8490 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8491 const Expr *ArgExpr) { 8492 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8493 "Invalid state"); 8494 8495 if (!ArgExpr) 8496 return; 8497 8498 SourceLocation Loc = ArgExpr->getBeginLoc(); 8499 8500 if (S.getSourceManager().isInSystemMacro(Loc)) 8501 return; 8502 8503 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8504 for (auto E : DiagnosticExprs) 8505 PDiag << E->getSourceRange(); 8506 8507 CheckFormatHandler::EmitFormatDiagnostic( 8508 S, IsFunctionCall, DiagnosticExprs[0], 8509 PDiag, Loc, /*IsStringLocation*/false, 8510 DiagnosticExprs[0]->getSourceRange()); 8511 } 8512 8513 bool 8514 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8515 SourceLocation Loc, 8516 const char *startSpec, 8517 unsigned specifierLen, 8518 const char *csStart, 8519 unsigned csLen) { 8520 bool keepGoing = true; 8521 if (argIndex < NumDataArgs) { 8522 // Consider the argument coverered, even though the specifier doesn't 8523 // make sense. 8524 CoveredArgs.set(argIndex); 8525 } 8526 else { 8527 // If argIndex exceeds the number of data arguments we 8528 // don't issue a warning because that is just a cascade of warnings (and 8529 // they may have intended '%%' anyway). We don't want to continue processing 8530 // the format string after this point, however, as we will like just get 8531 // gibberish when trying to match arguments. 8532 keepGoing = false; 8533 } 8534 8535 StringRef Specifier(csStart, csLen); 8536 8537 // If the specifier in non-printable, it could be the first byte of a UTF-8 8538 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8539 // hex value. 8540 std::string CodePointStr; 8541 if (!llvm::sys::locale::isPrint(*csStart)) { 8542 llvm::UTF32 CodePoint; 8543 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8544 const llvm::UTF8 *E = 8545 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8546 llvm::ConversionResult Result = 8547 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8548 8549 if (Result != llvm::conversionOK) { 8550 unsigned char FirstChar = *csStart; 8551 CodePoint = (llvm::UTF32)FirstChar; 8552 } 8553 8554 llvm::raw_string_ostream OS(CodePointStr); 8555 if (CodePoint < 256) 8556 OS << "\\x" << llvm::format("%02x", CodePoint); 8557 else if (CodePoint <= 0xFFFF) 8558 OS << "\\u" << llvm::format("%04x", CodePoint); 8559 else 8560 OS << "\\U" << llvm::format("%08x", CodePoint); 8561 OS.flush(); 8562 Specifier = CodePointStr; 8563 } 8564 8565 EmitFormatDiagnostic( 8566 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8567 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8568 8569 return keepGoing; 8570 } 8571 8572 void 8573 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8574 const char *startSpec, 8575 unsigned specifierLen) { 8576 EmitFormatDiagnostic( 8577 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8578 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8579 } 8580 8581 bool 8582 CheckFormatHandler::CheckNumArgs( 8583 const analyze_format_string::FormatSpecifier &FS, 8584 const analyze_format_string::ConversionSpecifier &CS, 8585 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8586 8587 if (argIndex >= NumDataArgs) { 8588 PartialDiagnostic PDiag = FS.usesPositionalArg() 8589 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8590 << (argIndex+1) << NumDataArgs) 8591 : S.PDiag(diag::warn_printf_insufficient_data_args); 8592 EmitFormatDiagnostic( 8593 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8594 getSpecifierRange(startSpecifier, specifierLen)); 8595 8596 // Since more arguments than conversion tokens are given, by extension 8597 // all arguments are covered, so mark this as so. 8598 UncoveredArg.setAllCovered(); 8599 return false; 8600 } 8601 return true; 8602 } 8603 8604 template<typename Range> 8605 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8606 SourceLocation Loc, 8607 bool IsStringLocation, 8608 Range StringRange, 8609 ArrayRef<FixItHint> FixIt) { 8610 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8611 Loc, IsStringLocation, StringRange, FixIt); 8612 } 8613 8614 /// If the format string is not within the function call, emit a note 8615 /// so that the function call and string are in diagnostic messages. 8616 /// 8617 /// \param InFunctionCall if true, the format string is within the function 8618 /// call and only one diagnostic message will be produced. Otherwise, an 8619 /// extra note will be emitted pointing to location of the format string. 8620 /// 8621 /// \param ArgumentExpr the expression that is passed as the format string 8622 /// argument in the function call. Used for getting locations when two 8623 /// diagnostics are emitted. 8624 /// 8625 /// \param PDiag the callee should already have provided any strings for the 8626 /// diagnostic message. This function only adds locations and fixits 8627 /// to diagnostics. 8628 /// 8629 /// \param Loc primary location for diagnostic. If two diagnostics are 8630 /// required, one will be at Loc and a new SourceLocation will be created for 8631 /// the other one. 8632 /// 8633 /// \param IsStringLocation if true, Loc points to the format string should be 8634 /// used for the note. Otherwise, Loc points to the argument list and will 8635 /// be used with PDiag. 8636 /// 8637 /// \param StringRange some or all of the string to highlight. This is 8638 /// templated so it can accept either a CharSourceRange or a SourceRange. 8639 /// 8640 /// \param FixIt optional fix it hint for the format string. 8641 template <typename Range> 8642 void CheckFormatHandler::EmitFormatDiagnostic( 8643 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8644 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8645 Range StringRange, ArrayRef<FixItHint> FixIt) { 8646 if (InFunctionCall) { 8647 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8648 D << StringRange; 8649 D << FixIt; 8650 } else { 8651 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8652 << ArgumentExpr->getSourceRange(); 8653 8654 const Sema::SemaDiagnosticBuilder &Note = 8655 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8656 diag::note_format_string_defined); 8657 8658 Note << StringRange; 8659 Note << FixIt; 8660 } 8661 } 8662 8663 //===--- CHECK: Printf format string checking ------------------------------===// 8664 8665 namespace { 8666 8667 class CheckPrintfHandler : public CheckFormatHandler { 8668 public: 8669 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8670 const Expr *origFormatExpr, 8671 const Sema::FormatStringType type, unsigned firstDataArg, 8672 unsigned numDataArgs, bool isObjC, const char *beg, 8673 bool hasVAListArg, ArrayRef<const Expr *> Args, 8674 unsigned formatIdx, bool inFunctionCall, 8675 Sema::VariadicCallType CallType, 8676 llvm::SmallBitVector &CheckedVarArgs, 8677 UncoveredArgHandler &UncoveredArg) 8678 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8679 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8680 inFunctionCall, CallType, CheckedVarArgs, 8681 UncoveredArg) {} 8682 8683 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8684 8685 /// Returns true if '%@' specifiers are allowed in the format string. 8686 bool allowsObjCArg() const { 8687 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8688 FSType == Sema::FST_OSTrace; 8689 } 8690 8691 bool HandleInvalidPrintfConversionSpecifier( 8692 const analyze_printf::PrintfSpecifier &FS, 8693 const char *startSpecifier, 8694 unsigned specifierLen) override; 8695 8696 void handleInvalidMaskType(StringRef MaskType) override; 8697 8698 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8699 const char *startSpecifier, 8700 unsigned specifierLen) override; 8701 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8702 const char *StartSpecifier, 8703 unsigned SpecifierLen, 8704 const Expr *E); 8705 8706 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8707 const char *startSpecifier, unsigned specifierLen); 8708 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8709 const analyze_printf::OptionalAmount &Amt, 8710 unsigned type, 8711 const char *startSpecifier, unsigned specifierLen); 8712 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8713 const analyze_printf::OptionalFlag &flag, 8714 const char *startSpecifier, unsigned specifierLen); 8715 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8716 const analyze_printf::OptionalFlag &ignoredFlag, 8717 const analyze_printf::OptionalFlag &flag, 8718 const char *startSpecifier, unsigned specifierLen); 8719 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8720 const Expr *E); 8721 8722 void HandleEmptyObjCModifierFlag(const char *startFlag, 8723 unsigned flagLen) override; 8724 8725 void HandleInvalidObjCModifierFlag(const char *startFlag, 8726 unsigned flagLen) override; 8727 8728 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8729 const char *flagsEnd, 8730 const char *conversionPosition) 8731 override; 8732 }; 8733 8734 } // namespace 8735 8736 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8737 const analyze_printf::PrintfSpecifier &FS, 8738 const char *startSpecifier, 8739 unsigned specifierLen) { 8740 const analyze_printf::PrintfConversionSpecifier &CS = 8741 FS.getConversionSpecifier(); 8742 8743 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8744 getLocationOfByte(CS.getStart()), 8745 startSpecifier, specifierLen, 8746 CS.getStart(), CS.getLength()); 8747 } 8748 8749 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8750 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8751 } 8752 8753 bool CheckPrintfHandler::HandleAmount( 8754 const analyze_format_string::OptionalAmount &Amt, 8755 unsigned k, const char *startSpecifier, 8756 unsigned specifierLen) { 8757 if (Amt.hasDataArgument()) { 8758 if (!HasVAListArg) { 8759 unsigned argIndex = Amt.getArgIndex(); 8760 if (argIndex >= NumDataArgs) { 8761 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8762 << k, 8763 getLocationOfByte(Amt.getStart()), 8764 /*IsStringLocation*/true, 8765 getSpecifierRange(startSpecifier, specifierLen)); 8766 // Don't do any more checking. We will just emit 8767 // spurious errors. 8768 return false; 8769 } 8770 8771 // Type check the data argument. It should be an 'int'. 8772 // Although not in conformance with C99, we also allow the argument to be 8773 // an 'unsigned int' as that is a reasonably safe case. GCC also 8774 // doesn't emit a warning for that case. 8775 CoveredArgs.set(argIndex); 8776 const Expr *Arg = getDataArg(argIndex); 8777 if (!Arg) 8778 return false; 8779 8780 QualType T = Arg->getType(); 8781 8782 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8783 assert(AT.isValid()); 8784 8785 if (!AT.matchesType(S.Context, T)) { 8786 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8787 << k << AT.getRepresentativeTypeName(S.Context) 8788 << T << Arg->getSourceRange(), 8789 getLocationOfByte(Amt.getStart()), 8790 /*IsStringLocation*/true, 8791 getSpecifierRange(startSpecifier, specifierLen)); 8792 // Don't do any more checking. We will just emit 8793 // spurious errors. 8794 return false; 8795 } 8796 } 8797 } 8798 return true; 8799 } 8800 8801 void CheckPrintfHandler::HandleInvalidAmount( 8802 const analyze_printf::PrintfSpecifier &FS, 8803 const analyze_printf::OptionalAmount &Amt, 8804 unsigned type, 8805 const char *startSpecifier, 8806 unsigned specifierLen) { 8807 const analyze_printf::PrintfConversionSpecifier &CS = 8808 FS.getConversionSpecifier(); 8809 8810 FixItHint fixit = 8811 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8812 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8813 Amt.getConstantLength())) 8814 : FixItHint(); 8815 8816 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8817 << type << CS.toString(), 8818 getLocationOfByte(Amt.getStart()), 8819 /*IsStringLocation*/true, 8820 getSpecifierRange(startSpecifier, specifierLen), 8821 fixit); 8822 } 8823 8824 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8825 const analyze_printf::OptionalFlag &flag, 8826 const char *startSpecifier, 8827 unsigned specifierLen) { 8828 // Warn about pointless flag with a fixit removal. 8829 const analyze_printf::PrintfConversionSpecifier &CS = 8830 FS.getConversionSpecifier(); 8831 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8832 << flag.toString() << CS.toString(), 8833 getLocationOfByte(flag.getPosition()), 8834 /*IsStringLocation*/true, 8835 getSpecifierRange(startSpecifier, specifierLen), 8836 FixItHint::CreateRemoval( 8837 getSpecifierRange(flag.getPosition(), 1))); 8838 } 8839 8840 void CheckPrintfHandler::HandleIgnoredFlag( 8841 const analyze_printf::PrintfSpecifier &FS, 8842 const analyze_printf::OptionalFlag &ignoredFlag, 8843 const analyze_printf::OptionalFlag &flag, 8844 const char *startSpecifier, 8845 unsigned specifierLen) { 8846 // Warn about ignored flag with a fixit removal. 8847 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8848 << ignoredFlag.toString() << flag.toString(), 8849 getLocationOfByte(ignoredFlag.getPosition()), 8850 /*IsStringLocation*/true, 8851 getSpecifierRange(startSpecifier, specifierLen), 8852 FixItHint::CreateRemoval( 8853 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8854 } 8855 8856 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8857 unsigned flagLen) { 8858 // Warn about an empty flag. 8859 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8860 getLocationOfByte(startFlag), 8861 /*IsStringLocation*/true, 8862 getSpecifierRange(startFlag, flagLen)); 8863 } 8864 8865 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8866 unsigned flagLen) { 8867 // Warn about an invalid flag. 8868 auto Range = getSpecifierRange(startFlag, flagLen); 8869 StringRef flag(startFlag, flagLen); 8870 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8871 getLocationOfByte(startFlag), 8872 /*IsStringLocation*/true, 8873 Range, FixItHint::CreateRemoval(Range)); 8874 } 8875 8876 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8877 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8878 // Warn about using '[...]' without a '@' conversion. 8879 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8880 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8881 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8882 getLocationOfByte(conversionPosition), 8883 /*IsStringLocation*/true, 8884 Range, FixItHint::CreateRemoval(Range)); 8885 } 8886 8887 // Determines if the specified is a C++ class or struct containing 8888 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8889 // "c_str()"). 8890 template<typename MemberKind> 8891 static llvm::SmallPtrSet<MemberKind*, 1> 8892 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8893 const RecordType *RT = Ty->getAs<RecordType>(); 8894 llvm::SmallPtrSet<MemberKind*, 1> Results; 8895 8896 if (!RT) 8897 return Results; 8898 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8899 if (!RD || !RD->getDefinition()) 8900 return Results; 8901 8902 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8903 Sema::LookupMemberName); 8904 R.suppressDiagnostics(); 8905 8906 // We just need to include all members of the right kind turned up by the 8907 // filter, at this point. 8908 if (S.LookupQualifiedName(R, RT->getDecl())) 8909 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8910 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8911 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8912 Results.insert(FK); 8913 } 8914 return Results; 8915 } 8916 8917 /// Check if we could call '.c_str()' on an object. 8918 /// 8919 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8920 /// allow the call, or if it would be ambiguous). 8921 bool Sema::hasCStrMethod(const Expr *E) { 8922 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8923 8924 MethodSet Results = 8925 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8926 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8927 MI != ME; ++MI) 8928 if ((*MI)->getMinRequiredArguments() == 0) 8929 return true; 8930 return false; 8931 } 8932 8933 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8934 // better diagnostic if so. AT is assumed to be valid. 8935 // Returns true when a c_str() conversion method is found. 8936 bool CheckPrintfHandler::checkForCStrMembers( 8937 const analyze_printf::ArgType &AT, const Expr *E) { 8938 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8939 8940 MethodSet Results = 8941 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8942 8943 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8944 MI != ME; ++MI) { 8945 const CXXMethodDecl *Method = *MI; 8946 if (Method->getMinRequiredArguments() == 0 && 8947 AT.matchesType(S.Context, Method->getReturnType())) { 8948 // FIXME: Suggest parens if the expression needs them. 8949 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8950 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8951 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8952 return true; 8953 } 8954 } 8955 8956 return false; 8957 } 8958 8959 bool 8960 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8961 &FS, 8962 const char *startSpecifier, 8963 unsigned specifierLen) { 8964 using namespace analyze_format_string; 8965 using namespace analyze_printf; 8966 8967 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8968 8969 if (FS.consumesDataArgument()) { 8970 if (atFirstArg) { 8971 atFirstArg = false; 8972 usesPositionalArgs = FS.usesPositionalArg(); 8973 } 8974 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8975 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8976 startSpecifier, specifierLen); 8977 return false; 8978 } 8979 } 8980 8981 // First check if the field width, precision, and conversion specifier 8982 // have matching data arguments. 8983 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8984 startSpecifier, specifierLen)) { 8985 return false; 8986 } 8987 8988 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8989 startSpecifier, specifierLen)) { 8990 return false; 8991 } 8992 8993 if (!CS.consumesDataArgument()) { 8994 // FIXME: Technically specifying a precision or field width here 8995 // makes no sense. Worth issuing a warning at some point. 8996 return true; 8997 } 8998 8999 // Consume the argument. 9000 unsigned argIndex = FS.getArgIndex(); 9001 if (argIndex < NumDataArgs) { 9002 // The check to see if the argIndex is valid will come later. 9003 // We set the bit here because we may exit early from this 9004 // function if we encounter some other error. 9005 CoveredArgs.set(argIndex); 9006 } 9007 9008 // FreeBSD kernel extensions. 9009 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 9010 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 9011 // We need at least two arguments. 9012 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 9013 return false; 9014 9015 // Claim the second argument. 9016 CoveredArgs.set(argIndex + 1); 9017 9018 // Type check the first argument (int for %b, pointer for %D) 9019 const Expr *Ex = getDataArg(argIndex); 9020 const analyze_printf::ArgType &AT = 9021 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 9022 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 9023 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 9024 EmitFormatDiagnostic( 9025 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9026 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 9027 << false << Ex->getSourceRange(), 9028 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9029 getSpecifierRange(startSpecifier, specifierLen)); 9030 9031 // Type check the second argument (char * for both %b and %D) 9032 Ex = getDataArg(argIndex + 1); 9033 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 9034 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 9035 EmitFormatDiagnostic( 9036 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9037 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 9038 << false << Ex->getSourceRange(), 9039 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9040 getSpecifierRange(startSpecifier, specifierLen)); 9041 9042 return true; 9043 } 9044 9045 // Check for using an Objective-C specific conversion specifier 9046 // in a non-ObjC literal. 9047 if (!allowsObjCArg() && CS.isObjCArg()) { 9048 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9049 specifierLen); 9050 } 9051 9052 // %P can only be used with os_log. 9053 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9054 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9055 specifierLen); 9056 } 9057 9058 // %n is not allowed with os_log. 9059 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9060 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9061 getLocationOfByte(CS.getStart()), 9062 /*IsStringLocation*/ false, 9063 getSpecifierRange(startSpecifier, specifierLen)); 9064 9065 return true; 9066 } 9067 9068 // Only scalars are allowed for os_trace. 9069 if (FSType == Sema::FST_OSTrace && 9070 (CS.getKind() == ConversionSpecifier::PArg || 9071 CS.getKind() == ConversionSpecifier::sArg || 9072 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9073 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9074 specifierLen); 9075 } 9076 9077 // Check for use of public/private annotation outside of os_log(). 9078 if (FSType != Sema::FST_OSLog) { 9079 if (FS.isPublic().isSet()) { 9080 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9081 << "public", 9082 getLocationOfByte(FS.isPublic().getPosition()), 9083 /*IsStringLocation*/ false, 9084 getSpecifierRange(startSpecifier, specifierLen)); 9085 } 9086 if (FS.isPrivate().isSet()) { 9087 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9088 << "private", 9089 getLocationOfByte(FS.isPrivate().getPosition()), 9090 /*IsStringLocation*/ false, 9091 getSpecifierRange(startSpecifier, specifierLen)); 9092 } 9093 } 9094 9095 // Check for invalid use of field width 9096 if (!FS.hasValidFieldWidth()) { 9097 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9098 startSpecifier, specifierLen); 9099 } 9100 9101 // Check for invalid use of precision 9102 if (!FS.hasValidPrecision()) { 9103 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9104 startSpecifier, specifierLen); 9105 } 9106 9107 // Precision is mandatory for %P specifier. 9108 if (CS.getKind() == ConversionSpecifier::PArg && 9109 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9110 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9111 getLocationOfByte(startSpecifier), 9112 /*IsStringLocation*/ false, 9113 getSpecifierRange(startSpecifier, specifierLen)); 9114 } 9115 9116 // Check each flag does not conflict with any other component. 9117 if (!FS.hasValidThousandsGroupingPrefix()) 9118 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9119 if (!FS.hasValidLeadingZeros()) 9120 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9121 if (!FS.hasValidPlusPrefix()) 9122 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9123 if (!FS.hasValidSpacePrefix()) 9124 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9125 if (!FS.hasValidAlternativeForm()) 9126 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9127 if (!FS.hasValidLeftJustified()) 9128 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9129 9130 // Check that flags are not ignored by another flag 9131 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9132 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9133 startSpecifier, specifierLen); 9134 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9135 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9136 startSpecifier, specifierLen); 9137 9138 // Check the length modifier is valid with the given conversion specifier. 9139 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9140 S.getLangOpts())) 9141 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9142 diag::warn_format_nonsensical_length); 9143 else if (!FS.hasStandardLengthModifier()) 9144 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9145 else if (!FS.hasStandardLengthConversionCombination()) 9146 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9147 diag::warn_format_non_standard_conversion_spec); 9148 9149 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9150 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9151 9152 // The remaining checks depend on the data arguments. 9153 if (HasVAListArg) 9154 return true; 9155 9156 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9157 return false; 9158 9159 const Expr *Arg = getDataArg(argIndex); 9160 if (!Arg) 9161 return true; 9162 9163 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9164 } 9165 9166 static bool requiresParensToAddCast(const Expr *E) { 9167 // FIXME: We should have a general way to reason about operator 9168 // precedence and whether parens are actually needed here. 9169 // Take care of a few common cases where they aren't. 9170 const Expr *Inside = E->IgnoreImpCasts(); 9171 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9172 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9173 9174 switch (Inside->getStmtClass()) { 9175 case Stmt::ArraySubscriptExprClass: 9176 case Stmt::CallExprClass: 9177 case Stmt::CharacterLiteralClass: 9178 case Stmt::CXXBoolLiteralExprClass: 9179 case Stmt::DeclRefExprClass: 9180 case Stmt::FloatingLiteralClass: 9181 case Stmt::IntegerLiteralClass: 9182 case Stmt::MemberExprClass: 9183 case Stmt::ObjCArrayLiteralClass: 9184 case Stmt::ObjCBoolLiteralExprClass: 9185 case Stmt::ObjCBoxedExprClass: 9186 case Stmt::ObjCDictionaryLiteralClass: 9187 case Stmt::ObjCEncodeExprClass: 9188 case Stmt::ObjCIvarRefExprClass: 9189 case Stmt::ObjCMessageExprClass: 9190 case Stmt::ObjCPropertyRefExprClass: 9191 case Stmt::ObjCStringLiteralClass: 9192 case Stmt::ObjCSubscriptRefExprClass: 9193 case Stmt::ParenExprClass: 9194 case Stmt::StringLiteralClass: 9195 case Stmt::UnaryOperatorClass: 9196 return false; 9197 default: 9198 return true; 9199 } 9200 } 9201 9202 static std::pair<QualType, StringRef> 9203 shouldNotPrintDirectly(const ASTContext &Context, 9204 QualType IntendedTy, 9205 const Expr *E) { 9206 // Use a 'while' to peel off layers of typedefs. 9207 QualType TyTy = IntendedTy; 9208 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9209 StringRef Name = UserTy->getDecl()->getName(); 9210 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9211 .Case("CFIndex", Context.getNSIntegerType()) 9212 .Case("NSInteger", Context.getNSIntegerType()) 9213 .Case("NSUInteger", Context.getNSUIntegerType()) 9214 .Case("SInt32", Context.IntTy) 9215 .Case("UInt32", Context.UnsignedIntTy) 9216 .Default(QualType()); 9217 9218 if (!CastTy.isNull()) 9219 return std::make_pair(CastTy, Name); 9220 9221 TyTy = UserTy->desugar(); 9222 } 9223 9224 // Strip parens if necessary. 9225 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9226 return shouldNotPrintDirectly(Context, 9227 PE->getSubExpr()->getType(), 9228 PE->getSubExpr()); 9229 9230 // If this is a conditional expression, then its result type is constructed 9231 // via usual arithmetic conversions and thus there might be no necessary 9232 // typedef sugar there. Recurse to operands to check for NSInteger & 9233 // Co. usage condition. 9234 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9235 QualType TrueTy, FalseTy; 9236 StringRef TrueName, FalseName; 9237 9238 std::tie(TrueTy, TrueName) = 9239 shouldNotPrintDirectly(Context, 9240 CO->getTrueExpr()->getType(), 9241 CO->getTrueExpr()); 9242 std::tie(FalseTy, FalseName) = 9243 shouldNotPrintDirectly(Context, 9244 CO->getFalseExpr()->getType(), 9245 CO->getFalseExpr()); 9246 9247 if (TrueTy == FalseTy) 9248 return std::make_pair(TrueTy, TrueName); 9249 else if (TrueTy.isNull()) 9250 return std::make_pair(FalseTy, FalseName); 9251 else if (FalseTy.isNull()) 9252 return std::make_pair(TrueTy, TrueName); 9253 } 9254 9255 return std::make_pair(QualType(), StringRef()); 9256 } 9257 9258 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9259 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9260 /// type do not count. 9261 static bool 9262 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9263 QualType From = ICE->getSubExpr()->getType(); 9264 QualType To = ICE->getType(); 9265 // It's an integer promotion if the destination type is the promoted 9266 // source type. 9267 if (ICE->getCastKind() == CK_IntegralCast && 9268 From->isPromotableIntegerType() && 9269 S.Context.getPromotedIntegerType(From) == To) 9270 return true; 9271 // Look through vector types, since we do default argument promotion for 9272 // those in OpenCL. 9273 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9274 From = VecTy->getElementType(); 9275 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9276 To = VecTy->getElementType(); 9277 // It's a floating promotion if the source type is a lower rank. 9278 return ICE->getCastKind() == CK_FloatingCast && 9279 S.Context.getFloatingTypeOrder(From, To) < 0; 9280 } 9281 9282 bool 9283 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9284 const char *StartSpecifier, 9285 unsigned SpecifierLen, 9286 const Expr *E) { 9287 using namespace analyze_format_string; 9288 using namespace analyze_printf; 9289 9290 // Now type check the data expression that matches the 9291 // format specifier. 9292 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9293 if (!AT.isValid()) 9294 return true; 9295 9296 QualType ExprTy = E->getType(); 9297 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9298 ExprTy = TET->getUnderlyingExpr()->getType(); 9299 } 9300 9301 // Diagnose attempts to print a boolean value as a character. Unlike other 9302 // -Wformat diagnostics, this is fine from a type perspective, but it still 9303 // doesn't make sense. 9304 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9305 E->isKnownToHaveBooleanValue()) { 9306 const CharSourceRange &CSR = 9307 getSpecifierRange(StartSpecifier, SpecifierLen); 9308 SmallString<4> FSString; 9309 llvm::raw_svector_ostream os(FSString); 9310 FS.toString(os); 9311 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9312 << FSString, 9313 E->getExprLoc(), false, CSR); 9314 return true; 9315 } 9316 9317 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9318 if (Match == analyze_printf::ArgType::Match) 9319 return true; 9320 9321 // Look through argument promotions for our error message's reported type. 9322 // This includes the integral and floating promotions, but excludes array 9323 // and function pointer decay (seeing that an argument intended to be a 9324 // string has type 'char [6]' is probably more confusing than 'char *') and 9325 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9326 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9327 if (isArithmeticArgumentPromotion(S, ICE)) { 9328 E = ICE->getSubExpr(); 9329 ExprTy = E->getType(); 9330 9331 // Check if we didn't match because of an implicit cast from a 'char' 9332 // or 'short' to an 'int'. This is done because printf is a varargs 9333 // function. 9334 if (ICE->getType() == S.Context.IntTy || 9335 ICE->getType() == S.Context.UnsignedIntTy) { 9336 // All further checking is done on the subexpression 9337 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9338 AT.matchesType(S.Context, ExprTy); 9339 if (ImplicitMatch == analyze_printf::ArgType::Match) 9340 return true; 9341 if (ImplicitMatch == ArgType::NoMatchPedantic || 9342 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9343 Match = ImplicitMatch; 9344 } 9345 } 9346 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9347 // Special case for 'a', which has type 'int' in C. 9348 // Note, however, that we do /not/ want to treat multibyte constants like 9349 // 'MooV' as characters! This form is deprecated but still exists. In 9350 // addition, don't treat expressions as of type 'char' if one byte length 9351 // modifier is provided. 9352 if (ExprTy == S.Context.IntTy && 9353 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9354 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9355 ExprTy = S.Context.CharTy; 9356 } 9357 9358 // Look through enums to their underlying type. 9359 bool IsEnum = false; 9360 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9361 ExprTy = EnumTy->getDecl()->getIntegerType(); 9362 IsEnum = true; 9363 } 9364 9365 // %C in an Objective-C context prints a unichar, not a wchar_t. 9366 // If the argument is an integer of some kind, believe the %C and suggest 9367 // a cast instead of changing the conversion specifier. 9368 QualType IntendedTy = ExprTy; 9369 if (isObjCContext() && 9370 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9371 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9372 !ExprTy->isCharType()) { 9373 // 'unichar' is defined as a typedef of unsigned short, but we should 9374 // prefer using the typedef if it is visible. 9375 IntendedTy = S.Context.UnsignedShortTy; 9376 9377 // While we are here, check if the value is an IntegerLiteral that happens 9378 // to be within the valid range. 9379 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9380 const llvm::APInt &V = IL->getValue(); 9381 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9382 return true; 9383 } 9384 9385 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9386 Sema::LookupOrdinaryName); 9387 if (S.LookupName(Result, S.getCurScope())) { 9388 NamedDecl *ND = Result.getFoundDecl(); 9389 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9390 if (TD->getUnderlyingType() == IntendedTy) 9391 IntendedTy = S.Context.getTypedefType(TD); 9392 } 9393 } 9394 } 9395 9396 // Special-case some of Darwin's platform-independence types by suggesting 9397 // casts to primitive types that are known to be large enough. 9398 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9399 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9400 QualType CastTy; 9401 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9402 if (!CastTy.isNull()) { 9403 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9404 // (long in ASTContext). Only complain to pedants. 9405 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9406 (AT.isSizeT() || AT.isPtrdiffT()) && 9407 AT.matchesType(S.Context, CastTy)) 9408 Match = ArgType::NoMatchPedantic; 9409 IntendedTy = CastTy; 9410 ShouldNotPrintDirectly = true; 9411 } 9412 } 9413 9414 // We may be able to offer a FixItHint if it is a supported type. 9415 PrintfSpecifier fixedFS = FS; 9416 bool Success = 9417 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9418 9419 if (Success) { 9420 // Get the fix string from the fixed format specifier 9421 SmallString<16> buf; 9422 llvm::raw_svector_ostream os(buf); 9423 fixedFS.toString(os); 9424 9425 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9426 9427 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9428 unsigned Diag; 9429 switch (Match) { 9430 case ArgType::Match: llvm_unreachable("expected non-matching"); 9431 case ArgType::NoMatchPedantic: 9432 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9433 break; 9434 case ArgType::NoMatchTypeConfusion: 9435 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9436 break; 9437 case ArgType::NoMatch: 9438 Diag = diag::warn_format_conversion_argument_type_mismatch; 9439 break; 9440 } 9441 9442 // In this case, the specifier is wrong and should be changed to match 9443 // the argument. 9444 EmitFormatDiagnostic(S.PDiag(Diag) 9445 << AT.getRepresentativeTypeName(S.Context) 9446 << IntendedTy << IsEnum << E->getSourceRange(), 9447 E->getBeginLoc(), 9448 /*IsStringLocation*/ false, SpecRange, 9449 FixItHint::CreateReplacement(SpecRange, os.str())); 9450 } else { 9451 // The canonical type for formatting this value is different from the 9452 // actual type of the expression. (This occurs, for example, with Darwin's 9453 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9454 // should be printed as 'long' for 64-bit compatibility.) 9455 // Rather than emitting a normal format/argument mismatch, we want to 9456 // add a cast to the recommended type (and correct the format string 9457 // if necessary). 9458 SmallString<16> CastBuf; 9459 llvm::raw_svector_ostream CastFix(CastBuf); 9460 CastFix << "("; 9461 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9462 CastFix << ")"; 9463 9464 SmallVector<FixItHint,4> Hints; 9465 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9466 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9467 9468 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9469 // If there's already a cast present, just replace it. 9470 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9471 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9472 9473 } else if (!requiresParensToAddCast(E)) { 9474 // If the expression has high enough precedence, 9475 // just write the C-style cast. 9476 Hints.push_back( 9477 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9478 } else { 9479 // Otherwise, add parens around the expression as well as the cast. 9480 CastFix << "("; 9481 Hints.push_back( 9482 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9483 9484 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9485 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9486 } 9487 9488 if (ShouldNotPrintDirectly) { 9489 // The expression has a type that should not be printed directly. 9490 // We extract the name from the typedef because we don't want to show 9491 // the underlying type in the diagnostic. 9492 StringRef Name; 9493 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9494 Name = TypedefTy->getDecl()->getName(); 9495 else 9496 Name = CastTyName; 9497 unsigned Diag = Match == ArgType::NoMatchPedantic 9498 ? diag::warn_format_argument_needs_cast_pedantic 9499 : diag::warn_format_argument_needs_cast; 9500 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9501 << E->getSourceRange(), 9502 E->getBeginLoc(), /*IsStringLocation=*/false, 9503 SpecRange, Hints); 9504 } else { 9505 // In this case, the expression could be printed using a different 9506 // specifier, but we've decided that the specifier is probably correct 9507 // and we should cast instead. Just use the normal warning message. 9508 EmitFormatDiagnostic( 9509 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9510 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9511 << E->getSourceRange(), 9512 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9513 } 9514 } 9515 } else { 9516 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9517 SpecifierLen); 9518 // Since the warning for passing non-POD types to variadic functions 9519 // was deferred until now, we emit a warning for non-POD 9520 // arguments here. 9521 switch (S.isValidVarArgType(ExprTy)) { 9522 case Sema::VAK_Valid: 9523 case Sema::VAK_ValidInCXX11: { 9524 unsigned Diag; 9525 switch (Match) { 9526 case ArgType::Match: llvm_unreachable("expected non-matching"); 9527 case ArgType::NoMatchPedantic: 9528 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9529 break; 9530 case ArgType::NoMatchTypeConfusion: 9531 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9532 break; 9533 case ArgType::NoMatch: 9534 Diag = diag::warn_format_conversion_argument_type_mismatch; 9535 break; 9536 } 9537 9538 EmitFormatDiagnostic( 9539 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9540 << IsEnum << CSR << E->getSourceRange(), 9541 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9542 break; 9543 } 9544 case Sema::VAK_Undefined: 9545 case Sema::VAK_MSVCUndefined: 9546 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9547 << S.getLangOpts().CPlusPlus11 << ExprTy 9548 << CallType 9549 << AT.getRepresentativeTypeName(S.Context) << CSR 9550 << E->getSourceRange(), 9551 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9552 checkForCStrMembers(AT, E); 9553 break; 9554 9555 case Sema::VAK_Invalid: 9556 if (ExprTy->isObjCObjectType()) 9557 EmitFormatDiagnostic( 9558 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9559 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9560 << AT.getRepresentativeTypeName(S.Context) << CSR 9561 << E->getSourceRange(), 9562 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9563 else 9564 // FIXME: If this is an initializer list, suggest removing the braces 9565 // or inserting a cast to the target type. 9566 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9567 << isa<InitListExpr>(E) << ExprTy << CallType 9568 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9569 break; 9570 } 9571 9572 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9573 "format string specifier index out of range"); 9574 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9575 } 9576 9577 return true; 9578 } 9579 9580 //===--- CHECK: Scanf format string checking ------------------------------===// 9581 9582 namespace { 9583 9584 class CheckScanfHandler : public CheckFormatHandler { 9585 public: 9586 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9587 const Expr *origFormatExpr, Sema::FormatStringType type, 9588 unsigned firstDataArg, unsigned numDataArgs, 9589 const char *beg, bool hasVAListArg, 9590 ArrayRef<const Expr *> Args, unsigned formatIdx, 9591 bool inFunctionCall, Sema::VariadicCallType CallType, 9592 llvm::SmallBitVector &CheckedVarArgs, 9593 UncoveredArgHandler &UncoveredArg) 9594 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9595 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9596 inFunctionCall, CallType, CheckedVarArgs, 9597 UncoveredArg) {} 9598 9599 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9600 const char *startSpecifier, 9601 unsigned specifierLen) override; 9602 9603 bool HandleInvalidScanfConversionSpecifier( 9604 const analyze_scanf::ScanfSpecifier &FS, 9605 const char *startSpecifier, 9606 unsigned specifierLen) override; 9607 9608 void HandleIncompleteScanList(const char *start, const char *end) override; 9609 }; 9610 9611 } // namespace 9612 9613 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9614 const char *end) { 9615 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9616 getLocationOfByte(end), /*IsStringLocation*/true, 9617 getSpecifierRange(start, end - start)); 9618 } 9619 9620 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9621 const analyze_scanf::ScanfSpecifier &FS, 9622 const char *startSpecifier, 9623 unsigned specifierLen) { 9624 const analyze_scanf::ScanfConversionSpecifier &CS = 9625 FS.getConversionSpecifier(); 9626 9627 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9628 getLocationOfByte(CS.getStart()), 9629 startSpecifier, specifierLen, 9630 CS.getStart(), CS.getLength()); 9631 } 9632 9633 bool CheckScanfHandler::HandleScanfSpecifier( 9634 const analyze_scanf::ScanfSpecifier &FS, 9635 const char *startSpecifier, 9636 unsigned specifierLen) { 9637 using namespace analyze_scanf; 9638 using namespace analyze_format_string; 9639 9640 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9641 9642 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9643 // be used to decide if we are using positional arguments consistently. 9644 if (FS.consumesDataArgument()) { 9645 if (atFirstArg) { 9646 atFirstArg = false; 9647 usesPositionalArgs = FS.usesPositionalArg(); 9648 } 9649 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9650 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9651 startSpecifier, specifierLen); 9652 return false; 9653 } 9654 } 9655 9656 // Check if the field with is non-zero. 9657 const OptionalAmount &Amt = FS.getFieldWidth(); 9658 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9659 if (Amt.getConstantAmount() == 0) { 9660 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9661 Amt.getConstantLength()); 9662 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9663 getLocationOfByte(Amt.getStart()), 9664 /*IsStringLocation*/true, R, 9665 FixItHint::CreateRemoval(R)); 9666 } 9667 } 9668 9669 if (!FS.consumesDataArgument()) { 9670 // FIXME: Technically specifying a precision or field width here 9671 // makes no sense. Worth issuing a warning at some point. 9672 return true; 9673 } 9674 9675 // Consume the argument. 9676 unsigned argIndex = FS.getArgIndex(); 9677 if (argIndex < NumDataArgs) { 9678 // The check to see if the argIndex is valid will come later. 9679 // We set the bit here because we may exit early from this 9680 // function if we encounter some other error. 9681 CoveredArgs.set(argIndex); 9682 } 9683 9684 // Check the length modifier is valid with the given conversion specifier. 9685 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9686 S.getLangOpts())) 9687 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9688 diag::warn_format_nonsensical_length); 9689 else if (!FS.hasStandardLengthModifier()) 9690 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9691 else if (!FS.hasStandardLengthConversionCombination()) 9692 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9693 diag::warn_format_non_standard_conversion_spec); 9694 9695 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9696 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9697 9698 // The remaining checks depend on the data arguments. 9699 if (HasVAListArg) 9700 return true; 9701 9702 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9703 return false; 9704 9705 // Check that the argument type matches the format specifier. 9706 const Expr *Ex = getDataArg(argIndex); 9707 if (!Ex) 9708 return true; 9709 9710 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9711 9712 if (!AT.isValid()) { 9713 return true; 9714 } 9715 9716 analyze_format_string::ArgType::MatchKind Match = 9717 AT.matchesType(S.Context, Ex->getType()); 9718 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9719 if (Match == analyze_format_string::ArgType::Match) 9720 return true; 9721 9722 ScanfSpecifier fixedFS = FS; 9723 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9724 S.getLangOpts(), S.Context); 9725 9726 unsigned Diag = 9727 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9728 : diag::warn_format_conversion_argument_type_mismatch; 9729 9730 if (Success) { 9731 // Get the fix string from the fixed format specifier. 9732 SmallString<128> buf; 9733 llvm::raw_svector_ostream os(buf); 9734 fixedFS.toString(os); 9735 9736 EmitFormatDiagnostic( 9737 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9738 << Ex->getType() << false << Ex->getSourceRange(), 9739 Ex->getBeginLoc(), 9740 /*IsStringLocation*/ false, 9741 getSpecifierRange(startSpecifier, specifierLen), 9742 FixItHint::CreateReplacement( 9743 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9744 } else { 9745 EmitFormatDiagnostic(S.PDiag(Diag) 9746 << AT.getRepresentativeTypeName(S.Context) 9747 << Ex->getType() << false << Ex->getSourceRange(), 9748 Ex->getBeginLoc(), 9749 /*IsStringLocation*/ false, 9750 getSpecifierRange(startSpecifier, specifierLen)); 9751 } 9752 9753 return true; 9754 } 9755 9756 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9757 const Expr *OrigFormatExpr, 9758 ArrayRef<const Expr *> Args, 9759 bool HasVAListArg, unsigned format_idx, 9760 unsigned firstDataArg, 9761 Sema::FormatStringType Type, 9762 bool inFunctionCall, 9763 Sema::VariadicCallType CallType, 9764 llvm::SmallBitVector &CheckedVarArgs, 9765 UncoveredArgHandler &UncoveredArg, 9766 bool IgnoreStringsWithoutSpecifiers) { 9767 // CHECK: is the format string a wide literal? 9768 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9769 CheckFormatHandler::EmitFormatDiagnostic( 9770 S, inFunctionCall, Args[format_idx], 9771 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9772 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9773 return; 9774 } 9775 9776 // Str - The format string. NOTE: this is NOT null-terminated! 9777 StringRef StrRef = FExpr->getString(); 9778 const char *Str = StrRef.data(); 9779 // Account for cases where the string literal is truncated in a declaration. 9780 const ConstantArrayType *T = 9781 S.Context.getAsConstantArrayType(FExpr->getType()); 9782 assert(T && "String literal not of constant array type!"); 9783 size_t TypeSize = T->getSize().getZExtValue(); 9784 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9785 const unsigned numDataArgs = Args.size() - firstDataArg; 9786 9787 if (IgnoreStringsWithoutSpecifiers && 9788 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9789 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9790 return; 9791 9792 // Emit a warning if the string literal is truncated and does not contain an 9793 // embedded null character. 9794 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 9795 CheckFormatHandler::EmitFormatDiagnostic( 9796 S, inFunctionCall, Args[format_idx], 9797 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9798 FExpr->getBeginLoc(), 9799 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9800 return; 9801 } 9802 9803 // CHECK: empty format string? 9804 if (StrLen == 0 && numDataArgs > 0) { 9805 CheckFormatHandler::EmitFormatDiagnostic( 9806 S, inFunctionCall, Args[format_idx], 9807 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9808 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9809 return; 9810 } 9811 9812 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9813 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9814 Type == Sema::FST_OSTrace) { 9815 CheckPrintfHandler H( 9816 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9817 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9818 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9819 CheckedVarArgs, UncoveredArg); 9820 9821 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9822 S.getLangOpts(), 9823 S.Context.getTargetInfo(), 9824 Type == Sema::FST_FreeBSDKPrintf)) 9825 H.DoneProcessing(); 9826 } else if (Type == Sema::FST_Scanf) { 9827 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9828 numDataArgs, Str, HasVAListArg, Args, format_idx, 9829 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9830 9831 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9832 S.getLangOpts(), 9833 S.Context.getTargetInfo())) 9834 H.DoneProcessing(); 9835 } // TODO: handle other formats 9836 } 9837 9838 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9839 // Str - The format string. NOTE: this is NOT null-terminated! 9840 StringRef StrRef = FExpr->getString(); 9841 const char *Str = StrRef.data(); 9842 // Account for cases where the string literal is truncated in a declaration. 9843 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9844 assert(T && "String literal not of constant array type!"); 9845 size_t TypeSize = T->getSize().getZExtValue(); 9846 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9847 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9848 getLangOpts(), 9849 Context.getTargetInfo()); 9850 } 9851 9852 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9853 9854 // Returns the related absolute value function that is larger, of 0 if one 9855 // does not exist. 9856 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9857 switch (AbsFunction) { 9858 default: 9859 return 0; 9860 9861 case Builtin::BI__builtin_abs: 9862 return Builtin::BI__builtin_labs; 9863 case Builtin::BI__builtin_labs: 9864 return Builtin::BI__builtin_llabs; 9865 case Builtin::BI__builtin_llabs: 9866 return 0; 9867 9868 case Builtin::BI__builtin_fabsf: 9869 return Builtin::BI__builtin_fabs; 9870 case Builtin::BI__builtin_fabs: 9871 return Builtin::BI__builtin_fabsl; 9872 case Builtin::BI__builtin_fabsl: 9873 return 0; 9874 9875 case Builtin::BI__builtin_cabsf: 9876 return Builtin::BI__builtin_cabs; 9877 case Builtin::BI__builtin_cabs: 9878 return Builtin::BI__builtin_cabsl; 9879 case Builtin::BI__builtin_cabsl: 9880 return 0; 9881 9882 case Builtin::BIabs: 9883 return Builtin::BIlabs; 9884 case Builtin::BIlabs: 9885 return Builtin::BIllabs; 9886 case Builtin::BIllabs: 9887 return 0; 9888 9889 case Builtin::BIfabsf: 9890 return Builtin::BIfabs; 9891 case Builtin::BIfabs: 9892 return Builtin::BIfabsl; 9893 case Builtin::BIfabsl: 9894 return 0; 9895 9896 case Builtin::BIcabsf: 9897 return Builtin::BIcabs; 9898 case Builtin::BIcabs: 9899 return Builtin::BIcabsl; 9900 case Builtin::BIcabsl: 9901 return 0; 9902 } 9903 } 9904 9905 // Returns the argument type of the absolute value function. 9906 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9907 unsigned AbsType) { 9908 if (AbsType == 0) 9909 return QualType(); 9910 9911 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9912 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9913 if (Error != ASTContext::GE_None) 9914 return QualType(); 9915 9916 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9917 if (!FT) 9918 return QualType(); 9919 9920 if (FT->getNumParams() != 1) 9921 return QualType(); 9922 9923 return FT->getParamType(0); 9924 } 9925 9926 // Returns the best absolute value function, or zero, based on type and 9927 // current absolute value function. 9928 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9929 unsigned AbsFunctionKind) { 9930 unsigned BestKind = 0; 9931 uint64_t ArgSize = Context.getTypeSize(ArgType); 9932 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9933 Kind = getLargerAbsoluteValueFunction(Kind)) { 9934 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9935 if (Context.getTypeSize(ParamType) >= ArgSize) { 9936 if (BestKind == 0) 9937 BestKind = Kind; 9938 else if (Context.hasSameType(ParamType, ArgType)) { 9939 BestKind = Kind; 9940 break; 9941 } 9942 } 9943 } 9944 return BestKind; 9945 } 9946 9947 enum AbsoluteValueKind { 9948 AVK_Integer, 9949 AVK_Floating, 9950 AVK_Complex 9951 }; 9952 9953 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9954 if (T->isIntegralOrEnumerationType()) 9955 return AVK_Integer; 9956 if (T->isRealFloatingType()) 9957 return AVK_Floating; 9958 if (T->isAnyComplexType()) 9959 return AVK_Complex; 9960 9961 llvm_unreachable("Type not integer, floating, or complex"); 9962 } 9963 9964 // Changes the absolute value function to a different type. Preserves whether 9965 // the function is a builtin. 9966 static unsigned changeAbsFunction(unsigned AbsKind, 9967 AbsoluteValueKind ValueKind) { 9968 switch (ValueKind) { 9969 case AVK_Integer: 9970 switch (AbsKind) { 9971 default: 9972 return 0; 9973 case Builtin::BI__builtin_fabsf: 9974 case Builtin::BI__builtin_fabs: 9975 case Builtin::BI__builtin_fabsl: 9976 case Builtin::BI__builtin_cabsf: 9977 case Builtin::BI__builtin_cabs: 9978 case Builtin::BI__builtin_cabsl: 9979 return Builtin::BI__builtin_abs; 9980 case Builtin::BIfabsf: 9981 case Builtin::BIfabs: 9982 case Builtin::BIfabsl: 9983 case Builtin::BIcabsf: 9984 case Builtin::BIcabs: 9985 case Builtin::BIcabsl: 9986 return Builtin::BIabs; 9987 } 9988 case AVK_Floating: 9989 switch (AbsKind) { 9990 default: 9991 return 0; 9992 case Builtin::BI__builtin_abs: 9993 case Builtin::BI__builtin_labs: 9994 case Builtin::BI__builtin_llabs: 9995 case Builtin::BI__builtin_cabsf: 9996 case Builtin::BI__builtin_cabs: 9997 case Builtin::BI__builtin_cabsl: 9998 return Builtin::BI__builtin_fabsf; 9999 case Builtin::BIabs: 10000 case Builtin::BIlabs: 10001 case Builtin::BIllabs: 10002 case Builtin::BIcabsf: 10003 case Builtin::BIcabs: 10004 case Builtin::BIcabsl: 10005 return Builtin::BIfabsf; 10006 } 10007 case AVK_Complex: 10008 switch (AbsKind) { 10009 default: 10010 return 0; 10011 case Builtin::BI__builtin_abs: 10012 case Builtin::BI__builtin_labs: 10013 case Builtin::BI__builtin_llabs: 10014 case Builtin::BI__builtin_fabsf: 10015 case Builtin::BI__builtin_fabs: 10016 case Builtin::BI__builtin_fabsl: 10017 return Builtin::BI__builtin_cabsf; 10018 case Builtin::BIabs: 10019 case Builtin::BIlabs: 10020 case Builtin::BIllabs: 10021 case Builtin::BIfabsf: 10022 case Builtin::BIfabs: 10023 case Builtin::BIfabsl: 10024 return Builtin::BIcabsf; 10025 } 10026 } 10027 llvm_unreachable("Unable to convert function"); 10028 } 10029 10030 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 10031 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 10032 if (!FnInfo) 10033 return 0; 10034 10035 switch (FDecl->getBuiltinID()) { 10036 default: 10037 return 0; 10038 case Builtin::BI__builtin_abs: 10039 case Builtin::BI__builtin_fabs: 10040 case Builtin::BI__builtin_fabsf: 10041 case Builtin::BI__builtin_fabsl: 10042 case Builtin::BI__builtin_labs: 10043 case Builtin::BI__builtin_llabs: 10044 case Builtin::BI__builtin_cabs: 10045 case Builtin::BI__builtin_cabsf: 10046 case Builtin::BI__builtin_cabsl: 10047 case Builtin::BIabs: 10048 case Builtin::BIlabs: 10049 case Builtin::BIllabs: 10050 case Builtin::BIfabs: 10051 case Builtin::BIfabsf: 10052 case Builtin::BIfabsl: 10053 case Builtin::BIcabs: 10054 case Builtin::BIcabsf: 10055 case Builtin::BIcabsl: 10056 return FDecl->getBuiltinID(); 10057 } 10058 llvm_unreachable("Unknown Builtin type"); 10059 } 10060 10061 // If the replacement is valid, emit a note with replacement function. 10062 // Additionally, suggest including the proper header if not already included. 10063 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10064 unsigned AbsKind, QualType ArgType) { 10065 bool EmitHeaderHint = true; 10066 const char *HeaderName = nullptr; 10067 const char *FunctionName = nullptr; 10068 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10069 FunctionName = "std::abs"; 10070 if (ArgType->isIntegralOrEnumerationType()) { 10071 HeaderName = "cstdlib"; 10072 } else if (ArgType->isRealFloatingType()) { 10073 HeaderName = "cmath"; 10074 } else { 10075 llvm_unreachable("Invalid Type"); 10076 } 10077 10078 // Lookup all std::abs 10079 if (NamespaceDecl *Std = S.getStdNamespace()) { 10080 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10081 R.suppressDiagnostics(); 10082 S.LookupQualifiedName(R, Std); 10083 10084 for (const auto *I : R) { 10085 const FunctionDecl *FDecl = nullptr; 10086 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10087 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10088 } else { 10089 FDecl = dyn_cast<FunctionDecl>(I); 10090 } 10091 if (!FDecl) 10092 continue; 10093 10094 // Found std::abs(), check that they are the right ones. 10095 if (FDecl->getNumParams() != 1) 10096 continue; 10097 10098 // Check that the parameter type can handle the argument. 10099 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10100 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10101 S.Context.getTypeSize(ArgType) <= 10102 S.Context.getTypeSize(ParamType)) { 10103 // Found a function, don't need the header hint. 10104 EmitHeaderHint = false; 10105 break; 10106 } 10107 } 10108 } 10109 } else { 10110 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10111 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10112 10113 if (HeaderName) { 10114 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10115 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10116 R.suppressDiagnostics(); 10117 S.LookupName(R, S.getCurScope()); 10118 10119 if (R.isSingleResult()) { 10120 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10121 if (FD && FD->getBuiltinID() == AbsKind) { 10122 EmitHeaderHint = false; 10123 } else { 10124 return; 10125 } 10126 } else if (!R.empty()) { 10127 return; 10128 } 10129 } 10130 } 10131 10132 S.Diag(Loc, diag::note_replace_abs_function) 10133 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10134 10135 if (!HeaderName) 10136 return; 10137 10138 if (!EmitHeaderHint) 10139 return; 10140 10141 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10142 << FunctionName; 10143 } 10144 10145 template <std::size_t StrLen> 10146 static bool IsStdFunction(const FunctionDecl *FDecl, 10147 const char (&Str)[StrLen]) { 10148 if (!FDecl) 10149 return false; 10150 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10151 return false; 10152 if (!FDecl->isInStdNamespace()) 10153 return false; 10154 10155 return true; 10156 } 10157 10158 // Warn when using the wrong abs() function. 10159 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10160 const FunctionDecl *FDecl) { 10161 if (Call->getNumArgs() != 1) 10162 return; 10163 10164 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10165 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10166 if (AbsKind == 0 && !IsStdAbs) 10167 return; 10168 10169 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10170 QualType ParamType = Call->getArg(0)->getType(); 10171 10172 // Unsigned types cannot be negative. Suggest removing the absolute value 10173 // function call. 10174 if (ArgType->isUnsignedIntegerType()) { 10175 const char *FunctionName = 10176 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10177 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10178 Diag(Call->getExprLoc(), diag::note_remove_abs) 10179 << FunctionName 10180 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10181 return; 10182 } 10183 10184 // Taking the absolute value of a pointer is very suspicious, they probably 10185 // wanted to index into an array, dereference a pointer, call a function, etc. 10186 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10187 unsigned DiagType = 0; 10188 if (ArgType->isFunctionType()) 10189 DiagType = 1; 10190 else if (ArgType->isArrayType()) 10191 DiagType = 2; 10192 10193 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10194 return; 10195 } 10196 10197 // std::abs has overloads which prevent most of the absolute value problems 10198 // from occurring. 10199 if (IsStdAbs) 10200 return; 10201 10202 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10203 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10204 10205 // The argument and parameter are the same kind. Check if they are the right 10206 // size. 10207 if (ArgValueKind == ParamValueKind) { 10208 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10209 return; 10210 10211 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10212 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10213 << FDecl << ArgType << ParamType; 10214 10215 if (NewAbsKind == 0) 10216 return; 10217 10218 emitReplacement(*this, Call->getExprLoc(), 10219 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10220 return; 10221 } 10222 10223 // ArgValueKind != ParamValueKind 10224 // The wrong type of absolute value function was used. Attempt to find the 10225 // proper one. 10226 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10227 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10228 if (NewAbsKind == 0) 10229 return; 10230 10231 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10232 << FDecl << ParamValueKind << ArgValueKind; 10233 10234 emitReplacement(*this, Call->getExprLoc(), 10235 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10236 } 10237 10238 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10239 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10240 const FunctionDecl *FDecl) { 10241 if (!Call || !FDecl) return; 10242 10243 // Ignore template specializations and macros. 10244 if (inTemplateInstantiation()) return; 10245 if (Call->getExprLoc().isMacroID()) return; 10246 10247 // Only care about the one template argument, two function parameter std::max 10248 if (Call->getNumArgs() != 2) return; 10249 if (!IsStdFunction(FDecl, "max")) return; 10250 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10251 if (!ArgList) return; 10252 if (ArgList->size() != 1) return; 10253 10254 // Check that template type argument is unsigned integer. 10255 const auto& TA = ArgList->get(0); 10256 if (TA.getKind() != TemplateArgument::Type) return; 10257 QualType ArgType = TA.getAsType(); 10258 if (!ArgType->isUnsignedIntegerType()) return; 10259 10260 // See if either argument is a literal zero. 10261 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10262 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10263 if (!MTE) return false; 10264 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10265 if (!Num) return false; 10266 if (Num->getValue() != 0) return false; 10267 return true; 10268 }; 10269 10270 const Expr *FirstArg = Call->getArg(0); 10271 const Expr *SecondArg = Call->getArg(1); 10272 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10273 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10274 10275 // Only warn when exactly one argument is zero. 10276 if (IsFirstArgZero == IsSecondArgZero) return; 10277 10278 SourceRange FirstRange = FirstArg->getSourceRange(); 10279 SourceRange SecondRange = SecondArg->getSourceRange(); 10280 10281 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10282 10283 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10284 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10285 10286 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10287 SourceRange RemovalRange; 10288 if (IsFirstArgZero) { 10289 RemovalRange = SourceRange(FirstRange.getBegin(), 10290 SecondRange.getBegin().getLocWithOffset(-1)); 10291 } else { 10292 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10293 SecondRange.getEnd()); 10294 } 10295 10296 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10297 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10298 << FixItHint::CreateRemoval(RemovalRange); 10299 } 10300 10301 //===--- CHECK: Standard memory functions ---------------------------------===// 10302 10303 /// Takes the expression passed to the size_t parameter of functions 10304 /// such as memcmp, strncat, etc and warns if it's a comparison. 10305 /// 10306 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10307 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10308 IdentifierInfo *FnName, 10309 SourceLocation FnLoc, 10310 SourceLocation RParenLoc) { 10311 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10312 if (!Size) 10313 return false; 10314 10315 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10316 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10317 return false; 10318 10319 SourceRange SizeRange = Size->getSourceRange(); 10320 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10321 << SizeRange << FnName; 10322 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10323 << FnName 10324 << FixItHint::CreateInsertion( 10325 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10326 << FixItHint::CreateRemoval(RParenLoc); 10327 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10328 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10329 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10330 ")"); 10331 10332 return true; 10333 } 10334 10335 /// Determine whether the given type is or contains a dynamic class type 10336 /// (e.g., whether it has a vtable). 10337 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10338 bool &IsContained) { 10339 // Look through array types while ignoring qualifiers. 10340 const Type *Ty = T->getBaseElementTypeUnsafe(); 10341 IsContained = false; 10342 10343 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10344 RD = RD ? RD->getDefinition() : nullptr; 10345 if (!RD || RD->isInvalidDecl()) 10346 return nullptr; 10347 10348 if (RD->isDynamicClass()) 10349 return RD; 10350 10351 // Check all the fields. If any bases were dynamic, the class is dynamic. 10352 // It's impossible for a class to transitively contain itself by value, so 10353 // infinite recursion is impossible. 10354 for (auto *FD : RD->fields()) { 10355 bool SubContained; 10356 if (const CXXRecordDecl *ContainedRD = 10357 getContainedDynamicClass(FD->getType(), SubContained)) { 10358 IsContained = true; 10359 return ContainedRD; 10360 } 10361 } 10362 10363 return nullptr; 10364 } 10365 10366 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10367 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10368 if (Unary->getKind() == UETT_SizeOf) 10369 return Unary; 10370 return nullptr; 10371 } 10372 10373 /// If E is a sizeof expression, returns its argument expression, 10374 /// otherwise returns NULL. 10375 static const Expr *getSizeOfExprArg(const Expr *E) { 10376 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10377 if (!SizeOf->isArgumentType()) 10378 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10379 return nullptr; 10380 } 10381 10382 /// If E is a sizeof expression, returns its argument type. 10383 static QualType getSizeOfArgType(const Expr *E) { 10384 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10385 return SizeOf->getTypeOfArgument(); 10386 return QualType(); 10387 } 10388 10389 namespace { 10390 10391 struct SearchNonTrivialToInitializeField 10392 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10393 using Super = 10394 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10395 10396 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10397 10398 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10399 SourceLocation SL) { 10400 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10401 asDerived().visitArray(PDIK, AT, SL); 10402 return; 10403 } 10404 10405 Super::visitWithKind(PDIK, FT, SL); 10406 } 10407 10408 void visitARCStrong(QualType FT, SourceLocation SL) { 10409 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10410 } 10411 void visitARCWeak(QualType FT, SourceLocation SL) { 10412 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10413 } 10414 void visitStruct(QualType FT, SourceLocation SL) { 10415 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10416 visit(FD->getType(), FD->getLocation()); 10417 } 10418 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10419 const ArrayType *AT, SourceLocation SL) { 10420 visit(getContext().getBaseElementType(AT), SL); 10421 } 10422 void visitTrivial(QualType FT, SourceLocation SL) {} 10423 10424 static void diag(QualType RT, const Expr *E, Sema &S) { 10425 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10426 } 10427 10428 ASTContext &getContext() { return S.getASTContext(); } 10429 10430 const Expr *E; 10431 Sema &S; 10432 }; 10433 10434 struct SearchNonTrivialToCopyField 10435 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10436 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10437 10438 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10439 10440 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10441 SourceLocation SL) { 10442 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10443 asDerived().visitArray(PCK, AT, SL); 10444 return; 10445 } 10446 10447 Super::visitWithKind(PCK, FT, SL); 10448 } 10449 10450 void visitARCStrong(QualType FT, SourceLocation SL) { 10451 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10452 } 10453 void visitARCWeak(QualType FT, SourceLocation SL) { 10454 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10455 } 10456 void visitStruct(QualType FT, SourceLocation SL) { 10457 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10458 visit(FD->getType(), FD->getLocation()); 10459 } 10460 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10461 SourceLocation SL) { 10462 visit(getContext().getBaseElementType(AT), SL); 10463 } 10464 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10465 SourceLocation SL) {} 10466 void visitTrivial(QualType FT, SourceLocation SL) {} 10467 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10468 10469 static void diag(QualType RT, const Expr *E, Sema &S) { 10470 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10471 } 10472 10473 ASTContext &getContext() { return S.getASTContext(); } 10474 10475 const Expr *E; 10476 Sema &S; 10477 }; 10478 10479 } 10480 10481 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10482 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10483 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10484 10485 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10486 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10487 return false; 10488 10489 return doesExprLikelyComputeSize(BO->getLHS()) || 10490 doesExprLikelyComputeSize(BO->getRHS()); 10491 } 10492 10493 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10494 } 10495 10496 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10497 /// 10498 /// \code 10499 /// #define MACRO 0 10500 /// foo(MACRO); 10501 /// foo(0); 10502 /// \endcode 10503 /// 10504 /// This should return true for the first call to foo, but not for the second 10505 /// (regardless of whether foo is a macro or function). 10506 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10507 SourceLocation CallLoc, 10508 SourceLocation ArgLoc) { 10509 if (!CallLoc.isMacroID()) 10510 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10511 10512 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10513 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10514 } 10515 10516 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10517 /// last two arguments transposed. 10518 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10519 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10520 return; 10521 10522 const Expr *SizeArg = 10523 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10524 10525 auto isLiteralZero = [](const Expr *E) { 10526 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10527 }; 10528 10529 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10530 SourceLocation CallLoc = Call->getRParenLoc(); 10531 SourceManager &SM = S.getSourceManager(); 10532 if (isLiteralZero(SizeArg) && 10533 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10534 10535 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10536 10537 // Some platforms #define bzero to __builtin_memset. See if this is the 10538 // case, and if so, emit a better diagnostic. 10539 if (BId == Builtin::BIbzero || 10540 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10541 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10542 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10543 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10544 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10545 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10546 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10547 } 10548 return; 10549 } 10550 10551 // If the second argument to a memset is a sizeof expression and the third 10552 // isn't, this is also likely an error. This should catch 10553 // 'memset(buf, sizeof(buf), 0xff)'. 10554 if (BId == Builtin::BImemset && 10555 doesExprLikelyComputeSize(Call->getArg(1)) && 10556 !doesExprLikelyComputeSize(Call->getArg(2))) { 10557 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10558 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10559 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10560 return; 10561 } 10562 } 10563 10564 /// Check for dangerous or invalid arguments to memset(). 10565 /// 10566 /// This issues warnings on known problematic, dangerous or unspecified 10567 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10568 /// function calls. 10569 /// 10570 /// \param Call The call expression to diagnose. 10571 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10572 unsigned BId, 10573 IdentifierInfo *FnName) { 10574 assert(BId != 0); 10575 10576 // It is possible to have a non-standard definition of memset. Validate 10577 // we have enough arguments, and if not, abort further checking. 10578 unsigned ExpectedNumArgs = 10579 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10580 if (Call->getNumArgs() < ExpectedNumArgs) 10581 return; 10582 10583 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10584 BId == Builtin::BIstrndup ? 1 : 2); 10585 unsigned LenArg = 10586 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10587 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10588 10589 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10590 Call->getBeginLoc(), Call->getRParenLoc())) 10591 return; 10592 10593 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10594 CheckMemaccessSize(*this, BId, Call); 10595 10596 // We have special checking when the length is a sizeof expression. 10597 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10598 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10599 llvm::FoldingSetNodeID SizeOfArgID; 10600 10601 // Although widely used, 'bzero' is not a standard function. Be more strict 10602 // with the argument types before allowing diagnostics and only allow the 10603 // form bzero(ptr, sizeof(...)). 10604 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10605 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10606 return; 10607 10608 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10609 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10610 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10611 10612 QualType DestTy = Dest->getType(); 10613 QualType PointeeTy; 10614 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10615 PointeeTy = DestPtrTy->getPointeeType(); 10616 10617 // Never warn about void type pointers. This can be used to suppress 10618 // false positives. 10619 if (PointeeTy->isVoidType()) 10620 continue; 10621 10622 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10623 // actually comparing the expressions for equality. Because computing the 10624 // expression IDs can be expensive, we only do this if the diagnostic is 10625 // enabled. 10626 if (SizeOfArg && 10627 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10628 SizeOfArg->getExprLoc())) { 10629 // We only compute IDs for expressions if the warning is enabled, and 10630 // cache the sizeof arg's ID. 10631 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10632 SizeOfArg->Profile(SizeOfArgID, Context, true); 10633 llvm::FoldingSetNodeID DestID; 10634 Dest->Profile(DestID, Context, true); 10635 if (DestID == SizeOfArgID) { 10636 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10637 // over sizeof(src) as well. 10638 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10639 StringRef ReadableName = FnName->getName(); 10640 10641 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10642 if (UnaryOp->getOpcode() == UO_AddrOf) 10643 ActionIdx = 1; // If its an address-of operator, just remove it. 10644 if (!PointeeTy->isIncompleteType() && 10645 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10646 ActionIdx = 2; // If the pointee's size is sizeof(char), 10647 // suggest an explicit length. 10648 10649 // If the function is defined as a builtin macro, do not show macro 10650 // expansion. 10651 SourceLocation SL = SizeOfArg->getExprLoc(); 10652 SourceRange DSR = Dest->getSourceRange(); 10653 SourceRange SSR = SizeOfArg->getSourceRange(); 10654 SourceManager &SM = getSourceManager(); 10655 10656 if (SM.isMacroArgExpansion(SL)) { 10657 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10658 SL = SM.getSpellingLoc(SL); 10659 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10660 SM.getSpellingLoc(DSR.getEnd())); 10661 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10662 SM.getSpellingLoc(SSR.getEnd())); 10663 } 10664 10665 DiagRuntimeBehavior(SL, SizeOfArg, 10666 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10667 << ReadableName 10668 << PointeeTy 10669 << DestTy 10670 << DSR 10671 << SSR); 10672 DiagRuntimeBehavior(SL, SizeOfArg, 10673 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10674 << ActionIdx 10675 << SSR); 10676 10677 break; 10678 } 10679 } 10680 10681 // Also check for cases where the sizeof argument is the exact same 10682 // type as the memory argument, and where it points to a user-defined 10683 // record type. 10684 if (SizeOfArgTy != QualType()) { 10685 if (PointeeTy->isRecordType() && 10686 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10687 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10688 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10689 << FnName << SizeOfArgTy << ArgIdx 10690 << PointeeTy << Dest->getSourceRange() 10691 << LenExpr->getSourceRange()); 10692 break; 10693 } 10694 } 10695 } else if (DestTy->isArrayType()) { 10696 PointeeTy = DestTy; 10697 } 10698 10699 if (PointeeTy == QualType()) 10700 continue; 10701 10702 // Always complain about dynamic classes. 10703 bool IsContained; 10704 if (const CXXRecordDecl *ContainedRD = 10705 getContainedDynamicClass(PointeeTy, IsContained)) { 10706 10707 unsigned OperationType = 0; 10708 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10709 // "overwritten" if we're warning about the destination for any call 10710 // but memcmp; otherwise a verb appropriate to the call. 10711 if (ArgIdx != 0 || IsCmp) { 10712 if (BId == Builtin::BImemcpy) 10713 OperationType = 1; 10714 else if(BId == Builtin::BImemmove) 10715 OperationType = 2; 10716 else if (IsCmp) 10717 OperationType = 3; 10718 } 10719 10720 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10721 PDiag(diag::warn_dyn_class_memaccess) 10722 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10723 << IsContained << ContainedRD << OperationType 10724 << Call->getCallee()->getSourceRange()); 10725 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10726 BId != Builtin::BImemset) 10727 DiagRuntimeBehavior( 10728 Dest->getExprLoc(), Dest, 10729 PDiag(diag::warn_arc_object_memaccess) 10730 << ArgIdx << FnName << PointeeTy 10731 << Call->getCallee()->getSourceRange()); 10732 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10733 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10734 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10735 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10736 PDiag(diag::warn_cstruct_memaccess) 10737 << ArgIdx << FnName << PointeeTy << 0); 10738 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10739 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10740 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10741 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10742 PDiag(diag::warn_cstruct_memaccess) 10743 << ArgIdx << FnName << PointeeTy << 1); 10744 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10745 } else { 10746 continue; 10747 } 10748 } else 10749 continue; 10750 10751 DiagRuntimeBehavior( 10752 Dest->getExprLoc(), Dest, 10753 PDiag(diag::note_bad_memaccess_silence) 10754 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10755 break; 10756 } 10757 } 10758 10759 // A little helper routine: ignore addition and subtraction of integer literals. 10760 // This intentionally does not ignore all integer constant expressions because 10761 // we don't want to remove sizeof(). 10762 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10763 Ex = Ex->IgnoreParenCasts(); 10764 10765 while (true) { 10766 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10767 if (!BO || !BO->isAdditiveOp()) 10768 break; 10769 10770 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10771 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10772 10773 if (isa<IntegerLiteral>(RHS)) 10774 Ex = LHS; 10775 else if (isa<IntegerLiteral>(LHS)) 10776 Ex = RHS; 10777 else 10778 break; 10779 } 10780 10781 return Ex; 10782 } 10783 10784 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10785 ASTContext &Context) { 10786 // Only handle constant-sized or VLAs, but not flexible members. 10787 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10788 // Only issue the FIXIT for arrays of size > 1. 10789 if (CAT->getSize().getSExtValue() <= 1) 10790 return false; 10791 } else if (!Ty->isVariableArrayType()) { 10792 return false; 10793 } 10794 return true; 10795 } 10796 10797 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10798 // be the size of the source, instead of the destination. 10799 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10800 IdentifierInfo *FnName) { 10801 10802 // Don't crash if the user has the wrong number of arguments 10803 unsigned NumArgs = Call->getNumArgs(); 10804 if ((NumArgs != 3) && (NumArgs != 4)) 10805 return; 10806 10807 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10808 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10809 const Expr *CompareWithSrc = nullptr; 10810 10811 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10812 Call->getBeginLoc(), Call->getRParenLoc())) 10813 return; 10814 10815 // Look for 'strlcpy(dst, x, sizeof(x))' 10816 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10817 CompareWithSrc = Ex; 10818 else { 10819 // Look for 'strlcpy(dst, x, strlen(x))' 10820 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10821 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10822 SizeCall->getNumArgs() == 1) 10823 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10824 } 10825 } 10826 10827 if (!CompareWithSrc) 10828 return; 10829 10830 // Determine if the argument to sizeof/strlen is equal to the source 10831 // argument. In principle there's all kinds of things you could do 10832 // here, for instance creating an == expression and evaluating it with 10833 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10834 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10835 if (!SrcArgDRE) 10836 return; 10837 10838 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10839 if (!CompareWithSrcDRE || 10840 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10841 return; 10842 10843 const Expr *OriginalSizeArg = Call->getArg(2); 10844 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10845 << OriginalSizeArg->getSourceRange() << FnName; 10846 10847 // Output a FIXIT hint if the destination is an array (rather than a 10848 // pointer to an array). This could be enhanced to handle some 10849 // pointers if we know the actual size, like if DstArg is 'array+2' 10850 // we could say 'sizeof(array)-2'. 10851 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10852 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10853 return; 10854 10855 SmallString<128> sizeString; 10856 llvm::raw_svector_ostream OS(sizeString); 10857 OS << "sizeof("; 10858 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10859 OS << ")"; 10860 10861 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10862 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10863 OS.str()); 10864 } 10865 10866 /// Check if two expressions refer to the same declaration. 10867 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10868 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10869 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10870 return D1->getDecl() == D2->getDecl(); 10871 return false; 10872 } 10873 10874 static const Expr *getStrlenExprArg(const Expr *E) { 10875 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10876 const FunctionDecl *FD = CE->getDirectCallee(); 10877 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10878 return nullptr; 10879 return CE->getArg(0)->IgnoreParenCasts(); 10880 } 10881 return nullptr; 10882 } 10883 10884 // Warn on anti-patterns as the 'size' argument to strncat. 10885 // The correct size argument should look like following: 10886 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10887 void Sema::CheckStrncatArguments(const CallExpr *CE, 10888 IdentifierInfo *FnName) { 10889 // Don't crash if the user has the wrong number of arguments. 10890 if (CE->getNumArgs() < 3) 10891 return; 10892 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10893 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10894 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10895 10896 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10897 CE->getRParenLoc())) 10898 return; 10899 10900 // Identify common expressions, which are wrongly used as the size argument 10901 // to strncat and may lead to buffer overflows. 10902 unsigned PatternType = 0; 10903 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10904 // - sizeof(dst) 10905 if (referToTheSameDecl(SizeOfArg, DstArg)) 10906 PatternType = 1; 10907 // - sizeof(src) 10908 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10909 PatternType = 2; 10910 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10911 if (BE->getOpcode() == BO_Sub) { 10912 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10913 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10914 // - sizeof(dst) - strlen(dst) 10915 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10916 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10917 PatternType = 1; 10918 // - sizeof(src) - (anything) 10919 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10920 PatternType = 2; 10921 } 10922 } 10923 10924 if (PatternType == 0) 10925 return; 10926 10927 // Generate the diagnostic. 10928 SourceLocation SL = LenArg->getBeginLoc(); 10929 SourceRange SR = LenArg->getSourceRange(); 10930 SourceManager &SM = getSourceManager(); 10931 10932 // If the function is defined as a builtin macro, do not show macro expansion. 10933 if (SM.isMacroArgExpansion(SL)) { 10934 SL = SM.getSpellingLoc(SL); 10935 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10936 SM.getSpellingLoc(SR.getEnd())); 10937 } 10938 10939 // Check if the destination is an array (rather than a pointer to an array). 10940 QualType DstTy = DstArg->getType(); 10941 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10942 Context); 10943 if (!isKnownSizeArray) { 10944 if (PatternType == 1) 10945 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10946 else 10947 Diag(SL, diag::warn_strncat_src_size) << SR; 10948 return; 10949 } 10950 10951 if (PatternType == 1) 10952 Diag(SL, diag::warn_strncat_large_size) << SR; 10953 else 10954 Diag(SL, diag::warn_strncat_src_size) << SR; 10955 10956 SmallString<128> sizeString; 10957 llvm::raw_svector_ostream OS(sizeString); 10958 OS << "sizeof("; 10959 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10960 OS << ") - "; 10961 OS << "strlen("; 10962 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10963 OS << ") - 1"; 10964 10965 Diag(SL, diag::note_strncat_wrong_size) 10966 << FixItHint::CreateReplacement(SR, OS.str()); 10967 } 10968 10969 namespace { 10970 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10971 const UnaryOperator *UnaryExpr, const Decl *D) { 10972 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10973 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10974 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10975 return; 10976 } 10977 } 10978 10979 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10980 const UnaryOperator *UnaryExpr) { 10981 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10982 const Decl *D = Lvalue->getDecl(); 10983 if (isa<DeclaratorDecl>(D)) 10984 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 10985 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10986 } 10987 10988 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10989 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10990 Lvalue->getMemberDecl()); 10991 } 10992 10993 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10994 const UnaryOperator *UnaryExpr) { 10995 const auto *Lambda = dyn_cast<LambdaExpr>( 10996 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10997 if (!Lambda) 10998 return; 10999 11000 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 11001 << CalleeName << 2 /*object: lambda expression*/; 11002 } 11003 11004 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 11005 const DeclRefExpr *Lvalue) { 11006 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 11007 if (Var == nullptr) 11008 return; 11009 11010 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 11011 << CalleeName << 0 /*object: */ << Var; 11012 } 11013 11014 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 11015 const CastExpr *Cast) { 11016 SmallString<128> SizeString; 11017 llvm::raw_svector_ostream OS(SizeString); 11018 11019 clang::CastKind Kind = Cast->getCastKind(); 11020 if (Kind == clang::CK_BitCast && 11021 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 11022 return; 11023 if (Kind == clang::CK_IntegralToPointer && 11024 !isa<IntegerLiteral>( 11025 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 11026 return; 11027 11028 switch (Cast->getCastKind()) { 11029 case clang::CK_BitCast: 11030 case clang::CK_IntegralToPointer: 11031 case clang::CK_FunctionToPointerDecay: 11032 OS << '\''; 11033 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 11034 OS << '\''; 11035 break; 11036 default: 11037 return; 11038 } 11039 11040 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 11041 << CalleeName << 0 /*object: */ << OS.str(); 11042 } 11043 } // namespace 11044 11045 /// Alerts the user that they are attempting to free a non-malloc'd object. 11046 void Sema::CheckFreeArguments(const CallExpr *E) { 11047 const std::string CalleeName = 11048 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 11049 11050 { // Prefer something that doesn't involve a cast to make things simpler. 11051 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11052 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11053 switch (UnaryExpr->getOpcode()) { 11054 case UnaryOperator::Opcode::UO_AddrOf: 11055 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11056 case UnaryOperator::Opcode::UO_Plus: 11057 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11058 default: 11059 break; 11060 } 11061 11062 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11063 if (Lvalue->getType()->isArrayType()) 11064 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11065 11066 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11067 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11068 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11069 return; 11070 } 11071 11072 if (isa<BlockExpr>(Arg)) { 11073 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11074 << CalleeName << 1 /*object: block*/; 11075 return; 11076 } 11077 } 11078 // Maybe the cast was important, check after the other cases. 11079 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11080 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11081 } 11082 11083 void 11084 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11085 SourceLocation ReturnLoc, 11086 bool isObjCMethod, 11087 const AttrVec *Attrs, 11088 const FunctionDecl *FD) { 11089 // Check if the return value is null but should not be. 11090 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11091 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11092 CheckNonNullExpr(*this, RetValExp)) 11093 Diag(ReturnLoc, diag::warn_null_ret) 11094 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11095 11096 // C++11 [basic.stc.dynamic.allocation]p4: 11097 // If an allocation function declared with a non-throwing 11098 // exception-specification fails to allocate storage, it shall return 11099 // a null pointer. Any other allocation function that fails to allocate 11100 // storage shall indicate failure only by throwing an exception [...] 11101 if (FD) { 11102 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11103 if (Op == OO_New || Op == OO_Array_New) { 11104 const FunctionProtoType *Proto 11105 = FD->getType()->castAs<FunctionProtoType>(); 11106 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11107 CheckNonNullExpr(*this, RetValExp)) 11108 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11109 << FD << getLangOpts().CPlusPlus11; 11110 } 11111 } 11112 11113 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11114 // here prevent the user from using a PPC MMA type as trailing return type. 11115 if (Context.getTargetInfo().getTriple().isPPC64()) 11116 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11117 } 11118 11119 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 11120 11121 /// Check for comparisons of floating point operands using != and ==. 11122 /// Issue a warning if these are no self-comparisons, as they are not likely 11123 /// to do what the programmer intended. 11124 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 11125 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11126 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11127 11128 // Special case: check for x == x (which is OK). 11129 // Do not emit warnings for such cases. 11130 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11131 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11132 if (DRL->getDecl() == DRR->getDecl()) 11133 return; 11134 11135 // Special case: check for comparisons against literals that can be exactly 11136 // represented by APFloat. In such cases, do not emit a warning. This 11137 // is a heuristic: often comparison against such literals are used to 11138 // detect if a value in a variable has not changed. This clearly can 11139 // lead to false negatives. 11140 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11141 if (FLL->isExact()) 11142 return; 11143 } else 11144 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11145 if (FLR->isExact()) 11146 return; 11147 11148 // Check for comparisons with builtin types. 11149 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11150 if (CL->getBuiltinCallee()) 11151 return; 11152 11153 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11154 if (CR->getBuiltinCallee()) 11155 return; 11156 11157 // Emit the diagnostic. 11158 Diag(Loc, diag::warn_floatingpoint_eq) 11159 << LHS->getSourceRange() << RHS->getSourceRange(); 11160 } 11161 11162 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11163 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11164 11165 namespace { 11166 11167 /// Structure recording the 'active' range of an integer-valued 11168 /// expression. 11169 struct IntRange { 11170 /// The number of bits active in the int. Note that this includes exactly one 11171 /// sign bit if !NonNegative. 11172 unsigned Width; 11173 11174 /// True if the int is known not to have negative values. If so, all leading 11175 /// bits before Width are known zero, otherwise they are known to be the 11176 /// same as the MSB within Width. 11177 bool NonNegative; 11178 11179 IntRange(unsigned Width, bool NonNegative) 11180 : Width(Width), NonNegative(NonNegative) {} 11181 11182 /// Number of bits excluding the sign bit. 11183 unsigned valueBits() const { 11184 return NonNegative ? Width : Width - 1; 11185 } 11186 11187 /// Returns the range of the bool type. 11188 static IntRange forBoolType() { 11189 return IntRange(1, true); 11190 } 11191 11192 /// Returns the range of an opaque value of the given integral type. 11193 static IntRange forValueOfType(ASTContext &C, QualType T) { 11194 return forValueOfCanonicalType(C, 11195 T->getCanonicalTypeInternal().getTypePtr()); 11196 } 11197 11198 /// Returns the range of an opaque value of a canonical integral type. 11199 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11200 assert(T->isCanonicalUnqualified()); 11201 11202 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11203 T = VT->getElementType().getTypePtr(); 11204 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11205 T = CT->getElementType().getTypePtr(); 11206 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11207 T = AT->getValueType().getTypePtr(); 11208 11209 if (!C.getLangOpts().CPlusPlus) { 11210 // For enum types in C code, use the underlying datatype. 11211 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11212 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11213 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11214 // For enum types in C++, use the known bit width of the enumerators. 11215 EnumDecl *Enum = ET->getDecl(); 11216 // In C++11, enums can have a fixed underlying type. Use this type to 11217 // compute the range. 11218 if (Enum->isFixed()) { 11219 return IntRange(C.getIntWidth(QualType(T, 0)), 11220 !ET->isSignedIntegerOrEnumerationType()); 11221 } 11222 11223 unsigned NumPositive = Enum->getNumPositiveBits(); 11224 unsigned NumNegative = Enum->getNumNegativeBits(); 11225 11226 if (NumNegative == 0) 11227 return IntRange(NumPositive, true/*NonNegative*/); 11228 else 11229 return IntRange(std::max(NumPositive + 1, NumNegative), 11230 false/*NonNegative*/); 11231 } 11232 11233 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11234 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11235 11236 const BuiltinType *BT = cast<BuiltinType>(T); 11237 assert(BT->isInteger()); 11238 11239 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11240 } 11241 11242 /// Returns the "target" range of a canonical integral type, i.e. 11243 /// the range of values expressible in the type. 11244 /// 11245 /// This matches forValueOfCanonicalType except that enums have the 11246 /// full range of their type, not the range of their enumerators. 11247 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11248 assert(T->isCanonicalUnqualified()); 11249 11250 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11251 T = VT->getElementType().getTypePtr(); 11252 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11253 T = CT->getElementType().getTypePtr(); 11254 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11255 T = AT->getValueType().getTypePtr(); 11256 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11257 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11258 11259 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11260 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11261 11262 const BuiltinType *BT = cast<BuiltinType>(T); 11263 assert(BT->isInteger()); 11264 11265 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11266 } 11267 11268 /// Returns the supremum of two ranges: i.e. their conservative merge. 11269 static IntRange join(IntRange L, IntRange R) { 11270 bool Unsigned = L.NonNegative && R.NonNegative; 11271 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11272 L.NonNegative && R.NonNegative); 11273 } 11274 11275 /// Return the range of a bitwise-AND of the two ranges. 11276 static IntRange bit_and(IntRange L, IntRange R) { 11277 unsigned Bits = std::max(L.Width, R.Width); 11278 bool NonNegative = false; 11279 if (L.NonNegative) { 11280 Bits = std::min(Bits, L.Width); 11281 NonNegative = true; 11282 } 11283 if (R.NonNegative) { 11284 Bits = std::min(Bits, R.Width); 11285 NonNegative = true; 11286 } 11287 return IntRange(Bits, NonNegative); 11288 } 11289 11290 /// Return the range of a sum of the two ranges. 11291 static IntRange sum(IntRange L, IntRange R) { 11292 bool Unsigned = L.NonNegative && R.NonNegative; 11293 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11294 Unsigned); 11295 } 11296 11297 /// Return the range of a difference of the two ranges. 11298 static IntRange difference(IntRange L, IntRange R) { 11299 // We need a 1-bit-wider range if: 11300 // 1) LHS can be negative: least value can be reduced. 11301 // 2) RHS can be negative: greatest value can be increased. 11302 bool CanWiden = !L.NonNegative || !R.NonNegative; 11303 bool Unsigned = L.NonNegative && R.Width == 0; 11304 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11305 !Unsigned, 11306 Unsigned); 11307 } 11308 11309 /// Return the range of a product of the two ranges. 11310 static IntRange product(IntRange L, IntRange R) { 11311 // If both LHS and RHS can be negative, we can form 11312 // -2^L * -2^R = 2^(L + R) 11313 // which requires L + R + 1 value bits to represent. 11314 bool CanWiden = !L.NonNegative && !R.NonNegative; 11315 bool Unsigned = L.NonNegative && R.NonNegative; 11316 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11317 Unsigned); 11318 } 11319 11320 /// Return the range of a remainder operation between the two ranges. 11321 static IntRange rem(IntRange L, IntRange R) { 11322 // The result of a remainder can't be larger than the result of 11323 // either side. The sign of the result is the sign of the LHS. 11324 bool Unsigned = L.NonNegative; 11325 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11326 Unsigned); 11327 } 11328 }; 11329 11330 } // namespace 11331 11332 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11333 unsigned MaxWidth) { 11334 if (value.isSigned() && value.isNegative()) 11335 return IntRange(value.getMinSignedBits(), false); 11336 11337 if (value.getBitWidth() > MaxWidth) 11338 value = value.trunc(MaxWidth); 11339 11340 // isNonNegative() just checks the sign bit without considering 11341 // signedness. 11342 return IntRange(value.getActiveBits(), true); 11343 } 11344 11345 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11346 unsigned MaxWidth) { 11347 if (result.isInt()) 11348 return GetValueRange(C, result.getInt(), MaxWidth); 11349 11350 if (result.isVector()) { 11351 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11352 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11353 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11354 R = IntRange::join(R, El); 11355 } 11356 return R; 11357 } 11358 11359 if (result.isComplexInt()) { 11360 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11361 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11362 return IntRange::join(R, I); 11363 } 11364 11365 // This can happen with lossless casts to intptr_t of "based" lvalues. 11366 // Assume it might use arbitrary bits. 11367 // FIXME: The only reason we need to pass the type in here is to get 11368 // the sign right on this one case. It would be nice if APValue 11369 // preserved this. 11370 assert(result.isLValue() || result.isAddrLabelDiff()); 11371 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11372 } 11373 11374 static QualType GetExprType(const Expr *E) { 11375 QualType Ty = E->getType(); 11376 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11377 Ty = AtomicRHS->getValueType(); 11378 return Ty; 11379 } 11380 11381 /// Pseudo-evaluate the given integer expression, estimating the 11382 /// range of values it might take. 11383 /// 11384 /// \param MaxWidth The width to which the value will be truncated. 11385 /// \param Approximate If \c true, return a likely range for the result: in 11386 /// particular, assume that arithmetic on narrower types doesn't leave 11387 /// those types. If \c false, return a range including all possible 11388 /// result values. 11389 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11390 bool InConstantContext, bool Approximate) { 11391 E = E->IgnoreParens(); 11392 11393 // Try a full evaluation first. 11394 Expr::EvalResult result; 11395 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11396 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11397 11398 // I think we only want to look through implicit casts here; if the 11399 // user has an explicit widening cast, we should treat the value as 11400 // being of the new, wider type. 11401 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11402 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11403 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11404 Approximate); 11405 11406 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11407 11408 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11409 CE->getCastKind() == CK_BooleanToSignedIntegral; 11410 11411 // Assume that non-integer casts can span the full range of the type. 11412 if (!isIntegerCast) 11413 return OutputTypeRange; 11414 11415 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11416 std::min(MaxWidth, OutputTypeRange.Width), 11417 InConstantContext, Approximate); 11418 11419 // Bail out if the subexpr's range is as wide as the cast type. 11420 if (SubRange.Width >= OutputTypeRange.Width) 11421 return OutputTypeRange; 11422 11423 // Otherwise, we take the smaller width, and we're non-negative if 11424 // either the output type or the subexpr is. 11425 return IntRange(SubRange.Width, 11426 SubRange.NonNegative || OutputTypeRange.NonNegative); 11427 } 11428 11429 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11430 // If we can fold the condition, just take that operand. 11431 bool CondResult; 11432 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11433 return GetExprRange(C, 11434 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11435 MaxWidth, InConstantContext, Approximate); 11436 11437 // Otherwise, conservatively merge. 11438 // GetExprRange requires an integer expression, but a throw expression 11439 // results in a void type. 11440 Expr *E = CO->getTrueExpr(); 11441 IntRange L = E->getType()->isVoidType() 11442 ? IntRange{0, true} 11443 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11444 E = CO->getFalseExpr(); 11445 IntRange R = E->getType()->isVoidType() 11446 ? IntRange{0, true} 11447 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11448 return IntRange::join(L, R); 11449 } 11450 11451 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11452 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11453 11454 switch (BO->getOpcode()) { 11455 case BO_Cmp: 11456 llvm_unreachable("builtin <=> should have class type"); 11457 11458 // Boolean-valued operations are single-bit and positive. 11459 case BO_LAnd: 11460 case BO_LOr: 11461 case BO_LT: 11462 case BO_GT: 11463 case BO_LE: 11464 case BO_GE: 11465 case BO_EQ: 11466 case BO_NE: 11467 return IntRange::forBoolType(); 11468 11469 // The type of the assignments is the type of the LHS, so the RHS 11470 // is not necessarily the same type. 11471 case BO_MulAssign: 11472 case BO_DivAssign: 11473 case BO_RemAssign: 11474 case BO_AddAssign: 11475 case BO_SubAssign: 11476 case BO_XorAssign: 11477 case BO_OrAssign: 11478 // TODO: bitfields? 11479 return IntRange::forValueOfType(C, GetExprType(E)); 11480 11481 // Simple assignments just pass through the RHS, which will have 11482 // been coerced to the LHS type. 11483 case BO_Assign: 11484 // TODO: bitfields? 11485 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11486 Approximate); 11487 11488 // Operations with opaque sources are black-listed. 11489 case BO_PtrMemD: 11490 case BO_PtrMemI: 11491 return IntRange::forValueOfType(C, GetExprType(E)); 11492 11493 // Bitwise-and uses the *infinum* of the two source ranges. 11494 case BO_And: 11495 case BO_AndAssign: 11496 Combine = IntRange::bit_and; 11497 break; 11498 11499 // Left shift gets black-listed based on a judgement call. 11500 case BO_Shl: 11501 // ...except that we want to treat '1 << (blah)' as logically 11502 // positive. It's an important idiom. 11503 if (IntegerLiteral *I 11504 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11505 if (I->getValue() == 1) { 11506 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11507 return IntRange(R.Width, /*NonNegative*/ true); 11508 } 11509 } 11510 LLVM_FALLTHROUGH; 11511 11512 case BO_ShlAssign: 11513 return IntRange::forValueOfType(C, GetExprType(E)); 11514 11515 // Right shift by a constant can narrow its left argument. 11516 case BO_Shr: 11517 case BO_ShrAssign: { 11518 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11519 Approximate); 11520 11521 // If the shift amount is a positive constant, drop the width by 11522 // that much. 11523 if (Optional<llvm::APSInt> shift = 11524 BO->getRHS()->getIntegerConstantExpr(C)) { 11525 if (shift->isNonNegative()) { 11526 unsigned zext = shift->getZExtValue(); 11527 if (zext >= L.Width) 11528 L.Width = (L.NonNegative ? 0 : 1); 11529 else 11530 L.Width -= zext; 11531 } 11532 } 11533 11534 return L; 11535 } 11536 11537 // Comma acts as its right operand. 11538 case BO_Comma: 11539 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11540 Approximate); 11541 11542 case BO_Add: 11543 if (!Approximate) 11544 Combine = IntRange::sum; 11545 break; 11546 11547 case BO_Sub: 11548 if (BO->getLHS()->getType()->isPointerType()) 11549 return IntRange::forValueOfType(C, GetExprType(E)); 11550 if (!Approximate) 11551 Combine = IntRange::difference; 11552 break; 11553 11554 case BO_Mul: 11555 if (!Approximate) 11556 Combine = IntRange::product; 11557 break; 11558 11559 // The width of a division result is mostly determined by the size 11560 // of the LHS. 11561 case BO_Div: { 11562 // Don't 'pre-truncate' the operands. 11563 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11564 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11565 Approximate); 11566 11567 // If the divisor is constant, use that. 11568 if (Optional<llvm::APSInt> divisor = 11569 BO->getRHS()->getIntegerConstantExpr(C)) { 11570 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11571 if (log2 >= L.Width) 11572 L.Width = (L.NonNegative ? 0 : 1); 11573 else 11574 L.Width = std::min(L.Width - log2, MaxWidth); 11575 return L; 11576 } 11577 11578 // Otherwise, just use the LHS's width. 11579 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11580 // could be -1. 11581 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11582 Approximate); 11583 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11584 } 11585 11586 case BO_Rem: 11587 Combine = IntRange::rem; 11588 break; 11589 11590 // The default behavior is okay for these. 11591 case BO_Xor: 11592 case BO_Or: 11593 break; 11594 } 11595 11596 // Combine the two ranges, but limit the result to the type in which we 11597 // performed the computation. 11598 QualType T = GetExprType(E); 11599 unsigned opWidth = C.getIntWidth(T); 11600 IntRange L = 11601 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11602 IntRange R = 11603 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11604 IntRange C = Combine(L, R); 11605 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11606 C.Width = std::min(C.Width, MaxWidth); 11607 return C; 11608 } 11609 11610 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11611 switch (UO->getOpcode()) { 11612 // Boolean-valued operations are white-listed. 11613 case UO_LNot: 11614 return IntRange::forBoolType(); 11615 11616 // Operations with opaque sources are black-listed. 11617 case UO_Deref: 11618 case UO_AddrOf: // should be impossible 11619 return IntRange::forValueOfType(C, GetExprType(E)); 11620 11621 default: 11622 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11623 Approximate); 11624 } 11625 } 11626 11627 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11628 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11629 Approximate); 11630 11631 if (const auto *BitField = E->getSourceBitField()) 11632 return IntRange(BitField->getBitWidthValue(C), 11633 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11634 11635 return IntRange::forValueOfType(C, GetExprType(E)); 11636 } 11637 11638 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11639 bool InConstantContext, bool Approximate) { 11640 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11641 Approximate); 11642 } 11643 11644 /// Checks whether the given value, which currently has the given 11645 /// source semantics, has the same value when coerced through the 11646 /// target semantics. 11647 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11648 const llvm::fltSemantics &Src, 11649 const llvm::fltSemantics &Tgt) { 11650 llvm::APFloat truncated = value; 11651 11652 bool ignored; 11653 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11654 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11655 11656 return truncated.bitwiseIsEqual(value); 11657 } 11658 11659 /// Checks whether the given value, which currently has the given 11660 /// source semantics, has the same value when coerced through the 11661 /// target semantics. 11662 /// 11663 /// The value might be a vector of floats (or a complex number). 11664 static bool IsSameFloatAfterCast(const APValue &value, 11665 const llvm::fltSemantics &Src, 11666 const llvm::fltSemantics &Tgt) { 11667 if (value.isFloat()) 11668 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11669 11670 if (value.isVector()) { 11671 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11672 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11673 return false; 11674 return true; 11675 } 11676 11677 assert(value.isComplexFloat()); 11678 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11679 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11680 } 11681 11682 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11683 bool IsListInit = false); 11684 11685 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11686 // Suppress cases where we are comparing against an enum constant. 11687 if (const DeclRefExpr *DR = 11688 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11689 if (isa<EnumConstantDecl>(DR->getDecl())) 11690 return true; 11691 11692 // Suppress cases where the value is expanded from a macro, unless that macro 11693 // is how a language represents a boolean literal. This is the case in both C 11694 // and Objective-C. 11695 SourceLocation BeginLoc = E->getBeginLoc(); 11696 if (BeginLoc.isMacroID()) { 11697 StringRef MacroName = Lexer::getImmediateMacroName( 11698 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11699 return MacroName != "YES" && MacroName != "NO" && 11700 MacroName != "true" && MacroName != "false"; 11701 } 11702 11703 return false; 11704 } 11705 11706 static bool isKnownToHaveUnsignedValue(Expr *E) { 11707 return E->getType()->isIntegerType() && 11708 (!E->getType()->isSignedIntegerType() || 11709 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11710 } 11711 11712 namespace { 11713 /// The promoted range of values of a type. In general this has the 11714 /// following structure: 11715 /// 11716 /// |-----------| . . . |-----------| 11717 /// ^ ^ ^ ^ 11718 /// Min HoleMin HoleMax Max 11719 /// 11720 /// ... where there is only a hole if a signed type is promoted to unsigned 11721 /// (in which case Min and Max are the smallest and largest representable 11722 /// values). 11723 struct PromotedRange { 11724 // Min, or HoleMax if there is a hole. 11725 llvm::APSInt PromotedMin; 11726 // Max, or HoleMin if there is a hole. 11727 llvm::APSInt PromotedMax; 11728 11729 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11730 if (R.Width == 0) 11731 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11732 else if (R.Width >= BitWidth && !Unsigned) { 11733 // Promotion made the type *narrower*. This happens when promoting 11734 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11735 // Treat all values of 'signed int' as being in range for now. 11736 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11737 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11738 } else { 11739 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11740 .extOrTrunc(BitWidth); 11741 PromotedMin.setIsUnsigned(Unsigned); 11742 11743 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11744 .extOrTrunc(BitWidth); 11745 PromotedMax.setIsUnsigned(Unsigned); 11746 } 11747 } 11748 11749 // Determine whether this range is contiguous (has no hole). 11750 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11751 11752 // Where a constant value is within the range. 11753 enum ComparisonResult { 11754 LT = 0x1, 11755 LE = 0x2, 11756 GT = 0x4, 11757 GE = 0x8, 11758 EQ = 0x10, 11759 NE = 0x20, 11760 InRangeFlag = 0x40, 11761 11762 Less = LE | LT | NE, 11763 Min = LE | InRangeFlag, 11764 InRange = InRangeFlag, 11765 Max = GE | InRangeFlag, 11766 Greater = GE | GT | NE, 11767 11768 OnlyValue = LE | GE | EQ | InRangeFlag, 11769 InHole = NE 11770 }; 11771 11772 ComparisonResult compare(const llvm::APSInt &Value) const { 11773 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11774 Value.isUnsigned() == PromotedMin.isUnsigned()); 11775 if (!isContiguous()) { 11776 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11777 if (Value.isMinValue()) return Min; 11778 if (Value.isMaxValue()) return Max; 11779 if (Value >= PromotedMin) return InRange; 11780 if (Value <= PromotedMax) return InRange; 11781 return InHole; 11782 } 11783 11784 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11785 case -1: return Less; 11786 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11787 case 1: 11788 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11789 case -1: return InRange; 11790 case 0: return Max; 11791 case 1: return Greater; 11792 } 11793 } 11794 11795 llvm_unreachable("impossible compare result"); 11796 } 11797 11798 static llvm::Optional<StringRef> 11799 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11800 if (Op == BO_Cmp) { 11801 ComparisonResult LTFlag = LT, GTFlag = GT; 11802 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11803 11804 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11805 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11806 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11807 return llvm::None; 11808 } 11809 11810 ComparisonResult TrueFlag, FalseFlag; 11811 if (Op == BO_EQ) { 11812 TrueFlag = EQ; 11813 FalseFlag = NE; 11814 } else if (Op == BO_NE) { 11815 TrueFlag = NE; 11816 FalseFlag = EQ; 11817 } else { 11818 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11819 TrueFlag = LT; 11820 FalseFlag = GE; 11821 } else { 11822 TrueFlag = GT; 11823 FalseFlag = LE; 11824 } 11825 if (Op == BO_GE || Op == BO_LE) 11826 std::swap(TrueFlag, FalseFlag); 11827 } 11828 if (R & TrueFlag) 11829 return StringRef("true"); 11830 if (R & FalseFlag) 11831 return StringRef("false"); 11832 return llvm::None; 11833 } 11834 }; 11835 } 11836 11837 static bool HasEnumType(Expr *E) { 11838 // Strip off implicit integral promotions. 11839 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11840 if (ICE->getCastKind() != CK_IntegralCast && 11841 ICE->getCastKind() != CK_NoOp) 11842 break; 11843 E = ICE->getSubExpr(); 11844 } 11845 11846 return E->getType()->isEnumeralType(); 11847 } 11848 11849 static int classifyConstantValue(Expr *Constant) { 11850 // The values of this enumeration are used in the diagnostics 11851 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11852 enum ConstantValueKind { 11853 Miscellaneous = 0, 11854 LiteralTrue, 11855 LiteralFalse 11856 }; 11857 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11858 return BL->getValue() ? ConstantValueKind::LiteralTrue 11859 : ConstantValueKind::LiteralFalse; 11860 return ConstantValueKind::Miscellaneous; 11861 } 11862 11863 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11864 Expr *Constant, Expr *Other, 11865 const llvm::APSInt &Value, 11866 bool RhsConstant) { 11867 if (S.inTemplateInstantiation()) 11868 return false; 11869 11870 Expr *OriginalOther = Other; 11871 11872 Constant = Constant->IgnoreParenImpCasts(); 11873 Other = Other->IgnoreParenImpCasts(); 11874 11875 // Suppress warnings on tautological comparisons between values of the same 11876 // enumeration type. There are only two ways we could warn on this: 11877 // - If the constant is outside the range of representable values of 11878 // the enumeration. In such a case, we should warn about the cast 11879 // to enumeration type, not about the comparison. 11880 // - If the constant is the maximum / minimum in-range value. For an 11881 // enumeratin type, such comparisons can be meaningful and useful. 11882 if (Constant->getType()->isEnumeralType() && 11883 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11884 return false; 11885 11886 IntRange OtherValueRange = GetExprRange( 11887 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11888 11889 QualType OtherT = Other->getType(); 11890 if (const auto *AT = OtherT->getAs<AtomicType>()) 11891 OtherT = AT->getValueType(); 11892 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11893 11894 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11895 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11896 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11897 S.NSAPIObj->isObjCBOOLType(OtherT) && 11898 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11899 11900 // Whether we're treating Other as being a bool because of the form of 11901 // expression despite it having another type (typically 'int' in C). 11902 bool OtherIsBooleanDespiteType = 11903 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11904 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11905 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11906 11907 // Check if all values in the range of possible values of this expression 11908 // lead to the same comparison outcome. 11909 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11910 Value.isUnsigned()); 11911 auto Cmp = OtherPromotedValueRange.compare(Value); 11912 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11913 if (!Result) 11914 return false; 11915 11916 // Also consider the range determined by the type alone. This allows us to 11917 // classify the warning under the proper diagnostic group. 11918 bool TautologicalTypeCompare = false; 11919 { 11920 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11921 Value.isUnsigned()); 11922 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11923 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11924 RhsConstant)) { 11925 TautologicalTypeCompare = true; 11926 Cmp = TypeCmp; 11927 Result = TypeResult; 11928 } 11929 } 11930 11931 // Don't warn if the non-constant operand actually always evaluates to the 11932 // same value. 11933 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11934 return false; 11935 11936 // Suppress the diagnostic for an in-range comparison if the constant comes 11937 // from a macro or enumerator. We don't want to diagnose 11938 // 11939 // some_long_value <= INT_MAX 11940 // 11941 // when sizeof(int) == sizeof(long). 11942 bool InRange = Cmp & PromotedRange::InRangeFlag; 11943 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11944 return false; 11945 11946 // A comparison of an unsigned bit-field against 0 is really a type problem, 11947 // even though at the type level the bit-field might promote to 'signed int'. 11948 if (Other->refersToBitField() && InRange && Value == 0 && 11949 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11950 TautologicalTypeCompare = true; 11951 11952 // If this is a comparison to an enum constant, include that 11953 // constant in the diagnostic. 11954 const EnumConstantDecl *ED = nullptr; 11955 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11956 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11957 11958 // Should be enough for uint128 (39 decimal digits) 11959 SmallString<64> PrettySourceValue; 11960 llvm::raw_svector_ostream OS(PrettySourceValue); 11961 if (ED) { 11962 OS << '\'' << *ED << "' (" << Value << ")"; 11963 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11964 Constant->IgnoreParenImpCasts())) { 11965 OS << (BL->getValue() ? "YES" : "NO"); 11966 } else { 11967 OS << Value; 11968 } 11969 11970 if (!TautologicalTypeCompare) { 11971 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11972 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11973 << E->getOpcodeStr() << OS.str() << *Result 11974 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11975 return true; 11976 } 11977 11978 if (IsObjCSignedCharBool) { 11979 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11980 S.PDiag(diag::warn_tautological_compare_objc_bool) 11981 << OS.str() << *Result); 11982 return true; 11983 } 11984 11985 // FIXME: We use a somewhat different formatting for the in-range cases and 11986 // cases involving boolean values for historical reasons. We should pick a 11987 // consistent way of presenting these diagnostics. 11988 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11989 11990 S.DiagRuntimeBehavior( 11991 E->getOperatorLoc(), E, 11992 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11993 : diag::warn_tautological_bool_compare) 11994 << OS.str() << classifyConstantValue(Constant) << OtherT 11995 << OtherIsBooleanDespiteType << *Result 11996 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11997 } else { 11998 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11999 unsigned Diag = 12000 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 12001 ? (HasEnumType(OriginalOther) 12002 ? diag::warn_unsigned_enum_always_true_comparison 12003 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 12004 : diag::warn_unsigned_always_true_comparison) 12005 : diag::warn_tautological_constant_compare; 12006 12007 S.Diag(E->getOperatorLoc(), Diag) 12008 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 12009 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12010 } 12011 12012 return true; 12013 } 12014 12015 /// Analyze the operands of the given comparison. Implements the 12016 /// fallback case from AnalyzeComparison. 12017 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 12018 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12019 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12020 } 12021 12022 /// Implements -Wsign-compare. 12023 /// 12024 /// \param E the binary operator to check for warnings 12025 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 12026 // The type the comparison is being performed in. 12027 QualType T = E->getLHS()->getType(); 12028 12029 // Only analyze comparison operators where both sides have been converted to 12030 // the same type. 12031 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 12032 return AnalyzeImpConvsInComparison(S, E); 12033 12034 // Don't analyze value-dependent comparisons directly. 12035 if (E->isValueDependent()) 12036 return AnalyzeImpConvsInComparison(S, E); 12037 12038 Expr *LHS = E->getLHS(); 12039 Expr *RHS = E->getRHS(); 12040 12041 if (T->isIntegralType(S.Context)) { 12042 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 12043 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 12044 12045 // We don't care about expressions whose result is a constant. 12046 if (RHSValue && LHSValue) 12047 return AnalyzeImpConvsInComparison(S, E); 12048 12049 // We only care about expressions where just one side is literal 12050 if ((bool)RHSValue ^ (bool)LHSValue) { 12051 // Is the constant on the RHS or LHS? 12052 const bool RhsConstant = (bool)RHSValue; 12053 Expr *Const = RhsConstant ? RHS : LHS; 12054 Expr *Other = RhsConstant ? LHS : RHS; 12055 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12056 12057 // Check whether an integer constant comparison results in a value 12058 // of 'true' or 'false'. 12059 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12060 return AnalyzeImpConvsInComparison(S, E); 12061 } 12062 } 12063 12064 if (!T->hasUnsignedIntegerRepresentation()) { 12065 // We don't do anything special if this isn't an unsigned integral 12066 // comparison: we're only interested in integral comparisons, and 12067 // signed comparisons only happen in cases we don't care to warn about. 12068 return AnalyzeImpConvsInComparison(S, E); 12069 } 12070 12071 LHS = LHS->IgnoreParenImpCasts(); 12072 RHS = RHS->IgnoreParenImpCasts(); 12073 12074 if (!S.getLangOpts().CPlusPlus) { 12075 // Avoid warning about comparison of integers with different signs when 12076 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12077 // the type of `E`. 12078 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12079 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12080 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12081 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12082 } 12083 12084 // Check to see if one of the (unmodified) operands is of different 12085 // signedness. 12086 Expr *signedOperand, *unsignedOperand; 12087 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12088 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12089 "unsigned comparison between two signed integer expressions?"); 12090 signedOperand = LHS; 12091 unsignedOperand = RHS; 12092 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12093 signedOperand = RHS; 12094 unsignedOperand = LHS; 12095 } else { 12096 return AnalyzeImpConvsInComparison(S, E); 12097 } 12098 12099 // Otherwise, calculate the effective range of the signed operand. 12100 IntRange signedRange = GetExprRange( 12101 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12102 12103 // Go ahead and analyze implicit conversions in the operands. Note 12104 // that we skip the implicit conversions on both sides. 12105 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12106 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12107 12108 // If the signed range is non-negative, -Wsign-compare won't fire. 12109 if (signedRange.NonNegative) 12110 return; 12111 12112 // For (in)equality comparisons, if the unsigned operand is a 12113 // constant which cannot collide with a overflowed signed operand, 12114 // then reinterpreting the signed operand as unsigned will not 12115 // change the result of the comparison. 12116 if (E->isEqualityOp()) { 12117 unsigned comparisonWidth = S.Context.getIntWidth(T); 12118 IntRange unsignedRange = 12119 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12120 /*Approximate*/ true); 12121 12122 // We should never be unable to prove that the unsigned operand is 12123 // non-negative. 12124 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12125 12126 if (unsignedRange.Width < comparisonWidth) 12127 return; 12128 } 12129 12130 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12131 S.PDiag(diag::warn_mixed_sign_comparison) 12132 << LHS->getType() << RHS->getType() 12133 << LHS->getSourceRange() << RHS->getSourceRange()); 12134 } 12135 12136 /// Analyzes an attempt to assign the given value to a bitfield. 12137 /// 12138 /// Returns true if there was something fishy about the attempt. 12139 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12140 SourceLocation InitLoc) { 12141 assert(Bitfield->isBitField()); 12142 if (Bitfield->isInvalidDecl()) 12143 return false; 12144 12145 // White-list bool bitfields. 12146 QualType BitfieldType = Bitfield->getType(); 12147 if (BitfieldType->isBooleanType()) 12148 return false; 12149 12150 if (BitfieldType->isEnumeralType()) { 12151 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12152 // If the underlying enum type was not explicitly specified as an unsigned 12153 // type and the enum contain only positive values, MSVC++ will cause an 12154 // inconsistency by storing this as a signed type. 12155 if (S.getLangOpts().CPlusPlus11 && 12156 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12157 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12158 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12159 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12160 << BitfieldEnumDecl; 12161 } 12162 } 12163 12164 if (Bitfield->getType()->isBooleanType()) 12165 return false; 12166 12167 // Ignore value- or type-dependent expressions. 12168 if (Bitfield->getBitWidth()->isValueDependent() || 12169 Bitfield->getBitWidth()->isTypeDependent() || 12170 Init->isValueDependent() || 12171 Init->isTypeDependent()) 12172 return false; 12173 12174 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12175 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12176 12177 Expr::EvalResult Result; 12178 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12179 Expr::SE_AllowSideEffects)) { 12180 // The RHS is not constant. If the RHS has an enum type, make sure the 12181 // bitfield is wide enough to hold all the values of the enum without 12182 // truncation. 12183 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12184 EnumDecl *ED = EnumTy->getDecl(); 12185 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12186 12187 // Enum types are implicitly signed on Windows, so check if there are any 12188 // negative enumerators to see if the enum was intended to be signed or 12189 // not. 12190 bool SignedEnum = ED->getNumNegativeBits() > 0; 12191 12192 // Check for surprising sign changes when assigning enum values to a 12193 // bitfield of different signedness. If the bitfield is signed and we 12194 // have exactly the right number of bits to store this unsigned enum, 12195 // suggest changing the enum to an unsigned type. This typically happens 12196 // on Windows where unfixed enums always use an underlying type of 'int'. 12197 unsigned DiagID = 0; 12198 if (SignedEnum && !SignedBitfield) { 12199 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12200 } else if (SignedBitfield && !SignedEnum && 12201 ED->getNumPositiveBits() == FieldWidth) { 12202 DiagID = diag::warn_signed_bitfield_enum_conversion; 12203 } 12204 12205 if (DiagID) { 12206 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12207 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12208 SourceRange TypeRange = 12209 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12210 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12211 << SignedEnum << TypeRange; 12212 } 12213 12214 // Compute the required bitwidth. If the enum has negative values, we need 12215 // one more bit than the normal number of positive bits to represent the 12216 // sign bit. 12217 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12218 ED->getNumNegativeBits()) 12219 : ED->getNumPositiveBits(); 12220 12221 // Check the bitwidth. 12222 if (BitsNeeded > FieldWidth) { 12223 Expr *WidthExpr = Bitfield->getBitWidth(); 12224 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12225 << Bitfield << ED; 12226 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12227 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12228 } 12229 } 12230 12231 return false; 12232 } 12233 12234 llvm::APSInt Value = Result.Val.getInt(); 12235 12236 unsigned OriginalWidth = Value.getBitWidth(); 12237 12238 if (!Value.isSigned() || Value.isNegative()) 12239 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12240 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12241 OriginalWidth = Value.getMinSignedBits(); 12242 12243 if (OriginalWidth <= FieldWidth) 12244 return false; 12245 12246 // Compute the value which the bitfield will contain. 12247 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12248 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12249 12250 // Check whether the stored value is equal to the original value. 12251 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12252 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12253 return false; 12254 12255 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12256 // therefore don't strictly fit into a signed bitfield of width 1. 12257 if (FieldWidth == 1 && Value == 1) 12258 return false; 12259 12260 std::string PrettyValue = toString(Value, 10); 12261 std::string PrettyTrunc = toString(TruncatedValue, 10); 12262 12263 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12264 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12265 << Init->getSourceRange(); 12266 12267 return true; 12268 } 12269 12270 /// Analyze the given simple or compound assignment for warning-worthy 12271 /// operations. 12272 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12273 // Just recurse on the LHS. 12274 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12275 12276 // We want to recurse on the RHS as normal unless we're assigning to 12277 // a bitfield. 12278 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12279 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12280 E->getOperatorLoc())) { 12281 // Recurse, ignoring any implicit conversions on the RHS. 12282 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12283 E->getOperatorLoc()); 12284 } 12285 } 12286 12287 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12288 12289 // Diagnose implicitly sequentially-consistent atomic assignment. 12290 if (E->getLHS()->getType()->isAtomicType()) 12291 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12292 } 12293 12294 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12295 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12296 SourceLocation CContext, unsigned diag, 12297 bool pruneControlFlow = false) { 12298 if (pruneControlFlow) { 12299 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12300 S.PDiag(diag) 12301 << SourceType << T << E->getSourceRange() 12302 << SourceRange(CContext)); 12303 return; 12304 } 12305 S.Diag(E->getExprLoc(), diag) 12306 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12307 } 12308 12309 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12310 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12311 SourceLocation CContext, 12312 unsigned diag, bool pruneControlFlow = false) { 12313 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12314 } 12315 12316 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12317 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12318 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12319 } 12320 12321 static void adornObjCBoolConversionDiagWithTernaryFixit( 12322 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12323 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12324 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12325 Ignored = OVE->getSourceExpr(); 12326 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12327 isa<BinaryOperator>(Ignored) || 12328 isa<CXXOperatorCallExpr>(Ignored); 12329 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12330 if (NeedsParens) 12331 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12332 << FixItHint::CreateInsertion(EndLoc, ")"); 12333 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12334 } 12335 12336 /// Diagnose an implicit cast from a floating point value to an integer value. 12337 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12338 SourceLocation CContext) { 12339 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12340 const bool PruneWarnings = S.inTemplateInstantiation(); 12341 12342 Expr *InnerE = E->IgnoreParenImpCasts(); 12343 // We also want to warn on, e.g., "int i = -1.234" 12344 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12345 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12346 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12347 12348 const bool IsLiteral = 12349 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12350 12351 llvm::APFloat Value(0.0); 12352 bool IsConstant = 12353 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12354 if (!IsConstant) { 12355 if (isObjCSignedCharBool(S, T)) { 12356 return adornObjCBoolConversionDiagWithTernaryFixit( 12357 S, E, 12358 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12359 << E->getType()); 12360 } 12361 12362 return DiagnoseImpCast(S, E, T, CContext, 12363 diag::warn_impcast_float_integer, PruneWarnings); 12364 } 12365 12366 bool isExact = false; 12367 12368 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12369 T->hasUnsignedIntegerRepresentation()); 12370 llvm::APFloat::opStatus Result = Value.convertToInteger( 12371 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12372 12373 // FIXME: Force the precision of the source value down so we don't print 12374 // digits which are usually useless (we don't really care here if we 12375 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12376 // would automatically print the shortest representation, but it's a bit 12377 // tricky to implement. 12378 SmallString<16> PrettySourceValue; 12379 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12380 precision = (precision * 59 + 195) / 196; 12381 Value.toString(PrettySourceValue, precision); 12382 12383 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12384 return adornObjCBoolConversionDiagWithTernaryFixit( 12385 S, E, 12386 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12387 << PrettySourceValue); 12388 } 12389 12390 if (Result == llvm::APFloat::opOK && isExact) { 12391 if (IsLiteral) return; 12392 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12393 PruneWarnings); 12394 } 12395 12396 // Conversion of a floating-point value to a non-bool integer where the 12397 // integral part cannot be represented by the integer type is undefined. 12398 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12399 return DiagnoseImpCast( 12400 S, E, T, CContext, 12401 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12402 : diag::warn_impcast_float_to_integer_out_of_range, 12403 PruneWarnings); 12404 12405 unsigned DiagID = 0; 12406 if (IsLiteral) { 12407 // Warn on floating point literal to integer. 12408 DiagID = diag::warn_impcast_literal_float_to_integer; 12409 } else if (IntegerValue == 0) { 12410 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12411 return DiagnoseImpCast(S, E, T, CContext, 12412 diag::warn_impcast_float_integer, PruneWarnings); 12413 } 12414 // Warn on non-zero to zero conversion. 12415 DiagID = diag::warn_impcast_float_to_integer_zero; 12416 } else { 12417 if (IntegerValue.isUnsigned()) { 12418 if (!IntegerValue.isMaxValue()) { 12419 return DiagnoseImpCast(S, E, T, CContext, 12420 diag::warn_impcast_float_integer, PruneWarnings); 12421 } 12422 } else { // IntegerValue.isSigned() 12423 if (!IntegerValue.isMaxSignedValue() && 12424 !IntegerValue.isMinSignedValue()) { 12425 return DiagnoseImpCast(S, E, T, CContext, 12426 diag::warn_impcast_float_integer, PruneWarnings); 12427 } 12428 } 12429 // Warn on evaluatable floating point expression to integer conversion. 12430 DiagID = diag::warn_impcast_float_to_integer; 12431 } 12432 12433 SmallString<16> PrettyTargetValue; 12434 if (IsBool) 12435 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12436 else 12437 IntegerValue.toString(PrettyTargetValue); 12438 12439 if (PruneWarnings) { 12440 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12441 S.PDiag(DiagID) 12442 << E->getType() << T.getUnqualifiedType() 12443 << PrettySourceValue << PrettyTargetValue 12444 << E->getSourceRange() << SourceRange(CContext)); 12445 } else { 12446 S.Diag(E->getExprLoc(), DiagID) 12447 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12448 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12449 } 12450 } 12451 12452 /// Analyze the given compound assignment for the possible losing of 12453 /// floating-point precision. 12454 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12455 assert(isa<CompoundAssignOperator>(E) && 12456 "Must be compound assignment operation"); 12457 // Recurse on the LHS and RHS in here 12458 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12459 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12460 12461 if (E->getLHS()->getType()->isAtomicType()) 12462 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12463 12464 // Now check the outermost expression 12465 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12466 const auto *RBT = cast<CompoundAssignOperator>(E) 12467 ->getComputationResultType() 12468 ->getAs<BuiltinType>(); 12469 12470 // The below checks assume source is floating point. 12471 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12472 12473 // If source is floating point but target is an integer. 12474 if (ResultBT->isInteger()) 12475 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12476 E->getExprLoc(), diag::warn_impcast_float_integer); 12477 12478 if (!ResultBT->isFloatingPoint()) 12479 return; 12480 12481 // If both source and target are floating points, warn about losing precision. 12482 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12483 QualType(ResultBT, 0), QualType(RBT, 0)); 12484 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12485 // warn about dropping FP rank. 12486 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12487 diag::warn_impcast_float_result_precision); 12488 } 12489 12490 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12491 IntRange Range) { 12492 if (!Range.Width) return "0"; 12493 12494 llvm::APSInt ValueInRange = Value; 12495 ValueInRange.setIsSigned(!Range.NonNegative); 12496 ValueInRange = ValueInRange.trunc(Range.Width); 12497 return toString(ValueInRange, 10); 12498 } 12499 12500 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12501 if (!isa<ImplicitCastExpr>(Ex)) 12502 return false; 12503 12504 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12505 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12506 const Type *Source = 12507 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12508 if (Target->isDependentType()) 12509 return false; 12510 12511 const BuiltinType *FloatCandidateBT = 12512 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12513 const Type *BoolCandidateType = ToBool ? Target : Source; 12514 12515 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12516 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12517 } 12518 12519 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12520 SourceLocation CC) { 12521 unsigned NumArgs = TheCall->getNumArgs(); 12522 for (unsigned i = 0; i < NumArgs; ++i) { 12523 Expr *CurrA = TheCall->getArg(i); 12524 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12525 continue; 12526 12527 bool IsSwapped = ((i > 0) && 12528 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12529 IsSwapped |= ((i < (NumArgs - 1)) && 12530 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12531 if (IsSwapped) { 12532 // Warn on this floating-point to bool conversion. 12533 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12534 CurrA->getType(), CC, 12535 diag::warn_impcast_floating_point_to_bool); 12536 } 12537 } 12538 } 12539 12540 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12541 SourceLocation CC) { 12542 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12543 E->getExprLoc())) 12544 return; 12545 12546 // Don't warn on functions which have return type nullptr_t. 12547 if (isa<CallExpr>(E)) 12548 return; 12549 12550 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12551 const Expr::NullPointerConstantKind NullKind = 12552 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12553 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12554 return; 12555 12556 // Return if target type is a safe conversion. 12557 if (T->isAnyPointerType() || T->isBlockPointerType() || 12558 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12559 return; 12560 12561 SourceLocation Loc = E->getSourceRange().getBegin(); 12562 12563 // Venture through the macro stacks to get to the source of macro arguments. 12564 // The new location is a better location than the complete location that was 12565 // passed in. 12566 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12567 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12568 12569 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12570 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12571 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12572 Loc, S.SourceMgr, S.getLangOpts()); 12573 if (MacroName == "NULL") 12574 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12575 } 12576 12577 // Only warn if the null and context location are in the same macro expansion. 12578 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12579 return; 12580 12581 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12582 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12583 << FixItHint::CreateReplacement(Loc, 12584 S.getFixItZeroLiteralForType(T, Loc)); 12585 } 12586 12587 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12588 ObjCArrayLiteral *ArrayLiteral); 12589 12590 static void 12591 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12592 ObjCDictionaryLiteral *DictionaryLiteral); 12593 12594 /// Check a single element within a collection literal against the 12595 /// target element type. 12596 static void checkObjCCollectionLiteralElement(Sema &S, 12597 QualType TargetElementType, 12598 Expr *Element, 12599 unsigned ElementKind) { 12600 // Skip a bitcast to 'id' or qualified 'id'. 12601 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12602 if (ICE->getCastKind() == CK_BitCast && 12603 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12604 Element = ICE->getSubExpr(); 12605 } 12606 12607 QualType ElementType = Element->getType(); 12608 ExprResult ElementResult(Element); 12609 if (ElementType->getAs<ObjCObjectPointerType>() && 12610 S.CheckSingleAssignmentConstraints(TargetElementType, 12611 ElementResult, 12612 false, false) 12613 != Sema::Compatible) { 12614 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12615 << ElementType << ElementKind << TargetElementType 12616 << Element->getSourceRange(); 12617 } 12618 12619 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12620 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12621 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12622 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12623 } 12624 12625 /// Check an Objective-C array literal being converted to the given 12626 /// target type. 12627 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12628 ObjCArrayLiteral *ArrayLiteral) { 12629 if (!S.NSArrayDecl) 12630 return; 12631 12632 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12633 if (!TargetObjCPtr) 12634 return; 12635 12636 if (TargetObjCPtr->isUnspecialized() || 12637 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12638 != S.NSArrayDecl->getCanonicalDecl()) 12639 return; 12640 12641 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12642 if (TypeArgs.size() != 1) 12643 return; 12644 12645 QualType TargetElementType = TypeArgs[0]; 12646 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12647 checkObjCCollectionLiteralElement(S, TargetElementType, 12648 ArrayLiteral->getElement(I), 12649 0); 12650 } 12651 } 12652 12653 /// Check an Objective-C dictionary literal being converted to the given 12654 /// target type. 12655 static void 12656 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12657 ObjCDictionaryLiteral *DictionaryLiteral) { 12658 if (!S.NSDictionaryDecl) 12659 return; 12660 12661 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12662 if (!TargetObjCPtr) 12663 return; 12664 12665 if (TargetObjCPtr->isUnspecialized() || 12666 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12667 != S.NSDictionaryDecl->getCanonicalDecl()) 12668 return; 12669 12670 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12671 if (TypeArgs.size() != 2) 12672 return; 12673 12674 QualType TargetKeyType = TypeArgs[0]; 12675 QualType TargetObjectType = TypeArgs[1]; 12676 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12677 auto Element = DictionaryLiteral->getKeyValueElement(I); 12678 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12679 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12680 } 12681 } 12682 12683 // Helper function to filter out cases for constant width constant conversion. 12684 // Don't warn on char array initialization or for non-decimal values. 12685 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12686 SourceLocation CC) { 12687 // If initializing from a constant, and the constant starts with '0', 12688 // then it is a binary, octal, or hexadecimal. Allow these constants 12689 // to fill all the bits, even if there is a sign change. 12690 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12691 const char FirstLiteralCharacter = 12692 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12693 if (FirstLiteralCharacter == '0') 12694 return false; 12695 } 12696 12697 // If the CC location points to a '{', and the type is char, then assume 12698 // assume it is an array initialization. 12699 if (CC.isValid() && T->isCharType()) { 12700 const char FirstContextCharacter = 12701 S.getSourceManager().getCharacterData(CC)[0]; 12702 if (FirstContextCharacter == '{') 12703 return false; 12704 } 12705 12706 return true; 12707 } 12708 12709 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12710 const auto *IL = dyn_cast<IntegerLiteral>(E); 12711 if (!IL) { 12712 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12713 if (UO->getOpcode() == UO_Minus) 12714 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12715 } 12716 } 12717 12718 return IL; 12719 } 12720 12721 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12722 E = E->IgnoreParenImpCasts(); 12723 SourceLocation ExprLoc = E->getExprLoc(); 12724 12725 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12726 BinaryOperator::Opcode Opc = BO->getOpcode(); 12727 Expr::EvalResult Result; 12728 // Do not diagnose unsigned shifts. 12729 if (Opc == BO_Shl) { 12730 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12731 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12732 if (LHS && LHS->getValue() == 0) 12733 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12734 else if (!E->isValueDependent() && LHS && RHS && 12735 RHS->getValue().isNonNegative() && 12736 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12737 S.Diag(ExprLoc, diag::warn_left_shift_always) 12738 << (Result.Val.getInt() != 0); 12739 else if (E->getType()->isSignedIntegerType()) 12740 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12741 } 12742 } 12743 12744 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12745 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12746 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12747 if (!LHS || !RHS) 12748 return; 12749 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12750 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12751 // Do not diagnose common idioms. 12752 return; 12753 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12754 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12755 } 12756 } 12757 12758 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12759 SourceLocation CC, 12760 bool *ICContext = nullptr, 12761 bool IsListInit = false) { 12762 if (E->isTypeDependent() || E->isValueDependent()) return; 12763 12764 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12765 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12766 if (Source == Target) return; 12767 if (Target->isDependentType()) return; 12768 12769 // If the conversion context location is invalid don't complain. We also 12770 // don't want to emit a warning if the issue occurs from the expansion of 12771 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12772 // delay this check as long as possible. Once we detect we are in that 12773 // scenario, we just return. 12774 if (CC.isInvalid()) 12775 return; 12776 12777 if (Source->isAtomicType()) 12778 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12779 12780 // Diagnose implicit casts to bool. 12781 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12782 if (isa<StringLiteral>(E)) 12783 // Warn on string literal to bool. Checks for string literals in logical 12784 // and expressions, for instance, assert(0 && "error here"), are 12785 // prevented by a check in AnalyzeImplicitConversions(). 12786 return DiagnoseImpCast(S, E, T, CC, 12787 diag::warn_impcast_string_literal_to_bool); 12788 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12789 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12790 // This covers the literal expressions that evaluate to Objective-C 12791 // objects. 12792 return DiagnoseImpCast(S, E, T, CC, 12793 diag::warn_impcast_objective_c_literal_to_bool); 12794 } 12795 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12796 // Warn on pointer to bool conversion that is always true. 12797 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12798 SourceRange(CC)); 12799 } 12800 } 12801 12802 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12803 // is a typedef for signed char (macOS), then that constant value has to be 1 12804 // or 0. 12805 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12806 Expr::EvalResult Result; 12807 if (E->EvaluateAsInt(Result, S.getASTContext(), 12808 Expr::SE_AllowSideEffects)) { 12809 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12810 adornObjCBoolConversionDiagWithTernaryFixit( 12811 S, E, 12812 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12813 << toString(Result.Val.getInt(), 10)); 12814 } 12815 return; 12816 } 12817 } 12818 12819 // Check implicit casts from Objective-C collection literals to specialized 12820 // collection types, e.g., NSArray<NSString *> *. 12821 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12822 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12823 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12824 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12825 12826 // Strip vector types. 12827 if (isa<VectorType>(Source)) { 12828 if (Target->isVLSTBuiltinType() && 12829 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12830 QualType(Source, 0)) || 12831 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12832 QualType(Source, 0)))) 12833 return; 12834 12835 if (!isa<VectorType>(Target)) { 12836 if (S.SourceMgr.isInSystemMacro(CC)) 12837 return; 12838 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12839 } 12840 12841 // If the vector cast is cast between two vectors of the same size, it is 12842 // a bitcast, not a conversion. 12843 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12844 return; 12845 12846 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12847 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12848 } 12849 if (auto VecTy = dyn_cast<VectorType>(Target)) 12850 Target = VecTy->getElementType().getTypePtr(); 12851 12852 // Strip complex types. 12853 if (isa<ComplexType>(Source)) { 12854 if (!isa<ComplexType>(Target)) { 12855 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12856 return; 12857 12858 return DiagnoseImpCast(S, E, T, CC, 12859 S.getLangOpts().CPlusPlus 12860 ? diag::err_impcast_complex_scalar 12861 : diag::warn_impcast_complex_scalar); 12862 } 12863 12864 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12865 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12866 } 12867 12868 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12869 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12870 12871 // If the source is floating point... 12872 if (SourceBT && SourceBT->isFloatingPoint()) { 12873 // ...and the target is floating point... 12874 if (TargetBT && TargetBT->isFloatingPoint()) { 12875 // ...then warn if we're dropping FP rank. 12876 12877 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12878 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12879 if (Order > 0) { 12880 // Don't warn about float constants that are precisely 12881 // representable in the target type. 12882 Expr::EvalResult result; 12883 if (E->EvaluateAsRValue(result, S.Context)) { 12884 // Value might be a float, a float vector, or a float complex. 12885 if (IsSameFloatAfterCast(result.Val, 12886 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12887 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12888 return; 12889 } 12890 12891 if (S.SourceMgr.isInSystemMacro(CC)) 12892 return; 12893 12894 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12895 } 12896 // ... or possibly if we're increasing rank, too 12897 else if (Order < 0) { 12898 if (S.SourceMgr.isInSystemMacro(CC)) 12899 return; 12900 12901 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12902 } 12903 return; 12904 } 12905 12906 // If the target is integral, always warn. 12907 if (TargetBT && TargetBT->isInteger()) { 12908 if (S.SourceMgr.isInSystemMacro(CC)) 12909 return; 12910 12911 DiagnoseFloatingImpCast(S, E, T, CC); 12912 } 12913 12914 // Detect the case where a call result is converted from floating-point to 12915 // to bool, and the final argument to the call is converted from bool, to 12916 // discover this typo: 12917 // 12918 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12919 // 12920 // FIXME: This is an incredibly special case; is there some more general 12921 // way to detect this class of misplaced-parentheses bug? 12922 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12923 // Check last argument of function call to see if it is an 12924 // implicit cast from a type matching the type the result 12925 // is being cast to. 12926 CallExpr *CEx = cast<CallExpr>(E); 12927 if (unsigned NumArgs = CEx->getNumArgs()) { 12928 Expr *LastA = CEx->getArg(NumArgs - 1); 12929 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12930 if (isa<ImplicitCastExpr>(LastA) && 12931 InnerE->getType()->isBooleanType()) { 12932 // Warn on this floating-point to bool conversion 12933 DiagnoseImpCast(S, E, T, CC, 12934 diag::warn_impcast_floating_point_to_bool); 12935 } 12936 } 12937 } 12938 return; 12939 } 12940 12941 // Valid casts involving fixed point types should be accounted for here. 12942 if (Source->isFixedPointType()) { 12943 if (Target->isUnsaturatedFixedPointType()) { 12944 Expr::EvalResult Result; 12945 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12946 S.isConstantEvaluated())) { 12947 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12948 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12949 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12950 if (Value > MaxVal || Value < MinVal) { 12951 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12952 S.PDiag(diag::warn_impcast_fixed_point_range) 12953 << Value.toString() << T 12954 << E->getSourceRange() 12955 << clang::SourceRange(CC)); 12956 return; 12957 } 12958 } 12959 } else if (Target->isIntegerType()) { 12960 Expr::EvalResult Result; 12961 if (!S.isConstantEvaluated() && 12962 E->EvaluateAsFixedPoint(Result, S.Context, 12963 Expr::SE_AllowSideEffects)) { 12964 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12965 12966 bool Overflowed; 12967 llvm::APSInt IntResult = FXResult.convertToInt( 12968 S.Context.getIntWidth(T), 12969 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12970 12971 if (Overflowed) { 12972 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12973 S.PDiag(diag::warn_impcast_fixed_point_range) 12974 << FXResult.toString() << T 12975 << E->getSourceRange() 12976 << clang::SourceRange(CC)); 12977 return; 12978 } 12979 } 12980 } 12981 } else if (Target->isUnsaturatedFixedPointType()) { 12982 if (Source->isIntegerType()) { 12983 Expr::EvalResult Result; 12984 if (!S.isConstantEvaluated() && 12985 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12986 llvm::APSInt Value = Result.Val.getInt(); 12987 12988 bool Overflowed; 12989 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12990 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12991 12992 if (Overflowed) { 12993 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12994 S.PDiag(diag::warn_impcast_fixed_point_range) 12995 << toString(Value, /*Radix=*/10) << T 12996 << E->getSourceRange() 12997 << clang::SourceRange(CC)); 12998 return; 12999 } 13000 } 13001 } 13002 } 13003 13004 // If we are casting an integer type to a floating point type without 13005 // initialization-list syntax, we might lose accuracy if the floating 13006 // point type has a narrower significand than the integer type. 13007 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 13008 TargetBT->isFloatingType() && !IsListInit) { 13009 // Determine the number of precision bits in the source integer type. 13010 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 13011 /*Approximate*/ true); 13012 unsigned int SourcePrecision = SourceRange.Width; 13013 13014 // Determine the number of precision bits in the 13015 // target floating point type. 13016 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 13017 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13018 13019 if (SourcePrecision > 0 && TargetPrecision > 0 && 13020 SourcePrecision > TargetPrecision) { 13021 13022 if (Optional<llvm::APSInt> SourceInt = 13023 E->getIntegerConstantExpr(S.Context)) { 13024 // If the source integer is a constant, convert it to the target 13025 // floating point type. Issue a warning if the value changes 13026 // during the whole conversion. 13027 llvm::APFloat TargetFloatValue( 13028 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13029 llvm::APFloat::opStatus ConversionStatus = 13030 TargetFloatValue.convertFromAPInt( 13031 *SourceInt, SourceBT->isSignedInteger(), 13032 llvm::APFloat::rmNearestTiesToEven); 13033 13034 if (ConversionStatus != llvm::APFloat::opOK) { 13035 SmallString<32> PrettySourceValue; 13036 SourceInt->toString(PrettySourceValue, 10); 13037 SmallString<32> PrettyTargetValue; 13038 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 13039 13040 S.DiagRuntimeBehavior( 13041 E->getExprLoc(), E, 13042 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 13043 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13044 << E->getSourceRange() << clang::SourceRange(CC)); 13045 } 13046 } else { 13047 // Otherwise, the implicit conversion may lose precision. 13048 DiagnoseImpCast(S, E, T, CC, 13049 diag::warn_impcast_integer_float_precision); 13050 } 13051 } 13052 } 13053 13054 DiagnoseNullConversion(S, E, T, CC); 13055 13056 S.DiscardMisalignedMemberAddress(Target, E); 13057 13058 if (Target->isBooleanType()) 13059 DiagnoseIntInBoolContext(S, E); 13060 13061 if (!Source->isIntegerType() || !Target->isIntegerType()) 13062 return; 13063 13064 // TODO: remove this early return once the false positives for constant->bool 13065 // in templates, macros, etc, are reduced or removed. 13066 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13067 return; 13068 13069 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13070 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13071 return adornObjCBoolConversionDiagWithTernaryFixit( 13072 S, E, 13073 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13074 << E->getType()); 13075 } 13076 13077 IntRange SourceTypeRange = 13078 IntRange::forTargetOfCanonicalType(S.Context, Source); 13079 IntRange LikelySourceRange = 13080 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13081 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13082 13083 if (LikelySourceRange.Width > TargetRange.Width) { 13084 // If the source is a constant, use a default-on diagnostic. 13085 // TODO: this should happen for bitfield stores, too. 13086 Expr::EvalResult Result; 13087 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13088 S.isConstantEvaluated())) { 13089 llvm::APSInt Value(32); 13090 Value = Result.Val.getInt(); 13091 13092 if (S.SourceMgr.isInSystemMacro(CC)) 13093 return; 13094 13095 std::string PrettySourceValue = toString(Value, 10); 13096 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13097 13098 S.DiagRuntimeBehavior( 13099 E->getExprLoc(), E, 13100 S.PDiag(diag::warn_impcast_integer_precision_constant) 13101 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13102 << E->getSourceRange() << SourceRange(CC)); 13103 return; 13104 } 13105 13106 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13107 if (S.SourceMgr.isInSystemMacro(CC)) 13108 return; 13109 13110 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13111 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13112 /* pruneControlFlow */ true); 13113 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13114 } 13115 13116 if (TargetRange.Width > SourceTypeRange.Width) { 13117 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13118 if (UO->getOpcode() == UO_Minus) 13119 if (Source->isUnsignedIntegerType()) { 13120 if (Target->isUnsignedIntegerType()) 13121 return DiagnoseImpCast(S, E, T, CC, 13122 diag::warn_impcast_high_order_zero_bits); 13123 if (Target->isSignedIntegerType()) 13124 return DiagnoseImpCast(S, E, T, CC, 13125 diag::warn_impcast_nonnegative_result); 13126 } 13127 } 13128 13129 if (TargetRange.Width == LikelySourceRange.Width && 13130 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13131 Source->isSignedIntegerType()) { 13132 // Warn when doing a signed to signed conversion, warn if the positive 13133 // source value is exactly the width of the target type, which will 13134 // cause a negative value to be stored. 13135 13136 Expr::EvalResult Result; 13137 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13138 !S.SourceMgr.isInSystemMacro(CC)) { 13139 llvm::APSInt Value = Result.Val.getInt(); 13140 if (isSameWidthConstantConversion(S, E, T, CC)) { 13141 std::string PrettySourceValue = toString(Value, 10); 13142 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13143 13144 S.DiagRuntimeBehavior( 13145 E->getExprLoc(), E, 13146 S.PDiag(diag::warn_impcast_integer_precision_constant) 13147 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13148 << E->getSourceRange() << SourceRange(CC)); 13149 return; 13150 } 13151 } 13152 13153 // Fall through for non-constants to give a sign conversion warning. 13154 } 13155 13156 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13157 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13158 LikelySourceRange.Width == TargetRange.Width)) { 13159 if (S.SourceMgr.isInSystemMacro(CC)) 13160 return; 13161 13162 unsigned DiagID = diag::warn_impcast_integer_sign; 13163 13164 // Traditionally, gcc has warned about this under -Wsign-compare. 13165 // We also want to warn about it in -Wconversion. 13166 // So if -Wconversion is off, use a completely identical diagnostic 13167 // in the sign-compare group. 13168 // The conditional-checking code will 13169 if (ICContext) { 13170 DiagID = diag::warn_impcast_integer_sign_conditional; 13171 *ICContext = true; 13172 } 13173 13174 return DiagnoseImpCast(S, E, T, CC, DiagID); 13175 } 13176 13177 // Diagnose conversions between different enumeration types. 13178 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13179 // type, to give us better diagnostics. 13180 QualType SourceType = E->getType(); 13181 if (!S.getLangOpts().CPlusPlus) { 13182 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13183 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13184 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13185 SourceType = S.Context.getTypeDeclType(Enum); 13186 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13187 } 13188 } 13189 13190 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13191 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13192 if (SourceEnum->getDecl()->hasNameForLinkage() && 13193 TargetEnum->getDecl()->hasNameForLinkage() && 13194 SourceEnum != TargetEnum) { 13195 if (S.SourceMgr.isInSystemMacro(CC)) 13196 return; 13197 13198 return DiagnoseImpCast(S, E, SourceType, T, CC, 13199 diag::warn_impcast_different_enum_types); 13200 } 13201 } 13202 13203 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13204 SourceLocation CC, QualType T); 13205 13206 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13207 SourceLocation CC, bool &ICContext) { 13208 E = E->IgnoreParenImpCasts(); 13209 13210 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13211 return CheckConditionalOperator(S, CO, CC, T); 13212 13213 AnalyzeImplicitConversions(S, E, CC); 13214 if (E->getType() != T) 13215 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13216 } 13217 13218 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13219 SourceLocation CC, QualType T) { 13220 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13221 13222 Expr *TrueExpr = E->getTrueExpr(); 13223 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13224 TrueExpr = BCO->getCommon(); 13225 13226 bool Suspicious = false; 13227 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13228 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13229 13230 if (T->isBooleanType()) 13231 DiagnoseIntInBoolContext(S, E); 13232 13233 // If -Wconversion would have warned about either of the candidates 13234 // for a signedness conversion to the context type... 13235 if (!Suspicious) return; 13236 13237 // ...but it's currently ignored... 13238 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13239 return; 13240 13241 // ...then check whether it would have warned about either of the 13242 // candidates for a signedness conversion to the condition type. 13243 if (E->getType() == T) return; 13244 13245 Suspicious = false; 13246 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13247 E->getType(), CC, &Suspicious); 13248 if (!Suspicious) 13249 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13250 E->getType(), CC, &Suspicious); 13251 } 13252 13253 /// Check conversion of given expression to boolean. 13254 /// Input argument E is a logical expression. 13255 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13256 if (S.getLangOpts().Bool) 13257 return; 13258 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13259 return; 13260 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13261 } 13262 13263 namespace { 13264 struct AnalyzeImplicitConversionsWorkItem { 13265 Expr *E; 13266 SourceLocation CC; 13267 bool IsListInit; 13268 }; 13269 } 13270 13271 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13272 /// that should be visited are added to WorkList. 13273 static void AnalyzeImplicitConversions( 13274 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13275 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13276 Expr *OrigE = Item.E; 13277 SourceLocation CC = Item.CC; 13278 13279 QualType T = OrigE->getType(); 13280 Expr *E = OrigE->IgnoreParenImpCasts(); 13281 13282 // Propagate whether we are in a C++ list initialization expression. 13283 // If so, we do not issue warnings for implicit int-float conversion 13284 // precision loss, because C++11 narrowing already handles it. 13285 bool IsListInit = Item.IsListInit || 13286 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13287 13288 if (E->isTypeDependent() || E->isValueDependent()) 13289 return; 13290 13291 Expr *SourceExpr = E; 13292 // Examine, but don't traverse into the source expression of an 13293 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13294 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13295 // evaluate it in the context of checking the specific conversion to T though. 13296 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13297 if (auto *Src = OVE->getSourceExpr()) 13298 SourceExpr = Src; 13299 13300 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13301 if (UO->getOpcode() == UO_Not && 13302 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13303 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13304 << OrigE->getSourceRange() << T->isBooleanType() 13305 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13306 13307 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13308 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13309 BO->getLHS()->isKnownToHaveBooleanValue() && 13310 BO->getRHS()->isKnownToHaveBooleanValue() && 13311 BO->getLHS()->HasSideEffects(S.Context) && 13312 BO->getRHS()->HasSideEffects(S.Context)) { 13313 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13314 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13315 << FixItHint::CreateReplacement( 13316 BO->getOperatorLoc(), 13317 (BO->getOpcode() == BO_And ? "&&" : "||")); 13318 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13319 } 13320 13321 // For conditional operators, we analyze the arguments as if they 13322 // were being fed directly into the output. 13323 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13324 CheckConditionalOperator(S, CO, CC, T); 13325 return; 13326 } 13327 13328 // Check implicit argument conversions for function calls. 13329 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13330 CheckImplicitArgumentConversions(S, Call, CC); 13331 13332 // Go ahead and check any implicit conversions we might have skipped. 13333 // The non-canonical typecheck is just an optimization; 13334 // CheckImplicitConversion will filter out dead implicit conversions. 13335 if (SourceExpr->getType() != T) 13336 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13337 13338 // Now continue drilling into this expression. 13339 13340 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13341 // The bound subexpressions in a PseudoObjectExpr are not reachable 13342 // as transitive children. 13343 // FIXME: Use a more uniform representation for this. 13344 for (auto *SE : POE->semantics()) 13345 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13346 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13347 } 13348 13349 // Skip past explicit casts. 13350 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13351 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13352 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13353 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13354 WorkList.push_back({E, CC, IsListInit}); 13355 return; 13356 } 13357 13358 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13359 // Do a somewhat different check with comparison operators. 13360 if (BO->isComparisonOp()) 13361 return AnalyzeComparison(S, BO); 13362 13363 // And with simple assignments. 13364 if (BO->getOpcode() == BO_Assign) 13365 return AnalyzeAssignment(S, BO); 13366 // And with compound assignments. 13367 if (BO->isAssignmentOp()) 13368 return AnalyzeCompoundAssignment(S, BO); 13369 } 13370 13371 // These break the otherwise-useful invariant below. Fortunately, 13372 // we don't really need to recurse into them, because any internal 13373 // expressions should have been analyzed already when they were 13374 // built into statements. 13375 if (isa<StmtExpr>(E)) return; 13376 13377 // Don't descend into unevaluated contexts. 13378 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13379 13380 // Now just recurse over the expression's children. 13381 CC = E->getExprLoc(); 13382 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13383 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13384 for (Stmt *SubStmt : E->children()) { 13385 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13386 if (!ChildExpr) 13387 continue; 13388 13389 if (IsLogicalAndOperator && 13390 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13391 // Ignore checking string literals that are in logical and operators. 13392 // This is a common pattern for asserts. 13393 continue; 13394 WorkList.push_back({ChildExpr, CC, IsListInit}); 13395 } 13396 13397 if (BO && BO->isLogicalOp()) { 13398 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13399 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13400 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13401 13402 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13403 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13404 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13405 } 13406 13407 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13408 if (U->getOpcode() == UO_LNot) { 13409 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13410 } else if (U->getOpcode() != UO_AddrOf) { 13411 if (U->getSubExpr()->getType()->isAtomicType()) 13412 S.Diag(U->getSubExpr()->getBeginLoc(), 13413 diag::warn_atomic_implicit_seq_cst); 13414 } 13415 } 13416 } 13417 13418 /// AnalyzeImplicitConversions - Find and report any interesting 13419 /// implicit conversions in the given expression. There are a couple 13420 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13421 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13422 bool IsListInit/*= false*/) { 13423 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13424 WorkList.push_back({OrigE, CC, IsListInit}); 13425 while (!WorkList.empty()) 13426 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13427 } 13428 13429 /// Diagnose integer type and any valid implicit conversion to it. 13430 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13431 // Taking into account implicit conversions, 13432 // allow any integer. 13433 if (!E->getType()->isIntegerType()) { 13434 S.Diag(E->getBeginLoc(), 13435 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13436 return true; 13437 } 13438 // Potentially emit standard warnings for implicit conversions if enabled 13439 // using -Wconversion. 13440 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13441 return false; 13442 } 13443 13444 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13445 // Returns true when emitting a warning about taking the address of a reference. 13446 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13447 const PartialDiagnostic &PD) { 13448 E = E->IgnoreParenImpCasts(); 13449 13450 const FunctionDecl *FD = nullptr; 13451 13452 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13453 if (!DRE->getDecl()->getType()->isReferenceType()) 13454 return false; 13455 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13456 if (!M->getMemberDecl()->getType()->isReferenceType()) 13457 return false; 13458 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13459 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13460 return false; 13461 FD = Call->getDirectCallee(); 13462 } else { 13463 return false; 13464 } 13465 13466 SemaRef.Diag(E->getExprLoc(), PD); 13467 13468 // If possible, point to location of function. 13469 if (FD) { 13470 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13471 } 13472 13473 return true; 13474 } 13475 13476 // Returns true if the SourceLocation is expanded from any macro body. 13477 // Returns false if the SourceLocation is invalid, is from not in a macro 13478 // expansion, or is from expanded from a top-level macro argument. 13479 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13480 if (Loc.isInvalid()) 13481 return false; 13482 13483 while (Loc.isMacroID()) { 13484 if (SM.isMacroBodyExpansion(Loc)) 13485 return true; 13486 Loc = SM.getImmediateMacroCallerLoc(Loc); 13487 } 13488 13489 return false; 13490 } 13491 13492 /// Diagnose pointers that are always non-null. 13493 /// \param E the expression containing the pointer 13494 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13495 /// compared to a null pointer 13496 /// \param IsEqual True when the comparison is equal to a null pointer 13497 /// \param Range Extra SourceRange to highlight in the diagnostic 13498 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13499 Expr::NullPointerConstantKind NullKind, 13500 bool IsEqual, SourceRange Range) { 13501 if (!E) 13502 return; 13503 13504 // Don't warn inside macros. 13505 if (E->getExprLoc().isMacroID()) { 13506 const SourceManager &SM = getSourceManager(); 13507 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13508 IsInAnyMacroBody(SM, Range.getBegin())) 13509 return; 13510 } 13511 E = E->IgnoreImpCasts(); 13512 13513 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13514 13515 if (isa<CXXThisExpr>(E)) { 13516 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13517 : diag::warn_this_bool_conversion; 13518 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13519 return; 13520 } 13521 13522 bool IsAddressOf = false; 13523 13524 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13525 if (UO->getOpcode() != UO_AddrOf) 13526 return; 13527 IsAddressOf = true; 13528 E = UO->getSubExpr(); 13529 } 13530 13531 if (IsAddressOf) { 13532 unsigned DiagID = IsCompare 13533 ? diag::warn_address_of_reference_null_compare 13534 : diag::warn_address_of_reference_bool_conversion; 13535 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13536 << IsEqual; 13537 if (CheckForReference(*this, E, PD)) { 13538 return; 13539 } 13540 } 13541 13542 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13543 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13544 std::string Str; 13545 llvm::raw_string_ostream S(Str); 13546 E->printPretty(S, nullptr, getPrintingPolicy()); 13547 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13548 : diag::warn_cast_nonnull_to_bool; 13549 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13550 << E->getSourceRange() << Range << IsEqual; 13551 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13552 }; 13553 13554 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13555 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13556 if (auto *Callee = Call->getDirectCallee()) { 13557 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13558 ComplainAboutNonnullParamOrCall(A); 13559 return; 13560 } 13561 } 13562 } 13563 13564 // Expect to find a single Decl. Skip anything more complicated. 13565 ValueDecl *D = nullptr; 13566 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13567 D = R->getDecl(); 13568 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13569 D = M->getMemberDecl(); 13570 } 13571 13572 // Weak Decls can be null. 13573 if (!D || D->isWeak()) 13574 return; 13575 13576 // Check for parameter decl with nonnull attribute 13577 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13578 if (getCurFunction() && 13579 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13580 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13581 ComplainAboutNonnullParamOrCall(A); 13582 return; 13583 } 13584 13585 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13586 // Skip function template not specialized yet. 13587 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13588 return; 13589 auto ParamIter = llvm::find(FD->parameters(), PV); 13590 assert(ParamIter != FD->param_end()); 13591 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13592 13593 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13594 if (!NonNull->args_size()) { 13595 ComplainAboutNonnullParamOrCall(NonNull); 13596 return; 13597 } 13598 13599 for (const ParamIdx &ArgNo : NonNull->args()) { 13600 if (ArgNo.getASTIndex() == ParamNo) { 13601 ComplainAboutNonnullParamOrCall(NonNull); 13602 return; 13603 } 13604 } 13605 } 13606 } 13607 } 13608 } 13609 13610 QualType T = D->getType(); 13611 const bool IsArray = T->isArrayType(); 13612 const bool IsFunction = T->isFunctionType(); 13613 13614 // Address of function is used to silence the function warning. 13615 if (IsAddressOf && IsFunction) { 13616 return; 13617 } 13618 13619 // Found nothing. 13620 if (!IsAddressOf && !IsFunction && !IsArray) 13621 return; 13622 13623 // Pretty print the expression for the diagnostic. 13624 std::string Str; 13625 llvm::raw_string_ostream S(Str); 13626 E->printPretty(S, nullptr, getPrintingPolicy()); 13627 13628 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13629 : diag::warn_impcast_pointer_to_bool; 13630 enum { 13631 AddressOf, 13632 FunctionPointer, 13633 ArrayPointer 13634 } DiagType; 13635 if (IsAddressOf) 13636 DiagType = AddressOf; 13637 else if (IsFunction) 13638 DiagType = FunctionPointer; 13639 else if (IsArray) 13640 DiagType = ArrayPointer; 13641 else 13642 llvm_unreachable("Could not determine diagnostic."); 13643 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13644 << Range << IsEqual; 13645 13646 if (!IsFunction) 13647 return; 13648 13649 // Suggest '&' to silence the function warning. 13650 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13651 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13652 13653 // Check to see if '()' fixit should be emitted. 13654 QualType ReturnType; 13655 UnresolvedSet<4> NonTemplateOverloads; 13656 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13657 if (ReturnType.isNull()) 13658 return; 13659 13660 if (IsCompare) { 13661 // There are two cases here. If there is null constant, the only suggest 13662 // for a pointer return type. If the null is 0, then suggest if the return 13663 // type is a pointer or an integer type. 13664 if (!ReturnType->isPointerType()) { 13665 if (NullKind == Expr::NPCK_ZeroExpression || 13666 NullKind == Expr::NPCK_ZeroLiteral) { 13667 if (!ReturnType->isIntegerType()) 13668 return; 13669 } else { 13670 return; 13671 } 13672 } 13673 } else { // !IsCompare 13674 // For function to bool, only suggest if the function pointer has bool 13675 // return type. 13676 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13677 return; 13678 } 13679 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13680 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13681 } 13682 13683 /// Diagnoses "dangerous" implicit conversions within the given 13684 /// expression (which is a full expression). Implements -Wconversion 13685 /// and -Wsign-compare. 13686 /// 13687 /// \param CC the "context" location of the implicit conversion, i.e. 13688 /// the most location of the syntactic entity requiring the implicit 13689 /// conversion 13690 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13691 // Don't diagnose in unevaluated contexts. 13692 if (isUnevaluatedContext()) 13693 return; 13694 13695 // Don't diagnose for value- or type-dependent expressions. 13696 if (E->isTypeDependent() || E->isValueDependent()) 13697 return; 13698 13699 // Check for array bounds violations in cases where the check isn't triggered 13700 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13701 // ArraySubscriptExpr is on the RHS of a variable initialization. 13702 CheckArrayAccess(E); 13703 13704 // This is not the right CC for (e.g.) a variable initialization. 13705 AnalyzeImplicitConversions(*this, E, CC); 13706 } 13707 13708 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13709 /// Input argument E is a logical expression. 13710 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13711 ::CheckBoolLikeConversion(*this, E, CC); 13712 } 13713 13714 /// Diagnose when expression is an integer constant expression and its evaluation 13715 /// results in integer overflow 13716 void Sema::CheckForIntOverflow (Expr *E) { 13717 // Use a work list to deal with nested struct initializers. 13718 SmallVector<Expr *, 2> Exprs(1, E); 13719 13720 do { 13721 Expr *OriginalE = Exprs.pop_back_val(); 13722 Expr *E = OriginalE->IgnoreParenCasts(); 13723 13724 if (isa<BinaryOperator>(E)) { 13725 E->EvaluateForOverflow(Context); 13726 continue; 13727 } 13728 13729 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13730 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13731 else if (isa<ObjCBoxedExpr>(OriginalE)) 13732 E->EvaluateForOverflow(Context); 13733 else if (auto Call = dyn_cast<CallExpr>(E)) 13734 Exprs.append(Call->arg_begin(), Call->arg_end()); 13735 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13736 Exprs.append(Message->arg_begin(), Message->arg_end()); 13737 } while (!Exprs.empty()); 13738 } 13739 13740 namespace { 13741 13742 /// Visitor for expressions which looks for unsequenced operations on the 13743 /// same object. 13744 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13745 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13746 13747 /// A tree of sequenced regions within an expression. Two regions are 13748 /// unsequenced if one is an ancestor or a descendent of the other. When we 13749 /// finish processing an expression with sequencing, such as a comma 13750 /// expression, we fold its tree nodes into its parent, since they are 13751 /// unsequenced with respect to nodes we will visit later. 13752 class SequenceTree { 13753 struct Value { 13754 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13755 unsigned Parent : 31; 13756 unsigned Merged : 1; 13757 }; 13758 SmallVector<Value, 8> Values; 13759 13760 public: 13761 /// A region within an expression which may be sequenced with respect 13762 /// to some other region. 13763 class Seq { 13764 friend class SequenceTree; 13765 13766 unsigned Index; 13767 13768 explicit Seq(unsigned N) : Index(N) {} 13769 13770 public: 13771 Seq() : Index(0) {} 13772 }; 13773 13774 SequenceTree() { Values.push_back(Value(0)); } 13775 Seq root() const { return Seq(0); } 13776 13777 /// Create a new sequence of operations, which is an unsequenced 13778 /// subset of \p Parent. This sequence of operations is sequenced with 13779 /// respect to other children of \p Parent. 13780 Seq allocate(Seq Parent) { 13781 Values.push_back(Value(Parent.Index)); 13782 return Seq(Values.size() - 1); 13783 } 13784 13785 /// Merge a sequence of operations into its parent. 13786 void merge(Seq S) { 13787 Values[S.Index].Merged = true; 13788 } 13789 13790 /// Determine whether two operations are unsequenced. This operation 13791 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13792 /// should have been merged into its parent as appropriate. 13793 bool isUnsequenced(Seq Cur, Seq Old) { 13794 unsigned C = representative(Cur.Index); 13795 unsigned Target = representative(Old.Index); 13796 while (C >= Target) { 13797 if (C == Target) 13798 return true; 13799 C = Values[C].Parent; 13800 } 13801 return false; 13802 } 13803 13804 private: 13805 /// Pick a representative for a sequence. 13806 unsigned representative(unsigned K) { 13807 if (Values[K].Merged) 13808 // Perform path compression as we go. 13809 return Values[K].Parent = representative(Values[K].Parent); 13810 return K; 13811 } 13812 }; 13813 13814 /// An object for which we can track unsequenced uses. 13815 using Object = const NamedDecl *; 13816 13817 /// Different flavors of object usage which we track. We only track the 13818 /// least-sequenced usage of each kind. 13819 enum UsageKind { 13820 /// A read of an object. Multiple unsequenced reads are OK. 13821 UK_Use, 13822 13823 /// A modification of an object which is sequenced before the value 13824 /// computation of the expression, such as ++n in C++. 13825 UK_ModAsValue, 13826 13827 /// A modification of an object which is not sequenced before the value 13828 /// computation of the expression, such as n++. 13829 UK_ModAsSideEffect, 13830 13831 UK_Count = UK_ModAsSideEffect + 1 13832 }; 13833 13834 /// Bundle together a sequencing region and the expression corresponding 13835 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13836 struct Usage { 13837 const Expr *UsageExpr; 13838 SequenceTree::Seq Seq; 13839 13840 Usage() : UsageExpr(nullptr), Seq() {} 13841 }; 13842 13843 struct UsageInfo { 13844 Usage Uses[UK_Count]; 13845 13846 /// Have we issued a diagnostic for this object already? 13847 bool Diagnosed; 13848 13849 UsageInfo() : Uses(), Diagnosed(false) {} 13850 }; 13851 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13852 13853 Sema &SemaRef; 13854 13855 /// Sequenced regions within the expression. 13856 SequenceTree Tree; 13857 13858 /// Declaration modifications and references which we have seen. 13859 UsageInfoMap UsageMap; 13860 13861 /// The region we are currently within. 13862 SequenceTree::Seq Region; 13863 13864 /// Filled in with declarations which were modified as a side-effect 13865 /// (that is, post-increment operations). 13866 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13867 13868 /// Expressions to check later. We defer checking these to reduce 13869 /// stack usage. 13870 SmallVectorImpl<const Expr *> &WorkList; 13871 13872 /// RAII object wrapping the visitation of a sequenced subexpression of an 13873 /// expression. At the end of this process, the side-effects of the evaluation 13874 /// become sequenced with respect to the value computation of the result, so 13875 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13876 /// UK_ModAsValue. 13877 struct SequencedSubexpression { 13878 SequencedSubexpression(SequenceChecker &Self) 13879 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13880 Self.ModAsSideEffect = &ModAsSideEffect; 13881 } 13882 13883 ~SequencedSubexpression() { 13884 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13885 // Add a new usage with usage kind UK_ModAsValue, and then restore 13886 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13887 // the previous one was empty). 13888 UsageInfo &UI = Self.UsageMap[M.first]; 13889 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13890 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13891 SideEffectUsage = M.second; 13892 } 13893 Self.ModAsSideEffect = OldModAsSideEffect; 13894 } 13895 13896 SequenceChecker &Self; 13897 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13898 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13899 }; 13900 13901 /// RAII object wrapping the visitation of a subexpression which we might 13902 /// choose to evaluate as a constant. If any subexpression is evaluated and 13903 /// found to be non-constant, this allows us to suppress the evaluation of 13904 /// the outer expression. 13905 class EvaluationTracker { 13906 public: 13907 EvaluationTracker(SequenceChecker &Self) 13908 : Self(Self), Prev(Self.EvalTracker) { 13909 Self.EvalTracker = this; 13910 } 13911 13912 ~EvaluationTracker() { 13913 Self.EvalTracker = Prev; 13914 if (Prev) 13915 Prev->EvalOK &= EvalOK; 13916 } 13917 13918 bool evaluate(const Expr *E, bool &Result) { 13919 if (!EvalOK || E->isValueDependent()) 13920 return false; 13921 EvalOK = E->EvaluateAsBooleanCondition( 13922 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13923 return EvalOK; 13924 } 13925 13926 private: 13927 SequenceChecker &Self; 13928 EvaluationTracker *Prev; 13929 bool EvalOK = true; 13930 } *EvalTracker = nullptr; 13931 13932 /// Find the object which is produced by the specified expression, 13933 /// if any. 13934 Object getObject(const Expr *E, bool Mod) const { 13935 E = E->IgnoreParenCasts(); 13936 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13937 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13938 return getObject(UO->getSubExpr(), Mod); 13939 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13940 if (BO->getOpcode() == BO_Comma) 13941 return getObject(BO->getRHS(), Mod); 13942 if (Mod && BO->isAssignmentOp()) 13943 return getObject(BO->getLHS(), Mod); 13944 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13945 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13946 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13947 return ME->getMemberDecl(); 13948 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13949 // FIXME: If this is a reference, map through to its value. 13950 return DRE->getDecl(); 13951 return nullptr; 13952 } 13953 13954 /// Note that an object \p O was modified or used by an expression 13955 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13956 /// the object \p O as obtained via the \p UsageMap. 13957 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13958 // Get the old usage for the given object and usage kind. 13959 Usage &U = UI.Uses[UK]; 13960 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13961 // If we have a modification as side effect and are in a sequenced 13962 // subexpression, save the old Usage so that we can restore it later 13963 // in SequencedSubexpression::~SequencedSubexpression. 13964 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13965 ModAsSideEffect->push_back(std::make_pair(O, U)); 13966 // Then record the new usage with the current sequencing region. 13967 U.UsageExpr = UsageExpr; 13968 U.Seq = Region; 13969 } 13970 } 13971 13972 /// Check whether a modification or use of an object \p O in an expression 13973 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13974 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13975 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13976 /// usage and false we are checking for a mod-use unsequenced usage. 13977 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13978 UsageKind OtherKind, bool IsModMod) { 13979 if (UI.Diagnosed) 13980 return; 13981 13982 const Usage &U = UI.Uses[OtherKind]; 13983 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13984 return; 13985 13986 const Expr *Mod = U.UsageExpr; 13987 const Expr *ModOrUse = UsageExpr; 13988 if (OtherKind == UK_Use) 13989 std::swap(Mod, ModOrUse); 13990 13991 SemaRef.DiagRuntimeBehavior( 13992 Mod->getExprLoc(), {Mod, ModOrUse}, 13993 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13994 : diag::warn_unsequenced_mod_use) 13995 << O << SourceRange(ModOrUse->getExprLoc())); 13996 UI.Diagnosed = true; 13997 } 13998 13999 // A note on note{Pre, Post}{Use, Mod}: 14000 // 14001 // (It helps to follow the algorithm with an expression such as 14002 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 14003 // operations before C++17 and both are well-defined in C++17). 14004 // 14005 // When visiting a node which uses/modify an object we first call notePreUse 14006 // or notePreMod before visiting its sub-expression(s). At this point the 14007 // children of the current node have not yet been visited and so the eventual 14008 // uses/modifications resulting from the children of the current node have not 14009 // been recorded yet. 14010 // 14011 // We then visit the children of the current node. After that notePostUse or 14012 // notePostMod is called. These will 1) detect an unsequenced modification 14013 // as side effect (as in "k++ + k") and 2) add a new usage with the 14014 // appropriate usage kind. 14015 // 14016 // We also have to be careful that some operation sequences modification as 14017 // side effect as well (for example: || or ,). To account for this we wrap 14018 // the visitation of such a sub-expression (for example: the LHS of || or ,) 14019 // with SequencedSubexpression. SequencedSubexpression is an RAII object 14020 // which record usages which are modifications as side effect, and then 14021 // downgrade them (or more accurately restore the previous usage which was a 14022 // modification as side effect) when exiting the scope of the sequenced 14023 // subexpression. 14024 14025 void notePreUse(Object O, const Expr *UseExpr) { 14026 UsageInfo &UI = UsageMap[O]; 14027 // Uses conflict with other modifications. 14028 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 14029 } 14030 14031 void notePostUse(Object O, const Expr *UseExpr) { 14032 UsageInfo &UI = UsageMap[O]; 14033 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 14034 /*IsModMod=*/false); 14035 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 14036 } 14037 14038 void notePreMod(Object O, const Expr *ModExpr) { 14039 UsageInfo &UI = UsageMap[O]; 14040 // Modifications conflict with other modifications and with uses. 14041 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 14042 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 14043 } 14044 14045 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 14046 UsageInfo &UI = UsageMap[O]; 14047 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 14048 /*IsModMod=*/true); 14049 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14050 } 14051 14052 public: 14053 SequenceChecker(Sema &S, const Expr *E, 14054 SmallVectorImpl<const Expr *> &WorkList) 14055 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14056 Visit(E); 14057 // Silence a -Wunused-private-field since WorkList is now unused. 14058 // TODO: Evaluate if it can be used, and if not remove it. 14059 (void)this->WorkList; 14060 } 14061 14062 void VisitStmt(const Stmt *S) { 14063 // Skip all statements which aren't expressions for now. 14064 } 14065 14066 void VisitExpr(const Expr *E) { 14067 // By default, just recurse to evaluated subexpressions. 14068 Base::VisitStmt(E); 14069 } 14070 14071 void VisitCastExpr(const CastExpr *E) { 14072 Object O = Object(); 14073 if (E->getCastKind() == CK_LValueToRValue) 14074 O = getObject(E->getSubExpr(), false); 14075 14076 if (O) 14077 notePreUse(O, E); 14078 VisitExpr(E); 14079 if (O) 14080 notePostUse(O, E); 14081 } 14082 14083 void VisitSequencedExpressions(const Expr *SequencedBefore, 14084 const Expr *SequencedAfter) { 14085 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14086 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14087 SequenceTree::Seq OldRegion = Region; 14088 14089 { 14090 SequencedSubexpression SeqBefore(*this); 14091 Region = BeforeRegion; 14092 Visit(SequencedBefore); 14093 } 14094 14095 Region = AfterRegion; 14096 Visit(SequencedAfter); 14097 14098 Region = OldRegion; 14099 14100 Tree.merge(BeforeRegion); 14101 Tree.merge(AfterRegion); 14102 } 14103 14104 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14105 // C++17 [expr.sub]p1: 14106 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14107 // expression E1 is sequenced before the expression E2. 14108 if (SemaRef.getLangOpts().CPlusPlus17) 14109 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14110 else { 14111 Visit(ASE->getLHS()); 14112 Visit(ASE->getRHS()); 14113 } 14114 } 14115 14116 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14117 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14118 void VisitBinPtrMem(const BinaryOperator *BO) { 14119 // C++17 [expr.mptr.oper]p4: 14120 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14121 // the expression E1 is sequenced before the expression E2. 14122 if (SemaRef.getLangOpts().CPlusPlus17) 14123 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14124 else { 14125 Visit(BO->getLHS()); 14126 Visit(BO->getRHS()); 14127 } 14128 } 14129 14130 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14131 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14132 void VisitBinShlShr(const BinaryOperator *BO) { 14133 // C++17 [expr.shift]p4: 14134 // The expression E1 is sequenced before the expression E2. 14135 if (SemaRef.getLangOpts().CPlusPlus17) 14136 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14137 else { 14138 Visit(BO->getLHS()); 14139 Visit(BO->getRHS()); 14140 } 14141 } 14142 14143 void VisitBinComma(const BinaryOperator *BO) { 14144 // C++11 [expr.comma]p1: 14145 // Every value computation and side effect associated with the left 14146 // expression is sequenced before every value computation and side 14147 // effect associated with the right expression. 14148 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14149 } 14150 14151 void VisitBinAssign(const BinaryOperator *BO) { 14152 SequenceTree::Seq RHSRegion; 14153 SequenceTree::Seq LHSRegion; 14154 if (SemaRef.getLangOpts().CPlusPlus17) { 14155 RHSRegion = Tree.allocate(Region); 14156 LHSRegion = Tree.allocate(Region); 14157 } else { 14158 RHSRegion = Region; 14159 LHSRegion = Region; 14160 } 14161 SequenceTree::Seq OldRegion = Region; 14162 14163 // C++11 [expr.ass]p1: 14164 // [...] the assignment is sequenced after the value computation 14165 // of the right and left operands, [...] 14166 // 14167 // so check it before inspecting the operands and update the 14168 // map afterwards. 14169 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14170 if (O) 14171 notePreMod(O, BO); 14172 14173 if (SemaRef.getLangOpts().CPlusPlus17) { 14174 // C++17 [expr.ass]p1: 14175 // [...] The right operand is sequenced before the left operand. [...] 14176 { 14177 SequencedSubexpression SeqBefore(*this); 14178 Region = RHSRegion; 14179 Visit(BO->getRHS()); 14180 } 14181 14182 Region = LHSRegion; 14183 Visit(BO->getLHS()); 14184 14185 if (O && isa<CompoundAssignOperator>(BO)) 14186 notePostUse(O, BO); 14187 14188 } else { 14189 // C++11 does not specify any sequencing between the LHS and RHS. 14190 Region = LHSRegion; 14191 Visit(BO->getLHS()); 14192 14193 if (O && isa<CompoundAssignOperator>(BO)) 14194 notePostUse(O, BO); 14195 14196 Region = RHSRegion; 14197 Visit(BO->getRHS()); 14198 } 14199 14200 // C++11 [expr.ass]p1: 14201 // the assignment is sequenced [...] before the value computation of the 14202 // assignment expression. 14203 // C11 6.5.16/3 has no such rule. 14204 Region = OldRegion; 14205 if (O) 14206 notePostMod(O, BO, 14207 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14208 : UK_ModAsSideEffect); 14209 if (SemaRef.getLangOpts().CPlusPlus17) { 14210 Tree.merge(RHSRegion); 14211 Tree.merge(LHSRegion); 14212 } 14213 } 14214 14215 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14216 VisitBinAssign(CAO); 14217 } 14218 14219 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14220 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14221 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14222 Object O = getObject(UO->getSubExpr(), true); 14223 if (!O) 14224 return VisitExpr(UO); 14225 14226 notePreMod(O, UO); 14227 Visit(UO->getSubExpr()); 14228 // C++11 [expr.pre.incr]p1: 14229 // the expression ++x is equivalent to x+=1 14230 notePostMod(O, UO, 14231 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14232 : UK_ModAsSideEffect); 14233 } 14234 14235 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14236 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14237 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14238 Object O = getObject(UO->getSubExpr(), true); 14239 if (!O) 14240 return VisitExpr(UO); 14241 14242 notePreMod(O, UO); 14243 Visit(UO->getSubExpr()); 14244 notePostMod(O, UO, UK_ModAsSideEffect); 14245 } 14246 14247 void VisitBinLOr(const BinaryOperator *BO) { 14248 // C++11 [expr.log.or]p2: 14249 // If the second expression is evaluated, every value computation and 14250 // side effect associated with the first expression is sequenced before 14251 // every value computation and side effect associated with the 14252 // second expression. 14253 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14254 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14255 SequenceTree::Seq OldRegion = Region; 14256 14257 EvaluationTracker Eval(*this); 14258 { 14259 SequencedSubexpression Sequenced(*this); 14260 Region = LHSRegion; 14261 Visit(BO->getLHS()); 14262 } 14263 14264 // C++11 [expr.log.or]p1: 14265 // [...] the second operand is not evaluated if the first operand 14266 // evaluates to true. 14267 bool EvalResult = false; 14268 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14269 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14270 if (ShouldVisitRHS) { 14271 Region = RHSRegion; 14272 Visit(BO->getRHS()); 14273 } 14274 14275 Region = OldRegion; 14276 Tree.merge(LHSRegion); 14277 Tree.merge(RHSRegion); 14278 } 14279 14280 void VisitBinLAnd(const BinaryOperator *BO) { 14281 // C++11 [expr.log.and]p2: 14282 // If the second expression is evaluated, every value computation and 14283 // side effect associated with the first expression is sequenced before 14284 // every value computation and side effect associated with the 14285 // second expression. 14286 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14287 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14288 SequenceTree::Seq OldRegion = Region; 14289 14290 EvaluationTracker Eval(*this); 14291 { 14292 SequencedSubexpression Sequenced(*this); 14293 Region = LHSRegion; 14294 Visit(BO->getLHS()); 14295 } 14296 14297 // C++11 [expr.log.and]p1: 14298 // [...] the second operand is not evaluated if the first operand is false. 14299 bool EvalResult = false; 14300 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14301 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14302 if (ShouldVisitRHS) { 14303 Region = RHSRegion; 14304 Visit(BO->getRHS()); 14305 } 14306 14307 Region = OldRegion; 14308 Tree.merge(LHSRegion); 14309 Tree.merge(RHSRegion); 14310 } 14311 14312 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14313 // C++11 [expr.cond]p1: 14314 // [...] Every value computation and side effect associated with the first 14315 // expression is sequenced before every value computation and side effect 14316 // associated with the second or third expression. 14317 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14318 14319 // No sequencing is specified between the true and false expression. 14320 // However since exactly one of both is going to be evaluated we can 14321 // consider them to be sequenced. This is needed to avoid warning on 14322 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14323 // both the true and false expressions because we can't evaluate x. 14324 // This will still allow us to detect an expression like (pre C++17) 14325 // "(x ? y += 1 : y += 2) = y". 14326 // 14327 // We don't wrap the visitation of the true and false expression with 14328 // SequencedSubexpression because we don't want to downgrade modifications 14329 // as side effect in the true and false expressions after the visition 14330 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14331 // not warn between the two "y++", but we should warn between the "y++" 14332 // and the "y". 14333 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14334 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14335 SequenceTree::Seq OldRegion = Region; 14336 14337 EvaluationTracker Eval(*this); 14338 { 14339 SequencedSubexpression Sequenced(*this); 14340 Region = ConditionRegion; 14341 Visit(CO->getCond()); 14342 } 14343 14344 // C++11 [expr.cond]p1: 14345 // [...] The first expression is contextually converted to bool (Clause 4). 14346 // It is evaluated and if it is true, the result of the conditional 14347 // expression is the value of the second expression, otherwise that of the 14348 // third expression. Only one of the second and third expressions is 14349 // evaluated. [...] 14350 bool EvalResult = false; 14351 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14352 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14353 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14354 if (ShouldVisitTrueExpr) { 14355 Region = TrueRegion; 14356 Visit(CO->getTrueExpr()); 14357 } 14358 if (ShouldVisitFalseExpr) { 14359 Region = FalseRegion; 14360 Visit(CO->getFalseExpr()); 14361 } 14362 14363 Region = OldRegion; 14364 Tree.merge(ConditionRegion); 14365 Tree.merge(TrueRegion); 14366 Tree.merge(FalseRegion); 14367 } 14368 14369 void VisitCallExpr(const CallExpr *CE) { 14370 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14371 14372 if (CE->isUnevaluatedBuiltinCall(Context)) 14373 return; 14374 14375 // C++11 [intro.execution]p15: 14376 // When calling a function [...], every value computation and side effect 14377 // associated with any argument expression, or with the postfix expression 14378 // designating the called function, is sequenced before execution of every 14379 // expression or statement in the body of the function [and thus before 14380 // the value computation of its result]. 14381 SequencedSubexpression Sequenced(*this); 14382 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14383 // C++17 [expr.call]p5 14384 // The postfix-expression is sequenced before each expression in the 14385 // expression-list and any default argument. [...] 14386 SequenceTree::Seq CalleeRegion; 14387 SequenceTree::Seq OtherRegion; 14388 if (SemaRef.getLangOpts().CPlusPlus17) { 14389 CalleeRegion = Tree.allocate(Region); 14390 OtherRegion = Tree.allocate(Region); 14391 } else { 14392 CalleeRegion = Region; 14393 OtherRegion = Region; 14394 } 14395 SequenceTree::Seq OldRegion = Region; 14396 14397 // Visit the callee expression first. 14398 Region = CalleeRegion; 14399 if (SemaRef.getLangOpts().CPlusPlus17) { 14400 SequencedSubexpression Sequenced(*this); 14401 Visit(CE->getCallee()); 14402 } else { 14403 Visit(CE->getCallee()); 14404 } 14405 14406 // Then visit the argument expressions. 14407 Region = OtherRegion; 14408 for (const Expr *Argument : CE->arguments()) 14409 Visit(Argument); 14410 14411 Region = OldRegion; 14412 if (SemaRef.getLangOpts().CPlusPlus17) { 14413 Tree.merge(CalleeRegion); 14414 Tree.merge(OtherRegion); 14415 } 14416 }); 14417 } 14418 14419 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14420 // C++17 [over.match.oper]p2: 14421 // [...] the operator notation is first transformed to the equivalent 14422 // function-call notation as summarized in Table 12 (where @ denotes one 14423 // of the operators covered in the specified subclause). However, the 14424 // operands are sequenced in the order prescribed for the built-in 14425 // operator (Clause 8). 14426 // 14427 // From the above only overloaded binary operators and overloaded call 14428 // operators have sequencing rules in C++17 that we need to handle 14429 // separately. 14430 if (!SemaRef.getLangOpts().CPlusPlus17 || 14431 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14432 return VisitCallExpr(CXXOCE); 14433 14434 enum { 14435 NoSequencing, 14436 LHSBeforeRHS, 14437 RHSBeforeLHS, 14438 LHSBeforeRest 14439 } SequencingKind; 14440 switch (CXXOCE->getOperator()) { 14441 case OO_Equal: 14442 case OO_PlusEqual: 14443 case OO_MinusEqual: 14444 case OO_StarEqual: 14445 case OO_SlashEqual: 14446 case OO_PercentEqual: 14447 case OO_CaretEqual: 14448 case OO_AmpEqual: 14449 case OO_PipeEqual: 14450 case OO_LessLessEqual: 14451 case OO_GreaterGreaterEqual: 14452 SequencingKind = RHSBeforeLHS; 14453 break; 14454 14455 case OO_LessLess: 14456 case OO_GreaterGreater: 14457 case OO_AmpAmp: 14458 case OO_PipePipe: 14459 case OO_Comma: 14460 case OO_ArrowStar: 14461 case OO_Subscript: 14462 SequencingKind = LHSBeforeRHS; 14463 break; 14464 14465 case OO_Call: 14466 SequencingKind = LHSBeforeRest; 14467 break; 14468 14469 default: 14470 SequencingKind = NoSequencing; 14471 break; 14472 } 14473 14474 if (SequencingKind == NoSequencing) 14475 return VisitCallExpr(CXXOCE); 14476 14477 // This is a call, so all subexpressions are sequenced before the result. 14478 SequencedSubexpression Sequenced(*this); 14479 14480 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14481 assert(SemaRef.getLangOpts().CPlusPlus17 && 14482 "Should only get there with C++17 and above!"); 14483 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14484 "Should only get there with an overloaded binary operator" 14485 " or an overloaded call operator!"); 14486 14487 if (SequencingKind == LHSBeforeRest) { 14488 assert(CXXOCE->getOperator() == OO_Call && 14489 "We should only have an overloaded call operator here!"); 14490 14491 // This is very similar to VisitCallExpr, except that we only have the 14492 // C++17 case. The postfix-expression is the first argument of the 14493 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14494 // are in the following arguments. 14495 // 14496 // Note that we intentionally do not visit the callee expression since 14497 // it is just a decayed reference to a function. 14498 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14499 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14500 SequenceTree::Seq OldRegion = Region; 14501 14502 assert(CXXOCE->getNumArgs() >= 1 && 14503 "An overloaded call operator must have at least one argument" 14504 " for the postfix-expression!"); 14505 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14506 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14507 CXXOCE->getNumArgs() - 1); 14508 14509 // Visit the postfix-expression first. 14510 { 14511 Region = PostfixExprRegion; 14512 SequencedSubexpression Sequenced(*this); 14513 Visit(PostfixExpr); 14514 } 14515 14516 // Then visit the argument expressions. 14517 Region = ArgsRegion; 14518 for (const Expr *Arg : Args) 14519 Visit(Arg); 14520 14521 Region = OldRegion; 14522 Tree.merge(PostfixExprRegion); 14523 Tree.merge(ArgsRegion); 14524 } else { 14525 assert(CXXOCE->getNumArgs() == 2 && 14526 "Should only have two arguments here!"); 14527 assert((SequencingKind == LHSBeforeRHS || 14528 SequencingKind == RHSBeforeLHS) && 14529 "Unexpected sequencing kind!"); 14530 14531 // We do not visit the callee expression since it is just a decayed 14532 // reference to a function. 14533 const Expr *E1 = CXXOCE->getArg(0); 14534 const Expr *E2 = CXXOCE->getArg(1); 14535 if (SequencingKind == RHSBeforeLHS) 14536 std::swap(E1, E2); 14537 14538 return VisitSequencedExpressions(E1, E2); 14539 } 14540 }); 14541 } 14542 14543 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14544 // This is a call, so all subexpressions are sequenced before the result. 14545 SequencedSubexpression Sequenced(*this); 14546 14547 if (!CCE->isListInitialization()) 14548 return VisitExpr(CCE); 14549 14550 // In C++11, list initializations are sequenced. 14551 SmallVector<SequenceTree::Seq, 32> Elts; 14552 SequenceTree::Seq Parent = Region; 14553 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14554 E = CCE->arg_end(); 14555 I != E; ++I) { 14556 Region = Tree.allocate(Parent); 14557 Elts.push_back(Region); 14558 Visit(*I); 14559 } 14560 14561 // Forget that the initializers are sequenced. 14562 Region = Parent; 14563 for (unsigned I = 0; I < Elts.size(); ++I) 14564 Tree.merge(Elts[I]); 14565 } 14566 14567 void VisitInitListExpr(const InitListExpr *ILE) { 14568 if (!SemaRef.getLangOpts().CPlusPlus11) 14569 return VisitExpr(ILE); 14570 14571 // In C++11, list initializations are sequenced. 14572 SmallVector<SequenceTree::Seq, 32> Elts; 14573 SequenceTree::Seq Parent = Region; 14574 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14575 const Expr *E = ILE->getInit(I); 14576 if (!E) 14577 continue; 14578 Region = Tree.allocate(Parent); 14579 Elts.push_back(Region); 14580 Visit(E); 14581 } 14582 14583 // Forget that the initializers are sequenced. 14584 Region = Parent; 14585 for (unsigned I = 0; I < Elts.size(); ++I) 14586 Tree.merge(Elts[I]); 14587 } 14588 }; 14589 14590 } // namespace 14591 14592 void Sema::CheckUnsequencedOperations(const Expr *E) { 14593 SmallVector<const Expr *, 8> WorkList; 14594 WorkList.push_back(E); 14595 while (!WorkList.empty()) { 14596 const Expr *Item = WorkList.pop_back_val(); 14597 SequenceChecker(*this, Item, WorkList); 14598 } 14599 } 14600 14601 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14602 bool IsConstexpr) { 14603 llvm::SaveAndRestore<bool> ConstantContext( 14604 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14605 CheckImplicitConversions(E, CheckLoc); 14606 if (!E->isInstantiationDependent()) 14607 CheckUnsequencedOperations(E); 14608 if (!IsConstexpr && !E->isValueDependent()) 14609 CheckForIntOverflow(E); 14610 DiagnoseMisalignedMembers(); 14611 } 14612 14613 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14614 FieldDecl *BitField, 14615 Expr *Init) { 14616 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14617 } 14618 14619 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14620 SourceLocation Loc) { 14621 if (!PType->isVariablyModifiedType()) 14622 return; 14623 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14624 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14625 return; 14626 } 14627 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14628 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14629 return; 14630 } 14631 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14632 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14633 return; 14634 } 14635 14636 const ArrayType *AT = S.Context.getAsArrayType(PType); 14637 if (!AT) 14638 return; 14639 14640 if (AT->getSizeModifier() != ArrayType::Star) { 14641 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14642 return; 14643 } 14644 14645 S.Diag(Loc, diag::err_array_star_in_function_definition); 14646 } 14647 14648 /// CheckParmsForFunctionDef - Check that the parameters of the given 14649 /// function are appropriate for the definition of a function. This 14650 /// takes care of any checks that cannot be performed on the 14651 /// declaration itself, e.g., that the types of each of the function 14652 /// parameters are complete. 14653 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14654 bool CheckParameterNames) { 14655 bool HasInvalidParm = false; 14656 for (ParmVarDecl *Param : Parameters) { 14657 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14658 // function declarator that is part of a function definition of 14659 // that function shall not have incomplete type. 14660 // 14661 // This is also C++ [dcl.fct]p6. 14662 if (!Param->isInvalidDecl() && 14663 RequireCompleteType(Param->getLocation(), Param->getType(), 14664 diag::err_typecheck_decl_incomplete_type)) { 14665 Param->setInvalidDecl(); 14666 HasInvalidParm = true; 14667 } 14668 14669 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14670 // declaration of each parameter shall include an identifier. 14671 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14672 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14673 // Diagnose this as an extension in C17 and earlier. 14674 if (!getLangOpts().C2x) 14675 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14676 } 14677 14678 // C99 6.7.5.3p12: 14679 // If the function declarator is not part of a definition of that 14680 // function, parameters may have incomplete type and may use the [*] 14681 // notation in their sequences of declarator specifiers to specify 14682 // variable length array types. 14683 QualType PType = Param->getOriginalType(); 14684 // FIXME: This diagnostic should point the '[*]' if source-location 14685 // information is added for it. 14686 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14687 14688 // If the parameter is a c++ class type and it has to be destructed in the 14689 // callee function, declare the destructor so that it can be called by the 14690 // callee function. Do not perform any direct access check on the dtor here. 14691 if (!Param->isInvalidDecl()) { 14692 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14693 if (!ClassDecl->isInvalidDecl() && 14694 !ClassDecl->hasIrrelevantDestructor() && 14695 !ClassDecl->isDependentContext() && 14696 ClassDecl->isParamDestroyedInCallee()) { 14697 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14698 MarkFunctionReferenced(Param->getLocation(), Destructor); 14699 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14700 } 14701 } 14702 } 14703 14704 // Parameters with the pass_object_size attribute only need to be marked 14705 // constant at function definitions. Because we lack information about 14706 // whether we're on a declaration or definition when we're instantiating the 14707 // attribute, we need to check for constness here. 14708 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14709 if (!Param->getType().isConstQualified()) 14710 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14711 << Attr->getSpelling() << 1; 14712 14713 // Check for parameter names shadowing fields from the class. 14714 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14715 // The owning context for the parameter should be the function, but we 14716 // want to see if this function's declaration context is a record. 14717 DeclContext *DC = Param->getDeclContext(); 14718 if (DC && DC->isFunctionOrMethod()) { 14719 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14720 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14721 RD, /*DeclIsField*/ false); 14722 } 14723 } 14724 } 14725 14726 return HasInvalidParm; 14727 } 14728 14729 Optional<std::pair<CharUnits, CharUnits>> 14730 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14731 14732 /// Compute the alignment and offset of the base class object given the 14733 /// derived-to-base cast expression and the alignment and offset of the derived 14734 /// class object. 14735 static std::pair<CharUnits, CharUnits> 14736 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14737 CharUnits BaseAlignment, CharUnits Offset, 14738 ASTContext &Ctx) { 14739 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14740 ++PathI) { 14741 const CXXBaseSpecifier *Base = *PathI; 14742 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14743 if (Base->isVirtual()) { 14744 // The complete object may have a lower alignment than the non-virtual 14745 // alignment of the base, in which case the base may be misaligned. Choose 14746 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14747 // conservative lower bound of the complete object alignment. 14748 CharUnits NonVirtualAlignment = 14749 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14750 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14751 Offset = CharUnits::Zero(); 14752 } else { 14753 const ASTRecordLayout &RL = 14754 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14755 Offset += RL.getBaseClassOffset(BaseDecl); 14756 } 14757 DerivedType = Base->getType(); 14758 } 14759 14760 return std::make_pair(BaseAlignment, Offset); 14761 } 14762 14763 /// Compute the alignment and offset of a binary additive operator. 14764 static Optional<std::pair<CharUnits, CharUnits>> 14765 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14766 bool IsSub, ASTContext &Ctx) { 14767 QualType PointeeType = PtrE->getType()->getPointeeType(); 14768 14769 if (!PointeeType->isConstantSizeType()) 14770 return llvm::None; 14771 14772 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14773 14774 if (!P) 14775 return llvm::None; 14776 14777 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14778 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14779 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14780 if (IsSub) 14781 Offset = -Offset; 14782 return std::make_pair(P->first, P->second + Offset); 14783 } 14784 14785 // If the integer expression isn't a constant expression, compute the lower 14786 // bound of the alignment using the alignment and offset of the pointer 14787 // expression and the element size. 14788 return std::make_pair( 14789 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14790 CharUnits::Zero()); 14791 } 14792 14793 /// This helper function takes an lvalue expression and returns the alignment of 14794 /// a VarDecl and a constant offset from the VarDecl. 14795 Optional<std::pair<CharUnits, CharUnits>> 14796 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14797 E = E->IgnoreParens(); 14798 switch (E->getStmtClass()) { 14799 default: 14800 break; 14801 case Stmt::CStyleCastExprClass: 14802 case Stmt::CXXStaticCastExprClass: 14803 case Stmt::ImplicitCastExprClass: { 14804 auto *CE = cast<CastExpr>(E); 14805 const Expr *From = CE->getSubExpr(); 14806 switch (CE->getCastKind()) { 14807 default: 14808 break; 14809 case CK_NoOp: 14810 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14811 case CK_UncheckedDerivedToBase: 14812 case CK_DerivedToBase: { 14813 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14814 if (!P) 14815 break; 14816 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14817 P->second, Ctx); 14818 } 14819 } 14820 break; 14821 } 14822 case Stmt::ArraySubscriptExprClass: { 14823 auto *ASE = cast<ArraySubscriptExpr>(E); 14824 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14825 false, Ctx); 14826 } 14827 case Stmt::DeclRefExprClass: { 14828 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14829 // FIXME: If VD is captured by copy or is an escaping __block variable, 14830 // use the alignment of VD's type. 14831 if (!VD->getType()->isReferenceType()) 14832 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14833 if (VD->hasInit()) 14834 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14835 } 14836 break; 14837 } 14838 case Stmt::MemberExprClass: { 14839 auto *ME = cast<MemberExpr>(E); 14840 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14841 if (!FD || FD->getType()->isReferenceType() || 14842 FD->getParent()->isInvalidDecl()) 14843 break; 14844 Optional<std::pair<CharUnits, CharUnits>> P; 14845 if (ME->isArrow()) 14846 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14847 else 14848 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14849 if (!P) 14850 break; 14851 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14852 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14853 return std::make_pair(P->first, 14854 P->second + CharUnits::fromQuantity(Offset)); 14855 } 14856 case Stmt::UnaryOperatorClass: { 14857 auto *UO = cast<UnaryOperator>(E); 14858 switch (UO->getOpcode()) { 14859 default: 14860 break; 14861 case UO_Deref: 14862 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14863 } 14864 break; 14865 } 14866 case Stmt::BinaryOperatorClass: { 14867 auto *BO = cast<BinaryOperator>(E); 14868 auto Opcode = BO->getOpcode(); 14869 switch (Opcode) { 14870 default: 14871 break; 14872 case BO_Comma: 14873 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14874 } 14875 break; 14876 } 14877 } 14878 return llvm::None; 14879 } 14880 14881 /// This helper function takes a pointer expression and returns the alignment of 14882 /// a VarDecl and a constant offset from the VarDecl. 14883 Optional<std::pair<CharUnits, CharUnits>> 14884 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14885 E = E->IgnoreParens(); 14886 switch (E->getStmtClass()) { 14887 default: 14888 break; 14889 case Stmt::CStyleCastExprClass: 14890 case Stmt::CXXStaticCastExprClass: 14891 case Stmt::ImplicitCastExprClass: { 14892 auto *CE = cast<CastExpr>(E); 14893 const Expr *From = CE->getSubExpr(); 14894 switch (CE->getCastKind()) { 14895 default: 14896 break; 14897 case CK_NoOp: 14898 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14899 case CK_ArrayToPointerDecay: 14900 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14901 case CK_UncheckedDerivedToBase: 14902 case CK_DerivedToBase: { 14903 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14904 if (!P) 14905 break; 14906 return getDerivedToBaseAlignmentAndOffset( 14907 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14908 } 14909 } 14910 break; 14911 } 14912 case Stmt::CXXThisExprClass: { 14913 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14914 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14915 return std::make_pair(Alignment, CharUnits::Zero()); 14916 } 14917 case Stmt::UnaryOperatorClass: { 14918 auto *UO = cast<UnaryOperator>(E); 14919 if (UO->getOpcode() == UO_AddrOf) 14920 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14921 break; 14922 } 14923 case Stmt::BinaryOperatorClass: { 14924 auto *BO = cast<BinaryOperator>(E); 14925 auto Opcode = BO->getOpcode(); 14926 switch (Opcode) { 14927 default: 14928 break; 14929 case BO_Add: 14930 case BO_Sub: { 14931 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14932 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14933 std::swap(LHS, RHS); 14934 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14935 Ctx); 14936 } 14937 case BO_Comma: 14938 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14939 } 14940 break; 14941 } 14942 } 14943 return llvm::None; 14944 } 14945 14946 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14947 // See if we can compute the alignment of a VarDecl and an offset from it. 14948 Optional<std::pair<CharUnits, CharUnits>> P = 14949 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14950 14951 if (P) 14952 return P->first.alignmentAtOffset(P->second); 14953 14954 // If that failed, return the type's alignment. 14955 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14956 } 14957 14958 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14959 /// pointer cast increases the alignment requirements. 14960 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14961 // This is actually a lot of work to potentially be doing on every 14962 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14963 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14964 return; 14965 14966 // Ignore dependent types. 14967 if (T->isDependentType() || Op->getType()->isDependentType()) 14968 return; 14969 14970 // Require that the destination be a pointer type. 14971 const PointerType *DestPtr = T->getAs<PointerType>(); 14972 if (!DestPtr) return; 14973 14974 // If the destination has alignment 1, we're done. 14975 QualType DestPointee = DestPtr->getPointeeType(); 14976 if (DestPointee->isIncompleteType()) return; 14977 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14978 if (DestAlign.isOne()) return; 14979 14980 // Require that the source be a pointer type. 14981 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14982 if (!SrcPtr) return; 14983 QualType SrcPointee = SrcPtr->getPointeeType(); 14984 14985 // Explicitly allow casts from cv void*. We already implicitly 14986 // allowed casts to cv void*, since they have alignment 1. 14987 // Also allow casts involving incomplete types, which implicitly 14988 // includes 'void'. 14989 if (SrcPointee->isIncompleteType()) return; 14990 14991 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14992 14993 if (SrcAlign >= DestAlign) return; 14994 14995 Diag(TRange.getBegin(), diag::warn_cast_align) 14996 << Op->getType() << T 14997 << static_cast<unsigned>(SrcAlign.getQuantity()) 14998 << static_cast<unsigned>(DestAlign.getQuantity()) 14999 << TRange << Op->getSourceRange(); 15000 } 15001 15002 /// Check whether this array fits the idiom of a size-one tail padded 15003 /// array member of a struct. 15004 /// 15005 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 15006 /// commonly used to emulate flexible arrays in C89 code. 15007 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 15008 const NamedDecl *ND) { 15009 if (Size != 1 || !ND) return false; 15010 15011 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 15012 if (!FD) return false; 15013 15014 // Don't consider sizes resulting from macro expansions or template argument 15015 // substitution to form C89 tail-padded arrays. 15016 15017 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 15018 while (TInfo) { 15019 TypeLoc TL = TInfo->getTypeLoc(); 15020 // Look through typedefs. 15021 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 15022 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 15023 TInfo = TDL->getTypeSourceInfo(); 15024 continue; 15025 } 15026 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 15027 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 15028 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 15029 return false; 15030 } 15031 break; 15032 } 15033 15034 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 15035 if (!RD) return false; 15036 if (RD->isUnion()) return false; 15037 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15038 if (!CRD->isStandardLayout()) return false; 15039 } 15040 15041 // See if this is the last field decl in the record. 15042 const Decl *D = FD; 15043 while ((D = D->getNextDeclInContext())) 15044 if (isa<FieldDecl>(D)) 15045 return false; 15046 return true; 15047 } 15048 15049 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15050 const ArraySubscriptExpr *ASE, 15051 bool AllowOnePastEnd, bool IndexNegated) { 15052 // Already diagnosed by the constant evaluator. 15053 if (isConstantEvaluated()) 15054 return; 15055 15056 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15057 if (IndexExpr->isValueDependent()) 15058 return; 15059 15060 const Type *EffectiveType = 15061 BaseExpr->getType()->getPointeeOrArrayElementType(); 15062 BaseExpr = BaseExpr->IgnoreParenCasts(); 15063 const ConstantArrayType *ArrayTy = 15064 Context.getAsConstantArrayType(BaseExpr->getType()); 15065 15066 const Type *BaseType = 15067 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15068 bool IsUnboundedArray = (BaseType == nullptr); 15069 if (EffectiveType->isDependentType() || 15070 (!IsUnboundedArray && BaseType->isDependentType())) 15071 return; 15072 15073 Expr::EvalResult Result; 15074 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15075 return; 15076 15077 llvm::APSInt index = Result.Val.getInt(); 15078 if (IndexNegated) { 15079 index.setIsUnsigned(false); 15080 index = -index; 15081 } 15082 15083 const NamedDecl *ND = nullptr; 15084 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15085 ND = DRE->getDecl(); 15086 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15087 ND = ME->getMemberDecl(); 15088 15089 if (IsUnboundedArray) { 15090 if (index.isUnsigned() || !index.isNegative()) { 15091 const auto &ASTC = getASTContext(); 15092 unsigned AddrBits = 15093 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15094 EffectiveType->getCanonicalTypeInternal())); 15095 if (index.getBitWidth() < AddrBits) 15096 index = index.zext(AddrBits); 15097 Optional<CharUnits> ElemCharUnits = 15098 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15099 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15100 // pointer) bounds-checking isn't meaningful. 15101 if (!ElemCharUnits) 15102 return; 15103 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15104 // If index has more active bits than address space, we already know 15105 // we have a bounds violation to warn about. Otherwise, compute 15106 // address of (index + 1)th element, and warn about bounds violation 15107 // only if that address exceeds address space. 15108 if (index.getActiveBits() <= AddrBits) { 15109 bool Overflow; 15110 llvm::APInt Product(index); 15111 Product += 1; 15112 Product = Product.umul_ov(ElemBytes, Overflow); 15113 if (!Overflow && Product.getActiveBits() <= AddrBits) 15114 return; 15115 } 15116 15117 // Need to compute max possible elements in address space, since that 15118 // is included in diag message. 15119 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15120 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15121 MaxElems += 1; 15122 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15123 MaxElems = MaxElems.udiv(ElemBytes); 15124 15125 unsigned DiagID = 15126 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15127 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15128 15129 // Diag message shows element size in bits and in "bytes" (platform- 15130 // dependent CharUnits) 15131 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15132 PDiag(DiagID) 15133 << toString(index, 10, true) << AddrBits 15134 << (unsigned)ASTC.toBits(*ElemCharUnits) 15135 << toString(ElemBytes, 10, false) 15136 << toString(MaxElems, 10, false) 15137 << (unsigned)MaxElems.getLimitedValue(~0U) 15138 << IndexExpr->getSourceRange()); 15139 15140 if (!ND) { 15141 // Try harder to find a NamedDecl to point at in the note. 15142 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15143 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15144 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15145 ND = DRE->getDecl(); 15146 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15147 ND = ME->getMemberDecl(); 15148 } 15149 15150 if (ND) 15151 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15152 PDiag(diag::note_array_declared_here) << ND); 15153 } 15154 return; 15155 } 15156 15157 if (index.isUnsigned() || !index.isNegative()) { 15158 // It is possible that the type of the base expression after 15159 // IgnoreParenCasts is incomplete, even though the type of the base 15160 // expression before IgnoreParenCasts is complete (see PR39746 for an 15161 // example). In this case we have no information about whether the array 15162 // access exceeds the array bounds. However we can still diagnose an array 15163 // access which precedes the array bounds. 15164 if (BaseType->isIncompleteType()) 15165 return; 15166 15167 llvm::APInt size = ArrayTy->getSize(); 15168 if (!size.isStrictlyPositive()) 15169 return; 15170 15171 if (BaseType != EffectiveType) { 15172 // Make sure we're comparing apples to apples when comparing index to size 15173 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15174 uint64_t array_typesize = Context.getTypeSize(BaseType); 15175 // Handle ptrarith_typesize being zero, such as when casting to void* 15176 if (!ptrarith_typesize) ptrarith_typesize = 1; 15177 if (ptrarith_typesize != array_typesize) { 15178 // There's a cast to a different size type involved 15179 uint64_t ratio = array_typesize / ptrarith_typesize; 15180 // TODO: Be smarter about handling cases where array_typesize is not a 15181 // multiple of ptrarith_typesize 15182 if (ptrarith_typesize * ratio == array_typesize) 15183 size *= llvm::APInt(size.getBitWidth(), ratio); 15184 } 15185 } 15186 15187 if (size.getBitWidth() > index.getBitWidth()) 15188 index = index.zext(size.getBitWidth()); 15189 else if (size.getBitWidth() < index.getBitWidth()) 15190 size = size.zext(index.getBitWidth()); 15191 15192 // For array subscripting the index must be less than size, but for pointer 15193 // arithmetic also allow the index (offset) to be equal to size since 15194 // computing the next address after the end of the array is legal and 15195 // commonly done e.g. in C++ iterators and range-based for loops. 15196 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15197 return; 15198 15199 // Also don't warn for arrays of size 1 which are members of some 15200 // structure. These are often used to approximate flexible arrays in C89 15201 // code. 15202 if (IsTailPaddedMemberArray(*this, size, ND)) 15203 return; 15204 15205 // Suppress the warning if the subscript expression (as identified by the 15206 // ']' location) and the index expression are both from macro expansions 15207 // within a system header. 15208 if (ASE) { 15209 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15210 ASE->getRBracketLoc()); 15211 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15212 SourceLocation IndexLoc = 15213 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15214 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15215 return; 15216 } 15217 } 15218 15219 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15220 : diag::warn_ptr_arith_exceeds_bounds; 15221 15222 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15223 PDiag(DiagID) << toString(index, 10, true) 15224 << toString(size, 10, true) 15225 << (unsigned)size.getLimitedValue(~0U) 15226 << IndexExpr->getSourceRange()); 15227 } else { 15228 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15229 if (!ASE) { 15230 DiagID = diag::warn_ptr_arith_precedes_bounds; 15231 if (index.isNegative()) index = -index; 15232 } 15233 15234 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15235 PDiag(DiagID) << toString(index, 10, true) 15236 << IndexExpr->getSourceRange()); 15237 } 15238 15239 if (!ND) { 15240 // Try harder to find a NamedDecl to point at in the note. 15241 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15242 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15243 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15244 ND = DRE->getDecl(); 15245 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15246 ND = ME->getMemberDecl(); 15247 } 15248 15249 if (ND) 15250 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15251 PDiag(diag::note_array_declared_here) << ND); 15252 } 15253 15254 void Sema::CheckArrayAccess(const Expr *expr) { 15255 int AllowOnePastEnd = 0; 15256 while (expr) { 15257 expr = expr->IgnoreParenImpCasts(); 15258 switch (expr->getStmtClass()) { 15259 case Stmt::ArraySubscriptExprClass: { 15260 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15261 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15262 AllowOnePastEnd > 0); 15263 expr = ASE->getBase(); 15264 break; 15265 } 15266 case Stmt::MemberExprClass: { 15267 expr = cast<MemberExpr>(expr)->getBase(); 15268 break; 15269 } 15270 case Stmt::OMPArraySectionExprClass: { 15271 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15272 if (ASE->getLowerBound()) 15273 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15274 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15275 return; 15276 } 15277 case Stmt::UnaryOperatorClass: { 15278 // Only unwrap the * and & unary operators 15279 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15280 expr = UO->getSubExpr(); 15281 switch (UO->getOpcode()) { 15282 case UO_AddrOf: 15283 AllowOnePastEnd++; 15284 break; 15285 case UO_Deref: 15286 AllowOnePastEnd--; 15287 break; 15288 default: 15289 return; 15290 } 15291 break; 15292 } 15293 case Stmt::ConditionalOperatorClass: { 15294 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15295 if (const Expr *lhs = cond->getLHS()) 15296 CheckArrayAccess(lhs); 15297 if (const Expr *rhs = cond->getRHS()) 15298 CheckArrayAccess(rhs); 15299 return; 15300 } 15301 case Stmt::CXXOperatorCallExprClass: { 15302 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15303 for (const auto *Arg : OCE->arguments()) 15304 CheckArrayAccess(Arg); 15305 return; 15306 } 15307 default: 15308 return; 15309 } 15310 } 15311 } 15312 15313 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15314 15315 namespace { 15316 15317 struct RetainCycleOwner { 15318 VarDecl *Variable = nullptr; 15319 SourceRange Range; 15320 SourceLocation Loc; 15321 bool Indirect = false; 15322 15323 RetainCycleOwner() = default; 15324 15325 void setLocsFrom(Expr *e) { 15326 Loc = e->getExprLoc(); 15327 Range = e->getSourceRange(); 15328 } 15329 }; 15330 15331 } // namespace 15332 15333 /// Consider whether capturing the given variable can possibly lead to 15334 /// a retain cycle. 15335 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15336 // In ARC, it's captured strongly iff the variable has __strong 15337 // lifetime. In MRR, it's captured strongly if the variable is 15338 // __block and has an appropriate type. 15339 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15340 return false; 15341 15342 owner.Variable = var; 15343 if (ref) 15344 owner.setLocsFrom(ref); 15345 return true; 15346 } 15347 15348 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15349 while (true) { 15350 e = e->IgnoreParens(); 15351 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15352 switch (cast->getCastKind()) { 15353 case CK_BitCast: 15354 case CK_LValueBitCast: 15355 case CK_LValueToRValue: 15356 case CK_ARCReclaimReturnedObject: 15357 e = cast->getSubExpr(); 15358 continue; 15359 15360 default: 15361 return false; 15362 } 15363 } 15364 15365 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15366 ObjCIvarDecl *ivar = ref->getDecl(); 15367 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15368 return false; 15369 15370 // Try to find a retain cycle in the base. 15371 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15372 return false; 15373 15374 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15375 owner.Indirect = true; 15376 return true; 15377 } 15378 15379 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15380 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15381 if (!var) return false; 15382 return considerVariable(var, ref, owner); 15383 } 15384 15385 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15386 if (member->isArrow()) return false; 15387 15388 // Don't count this as an indirect ownership. 15389 e = member->getBase(); 15390 continue; 15391 } 15392 15393 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15394 // Only pay attention to pseudo-objects on property references. 15395 ObjCPropertyRefExpr *pre 15396 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15397 ->IgnoreParens()); 15398 if (!pre) return false; 15399 if (pre->isImplicitProperty()) return false; 15400 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15401 if (!property->isRetaining() && 15402 !(property->getPropertyIvarDecl() && 15403 property->getPropertyIvarDecl()->getType() 15404 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15405 return false; 15406 15407 owner.Indirect = true; 15408 if (pre->isSuperReceiver()) { 15409 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15410 if (!owner.Variable) 15411 return false; 15412 owner.Loc = pre->getLocation(); 15413 owner.Range = pre->getSourceRange(); 15414 return true; 15415 } 15416 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15417 ->getSourceExpr()); 15418 continue; 15419 } 15420 15421 // Array ivars? 15422 15423 return false; 15424 } 15425 } 15426 15427 namespace { 15428 15429 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15430 ASTContext &Context; 15431 VarDecl *Variable; 15432 Expr *Capturer = nullptr; 15433 bool VarWillBeReased = false; 15434 15435 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15436 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15437 Context(Context), Variable(variable) {} 15438 15439 void VisitDeclRefExpr(DeclRefExpr *ref) { 15440 if (ref->getDecl() == Variable && !Capturer) 15441 Capturer = ref; 15442 } 15443 15444 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15445 if (Capturer) return; 15446 Visit(ref->getBase()); 15447 if (Capturer && ref->isFreeIvar()) 15448 Capturer = ref; 15449 } 15450 15451 void VisitBlockExpr(BlockExpr *block) { 15452 // Look inside nested blocks 15453 if (block->getBlockDecl()->capturesVariable(Variable)) 15454 Visit(block->getBlockDecl()->getBody()); 15455 } 15456 15457 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15458 if (Capturer) return; 15459 if (OVE->getSourceExpr()) 15460 Visit(OVE->getSourceExpr()); 15461 } 15462 15463 void VisitBinaryOperator(BinaryOperator *BinOp) { 15464 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15465 return; 15466 Expr *LHS = BinOp->getLHS(); 15467 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15468 if (DRE->getDecl() != Variable) 15469 return; 15470 if (Expr *RHS = BinOp->getRHS()) { 15471 RHS = RHS->IgnoreParenCasts(); 15472 Optional<llvm::APSInt> Value; 15473 VarWillBeReased = 15474 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15475 *Value == 0); 15476 } 15477 } 15478 } 15479 }; 15480 15481 } // namespace 15482 15483 /// Check whether the given argument is a block which captures a 15484 /// variable. 15485 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15486 assert(owner.Variable && owner.Loc.isValid()); 15487 15488 e = e->IgnoreParenCasts(); 15489 15490 // Look through [^{...} copy] and Block_copy(^{...}). 15491 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15492 Selector Cmd = ME->getSelector(); 15493 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15494 e = ME->getInstanceReceiver(); 15495 if (!e) 15496 return nullptr; 15497 e = e->IgnoreParenCasts(); 15498 } 15499 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15500 if (CE->getNumArgs() == 1) { 15501 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15502 if (Fn) { 15503 const IdentifierInfo *FnI = Fn->getIdentifier(); 15504 if (FnI && FnI->isStr("_Block_copy")) { 15505 e = CE->getArg(0)->IgnoreParenCasts(); 15506 } 15507 } 15508 } 15509 } 15510 15511 BlockExpr *block = dyn_cast<BlockExpr>(e); 15512 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15513 return nullptr; 15514 15515 FindCaptureVisitor visitor(S.Context, owner.Variable); 15516 visitor.Visit(block->getBlockDecl()->getBody()); 15517 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15518 } 15519 15520 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15521 RetainCycleOwner &owner) { 15522 assert(capturer); 15523 assert(owner.Variable && owner.Loc.isValid()); 15524 15525 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15526 << owner.Variable << capturer->getSourceRange(); 15527 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15528 << owner.Indirect << owner.Range; 15529 } 15530 15531 /// Check for a keyword selector that starts with the word 'add' or 15532 /// 'set'. 15533 static bool isSetterLikeSelector(Selector sel) { 15534 if (sel.isUnarySelector()) return false; 15535 15536 StringRef str = sel.getNameForSlot(0); 15537 while (!str.empty() && str.front() == '_') str = str.substr(1); 15538 if (str.startswith("set")) 15539 str = str.substr(3); 15540 else if (str.startswith("add")) { 15541 // Specially allow 'addOperationWithBlock:'. 15542 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15543 return false; 15544 str = str.substr(3); 15545 } 15546 else 15547 return false; 15548 15549 if (str.empty()) return true; 15550 return !isLowercase(str.front()); 15551 } 15552 15553 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15554 ObjCMessageExpr *Message) { 15555 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15556 Message->getReceiverInterface(), 15557 NSAPI::ClassId_NSMutableArray); 15558 if (!IsMutableArray) { 15559 return None; 15560 } 15561 15562 Selector Sel = Message->getSelector(); 15563 15564 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15565 S.NSAPIObj->getNSArrayMethodKind(Sel); 15566 if (!MKOpt) { 15567 return None; 15568 } 15569 15570 NSAPI::NSArrayMethodKind MK = *MKOpt; 15571 15572 switch (MK) { 15573 case NSAPI::NSMutableArr_addObject: 15574 case NSAPI::NSMutableArr_insertObjectAtIndex: 15575 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15576 return 0; 15577 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15578 return 1; 15579 15580 default: 15581 return None; 15582 } 15583 15584 return None; 15585 } 15586 15587 static 15588 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15589 ObjCMessageExpr *Message) { 15590 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15591 Message->getReceiverInterface(), 15592 NSAPI::ClassId_NSMutableDictionary); 15593 if (!IsMutableDictionary) { 15594 return None; 15595 } 15596 15597 Selector Sel = Message->getSelector(); 15598 15599 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15600 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15601 if (!MKOpt) { 15602 return None; 15603 } 15604 15605 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15606 15607 switch (MK) { 15608 case NSAPI::NSMutableDict_setObjectForKey: 15609 case NSAPI::NSMutableDict_setValueForKey: 15610 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15611 return 0; 15612 15613 default: 15614 return None; 15615 } 15616 15617 return None; 15618 } 15619 15620 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15621 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15622 Message->getReceiverInterface(), 15623 NSAPI::ClassId_NSMutableSet); 15624 15625 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15626 Message->getReceiverInterface(), 15627 NSAPI::ClassId_NSMutableOrderedSet); 15628 if (!IsMutableSet && !IsMutableOrderedSet) { 15629 return None; 15630 } 15631 15632 Selector Sel = Message->getSelector(); 15633 15634 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15635 if (!MKOpt) { 15636 return None; 15637 } 15638 15639 NSAPI::NSSetMethodKind MK = *MKOpt; 15640 15641 switch (MK) { 15642 case NSAPI::NSMutableSet_addObject: 15643 case NSAPI::NSOrderedSet_setObjectAtIndex: 15644 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15645 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15646 return 0; 15647 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15648 return 1; 15649 } 15650 15651 return None; 15652 } 15653 15654 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15655 if (!Message->isInstanceMessage()) { 15656 return; 15657 } 15658 15659 Optional<int> ArgOpt; 15660 15661 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15662 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15663 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15664 return; 15665 } 15666 15667 int ArgIndex = *ArgOpt; 15668 15669 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15670 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15671 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15672 } 15673 15674 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15675 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15676 if (ArgRE->isObjCSelfExpr()) { 15677 Diag(Message->getSourceRange().getBegin(), 15678 diag::warn_objc_circular_container) 15679 << ArgRE->getDecl() << StringRef("'super'"); 15680 } 15681 } 15682 } else { 15683 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15684 15685 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15686 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15687 } 15688 15689 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15690 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15691 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15692 ValueDecl *Decl = ReceiverRE->getDecl(); 15693 Diag(Message->getSourceRange().getBegin(), 15694 diag::warn_objc_circular_container) 15695 << Decl << Decl; 15696 if (!ArgRE->isObjCSelfExpr()) { 15697 Diag(Decl->getLocation(), 15698 diag::note_objc_circular_container_declared_here) 15699 << Decl; 15700 } 15701 } 15702 } 15703 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15704 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15705 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15706 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15707 Diag(Message->getSourceRange().getBegin(), 15708 diag::warn_objc_circular_container) 15709 << Decl << Decl; 15710 Diag(Decl->getLocation(), 15711 diag::note_objc_circular_container_declared_here) 15712 << Decl; 15713 } 15714 } 15715 } 15716 } 15717 } 15718 15719 /// Check a message send to see if it's likely to cause a retain cycle. 15720 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15721 // Only check instance methods whose selector looks like a setter. 15722 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15723 return; 15724 15725 // Try to find a variable that the receiver is strongly owned by. 15726 RetainCycleOwner owner; 15727 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15728 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15729 return; 15730 } else { 15731 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15732 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15733 owner.Loc = msg->getSuperLoc(); 15734 owner.Range = msg->getSuperLoc(); 15735 } 15736 15737 // Check whether the receiver is captured by any of the arguments. 15738 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15739 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15740 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15741 // noescape blocks should not be retained by the method. 15742 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15743 continue; 15744 return diagnoseRetainCycle(*this, capturer, owner); 15745 } 15746 } 15747 } 15748 15749 /// Check a property assign to see if it's likely to cause a retain cycle. 15750 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15751 RetainCycleOwner owner; 15752 if (!findRetainCycleOwner(*this, receiver, owner)) 15753 return; 15754 15755 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15756 diagnoseRetainCycle(*this, capturer, owner); 15757 } 15758 15759 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15760 RetainCycleOwner Owner; 15761 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15762 return; 15763 15764 // Because we don't have an expression for the variable, we have to set the 15765 // location explicitly here. 15766 Owner.Loc = Var->getLocation(); 15767 Owner.Range = Var->getSourceRange(); 15768 15769 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15770 diagnoseRetainCycle(*this, Capturer, Owner); 15771 } 15772 15773 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15774 Expr *RHS, bool isProperty) { 15775 // Check if RHS is an Objective-C object literal, which also can get 15776 // immediately zapped in a weak reference. Note that we explicitly 15777 // allow ObjCStringLiterals, since those are designed to never really die. 15778 RHS = RHS->IgnoreParenImpCasts(); 15779 15780 // This enum needs to match with the 'select' in 15781 // warn_objc_arc_literal_assign (off-by-1). 15782 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15783 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15784 return false; 15785 15786 S.Diag(Loc, diag::warn_arc_literal_assign) 15787 << (unsigned) Kind 15788 << (isProperty ? 0 : 1) 15789 << RHS->getSourceRange(); 15790 15791 return true; 15792 } 15793 15794 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15795 Qualifiers::ObjCLifetime LT, 15796 Expr *RHS, bool isProperty) { 15797 // Strip off any implicit cast added to get to the one ARC-specific. 15798 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15799 if (cast->getCastKind() == CK_ARCConsumeObject) { 15800 S.Diag(Loc, diag::warn_arc_retained_assign) 15801 << (LT == Qualifiers::OCL_ExplicitNone) 15802 << (isProperty ? 0 : 1) 15803 << RHS->getSourceRange(); 15804 return true; 15805 } 15806 RHS = cast->getSubExpr(); 15807 } 15808 15809 if (LT == Qualifiers::OCL_Weak && 15810 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15811 return true; 15812 15813 return false; 15814 } 15815 15816 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15817 QualType LHS, Expr *RHS) { 15818 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15819 15820 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15821 return false; 15822 15823 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15824 return true; 15825 15826 return false; 15827 } 15828 15829 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15830 Expr *LHS, Expr *RHS) { 15831 QualType LHSType; 15832 // PropertyRef on LHS type need be directly obtained from 15833 // its declaration as it has a PseudoType. 15834 ObjCPropertyRefExpr *PRE 15835 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15836 if (PRE && !PRE->isImplicitProperty()) { 15837 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15838 if (PD) 15839 LHSType = PD->getType(); 15840 } 15841 15842 if (LHSType.isNull()) 15843 LHSType = LHS->getType(); 15844 15845 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15846 15847 if (LT == Qualifiers::OCL_Weak) { 15848 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15849 getCurFunction()->markSafeWeakUse(LHS); 15850 } 15851 15852 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15853 return; 15854 15855 // FIXME. Check for other life times. 15856 if (LT != Qualifiers::OCL_None) 15857 return; 15858 15859 if (PRE) { 15860 if (PRE->isImplicitProperty()) 15861 return; 15862 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15863 if (!PD) 15864 return; 15865 15866 unsigned Attributes = PD->getPropertyAttributes(); 15867 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15868 // when 'assign' attribute was not explicitly specified 15869 // by user, ignore it and rely on property type itself 15870 // for lifetime info. 15871 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15872 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15873 LHSType->isObjCRetainableType()) 15874 return; 15875 15876 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15877 if (cast->getCastKind() == CK_ARCConsumeObject) { 15878 Diag(Loc, diag::warn_arc_retained_property_assign) 15879 << RHS->getSourceRange(); 15880 return; 15881 } 15882 RHS = cast->getSubExpr(); 15883 } 15884 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15885 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15886 return; 15887 } 15888 } 15889 } 15890 15891 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15892 15893 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15894 SourceLocation StmtLoc, 15895 const NullStmt *Body) { 15896 // Do not warn if the body is a macro that expands to nothing, e.g: 15897 // 15898 // #define CALL(x) 15899 // if (condition) 15900 // CALL(0); 15901 if (Body->hasLeadingEmptyMacro()) 15902 return false; 15903 15904 // Get line numbers of statement and body. 15905 bool StmtLineInvalid; 15906 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15907 &StmtLineInvalid); 15908 if (StmtLineInvalid) 15909 return false; 15910 15911 bool BodyLineInvalid; 15912 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15913 &BodyLineInvalid); 15914 if (BodyLineInvalid) 15915 return false; 15916 15917 // Warn if null statement and body are on the same line. 15918 if (StmtLine != BodyLine) 15919 return false; 15920 15921 return true; 15922 } 15923 15924 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15925 const Stmt *Body, 15926 unsigned DiagID) { 15927 // Since this is a syntactic check, don't emit diagnostic for template 15928 // instantiations, this just adds noise. 15929 if (CurrentInstantiationScope) 15930 return; 15931 15932 // The body should be a null statement. 15933 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15934 if (!NBody) 15935 return; 15936 15937 // Do the usual checks. 15938 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15939 return; 15940 15941 Diag(NBody->getSemiLoc(), DiagID); 15942 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15943 } 15944 15945 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15946 const Stmt *PossibleBody) { 15947 assert(!CurrentInstantiationScope); // Ensured by caller 15948 15949 SourceLocation StmtLoc; 15950 const Stmt *Body; 15951 unsigned DiagID; 15952 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15953 StmtLoc = FS->getRParenLoc(); 15954 Body = FS->getBody(); 15955 DiagID = diag::warn_empty_for_body; 15956 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15957 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15958 Body = WS->getBody(); 15959 DiagID = diag::warn_empty_while_body; 15960 } else 15961 return; // Neither `for' nor `while'. 15962 15963 // The body should be a null statement. 15964 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15965 if (!NBody) 15966 return; 15967 15968 // Skip expensive checks if diagnostic is disabled. 15969 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15970 return; 15971 15972 // Do the usual checks. 15973 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15974 return; 15975 15976 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15977 // noise level low, emit diagnostics only if for/while is followed by a 15978 // CompoundStmt, e.g.: 15979 // for (int i = 0; i < n; i++); 15980 // { 15981 // a(i); 15982 // } 15983 // or if for/while is followed by a statement with more indentation 15984 // than for/while itself: 15985 // for (int i = 0; i < n; i++); 15986 // a(i); 15987 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15988 if (!ProbableTypo) { 15989 bool BodyColInvalid; 15990 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15991 PossibleBody->getBeginLoc(), &BodyColInvalid); 15992 if (BodyColInvalid) 15993 return; 15994 15995 bool StmtColInvalid; 15996 unsigned StmtCol = 15997 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15998 if (StmtColInvalid) 15999 return; 16000 16001 if (BodyCol > StmtCol) 16002 ProbableTypo = true; 16003 } 16004 16005 if (ProbableTypo) { 16006 Diag(NBody->getSemiLoc(), DiagID); 16007 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16008 } 16009 } 16010 16011 //===--- CHECK: Warn on self move with std::move. -------------------------===// 16012 16013 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 16014 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 16015 SourceLocation OpLoc) { 16016 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 16017 return; 16018 16019 if (inTemplateInstantiation()) 16020 return; 16021 16022 // Strip parens and casts away. 16023 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 16024 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 16025 16026 // Check for a call expression 16027 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 16028 if (!CE || CE->getNumArgs() != 1) 16029 return; 16030 16031 // Check for a call to std::move 16032 if (!CE->isCallToStdMove()) 16033 return; 16034 16035 // Get argument from std::move 16036 RHSExpr = CE->getArg(0); 16037 16038 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 16039 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 16040 16041 // Two DeclRefExpr's, check that the decls are the same. 16042 if (LHSDeclRef && RHSDeclRef) { 16043 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16044 return; 16045 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16046 RHSDeclRef->getDecl()->getCanonicalDecl()) 16047 return; 16048 16049 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16050 << LHSExpr->getSourceRange() 16051 << RHSExpr->getSourceRange(); 16052 return; 16053 } 16054 16055 // Member variables require a different approach to check for self moves. 16056 // MemberExpr's are the same if every nested MemberExpr refers to the same 16057 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16058 // the base Expr's are CXXThisExpr's. 16059 const Expr *LHSBase = LHSExpr; 16060 const Expr *RHSBase = RHSExpr; 16061 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16062 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16063 if (!LHSME || !RHSME) 16064 return; 16065 16066 while (LHSME && RHSME) { 16067 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16068 RHSME->getMemberDecl()->getCanonicalDecl()) 16069 return; 16070 16071 LHSBase = LHSME->getBase(); 16072 RHSBase = RHSME->getBase(); 16073 LHSME = dyn_cast<MemberExpr>(LHSBase); 16074 RHSME = dyn_cast<MemberExpr>(RHSBase); 16075 } 16076 16077 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16078 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16079 if (LHSDeclRef && RHSDeclRef) { 16080 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16081 return; 16082 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16083 RHSDeclRef->getDecl()->getCanonicalDecl()) 16084 return; 16085 16086 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16087 << LHSExpr->getSourceRange() 16088 << RHSExpr->getSourceRange(); 16089 return; 16090 } 16091 16092 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16093 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16094 << LHSExpr->getSourceRange() 16095 << RHSExpr->getSourceRange(); 16096 } 16097 16098 //===--- Layout compatibility ----------------------------------------------// 16099 16100 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16101 16102 /// Check if two enumeration types are layout-compatible. 16103 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16104 // C++11 [dcl.enum] p8: 16105 // Two enumeration types are layout-compatible if they have the same 16106 // underlying type. 16107 return ED1->isComplete() && ED2->isComplete() && 16108 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16109 } 16110 16111 /// Check if two fields are layout-compatible. 16112 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16113 FieldDecl *Field2) { 16114 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16115 return false; 16116 16117 if (Field1->isBitField() != Field2->isBitField()) 16118 return false; 16119 16120 if (Field1->isBitField()) { 16121 // Make sure that the bit-fields are the same length. 16122 unsigned Bits1 = Field1->getBitWidthValue(C); 16123 unsigned Bits2 = Field2->getBitWidthValue(C); 16124 16125 if (Bits1 != Bits2) 16126 return false; 16127 } 16128 16129 return true; 16130 } 16131 16132 /// Check if two standard-layout structs are layout-compatible. 16133 /// (C++11 [class.mem] p17) 16134 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16135 RecordDecl *RD2) { 16136 // If both records are C++ classes, check that base classes match. 16137 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16138 // If one of records is a CXXRecordDecl we are in C++ mode, 16139 // thus the other one is a CXXRecordDecl, too. 16140 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16141 // Check number of base classes. 16142 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16143 return false; 16144 16145 // Check the base classes. 16146 for (CXXRecordDecl::base_class_const_iterator 16147 Base1 = D1CXX->bases_begin(), 16148 BaseEnd1 = D1CXX->bases_end(), 16149 Base2 = D2CXX->bases_begin(); 16150 Base1 != BaseEnd1; 16151 ++Base1, ++Base2) { 16152 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16153 return false; 16154 } 16155 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16156 // If only RD2 is a C++ class, it should have zero base classes. 16157 if (D2CXX->getNumBases() > 0) 16158 return false; 16159 } 16160 16161 // Check the fields. 16162 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16163 Field2End = RD2->field_end(), 16164 Field1 = RD1->field_begin(), 16165 Field1End = RD1->field_end(); 16166 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16167 if (!isLayoutCompatible(C, *Field1, *Field2)) 16168 return false; 16169 } 16170 if (Field1 != Field1End || Field2 != Field2End) 16171 return false; 16172 16173 return true; 16174 } 16175 16176 /// Check if two standard-layout unions are layout-compatible. 16177 /// (C++11 [class.mem] p18) 16178 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16179 RecordDecl *RD2) { 16180 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16181 for (auto *Field2 : RD2->fields()) 16182 UnmatchedFields.insert(Field2); 16183 16184 for (auto *Field1 : RD1->fields()) { 16185 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16186 I = UnmatchedFields.begin(), 16187 E = UnmatchedFields.end(); 16188 16189 for ( ; I != E; ++I) { 16190 if (isLayoutCompatible(C, Field1, *I)) { 16191 bool Result = UnmatchedFields.erase(*I); 16192 (void) Result; 16193 assert(Result); 16194 break; 16195 } 16196 } 16197 if (I == E) 16198 return false; 16199 } 16200 16201 return UnmatchedFields.empty(); 16202 } 16203 16204 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16205 RecordDecl *RD2) { 16206 if (RD1->isUnion() != RD2->isUnion()) 16207 return false; 16208 16209 if (RD1->isUnion()) 16210 return isLayoutCompatibleUnion(C, RD1, RD2); 16211 else 16212 return isLayoutCompatibleStruct(C, RD1, RD2); 16213 } 16214 16215 /// Check if two types are layout-compatible in C++11 sense. 16216 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16217 if (T1.isNull() || T2.isNull()) 16218 return false; 16219 16220 // C++11 [basic.types] p11: 16221 // If two types T1 and T2 are the same type, then T1 and T2 are 16222 // layout-compatible types. 16223 if (C.hasSameType(T1, T2)) 16224 return true; 16225 16226 T1 = T1.getCanonicalType().getUnqualifiedType(); 16227 T2 = T2.getCanonicalType().getUnqualifiedType(); 16228 16229 const Type::TypeClass TC1 = T1->getTypeClass(); 16230 const Type::TypeClass TC2 = T2->getTypeClass(); 16231 16232 if (TC1 != TC2) 16233 return false; 16234 16235 if (TC1 == Type::Enum) { 16236 return isLayoutCompatible(C, 16237 cast<EnumType>(T1)->getDecl(), 16238 cast<EnumType>(T2)->getDecl()); 16239 } else if (TC1 == Type::Record) { 16240 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16241 return false; 16242 16243 return isLayoutCompatible(C, 16244 cast<RecordType>(T1)->getDecl(), 16245 cast<RecordType>(T2)->getDecl()); 16246 } 16247 16248 return false; 16249 } 16250 16251 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16252 16253 /// Given a type tag expression find the type tag itself. 16254 /// 16255 /// \param TypeExpr Type tag expression, as it appears in user's code. 16256 /// 16257 /// \param VD Declaration of an identifier that appears in a type tag. 16258 /// 16259 /// \param MagicValue Type tag magic value. 16260 /// 16261 /// \param isConstantEvaluated whether the evalaution should be performed in 16262 16263 /// constant context. 16264 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16265 const ValueDecl **VD, uint64_t *MagicValue, 16266 bool isConstantEvaluated) { 16267 while(true) { 16268 if (!TypeExpr) 16269 return false; 16270 16271 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16272 16273 switch (TypeExpr->getStmtClass()) { 16274 case Stmt::UnaryOperatorClass: { 16275 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16276 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16277 TypeExpr = UO->getSubExpr(); 16278 continue; 16279 } 16280 return false; 16281 } 16282 16283 case Stmt::DeclRefExprClass: { 16284 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16285 *VD = DRE->getDecl(); 16286 return true; 16287 } 16288 16289 case Stmt::IntegerLiteralClass: { 16290 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16291 llvm::APInt MagicValueAPInt = IL->getValue(); 16292 if (MagicValueAPInt.getActiveBits() <= 64) { 16293 *MagicValue = MagicValueAPInt.getZExtValue(); 16294 return true; 16295 } else 16296 return false; 16297 } 16298 16299 case Stmt::BinaryConditionalOperatorClass: 16300 case Stmt::ConditionalOperatorClass: { 16301 const AbstractConditionalOperator *ACO = 16302 cast<AbstractConditionalOperator>(TypeExpr); 16303 bool Result; 16304 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16305 isConstantEvaluated)) { 16306 if (Result) 16307 TypeExpr = ACO->getTrueExpr(); 16308 else 16309 TypeExpr = ACO->getFalseExpr(); 16310 continue; 16311 } 16312 return false; 16313 } 16314 16315 case Stmt::BinaryOperatorClass: { 16316 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16317 if (BO->getOpcode() == BO_Comma) { 16318 TypeExpr = BO->getRHS(); 16319 continue; 16320 } 16321 return false; 16322 } 16323 16324 default: 16325 return false; 16326 } 16327 } 16328 } 16329 16330 /// Retrieve the C type corresponding to type tag TypeExpr. 16331 /// 16332 /// \param TypeExpr Expression that specifies a type tag. 16333 /// 16334 /// \param MagicValues Registered magic values. 16335 /// 16336 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16337 /// kind. 16338 /// 16339 /// \param TypeInfo Information about the corresponding C type. 16340 /// 16341 /// \param isConstantEvaluated whether the evalaution should be performed in 16342 /// constant context. 16343 /// 16344 /// \returns true if the corresponding C type was found. 16345 static bool GetMatchingCType( 16346 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16347 const ASTContext &Ctx, 16348 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16349 *MagicValues, 16350 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16351 bool isConstantEvaluated) { 16352 FoundWrongKind = false; 16353 16354 // Variable declaration that has type_tag_for_datatype attribute. 16355 const ValueDecl *VD = nullptr; 16356 16357 uint64_t MagicValue; 16358 16359 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16360 return false; 16361 16362 if (VD) { 16363 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16364 if (I->getArgumentKind() != ArgumentKind) { 16365 FoundWrongKind = true; 16366 return false; 16367 } 16368 TypeInfo.Type = I->getMatchingCType(); 16369 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16370 TypeInfo.MustBeNull = I->getMustBeNull(); 16371 return true; 16372 } 16373 return false; 16374 } 16375 16376 if (!MagicValues) 16377 return false; 16378 16379 llvm::DenseMap<Sema::TypeTagMagicValue, 16380 Sema::TypeTagData>::const_iterator I = 16381 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16382 if (I == MagicValues->end()) 16383 return false; 16384 16385 TypeInfo = I->second; 16386 return true; 16387 } 16388 16389 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16390 uint64_t MagicValue, QualType Type, 16391 bool LayoutCompatible, 16392 bool MustBeNull) { 16393 if (!TypeTagForDatatypeMagicValues) 16394 TypeTagForDatatypeMagicValues.reset( 16395 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16396 16397 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16398 (*TypeTagForDatatypeMagicValues)[Magic] = 16399 TypeTagData(Type, LayoutCompatible, MustBeNull); 16400 } 16401 16402 static bool IsSameCharType(QualType T1, QualType T2) { 16403 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16404 if (!BT1) 16405 return false; 16406 16407 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16408 if (!BT2) 16409 return false; 16410 16411 BuiltinType::Kind T1Kind = BT1->getKind(); 16412 BuiltinType::Kind T2Kind = BT2->getKind(); 16413 16414 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16415 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16416 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16417 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16418 } 16419 16420 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16421 const ArrayRef<const Expr *> ExprArgs, 16422 SourceLocation CallSiteLoc) { 16423 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16424 bool IsPointerAttr = Attr->getIsPointer(); 16425 16426 // Retrieve the argument representing the 'type_tag'. 16427 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16428 if (TypeTagIdxAST >= ExprArgs.size()) { 16429 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16430 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16431 return; 16432 } 16433 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16434 bool FoundWrongKind; 16435 TypeTagData TypeInfo; 16436 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16437 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16438 TypeInfo, isConstantEvaluated())) { 16439 if (FoundWrongKind) 16440 Diag(TypeTagExpr->getExprLoc(), 16441 diag::warn_type_tag_for_datatype_wrong_kind) 16442 << TypeTagExpr->getSourceRange(); 16443 return; 16444 } 16445 16446 // Retrieve the argument representing the 'arg_idx'. 16447 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16448 if (ArgumentIdxAST >= ExprArgs.size()) { 16449 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16450 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16451 return; 16452 } 16453 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16454 if (IsPointerAttr) { 16455 // Skip implicit cast of pointer to `void *' (as a function argument). 16456 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16457 if (ICE->getType()->isVoidPointerType() && 16458 ICE->getCastKind() == CK_BitCast) 16459 ArgumentExpr = ICE->getSubExpr(); 16460 } 16461 QualType ArgumentType = ArgumentExpr->getType(); 16462 16463 // Passing a `void*' pointer shouldn't trigger a warning. 16464 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16465 return; 16466 16467 if (TypeInfo.MustBeNull) { 16468 // Type tag with matching void type requires a null pointer. 16469 if (!ArgumentExpr->isNullPointerConstant(Context, 16470 Expr::NPC_ValueDependentIsNotNull)) { 16471 Diag(ArgumentExpr->getExprLoc(), 16472 diag::warn_type_safety_null_pointer_required) 16473 << ArgumentKind->getName() 16474 << ArgumentExpr->getSourceRange() 16475 << TypeTagExpr->getSourceRange(); 16476 } 16477 return; 16478 } 16479 16480 QualType RequiredType = TypeInfo.Type; 16481 if (IsPointerAttr) 16482 RequiredType = Context.getPointerType(RequiredType); 16483 16484 bool mismatch = false; 16485 if (!TypeInfo.LayoutCompatible) { 16486 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16487 16488 // C++11 [basic.fundamental] p1: 16489 // Plain char, signed char, and unsigned char are three distinct types. 16490 // 16491 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16492 // char' depending on the current char signedness mode. 16493 if (mismatch) 16494 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16495 RequiredType->getPointeeType())) || 16496 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16497 mismatch = false; 16498 } else 16499 if (IsPointerAttr) 16500 mismatch = !isLayoutCompatible(Context, 16501 ArgumentType->getPointeeType(), 16502 RequiredType->getPointeeType()); 16503 else 16504 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16505 16506 if (mismatch) 16507 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16508 << ArgumentType << ArgumentKind 16509 << TypeInfo.LayoutCompatible << RequiredType 16510 << ArgumentExpr->getSourceRange() 16511 << TypeTagExpr->getSourceRange(); 16512 } 16513 16514 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16515 CharUnits Alignment) { 16516 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16517 } 16518 16519 void Sema::DiagnoseMisalignedMembers() { 16520 for (MisalignedMember &m : MisalignedMembers) { 16521 const NamedDecl *ND = m.RD; 16522 if (ND->getName().empty()) { 16523 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16524 ND = TD; 16525 } 16526 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16527 << m.MD << ND << m.E->getSourceRange(); 16528 } 16529 MisalignedMembers.clear(); 16530 } 16531 16532 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16533 E = E->IgnoreParens(); 16534 if (!T->isPointerType() && !T->isIntegerType()) 16535 return; 16536 if (isa<UnaryOperator>(E) && 16537 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16538 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16539 if (isa<MemberExpr>(Op)) { 16540 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16541 if (MA != MisalignedMembers.end() && 16542 (T->isIntegerType() || 16543 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16544 Context.getTypeAlignInChars( 16545 T->getPointeeType()) <= MA->Alignment)))) 16546 MisalignedMembers.erase(MA); 16547 } 16548 } 16549 } 16550 16551 void Sema::RefersToMemberWithReducedAlignment( 16552 Expr *E, 16553 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16554 Action) { 16555 const auto *ME = dyn_cast<MemberExpr>(E); 16556 if (!ME) 16557 return; 16558 16559 // No need to check expressions with an __unaligned-qualified type. 16560 if (E->getType().getQualifiers().hasUnaligned()) 16561 return; 16562 16563 // For a chain of MemberExpr like "a.b.c.d" this list 16564 // will keep FieldDecl's like [d, c, b]. 16565 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16566 const MemberExpr *TopME = nullptr; 16567 bool AnyIsPacked = false; 16568 do { 16569 QualType BaseType = ME->getBase()->getType(); 16570 if (BaseType->isDependentType()) 16571 return; 16572 if (ME->isArrow()) 16573 BaseType = BaseType->getPointeeType(); 16574 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16575 if (RD->isInvalidDecl()) 16576 return; 16577 16578 ValueDecl *MD = ME->getMemberDecl(); 16579 auto *FD = dyn_cast<FieldDecl>(MD); 16580 // We do not care about non-data members. 16581 if (!FD || FD->isInvalidDecl()) 16582 return; 16583 16584 AnyIsPacked = 16585 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16586 ReverseMemberChain.push_back(FD); 16587 16588 TopME = ME; 16589 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16590 } while (ME); 16591 assert(TopME && "We did not compute a topmost MemberExpr!"); 16592 16593 // Not the scope of this diagnostic. 16594 if (!AnyIsPacked) 16595 return; 16596 16597 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16598 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16599 // TODO: The innermost base of the member expression may be too complicated. 16600 // For now, just disregard these cases. This is left for future 16601 // improvement. 16602 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16603 return; 16604 16605 // Alignment expected by the whole expression. 16606 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16607 16608 // No need to do anything else with this case. 16609 if (ExpectedAlignment.isOne()) 16610 return; 16611 16612 // Synthesize offset of the whole access. 16613 CharUnits Offset; 16614 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16615 I++) { 16616 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16617 } 16618 16619 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16620 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16621 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16622 16623 // The base expression of the innermost MemberExpr may give 16624 // stronger guarantees than the class containing the member. 16625 if (DRE && !TopME->isArrow()) { 16626 const ValueDecl *VD = DRE->getDecl(); 16627 if (!VD->getType()->isReferenceType()) 16628 CompleteObjectAlignment = 16629 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16630 } 16631 16632 // Check if the synthesized offset fulfills the alignment. 16633 if (Offset % ExpectedAlignment != 0 || 16634 // It may fulfill the offset it but the effective alignment may still be 16635 // lower than the expected expression alignment. 16636 CompleteObjectAlignment < ExpectedAlignment) { 16637 // If this happens, we want to determine a sensible culprit of this. 16638 // Intuitively, watching the chain of member expressions from right to 16639 // left, we start with the required alignment (as required by the field 16640 // type) but some packed attribute in that chain has reduced the alignment. 16641 // It may happen that another packed structure increases it again. But if 16642 // we are here such increase has not been enough. So pointing the first 16643 // FieldDecl that either is packed or else its RecordDecl is, 16644 // seems reasonable. 16645 FieldDecl *FD = nullptr; 16646 CharUnits Alignment; 16647 for (FieldDecl *FDI : ReverseMemberChain) { 16648 if (FDI->hasAttr<PackedAttr>() || 16649 FDI->getParent()->hasAttr<PackedAttr>()) { 16650 FD = FDI; 16651 Alignment = std::min( 16652 Context.getTypeAlignInChars(FD->getType()), 16653 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16654 break; 16655 } 16656 } 16657 assert(FD && "We did not find a packed FieldDecl!"); 16658 Action(E, FD->getParent(), FD, Alignment); 16659 } 16660 } 16661 16662 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16663 using namespace std::placeholders; 16664 16665 RefersToMemberWithReducedAlignment( 16666 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16667 _2, _3, _4)); 16668 } 16669 16670 // Check if \p Ty is a valid type for the elementwise math builtins. If it is 16671 // not a valid type, emit an error message and return true. Otherwise return 16672 // false. 16673 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, 16674 QualType Ty) { 16675 if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) { 16676 S.Diag(Loc, diag::err_builtin_invalid_arg_type) 16677 << 1 << /* vector, integer or float ty*/ 0 << Ty; 16678 return true; 16679 } 16680 return false; 16681 } 16682 16683 bool Sema::SemaBuiltinElementwiseMathOneArg(CallExpr *TheCall) { 16684 if (checkArgCount(*this, TheCall, 1)) 16685 return true; 16686 16687 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 16688 SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc(); 16689 if (A.isInvalid()) 16690 return true; 16691 16692 TheCall->setArg(0, A.get()); 16693 QualType TyA = A.get()->getType(); 16694 if (checkMathBuiltinElementType(*this, ArgLoc, TyA)) 16695 return true; 16696 16697 QualType EltTy = TyA; 16698 if (auto *VecTy = EltTy->getAs<VectorType>()) 16699 EltTy = VecTy->getElementType(); 16700 if (EltTy->isUnsignedIntegerType()) 16701 return Diag(ArgLoc, diag::err_builtin_invalid_arg_type) 16702 << 1 << /*signed integer or float ty*/ 3 << TyA; 16703 16704 TheCall->setType(TyA); 16705 return false; 16706 } 16707 16708 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) { 16709 if (checkArgCount(*this, TheCall, 2)) 16710 return true; 16711 16712 ExprResult A = TheCall->getArg(0); 16713 ExprResult B = TheCall->getArg(1); 16714 // Do standard promotions between the two arguments, returning their common 16715 // type. 16716 QualType Res = 16717 UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison); 16718 if (A.isInvalid() || B.isInvalid()) 16719 return true; 16720 16721 QualType TyA = A.get()->getType(); 16722 QualType TyB = B.get()->getType(); 16723 16724 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType()) 16725 return Diag(A.get()->getBeginLoc(), 16726 diag::err_typecheck_call_different_arg_types) 16727 << TyA << TyB; 16728 16729 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 16730 return true; 16731 16732 TheCall->setArg(0, A.get()); 16733 TheCall->setArg(1, B.get()); 16734 TheCall->setType(Res); 16735 return false; 16736 } 16737 16738 bool Sema::SemaBuiltinReduceMath(CallExpr *TheCall) { 16739 if (checkArgCount(*this, TheCall, 1)) 16740 return true; 16741 16742 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 16743 if (A.isInvalid()) 16744 return true; 16745 16746 TheCall->setArg(0, A.get()); 16747 const VectorType *TyA = A.get()->getType()->getAs<VectorType>(); 16748 if (!TyA) { 16749 SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc(); 16750 return Diag(ArgLoc, diag::err_builtin_invalid_arg_type) 16751 << 1 << /* vector ty*/ 4 << A.get()->getType(); 16752 } 16753 16754 TheCall->setType(TyA->getElementType()); 16755 return false; 16756 } 16757 16758 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16759 ExprResult CallResult) { 16760 if (checkArgCount(*this, TheCall, 1)) 16761 return ExprError(); 16762 16763 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16764 if (MatrixArg.isInvalid()) 16765 return MatrixArg; 16766 Expr *Matrix = MatrixArg.get(); 16767 16768 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16769 if (!MType) { 16770 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16771 << 1 << /* matrix ty*/ 1 << Matrix->getType(); 16772 return ExprError(); 16773 } 16774 16775 // Create returned matrix type by swapping rows and columns of the argument 16776 // matrix type. 16777 QualType ResultType = Context.getConstantMatrixType( 16778 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16779 16780 // Change the return type to the type of the returned matrix. 16781 TheCall->setType(ResultType); 16782 16783 // Update call argument to use the possibly converted matrix argument. 16784 TheCall->setArg(0, Matrix); 16785 return CallResult; 16786 } 16787 16788 // Get and verify the matrix dimensions. 16789 static llvm::Optional<unsigned> 16790 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16791 SourceLocation ErrorPos; 16792 Optional<llvm::APSInt> Value = 16793 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16794 if (!Value) { 16795 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16796 << Name; 16797 return {}; 16798 } 16799 uint64_t Dim = Value->getZExtValue(); 16800 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16801 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16802 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16803 return {}; 16804 } 16805 return Dim; 16806 } 16807 16808 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16809 ExprResult CallResult) { 16810 if (!getLangOpts().MatrixTypes) { 16811 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16812 return ExprError(); 16813 } 16814 16815 if (checkArgCount(*this, TheCall, 4)) 16816 return ExprError(); 16817 16818 unsigned PtrArgIdx = 0; 16819 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16820 Expr *RowsExpr = TheCall->getArg(1); 16821 Expr *ColumnsExpr = TheCall->getArg(2); 16822 Expr *StrideExpr = TheCall->getArg(3); 16823 16824 bool ArgError = false; 16825 16826 // Check pointer argument. 16827 { 16828 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16829 if (PtrConv.isInvalid()) 16830 return PtrConv; 16831 PtrExpr = PtrConv.get(); 16832 TheCall->setArg(0, PtrExpr); 16833 if (PtrExpr->isTypeDependent()) { 16834 TheCall->setType(Context.DependentTy); 16835 return TheCall; 16836 } 16837 } 16838 16839 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16840 QualType ElementTy; 16841 if (!PtrTy) { 16842 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16843 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 16844 ArgError = true; 16845 } else { 16846 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16847 16848 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16849 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16850 << PtrArgIdx + 1 << /* pointer to element ty*/ 2 16851 << PtrExpr->getType(); 16852 ArgError = true; 16853 } 16854 } 16855 16856 // Apply default Lvalue conversions and convert the expression to size_t. 16857 auto ApplyArgumentConversions = [this](Expr *E) { 16858 ExprResult Conv = DefaultLvalueConversion(E); 16859 if (Conv.isInvalid()) 16860 return Conv; 16861 16862 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16863 }; 16864 16865 // Apply conversion to row and column expressions. 16866 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16867 if (!RowsConv.isInvalid()) { 16868 RowsExpr = RowsConv.get(); 16869 TheCall->setArg(1, RowsExpr); 16870 } else 16871 RowsExpr = nullptr; 16872 16873 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16874 if (!ColumnsConv.isInvalid()) { 16875 ColumnsExpr = ColumnsConv.get(); 16876 TheCall->setArg(2, ColumnsExpr); 16877 } else 16878 ColumnsExpr = nullptr; 16879 16880 // If any any part of the result matrix type is still pending, just use 16881 // Context.DependentTy, until all parts are resolved. 16882 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16883 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16884 TheCall->setType(Context.DependentTy); 16885 return CallResult; 16886 } 16887 16888 // Check row and column dimensions. 16889 llvm::Optional<unsigned> MaybeRows; 16890 if (RowsExpr) 16891 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16892 16893 llvm::Optional<unsigned> MaybeColumns; 16894 if (ColumnsExpr) 16895 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16896 16897 // Check stride argument. 16898 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16899 if (StrideConv.isInvalid()) 16900 return ExprError(); 16901 StrideExpr = StrideConv.get(); 16902 TheCall->setArg(3, StrideExpr); 16903 16904 if (MaybeRows) { 16905 if (Optional<llvm::APSInt> Value = 16906 StrideExpr->getIntegerConstantExpr(Context)) { 16907 uint64_t Stride = Value->getZExtValue(); 16908 if (Stride < *MaybeRows) { 16909 Diag(StrideExpr->getBeginLoc(), 16910 diag::err_builtin_matrix_stride_too_small); 16911 ArgError = true; 16912 } 16913 } 16914 } 16915 16916 if (ArgError || !MaybeRows || !MaybeColumns) 16917 return ExprError(); 16918 16919 TheCall->setType( 16920 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16921 return CallResult; 16922 } 16923 16924 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16925 ExprResult CallResult) { 16926 if (checkArgCount(*this, TheCall, 3)) 16927 return ExprError(); 16928 16929 unsigned PtrArgIdx = 1; 16930 Expr *MatrixExpr = TheCall->getArg(0); 16931 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16932 Expr *StrideExpr = TheCall->getArg(2); 16933 16934 bool ArgError = false; 16935 16936 { 16937 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16938 if (MatrixConv.isInvalid()) 16939 return MatrixConv; 16940 MatrixExpr = MatrixConv.get(); 16941 TheCall->setArg(0, MatrixExpr); 16942 } 16943 if (MatrixExpr->isTypeDependent()) { 16944 TheCall->setType(Context.DependentTy); 16945 return TheCall; 16946 } 16947 16948 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16949 if (!MatrixTy) { 16950 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16951 << 1 << /*matrix ty */ 1 << MatrixExpr->getType(); 16952 ArgError = true; 16953 } 16954 16955 { 16956 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16957 if (PtrConv.isInvalid()) 16958 return PtrConv; 16959 PtrExpr = PtrConv.get(); 16960 TheCall->setArg(1, PtrExpr); 16961 if (PtrExpr->isTypeDependent()) { 16962 TheCall->setType(Context.DependentTy); 16963 return TheCall; 16964 } 16965 } 16966 16967 // Check pointer argument. 16968 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16969 if (!PtrTy) { 16970 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16971 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 16972 ArgError = true; 16973 } else { 16974 QualType ElementTy = PtrTy->getPointeeType(); 16975 if (ElementTy.isConstQualified()) { 16976 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16977 ArgError = true; 16978 } 16979 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16980 if (MatrixTy && 16981 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16982 Diag(PtrExpr->getBeginLoc(), 16983 diag::err_builtin_matrix_pointer_arg_mismatch) 16984 << ElementTy << MatrixTy->getElementType(); 16985 ArgError = true; 16986 } 16987 } 16988 16989 // Apply default Lvalue conversions and convert the stride expression to 16990 // size_t. 16991 { 16992 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16993 if (StrideConv.isInvalid()) 16994 return StrideConv; 16995 16996 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16997 if (StrideConv.isInvalid()) 16998 return StrideConv; 16999 StrideExpr = StrideConv.get(); 17000 TheCall->setArg(2, StrideExpr); 17001 } 17002 17003 // Check stride argument. 17004 if (MatrixTy) { 17005 if (Optional<llvm::APSInt> Value = 17006 StrideExpr->getIntegerConstantExpr(Context)) { 17007 uint64_t Stride = Value->getZExtValue(); 17008 if (Stride < MatrixTy->getNumRows()) { 17009 Diag(StrideExpr->getBeginLoc(), 17010 diag::err_builtin_matrix_stride_too_small); 17011 ArgError = true; 17012 } 17013 } 17014 } 17015 17016 if (ArgError) 17017 return ExprError(); 17018 17019 return CallResult; 17020 } 17021 17022 /// \brief Enforce the bounds of a TCB 17023 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 17024 /// directly calls other functions in the same TCB as marked by the enforce_tcb 17025 /// and enforce_tcb_leaf attributes. 17026 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 17027 const FunctionDecl *Callee) { 17028 const FunctionDecl *Caller = getCurFunctionDecl(); 17029 17030 // Calls to builtins are not enforced. 17031 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 17032 Callee->getBuiltinID() != 0) 17033 return; 17034 17035 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 17036 // all TCBs the callee is a part of. 17037 llvm::StringSet<> CalleeTCBs; 17038 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 17039 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17040 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 17041 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17042 17043 // Go through the TCBs the caller is a part of and emit warnings if Caller 17044 // is in a TCB that the Callee is not. 17045 for_each( 17046 Caller->specific_attrs<EnforceTCBAttr>(), 17047 [&](const auto *A) { 17048 StringRef CallerTCB = A->getTCBName(); 17049 if (CalleeTCBs.count(CallerTCB) == 0) { 17050 this->Diag(TheCall->getExprLoc(), 17051 diag::warn_tcb_enforcement_violation) << Callee 17052 << CallerTCB; 17053 } 17054 }); 17055 } 17056