1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cstddef> 95 #include <cstdint> 96 #include <functional> 97 #include <limits> 98 #include <string> 99 #include <tuple> 100 #include <utility> 101 102 using namespace clang; 103 using namespace sema; 104 105 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 106 unsigned ByteNo) const { 107 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 108 Context.getTargetInfo()); 109 } 110 111 /// Checks that a call expression's argument count is the desired number. 112 /// This is useful when doing custom type-checking. Returns true on error. 113 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 114 unsigned argCount = call->getNumArgs(); 115 if (argCount == desiredArgCount) return false; 116 117 if (argCount < desiredArgCount) 118 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 119 << 0 /*function call*/ << desiredArgCount << argCount 120 << call->getSourceRange(); 121 122 // Highlight all the excess arguments. 123 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 124 call->getArg(argCount - 1)->getEndLoc()); 125 126 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 127 << 0 /*function call*/ << desiredArgCount << argCount 128 << call->getArg(1)->getSourceRange(); 129 } 130 131 /// Check that the first argument to __builtin_annotation is an integer 132 /// and the second argument is a non-wide string literal. 133 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 134 if (checkArgCount(S, TheCall, 2)) 135 return true; 136 137 // First argument should be an integer. 138 Expr *ValArg = TheCall->getArg(0); 139 QualType Ty = ValArg->getType(); 140 if (!Ty->isIntegerType()) { 141 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 142 << ValArg->getSourceRange(); 143 return true; 144 } 145 146 // Second argument should be a constant string. 147 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 148 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 149 if (!Literal || !Literal->isAscii()) { 150 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 151 << StrArg->getSourceRange(); 152 return true; 153 } 154 155 TheCall->setType(Ty); 156 return false; 157 } 158 159 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 160 // We need at least one argument. 161 if (TheCall->getNumArgs() < 1) { 162 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 163 << 0 << 1 << TheCall->getNumArgs() 164 << TheCall->getCallee()->getSourceRange(); 165 return true; 166 } 167 168 // All arguments should be wide string literals. 169 for (Expr *Arg : TheCall->arguments()) { 170 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 171 if (!Literal || !Literal->isWide()) { 172 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 173 << Arg->getSourceRange(); 174 return true; 175 } 176 } 177 178 return false; 179 } 180 181 /// Check that the argument to __builtin_addressof is a glvalue, and set the 182 /// result type to the corresponding pointer type. 183 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 184 if (checkArgCount(S, TheCall, 1)) 185 return true; 186 187 ExprResult Arg(TheCall->getArg(0)); 188 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 189 if (ResultType.isNull()) 190 return true; 191 192 TheCall->setArg(0, Arg.get()); 193 TheCall->setType(ResultType); 194 return false; 195 } 196 197 /// Check the number of arguments and set the result type to 198 /// the argument type. 199 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 200 if (checkArgCount(S, TheCall, 1)) 201 return true; 202 203 TheCall->setType(TheCall->getArg(0)->getType()); 204 return false; 205 } 206 207 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 208 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 209 /// type (but not a function pointer) and that the alignment is a power-of-two. 210 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 211 if (checkArgCount(S, TheCall, 2)) 212 return true; 213 214 clang::Expr *Source = TheCall->getArg(0); 215 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 216 217 auto IsValidIntegerType = [](QualType Ty) { 218 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 219 }; 220 QualType SrcTy = Source->getType(); 221 // We should also be able to use it with arrays (but not functions!). 222 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 223 SrcTy = S.Context.getDecayedType(SrcTy); 224 } 225 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 226 SrcTy->isFunctionPointerType()) { 227 // FIXME: this is not quite the right error message since we don't allow 228 // floating point types, or member pointers. 229 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 230 << SrcTy; 231 return true; 232 } 233 234 clang::Expr *AlignOp = TheCall->getArg(1); 235 if (!IsValidIntegerType(AlignOp->getType())) { 236 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 237 << AlignOp->getType(); 238 return true; 239 } 240 Expr::EvalResult AlignResult; 241 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 242 // We can't check validity of alignment if it is value dependent. 243 if (!AlignOp->isValueDependent() && 244 AlignOp->EvaluateAsInt(AlignResult, S.Context, 245 Expr::SE_AllowSideEffects)) { 246 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 247 llvm::APSInt MaxValue( 248 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 249 if (AlignValue < 1) { 250 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 251 return true; 252 } 253 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 254 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 255 << MaxValue.toString(10); 256 return true; 257 } 258 if (!AlignValue.isPowerOf2()) { 259 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 260 return true; 261 } 262 if (AlignValue == 1) { 263 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 264 << IsBooleanAlignBuiltin; 265 } 266 } 267 268 ExprResult SrcArg = S.PerformCopyInitialization( 269 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 270 SourceLocation(), Source); 271 if (SrcArg.isInvalid()) 272 return true; 273 TheCall->setArg(0, SrcArg.get()); 274 ExprResult AlignArg = 275 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 276 S.Context, AlignOp->getType(), false), 277 SourceLocation(), AlignOp); 278 if (AlignArg.isInvalid()) 279 return true; 280 TheCall->setArg(1, AlignArg.get()); 281 // For align_up/align_down, the return type is the same as the (potentially 282 // decayed) argument type including qualifiers. For is_aligned(), the result 283 // is always bool. 284 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 285 return false; 286 } 287 288 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 289 unsigned BuiltinID) { 290 if (checkArgCount(S, TheCall, 3)) 291 return true; 292 293 // First two arguments should be integers. 294 for (unsigned I = 0; I < 2; ++I) { 295 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 296 if (Arg.isInvalid()) return true; 297 TheCall->setArg(I, Arg.get()); 298 299 QualType Ty = Arg.get()->getType(); 300 if (!Ty->isIntegerType()) { 301 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 302 << Ty << Arg.get()->getSourceRange(); 303 return true; 304 } 305 } 306 307 // Third argument should be a pointer to a non-const integer. 308 // IRGen correctly handles volatile, restrict, and address spaces, and 309 // the other qualifiers aren't possible. 310 { 311 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 312 if (Arg.isInvalid()) return true; 313 TheCall->setArg(2, Arg.get()); 314 315 QualType Ty = Arg.get()->getType(); 316 const auto *PtrTy = Ty->getAs<PointerType>(); 317 if (!PtrTy || 318 !PtrTy->getPointeeType()->isIntegerType() || 319 PtrTy->getPointeeType().isConstQualified()) { 320 S.Diag(Arg.get()->getBeginLoc(), 321 diag::err_overflow_builtin_must_be_ptr_int) 322 << Ty << Arg.get()->getSourceRange(); 323 return true; 324 } 325 } 326 327 // Disallow signed ExtIntType args larger than 128 bits to mul function until 328 // we improve backend support. 329 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 330 for (unsigned I = 0; I < 3; ++I) { 331 const auto Arg = TheCall->getArg(I); 332 // Third argument will be a pointer. 333 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 334 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 335 S.getASTContext().getIntWidth(Ty) > 128) 336 return S.Diag(Arg->getBeginLoc(), 337 diag::err_overflow_builtin_ext_int_max_size) 338 << 128; 339 } 340 } 341 342 return false; 343 } 344 345 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 346 if (checkArgCount(S, BuiltinCall, 2)) 347 return true; 348 349 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 350 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 351 Expr *Call = BuiltinCall->getArg(0); 352 Expr *Chain = BuiltinCall->getArg(1); 353 354 if (Call->getStmtClass() != Stmt::CallExprClass) { 355 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 356 << Call->getSourceRange(); 357 return true; 358 } 359 360 auto CE = cast<CallExpr>(Call); 361 if (CE->getCallee()->getType()->isBlockPointerType()) { 362 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 363 << Call->getSourceRange(); 364 return true; 365 } 366 367 const Decl *TargetDecl = CE->getCalleeDecl(); 368 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 369 if (FD->getBuiltinID()) { 370 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 371 << Call->getSourceRange(); 372 return true; 373 } 374 375 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 376 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 377 << Call->getSourceRange(); 378 return true; 379 } 380 381 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 382 if (ChainResult.isInvalid()) 383 return true; 384 if (!ChainResult.get()->getType()->isPointerType()) { 385 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 386 << Chain->getSourceRange(); 387 return true; 388 } 389 390 QualType ReturnTy = CE->getCallReturnType(S.Context); 391 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 392 QualType BuiltinTy = S.Context.getFunctionType( 393 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 394 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 395 396 Builtin = 397 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 398 399 BuiltinCall->setType(CE->getType()); 400 BuiltinCall->setValueKind(CE->getValueKind()); 401 BuiltinCall->setObjectKind(CE->getObjectKind()); 402 BuiltinCall->setCallee(Builtin); 403 BuiltinCall->setArg(1, ChainResult.get()); 404 405 return false; 406 } 407 408 namespace { 409 410 class EstimateSizeFormatHandler 411 : public analyze_format_string::FormatStringHandler { 412 size_t Size; 413 414 public: 415 EstimateSizeFormatHandler(StringRef Format) 416 : Size(std::min(Format.find(0), Format.size()) + 417 1 /* null byte always written by sprintf */) {} 418 419 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 420 const char *, unsigned SpecifierLen) override { 421 422 const size_t FieldWidth = computeFieldWidth(FS); 423 const size_t Precision = computePrecision(FS); 424 425 // The actual format. 426 switch (FS.getConversionSpecifier().getKind()) { 427 // Just a char. 428 case analyze_format_string::ConversionSpecifier::cArg: 429 case analyze_format_string::ConversionSpecifier::CArg: 430 Size += std::max(FieldWidth, (size_t)1); 431 break; 432 // Just an integer. 433 case analyze_format_string::ConversionSpecifier::dArg: 434 case analyze_format_string::ConversionSpecifier::DArg: 435 case analyze_format_string::ConversionSpecifier::iArg: 436 case analyze_format_string::ConversionSpecifier::oArg: 437 case analyze_format_string::ConversionSpecifier::OArg: 438 case analyze_format_string::ConversionSpecifier::uArg: 439 case analyze_format_string::ConversionSpecifier::UArg: 440 case analyze_format_string::ConversionSpecifier::xArg: 441 case analyze_format_string::ConversionSpecifier::XArg: 442 Size += std::max(FieldWidth, Precision); 443 break; 444 445 // %g style conversion switches between %f or %e style dynamically. 446 // %f always takes less space, so default to it. 447 case analyze_format_string::ConversionSpecifier::gArg: 448 case analyze_format_string::ConversionSpecifier::GArg: 449 450 // Floating point number in the form '[+]ddd.ddd'. 451 case analyze_format_string::ConversionSpecifier::fArg: 452 case analyze_format_string::ConversionSpecifier::FArg: 453 Size += std::max(FieldWidth, 1 /* integer part */ + 454 (Precision ? 1 + Precision 455 : 0) /* period + decimal */); 456 break; 457 458 // Floating point number in the form '[-]d.ddde[+-]dd'. 459 case analyze_format_string::ConversionSpecifier::eArg: 460 case analyze_format_string::ConversionSpecifier::EArg: 461 Size += 462 std::max(FieldWidth, 463 1 /* integer part */ + 464 (Precision ? 1 + Precision : 0) /* period + decimal */ + 465 1 /* e or E letter */ + 2 /* exponent */); 466 break; 467 468 // Floating point number in the form '[-]0xh.hhhhp±dd'. 469 case analyze_format_string::ConversionSpecifier::aArg: 470 case analyze_format_string::ConversionSpecifier::AArg: 471 Size += 472 std::max(FieldWidth, 473 2 /* 0x */ + 1 /* integer part */ + 474 (Precision ? 1 + Precision : 0) /* period + decimal */ + 475 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 476 break; 477 478 // Just a string. 479 case analyze_format_string::ConversionSpecifier::sArg: 480 case analyze_format_string::ConversionSpecifier::SArg: 481 Size += FieldWidth; 482 break; 483 484 // Just a pointer in the form '0xddd'. 485 case analyze_format_string::ConversionSpecifier::pArg: 486 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 487 break; 488 489 // A plain percent. 490 case analyze_format_string::ConversionSpecifier::PercentArg: 491 Size += 1; 492 break; 493 494 default: 495 break; 496 } 497 498 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 499 500 if (FS.hasAlternativeForm()) { 501 switch (FS.getConversionSpecifier().getKind()) { 502 default: 503 break; 504 // Force a leading '0'. 505 case analyze_format_string::ConversionSpecifier::oArg: 506 Size += 1; 507 break; 508 // Force a leading '0x'. 509 case analyze_format_string::ConversionSpecifier::xArg: 510 case analyze_format_string::ConversionSpecifier::XArg: 511 Size += 2; 512 break; 513 // Force a period '.' before decimal, even if precision is 0. 514 case analyze_format_string::ConversionSpecifier::aArg: 515 case analyze_format_string::ConversionSpecifier::AArg: 516 case analyze_format_string::ConversionSpecifier::eArg: 517 case analyze_format_string::ConversionSpecifier::EArg: 518 case analyze_format_string::ConversionSpecifier::fArg: 519 case analyze_format_string::ConversionSpecifier::FArg: 520 case analyze_format_string::ConversionSpecifier::gArg: 521 case analyze_format_string::ConversionSpecifier::GArg: 522 Size += (Precision ? 0 : 1); 523 break; 524 } 525 } 526 assert(SpecifierLen <= Size && "no underflow"); 527 Size -= SpecifierLen; 528 return true; 529 } 530 531 size_t getSizeLowerBound() const { return Size; } 532 533 private: 534 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 535 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 536 size_t FieldWidth = 0; 537 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 538 FieldWidth = FW.getConstantAmount(); 539 return FieldWidth; 540 } 541 542 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 543 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 544 size_t Precision = 0; 545 546 // See man 3 printf for default precision value based on the specifier. 547 switch (FW.getHowSpecified()) { 548 case analyze_format_string::OptionalAmount::NotSpecified: 549 switch (FS.getConversionSpecifier().getKind()) { 550 default: 551 break; 552 case analyze_format_string::ConversionSpecifier::dArg: // %d 553 case analyze_format_string::ConversionSpecifier::DArg: // %D 554 case analyze_format_string::ConversionSpecifier::iArg: // %i 555 Precision = 1; 556 break; 557 case analyze_format_string::ConversionSpecifier::oArg: // %d 558 case analyze_format_string::ConversionSpecifier::OArg: // %D 559 case analyze_format_string::ConversionSpecifier::uArg: // %d 560 case analyze_format_string::ConversionSpecifier::UArg: // %D 561 case analyze_format_string::ConversionSpecifier::xArg: // %d 562 case analyze_format_string::ConversionSpecifier::XArg: // %D 563 Precision = 1; 564 break; 565 case analyze_format_string::ConversionSpecifier::fArg: // %f 566 case analyze_format_string::ConversionSpecifier::FArg: // %F 567 case analyze_format_string::ConversionSpecifier::eArg: // %e 568 case analyze_format_string::ConversionSpecifier::EArg: // %E 569 case analyze_format_string::ConversionSpecifier::gArg: // %g 570 case analyze_format_string::ConversionSpecifier::GArg: // %G 571 Precision = 6; 572 break; 573 case analyze_format_string::ConversionSpecifier::pArg: // %d 574 Precision = 1; 575 break; 576 } 577 break; 578 case analyze_format_string::OptionalAmount::Constant: 579 Precision = FW.getConstantAmount(); 580 break; 581 default: 582 break; 583 } 584 return Precision; 585 } 586 }; 587 588 } // namespace 589 590 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 591 /// __builtin_*_chk function, then use the object size argument specified in the 592 /// source. Otherwise, infer the object size using __builtin_object_size. 593 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 594 CallExpr *TheCall) { 595 // FIXME: There are some more useful checks we could be doing here: 596 // - Evaluate strlen of strcpy arguments, use as object size. 597 598 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 599 isConstantEvaluated()) 600 return; 601 602 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 603 if (!BuiltinID) 604 return; 605 606 const TargetInfo &TI = getASTContext().getTargetInfo(); 607 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 608 609 unsigned DiagID = 0; 610 bool IsChkVariant = false; 611 Optional<llvm::APSInt> UsedSize; 612 unsigned SizeIndex, ObjectIndex; 613 switch (BuiltinID) { 614 default: 615 return; 616 case Builtin::BIsprintf: 617 case Builtin::BI__builtin___sprintf_chk: { 618 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 619 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 620 621 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 622 623 if (!Format->isAscii() && !Format->isUTF8()) 624 return; 625 626 StringRef FormatStrRef = Format->getString(); 627 EstimateSizeFormatHandler H(FormatStrRef); 628 const char *FormatBytes = FormatStrRef.data(); 629 const ConstantArrayType *T = 630 Context.getAsConstantArrayType(Format->getType()); 631 assert(T && "String literal not of constant array type!"); 632 size_t TypeSize = T->getSize().getZExtValue(); 633 634 // In case there's a null byte somewhere. 635 size_t StrLen = 636 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 637 if (!analyze_format_string::ParsePrintfString( 638 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 639 Context.getTargetInfo(), false)) { 640 DiagID = diag::warn_fortify_source_format_overflow; 641 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 642 .extOrTrunc(SizeTypeWidth); 643 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 644 IsChkVariant = true; 645 ObjectIndex = 2; 646 } else { 647 IsChkVariant = false; 648 ObjectIndex = 0; 649 } 650 break; 651 } 652 } 653 return; 654 } 655 case Builtin::BI__builtin___memcpy_chk: 656 case Builtin::BI__builtin___memmove_chk: 657 case Builtin::BI__builtin___memset_chk: 658 case Builtin::BI__builtin___strlcat_chk: 659 case Builtin::BI__builtin___strlcpy_chk: 660 case Builtin::BI__builtin___strncat_chk: 661 case Builtin::BI__builtin___strncpy_chk: 662 case Builtin::BI__builtin___stpncpy_chk: 663 case Builtin::BI__builtin___memccpy_chk: 664 case Builtin::BI__builtin___mempcpy_chk: { 665 DiagID = diag::warn_builtin_chk_overflow; 666 IsChkVariant = true; 667 SizeIndex = TheCall->getNumArgs() - 2; 668 ObjectIndex = TheCall->getNumArgs() - 1; 669 break; 670 } 671 672 case Builtin::BI__builtin___snprintf_chk: 673 case Builtin::BI__builtin___vsnprintf_chk: { 674 DiagID = diag::warn_builtin_chk_overflow; 675 IsChkVariant = true; 676 SizeIndex = 1; 677 ObjectIndex = 3; 678 break; 679 } 680 681 case Builtin::BIstrncat: 682 case Builtin::BI__builtin_strncat: 683 case Builtin::BIstrncpy: 684 case Builtin::BI__builtin_strncpy: 685 case Builtin::BIstpncpy: 686 case Builtin::BI__builtin_stpncpy: { 687 // Whether these functions overflow depends on the runtime strlen of the 688 // string, not just the buffer size, so emitting the "always overflow" 689 // diagnostic isn't quite right. We should still diagnose passing a buffer 690 // size larger than the destination buffer though; this is a runtime abort 691 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 692 DiagID = diag::warn_fortify_source_size_mismatch; 693 SizeIndex = TheCall->getNumArgs() - 1; 694 ObjectIndex = 0; 695 break; 696 } 697 698 case Builtin::BImemcpy: 699 case Builtin::BI__builtin_memcpy: 700 case Builtin::BImemmove: 701 case Builtin::BI__builtin_memmove: 702 case Builtin::BImemset: 703 case Builtin::BI__builtin_memset: 704 case Builtin::BImempcpy: 705 case Builtin::BI__builtin_mempcpy: { 706 DiagID = diag::warn_fortify_source_overflow; 707 SizeIndex = TheCall->getNumArgs() - 1; 708 ObjectIndex = 0; 709 break; 710 } 711 case Builtin::BIsnprintf: 712 case Builtin::BI__builtin_snprintf: 713 case Builtin::BIvsnprintf: 714 case Builtin::BI__builtin_vsnprintf: { 715 DiagID = diag::warn_fortify_source_size_mismatch; 716 SizeIndex = 1; 717 ObjectIndex = 0; 718 break; 719 } 720 } 721 722 llvm::APSInt ObjectSize; 723 // For __builtin___*_chk, the object size is explicitly provided by the caller 724 // (usually using __builtin_object_size). Use that value to check this call. 725 if (IsChkVariant) { 726 Expr::EvalResult Result; 727 Expr *SizeArg = TheCall->getArg(ObjectIndex); 728 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 729 return; 730 ObjectSize = Result.Val.getInt(); 731 732 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 733 } else { 734 // If the parameter has a pass_object_size attribute, then we should use its 735 // (potentially) more strict checking mode. Otherwise, conservatively assume 736 // type 0. 737 int BOSType = 0; 738 if (const auto *POS = 739 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 740 BOSType = POS->getType(); 741 742 Expr *ObjArg = TheCall->getArg(ObjectIndex); 743 uint64_t Result; 744 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 745 return; 746 // Get the object size in the target's size_t width. 747 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 748 } 749 750 // Evaluate the number of bytes of the object that this call will use. 751 if (!UsedSize) { 752 Expr::EvalResult Result; 753 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 754 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 755 return; 756 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 757 } 758 759 if (UsedSize.getValue().ule(ObjectSize)) 760 return; 761 762 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 763 // Skim off the details of whichever builtin was called to produce a better 764 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 765 if (IsChkVariant) { 766 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 767 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 768 } else if (FunctionName.startswith("__builtin_")) { 769 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 770 } 771 772 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 773 PDiag(DiagID) 774 << FunctionName << ObjectSize.toString(/*Radix=*/10) 775 << UsedSize.getValue().toString(/*Radix=*/10)); 776 } 777 778 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 779 Scope::ScopeFlags NeededScopeFlags, 780 unsigned DiagID) { 781 // Scopes aren't available during instantiation. Fortunately, builtin 782 // functions cannot be template args so they cannot be formed through template 783 // instantiation. Therefore checking once during the parse is sufficient. 784 if (SemaRef.inTemplateInstantiation()) 785 return false; 786 787 Scope *S = SemaRef.getCurScope(); 788 while (S && !S->isSEHExceptScope()) 789 S = S->getParent(); 790 if (!S || !(S->getFlags() & NeededScopeFlags)) { 791 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 792 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 793 << DRE->getDecl()->getIdentifier(); 794 return true; 795 } 796 797 return false; 798 } 799 800 static inline bool isBlockPointer(Expr *Arg) { 801 return Arg->getType()->isBlockPointerType(); 802 } 803 804 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 805 /// void*, which is a requirement of device side enqueue. 806 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 807 const BlockPointerType *BPT = 808 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 809 ArrayRef<QualType> Params = 810 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 811 unsigned ArgCounter = 0; 812 bool IllegalParams = false; 813 // Iterate through the block parameters until either one is found that is not 814 // a local void*, or the block is valid. 815 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 816 I != E; ++I, ++ArgCounter) { 817 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 818 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 819 LangAS::opencl_local) { 820 // Get the location of the error. If a block literal has been passed 821 // (BlockExpr) then we can point straight to the offending argument, 822 // else we just point to the variable reference. 823 SourceLocation ErrorLoc; 824 if (isa<BlockExpr>(BlockArg)) { 825 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 826 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 827 } else if (isa<DeclRefExpr>(BlockArg)) { 828 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 829 } 830 S.Diag(ErrorLoc, 831 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 832 IllegalParams = true; 833 } 834 } 835 836 return IllegalParams; 837 } 838 839 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 840 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_subgroups", 841 S.getLangOpts())) { 842 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 843 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 844 return true; 845 } 846 return false; 847 } 848 849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 850 if (checkArgCount(S, TheCall, 2)) 851 return true; 852 853 if (checkOpenCLSubgroupExt(S, TheCall)) 854 return true; 855 856 // First argument is an ndrange_t type. 857 Expr *NDRangeArg = TheCall->getArg(0); 858 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 859 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 860 << TheCall->getDirectCallee() << "'ndrange_t'"; 861 return true; 862 } 863 864 Expr *BlockArg = TheCall->getArg(1); 865 if (!isBlockPointer(BlockArg)) { 866 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 867 << TheCall->getDirectCallee() << "block"; 868 return true; 869 } 870 return checkOpenCLBlockArgs(S, BlockArg); 871 } 872 873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 874 /// get_kernel_work_group_size 875 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 877 if (checkArgCount(S, TheCall, 1)) 878 return true; 879 880 Expr *BlockArg = TheCall->getArg(0); 881 if (!isBlockPointer(BlockArg)) { 882 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 883 << TheCall->getDirectCallee() << "block"; 884 return true; 885 } 886 return checkOpenCLBlockArgs(S, BlockArg); 887 } 888 889 /// Diagnose integer type and any valid implicit conversion to it. 890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 891 const QualType &IntType); 892 893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 894 unsigned Start, unsigned End) { 895 bool IllegalParams = false; 896 for (unsigned I = Start; I <= End; ++I) 897 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 898 S.Context.getSizeType()); 899 return IllegalParams; 900 } 901 902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 903 /// 'local void*' parameter of passed block. 904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 905 Expr *BlockArg, 906 unsigned NumNonVarArgs) { 907 const BlockPointerType *BPT = 908 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 909 unsigned NumBlockParams = 910 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 911 unsigned TotalNumArgs = TheCall->getNumArgs(); 912 913 // For each argument passed to the block, a corresponding uint needs to 914 // be passed to describe the size of the local memory. 915 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 916 S.Diag(TheCall->getBeginLoc(), 917 diag::err_opencl_enqueue_kernel_local_size_args); 918 return true; 919 } 920 921 // Check that the sizes of the local memory are specified by integers. 922 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 923 TotalNumArgs - 1); 924 } 925 926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 927 /// overload formats specified in Table 6.13.17.1. 928 /// int enqueue_kernel(queue_t queue, 929 /// kernel_enqueue_flags_t flags, 930 /// const ndrange_t ndrange, 931 /// void (^block)(void)) 932 /// int enqueue_kernel(queue_t queue, 933 /// kernel_enqueue_flags_t flags, 934 /// const ndrange_t ndrange, 935 /// uint num_events_in_wait_list, 936 /// clk_event_t *event_wait_list, 937 /// clk_event_t *event_ret, 938 /// void (^block)(void)) 939 /// int enqueue_kernel(queue_t queue, 940 /// kernel_enqueue_flags_t flags, 941 /// const ndrange_t ndrange, 942 /// void (^block)(local void*, ...), 943 /// uint size0, ...) 944 /// int enqueue_kernel(queue_t queue, 945 /// kernel_enqueue_flags_t flags, 946 /// const ndrange_t ndrange, 947 /// uint num_events_in_wait_list, 948 /// clk_event_t *event_wait_list, 949 /// clk_event_t *event_ret, 950 /// void (^block)(local void*, ...), 951 /// uint size0, ...) 952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 953 unsigned NumArgs = TheCall->getNumArgs(); 954 955 if (NumArgs < 4) { 956 S.Diag(TheCall->getBeginLoc(), 957 diag::err_typecheck_call_too_few_args_at_least) 958 << 0 << 4 << NumArgs; 959 return true; 960 } 961 962 Expr *Arg0 = TheCall->getArg(0); 963 Expr *Arg1 = TheCall->getArg(1); 964 Expr *Arg2 = TheCall->getArg(2); 965 Expr *Arg3 = TheCall->getArg(3); 966 967 // First argument always needs to be a queue_t type. 968 if (!Arg0->getType()->isQueueT()) { 969 S.Diag(TheCall->getArg(0)->getBeginLoc(), 970 diag::err_opencl_builtin_expected_type) 971 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 972 return true; 973 } 974 975 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 976 if (!Arg1->getType()->isIntegerType()) { 977 S.Diag(TheCall->getArg(1)->getBeginLoc(), 978 diag::err_opencl_builtin_expected_type) 979 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 980 return true; 981 } 982 983 // Third argument is always an ndrange_t type. 984 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 985 S.Diag(TheCall->getArg(2)->getBeginLoc(), 986 diag::err_opencl_builtin_expected_type) 987 << TheCall->getDirectCallee() << "'ndrange_t'"; 988 return true; 989 } 990 991 // With four arguments, there is only one form that the function could be 992 // called in: no events and no variable arguments. 993 if (NumArgs == 4) { 994 // check that the last argument is the right block type. 995 if (!isBlockPointer(Arg3)) { 996 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 997 << TheCall->getDirectCallee() << "block"; 998 return true; 999 } 1000 // we have a block type, check the prototype 1001 const BlockPointerType *BPT = 1002 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1003 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1004 S.Diag(Arg3->getBeginLoc(), 1005 diag::err_opencl_enqueue_kernel_blocks_no_args); 1006 return true; 1007 } 1008 return false; 1009 } 1010 // we can have block + varargs. 1011 if (isBlockPointer(Arg3)) 1012 return (checkOpenCLBlockArgs(S, Arg3) || 1013 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1014 // last two cases with either exactly 7 args or 7 args and varargs. 1015 if (NumArgs >= 7) { 1016 // check common block argument. 1017 Expr *Arg6 = TheCall->getArg(6); 1018 if (!isBlockPointer(Arg6)) { 1019 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1020 << TheCall->getDirectCallee() << "block"; 1021 return true; 1022 } 1023 if (checkOpenCLBlockArgs(S, Arg6)) 1024 return true; 1025 1026 // Forth argument has to be any integer type. 1027 if (!Arg3->getType()->isIntegerType()) { 1028 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1029 diag::err_opencl_builtin_expected_type) 1030 << TheCall->getDirectCallee() << "integer"; 1031 return true; 1032 } 1033 // check remaining common arguments. 1034 Expr *Arg4 = TheCall->getArg(4); 1035 Expr *Arg5 = TheCall->getArg(5); 1036 1037 // Fifth argument is always passed as a pointer to clk_event_t. 1038 if (!Arg4->isNullPointerConstant(S.Context, 1039 Expr::NPC_ValueDependentIsNotNull) && 1040 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1041 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1042 diag::err_opencl_builtin_expected_type) 1043 << TheCall->getDirectCallee() 1044 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1045 return true; 1046 } 1047 1048 // Sixth argument is always passed as a pointer to clk_event_t. 1049 if (!Arg5->isNullPointerConstant(S.Context, 1050 Expr::NPC_ValueDependentIsNotNull) && 1051 !(Arg5->getType()->isPointerType() && 1052 Arg5->getType()->getPointeeType()->isClkEventT())) { 1053 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1054 diag::err_opencl_builtin_expected_type) 1055 << TheCall->getDirectCallee() 1056 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1057 return true; 1058 } 1059 1060 if (NumArgs == 7) 1061 return false; 1062 1063 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1064 } 1065 1066 // None of the specific case has been detected, give generic error 1067 S.Diag(TheCall->getBeginLoc(), 1068 diag::err_opencl_enqueue_kernel_incorrect_args); 1069 return true; 1070 } 1071 1072 /// Returns OpenCL access qual. 1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1074 return D->getAttr<OpenCLAccessAttr>(); 1075 } 1076 1077 /// Returns true if pipe element type is different from the pointer. 1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1079 const Expr *Arg0 = Call->getArg(0); 1080 // First argument type should always be pipe. 1081 if (!Arg0->getType()->isPipeType()) { 1082 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1083 << Call->getDirectCallee() << Arg0->getSourceRange(); 1084 return true; 1085 } 1086 OpenCLAccessAttr *AccessQual = 1087 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1088 // Validates the access qualifier is compatible with the call. 1089 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1090 // read_only and write_only, and assumed to be read_only if no qualifier is 1091 // specified. 1092 switch (Call->getDirectCallee()->getBuiltinID()) { 1093 case Builtin::BIread_pipe: 1094 case Builtin::BIreserve_read_pipe: 1095 case Builtin::BIcommit_read_pipe: 1096 case Builtin::BIwork_group_reserve_read_pipe: 1097 case Builtin::BIsub_group_reserve_read_pipe: 1098 case Builtin::BIwork_group_commit_read_pipe: 1099 case Builtin::BIsub_group_commit_read_pipe: 1100 if (!(!AccessQual || AccessQual->isReadOnly())) { 1101 S.Diag(Arg0->getBeginLoc(), 1102 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1103 << "read_only" << Arg0->getSourceRange(); 1104 return true; 1105 } 1106 break; 1107 case Builtin::BIwrite_pipe: 1108 case Builtin::BIreserve_write_pipe: 1109 case Builtin::BIcommit_write_pipe: 1110 case Builtin::BIwork_group_reserve_write_pipe: 1111 case Builtin::BIsub_group_reserve_write_pipe: 1112 case Builtin::BIwork_group_commit_write_pipe: 1113 case Builtin::BIsub_group_commit_write_pipe: 1114 if (!(AccessQual && AccessQual->isWriteOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "write_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 default: 1122 break; 1123 } 1124 return false; 1125 } 1126 1127 /// Returns true if pipe element type is different from the pointer. 1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1129 const Expr *Arg0 = Call->getArg(0); 1130 const Expr *ArgIdx = Call->getArg(Idx); 1131 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1132 const QualType EltTy = PipeTy->getElementType(); 1133 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1134 // The Idx argument should be a pointer and the type of the pointer and 1135 // the type of pipe element should also be the same. 1136 if (!ArgTy || 1137 !S.Context.hasSameType( 1138 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1139 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1140 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1141 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1142 return true; 1143 } 1144 return false; 1145 } 1146 1147 // Performs semantic analysis for the read/write_pipe call. 1148 // \param S Reference to the semantic analyzer. 1149 // \param Call A pointer to the builtin call. 1150 // \return True if a semantic error has been found, false otherwise. 1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1152 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1153 // functions have two forms. 1154 switch (Call->getNumArgs()) { 1155 case 2: 1156 if (checkOpenCLPipeArg(S, Call)) 1157 return true; 1158 // The call with 2 arguments should be 1159 // read/write_pipe(pipe T, T*). 1160 // Check packet type T. 1161 if (checkOpenCLPipePacketType(S, Call, 1)) 1162 return true; 1163 break; 1164 1165 case 4: { 1166 if (checkOpenCLPipeArg(S, Call)) 1167 return true; 1168 // The call with 4 arguments should be 1169 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1170 // Check reserve_id_t. 1171 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1172 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1173 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1174 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1175 return true; 1176 } 1177 1178 // Check the index. 1179 const Expr *Arg2 = Call->getArg(2); 1180 if (!Arg2->getType()->isIntegerType() && 1181 !Arg2->getType()->isUnsignedIntegerType()) { 1182 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1183 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1184 << Arg2->getType() << Arg2->getSourceRange(); 1185 return true; 1186 } 1187 1188 // Check packet type T. 1189 if (checkOpenCLPipePacketType(S, Call, 3)) 1190 return true; 1191 } break; 1192 default: 1193 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1194 << Call->getDirectCallee() << Call->getSourceRange(); 1195 return true; 1196 } 1197 1198 return false; 1199 } 1200 1201 // Performs a semantic analysis on the {work_group_/sub_group_ 1202 // /_}reserve_{read/write}_pipe 1203 // \param S Reference to the semantic analyzer. 1204 // \param Call The call to the builtin function to be analyzed. 1205 // \return True if a semantic error was found, false otherwise. 1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1207 if (checkArgCount(S, Call, 2)) 1208 return true; 1209 1210 if (checkOpenCLPipeArg(S, Call)) 1211 return true; 1212 1213 // Check the reserve size. 1214 if (!Call->getArg(1)->getType()->isIntegerType() && 1215 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1216 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1217 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1218 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1219 return true; 1220 } 1221 1222 // Since return type of reserve_read/write_pipe built-in function is 1223 // reserve_id_t, which is not defined in the builtin def file , we used int 1224 // as return type and need to override the return type of these functions. 1225 Call->setType(S.Context.OCLReserveIDTy); 1226 1227 return false; 1228 } 1229 1230 // Performs a semantic analysis on {work_group_/sub_group_ 1231 // /_}commit_{read/write}_pipe 1232 // \param S Reference to the semantic analyzer. 1233 // \param Call The call to the builtin function to be analyzed. 1234 // \return True if a semantic error was found, false otherwise. 1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1236 if (checkArgCount(S, Call, 2)) 1237 return true; 1238 1239 if (checkOpenCLPipeArg(S, Call)) 1240 return true; 1241 1242 // Check reserve_id_t. 1243 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1244 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1245 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1246 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1247 return true; 1248 } 1249 1250 return false; 1251 } 1252 1253 // Performs a semantic analysis on the call to built-in Pipe 1254 // Query Functions. 1255 // \param S Reference to the semantic analyzer. 1256 // \param Call The call to the builtin function to be analyzed. 1257 // \return True if a semantic error was found, false otherwise. 1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1259 if (checkArgCount(S, Call, 1)) 1260 return true; 1261 1262 if (!Call->getArg(0)->getType()->isPipeType()) { 1263 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1264 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1265 return true; 1266 } 1267 1268 return false; 1269 } 1270 1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1272 // Performs semantic analysis for the to_global/local/private call. 1273 // \param S Reference to the semantic analyzer. 1274 // \param BuiltinID ID of the builtin function. 1275 // \param Call A pointer to the builtin call. 1276 // \return True if a semantic error has been found, false otherwise. 1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1278 CallExpr *Call) { 1279 if (checkArgCount(S, Call, 1)) 1280 return true; 1281 1282 auto RT = Call->getArg(0)->getType(); 1283 if (!RT->isPointerType() || RT->getPointeeType() 1284 .getAddressSpace() == LangAS::opencl_constant) { 1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1286 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1287 return true; 1288 } 1289 1290 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1291 S.Diag(Call->getArg(0)->getBeginLoc(), 1292 diag::warn_opencl_generic_address_space_arg) 1293 << Call->getDirectCallee()->getNameInfo().getAsString() 1294 << Call->getArg(0)->getSourceRange(); 1295 } 1296 1297 RT = RT->getPointeeType(); 1298 auto Qual = RT.getQualifiers(); 1299 switch (BuiltinID) { 1300 case Builtin::BIto_global: 1301 Qual.setAddressSpace(LangAS::opencl_global); 1302 break; 1303 case Builtin::BIto_local: 1304 Qual.setAddressSpace(LangAS::opencl_local); 1305 break; 1306 case Builtin::BIto_private: 1307 Qual.setAddressSpace(LangAS::opencl_private); 1308 break; 1309 default: 1310 llvm_unreachable("Invalid builtin function"); 1311 } 1312 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1313 RT.getUnqualifiedType(), Qual))); 1314 1315 return false; 1316 } 1317 1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1319 if (checkArgCount(S, TheCall, 1)) 1320 return ExprError(); 1321 1322 // Compute __builtin_launder's parameter type from the argument. 1323 // The parameter type is: 1324 // * The type of the argument if it's not an array or function type, 1325 // Otherwise, 1326 // * The decayed argument type. 1327 QualType ParamTy = [&]() { 1328 QualType ArgTy = TheCall->getArg(0)->getType(); 1329 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1330 return S.Context.getPointerType(Ty->getElementType()); 1331 if (ArgTy->isFunctionType()) { 1332 return S.Context.getPointerType(ArgTy); 1333 } 1334 return ArgTy; 1335 }(); 1336 1337 TheCall->setType(ParamTy); 1338 1339 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1340 if (!ParamTy->isPointerType()) 1341 return 0; 1342 if (ParamTy->isFunctionPointerType()) 1343 return 1; 1344 if (ParamTy->isVoidPointerType()) 1345 return 2; 1346 return llvm::Optional<unsigned>{}; 1347 }(); 1348 if (DiagSelect.hasValue()) { 1349 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1350 << DiagSelect.getValue() << TheCall->getSourceRange(); 1351 return ExprError(); 1352 } 1353 1354 // We either have an incomplete class type, or we have a class template 1355 // whose instantiation has not been forced. Example: 1356 // 1357 // template <class T> struct Foo { T value; }; 1358 // Foo<int> *p = nullptr; 1359 // auto *d = __builtin_launder(p); 1360 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1361 diag::err_incomplete_type)) 1362 return ExprError(); 1363 1364 assert(ParamTy->getPointeeType()->isObjectType() && 1365 "Unhandled non-object pointer case"); 1366 1367 InitializedEntity Entity = 1368 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1369 ExprResult Arg = 1370 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1371 if (Arg.isInvalid()) 1372 return ExprError(); 1373 TheCall->setArg(0, Arg.get()); 1374 1375 return TheCall; 1376 } 1377 1378 // Emit an error and return true if the current architecture is not in the list 1379 // of supported architectures. 1380 static bool 1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1382 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1383 llvm::Triple::ArchType CurArch = 1384 S.getASTContext().getTargetInfo().getTriple().getArch(); 1385 if (llvm::is_contained(SupportedArchs, CurArch)) 1386 return false; 1387 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1388 << TheCall->getSourceRange(); 1389 return true; 1390 } 1391 1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1393 SourceLocation CallSiteLoc); 1394 1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1396 CallExpr *TheCall) { 1397 switch (TI.getTriple().getArch()) { 1398 default: 1399 // Some builtins don't require additional checking, so just consider these 1400 // acceptable. 1401 return false; 1402 case llvm::Triple::arm: 1403 case llvm::Triple::armeb: 1404 case llvm::Triple::thumb: 1405 case llvm::Triple::thumbeb: 1406 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1407 case llvm::Triple::aarch64: 1408 case llvm::Triple::aarch64_32: 1409 case llvm::Triple::aarch64_be: 1410 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1411 case llvm::Triple::bpfeb: 1412 case llvm::Triple::bpfel: 1413 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::hexagon: 1415 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1416 case llvm::Triple::mips: 1417 case llvm::Triple::mipsel: 1418 case llvm::Triple::mips64: 1419 case llvm::Triple::mips64el: 1420 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::systemz: 1422 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1423 case llvm::Triple::x86: 1424 case llvm::Triple::x86_64: 1425 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1426 case llvm::Triple::ppc: 1427 case llvm::Triple::ppcle: 1428 case llvm::Triple::ppc64: 1429 case llvm::Triple::ppc64le: 1430 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1431 case llvm::Triple::amdgcn: 1432 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1433 case llvm::Triple::riscv32: 1434 case llvm::Triple::riscv64: 1435 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1436 } 1437 } 1438 1439 ExprResult 1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1441 CallExpr *TheCall) { 1442 ExprResult TheCallResult(TheCall); 1443 1444 // Find out if any arguments are required to be integer constant expressions. 1445 unsigned ICEArguments = 0; 1446 ASTContext::GetBuiltinTypeError Error; 1447 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1448 if (Error != ASTContext::GE_None) 1449 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1450 1451 // If any arguments are required to be ICE's, check and diagnose. 1452 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1453 // Skip arguments not required to be ICE's. 1454 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1455 1456 llvm::APSInt Result; 1457 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1458 return true; 1459 ICEArguments &= ~(1 << ArgNo); 1460 } 1461 1462 switch (BuiltinID) { 1463 case Builtin::BI__builtin___CFStringMakeConstantString: 1464 assert(TheCall->getNumArgs() == 1 && 1465 "Wrong # arguments to builtin CFStringMakeConstantString"); 1466 if (CheckObjCString(TheCall->getArg(0))) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__builtin_ms_va_start: 1470 case Builtin::BI__builtin_stdarg_start: 1471 case Builtin::BI__builtin_va_start: 1472 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1473 return ExprError(); 1474 break; 1475 case Builtin::BI__va_start: { 1476 switch (Context.getTargetInfo().getTriple().getArch()) { 1477 case llvm::Triple::aarch64: 1478 case llvm::Triple::arm: 1479 case llvm::Triple::thumb: 1480 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1481 return ExprError(); 1482 break; 1483 default: 1484 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1485 return ExprError(); 1486 break; 1487 } 1488 break; 1489 } 1490 1491 // The acquire, release, and no fence variants are ARM and AArch64 only. 1492 case Builtin::BI_interlockedbittestandset_acq: 1493 case Builtin::BI_interlockedbittestandset_rel: 1494 case Builtin::BI_interlockedbittestandset_nf: 1495 case Builtin::BI_interlockedbittestandreset_acq: 1496 case Builtin::BI_interlockedbittestandreset_rel: 1497 case Builtin::BI_interlockedbittestandreset_nf: 1498 if (CheckBuiltinTargetSupport( 1499 *this, BuiltinID, TheCall, 1500 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1501 return ExprError(); 1502 break; 1503 1504 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1505 case Builtin::BI_bittest64: 1506 case Builtin::BI_bittestandcomplement64: 1507 case Builtin::BI_bittestandreset64: 1508 case Builtin::BI_bittestandset64: 1509 case Builtin::BI_interlockedbittestandreset64: 1510 case Builtin::BI_interlockedbittestandset64: 1511 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1512 {llvm::Triple::x86_64, llvm::Triple::arm, 1513 llvm::Triple::thumb, llvm::Triple::aarch64})) 1514 return ExprError(); 1515 break; 1516 1517 case Builtin::BI__builtin_isgreater: 1518 case Builtin::BI__builtin_isgreaterequal: 1519 case Builtin::BI__builtin_isless: 1520 case Builtin::BI__builtin_islessequal: 1521 case Builtin::BI__builtin_islessgreater: 1522 case Builtin::BI__builtin_isunordered: 1523 if (SemaBuiltinUnorderedCompare(TheCall)) 1524 return ExprError(); 1525 break; 1526 case Builtin::BI__builtin_fpclassify: 1527 if (SemaBuiltinFPClassification(TheCall, 6)) 1528 return ExprError(); 1529 break; 1530 case Builtin::BI__builtin_isfinite: 1531 case Builtin::BI__builtin_isinf: 1532 case Builtin::BI__builtin_isinf_sign: 1533 case Builtin::BI__builtin_isnan: 1534 case Builtin::BI__builtin_isnormal: 1535 case Builtin::BI__builtin_signbit: 1536 case Builtin::BI__builtin_signbitf: 1537 case Builtin::BI__builtin_signbitl: 1538 if (SemaBuiltinFPClassification(TheCall, 1)) 1539 return ExprError(); 1540 break; 1541 case Builtin::BI__builtin_shufflevector: 1542 return SemaBuiltinShuffleVector(TheCall); 1543 // TheCall will be freed by the smart pointer here, but that's fine, since 1544 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1545 case Builtin::BI__builtin_prefetch: 1546 if (SemaBuiltinPrefetch(TheCall)) 1547 return ExprError(); 1548 break; 1549 case Builtin::BI__builtin_alloca_with_align: 1550 if (SemaBuiltinAllocaWithAlign(TheCall)) 1551 return ExprError(); 1552 LLVM_FALLTHROUGH; 1553 case Builtin::BI__builtin_alloca: 1554 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1555 << TheCall->getDirectCallee(); 1556 break; 1557 case Builtin::BI__assume: 1558 case Builtin::BI__builtin_assume: 1559 if (SemaBuiltinAssume(TheCall)) 1560 return ExprError(); 1561 break; 1562 case Builtin::BI__builtin_assume_aligned: 1563 if (SemaBuiltinAssumeAligned(TheCall)) 1564 return ExprError(); 1565 break; 1566 case Builtin::BI__builtin_dynamic_object_size: 1567 case Builtin::BI__builtin_object_size: 1568 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1569 return ExprError(); 1570 break; 1571 case Builtin::BI__builtin_longjmp: 1572 if (SemaBuiltinLongjmp(TheCall)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__builtin_setjmp: 1576 if (SemaBuiltinSetjmp(TheCall)) 1577 return ExprError(); 1578 break; 1579 case Builtin::BI__builtin_classify_type: 1580 if (checkArgCount(*this, TheCall, 1)) return true; 1581 TheCall->setType(Context.IntTy); 1582 break; 1583 case Builtin::BI__builtin_complex: 1584 if (SemaBuiltinComplex(TheCall)) 1585 return ExprError(); 1586 break; 1587 case Builtin::BI__builtin_constant_p: { 1588 if (checkArgCount(*this, TheCall, 1)) return true; 1589 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1590 if (Arg.isInvalid()) return true; 1591 TheCall->setArg(0, Arg.get()); 1592 TheCall->setType(Context.IntTy); 1593 break; 1594 } 1595 case Builtin::BI__builtin_launder: 1596 return SemaBuiltinLaunder(*this, TheCall); 1597 case Builtin::BI__sync_fetch_and_add: 1598 case Builtin::BI__sync_fetch_and_add_1: 1599 case Builtin::BI__sync_fetch_and_add_2: 1600 case Builtin::BI__sync_fetch_and_add_4: 1601 case Builtin::BI__sync_fetch_and_add_8: 1602 case Builtin::BI__sync_fetch_and_add_16: 1603 case Builtin::BI__sync_fetch_and_sub: 1604 case Builtin::BI__sync_fetch_and_sub_1: 1605 case Builtin::BI__sync_fetch_and_sub_2: 1606 case Builtin::BI__sync_fetch_and_sub_4: 1607 case Builtin::BI__sync_fetch_and_sub_8: 1608 case Builtin::BI__sync_fetch_and_sub_16: 1609 case Builtin::BI__sync_fetch_and_or: 1610 case Builtin::BI__sync_fetch_and_or_1: 1611 case Builtin::BI__sync_fetch_and_or_2: 1612 case Builtin::BI__sync_fetch_and_or_4: 1613 case Builtin::BI__sync_fetch_and_or_8: 1614 case Builtin::BI__sync_fetch_and_or_16: 1615 case Builtin::BI__sync_fetch_and_and: 1616 case Builtin::BI__sync_fetch_and_and_1: 1617 case Builtin::BI__sync_fetch_and_and_2: 1618 case Builtin::BI__sync_fetch_and_and_4: 1619 case Builtin::BI__sync_fetch_and_and_8: 1620 case Builtin::BI__sync_fetch_and_and_16: 1621 case Builtin::BI__sync_fetch_and_xor: 1622 case Builtin::BI__sync_fetch_and_xor_1: 1623 case Builtin::BI__sync_fetch_and_xor_2: 1624 case Builtin::BI__sync_fetch_and_xor_4: 1625 case Builtin::BI__sync_fetch_and_xor_8: 1626 case Builtin::BI__sync_fetch_and_xor_16: 1627 case Builtin::BI__sync_fetch_and_nand: 1628 case Builtin::BI__sync_fetch_and_nand_1: 1629 case Builtin::BI__sync_fetch_and_nand_2: 1630 case Builtin::BI__sync_fetch_and_nand_4: 1631 case Builtin::BI__sync_fetch_and_nand_8: 1632 case Builtin::BI__sync_fetch_and_nand_16: 1633 case Builtin::BI__sync_add_and_fetch: 1634 case Builtin::BI__sync_add_and_fetch_1: 1635 case Builtin::BI__sync_add_and_fetch_2: 1636 case Builtin::BI__sync_add_and_fetch_4: 1637 case Builtin::BI__sync_add_and_fetch_8: 1638 case Builtin::BI__sync_add_and_fetch_16: 1639 case Builtin::BI__sync_sub_and_fetch: 1640 case Builtin::BI__sync_sub_and_fetch_1: 1641 case Builtin::BI__sync_sub_and_fetch_2: 1642 case Builtin::BI__sync_sub_and_fetch_4: 1643 case Builtin::BI__sync_sub_and_fetch_8: 1644 case Builtin::BI__sync_sub_and_fetch_16: 1645 case Builtin::BI__sync_and_and_fetch: 1646 case Builtin::BI__sync_and_and_fetch_1: 1647 case Builtin::BI__sync_and_and_fetch_2: 1648 case Builtin::BI__sync_and_and_fetch_4: 1649 case Builtin::BI__sync_and_and_fetch_8: 1650 case Builtin::BI__sync_and_and_fetch_16: 1651 case Builtin::BI__sync_or_and_fetch: 1652 case Builtin::BI__sync_or_and_fetch_1: 1653 case Builtin::BI__sync_or_and_fetch_2: 1654 case Builtin::BI__sync_or_and_fetch_4: 1655 case Builtin::BI__sync_or_and_fetch_8: 1656 case Builtin::BI__sync_or_and_fetch_16: 1657 case Builtin::BI__sync_xor_and_fetch: 1658 case Builtin::BI__sync_xor_and_fetch_1: 1659 case Builtin::BI__sync_xor_and_fetch_2: 1660 case Builtin::BI__sync_xor_and_fetch_4: 1661 case Builtin::BI__sync_xor_and_fetch_8: 1662 case Builtin::BI__sync_xor_and_fetch_16: 1663 case Builtin::BI__sync_nand_and_fetch: 1664 case Builtin::BI__sync_nand_and_fetch_1: 1665 case Builtin::BI__sync_nand_and_fetch_2: 1666 case Builtin::BI__sync_nand_and_fetch_4: 1667 case Builtin::BI__sync_nand_and_fetch_8: 1668 case Builtin::BI__sync_nand_and_fetch_16: 1669 case Builtin::BI__sync_val_compare_and_swap: 1670 case Builtin::BI__sync_val_compare_and_swap_1: 1671 case Builtin::BI__sync_val_compare_and_swap_2: 1672 case Builtin::BI__sync_val_compare_and_swap_4: 1673 case Builtin::BI__sync_val_compare_and_swap_8: 1674 case Builtin::BI__sync_val_compare_and_swap_16: 1675 case Builtin::BI__sync_bool_compare_and_swap: 1676 case Builtin::BI__sync_bool_compare_and_swap_1: 1677 case Builtin::BI__sync_bool_compare_and_swap_2: 1678 case Builtin::BI__sync_bool_compare_and_swap_4: 1679 case Builtin::BI__sync_bool_compare_and_swap_8: 1680 case Builtin::BI__sync_bool_compare_and_swap_16: 1681 case Builtin::BI__sync_lock_test_and_set: 1682 case Builtin::BI__sync_lock_test_and_set_1: 1683 case Builtin::BI__sync_lock_test_and_set_2: 1684 case Builtin::BI__sync_lock_test_and_set_4: 1685 case Builtin::BI__sync_lock_test_and_set_8: 1686 case Builtin::BI__sync_lock_test_and_set_16: 1687 case Builtin::BI__sync_lock_release: 1688 case Builtin::BI__sync_lock_release_1: 1689 case Builtin::BI__sync_lock_release_2: 1690 case Builtin::BI__sync_lock_release_4: 1691 case Builtin::BI__sync_lock_release_8: 1692 case Builtin::BI__sync_lock_release_16: 1693 case Builtin::BI__sync_swap: 1694 case Builtin::BI__sync_swap_1: 1695 case Builtin::BI__sync_swap_2: 1696 case Builtin::BI__sync_swap_4: 1697 case Builtin::BI__sync_swap_8: 1698 case Builtin::BI__sync_swap_16: 1699 return SemaBuiltinAtomicOverloaded(TheCallResult); 1700 case Builtin::BI__sync_synchronize: 1701 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1702 << TheCall->getCallee()->getSourceRange(); 1703 break; 1704 case Builtin::BI__builtin_nontemporal_load: 1705 case Builtin::BI__builtin_nontemporal_store: 1706 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1707 case Builtin::BI__builtin_memcpy_inline: { 1708 clang::Expr *SizeOp = TheCall->getArg(2); 1709 // We warn about copying to or from `nullptr` pointers when `size` is 1710 // greater than 0. When `size` is value dependent we cannot evaluate its 1711 // value so we bail out. 1712 if (SizeOp->isValueDependent()) 1713 break; 1714 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1715 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1716 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1717 } 1718 break; 1719 } 1720 #define BUILTIN(ID, TYPE, ATTRS) 1721 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1722 case Builtin::BI##ID: \ 1723 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1724 #include "clang/Basic/Builtins.def" 1725 case Builtin::BI__annotation: 1726 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1727 return ExprError(); 1728 break; 1729 case Builtin::BI__builtin_annotation: 1730 if (SemaBuiltinAnnotation(*this, TheCall)) 1731 return ExprError(); 1732 break; 1733 case Builtin::BI__builtin_addressof: 1734 if (SemaBuiltinAddressof(*this, TheCall)) 1735 return ExprError(); 1736 break; 1737 case Builtin::BI__builtin_is_aligned: 1738 case Builtin::BI__builtin_align_up: 1739 case Builtin::BI__builtin_align_down: 1740 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1741 return ExprError(); 1742 break; 1743 case Builtin::BI__builtin_add_overflow: 1744 case Builtin::BI__builtin_sub_overflow: 1745 case Builtin::BI__builtin_mul_overflow: 1746 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1747 return ExprError(); 1748 break; 1749 case Builtin::BI__builtin_operator_new: 1750 case Builtin::BI__builtin_operator_delete: { 1751 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1752 ExprResult Res = 1753 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1754 if (Res.isInvalid()) 1755 CorrectDelayedTyposInExpr(TheCallResult.get()); 1756 return Res; 1757 } 1758 case Builtin::BI__builtin_dump_struct: { 1759 // We first want to ensure we are called with 2 arguments 1760 if (checkArgCount(*this, TheCall, 2)) 1761 return ExprError(); 1762 // Ensure that the first argument is of type 'struct XX *' 1763 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1764 const QualType PtrArgType = PtrArg->getType(); 1765 if (!PtrArgType->isPointerType() || 1766 !PtrArgType->getPointeeType()->isRecordType()) { 1767 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1768 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1769 << "structure pointer"; 1770 return ExprError(); 1771 } 1772 1773 // Ensure that the second argument is of type 'FunctionType' 1774 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1775 const QualType FnPtrArgType = FnPtrArg->getType(); 1776 if (!FnPtrArgType->isPointerType()) { 1777 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1778 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1779 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1780 return ExprError(); 1781 } 1782 1783 const auto *FuncType = 1784 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1785 1786 if (!FuncType) { 1787 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1788 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1789 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1790 return ExprError(); 1791 } 1792 1793 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1794 if (!FT->getNumParams()) { 1795 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1796 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1797 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1798 return ExprError(); 1799 } 1800 QualType PT = FT->getParamType(0); 1801 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1802 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1803 !PT->getPointeeType().isConstQualified()) { 1804 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1805 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1806 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1807 return ExprError(); 1808 } 1809 } 1810 1811 TheCall->setType(Context.IntTy); 1812 break; 1813 } 1814 case Builtin::BI__builtin_expect_with_probability: { 1815 // We first want to ensure we are called with 3 arguments 1816 if (checkArgCount(*this, TheCall, 3)) 1817 return ExprError(); 1818 // then check probability is constant float in range [0.0, 1.0] 1819 const Expr *ProbArg = TheCall->getArg(2); 1820 SmallVector<PartialDiagnosticAt, 8> Notes; 1821 Expr::EvalResult Eval; 1822 Eval.Diag = &Notes; 1823 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1824 !Eval.Val.isFloat()) { 1825 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1826 << ProbArg->getSourceRange(); 1827 for (const PartialDiagnosticAt &PDiag : Notes) 1828 Diag(PDiag.first, PDiag.second); 1829 return ExprError(); 1830 } 1831 llvm::APFloat Probability = Eval.Val.getFloat(); 1832 bool LoseInfo = false; 1833 Probability.convert(llvm::APFloat::IEEEdouble(), 1834 llvm::RoundingMode::Dynamic, &LoseInfo); 1835 if (!(Probability >= llvm::APFloat(0.0) && 1836 Probability <= llvm::APFloat(1.0))) { 1837 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1838 << ProbArg->getSourceRange(); 1839 return ExprError(); 1840 } 1841 break; 1842 } 1843 case Builtin::BI__builtin_preserve_access_index: 1844 if (SemaBuiltinPreserveAI(*this, TheCall)) 1845 return ExprError(); 1846 break; 1847 case Builtin::BI__builtin_call_with_static_chain: 1848 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1849 return ExprError(); 1850 break; 1851 case Builtin::BI__exception_code: 1852 case Builtin::BI_exception_code: 1853 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1854 diag::err_seh___except_block)) 1855 return ExprError(); 1856 break; 1857 case Builtin::BI__exception_info: 1858 case Builtin::BI_exception_info: 1859 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1860 diag::err_seh___except_filter)) 1861 return ExprError(); 1862 break; 1863 case Builtin::BI__GetExceptionInfo: 1864 if (checkArgCount(*this, TheCall, 1)) 1865 return ExprError(); 1866 1867 if (CheckCXXThrowOperand( 1868 TheCall->getBeginLoc(), 1869 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1870 TheCall)) 1871 return ExprError(); 1872 1873 TheCall->setType(Context.VoidPtrTy); 1874 break; 1875 // OpenCL v2.0, s6.13.16 - Pipe functions 1876 case Builtin::BIread_pipe: 1877 case Builtin::BIwrite_pipe: 1878 // Since those two functions are declared with var args, we need a semantic 1879 // check for the argument. 1880 if (SemaBuiltinRWPipe(*this, TheCall)) 1881 return ExprError(); 1882 break; 1883 case Builtin::BIreserve_read_pipe: 1884 case Builtin::BIreserve_write_pipe: 1885 case Builtin::BIwork_group_reserve_read_pipe: 1886 case Builtin::BIwork_group_reserve_write_pipe: 1887 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1888 return ExprError(); 1889 break; 1890 case Builtin::BIsub_group_reserve_read_pipe: 1891 case Builtin::BIsub_group_reserve_write_pipe: 1892 if (checkOpenCLSubgroupExt(*this, TheCall) || 1893 SemaBuiltinReserveRWPipe(*this, TheCall)) 1894 return ExprError(); 1895 break; 1896 case Builtin::BIcommit_read_pipe: 1897 case Builtin::BIcommit_write_pipe: 1898 case Builtin::BIwork_group_commit_read_pipe: 1899 case Builtin::BIwork_group_commit_write_pipe: 1900 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1901 return ExprError(); 1902 break; 1903 case Builtin::BIsub_group_commit_read_pipe: 1904 case Builtin::BIsub_group_commit_write_pipe: 1905 if (checkOpenCLSubgroupExt(*this, TheCall) || 1906 SemaBuiltinCommitRWPipe(*this, TheCall)) 1907 return ExprError(); 1908 break; 1909 case Builtin::BIget_pipe_num_packets: 1910 case Builtin::BIget_pipe_max_packets: 1911 if (SemaBuiltinPipePackets(*this, TheCall)) 1912 return ExprError(); 1913 break; 1914 case Builtin::BIto_global: 1915 case Builtin::BIto_local: 1916 case Builtin::BIto_private: 1917 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1918 return ExprError(); 1919 break; 1920 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1921 case Builtin::BIenqueue_kernel: 1922 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1923 return ExprError(); 1924 break; 1925 case Builtin::BIget_kernel_work_group_size: 1926 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1927 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1928 return ExprError(); 1929 break; 1930 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1931 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1932 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1933 return ExprError(); 1934 break; 1935 case Builtin::BI__builtin_os_log_format: 1936 Cleanup.setExprNeedsCleanups(true); 1937 LLVM_FALLTHROUGH; 1938 case Builtin::BI__builtin_os_log_format_buffer_size: 1939 if (SemaBuiltinOSLogFormat(TheCall)) 1940 return ExprError(); 1941 break; 1942 case Builtin::BI__builtin_frame_address: 1943 case Builtin::BI__builtin_return_address: { 1944 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1945 return ExprError(); 1946 1947 // -Wframe-address warning if non-zero passed to builtin 1948 // return/frame address. 1949 Expr::EvalResult Result; 1950 if (!TheCall->getArg(0)->isValueDependent() && 1951 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1952 Result.Val.getInt() != 0) 1953 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1954 << ((BuiltinID == Builtin::BI__builtin_return_address) 1955 ? "__builtin_return_address" 1956 : "__builtin_frame_address") 1957 << TheCall->getSourceRange(); 1958 break; 1959 } 1960 1961 case Builtin::BI__builtin_matrix_transpose: 1962 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1963 1964 case Builtin::BI__builtin_matrix_column_major_load: 1965 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1966 1967 case Builtin::BI__builtin_matrix_column_major_store: 1968 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1969 } 1970 1971 // Since the target specific builtins for each arch overlap, only check those 1972 // of the arch we are compiling for. 1973 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1974 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1975 assert(Context.getAuxTargetInfo() && 1976 "Aux Target Builtin, but not an aux target?"); 1977 1978 if (CheckTSBuiltinFunctionCall( 1979 *Context.getAuxTargetInfo(), 1980 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1981 return ExprError(); 1982 } else { 1983 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 1984 TheCall)) 1985 return ExprError(); 1986 } 1987 } 1988 1989 return TheCallResult; 1990 } 1991 1992 // Get the valid immediate range for the specified NEON type code. 1993 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1994 NeonTypeFlags Type(t); 1995 int IsQuad = ForceQuad ? true : Type.isQuad(); 1996 switch (Type.getEltType()) { 1997 case NeonTypeFlags::Int8: 1998 case NeonTypeFlags::Poly8: 1999 return shift ? 7 : (8 << IsQuad) - 1; 2000 case NeonTypeFlags::Int16: 2001 case NeonTypeFlags::Poly16: 2002 return shift ? 15 : (4 << IsQuad) - 1; 2003 case NeonTypeFlags::Int32: 2004 return shift ? 31 : (2 << IsQuad) - 1; 2005 case NeonTypeFlags::Int64: 2006 case NeonTypeFlags::Poly64: 2007 return shift ? 63 : (1 << IsQuad) - 1; 2008 case NeonTypeFlags::Poly128: 2009 return shift ? 127 : (1 << IsQuad) - 1; 2010 case NeonTypeFlags::Float16: 2011 assert(!shift && "cannot shift float types!"); 2012 return (4 << IsQuad) - 1; 2013 case NeonTypeFlags::Float32: 2014 assert(!shift && "cannot shift float types!"); 2015 return (2 << IsQuad) - 1; 2016 case NeonTypeFlags::Float64: 2017 assert(!shift && "cannot shift float types!"); 2018 return (1 << IsQuad) - 1; 2019 case NeonTypeFlags::BFloat16: 2020 assert(!shift && "cannot shift float types!"); 2021 return (4 << IsQuad) - 1; 2022 } 2023 llvm_unreachable("Invalid NeonTypeFlag!"); 2024 } 2025 2026 /// getNeonEltType - Return the QualType corresponding to the elements of 2027 /// the vector type specified by the NeonTypeFlags. This is used to check 2028 /// the pointer arguments for Neon load/store intrinsics. 2029 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2030 bool IsPolyUnsigned, bool IsInt64Long) { 2031 switch (Flags.getEltType()) { 2032 case NeonTypeFlags::Int8: 2033 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2034 case NeonTypeFlags::Int16: 2035 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2036 case NeonTypeFlags::Int32: 2037 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2038 case NeonTypeFlags::Int64: 2039 if (IsInt64Long) 2040 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2041 else 2042 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2043 : Context.LongLongTy; 2044 case NeonTypeFlags::Poly8: 2045 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2046 case NeonTypeFlags::Poly16: 2047 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2048 case NeonTypeFlags::Poly64: 2049 if (IsInt64Long) 2050 return Context.UnsignedLongTy; 2051 else 2052 return Context.UnsignedLongLongTy; 2053 case NeonTypeFlags::Poly128: 2054 break; 2055 case NeonTypeFlags::Float16: 2056 return Context.HalfTy; 2057 case NeonTypeFlags::Float32: 2058 return Context.FloatTy; 2059 case NeonTypeFlags::Float64: 2060 return Context.DoubleTy; 2061 case NeonTypeFlags::BFloat16: 2062 return Context.BFloat16Ty; 2063 } 2064 llvm_unreachable("Invalid NeonTypeFlag!"); 2065 } 2066 2067 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2068 // Range check SVE intrinsics that take immediate values. 2069 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2070 2071 switch (BuiltinID) { 2072 default: 2073 return false; 2074 #define GET_SVE_IMMEDIATE_CHECK 2075 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2076 #undef GET_SVE_IMMEDIATE_CHECK 2077 } 2078 2079 // Perform all the immediate checks for this builtin call. 2080 bool HasError = false; 2081 for (auto &I : ImmChecks) { 2082 int ArgNum, CheckTy, ElementSizeInBits; 2083 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2084 2085 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2086 2087 // Function that checks whether the operand (ArgNum) is an immediate 2088 // that is one of the predefined values. 2089 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2090 int ErrDiag) -> bool { 2091 // We can't check the value of a dependent argument. 2092 Expr *Arg = TheCall->getArg(ArgNum); 2093 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2094 return false; 2095 2096 // Check constant-ness first. 2097 llvm::APSInt Imm; 2098 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2099 return true; 2100 2101 if (!CheckImm(Imm.getSExtValue())) 2102 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2103 return false; 2104 }; 2105 2106 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2107 case SVETypeFlags::ImmCheck0_31: 2108 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2109 HasError = true; 2110 break; 2111 case SVETypeFlags::ImmCheck0_13: 2112 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2113 HasError = true; 2114 break; 2115 case SVETypeFlags::ImmCheck1_16: 2116 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2117 HasError = true; 2118 break; 2119 case SVETypeFlags::ImmCheck0_7: 2120 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2121 HasError = true; 2122 break; 2123 case SVETypeFlags::ImmCheckExtract: 2124 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2125 (2048 / ElementSizeInBits) - 1)) 2126 HasError = true; 2127 break; 2128 case SVETypeFlags::ImmCheckShiftRight: 2129 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2130 HasError = true; 2131 break; 2132 case SVETypeFlags::ImmCheckShiftRightNarrow: 2133 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2134 ElementSizeInBits / 2)) 2135 HasError = true; 2136 break; 2137 case SVETypeFlags::ImmCheckShiftLeft: 2138 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2139 ElementSizeInBits - 1)) 2140 HasError = true; 2141 break; 2142 case SVETypeFlags::ImmCheckLaneIndex: 2143 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2144 (128 / (1 * ElementSizeInBits)) - 1)) 2145 HasError = true; 2146 break; 2147 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2148 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2149 (128 / (2 * ElementSizeInBits)) - 1)) 2150 HasError = true; 2151 break; 2152 case SVETypeFlags::ImmCheckLaneIndexDot: 2153 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2154 (128 / (4 * ElementSizeInBits)) - 1)) 2155 HasError = true; 2156 break; 2157 case SVETypeFlags::ImmCheckComplexRot90_270: 2158 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2159 diag::err_rotation_argument_to_cadd)) 2160 HasError = true; 2161 break; 2162 case SVETypeFlags::ImmCheckComplexRotAll90: 2163 if (CheckImmediateInSet( 2164 [](int64_t V) { 2165 return V == 0 || V == 90 || V == 180 || V == 270; 2166 }, 2167 diag::err_rotation_argument_to_cmla)) 2168 HasError = true; 2169 break; 2170 case SVETypeFlags::ImmCheck0_1: 2171 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2172 HasError = true; 2173 break; 2174 case SVETypeFlags::ImmCheck0_2: 2175 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2176 HasError = true; 2177 break; 2178 case SVETypeFlags::ImmCheck0_3: 2179 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2180 HasError = true; 2181 break; 2182 } 2183 } 2184 2185 return HasError; 2186 } 2187 2188 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2189 unsigned BuiltinID, CallExpr *TheCall) { 2190 llvm::APSInt Result; 2191 uint64_t mask = 0; 2192 unsigned TV = 0; 2193 int PtrArgNum = -1; 2194 bool HasConstPtr = false; 2195 switch (BuiltinID) { 2196 #define GET_NEON_OVERLOAD_CHECK 2197 #include "clang/Basic/arm_neon.inc" 2198 #include "clang/Basic/arm_fp16.inc" 2199 #undef GET_NEON_OVERLOAD_CHECK 2200 } 2201 2202 // For NEON intrinsics which are overloaded on vector element type, validate 2203 // the immediate which specifies which variant to emit. 2204 unsigned ImmArg = TheCall->getNumArgs()-1; 2205 if (mask) { 2206 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2207 return true; 2208 2209 TV = Result.getLimitedValue(64); 2210 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2211 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2212 << TheCall->getArg(ImmArg)->getSourceRange(); 2213 } 2214 2215 if (PtrArgNum >= 0) { 2216 // Check that pointer arguments have the specified type. 2217 Expr *Arg = TheCall->getArg(PtrArgNum); 2218 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2219 Arg = ICE->getSubExpr(); 2220 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2221 QualType RHSTy = RHS.get()->getType(); 2222 2223 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2224 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2225 Arch == llvm::Triple::aarch64_32 || 2226 Arch == llvm::Triple::aarch64_be; 2227 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2228 QualType EltTy = 2229 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2230 if (HasConstPtr) 2231 EltTy = EltTy.withConst(); 2232 QualType LHSTy = Context.getPointerType(EltTy); 2233 AssignConvertType ConvTy; 2234 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2235 if (RHS.isInvalid()) 2236 return true; 2237 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2238 RHS.get(), AA_Assigning)) 2239 return true; 2240 } 2241 2242 // For NEON intrinsics which take an immediate value as part of the 2243 // instruction, range check them here. 2244 unsigned i = 0, l = 0, u = 0; 2245 switch (BuiltinID) { 2246 default: 2247 return false; 2248 #define GET_NEON_IMMEDIATE_CHECK 2249 #include "clang/Basic/arm_neon.inc" 2250 #include "clang/Basic/arm_fp16.inc" 2251 #undef GET_NEON_IMMEDIATE_CHECK 2252 } 2253 2254 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2255 } 2256 2257 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2258 switch (BuiltinID) { 2259 default: 2260 return false; 2261 #include "clang/Basic/arm_mve_builtin_sema.inc" 2262 } 2263 } 2264 2265 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2266 CallExpr *TheCall) { 2267 bool Err = false; 2268 switch (BuiltinID) { 2269 default: 2270 return false; 2271 #include "clang/Basic/arm_cde_builtin_sema.inc" 2272 } 2273 2274 if (Err) 2275 return true; 2276 2277 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2278 } 2279 2280 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2281 const Expr *CoprocArg, bool WantCDE) { 2282 if (isConstantEvaluated()) 2283 return false; 2284 2285 // We can't check the value of a dependent argument. 2286 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2287 return false; 2288 2289 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2290 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2291 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2292 2293 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2294 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2295 2296 if (IsCDECoproc != WantCDE) 2297 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2298 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2299 2300 return false; 2301 } 2302 2303 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2304 unsigned MaxWidth) { 2305 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2306 BuiltinID == ARM::BI__builtin_arm_ldaex || 2307 BuiltinID == ARM::BI__builtin_arm_strex || 2308 BuiltinID == ARM::BI__builtin_arm_stlex || 2309 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2310 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2311 BuiltinID == AArch64::BI__builtin_arm_strex || 2312 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2313 "unexpected ARM builtin"); 2314 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2315 BuiltinID == ARM::BI__builtin_arm_ldaex || 2316 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2317 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2318 2319 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2320 2321 // Ensure that we have the proper number of arguments. 2322 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2323 return true; 2324 2325 // Inspect the pointer argument of the atomic builtin. This should always be 2326 // a pointer type, whose element is an integral scalar or pointer type. 2327 // Because it is a pointer type, we don't have to worry about any implicit 2328 // casts here. 2329 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2330 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2331 if (PointerArgRes.isInvalid()) 2332 return true; 2333 PointerArg = PointerArgRes.get(); 2334 2335 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2336 if (!pointerType) { 2337 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2338 << PointerArg->getType() << PointerArg->getSourceRange(); 2339 return true; 2340 } 2341 2342 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2343 // task is to insert the appropriate casts into the AST. First work out just 2344 // what the appropriate type is. 2345 QualType ValType = pointerType->getPointeeType(); 2346 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2347 if (IsLdrex) 2348 AddrType.addConst(); 2349 2350 // Issue a warning if the cast is dodgy. 2351 CastKind CastNeeded = CK_NoOp; 2352 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2353 CastNeeded = CK_BitCast; 2354 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2355 << PointerArg->getType() << Context.getPointerType(AddrType) 2356 << AA_Passing << PointerArg->getSourceRange(); 2357 } 2358 2359 // Finally, do the cast and replace the argument with the corrected version. 2360 AddrType = Context.getPointerType(AddrType); 2361 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2362 if (PointerArgRes.isInvalid()) 2363 return true; 2364 PointerArg = PointerArgRes.get(); 2365 2366 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2367 2368 // In general, we allow ints, floats and pointers to be loaded and stored. 2369 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2370 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2371 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2372 << PointerArg->getType() << PointerArg->getSourceRange(); 2373 return true; 2374 } 2375 2376 // But ARM doesn't have instructions to deal with 128-bit versions. 2377 if (Context.getTypeSize(ValType) > MaxWidth) { 2378 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2379 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2380 << PointerArg->getType() << PointerArg->getSourceRange(); 2381 return true; 2382 } 2383 2384 switch (ValType.getObjCLifetime()) { 2385 case Qualifiers::OCL_None: 2386 case Qualifiers::OCL_ExplicitNone: 2387 // okay 2388 break; 2389 2390 case Qualifiers::OCL_Weak: 2391 case Qualifiers::OCL_Strong: 2392 case Qualifiers::OCL_Autoreleasing: 2393 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2394 << ValType << PointerArg->getSourceRange(); 2395 return true; 2396 } 2397 2398 if (IsLdrex) { 2399 TheCall->setType(ValType); 2400 return false; 2401 } 2402 2403 // Initialize the argument to be stored. 2404 ExprResult ValArg = TheCall->getArg(0); 2405 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2406 Context, ValType, /*consume*/ false); 2407 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2408 if (ValArg.isInvalid()) 2409 return true; 2410 TheCall->setArg(0, ValArg.get()); 2411 2412 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2413 // but the custom checker bypasses all default analysis. 2414 TheCall->setType(Context.IntTy); 2415 return false; 2416 } 2417 2418 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2419 CallExpr *TheCall) { 2420 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2421 BuiltinID == ARM::BI__builtin_arm_ldaex || 2422 BuiltinID == ARM::BI__builtin_arm_strex || 2423 BuiltinID == ARM::BI__builtin_arm_stlex) { 2424 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2425 } 2426 2427 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2428 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2429 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2430 } 2431 2432 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2433 BuiltinID == ARM::BI__builtin_arm_wsr64) 2434 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2435 2436 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2437 BuiltinID == ARM::BI__builtin_arm_rsrp || 2438 BuiltinID == ARM::BI__builtin_arm_wsr || 2439 BuiltinID == ARM::BI__builtin_arm_wsrp) 2440 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2441 2442 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2443 return true; 2444 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2445 return true; 2446 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2447 return true; 2448 2449 // For intrinsics which take an immediate value as part of the instruction, 2450 // range check them here. 2451 // FIXME: VFP Intrinsics should error if VFP not present. 2452 switch (BuiltinID) { 2453 default: return false; 2454 case ARM::BI__builtin_arm_ssat: 2455 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2456 case ARM::BI__builtin_arm_usat: 2457 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2458 case ARM::BI__builtin_arm_ssat16: 2459 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2460 case ARM::BI__builtin_arm_usat16: 2461 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2462 case ARM::BI__builtin_arm_vcvtr_f: 2463 case ARM::BI__builtin_arm_vcvtr_d: 2464 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2465 case ARM::BI__builtin_arm_dmb: 2466 case ARM::BI__builtin_arm_dsb: 2467 case ARM::BI__builtin_arm_isb: 2468 case ARM::BI__builtin_arm_dbg: 2469 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2470 case ARM::BI__builtin_arm_cdp: 2471 case ARM::BI__builtin_arm_cdp2: 2472 case ARM::BI__builtin_arm_mcr: 2473 case ARM::BI__builtin_arm_mcr2: 2474 case ARM::BI__builtin_arm_mrc: 2475 case ARM::BI__builtin_arm_mrc2: 2476 case ARM::BI__builtin_arm_mcrr: 2477 case ARM::BI__builtin_arm_mcrr2: 2478 case ARM::BI__builtin_arm_mrrc: 2479 case ARM::BI__builtin_arm_mrrc2: 2480 case ARM::BI__builtin_arm_ldc: 2481 case ARM::BI__builtin_arm_ldcl: 2482 case ARM::BI__builtin_arm_ldc2: 2483 case ARM::BI__builtin_arm_ldc2l: 2484 case ARM::BI__builtin_arm_stc: 2485 case ARM::BI__builtin_arm_stcl: 2486 case ARM::BI__builtin_arm_stc2: 2487 case ARM::BI__builtin_arm_stc2l: 2488 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2489 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2490 /*WantCDE*/ false); 2491 } 2492 } 2493 2494 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2495 unsigned BuiltinID, 2496 CallExpr *TheCall) { 2497 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2498 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2499 BuiltinID == AArch64::BI__builtin_arm_strex || 2500 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2501 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2502 } 2503 2504 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2505 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2506 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2507 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2508 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2509 } 2510 2511 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2512 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2513 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2514 2515 // Memory Tagging Extensions (MTE) Intrinsics 2516 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2517 BuiltinID == AArch64::BI__builtin_arm_addg || 2518 BuiltinID == AArch64::BI__builtin_arm_gmi || 2519 BuiltinID == AArch64::BI__builtin_arm_ldg || 2520 BuiltinID == AArch64::BI__builtin_arm_stg || 2521 BuiltinID == AArch64::BI__builtin_arm_subp) { 2522 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2523 } 2524 2525 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2526 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2527 BuiltinID == AArch64::BI__builtin_arm_wsr || 2528 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2529 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2530 2531 // Only check the valid encoding range. Any constant in this range would be 2532 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2533 // an exception for incorrect registers. This matches MSVC behavior. 2534 if (BuiltinID == AArch64::BI_ReadStatusReg || 2535 BuiltinID == AArch64::BI_WriteStatusReg) 2536 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2537 2538 if (BuiltinID == AArch64::BI__getReg) 2539 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2540 2541 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2542 return true; 2543 2544 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2545 return true; 2546 2547 // For intrinsics which take an immediate value as part of the instruction, 2548 // range check them here. 2549 unsigned i = 0, l = 0, u = 0; 2550 switch (BuiltinID) { 2551 default: return false; 2552 case AArch64::BI__builtin_arm_dmb: 2553 case AArch64::BI__builtin_arm_dsb: 2554 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2555 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2556 } 2557 2558 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2559 } 2560 2561 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2562 if (Arg->getType()->getAsPlaceholderType()) 2563 return false; 2564 2565 // The first argument needs to be a record field access. 2566 // If it is an array element access, we delay decision 2567 // to BPF backend to check whether the access is a 2568 // field access or not. 2569 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2570 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2571 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2572 } 2573 2574 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2575 QualType VectorTy, QualType EltTy) { 2576 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2577 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2578 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2579 << Call->getSourceRange() << VectorEltTy << EltTy; 2580 return false; 2581 } 2582 return true; 2583 } 2584 2585 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2586 QualType ArgType = Arg->getType(); 2587 if (ArgType->getAsPlaceholderType()) 2588 return false; 2589 2590 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2591 // format: 2592 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2593 // 2. <type> var; 2594 // __builtin_preserve_type_info(var, flag); 2595 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2596 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2597 return false; 2598 2599 // Typedef type. 2600 if (ArgType->getAs<TypedefType>()) 2601 return true; 2602 2603 // Record type or Enum type. 2604 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2605 if (const auto *RT = Ty->getAs<RecordType>()) { 2606 if (!RT->getDecl()->getDeclName().isEmpty()) 2607 return true; 2608 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2609 if (!ET->getDecl()->getDeclName().isEmpty()) 2610 return true; 2611 } 2612 2613 return false; 2614 } 2615 2616 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2617 QualType ArgType = Arg->getType(); 2618 if (ArgType->getAsPlaceholderType()) 2619 return false; 2620 2621 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2622 // format: 2623 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2624 // flag); 2625 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2626 if (!UO) 2627 return false; 2628 2629 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2630 if (!CE) 2631 return false; 2632 if (CE->getCastKind() != CK_IntegralToPointer && 2633 CE->getCastKind() != CK_NullToPointer) 2634 return false; 2635 2636 // The integer must be from an EnumConstantDecl. 2637 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2638 if (!DR) 2639 return false; 2640 2641 const EnumConstantDecl *Enumerator = 2642 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2643 if (!Enumerator) 2644 return false; 2645 2646 // The type must be EnumType. 2647 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2648 const auto *ET = Ty->getAs<EnumType>(); 2649 if (!ET) 2650 return false; 2651 2652 // The enum value must be supported. 2653 for (auto *EDI : ET->getDecl()->enumerators()) { 2654 if (EDI == Enumerator) 2655 return true; 2656 } 2657 2658 return false; 2659 } 2660 2661 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2662 CallExpr *TheCall) { 2663 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2664 BuiltinID == BPF::BI__builtin_btf_type_id || 2665 BuiltinID == BPF::BI__builtin_preserve_type_info || 2666 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2667 "unexpected BPF builtin"); 2668 2669 if (checkArgCount(*this, TheCall, 2)) 2670 return true; 2671 2672 // The second argument needs to be a constant int 2673 Expr *Arg = TheCall->getArg(1); 2674 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2675 diag::kind kind; 2676 if (!Value) { 2677 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2678 kind = diag::err_preserve_field_info_not_const; 2679 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2680 kind = diag::err_btf_type_id_not_const; 2681 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2682 kind = diag::err_preserve_type_info_not_const; 2683 else 2684 kind = diag::err_preserve_enum_value_not_const; 2685 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2686 return true; 2687 } 2688 2689 // The first argument 2690 Arg = TheCall->getArg(0); 2691 bool InvalidArg = false; 2692 bool ReturnUnsignedInt = true; 2693 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2694 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2695 InvalidArg = true; 2696 kind = diag::err_preserve_field_info_not_field; 2697 } 2698 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2699 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2700 InvalidArg = true; 2701 kind = diag::err_preserve_type_info_invalid; 2702 } 2703 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2704 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2705 InvalidArg = true; 2706 kind = diag::err_preserve_enum_value_invalid; 2707 } 2708 ReturnUnsignedInt = false; 2709 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2710 ReturnUnsignedInt = false; 2711 } 2712 2713 if (InvalidArg) { 2714 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2715 return true; 2716 } 2717 2718 if (ReturnUnsignedInt) 2719 TheCall->setType(Context.UnsignedIntTy); 2720 else 2721 TheCall->setType(Context.UnsignedLongTy); 2722 return false; 2723 } 2724 2725 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2726 struct ArgInfo { 2727 uint8_t OpNum; 2728 bool IsSigned; 2729 uint8_t BitWidth; 2730 uint8_t Align; 2731 }; 2732 struct BuiltinInfo { 2733 unsigned BuiltinID; 2734 ArgInfo Infos[2]; 2735 }; 2736 2737 static BuiltinInfo Infos[] = { 2738 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2739 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2740 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2741 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2742 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2743 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2744 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2745 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2746 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2747 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2748 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2749 2750 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2761 2762 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2814 {{ 1, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2822 {{ 1, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2829 { 2, false, 5, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2831 { 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2833 { 3, false, 5, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2835 { 3, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2852 {{ 2, false, 4, 0 }, 2853 { 3, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2855 {{ 2, false, 4, 0 }, 2856 { 3, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2858 {{ 2, false, 4, 0 }, 2859 { 3, false, 5, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2861 {{ 2, false, 4, 0 }, 2862 { 3, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2874 { 2, false, 5, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2876 { 2, false, 6, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2886 {{ 1, false, 4, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2889 {{ 1, false, 4, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2910 {{ 3, false, 1, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2915 {{ 3, false, 1, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2920 {{ 3, false, 1, 0 }} }, 2921 }; 2922 2923 // Use a dynamically initialized static to sort the table exactly once on 2924 // first run. 2925 static const bool SortOnce = 2926 (llvm::sort(Infos, 2927 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2928 return LHS.BuiltinID < RHS.BuiltinID; 2929 }), 2930 true); 2931 (void)SortOnce; 2932 2933 const BuiltinInfo *F = llvm::partition_point( 2934 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2935 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2936 return false; 2937 2938 bool Error = false; 2939 2940 for (const ArgInfo &A : F->Infos) { 2941 // Ignore empty ArgInfo elements. 2942 if (A.BitWidth == 0) 2943 continue; 2944 2945 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2946 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2947 if (!A.Align) { 2948 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2949 } else { 2950 unsigned M = 1 << A.Align; 2951 Min *= M; 2952 Max *= M; 2953 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2954 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2955 } 2956 } 2957 return Error; 2958 } 2959 2960 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2961 CallExpr *TheCall) { 2962 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2963 } 2964 2965 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2966 unsigned BuiltinID, CallExpr *TheCall) { 2967 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2968 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2969 } 2970 2971 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2972 CallExpr *TheCall) { 2973 2974 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2975 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2976 if (!TI.hasFeature("dsp")) 2977 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2978 } 2979 2980 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2981 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2982 if (!TI.hasFeature("dspr2")) 2983 return Diag(TheCall->getBeginLoc(), 2984 diag::err_mips_builtin_requires_dspr2); 2985 } 2986 2987 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2988 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2989 if (!TI.hasFeature("msa")) 2990 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2991 } 2992 2993 return false; 2994 } 2995 2996 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2997 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2998 // ordering for DSP is unspecified. MSA is ordered by the data format used 2999 // by the underlying instruction i.e., df/m, df/n and then by size. 3000 // 3001 // FIXME: The size tests here should instead be tablegen'd along with the 3002 // definitions from include/clang/Basic/BuiltinsMips.def. 3003 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3004 // be too. 3005 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3006 unsigned i = 0, l = 0, u = 0, m = 0; 3007 switch (BuiltinID) { 3008 default: return false; 3009 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3010 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3011 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3012 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3013 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3014 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3015 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3016 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3017 // df/m field. 3018 // These intrinsics take an unsigned 3 bit immediate. 3019 case Mips::BI__builtin_msa_bclri_b: 3020 case Mips::BI__builtin_msa_bnegi_b: 3021 case Mips::BI__builtin_msa_bseti_b: 3022 case Mips::BI__builtin_msa_sat_s_b: 3023 case Mips::BI__builtin_msa_sat_u_b: 3024 case Mips::BI__builtin_msa_slli_b: 3025 case Mips::BI__builtin_msa_srai_b: 3026 case Mips::BI__builtin_msa_srari_b: 3027 case Mips::BI__builtin_msa_srli_b: 3028 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3029 case Mips::BI__builtin_msa_binsli_b: 3030 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3031 // These intrinsics take an unsigned 4 bit immediate. 3032 case Mips::BI__builtin_msa_bclri_h: 3033 case Mips::BI__builtin_msa_bnegi_h: 3034 case Mips::BI__builtin_msa_bseti_h: 3035 case Mips::BI__builtin_msa_sat_s_h: 3036 case Mips::BI__builtin_msa_sat_u_h: 3037 case Mips::BI__builtin_msa_slli_h: 3038 case Mips::BI__builtin_msa_srai_h: 3039 case Mips::BI__builtin_msa_srari_h: 3040 case Mips::BI__builtin_msa_srli_h: 3041 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3042 case Mips::BI__builtin_msa_binsli_h: 3043 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3044 // These intrinsics take an unsigned 5 bit immediate. 3045 // The first block of intrinsics actually have an unsigned 5 bit field, 3046 // not a df/n field. 3047 case Mips::BI__builtin_msa_cfcmsa: 3048 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3049 case Mips::BI__builtin_msa_clei_u_b: 3050 case Mips::BI__builtin_msa_clei_u_h: 3051 case Mips::BI__builtin_msa_clei_u_w: 3052 case Mips::BI__builtin_msa_clei_u_d: 3053 case Mips::BI__builtin_msa_clti_u_b: 3054 case Mips::BI__builtin_msa_clti_u_h: 3055 case Mips::BI__builtin_msa_clti_u_w: 3056 case Mips::BI__builtin_msa_clti_u_d: 3057 case Mips::BI__builtin_msa_maxi_u_b: 3058 case Mips::BI__builtin_msa_maxi_u_h: 3059 case Mips::BI__builtin_msa_maxi_u_w: 3060 case Mips::BI__builtin_msa_maxi_u_d: 3061 case Mips::BI__builtin_msa_mini_u_b: 3062 case Mips::BI__builtin_msa_mini_u_h: 3063 case Mips::BI__builtin_msa_mini_u_w: 3064 case Mips::BI__builtin_msa_mini_u_d: 3065 case Mips::BI__builtin_msa_addvi_b: 3066 case Mips::BI__builtin_msa_addvi_h: 3067 case Mips::BI__builtin_msa_addvi_w: 3068 case Mips::BI__builtin_msa_addvi_d: 3069 case Mips::BI__builtin_msa_bclri_w: 3070 case Mips::BI__builtin_msa_bnegi_w: 3071 case Mips::BI__builtin_msa_bseti_w: 3072 case Mips::BI__builtin_msa_sat_s_w: 3073 case Mips::BI__builtin_msa_sat_u_w: 3074 case Mips::BI__builtin_msa_slli_w: 3075 case Mips::BI__builtin_msa_srai_w: 3076 case Mips::BI__builtin_msa_srari_w: 3077 case Mips::BI__builtin_msa_srli_w: 3078 case Mips::BI__builtin_msa_srlri_w: 3079 case Mips::BI__builtin_msa_subvi_b: 3080 case Mips::BI__builtin_msa_subvi_h: 3081 case Mips::BI__builtin_msa_subvi_w: 3082 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3083 case Mips::BI__builtin_msa_binsli_w: 3084 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3085 // These intrinsics take an unsigned 6 bit immediate. 3086 case Mips::BI__builtin_msa_bclri_d: 3087 case Mips::BI__builtin_msa_bnegi_d: 3088 case Mips::BI__builtin_msa_bseti_d: 3089 case Mips::BI__builtin_msa_sat_s_d: 3090 case Mips::BI__builtin_msa_sat_u_d: 3091 case Mips::BI__builtin_msa_slli_d: 3092 case Mips::BI__builtin_msa_srai_d: 3093 case Mips::BI__builtin_msa_srari_d: 3094 case Mips::BI__builtin_msa_srli_d: 3095 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3096 case Mips::BI__builtin_msa_binsli_d: 3097 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3098 // These intrinsics take a signed 5 bit immediate. 3099 case Mips::BI__builtin_msa_ceqi_b: 3100 case Mips::BI__builtin_msa_ceqi_h: 3101 case Mips::BI__builtin_msa_ceqi_w: 3102 case Mips::BI__builtin_msa_ceqi_d: 3103 case Mips::BI__builtin_msa_clti_s_b: 3104 case Mips::BI__builtin_msa_clti_s_h: 3105 case Mips::BI__builtin_msa_clti_s_w: 3106 case Mips::BI__builtin_msa_clti_s_d: 3107 case Mips::BI__builtin_msa_clei_s_b: 3108 case Mips::BI__builtin_msa_clei_s_h: 3109 case Mips::BI__builtin_msa_clei_s_w: 3110 case Mips::BI__builtin_msa_clei_s_d: 3111 case Mips::BI__builtin_msa_maxi_s_b: 3112 case Mips::BI__builtin_msa_maxi_s_h: 3113 case Mips::BI__builtin_msa_maxi_s_w: 3114 case Mips::BI__builtin_msa_maxi_s_d: 3115 case Mips::BI__builtin_msa_mini_s_b: 3116 case Mips::BI__builtin_msa_mini_s_h: 3117 case Mips::BI__builtin_msa_mini_s_w: 3118 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3119 // These intrinsics take an unsigned 8 bit immediate. 3120 case Mips::BI__builtin_msa_andi_b: 3121 case Mips::BI__builtin_msa_nori_b: 3122 case Mips::BI__builtin_msa_ori_b: 3123 case Mips::BI__builtin_msa_shf_b: 3124 case Mips::BI__builtin_msa_shf_h: 3125 case Mips::BI__builtin_msa_shf_w: 3126 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3127 case Mips::BI__builtin_msa_bseli_b: 3128 case Mips::BI__builtin_msa_bmnzi_b: 3129 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3130 // df/n format 3131 // These intrinsics take an unsigned 4 bit immediate. 3132 case Mips::BI__builtin_msa_copy_s_b: 3133 case Mips::BI__builtin_msa_copy_u_b: 3134 case Mips::BI__builtin_msa_insve_b: 3135 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3136 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3137 // These intrinsics take an unsigned 3 bit immediate. 3138 case Mips::BI__builtin_msa_copy_s_h: 3139 case Mips::BI__builtin_msa_copy_u_h: 3140 case Mips::BI__builtin_msa_insve_h: 3141 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3142 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3143 // These intrinsics take an unsigned 2 bit immediate. 3144 case Mips::BI__builtin_msa_copy_s_w: 3145 case Mips::BI__builtin_msa_copy_u_w: 3146 case Mips::BI__builtin_msa_insve_w: 3147 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3148 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3149 // These intrinsics take an unsigned 1 bit immediate. 3150 case Mips::BI__builtin_msa_copy_s_d: 3151 case Mips::BI__builtin_msa_copy_u_d: 3152 case Mips::BI__builtin_msa_insve_d: 3153 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3154 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3155 // Memory offsets and immediate loads. 3156 // These intrinsics take a signed 10 bit immediate. 3157 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3158 case Mips::BI__builtin_msa_ldi_h: 3159 case Mips::BI__builtin_msa_ldi_w: 3160 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3161 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3162 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3163 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3164 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3165 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3166 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3167 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3168 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3169 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3170 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3171 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3172 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3173 } 3174 3175 if (!m) 3176 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3177 3178 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3179 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3180 } 3181 3182 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3183 /// advancing the pointer over the consumed characters. The decoded type is 3184 /// returned. If the decoded type represents a constant integer with a 3185 /// constraint on its value then Mask is set to that value. The type descriptors 3186 /// used in Str are specific to PPC MMA builtins and are documented in the file 3187 /// defining the PPC builtins. 3188 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3189 unsigned &Mask) { 3190 bool RequireICE = false; 3191 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3192 switch (*Str++) { 3193 case 'V': 3194 return Context.getVectorType(Context.UnsignedCharTy, 16, 3195 VectorType::VectorKind::AltiVecVector); 3196 case 'i': { 3197 char *End; 3198 unsigned size = strtoul(Str, &End, 10); 3199 assert(End != Str && "Missing constant parameter constraint"); 3200 Str = End; 3201 Mask = size; 3202 return Context.IntTy; 3203 } 3204 case 'W': { 3205 char *End; 3206 unsigned size = strtoul(Str, &End, 10); 3207 assert(End != Str && "Missing PowerPC MMA type size"); 3208 Str = End; 3209 QualType Type; 3210 switch (size) { 3211 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3212 case size: Type = Context.Id##Ty; break; 3213 #include "clang/Basic/PPCTypes.def" 3214 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3215 } 3216 bool CheckVectorArgs = false; 3217 while (!CheckVectorArgs) { 3218 switch (*Str++) { 3219 case '*': 3220 Type = Context.getPointerType(Type); 3221 break; 3222 case 'C': 3223 Type = Type.withConst(); 3224 break; 3225 default: 3226 CheckVectorArgs = true; 3227 --Str; 3228 break; 3229 } 3230 } 3231 return Type; 3232 } 3233 default: 3234 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3235 } 3236 } 3237 3238 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3239 CallExpr *TheCall) { 3240 unsigned i = 0, l = 0, u = 0; 3241 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3242 BuiltinID == PPC::BI__builtin_divdeu || 3243 BuiltinID == PPC::BI__builtin_bpermd; 3244 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3245 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3246 BuiltinID == PPC::BI__builtin_divweu || 3247 BuiltinID == PPC::BI__builtin_divde || 3248 BuiltinID == PPC::BI__builtin_divdeu; 3249 3250 if (Is64BitBltin && !IsTarget64Bit) 3251 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3252 << TheCall->getSourceRange(); 3253 3254 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3255 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3256 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3257 << TheCall->getSourceRange(); 3258 3259 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3260 if (!TI.hasFeature("vsx")) 3261 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3262 << TheCall->getSourceRange(); 3263 return false; 3264 }; 3265 3266 switch (BuiltinID) { 3267 default: return false; 3268 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3269 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3270 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3271 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3272 case PPC::BI__builtin_altivec_dss: 3273 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3274 case PPC::BI__builtin_tbegin: 3275 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3276 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3277 case PPC::BI__builtin_tabortwc: 3278 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3279 case PPC::BI__builtin_tabortwci: 3280 case PPC::BI__builtin_tabortdci: 3281 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3282 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3283 case PPC::BI__builtin_altivec_dst: 3284 case PPC::BI__builtin_altivec_dstt: 3285 case PPC::BI__builtin_altivec_dstst: 3286 case PPC::BI__builtin_altivec_dststt: 3287 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3288 case PPC::BI__builtin_vsx_xxpermdi: 3289 case PPC::BI__builtin_vsx_xxsldwi: 3290 return SemaBuiltinVSX(TheCall); 3291 case PPC::BI__builtin_unpack_vector_int128: 3292 return SemaVSXCheck(TheCall) || 3293 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3294 case PPC::BI__builtin_pack_vector_int128: 3295 return SemaVSXCheck(TheCall); 3296 case PPC::BI__builtin_altivec_vgnb: 3297 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3298 case PPC::BI__builtin_altivec_vec_replace_elt: 3299 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3300 QualType VecTy = TheCall->getArg(0)->getType(); 3301 QualType EltTy = TheCall->getArg(1)->getType(); 3302 unsigned Width = Context.getIntWidth(EltTy); 3303 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3304 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3305 } 3306 case PPC::BI__builtin_vsx_xxeval: 3307 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3308 case PPC::BI__builtin_altivec_vsldbi: 3309 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3310 case PPC::BI__builtin_altivec_vsrdbi: 3311 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3312 case PPC::BI__builtin_vsx_xxpermx: 3313 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3314 #define CUSTOM_BUILTIN(Name, Types, Acc) \ 3315 case PPC::BI__builtin_##Name: \ 3316 return SemaBuiltinPPCMMACall(TheCall, Types); 3317 #include "clang/Basic/BuiltinsPPC.def" 3318 } 3319 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3320 } 3321 3322 // Check if the given type is a non-pointer PPC MMA type. This function is used 3323 // in Sema to prevent invalid uses of restricted PPC MMA types. 3324 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3325 if (Type->isPointerType() || Type->isArrayType()) 3326 return false; 3327 3328 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3329 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3330 if (false 3331 #include "clang/Basic/PPCTypes.def" 3332 ) { 3333 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3334 return true; 3335 } 3336 return false; 3337 } 3338 3339 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3340 CallExpr *TheCall) { 3341 // position of memory order and scope arguments in the builtin 3342 unsigned OrderIndex, ScopeIndex; 3343 switch (BuiltinID) { 3344 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3345 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3346 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3347 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3348 OrderIndex = 2; 3349 ScopeIndex = 3; 3350 break; 3351 case AMDGPU::BI__builtin_amdgcn_fence: 3352 OrderIndex = 0; 3353 ScopeIndex = 1; 3354 break; 3355 default: 3356 return false; 3357 } 3358 3359 ExprResult Arg = TheCall->getArg(OrderIndex); 3360 auto ArgExpr = Arg.get(); 3361 Expr::EvalResult ArgResult; 3362 3363 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3364 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3365 << ArgExpr->getType(); 3366 int ord = ArgResult.Val.getInt().getZExtValue(); 3367 3368 // Check valididty of memory ordering as per C11 / C++11's memody model. 3369 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3370 case llvm::AtomicOrderingCABI::acquire: 3371 case llvm::AtomicOrderingCABI::release: 3372 case llvm::AtomicOrderingCABI::acq_rel: 3373 case llvm::AtomicOrderingCABI::seq_cst: 3374 break; 3375 default: { 3376 return Diag(ArgExpr->getBeginLoc(), 3377 diag::warn_atomic_op_has_invalid_memory_order) 3378 << ArgExpr->getSourceRange(); 3379 } 3380 } 3381 3382 Arg = TheCall->getArg(ScopeIndex); 3383 ArgExpr = Arg.get(); 3384 Expr::EvalResult ArgResult1; 3385 // Check that sync scope is a constant literal 3386 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3387 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3388 << ArgExpr->getType(); 3389 3390 return false; 3391 } 3392 3393 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3394 unsigned BuiltinID, 3395 CallExpr *TheCall) { 3396 // CodeGenFunction can also detect this, but this gives a better error 3397 // message. 3398 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3399 if (Features.find("experimental-v") != StringRef::npos && 3400 !TI.hasFeature("experimental-v")) 3401 return Diag(TheCall->getBeginLoc(), diag::err_riscvv_builtin_requires_v) 3402 << TheCall->getSourceRange(); 3403 3404 return false; 3405 } 3406 3407 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3408 CallExpr *TheCall) { 3409 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3410 Expr *Arg = TheCall->getArg(0); 3411 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3412 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3413 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3414 << Arg->getSourceRange(); 3415 } 3416 3417 // For intrinsics which take an immediate value as part of the instruction, 3418 // range check them here. 3419 unsigned i = 0, l = 0, u = 0; 3420 switch (BuiltinID) { 3421 default: return false; 3422 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3423 case SystemZ::BI__builtin_s390_verimb: 3424 case SystemZ::BI__builtin_s390_verimh: 3425 case SystemZ::BI__builtin_s390_verimf: 3426 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3427 case SystemZ::BI__builtin_s390_vfaeb: 3428 case SystemZ::BI__builtin_s390_vfaeh: 3429 case SystemZ::BI__builtin_s390_vfaef: 3430 case SystemZ::BI__builtin_s390_vfaebs: 3431 case SystemZ::BI__builtin_s390_vfaehs: 3432 case SystemZ::BI__builtin_s390_vfaefs: 3433 case SystemZ::BI__builtin_s390_vfaezb: 3434 case SystemZ::BI__builtin_s390_vfaezh: 3435 case SystemZ::BI__builtin_s390_vfaezf: 3436 case SystemZ::BI__builtin_s390_vfaezbs: 3437 case SystemZ::BI__builtin_s390_vfaezhs: 3438 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3439 case SystemZ::BI__builtin_s390_vfisb: 3440 case SystemZ::BI__builtin_s390_vfidb: 3441 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3442 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3443 case SystemZ::BI__builtin_s390_vftcisb: 3444 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3445 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3446 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3447 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3448 case SystemZ::BI__builtin_s390_vstrcb: 3449 case SystemZ::BI__builtin_s390_vstrch: 3450 case SystemZ::BI__builtin_s390_vstrcf: 3451 case SystemZ::BI__builtin_s390_vstrczb: 3452 case SystemZ::BI__builtin_s390_vstrczh: 3453 case SystemZ::BI__builtin_s390_vstrczf: 3454 case SystemZ::BI__builtin_s390_vstrcbs: 3455 case SystemZ::BI__builtin_s390_vstrchs: 3456 case SystemZ::BI__builtin_s390_vstrcfs: 3457 case SystemZ::BI__builtin_s390_vstrczbs: 3458 case SystemZ::BI__builtin_s390_vstrczhs: 3459 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3460 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3461 case SystemZ::BI__builtin_s390_vfminsb: 3462 case SystemZ::BI__builtin_s390_vfmaxsb: 3463 case SystemZ::BI__builtin_s390_vfmindb: 3464 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3465 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3466 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3467 } 3468 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3469 } 3470 3471 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3472 /// This checks that the target supports __builtin_cpu_supports and 3473 /// that the string argument is constant and valid. 3474 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3475 CallExpr *TheCall) { 3476 Expr *Arg = TheCall->getArg(0); 3477 3478 // Check if the argument is a string literal. 3479 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3480 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3481 << Arg->getSourceRange(); 3482 3483 // Check the contents of the string. 3484 StringRef Feature = 3485 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3486 if (!TI.validateCpuSupports(Feature)) 3487 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3488 << Arg->getSourceRange(); 3489 return false; 3490 } 3491 3492 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3493 /// This checks that the target supports __builtin_cpu_is and 3494 /// that the string argument is constant and valid. 3495 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3496 Expr *Arg = TheCall->getArg(0); 3497 3498 // Check if the argument is a string literal. 3499 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3500 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3501 << Arg->getSourceRange(); 3502 3503 // Check the contents of the string. 3504 StringRef Feature = 3505 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3506 if (!TI.validateCpuIs(Feature)) 3507 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3508 << Arg->getSourceRange(); 3509 return false; 3510 } 3511 3512 // Check if the rounding mode is legal. 3513 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3514 // Indicates if this instruction has rounding control or just SAE. 3515 bool HasRC = false; 3516 3517 unsigned ArgNum = 0; 3518 switch (BuiltinID) { 3519 default: 3520 return false; 3521 case X86::BI__builtin_ia32_vcvttsd2si32: 3522 case X86::BI__builtin_ia32_vcvttsd2si64: 3523 case X86::BI__builtin_ia32_vcvttsd2usi32: 3524 case X86::BI__builtin_ia32_vcvttsd2usi64: 3525 case X86::BI__builtin_ia32_vcvttss2si32: 3526 case X86::BI__builtin_ia32_vcvttss2si64: 3527 case X86::BI__builtin_ia32_vcvttss2usi32: 3528 case X86::BI__builtin_ia32_vcvttss2usi64: 3529 ArgNum = 1; 3530 break; 3531 case X86::BI__builtin_ia32_maxpd512: 3532 case X86::BI__builtin_ia32_maxps512: 3533 case X86::BI__builtin_ia32_minpd512: 3534 case X86::BI__builtin_ia32_minps512: 3535 ArgNum = 2; 3536 break; 3537 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3538 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3539 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3540 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3541 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3542 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3543 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3544 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3545 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3546 case X86::BI__builtin_ia32_exp2pd_mask: 3547 case X86::BI__builtin_ia32_exp2ps_mask: 3548 case X86::BI__builtin_ia32_getexppd512_mask: 3549 case X86::BI__builtin_ia32_getexpps512_mask: 3550 case X86::BI__builtin_ia32_rcp28pd_mask: 3551 case X86::BI__builtin_ia32_rcp28ps_mask: 3552 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3553 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3554 case X86::BI__builtin_ia32_vcomisd: 3555 case X86::BI__builtin_ia32_vcomiss: 3556 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3557 ArgNum = 3; 3558 break; 3559 case X86::BI__builtin_ia32_cmppd512_mask: 3560 case X86::BI__builtin_ia32_cmpps512_mask: 3561 case X86::BI__builtin_ia32_cmpsd_mask: 3562 case X86::BI__builtin_ia32_cmpss_mask: 3563 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3564 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3565 case X86::BI__builtin_ia32_getexpss128_round_mask: 3566 case X86::BI__builtin_ia32_getmantpd512_mask: 3567 case X86::BI__builtin_ia32_getmantps512_mask: 3568 case X86::BI__builtin_ia32_maxsd_round_mask: 3569 case X86::BI__builtin_ia32_maxss_round_mask: 3570 case X86::BI__builtin_ia32_minsd_round_mask: 3571 case X86::BI__builtin_ia32_minss_round_mask: 3572 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3573 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3574 case X86::BI__builtin_ia32_reducepd512_mask: 3575 case X86::BI__builtin_ia32_reduceps512_mask: 3576 case X86::BI__builtin_ia32_rndscalepd_mask: 3577 case X86::BI__builtin_ia32_rndscaleps_mask: 3578 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3579 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3580 ArgNum = 4; 3581 break; 3582 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3583 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3584 case X86::BI__builtin_ia32_fixupimmps512_mask: 3585 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3586 case X86::BI__builtin_ia32_fixupimmsd_mask: 3587 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3588 case X86::BI__builtin_ia32_fixupimmss_mask: 3589 case X86::BI__builtin_ia32_fixupimmss_maskz: 3590 case X86::BI__builtin_ia32_getmantsd_round_mask: 3591 case X86::BI__builtin_ia32_getmantss_round_mask: 3592 case X86::BI__builtin_ia32_rangepd512_mask: 3593 case X86::BI__builtin_ia32_rangeps512_mask: 3594 case X86::BI__builtin_ia32_rangesd128_round_mask: 3595 case X86::BI__builtin_ia32_rangess128_round_mask: 3596 case X86::BI__builtin_ia32_reducesd_mask: 3597 case X86::BI__builtin_ia32_reducess_mask: 3598 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3599 case X86::BI__builtin_ia32_rndscaless_round_mask: 3600 ArgNum = 5; 3601 break; 3602 case X86::BI__builtin_ia32_vcvtsd2si64: 3603 case X86::BI__builtin_ia32_vcvtsd2si32: 3604 case X86::BI__builtin_ia32_vcvtsd2usi32: 3605 case X86::BI__builtin_ia32_vcvtsd2usi64: 3606 case X86::BI__builtin_ia32_vcvtss2si32: 3607 case X86::BI__builtin_ia32_vcvtss2si64: 3608 case X86::BI__builtin_ia32_vcvtss2usi32: 3609 case X86::BI__builtin_ia32_vcvtss2usi64: 3610 case X86::BI__builtin_ia32_sqrtpd512: 3611 case X86::BI__builtin_ia32_sqrtps512: 3612 ArgNum = 1; 3613 HasRC = true; 3614 break; 3615 case X86::BI__builtin_ia32_addpd512: 3616 case X86::BI__builtin_ia32_addps512: 3617 case X86::BI__builtin_ia32_divpd512: 3618 case X86::BI__builtin_ia32_divps512: 3619 case X86::BI__builtin_ia32_mulpd512: 3620 case X86::BI__builtin_ia32_mulps512: 3621 case X86::BI__builtin_ia32_subpd512: 3622 case X86::BI__builtin_ia32_subps512: 3623 case X86::BI__builtin_ia32_cvtsi2sd64: 3624 case X86::BI__builtin_ia32_cvtsi2ss32: 3625 case X86::BI__builtin_ia32_cvtsi2ss64: 3626 case X86::BI__builtin_ia32_cvtusi2sd64: 3627 case X86::BI__builtin_ia32_cvtusi2ss32: 3628 case X86::BI__builtin_ia32_cvtusi2ss64: 3629 ArgNum = 2; 3630 HasRC = true; 3631 break; 3632 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3633 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3634 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3635 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3636 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3637 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3638 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3639 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3640 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3641 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3642 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3643 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3644 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3645 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3646 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3647 ArgNum = 3; 3648 HasRC = true; 3649 break; 3650 case X86::BI__builtin_ia32_addss_round_mask: 3651 case X86::BI__builtin_ia32_addsd_round_mask: 3652 case X86::BI__builtin_ia32_divss_round_mask: 3653 case X86::BI__builtin_ia32_divsd_round_mask: 3654 case X86::BI__builtin_ia32_mulss_round_mask: 3655 case X86::BI__builtin_ia32_mulsd_round_mask: 3656 case X86::BI__builtin_ia32_subss_round_mask: 3657 case X86::BI__builtin_ia32_subsd_round_mask: 3658 case X86::BI__builtin_ia32_scalefpd512_mask: 3659 case X86::BI__builtin_ia32_scalefps512_mask: 3660 case X86::BI__builtin_ia32_scalefsd_round_mask: 3661 case X86::BI__builtin_ia32_scalefss_round_mask: 3662 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3663 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3664 case X86::BI__builtin_ia32_sqrtss_round_mask: 3665 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3666 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3667 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3668 case X86::BI__builtin_ia32_vfmaddss3_mask: 3669 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3670 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3671 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3672 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3673 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3674 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3675 case X86::BI__builtin_ia32_vfmaddps512_mask: 3676 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3677 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3678 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3679 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3680 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3681 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3682 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3683 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3684 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3685 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3686 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3687 ArgNum = 4; 3688 HasRC = true; 3689 break; 3690 } 3691 3692 llvm::APSInt Result; 3693 3694 // We can't check the value of a dependent argument. 3695 Expr *Arg = TheCall->getArg(ArgNum); 3696 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3697 return false; 3698 3699 // Check constant-ness first. 3700 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3701 return true; 3702 3703 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3704 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3705 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3706 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3707 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3708 Result == 8/*ROUND_NO_EXC*/ || 3709 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3710 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3711 return false; 3712 3713 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3714 << Arg->getSourceRange(); 3715 } 3716 3717 // Check if the gather/scatter scale is legal. 3718 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3719 CallExpr *TheCall) { 3720 unsigned ArgNum = 0; 3721 switch (BuiltinID) { 3722 default: 3723 return false; 3724 case X86::BI__builtin_ia32_gatherpfdpd: 3725 case X86::BI__builtin_ia32_gatherpfdps: 3726 case X86::BI__builtin_ia32_gatherpfqpd: 3727 case X86::BI__builtin_ia32_gatherpfqps: 3728 case X86::BI__builtin_ia32_scatterpfdpd: 3729 case X86::BI__builtin_ia32_scatterpfdps: 3730 case X86::BI__builtin_ia32_scatterpfqpd: 3731 case X86::BI__builtin_ia32_scatterpfqps: 3732 ArgNum = 3; 3733 break; 3734 case X86::BI__builtin_ia32_gatherd_pd: 3735 case X86::BI__builtin_ia32_gatherd_pd256: 3736 case X86::BI__builtin_ia32_gatherq_pd: 3737 case X86::BI__builtin_ia32_gatherq_pd256: 3738 case X86::BI__builtin_ia32_gatherd_ps: 3739 case X86::BI__builtin_ia32_gatherd_ps256: 3740 case X86::BI__builtin_ia32_gatherq_ps: 3741 case X86::BI__builtin_ia32_gatherq_ps256: 3742 case X86::BI__builtin_ia32_gatherd_q: 3743 case X86::BI__builtin_ia32_gatherd_q256: 3744 case X86::BI__builtin_ia32_gatherq_q: 3745 case X86::BI__builtin_ia32_gatherq_q256: 3746 case X86::BI__builtin_ia32_gatherd_d: 3747 case X86::BI__builtin_ia32_gatherd_d256: 3748 case X86::BI__builtin_ia32_gatherq_d: 3749 case X86::BI__builtin_ia32_gatherq_d256: 3750 case X86::BI__builtin_ia32_gather3div2df: 3751 case X86::BI__builtin_ia32_gather3div2di: 3752 case X86::BI__builtin_ia32_gather3div4df: 3753 case X86::BI__builtin_ia32_gather3div4di: 3754 case X86::BI__builtin_ia32_gather3div4sf: 3755 case X86::BI__builtin_ia32_gather3div4si: 3756 case X86::BI__builtin_ia32_gather3div8sf: 3757 case X86::BI__builtin_ia32_gather3div8si: 3758 case X86::BI__builtin_ia32_gather3siv2df: 3759 case X86::BI__builtin_ia32_gather3siv2di: 3760 case X86::BI__builtin_ia32_gather3siv4df: 3761 case X86::BI__builtin_ia32_gather3siv4di: 3762 case X86::BI__builtin_ia32_gather3siv4sf: 3763 case X86::BI__builtin_ia32_gather3siv4si: 3764 case X86::BI__builtin_ia32_gather3siv8sf: 3765 case X86::BI__builtin_ia32_gather3siv8si: 3766 case X86::BI__builtin_ia32_gathersiv8df: 3767 case X86::BI__builtin_ia32_gathersiv16sf: 3768 case X86::BI__builtin_ia32_gatherdiv8df: 3769 case X86::BI__builtin_ia32_gatherdiv16sf: 3770 case X86::BI__builtin_ia32_gathersiv8di: 3771 case X86::BI__builtin_ia32_gathersiv16si: 3772 case X86::BI__builtin_ia32_gatherdiv8di: 3773 case X86::BI__builtin_ia32_gatherdiv16si: 3774 case X86::BI__builtin_ia32_scatterdiv2df: 3775 case X86::BI__builtin_ia32_scatterdiv2di: 3776 case X86::BI__builtin_ia32_scatterdiv4df: 3777 case X86::BI__builtin_ia32_scatterdiv4di: 3778 case X86::BI__builtin_ia32_scatterdiv4sf: 3779 case X86::BI__builtin_ia32_scatterdiv4si: 3780 case X86::BI__builtin_ia32_scatterdiv8sf: 3781 case X86::BI__builtin_ia32_scatterdiv8si: 3782 case X86::BI__builtin_ia32_scattersiv2df: 3783 case X86::BI__builtin_ia32_scattersiv2di: 3784 case X86::BI__builtin_ia32_scattersiv4df: 3785 case X86::BI__builtin_ia32_scattersiv4di: 3786 case X86::BI__builtin_ia32_scattersiv4sf: 3787 case X86::BI__builtin_ia32_scattersiv4si: 3788 case X86::BI__builtin_ia32_scattersiv8sf: 3789 case X86::BI__builtin_ia32_scattersiv8si: 3790 case X86::BI__builtin_ia32_scattersiv8df: 3791 case X86::BI__builtin_ia32_scattersiv16sf: 3792 case X86::BI__builtin_ia32_scatterdiv8df: 3793 case X86::BI__builtin_ia32_scatterdiv16sf: 3794 case X86::BI__builtin_ia32_scattersiv8di: 3795 case X86::BI__builtin_ia32_scattersiv16si: 3796 case X86::BI__builtin_ia32_scatterdiv8di: 3797 case X86::BI__builtin_ia32_scatterdiv16si: 3798 ArgNum = 4; 3799 break; 3800 } 3801 3802 llvm::APSInt Result; 3803 3804 // We can't check the value of a dependent argument. 3805 Expr *Arg = TheCall->getArg(ArgNum); 3806 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3807 return false; 3808 3809 // Check constant-ness first. 3810 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3811 return true; 3812 3813 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3814 return false; 3815 3816 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3817 << Arg->getSourceRange(); 3818 } 3819 3820 enum { TileRegLow = 0, TileRegHigh = 7 }; 3821 3822 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3823 ArrayRef<int> ArgNums) { 3824 for (int ArgNum : ArgNums) { 3825 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3826 return true; 3827 } 3828 return false; 3829 } 3830 3831 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3832 ArrayRef<int> ArgNums) { 3833 // Because the max number of tile register is TileRegHigh + 1, so here we use 3834 // each bit to represent the usage of them in bitset. 3835 std::bitset<TileRegHigh + 1> ArgValues; 3836 for (int ArgNum : ArgNums) { 3837 Expr *Arg = TheCall->getArg(ArgNum); 3838 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3839 continue; 3840 3841 llvm::APSInt Result; 3842 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3843 return true; 3844 int ArgExtValue = Result.getExtValue(); 3845 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3846 "Incorrect tile register num."); 3847 if (ArgValues.test(ArgExtValue)) 3848 return Diag(TheCall->getBeginLoc(), 3849 diag::err_x86_builtin_tile_arg_duplicate) 3850 << TheCall->getArg(ArgNum)->getSourceRange(); 3851 ArgValues.set(ArgExtValue); 3852 } 3853 return false; 3854 } 3855 3856 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3857 ArrayRef<int> ArgNums) { 3858 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3859 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3860 } 3861 3862 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3863 switch (BuiltinID) { 3864 default: 3865 return false; 3866 case X86::BI__builtin_ia32_tileloadd64: 3867 case X86::BI__builtin_ia32_tileloaddt164: 3868 case X86::BI__builtin_ia32_tilestored64: 3869 case X86::BI__builtin_ia32_tilezero: 3870 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3871 case X86::BI__builtin_ia32_tdpbssd: 3872 case X86::BI__builtin_ia32_tdpbsud: 3873 case X86::BI__builtin_ia32_tdpbusd: 3874 case X86::BI__builtin_ia32_tdpbuud: 3875 case X86::BI__builtin_ia32_tdpbf16ps: 3876 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3877 } 3878 } 3879 static bool isX86_32Builtin(unsigned BuiltinID) { 3880 // These builtins only work on x86-32 targets. 3881 switch (BuiltinID) { 3882 case X86::BI__builtin_ia32_readeflags_u32: 3883 case X86::BI__builtin_ia32_writeeflags_u32: 3884 return true; 3885 } 3886 3887 return false; 3888 } 3889 3890 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3891 CallExpr *TheCall) { 3892 if (BuiltinID == X86::BI__builtin_cpu_supports) 3893 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3894 3895 if (BuiltinID == X86::BI__builtin_cpu_is) 3896 return SemaBuiltinCpuIs(*this, TI, TheCall); 3897 3898 // Check for 32-bit only builtins on a 64-bit target. 3899 const llvm::Triple &TT = TI.getTriple(); 3900 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3901 return Diag(TheCall->getCallee()->getBeginLoc(), 3902 diag::err_32_bit_builtin_64_bit_tgt); 3903 3904 // If the intrinsic has rounding or SAE make sure its valid. 3905 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3906 return true; 3907 3908 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3909 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3910 return true; 3911 3912 // If the intrinsic has a tile arguments, make sure they are valid. 3913 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3914 return true; 3915 3916 // For intrinsics which take an immediate value as part of the instruction, 3917 // range check them here. 3918 int i = 0, l = 0, u = 0; 3919 switch (BuiltinID) { 3920 default: 3921 return false; 3922 case X86::BI__builtin_ia32_vec_ext_v2si: 3923 case X86::BI__builtin_ia32_vec_ext_v2di: 3924 case X86::BI__builtin_ia32_vextractf128_pd256: 3925 case X86::BI__builtin_ia32_vextractf128_ps256: 3926 case X86::BI__builtin_ia32_vextractf128_si256: 3927 case X86::BI__builtin_ia32_extract128i256: 3928 case X86::BI__builtin_ia32_extractf64x4_mask: 3929 case X86::BI__builtin_ia32_extracti64x4_mask: 3930 case X86::BI__builtin_ia32_extractf32x8_mask: 3931 case X86::BI__builtin_ia32_extracti32x8_mask: 3932 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3933 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3934 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3935 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3936 i = 1; l = 0; u = 1; 3937 break; 3938 case X86::BI__builtin_ia32_vec_set_v2di: 3939 case X86::BI__builtin_ia32_vinsertf128_pd256: 3940 case X86::BI__builtin_ia32_vinsertf128_ps256: 3941 case X86::BI__builtin_ia32_vinsertf128_si256: 3942 case X86::BI__builtin_ia32_insert128i256: 3943 case X86::BI__builtin_ia32_insertf32x8: 3944 case X86::BI__builtin_ia32_inserti32x8: 3945 case X86::BI__builtin_ia32_insertf64x4: 3946 case X86::BI__builtin_ia32_inserti64x4: 3947 case X86::BI__builtin_ia32_insertf64x2_256: 3948 case X86::BI__builtin_ia32_inserti64x2_256: 3949 case X86::BI__builtin_ia32_insertf32x4_256: 3950 case X86::BI__builtin_ia32_inserti32x4_256: 3951 i = 2; l = 0; u = 1; 3952 break; 3953 case X86::BI__builtin_ia32_vpermilpd: 3954 case X86::BI__builtin_ia32_vec_ext_v4hi: 3955 case X86::BI__builtin_ia32_vec_ext_v4si: 3956 case X86::BI__builtin_ia32_vec_ext_v4sf: 3957 case X86::BI__builtin_ia32_vec_ext_v4di: 3958 case X86::BI__builtin_ia32_extractf32x4_mask: 3959 case X86::BI__builtin_ia32_extracti32x4_mask: 3960 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3961 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3962 i = 1; l = 0; u = 3; 3963 break; 3964 case X86::BI_mm_prefetch: 3965 case X86::BI__builtin_ia32_vec_ext_v8hi: 3966 case X86::BI__builtin_ia32_vec_ext_v8si: 3967 i = 1; l = 0; u = 7; 3968 break; 3969 case X86::BI__builtin_ia32_sha1rnds4: 3970 case X86::BI__builtin_ia32_blendpd: 3971 case X86::BI__builtin_ia32_shufpd: 3972 case X86::BI__builtin_ia32_vec_set_v4hi: 3973 case X86::BI__builtin_ia32_vec_set_v4si: 3974 case X86::BI__builtin_ia32_vec_set_v4di: 3975 case X86::BI__builtin_ia32_shuf_f32x4_256: 3976 case X86::BI__builtin_ia32_shuf_f64x2_256: 3977 case X86::BI__builtin_ia32_shuf_i32x4_256: 3978 case X86::BI__builtin_ia32_shuf_i64x2_256: 3979 case X86::BI__builtin_ia32_insertf64x2_512: 3980 case X86::BI__builtin_ia32_inserti64x2_512: 3981 case X86::BI__builtin_ia32_insertf32x4: 3982 case X86::BI__builtin_ia32_inserti32x4: 3983 i = 2; l = 0; u = 3; 3984 break; 3985 case X86::BI__builtin_ia32_vpermil2pd: 3986 case X86::BI__builtin_ia32_vpermil2pd256: 3987 case X86::BI__builtin_ia32_vpermil2ps: 3988 case X86::BI__builtin_ia32_vpermil2ps256: 3989 i = 3; l = 0; u = 3; 3990 break; 3991 case X86::BI__builtin_ia32_cmpb128_mask: 3992 case X86::BI__builtin_ia32_cmpw128_mask: 3993 case X86::BI__builtin_ia32_cmpd128_mask: 3994 case X86::BI__builtin_ia32_cmpq128_mask: 3995 case X86::BI__builtin_ia32_cmpb256_mask: 3996 case X86::BI__builtin_ia32_cmpw256_mask: 3997 case X86::BI__builtin_ia32_cmpd256_mask: 3998 case X86::BI__builtin_ia32_cmpq256_mask: 3999 case X86::BI__builtin_ia32_cmpb512_mask: 4000 case X86::BI__builtin_ia32_cmpw512_mask: 4001 case X86::BI__builtin_ia32_cmpd512_mask: 4002 case X86::BI__builtin_ia32_cmpq512_mask: 4003 case X86::BI__builtin_ia32_ucmpb128_mask: 4004 case X86::BI__builtin_ia32_ucmpw128_mask: 4005 case X86::BI__builtin_ia32_ucmpd128_mask: 4006 case X86::BI__builtin_ia32_ucmpq128_mask: 4007 case X86::BI__builtin_ia32_ucmpb256_mask: 4008 case X86::BI__builtin_ia32_ucmpw256_mask: 4009 case X86::BI__builtin_ia32_ucmpd256_mask: 4010 case X86::BI__builtin_ia32_ucmpq256_mask: 4011 case X86::BI__builtin_ia32_ucmpb512_mask: 4012 case X86::BI__builtin_ia32_ucmpw512_mask: 4013 case X86::BI__builtin_ia32_ucmpd512_mask: 4014 case X86::BI__builtin_ia32_ucmpq512_mask: 4015 case X86::BI__builtin_ia32_vpcomub: 4016 case X86::BI__builtin_ia32_vpcomuw: 4017 case X86::BI__builtin_ia32_vpcomud: 4018 case X86::BI__builtin_ia32_vpcomuq: 4019 case X86::BI__builtin_ia32_vpcomb: 4020 case X86::BI__builtin_ia32_vpcomw: 4021 case X86::BI__builtin_ia32_vpcomd: 4022 case X86::BI__builtin_ia32_vpcomq: 4023 case X86::BI__builtin_ia32_vec_set_v8hi: 4024 case X86::BI__builtin_ia32_vec_set_v8si: 4025 i = 2; l = 0; u = 7; 4026 break; 4027 case X86::BI__builtin_ia32_vpermilpd256: 4028 case X86::BI__builtin_ia32_roundps: 4029 case X86::BI__builtin_ia32_roundpd: 4030 case X86::BI__builtin_ia32_roundps256: 4031 case X86::BI__builtin_ia32_roundpd256: 4032 case X86::BI__builtin_ia32_getmantpd128_mask: 4033 case X86::BI__builtin_ia32_getmantpd256_mask: 4034 case X86::BI__builtin_ia32_getmantps128_mask: 4035 case X86::BI__builtin_ia32_getmantps256_mask: 4036 case X86::BI__builtin_ia32_getmantpd512_mask: 4037 case X86::BI__builtin_ia32_getmantps512_mask: 4038 case X86::BI__builtin_ia32_vec_ext_v16qi: 4039 case X86::BI__builtin_ia32_vec_ext_v16hi: 4040 i = 1; l = 0; u = 15; 4041 break; 4042 case X86::BI__builtin_ia32_pblendd128: 4043 case X86::BI__builtin_ia32_blendps: 4044 case X86::BI__builtin_ia32_blendpd256: 4045 case X86::BI__builtin_ia32_shufpd256: 4046 case X86::BI__builtin_ia32_roundss: 4047 case X86::BI__builtin_ia32_roundsd: 4048 case X86::BI__builtin_ia32_rangepd128_mask: 4049 case X86::BI__builtin_ia32_rangepd256_mask: 4050 case X86::BI__builtin_ia32_rangepd512_mask: 4051 case X86::BI__builtin_ia32_rangeps128_mask: 4052 case X86::BI__builtin_ia32_rangeps256_mask: 4053 case X86::BI__builtin_ia32_rangeps512_mask: 4054 case X86::BI__builtin_ia32_getmantsd_round_mask: 4055 case X86::BI__builtin_ia32_getmantss_round_mask: 4056 case X86::BI__builtin_ia32_vec_set_v16qi: 4057 case X86::BI__builtin_ia32_vec_set_v16hi: 4058 i = 2; l = 0; u = 15; 4059 break; 4060 case X86::BI__builtin_ia32_vec_ext_v32qi: 4061 i = 1; l = 0; u = 31; 4062 break; 4063 case X86::BI__builtin_ia32_cmpps: 4064 case X86::BI__builtin_ia32_cmpss: 4065 case X86::BI__builtin_ia32_cmppd: 4066 case X86::BI__builtin_ia32_cmpsd: 4067 case X86::BI__builtin_ia32_cmpps256: 4068 case X86::BI__builtin_ia32_cmppd256: 4069 case X86::BI__builtin_ia32_cmpps128_mask: 4070 case X86::BI__builtin_ia32_cmppd128_mask: 4071 case X86::BI__builtin_ia32_cmpps256_mask: 4072 case X86::BI__builtin_ia32_cmppd256_mask: 4073 case X86::BI__builtin_ia32_cmpps512_mask: 4074 case X86::BI__builtin_ia32_cmppd512_mask: 4075 case X86::BI__builtin_ia32_cmpsd_mask: 4076 case X86::BI__builtin_ia32_cmpss_mask: 4077 case X86::BI__builtin_ia32_vec_set_v32qi: 4078 i = 2; l = 0; u = 31; 4079 break; 4080 case X86::BI__builtin_ia32_permdf256: 4081 case X86::BI__builtin_ia32_permdi256: 4082 case X86::BI__builtin_ia32_permdf512: 4083 case X86::BI__builtin_ia32_permdi512: 4084 case X86::BI__builtin_ia32_vpermilps: 4085 case X86::BI__builtin_ia32_vpermilps256: 4086 case X86::BI__builtin_ia32_vpermilpd512: 4087 case X86::BI__builtin_ia32_vpermilps512: 4088 case X86::BI__builtin_ia32_pshufd: 4089 case X86::BI__builtin_ia32_pshufd256: 4090 case X86::BI__builtin_ia32_pshufd512: 4091 case X86::BI__builtin_ia32_pshufhw: 4092 case X86::BI__builtin_ia32_pshufhw256: 4093 case X86::BI__builtin_ia32_pshufhw512: 4094 case X86::BI__builtin_ia32_pshuflw: 4095 case X86::BI__builtin_ia32_pshuflw256: 4096 case X86::BI__builtin_ia32_pshuflw512: 4097 case X86::BI__builtin_ia32_vcvtps2ph: 4098 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4099 case X86::BI__builtin_ia32_vcvtps2ph256: 4100 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4101 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4102 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4103 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4104 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4105 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4106 case X86::BI__builtin_ia32_rndscaleps_mask: 4107 case X86::BI__builtin_ia32_rndscalepd_mask: 4108 case X86::BI__builtin_ia32_reducepd128_mask: 4109 case X86::BI__builtin_ia32_reducepd256_mask: 4110 case X86::BI__builtin_ia32_reducepd512_mask: 4111 case X86::BI__builtin_ia32_reduceps128_mask: 4112 case X86::BI__builtin_ia32_reduceps256_mask: 4113 case X86::BI__builtin_ia32_reduceps512_mask: 4114 case X86::BI__builtin_ia32_prold512: 4115 case X86::BI__builtin_ia32_prolq512: 4116 case X86::BI__builtin_ia32_prold128: 4117 case X86::BI__builtin_ia32_prold256: 4118 case X86::BI__builtin_ia32_prolq128: 4119 case X86::BI__builtin_ia32_prolq256: 4120 case X86::BI__builtin_ia32_prord512: 4121 case X86::BI__builtin_ia32_prorq512: 4122 case X86::BI__builtin_ia32_prord128: 4123 case X86::BI__builtin_ia32_prord256: 4124 case X86::BI__builtin_ia32_prorq128: 4125 case X86::BI__builtin_ia32_prorq256: 4126 case X86::BI__builtin_ia32_fpclasspd128_mask: 4127 case X86::BI__builtin_ia32_fpclasspd256_mask: 4128 case X86::BI__builtin_ia32_fpclassps128_mask: 4129 case X86::BI__builtin_ia32_fpclassps256_mask: 4130 case X86::BI__builtin_ia32_fpclassps512_mask: 4131 case X86::BI__builtin_ia32_fpclasspd512_mask: 4132 case X86::BI__builtin_ia32_fpclasssd_mask: 4133 case X86::BI__builtin_ia32_fpclassss_mask: 4134 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4135 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4136 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4137 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4138 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4139 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4140 case X86::BI__builtin_ia32_kshiftliqi: 4141 case X86::BI__builtin_ia32_kshiftlihi: 4142 case X86::BI__builtin_ia32_kshiftlisi: 4143 case X86::BI__builtin_ia32_kshiftlidi: 4144 case X86::BI__builtin_ia32_kshiftriqi: 4145 case X86::BI__builtin_ia32_kshiftrihi: 4146 case X86::BI__builtin_ia32_kshiftrisi: 4147 case X86::BI__builtin_ia32_kshiftridi: 4148 i = 1; l = 0; u = 255; 4149 break; 4150 case X86::BI__builtin_ia32_vperm2f128_pd256: 4151 case X86::BI__builtin_ia32_vperm2f128_ps256: 4152 case X86::BI__builtin_ia32_vperm2f128_si256: 4153 case X86::BI__builtin_ia32_permti256: 4154 case X86::BI__builtin_ia32_pblendw128: 4155 case X86::BI__builtin_ia32_pblendw256: 4156 case X86::BI__builtin_ia32_blendps256: 4157 case X86::BI__builtin_ia32_pblendd256: 4158 case X86::BI__builtin_ia32_palignr128: 4159 case X86::BI__builtin_ia32_palignr256: 4160 case X86::BI__builtin_ia32_palignr512: 4161 case X86::BI__builtin_ia32_alignq512: 4162 case X86::BI__builtin_ia32_alignd512: 4163 case X86::BI__builtin_ia32_alignd128: 4164 case X86::BI__builtin_ia32_alignd256: 4165 case X86::BI__builtin_ia32_alignq128: 4166 case X86::BI__builtin_ia32_alignq256: 4167 case X86::BI__builtin_ia32_vcomisd: 4168 case X86::BI__builtin_ia32_vcomiss: 4169 case X86::BI__builtin_ia32_shuf_f32x4: 4170 case X86::BI__builtin_ia32_shuf_f64x2: 4171 case X86::BI__builtin_ia32_shuf_i32x4: 4172 case X86::BI__builtin_ia32_shuf_i64x2: 4173 case X86::BI__builtin_ia32_shufpd512: 4174 case X86::BI__builtin_ia32_shufps: 4175 case X86::BI__builtin_ia32_shufps256: 4176 case X86::BI__builtin_ia32_shufps512: 4177 case X86::BI__builtin_ia32_dbpsadbw128: 4178 case X86::BI__builtin_ia32_dbpsadbw256: 4179 case X86::BI__builtin_ia32_dbpsadbw512: 4180 case X86::BI__builtin_ia32_vpshldd128: 4181 case X86::BI__builtin_ia32_vpshldd256: 4182 case X86::BI__builtin_ia32_vpshldd512: 4183 case X86::BI__builtin_ia32_vpshldq128: 4184 case X86::BI__builtin_ia32_vpshldq256: 4185 case X86::BI__builtin_ia32_vpshldq512: 4186 case X86::BI__builtin_ia32_vpshldw128: 4187 case X86::BI__builtin_ia32_vpshldw256: 4188 case X86::BI__builtin_ia32_vpshldw512: 4189 case X86::BI__builtin_ia32_vpshrdd128: 4190 case X86::BI__builtin_ia32_vpshrdd256: 4191 case X86::BI__builtin_ia32_vpshrdd512: 4192 case X86::BI__builtin_ia32_vpshrdq128: 4193 case X86::BI__builtin_ia32_vpshrdq256: 4194 case X86::BI__builtin_ia32_vpshrdq512: 4195 case X86::BI__builtin_ia32_vpshrdw128: 4196 case X86::BI__builtin_ia32_vpshrdw256: 4197 case X86::BI__builtin_ia32_vpshrdw512: 4198 i = 2; l = 0; u = 255; 4199 break; 4200 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4201 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4202 case X86::BI__builtin_ia32_fixupimmps512_mask: 4203 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4204 case X86::BI__builtin_ia32_fixupimmsd_mask: 4205 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4206 case X86::BI__builtin_ia32_fixupimmss_mask: 4207 case X86::BI__builtin_ia32_fixupimmss_maskz: 4208 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4209 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4210 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4211 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4212 case X86::BI__builtin_ia32_fixupimmps128_mask: 4213 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4214 case X86::BI__builtin_ia32_fixupimmps256_mask: 4215 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4216 case X86::BI__builtin_ia32_pternlogd512_mask: 4217 case X86::BI__builtin_ia32_pternlogd512_maskz: 4218 case X86::BI__builtin_ia32_pternlogq512_mask: 4219 case X86::BI__builtin_ia32_pternlogq512_maskz: 4220 case X86::BI__builtin_ia32_pternlogd128_mask: 4221 case X86::BI__builtin_ia32_pternlogd128_maskz: 4222 case X86::BI__builtin_ia32_pternlogd256_mask: 4223 case X86::BI__builtin_ia32_pternlogd256_maskz: 4224 case X86::BI__builtin_ia32_pternlogq128_mask: 4225 case X86::BI__builtin_ia32_pternlogq128_maskz: 4226 case X86::BI__builtin_ia32_pternlogq256_mask: 4227 case X86::BI__builtin_ia32_pternlogq256_maskz: 4228 i = 3; l = 0; u = 255; 4229 break; 4230 case X86::BI__builtin_ia32_gatherpfdpd: 4231 case X86::BI__builtin_ia32_gatherpfdps: 4232 case X86::BI__builtin_ia32_gatherpfqpd: 4233 case X86::BI__builtin_ia32_gatherpfqps: 4234 case X86::BI__builtin_ia32_scatterpfdpd: 4235 case X86::BI__builtin_ia32_scatterpfdps: 4236 case X86::BI__builtin_ia32_scatterpfqpd: 4237 case X86::BI__builtin_ia32_scatterpfqps: 4238 i = 4; l = 2; u = 3; 4239 break; 4240 case X86::BI__builtin_ia32_reducesd_mask: 4241 case X86::BI__builtin_ia32_reducess_mask: 4242 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4243 case X86::BI__builtin_ia32_rndscaless_round_mask: 4244 i = 4; l = 0; u = 255; 4245 break; 4246 } 4247 4248 // Note that we don't force a hard error on the range check here, allowing 4249 // template-generated or macro-generated dead code to potentially have out-of- 4250 // range values. These need to code generate, but don't need to necessarily 4251 // make any sense. We use a warning that defaults to an error. 4252 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4253 } 4254 4255 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4256 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4257 /// Returns true when the format fits the function and the FormatStringInfo has 4258 /// been populated. 4259 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4260 FormatStringInfo *FSI) { 4261 FSI->HasVAListArg = Format->getFirstArg() == 0; 4262 FSI->FormatIdx = Format->getFormatIdx() - 1; 4263 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4264 4265 // The way the format attribute works in GCC, the implicit this argument 4266 // of member functions is counted. However, it doesn't appear in our own 4267 // lists, so decrement format_idx in that case. 4268 if (IsCXXMember) { 4269 if(FSI->FormatIdx == 0) 4270 return false; 4271 --FSI->FormatIdx; 4272 if (FSI->FirstDataArg != 0) 4273 --FSI->FirstDataArg; 4274 } 4275 return true; 4276 } 4277 4278 /// Checks if a the given expression evaluates to null. 4279 /// 4280 /// Returns true if the value evaluates to null. 4281 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4282 // If the expression has non-null type, it doesn't evaluate to null. 4283 if (auto nullability 4284 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4285 if (*nullability == NullabilityKind::NonNull) 4286 return false; 4287 } 4288 4289 // As a special case, transparent unions initialized with zero are 4290 // considered null for the purposes of the nonnull attribute. 4291 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4292 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4293 if (const CompoundLiteralExpr *CLE = 4294 dyn_cast<CompoundLiteralExpr>(Expr)) 4295 if (const InitListExpr *ILE = 4296 dyn_cast<InitListExpr>(CLE->getInitializer())) 4297 Expr = ILE->getInit(0); 4298 } 4299 4300 bool Result; 4301 return (!Expr->isValueDependent() && 4302 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4303 !Result); 4304 } 4305 4306 static void CheckNonNullArgument(Sema &S, 4307 const Expr *ArgExpr, 4308 SourceLocation CallSiteLoc) { 4309 if (CheckNonNullExpr(S, ArgExpr)) 4310 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4311 S.PDiag(diag::warn_null_arg) 4312 << ArgExpr->getSourceRange()); 4313 } 4314 4315 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4316 FormatStringInfo FSI; 4317 if ((GetFormatStringType(Format) == FST_NSString) && 4318 getFormatStringInfo(Format, false, &FSI)) { 4319 Idx = FSI.FormatIdx; 4320 return true; 4321 } 4322 return false; 4323 } 4324 4325 /// Diagnose use of %s directive in an NSString which is being passed 4326 /// as formatting string to formatting method. 4327 static void 4328 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4329 const NamedDecl *FDecl, 4330 Expr **Args, 4331 unsigned NumArgs) { 4332 unsigned Idx = 0; 4333 bool Format = false; 4334 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4335 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4336 Idx = 2; 4337 Format = true; 4338 } 4339 else 4340 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4341 if (S.GetFormatNSStringIdx(I, Idx)) { 4342 Format = true; 4343 break; 4344 } 4345 } 4346 if (!Format || NumArgs <= Idx) 4347 return; 4348 const Expr *FormatExpr = Args[Idx]; 4349 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4350 FormatExpr = CSCE->getSubExpr(); 4351 const StringLiteral *FormatString; 4352 if (const ObjCStringLiteral *OSL = 4353 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4354 FormatString = OSL->getString(); 4355 else 4356 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4357 if (!FormatString) 4358 return; 4359 if (S.FormatStringHasSArg(FormatString)) { 4360 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4361 << "%s" << 1 << 1; 4362 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4363 << FDecl->getDeclName(); 4364 } 4365 } 4366 4367 /// Determine whether the given type has a non-null nullability annotation. 4368 static bool isNonNullType(ASTContext &ctx, QualType type) { 4369 if (auto nullability = type->getNullability(ctx)) 4370 return *nullability == NullabilityKind::NonNull; 4371 4372 return false; 4373 } 4374 4375 static void CheckNonNullArguments(Sema &S, 4376 const NamedDecl *FDecl, 4377 const FunctionProtoType *Proto, 4378 ArrayRef<const Expr *> Args, 4379 SourceLocation CallSiteLoc) { 4380 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4381 4382 // Already checked by by constant evaluator. 4383 if (S.isConstantEvaluated()) 4384 return; 4385 // Check the attributes attached to the method/function itself. 4386 llvm::SmallBitVector NonNullArgs; 4387 if (FDecl) { 4388 // Handle the nonnull attribute on the function/method declaration itself. 4389 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4390 if (!NonNull->args_size()) { 4391 // Easy case: all pointer arguments are nonnull. 4392 for (const auto *Arg : Args) 4393 if (S.isValidPointerAttrType(Arg->getType())) 4394 CheckNonNullArgument(S, Arg, CallSiteLoc); 4395 return; 4396 } 4397 4398 for (const ParamIdx &Idx : NonNull->args()) { 4399 unsigned IdxAST = Idx.getASTIndex(); 4400 if (IdxAST >= Args.size()) 4401 continue; 4402 if (NonNullArgs.empty()) 4403 NonNullArgs.resize(Args.size()); 4404 NonNullArgs.set(IdxAST); 4405 } 4406 } 4407 } 4408 4409 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4410 // Handle the nonnull attribute on the parameters of the 4411 // function/method. 4412 ArrayRef<ParmVarDecl*> parms; 4413 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4414 parms = FD->parameters(); 4415 else 4416 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4417 4418 unsigned ParamIndex = 0; 4419 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4420 I != E; ++I, ++ParamIndex) { 4421 const ParmVarDecl *PVD = *I; 4422 if (PVD->hasAttr<NonNullAttr>() || 4423 isNonNullType(S.Context, PVD->getType())) { 4424 if (NonNullArgs.empty()) 4425 NonNullArgs.resize(Args.size()); 4426 4427 NonNullArgs.set(ParamIndex); 4428 } 4429 } 4430 } else { 4431 // If we have a non-function, non-method declaration but no 4432 // function prototype, try to dig out the function prototype. 4433 if (!Proto) { 4434 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4435 QualType type = VD->getType().getNonReferenceType(); 4436 if (auto pointerType = type->getAs<PointerType>()) 4437 type = pointerType->getPointeeType(); 4438 else if (auto blockType = type->getAs<BlockPointerType>()) 4439 type = blockType->getPointeeType(); 4440 // FIXME: data member pointers? 4441 4442 // Dig out the function prototype, if there is one. 4443 Proto = type->getAs<FunctionProtoType>(); 4444 } 4445 } 4446 4447 // Fill in non-null argument information from the nullability 4448 // information on the parameter types (if we have them). 4449 if (Proto) { 4450 unsigned Index = 0; 4451 for (auto paramType : Proto->getParamTypes()) { 4452 if (isNonNullType(S.Context, paramType)) { 4453 if (NonNullArgs.empty()) 4454 NonNullArgs.resize(Args.size()); 4455 4456 NonNullArgs.set(Index); 4457 } 4458 4459 ++Index; 4460 } 4461 } 4462 } 4463 4464 // Check for non-null arguments. 4465 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4466 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4467 if (NonNullArgs[ArgIndex]) 4468 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4469 } 4470 } 4471 4472 /// Warn if a pointer or reference argument passed to a function points to an 4473 /// object that is less aligned than the parameter. This can happen when 4474 /// creating a typedef with a lower alignment than the original type and then 4475 /// calling functions defined in terms of the original type. 4476 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4477 StringRef ParamName, QualType ArgTy, 4478 QualType ParamTy) { 4479 4480 // If a function accepts a pointer or reference type 4481 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4482 return; 4483 4484 // If the parameter is a pointer type, get the pointee type for the 4485 // argument too. If the parameter is a reference type, don't try to get 4486 // the pointee type for the argument. 4487 if (ParamTy->isPointerType()) 4488 ArgTy = ArgTy->getPointeeType(); 4489 4490 // Remove reference or pointer 4491 ParamTy = ParamTy->getPointeeType(); 4492 4493 // Find expected alignment, and the actual alignment of the passed object. 4494 // getTypeAlignInChars requires complete types 4495 if (ParamTy->isIncompleteType() || ArgTy->isIncompleteType()) 4496 return; 4497 4498 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4499 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4500 4501 // If the argument is less aligned than the parameter, there is a 4502 // potential alignment issue. 4503 if (ArgAlign < ParamAlign) 4504 Diag(Loc, diag::warn_param_mismatched_alignment) 4505 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4506 << ParamName << FDecl; 4507 } 4508 4509 /// Handles the checks for format strings, non-POD arguments to vararg 4510 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4511 /// attributes. 4512 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4513 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4514 bool IsMemberFunction, SourceLocation Loc, 4515 SourceRange Range, VariadicCallType CallType) { 4516 // FIXME: We should check as much as we can in the template definition. 4517 if (CurContext->isDependentContext()) 4518 return; 4519 4520 // Printf and scanf checking. 4521 llvm::SmallBitVector CheckedVarArgs; 4522 if (FDecl) { 4523 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4524 // Only create vector if there are format attributes. 4525 CheckedVarArgs.resize(Args.size()); 4526 4527 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4528 CheckedVarArgs); 4529 } 4530 } 4531 4532 // Refuse POD arguments that weren't caught by the format string 4533 // checks above. 4534 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4535 if (CallType != VariadicDoesNotApply && 4536 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4537 unsigned NumParams = Proto ? Proto->getNumParams() 4538 : FDecl && isa<FunctionDecl>(FDecl) 4539 ? cast<FunctionDecl>(FDecl)->getNumParams() 4540 : FDecl && isa<ObjCMethodDecl>(FDecl) 4541 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4542 : 0; 4543 4544 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4545 // Args[ArgIdx] can be null in malformed code. 4546 if (const Expr *Arg = Args[ArgIdx]) { 4547 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4548 checkVariadicArgument(Arg, CallType); 4549 } 4550 } 4551 } 4552 4553 if (FDecl || Proto) { 4554 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4555 4556 // Type safety checking. 4557 if (FDecl) { 4558 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4559 CheckArgumentWithTypeTag(I, Args, Loc); 4560 } 4561 } 4562 4563 // Check that passed arguments match the alignment of original arguments. 4564 // Try to get the missing prototype from the declaration. 4565 if (!Proto && FDecl) { 4566 const auto *FT = FDecl->getFunctionType(); 4567 if (isa_and_nonnull<FunctionProtoType>(FT)) 4568 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 4569 } 4570 if (Proto) { 4571 // For variadic functions, we may have more args than parameters. 4572 // For some K&R functions, we may have less args than parameters. 4573 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 4574 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 4575 // Args[ArgIdx] can be null in malformed code. 4576 if (const Expr *Arg = Args[ArgIdx]) { 4577 QualType ParamTy = Proto->getParamType(ArgIdx); 4578 QualType ArgTy = Arg->getType(); 4579 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 4580 ArgTy, ParamTy); 4581 } 4582 } 4583 } 4584 4585 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4586 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4587 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4588 if (!Arg->isValueDependent()) { 4589 Expr::EvalResult Align; 4590 if (Arg->EvaluateAsInt(Align, Context)) { 4591 const llvm::APSInt &I = Align.Val.getInt(); 4592 if (!I.isPowerOf2()) 4593 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4594 << Arg->getSourceRange(); 4595 4596 if (I > Sema::MaximumAlignment) 4597 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4598 << Arg->getSourceRange() << Sema::MaximumAlignment; 4599 } 4600 } 4601 } 4602 4603 if (FD) 4604 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4605 } 4606 4607 /// CheckConstructorCall - Check a constructor call for correctness and safety 4608 /// properties not enforced by the C type system. 4609 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 4610 ArrayRef<const Expr *> Args, 4611 const FunctionProtoType *Proto, 4612 SourceLocation Loc) { 4613 VariadicCallType CallType = 4614 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4615 4616 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 4617 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 4618 Context.getPointerType(Ctor->getThisObjectType())); 4619 4620 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4621 Loc, SourceRange(), CallType); 4622 } 4623 4624 /// CheckFunctionCall - Check a direct function call for various correctness 4625 /// and safety properties not strictly enforced by the C type system. 4626 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4627 const FunctionProtoType *Proto) { 4628 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4629 isa<CXXMethodDecl>(FDecl); 4630 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4631 IsMemberOperatorCall; 4632 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4633 TheCall->getCallee()); 4634 Expr** Args = TheCall->getArgs(); 4635 unsigned NumArgs = TheCall->getNumArgs(); 4636 4637 Expr *ImplicitThis = nullptr; 4638 if (IsMemberOperatorCall) { 4639 // If this is a call to a member operator, hide the first argument 4640 // from checkCall. 4641 // FIXME: Our choice of AST representation here is less than ideal. 4642 ImplicitThis = Args[0]; 4643 ++Args; 4644 --NumArgs; 4645 } else if (IsMemberFunction) 4646 ImplicitThis = 4647 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4648 4649 if (ImplicitThis) { 4650 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 4651 // used. 4652 QualType ThisType = ImplicitThis->getType(); 4653 if (!ThisType->isPointerType()) { 4654 assert(!ThisType->isReferenceType()); 4655 ThisType = Context.getPointerType(ThisType); 4656 } 4657 4658 QualType ThisTypeFromDecl = 4659 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 4660 4661 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 4662 ThisTypeFromDecl); 4663 } 4664 4665 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4666 IsMemberFunction, TheCall->getRParenLoc(), 4667 TheCall->getCallee()->getSourceRange(), CallType); 4668 4669 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4670 // None of the checks below are needed for functions that don't have 4671 // simple names (e.g., C++ conversion functions). 4672 if (!FnInfo) 4673 return false; 4674 4675 CheckTCBEnforcement(TheCall, FDecl); 4676 4677 CheckAbsoluteValueFunction(TheCall, FDecl); 4678 CheckMaxUnsignedZero(TheCall, FDecl); 4679 4680 if (getLangOpts().ObjC) 4681 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4682 4683 unsigned CMId = FDecl->getMemoryFunctionKind(); 4684 4685 // Handle memory setting and copying functions. 4686 switch (CMId) { 4687 case 0: 4688 return false; 4689 case Builtin::BIstrlcpy: // fallthrough 4690 case Builtin::BIstrlcat: 4691 CheckStrlcpycatArguments(TheCall, FnInfo); 4692 break; 4693 case Builtin::BIstrncat: 4694 CheckStrncatArguments(TheCall, FnInfo); 4695 break; 4696 case Builtin::BIfree: 4697 CheckFreeArguments(TheCall); 4698 break; 4699 default: 4700 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4701 } 4702 4703 return false; 4704 } 4705 4706 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4707 ArrayRef<const Expr *> Args) { 4708 VariadicCallType CallType = 4709 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4710 4711 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4712 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4713 CallType); 4714 4715 return false; 4716 } 4717 4718 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4719 const FunctionProtoType *Proto) { 4720 QualType Ty; 4721 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4722 Ty = V->getType().getNonReferenceType(); 4723 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4724 Ty = F->getType().getNonReferenceType(); 4725 else 4726 return false; 4727 4728 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4729 !Ty->isFunctionProtoType()) 4730 return false; 4731 4732 VariadicCallType CallType; 4733 if (!Proto || !Proto->isVariadic()) { 4734 CallType = VariadicDoesNotApply; 4735 } else if (Ty->isBlockPointerType()) { 4736 CallType = VariadicBlock; 4737 } else { // Ty->isFunctionPointerType() 4738 CallType = VariadicFunction; 4739 } 4740 4741 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4742 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4743 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4744 TheCall->getCallee()->getSourceRange(), CallType); 4745 4746 return false; 4747 } 4748 4749 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4750 /// such as function pointers returned from functions. 4751 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4752 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4753 TheCall->getCallee()); 4754 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4755 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4756 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4757 TheCall->getCallee()->getSourceRange(), CallType); 4758 4759 return false; 4760 } 4761 4762 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4763 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4764 return false; 4765 4766 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4767 switch (Op) { 4768 case AtomicExpr::AO__c11_atomic_init: 4769 case AtomicExpr::AO__opencl_atomic_init: 4770 llvm_unreachable("There is no ordering argument for an init"); 4771 4772 case AtomicExpr::AO__c11_atomic_load: 4773 case AtomicExpr::AO__opencl_atomic_load: 4774 case AtomicExpr::AO__atomic_load_n: 4775 case AtomicExpr::AO__atomic_load: 4776 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4777 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4778 4779 case AtomicExpr::AO__c11_atomic_store: 4780 case AtomicExpr::AO__opencl_atomic_store: 4781 case AtomicExpr::AO__atomic_store: 4782 case AtomicExpr::AO__atomic_store_n: 4783 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4784 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4785 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4786 4787 default: 4788 return true; 4789 } 4790 } 4791 4792 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4793 AtomicExpr::AtomicOp Op) { 4794 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4795 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4796 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4797 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4798 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4799 Op); 4800 } 4801 4802 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4803 SourceLocation RParenLoc, MultiExprArg Args, 4804 AtomicExpr::AtomicOp Op, 4805 AtomicArgumentOrder ArgOrder) { 4806 // All the non-OpenCL operations take one of the following forms. 4807 // The OpenCL operations take the __c11 forms with one extra argument for 4808 // synchronization scope. 4809 enum { 4810 // C __c11_atomic_init(A *, C) 4811 Init, 4812 4813 // C __c11_atomic_load(A *, int) 4814 Load, 4815 4816 // void __atomic_load(A *, CP, int) 4817 LoadCopy, 4818 4819 // void __atomic_store(A *, CP, int) 4820 Copy, 4821 4822 // C __c11_atomic_add(A *, M, int) 4823 Arithmetic, 4824 4825 // C __atomic_exchange_n(A *, CP, int) 4826 Xchg, 4827 4828 // void __atomic_exchange(A *, C *, CP, int) 4829 GNUXchg, 4830 4831 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4832 C11CmpXchg, 4833 4834 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4835 GNUCmpXchg 4836 } Form = Init; 4837 4838 const unsigned NumForm = GNUCmpXchg + 1; 4839 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4840 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4841 // where: 4842 // C is an appropriate type, 4843 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4844 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4845 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4846 // the int parameters are for orderings. 4847 4848 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4849 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4850 "need to update code for modified forms"); 4851 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4852 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4853 AtomicExpr::AO__atomic_load, 4854 "need to update code for modified C11 atomics"); 4855 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4856 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4857 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4858 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4859 IsOpenCL; 4860 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4861 Op == AtomicExpr::AO__atomic_store_n || 4862 Op == AtomicExpr::AO__atomic_exchange_n || 4863 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4864 bool IsAddSub = false; 4865 4866 switch (Op) { 4867 case AtomicExpr::AO__c11_atomic_init: 4868 case AtomicExpr::AO__opencl_atomic_init: 4869 Form = Init; 4870 break; 4871 4872 case AtomicExpr::AO__c11_atomic_load: 4873 case AtomicExpr::AO__opencl_atomic_load: 4874 case AtomicExpr::AO__atomic_load_n: 4875 Form = Load; 4876 break; 4877 4878 case AtomicExpr::AO__atomic_load: 4879 Form = LoadCopy; 4880 break; 4881 4882 case AtomicExpr::AO__c11_atomic_store: 4883 case AtomicExpr::AO__opencl_atomic_store: 4884 case AtomicExpr::AO__atomic_store: 4885 case AtomicExpr::AO__atomic_store_n: 4886 Form = Copy; 4887 break; 4888 4889 case AtomicExpr::AO__c11_atomic_fetch_add: 4890 case AtomicExpr::AO__c11_atomic_fetch_sub: 4891 case AtomicExpr::AO__opencl_atomic_fetch_add: 4892 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4893 case AtomicExpr::AO__atomic_fetch_add: 4894 case AtomicExpr::AO__atomic_fetch_sub: 4895 case AtomicExpr::AO__atomic_add_fetch: 4896 case AtomicExpr::AO__atomic_sub_fetch: 4897 IsAddSub = true; 4898 LLVM_FALLTHROUGH; 4899 case AtomicExpr::AO__c11_atomic_fetch_and: 4900 case AtomicExpr::AO__c11_atomic_fetch_or: 4901 case AtomicExpr::AO__c11_atomic_fetch_xor: 4902 case AtomicExpr::AO__opencl_atomic_fetch_and: 4903 case AtomicExpr::AO__opencl_atomic_fetch_or: 4904 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4905 case AtomicExpr::AO__atomic_fetch_and: 4906 case AtomicExpr::AO__atomic_fetch_or: 4907 case AtomicExpr::AO__atomic_fetch_xor: 4908 case AtomicExpr::AO__atomic_fetch_nand: 4909 case AtomicExpr::AO__atomic_and_fetch: 4910 case AtomicExpr::AO__atomic_or_fetch: 4911 case AtomicExpr::AO__atomic_xor_fetch: 4912 case AtomicExpr::AO__atomic_nand_fetch: 4913 case AtomicExpr::AO__c11_atomic_fetch_min: 4914 case AtomicExpr::AO__c11_atomic_fetch_max: 4915 case AtomicExpr::AO__opencl_atomic_fetch_min: 4916 case AtomicExpr::AO__opencl_atomic_fetch_max: 4917 case AtomicExpr::AO__atomic_min_fetch: 4918 case AtomicExpr::AO__atomic_max_fetch: 4919 case AtomicExpr::AO__atomic_fetch_min: 4920 case AtomicExpr::AO__atomic_fetch_max: 4921 Form = Arithmetic; 4922 break; 4923 4924 case AtomicExpr::AO__c11_atomic_exchange: 4925 case AtomicExpr::AO__opencl_atomic_exchange: 4926 case AtomicExpr::AO__atomic_exchange_n: 4927 Form = Xchg; 4928 break; 4929 4930 case AtomicExpr::AO__atomic_exchange: 4931 Form = GNUXchg; 4932 break; 4933 4934 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4935 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4936 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4937 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4938 Form = C11CmpXchg; 4939 break; 4940 4941 case AtomicExpr::AO__atomic_compare_exchange: 4942 case AtomicExpr::AO__atomic_compare_exchange_n: 4943 Form = GNUCmpXchg; 4944 break; 4945 } 4946 4947 unsigned AdjustedNumArgs = NumArgs[Form]; 4948 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4949 ++AdjustedNumArgs; 4950 // Check we have the right number of arguments. 4951 if (Args.size() < AdjustedNumArgs) { 4952 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4953 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4954 << ExprRange; 4955 return ExprError(); 4956 } else if (Args.size() > AdjustedNumArgs) { 4957 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4958 diag::err_typecheck_call_too_many_args) 4959 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4960 << ExprRange; 4961 return ExprError(); 4962 } 4963 4964 // Inspect the first argument of the atomic operation. 4965 Expr *Ptr = Args[0]; 4966 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4967 if (ConvertedPtr.isInvalid()) 4968 return ExprError(); 4969 4970 Ptr = ConvertedPtr.get(); 4971 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4972 if (!pointerType) { 4973 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4974 << Ptr->getType() << Ptr->getSourceRange(); 4975 return ExprError(); 4976 } 4977 4978 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4979 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4980 QualType ValType = AtomTy; // 'C' 4981 if (IsC11) { 4982 if (!AtomTy->isAtomicType()) { 4983 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4984 << Ptr->getType() << Ptr->getSourceRange(); 4985 return ExprError(); 4986 } 4987 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4988 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4989 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4990 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4991 << Ptr->getSourceRange(); 4992 return ExprError(); 4993 } 4994 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4995 } else if (Form != Load && Form != LoadCopy) { 4996 if (ValType.isConstQualified()) { 4997 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4998 << Ptr->getType() << Ptr->getSourceRange(); 4999 return ExprError(); 5000 } 5001 } 5002 5003 // For an arithmetic operation, the implied arithmetic must be well-formed. 5004 if (Form == Arithmetic) { 5005 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 5006 if (IsAddSub && !ValType->isIntegerType() 5007 && !ValType->isPointerType()) { 5008 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5009 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5010 return ExprError(); 5011 } 5012 if (!IsAddSub && !ValType->isIntegerType()) { 5013 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5014 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5015 return ExprError(); 5016 } 5017 if (IsC11 && ValType->isPointerType() && 5018 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5019 diag::err_incomplete_type)) { 5020 return ExprError(); 5021 } 5022 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5023 // For __atomic_*_n operations, the value type must be a scalar integral or 5024 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5025 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5026 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5027 return ExprError(); 5028 } 5029 5030 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5031 !AtomTy->isScalarType()) { 5032 // For GNU atomics, require a trivially-copyable type. This is not part of 5033 // the GNU atomics specification, but we enforce it for sanity. 5034 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5035 << Ptr->getType() << Ptr->getSourceRange(); 5036 return ExprError(); 5037 } 5038 5039 switch (ValType.getObjCLifetime()) { 5040 case Qualifiers::OCL_None: 5041 case Qualifiers::OCL_ExplicitNone: 5042 // okay 5043 break; 5044 5045 case Qualifiers::OCL_Weak: 5046 case Qualifiers::OCL_Strong: 5047 case Qualifiers::OCL_Autoreleasing: 5048 // FIXME: Can this happen? By this point, ValType should be known 5049 // to be trivially copyable. 5050 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5051 << ValType << Ptr->getSourceRange(); 5052 return ExprError(); 5053 } 5054 5055 // All atomic operations have an overload which takes a pointer to a volatile 5056 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5057 // into the result or the other operands. Similarly atomic_load takes a 5058 // pointer to a const 'A'. 5059 ValType.removeLocalVolatile(); 5060 ValType.removeLocalConst(); 5061 QualType ResultType = ValType; 5062 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5063 Form == Init) 5064 ResultType = Context.VoidTy; 5065 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5066 ResultType = Context.BoolTy; 5067 5068 // The type of a parameter passed 'by value'. In the GNU atomics, such 5069 // arguments are actually passed as pointers. 5070 QualType ByValType = ValType; // 'CP' 5071 bool IsPassedByAddress = false; 5072 if (!IsC11 && !IsN) { 5073 ByValType = Ptr->getType(); 5074 IsPassedByAddress = true; 5075 } 5076 5077 SmallVector<Expr *, 5> APIOrderedArgs; 5078 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5079 APIOrderedArgs.push_back(Args[0]); 5080 switch (Form) { 5081 case Init: 5082 case Load: 5083 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5084 break; 5085 case LoadCopy: 5086 case Copy: 5087 case Arithmetic: 5088 case Xchg: 5089 APIOrderedArgs.push_back(Args[2]); // Val1 5090 APIOrderedArgs.push_back(Args[1]); // Order 5091 break; 5092 case GNUXchg: 5093 APIOrderedArgs.push_back(Args[2]); // Val1 5094 APIOrderedArgs.push_back(Args[3]); // Val2 5095 APIOrderedArgs.push_back(Args[1]); // Order 5096 break; 5097 case C11CmpXchg: 5098 APIOrderedArgs.push_back(Args[2]); // Val1 5099 APIOrderedArgs.push_back(Args[4]); // Val2 5100 APIOrderedArgs.push_back(Args[1]); // Order 5101 APIOrderedArgs.push_back(Args[3]); // OrderFail 5102 break; 5103 case GNUCmpXchg: 5104 APIOrderedArgs.push_back(Args[2]); // Val1 5105 APIOrderedArgs.push_back(Args[4]); // Val2 5106 APIOrderedArgs.push_back(Args[5]); // Weak 5107 APIOrderedArgs.push_back(Args[1]); // Order 5108 APIOrderedArgs.push_back(Args[3]); // OrderFail 5109 break; 5110 } 5111 } else 5112 APIOrderedArgs.append(Args.begin(), Args.end()); 5113 5114 // The first argument's non-CV pointer type is used to deduce the type of 5115 // subsequent arguments, except for: 5116 // - weak flag (always converted to bool) 5117 // - memory order (always converted to int) 5118 // - scope (always converted to int) 5119 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5120 QualType Ty; 5121 if (i < NumVals[Form] + 1) { 5122 switch (i) { 5123 case 0: 5124 // The first argument is always a pointer. It has a fixed type. 5125 // It is always dereferenced, a nullptr is undefined. 5126 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5127 // Nothing else to do: we already know all we want about this pointer. 5128 continue; 5129 case 1: 5130 // The second argument is the non-atomic operand. For arithmetic, this 5131 // is always passed by value, and for a compare_exchange it is always 5132 // passed by address. For the rest, GNU uses by-address and C11 uses 5133 // by-value. 5134 assert(Form != Load); 5135 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 5136 Ty = ValType; 5137 else if (Form == Copy || Form == Xchg) { 5138 if (IsPassedByAddress) { 5139 // The value pointer is always dereferenced, a nullptr is undefined. 5140 CheckNonNullArgument(*this, APIOrderedArgs[i], 5141 ExprRange.getBegin()); 5142 } 5143 Ty = ByValType; 5144 } else if (Form == Arithmetic) 5145 Ty = Context.getPointerDiffType(); 5146 else { 5147 Expr *ValArg = APIOrderedArgs[i]; 5148 // The value pointer is always dereferenced, a nullptr is undefined. 5149 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5150 LangAS AS = LangAS::Default; 5151 // Keep address space of non-atomic pointer type. 5152 if (const PointerType *PtrTy = 5153 ValArg->getType()->getAs<PointerType>()) { 5154 AS = PtrTy->getPointeeType().getAddressSpace(); 5155 } 5156 Ty = Context.getPointerType( 5157 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5158 } 5159 break; 5160 case 2: 5161 // The third argument to compare_exchange / GNU exchange is the desired 5162 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5163 if (IsPassedByAddress) 5164 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5165 Ty = ByValType; 5166 break; 5167 case 3: 5168 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5169 Ty = Context.BoolTy; 5170 break; 5171 } 5172 } else { 5173 // The order(s) and scope are always converted to int. 5174 Ty = Context.IntTy; 5175 } 5176 5177 InitializedEntity Entity = 5178 InitializedEntity::InitializeParameter(Context, Ty, false); 5179 ExprResult Arg = APIOrderedArgs[i]; 5180 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5181 if (Arg.isInvalid()) 5182 return true; 5183 APIOrderedArgs[i] = Arg.get(); 5184 } 5185 5186 // Permute the arguments into a 'consistent' order. 5187 SmallVector<Expr*, 5> SubExprs; 5188 SubExprs.push_back(Ptr); 5189 switch (Form) { 5190 case Init: 5191 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5192 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5193 break; 5194 case Load: 5195 SubExprs.push_back(APIOrderedArgs[1]); // Order 5196 break; 5197 case LoadCopy: 5198 case Copy: 5199 case Arithmetic: 5200 case Xchg: 5201 SubExprs.push_back(APIOrderedArgs[2]); // Order 5202 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5203 break; 5204 case GNUXchg: 5205 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5206 SubExprs.push_back(APIOrderedArgs[3]); // Order 5207 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5208 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5209 break; 5210 case C11CmpXchg: 5211 SubExprs.push_back(APIOrderedArgs[3]); // Order 5212 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5213 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5214 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5215 break; 5216 case GNUCmpXchg: 5217 SubExprs.push_back(APIOrderedArgs[4]); // Order 5218 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5219 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5220 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5221 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5222 break; 5223 } 5224 5225 if (SubExprs.size() >= 2 && Form != Init) { 5226 if (Optional<llvm::APSInt> Result = 5227 SubExprs[1]->getIntegerConstantExpr(Context)) 5228 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5229 Diag(SubExprs[1]->getBeginLoc(), 5230 diag::warn_atomic_op_has_invalid_memory_order) 5231 << SubExprs[1]->getSourceRange(); 5232 } 5233 5234 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5235 auto *Scope = Args[Args.size() - 1]; 5236 if (Optional<llvm::APSInt> Result = 5237 Scope->getIntegerConstantExpr(Context)) { 5238 if (!ScopeModel->isValid(Result->getZExtValue())) 5239 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5240 << Scope->getSourceRange(); 5241 } 5242 SubExprs.push_back(Scope); 5243 } 5244 5245 AtomicExpr *AE = new (Context) 5246 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5247 5248 if ((Op == AtomicExpr::AO__c11_atomic_load || 5249 Op == AtomicExpr::AO__c11_atomic_store || 5250 Op == AtomicExpr::AO__opencl_atomic_load || 5251 Op == AtomicExpr::AO__opencl_atomic_store ) && 5252 Context.AtomicUsesUnsupportedLibcall(AE)) 5253 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5254 << ((Op == AtomicExpr::AO__c11_atomic_load || 5255 Op == AtomicExpr::AO__opencl_atomic_load) 5256 ? 0 5257 : 1); 5258 5259 if (ValType->isExtIntType()) { 5260 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5261 return ExprError(); 5262 } 5263 5264 return AE; 5265 } 5266 5267 /// checkBuiltinArgument - Given a call to a builtin function, perform 5268 /// normal type-checking on the given argument, updating the call in 5269 /// place. This is useful when a builtin function requires custom 5270 /// type-checking for some of its arguments but not necessarily all of 5271 /// them. 5272 /// 5273 /// Returns true on error. 5274 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5275 FunctionDecl *Fn = E->getDirectCallee(); 5276 assert(Fn && "builtin call without direct callee!"); 5277 5278 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5279 InitializedEntity Entity = 5280 InitializedEntity::InitializeParameter(S.Context, Param); 5281 5282 ExprResult Arg = E->getArg(0); 5283 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5284 if (Arg.isInvalid()) 5285 return true; 5286 5287 E->setArg(ArgIndex, Arg.get()); 5288 return false; 5289 } 5290 5291 /// We have a call to a function like __sync_fetch_and_add, which is an 5292 /// overloaded function based on the pointer type of its first argument. 5293 /// The main BuildCallExpr routines have already promoted the types of 5294 /// arguments because all of these calls are prototyped as void(...). 5295 /// 5296 /// This function goes through and does final semantic checking for these 5297 /// builtins, as well as generating any warnings. 5298 ExprResult 5299 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5300 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5301 Expr *Callee = TheCall->getCallee(); 5302 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5303 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5304 5305 // Ensure that we have at least one argument to do type inference from. 5306 if (TheCall->getNumArgs() < 1) { 5307 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5308 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5309 return ExprError(); 5310 } 5311 5312 // Inspect the first argument of the atomic builtin. This should always be 5313 // a pointer type, whose element is an integral scalar or pointer type. 5314 // Because it is a pointer type, we don't have to worry about any implicit 5315 // casts here. 5316 // FIXME: We don't allow floating point scalars as input. 5317 Expr *FirstArg = TheCall->getArg(0); 5318 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5319 if (FirstArgResult.isInvalid()) 5320 return ExprError(); 5321 FirstArg = FirstArgResult.get(); 5322 TheCall->setArg(0, FirstArg); 5323 5324 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5325 if (!pointerType) { 5326 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5327 << FirstArg->getType() << FirstArg->getSourceRange(); 5328 return ExprError(); 5329 } 5330 5331 QualType ValType = pointerType->getPointeeType(); 5332 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5333 !ValType->isBlockPointerType()) { 5334 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5335 << FirstArg->getType() << FirstArg->getSourceRange(); 5336 return ExprError(); 5337 } 5338 5339 if (ValType.isConstQualified()) { 5340 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5341 << FirstArg->getType() << FirstArg->getSourceRange(); 5342 return ExprError(); 5343 } 5344 5345 switch (ValType.getObjCLifetime()) { 5346 case Qualifiers::OCL_None: 5347 case Qualifiers::OCL_ExplicitNone: 5348 // okay 5349 break; 5350 5351 case Qualifiers::OCL_Weak: 5352 case Qualifiers::OCL_Strong: 5353 case Qualifiers::OCL_Autoreleasing: 5354 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5355 << ValType << FirstArg->getSourceRange(); 5356 return ExprError(); 5357 } 5358 5359 // Strip any qualifiers off ValType. 5360 ValType = ValType.getUnqualifiedType(); 5361 5362 // The majority of builtins return a value, but a few have special return 5363 // types, so allow them to override appropriately below. 5364 QualType ResultType = ValType; 5365 5366 // We need to figure out which concrete builtin this maps onto. For example, 5367 // __sync_fetch_and_add with a 2 byte object turns into 5368 // __sync_fetch_and_add_2. 5369 #define BUILTIN_ROW(x) \ 5370 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5371 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5372 5373 static const unsigned BuiltinIndices[][5] = { 5374 BUILTIN_ROW(__sync_fetch_and_add), 5375 BUILTIN_ROW(__sync_fetch_and_sub), 5376 BUILTIN_ROW(__sync_fetch_and_or), 5377 BUILTIN_ROW(__sync_fetch_and_and), 5378 BUILTIN_ROW(__sync_fetch_and_xor), 5379 BUILTIN_ROW(__sync_fetch_and_nand), 5380 5381 BUILTIN_ROW(__sync_add_and_fetch), 5382 BUILTIN_ROW(__sync_sub_and_fetch), 5383 BUILTIN_ROW(__sync_and_and_fetch), 5384 BUILTIN_ROW(__sync_or_and_fetch), 5385 BUILTIN_ROW(__sync_xor_and_fetch), 5386 BUILTIN_ROW(__sync_nand_and_fetch), 5387 5388 BUILTIN_ROW(__sync_val_compare_and_swap), 5389 BUILTIN_ROW(__sync_bool_compare_and_swap), 5390 BUILTIN_ROW(__sync_lock_test_and_set), 5391 BUILTIN_ROW(__sync_lock_release), 5392 BUILTIN_ROW(__sync_swap) 5393 }; 5394 #undef BUILTIN_ROW 5395 5396 // Determine the index of the size. 5397 unsigned SizeIndex; 5398 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5399 case 1: SizeIndex = 0; break; 5400 case 2: SizeIndex = 1; break; 5401 case 4: SizeIndex = 2; break; 5402 case 8: SizeIndex = 3; break; 5403 case 16: SizeIndex = 4; break; 5404 default: 5405 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5406 << FirstArg->getType() << FirstArg->getSourceRange(); 5407 return ExprError(); 5408 } 5409 5410 // Each of these builtins has one pointer argument, followed by some number of 5411 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5412 // that we ignore. Find out which row of BuiltinIndices to read from as well 5413 // as the number of fixed args. 5414 unsigned BuiltinID = FDecl->getBuiltinID(); 5415 unsigned BuiltinIndex, NumFixed = 1; 5416 bool WarnAboutSemanticsChange = false; 5417 switch (BuiltinID) { 5418 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5419 case Builtin::BI__sync_fetch_and_add: 5420 case Builtin::BI__sync_fetch_and_add_1: 5421 case Builtin::BI__sync_fetch_and_add_2: 5422 case Builtin::BI__sync_fetch_and_add_4: 5423 case Builtin::BI__sync_fetch_and_add_8: 5424 case Builtin::BI__sync_fetch_and_add_16: 5425 BuiltinIndex = 0; 5426 break; 5427 5428 case Builtin::BI__sync_fetch_and_sub: 5429 case Builtin::BI__sync_fetch_and_sub_1: 5430 case Builtin::BI__sync_fetch_and_sub_2: 5431 case Builtin::BI__sync_fetch_and_sub_4: 5432 case Builtin::BI__sync_fetch_and_sub_8: 5433 case Builtin::BI__sync_fetch_and_sub_16: 5434 BuiltinIndex = 1; 5435 break; 5436 5437 case Builtin::BI__sync_fetch_and_or: 5438 case Builtin::BI__sync_fetch_and_or_1: 5439 case Builtin::BI__sync_fetch_and_or_2: 5440 case Builtin::BI__sync_fetch_and_or_4: 5441 case Builtin::BI__sync_fetch_and_or_8: 5442 case Builtin::BI__sync_fetch_and_or_16: 5443 BuiltinIndex = 2; 5444 break; 5445 5446 case Builtin::BI__sync_fetch_and_and: 5447 case Builtin::BI__sync_fetch_and_and_1: 5448 case Builtin::BI__sync_fetch_and_and_2: 5449 case Builtin::BI__sync_fetch_and_and_4: 5450 case Builtin::BI__sync_fetch_and_and_8: 5451 case Builtin::BI__sync_fetch_and_and_16: 5452 BuiltinIndex = 3; 5453 break; 5454 5455 case Builtin::BI__sync_fetch_and_xor: 5456 case Builtin::BI__sync_fetch_and_xor_1: 5457 case Builtin::BI__sync_fetch_and_xor_2: 5458 case Builtin::BI__sync_fetch_and_xor_4: 5459 case Builtin::BI__sync_fetch_and_xor_8: 5460 case Builtin::BI__sync_fetch_and_xor_16: 5461 BuiltinIndex = 4; 5462 break; 5463 5464 case Builtin::BI__sync_fetch_and_nand: 5465 case Builtin::BI__sync_fetch_and_nand_1: 5466 case Builtin::BI__sync_fetch_and_nand_2: 5467 case Builtin::BI__sync_fetch_and_nand_4: 5468 case Builtin::BI__sync_fetch_and_nand_8: 5469 case Builtin::BI__sync_fetch_and_nand_16: 5470 BuiltinIndex = 5; 5471 WarnAboutSemanticsChange = true; 5472 break; 5473 5474 case Builtin::BI__sync_add_and_fetch: 5475 case Builtin::BI__sync_add_and_fetch_1: 5476 case Builtin::BI__sync_add_and_fetch_2: 5477 case Builtin::BI__sync_add_and_fetch_4: 5478 case Builtin::BI__sync_add_and_fetch_8: 5479 case Builtin::BI__sync_add_and_fetch_16: 5480 BuiltinIndex = 6; 5481 break; 5482 5483 case Builtin::BI__sync_sub_and_fetch: 5484 case Builtin::BI__sync_sub_and_fetch_1: 5485 case Builtin::BI__sync_sub_and_fetch_2: 5486 case Builtin::BI__sync_sub_and_fetch_4: 5487 case Builtin::BI__sync_sub_and_fetch_8: 5488 case Builtin::BI__sync_sub_and_fetch_16: 5489 BuiltinIndex = 7; 5490 break; 5491 5492 case Builtin::BI__sync_and_and_fetch: 5493 case Builtin::BI__sync_and_and_fetch_1: 5494 case Builtin::BI__sync_and_and_fetch_2: 5495 case Builtin::BI__sync_and_and_fetch_4: 5496 case Builtin::BI__sync_and_and_fetch_8: 5497 case Builtin::BI__sync_and_and_fetch_16: 5498 BuiltinIndex = 8; 5499 break; 5500 5501 case Builtin::BI__sync_or_and_fetch: 5502 case Builtin::BI__sync_or_and_fetch_1: 5503 case Builtin::BI__sync_or_and_fetch_2: 5504 case Builtin::BI__sync_or_and_fetch_4: 5505 case Builtin::BI__sync_or_and_fetch_8: 5506 case Builtin::BI__sync_or_and_fetch_16: 5507 BuiltinIndex = 9; 5508 break; 5509 5510 case Builtin::BI__sync_xor_and_fetch: 5511 case Builtin::BI__sync_xor_and_fetch_1: 5512 case Builtin::BI__sync_xor_and_fetch_2: 5513 case Builtin::BI__sync_xor_and_fetch_4: 5514 case Builtin::BI__sync_xor_and_fetch_8: 5515 case Builtin::BI__sync_xor_and_fetch_16: 5516 BuiltinIndex = 10; 5517 break; 5518 5519 case Builtin::BI__sync_nand_and_fetch: 5520 case Builtin::BI__sync_nand_and_fetch_1: 5521 case Builtin::BI__sync_nand_and_fetch_2: 5522 case Builtin::BI__sync_nand_and_fetch_4: 5523 case Builtin::BI__sync_nand_and_fetch_8: 5524 case Builtin::BI__sync_nand_and_fetch_16: 5525 BuiltinIndex = 11; 5526 WarnAboutSemanticsChange = true; 5527 break; 5528 5529 case Builtin::BI__sync_val_compare_and_swap: 5530 case Builtin::BI__sync_val_compare_and_swap_1: 5531 case Builtin::BI__sync_val_compare_and_swap_2: 5532 case Builtin::BI__sync_val_compare_and_swap_4: 5533 case Builtin::BI__sync_val_compare_and_swap_8: 5534 case Builtin::BI__sync_val_compare_and_swap_16: 5535 BuiltinIndex = 12; 5536 NumFixed = 2; 5537 break; 5538 5539 case Builtin::BI__sync_bool_compare_and_swap: 5540 case Builtin::BI__sync_bool_compare_and_swap_1: 5541 case Builtin::BI__sync_bool_compare_and_swap_2: 5542 case Builtin::BI__sync_bool_compare_and_swap_4: 5543 case Builtin::BI__sync_bool_compare_and_swap_8: 5544 case Builtin::BI__sync_bool_compare_and_swap_16: 5545 BuiltinIndex = 13; 5546 NumFixed = 2; 5547 ResultType = Context.BoolTy; 5548 break; 5549 5550 case Builtin::BI__sync_lock_test_and_set: 5551 case Builtin::BI__sync_lock_test_and_set_1: 5552 case Builtin::BI__sync_lock_test_and_set_2: 5553 case Builtin::BI__sync_lock_test_and_set_4: 5554 case Builtin::BI__sync_lock_test_and_set_8: 5555 case Builtin::BI__sync_lock_test_and_set_16: 5556 BuiltinIndex = 14; 5557 break; 5558 5559 case Builtin::BI__sync_lock_release: 5560 case Builtin::BI__sync_lock_release_1: 5561 case Builtin::BI__sync_lock_release_2: 5562 case Builtin::BI__sync_lock_release_4: 5563 case Builtin::BI__sync_lock_release_8: 5564 case Builtin::BI__sync_lock_release_16: 5565 BuiltinIndex = 15; 5566 NumFixed = 0; 5567 ResultType = Context.VoidTy; 5568 break; 5569 5570 case Builtin::BI__sync_swap: 5571 case Builtin::BI__sync_swap_1: 5572 case Builtin::BI__sync_swap_2: 5573 case Builtin::BI__sync_swap_4: 5574 case Builtin::BI__sync_swap_8: 5575 case Builtin::BI__sync_swap_16: 5576 BuiltinIndex = 16; 5577 break; 5578 } 5579 5580 // Now that we know how many fixed arguments we expect, first check that we 5581 // have at least that many. 5582 if (TheCall->getNumArgs() < 1+NumFixed) { 5583 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5584 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5585 << Callee->getSourceRange(); 5586 return ExprError(); 5587 } 5588 5589 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5590 << Callee->getSourceRange(); 5591 5592 if (WarnAboutSemanticsChange) { 5593 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5594 << Callee->getSourceRange(); 5595 } 5596 5597 // Get the decl for the concrete builtin from this, we can tell what the 5598 // concrete integer type we should convert to is. 5599 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5600 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5601 FunctionDecl *NewBuiltinDecl; 5602 if (NewBuiltinID == BuiltinID) 5603 NewBuiltinDecl = FDecl; 5604 else { 5605 // Perform builtin lookup to avoid redeclaring it. 5606 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5607 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5608 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5609 assert(Res.getFoundDecl()); 5610 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5611 if (!NewBuiltinDecl) 5612 return ExprError(); 5613 } 5614 5615 // The first argument --- the pointer --- has a fixed type; we 5616 // deduce the types of the rest of the arguments accordingly. Walk 5617 // the remaining arguments, converting them to the deduced value type. 5618 for (unsigned i = 0; i != NumFixed; ++i) { 5619 ExprResult Arg = TheCall->getArg(i+1); 5620 5621 // GCC does an implicit conversion to the pointer or integer ValType. This 5622 // can fail in some cases (1i -> int**), check for this error case now. 5623 // Initialize the argument. 5624 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5625 ValType, /*consume*/ false); 5626 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5627 if (Arg.isInvalid()) 5628 return ExprError(); 5629 5630 // Okay, we have something that *can* be converted to the right type. Check 5631 // to see if there is a potentially weird extension going on here. This can 5632 // happen when you do an atomic operation on something like an char* and 5633 // pass in 42. The 42 gets converted to char. This is even more strange 5634 // for things like 45.123 -> char, etc. 5635 // FIXME: Do this check. 5636 TheCall->setArg(i+1, Arg.get()); 5637 } 5638 5639 // Create a new DeclRefExpr to refer to the new decl. 5640 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5641 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5642 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5643 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5644 5645 // Set the callee in the CallExpr. 5646 // FIXME: This loses syntactic information. 5647 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5648 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5649 CK_BuiltinFnToFnPtr); 5650 TheCall->setCallee(PromotedCall.get()); 5651 5652 // Change the result type of the call to match the original value type. This 5653 // is arbitrary, but the codegen for these builtins ins design to handle it 5654 // gracefully. 5655 TheCall->setType(ResultType); 5656 5657 // Prohibit use of _ExtInt with atomic builtins. 5658 // The arguments would have already been converted to the first argument's 5659 // type, so only need to check the first argument. 5660 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5661 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5662 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5663 return ExprError(); 5664 } 5665 5666 return TheCallResult; 5667 } 5668 5669 /// SemaBuiltinNontemporalOverloaded - We have a call to 5670 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5671 /// overloaded function based on the pointer type of its last argument. 5672 /// 5673 /// This function goes through and does final semantic checking for these 5674 /// builtins. 5675 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5676 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5677 DeclRefExpr *DRE = 5678 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5679 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5680 unsigned BuiltinID = FDecl->getBuiltinID(); 5681 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5682 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5683 "Unexpected nontemporal load/store builtin!"); 5684 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5685 unsigned numArgs = isStore ? 2 : 1; 5686 5687 // Ensure that we have the proper number of arguments. 5688 if (checkArgCount(*this, TheCall, numArgs)) 5689 return ExprError(); 5690 5691 // Inspect the last argument of the nontemporal builtin. This should always 5692 // be a pointer type, from which we imply the type of the memory access. 5693 // Because it is a pointer type, we don't have to worry about any implicit 5694 // casts here. 5695 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5696 ExprResult PointerArgResult = 5697 DefaultFunctionArrayLvalueConversion(PointerArg); 5698 5699 if (PointerArgResult.isInvalid()) 5700 return ExprError(); 5701 PointerArg = PointerArgResult.get(); 5702 TheCall->setArg(numArgs - 1, PointerArg); 5703 5704 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5705 if (!pointerType) { 5706 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5707 << PointerArg->getType() << PointerArg->getSourceRange(); 5708 return ExprError(); 5709 } 5710 5711 QualType ValType = pointerType->getPointeeType(); 5712 5713 // Strip any qualifiers off ValType. 5714 ValType = ValType.getUnqualifiedType(); 5715 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5716 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5717 !ValType->isVectorType()) { 5718 Diag(DRE->getBeginLoc(), 5719 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5720 << PointerArg->getType() << PointerArg->getSourceRange(); 5721 return ExprError(); 5722 } 5723 5724 if (!isStore) { 5725 TheCall->setType(ValType); 5726 return TheCallResult; 5727 } 5728 5729 ExprResult ValArg = TheCall->getArg(0); 5730 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5731 Context, ValType, /*consume*/ false); 5732 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5733 if (ValArg.isInvalid()) 5734 return ExprError(); 5735 5736 TheCall->setArg(0, ValArg.get()); 5737 TheCall->setType(Context.VoidTy); 5738 return TheCallResult; 5739 } 5740 5741 /// CheckObjCString - Checks that the argument to the builtin 5742 /// CFString constructor is correct 5743 /// Note: It might also make sense to do the UTF-16 conversion here (would 5744 /// simplify the backend). 5745 bool Sema::CheckObjCString(Expr *Arg) { 5746 Arg = Arg->IgnoreParenCasts(); 5747 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5748 5749 if (!Literal || !Literal->isAscii()) { 5750 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5751 << Arg->getSourceRange(); 5752 return true; 5753 } 5754 5755 if (Literal->containsNonAsciiOrNull()) { 5756 StringRef String = Literal->getString(); 5757 unsigned NumBytes = String.size(); 5758 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5759 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5760 llvm::UTF16 *ToPtr = &ToBuf[0]; 5761 5762 llvm::ConversionResult Result = 5763 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5764 ToPtr + NumBytes, llvm::strictConversion); 5765 // Check for conversion failure. 5766 if (Result != llvm::conversionOK) 5767 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5768 << Arg->getSourceRange(); 5769 } 5770 return false; 5771 } 5772 5773 /// CheckObjCString - Checks that the format string argument to the os_log() 5774 /// and os_trace() functions is correct, and converts it to const char *. 5775 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5776 Arg = Arg->IgnoreParenCasts(); 5777 auto *Literal = dyn_cast<StringLiteral>(Arg); 5778 if (!Literal) { 5779 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5780 Literal = ObjcLiteral->getString(); 5781 } 5782 } 5783 5784 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5785 return ExprError( 5786 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5787 << Arg->getSourceRange()); 5788 } 5789 5790 ExprResult Result(Literal); 5791 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5792 InitializedEntity Entity = 5793 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5794 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5795 return Result; 5796 } 5797 5798 /// Check that the user is calling the appropriate va_start builtin for the 5799 /// target and calling convention. 5800 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5801 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5802 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5803 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5804 TT.getArch() == llvm::Triple::aarch64_32); 5805 bool IsWindows = TT.isOSWindows(); 5806 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5807 if (IsX64 || IsAArch64) { 5808 CallingConv CC = CC_C; 5809 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5810 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5811 if (IsMSVAStart) { 5812 // Don't allow this in System V ABI functions. 5813 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5814 return S.Diag(Fn->getBeginLoc(), 5815 diag::err_ms_va_start_used_in_sysv_function); 5816 } else { 5817 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5818 // On x64 Windows, don't allow this in System V ABI functions. 5819 // (Yes, that means there's no corresponding way to support variadic 5820 // System V ABI functions on Windows.) 5821 if ((IsWindows && CC == CC_X86_64SysV) || 5822 (!IsWindows && CC == CC_Win64)) 5823 return S.Diag(Fn->getBeginLoc(), 5824 diag::err_va_start_used_in_wrong_abi_function) 5825 << !IsWindows; 5826 } 5827 return false; 5828 } 5829 5830 if (IsMSVAStart) 5831 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5832 return false; 5833 } 5834 5835 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5836 ParmVarDecl **LastParam = nullptr) { 5837 // Determine whether the current function, block, or obj-c method is variadic 5838 // and get its parameter list. 5839 bool IsVariadic = false; 5840 ArrayRef<ParmVarDecl *> Params; 5841 DeclContext *Caller = S.CurContext; 5842 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5843 IsVariadic = Block->isVariadic(); 5844 Params = Block->parameters(); 5845 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5846 IsVariadic = FD->isVariadic(); 5847 Params = FD->parameters(); 5848 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5849 IsVariadic = MD->isVariadic(); 5850 // FIXME: This isn't correct for methods (results in bogus warning). 5851 Params = MD->parameters(); 5852 } else if (isa<CapturedDecl>(Caller)) { 5853 // We don't support va_start in a CapturedDecl. 5854 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5855 return true; 5856 } else { 5857 // This must be some other declcontext that parses exprs. 5858 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5859 return true; 5860 } 5861 5862 if (!IsVariadic) { 5863 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5864 return true; 5865 } 5866 5867 if (LastParam) 5868 *LastParam = Params.empty() ? nullptr : Params.back(); 5869 5870 return false; 5871 } 5872 5873 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5874 /// for validity. Emit an error and return true on failure; return false 5875 /// on success. 5876 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5877 Expr *Fn = TheCall->getCallee(); 5878 5879 if (checkVAStartABI(*this, BuiltinID, Fn)) 5880 return true; 5881 5882 if (checkArgCount(*this, TheCall, 2)) 5883 return true; 5884 5885 // Type-check the first argument normally. 5886 if (checkBuiltinArgument(*this, TheCall, 0)) 5887 return true; 5888 5889 // Check that the current function is variadic, and get its last parameter. 5890 ParmVarDecl *LastParam; 5891 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5892 return true; 5893 5894 // Verify that the second argument to the builtin is the last argument of the 5895 // current function or method. 5896 bool SecondArgIsLastNamedArgument = false; 5897 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5898 5899 // These are valid if SecondArgIsLastNamedArgument is false after the next 5900 // block. 5901 QualType Type; 5902 SourceLocation ParamLoc; 5903 bool IsCRegister = false; 5904 5905 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5906 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5907 SecondArgIsLastNamedArgument = PV == LastParam; 5908 5909 Type = PV->getType(); 5910 ParamLoc = PV->getLocation(); 5911 IsCRegister = 5912 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5913 } 5914 } 5915 5916 if (!SecondArgIsLastNamedArgument) 5917 Diag(TheCall->getArg(1)->getBeginLoc(), 5918 diag::warn_second_arg_of_va_start_not_last_named_param); 5919 else if (IsCRegister || Type->isReferenceType() || 5920 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5921 // Promotable integers are UB, but enumerations need a bit of 5922 // extra checking to see what their promotable type actually is. 5923 if (!Type->isPromotableIntegerType()) 5924 return false; 5925 if (!Type->isEnumeralType()) 5926 return true; 5927 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5928 return !(ED && 5929 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5930 }()) { 5931 unsigned Reason = 0; 5932 if (Type->isReferenceType()) Reason = 1; 5933 else if (IsCRegister) Reason = 2; 5934 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5935 Diag(ParamLoc, diag::note_parameter_type) << Type; 5936 } 5937 5938 TheCall->setType(Context.VoidTy); 5939 return false; 5940 } 5941 5942 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5943 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5944 // const char *named_addr); 5945 5946 Expr *Func = Call->getCallee(); 5947 5948 if (Call->getNumArgs() < 3) 5949 return Diag(Call->getEndLoc(), 5950 diag::err_typecheck_call_too_few_args_at_least) 5951 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5952 5953 // Type-check the first argument normally. 5954 if (checkBuiltinArgument(*this, Call, 0)) 5955 return true; 5956 5957 // Check that the current function is variadic. 5958 if (checkVAStartIsInVariadicFunction(*this, Func)) 5959 return true; 5960 5961 // __va_start on Windows does not validate the parameter qualifiers 5962 5963 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5964 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5965 5966 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5967 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5968 5969 const QualType &ConstCharPtrTy = 5970 Context.getPointerType(Context.CharTy.withConst()); 5971 if (!Arg1Ty->isPointerType() || 5972 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5973 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5974 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5975 << 0 /* qualifier difference */ 5976 << 3 /* parameter mismatch */ 5977 << 2 << Arg1->getType() << ConstCharPtrTy; 5978 5979 const QualType SizeTy = Context.getSizeType(); 5980 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5981 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5982 << Arg2->getType() << SizeTy << 1 /* different class */ 5983 << 0 /* qualifier difference */ 5984 << 3 /* parameter mismatch */ 5985 << 3 << Arg2->getType() << SizeTy; 5986 5987 return false; 5988 } 5989 5990 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5991 /// friends. This is declared to take (...), so we have to check everything. 5992 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5993 if (checkArgCount(*this, TheCall, 2)) 5994 return true; 5995 5996 ExprResult OrigArg0 = TheCall->getArg(0); 5997 ExprResult OrigArg1 = TheCall->getArg(1); 5998 5999 // Do standard promotions between the two arguments, returning their common 6000 // type. 6001 QualType Res = UsualArithmeticConversions( 6002 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6003 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6004 return true; 6005 6006 // Make sure any conversions are pushed back into the call; this is 6007 // type safe since unordered compare builtins are declared as "_Bool 6008 // foo(...)". 6009 TheCall->setArg(0, OrigArg0.get()); 6010 TheCall->setArg(1, OrigArg1.get()); 6011 6012 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6013 return false; 6014 6015 // If the common type isn't a real floating type, then the arguments were 6016 // invalid for this operation. 6017 if (Res.isNull() || !Res->isRealFloatingType()) 6018 return Diag(OrigArg0.get()->getBeginLoc(), 6019 diag::err_typecheck_call_invalid_ordered_compare) 6020 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6021 << SourceRange(OrigArg0.get()->getBeginLoc(), 6022 OrigArg1.get()->getEndLoc()); 6023 6024 return false; 6025 } 6026 6027 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6028 /// __builtin_isnan and friends. This is declared to take (...), so we have 6029 /// to check everything. We expect the last argument to be a floating point 6030 /// value. 6031 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6032 if (checkArgCount(*this, TheCall, NumArgs)) 6033 return true; 6034 6035 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6036 // on all preceding parameters just being int. Try all of those. 6037 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6038 Expr *Arg = TheCall->getArg(i); 6039 6040 if (Arg->isTypeDependent()) 6041 return false; 6042 6043 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6044 6045 if (Res.isInvalid()) 6046 return true; 6047 TheCall->setArg(i, Res.get()); 6048 } 6049 6050 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6051 6052 if (OrigArg->isTypeDependent()) 6053 return false; 6054 6055 // Usual Unary Conversions will convert half to float, which we want for 6056 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6057 // type how it is, but do normal L->Rvalue conversions. 6058 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6059 OrigArg = UsualUnaryConversions(OrigArg).get(); 6060 else 6061 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6062 TheCall->setArg(NumArgs - 1, OrigArg); 6063 6064 // This operation requires a non-_Complex floating-point number. 6065 if (!OrigArg->getType()->isRealFloatingType()) 6066 return Diag(OrigArg->getBeginLoc(), 6067 diag::err_typecheck_call_invalid_unary_fp) 6068 << OrigArg->getType() << OrigArg->getSourceRange(); 6069 6070 return false; 6071 } 6072 6073 /// Perform semantic analysis for a call to __builtin_complex. 6074 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6075 if (checkArgCount(*this, TheCall, 2)) 6076 return true; 6077 6078 bool Dependent = false; 6079 for (unsigned I = 0; I != 2; ++I) { 6080 Expr *Arg = TheCall->getArg(I); 6081 QualType T = Arg->getType(); 6082 if (T->isDependentType()) { 6083 Dependent = true; 6084 continue; 6085 } 6086 6087 // Despite supporting _Complex int, GCC requires a real floating point type 6088 // for the operands of __builtin_complex. 6089 if (!T->isRealFloatingType()) { 6090 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6091 << Arg->getType() << Arg->getSourceRange(); 6092 } 6093 6094 ExprResult Converted = DefaultLvalueConversion(Arg); 6095 if (Converted.isInvalid()) 6096 return true; 6097 TheCall->setArg(I, Converted.get()); 6098 } 6099 6100 if (Dependent) { 6101 TheCall->setType(Context.DependentTy); 6102 return false; 6103 } 6104 6105 Expr *Real = TheCall->getArg(0); 6106 Expr *Imag = TheCall->getArg(1); 6107 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6108 return Diag(Real->getBeginLoc(), 6109 diag::err_typecheck_call_different_arg_types) 6110 << Real->getType() << Imag->getType() 6111 << Real->getSourceRange() << Imag->getSourceRange(); 6112 } 6113 6114 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6115 // don't allow this builtin to form those types either. 6116 // FIXME: Should we allow these types? 6117 if (Real->getType()->isFloat16Type()) 6118 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6119 << "_Float16"; 6120 if (Real->getType()->isHalfType()) 6121 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6122 << "half"; 6123 6124 TheCall->setType(Context.getComplexType(Real->getType())); 6125 return false; 6126 } 6127 6128 // Customized Sema Checking for VSX builtins that have the following signature: 6129 // vector [...] builtinName(vector [...], vector [...], const int); 6130 // Which takes the same type of vectors (any legal vector type) for the first 6131 // two arguments and takes compile time constant for the third argument. 6132 // Example builtins are : 6133 // vector double vec_xxpermdi(vector double, vector double, int); 6134 // vector short vec_xxsldwi(vector short, vector short, int); 6135 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6136 unsigned ExpectedNumArgs = 3; 6137 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6138 return true; 6139 6140 // Check the third argument is a compile time constant 6141 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6142 return Diag(TheCall->getBeginLoc(), 6143 diag::err_vsx_builtin_nonconstant_argument) 6144 << 3 /* argument index */ << TheCall->getDirectCallee() 6145 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6146 TheCall->getArg(2)->getEndLoc()); 6147 6148 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6149 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6150 6151 // Check the type of argument 1 and argument 2 are vectors. 6152 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6153 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6154 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6155 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6156 << TheCall->getDirectCallee() 6157 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6158 TheCall->getArg(1)->getEndLoc()); 6159 } 6160 6161 // Check the first two arguments are the same type. 6162 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6163 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6164 << TheCall->getDirectCallee() 6165 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6166 TheCall->getArg(1)->getEndLoc()); 6167 } 6168 6169 // When default clang type checking is turned off and the customized type 6170 // checking is used, the returning type of the function must be explicitly 6171 // set. Otherwise it is _Bool by default. 6172 TheCall->setType(Arg1Ty); 6173 6174 return false; 6175 } 6176 6177 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6178 // This is declared to take (...), so we have to check everything. 6179 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6180 if (TheCall->getNumArgs() < 2) 6181 return ExprError(Diag(TheCall->getEndLoc(), 6182 diag::err_typecheck_call_too_few_args_at_least) 6183 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6184 << TheCall->getSourceRange()); 6185 6186 // Determine which of the following types of shufflevector we're checking: 6187 // 1) unary, vector mask: (lhs, mask) 6188 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6189 QualType resType = TheCall->getArg(0)->getType(); 6190 unsigned numElements = 0; 6191 6192 if (!TheCall->getArg(0)->isTypeDependent() && 6193 !TheCall->getArg(1)->isTypeDependent()) { 6194 QualType LHSType = TheCall->getArg(0)->getType(); 6195 QualType RHSType = TheCall->getArg(1)->getType(); 6196 6197 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6198 return ExprError( 6199 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6200 << TheCall->getDirectCallee() 6201 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6202 TheCall->getArg(1)->getEndLoc())); 6203 6204 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6205 unsigned numResElements = TheCall->getNumArgs() - 2; 6206 6207 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6208 // with mask. If so, verify that RHS is an integer vector type with the 6209 // same number of elts as lhs. 6210 if (TheCall->getNumArgs() == 2) { 6211 if (!RHSType->hasIntegerRepresentation() || 6212 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6213 return ExprError(Diag(TheCall->getBeginLoc(), 6214 diag::err_vec_builtin_incompatible_vector) 6215 << TheCall->getDirectCallee() 6216 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6217 TheCall->getArg(1)->getEndLoc())); 6218 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6219 return ExprError(Diag(TheCall->getBeginLoc(), 6220 diag::err_vec_builtin_incompatible_vector) 6221 << TheCall->getDirectCallee() 6222 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6223 TheCall->getArg(1)->getEndLoc())); 6224 } else if (numElements != numResElements) { 6225 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6226 resType = Context.getVectorType(eltType, numResElements, 6227 VectorType::GenericVector); 6228 } 6229 } 6230 6231 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6232 if (TheCall->getArg(i)->isTypeDependent() || 6233 TheCall->getArg(i)->isValueDependent()) 6234 continue; 6235 6236 Optional<llvm::APSInt> Result; 6237 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6238 return ExprError(Diag(TheCall->getBeginLoc(), 6239 diag::err_shufflevector_nonconstant_argument) 6240 << TheCall->getArg(i)->getSourceRange()); 6241 6242 // Allow -1 which will be translated to undef in the IR. 6243 if (Result->isSigned() && Result->isAllOnesValue()) 6244 continue; 6245 6246 if (Result->getActiveBits() > 64 || 6247 Result->getZExtValue() >= numElements * 2) 6248 return ExprError(Diag(TheCall->getBeginLoc(), 6249 diag::err_shufflevector_argument_too_large) 6250 << TheCall->getArg(i)->getSourceRange()); 6251 } 6252 6253 SmallVector<Expr*, 32> exprs; 6254 6255 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6256 exprs.push_back(TheCall->getArg(i)); 6257 TheCall->setArg(i, nullptr); 6258 } 6259 6260 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6261 TheCall->getCallee()->getBeginLoc(), 6262 TheCall->getRParenLoc()); 6263 } 6264 6265 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6266 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6267 SourceLocation BuiltinLoc, 6268 SourceLocation RParenLoc) { 6269 ExprValueKind VK = VK_RValue; 6270 ExprObjectKind OK = OK_Ordinary; 6271 QualType DstTy = TInfo->getType(); 6272 QualType SrcTy = E->getType(); 6273 6274 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6275 return ExprError(Diag(BuiltinLoc, 6276 diag::err_convertvector_non_vector) 6277 << E->getSourceRange()); 6278 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6279 return ExprError(Diag(BuiltinLoc, 6280 diag::err_convertvector_non_vector_type)); 6281 6282 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6283 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6284 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6285 if (SrcElts != DstElts) 6286 return ExprError(Diag(BuiltinLoc, 6287 diag::err_convertvector_incompatible_vector) 6288 << E->getSourceRange()); 6289 } 6290 6291 return new (Context) 6292 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6293 } 6294 6295 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6296 // This is declared to take (const void*, ...) and can take two 6297 // optional constant int args. 6298 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6299 unsigned NumArgs = TheCall->getNumArgs(); 6300 6301 if (NumArgs > 3) 6302 return Diag(TheCall->getEndLoc(), 6303 diag::err_typecheck_call_too_many_args_at_most) 6304 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6305 6306 // Argument 0 is checked for us and the remaining arguments must be 6307 // constant integers. 6308 for (unsigned i = 1; i != NumArgs; ++i) 6309 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6310 return true; 6311 6312 return false; 6313 } 6314 6315 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6316 // __assume does not evaluate its arguments, and should warn if its argument 6317 // has side effects. 6318 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6319 Expr *Arg = TheCall->getArg(0); 6320 if (Arg->isInstantiationDependent()) return false; 6321 6322 if (Arg->HasSideEffects(Context)) 6323 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6324 << Arg->getSourceRange() 6325 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6326 6327 return false; 6328 } 6329 6330 /// Handle __builtin_alloca_with_align. This is declared 6331 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6332 /// than 8. 6333 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6334 // The alignment must be a constant integer. 6335 Expr *Arg = TheCall->getArg(1); 6336 6337 // We can't check the value of a dependent argument. 6338 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6339 if (const auto *UE = 6340 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6341 if (UE->getKind() == UETT_AlignOf || 6342 UE->getKind() == UETT_PreferredAlignOf) 6343 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6344 << Arg->getSourceRange(); 6345 6346 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6347 6348 if (!Result.isPowerOf2()) 6349 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6350 << Arg->getSourceRange(); 6351 6352 if (Result < Context.getCharWidth()) 6353 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6354 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6355 6356 if (Result > std::numeric_limits<int32_t>::max()) 6357 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6358 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6359 } 6360 6361 return false; 6362 } 6363 6364 /// Handle __builtin_assume_aligned. This is declared 6365 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6366 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6367 unsigned NumArgs = TheCall->getNumArgs(); 6368 6369 if (NumArgs > 3) 6370 return Diag(TheCall->getEndLoc(), 6371 diag::err_typecheck_call_too_many_args_at_most) 6372 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6373 6374 // The alignment must be a constant integer. 6375 Expr *Arg = TheCall->getArg(1); 6376 6377 // We can't check the value of a dependent argument. 6378 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6379 llvm::APSInt Result; 6380 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6381 return true; 6382 6383 if (!Result.isPowerOf2()) 6384 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6385 << Arg->getSourceRange(); 6386 6387 if (Result > Sema::MaximumAlignment) 6388 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6389 << Arg->getSourceRange() << Sema::MaximumAlignment; 6390 } 6391 6392 if (NumArgs > 2) { 6393 ExprResult Arg(TheCall->getArg(2)); 6394 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6395 Context.getSizeType(), false); 6396 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6397 if (Arg.isInvalid()) return true; 6398 TheCall->setArg(2, Arg.get()); 6399 } 6400 6401 return false; 6402 } 6403 6404 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6405 unsigned BuiltinID = 6406 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6407 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6408 6409 unsigned NumArgs = TheCall->getNumArgs(); 6410 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6411 if (NumArgs < NumRequiredArgs) { 6412 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6413 << 0 /* function call */ << NumRequiredArgs << NumArgs 6414 << TheCall->getSourceRange(); 6415 } 6416 if (NumArgs >= NumRequiredArgs + 0x100) { 6417 return Diag(TheCall->getEndLoc(), 6418 diag::err_typecheck_call_too_many_args_at_most) 6419 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6420 << TheCall->getSourceRange(); 6421 } 6422 unsigned i = 0; 6423 6424 // For formatting call, check buffer arg. 6425 if (!IsSizeCall) { 6426 ExprResult Arg(TheCall->getArg(i)); 6427 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6428 Context, Context.VoidPtrTy, false); 6429 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6430 if (Arg.isInvalid()) 6431 return true; 6432 TheCall->setArg(i, Arg.get()); 6433 i++; 6434 } 6435 6436 // Check string literal arg. 6437 unsigned FormatIdx = i; 6438 { 6439 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6440 if (Arg.isInvalid()) 6441 return true; 6442 TheCall->setArg(i, Arg.get()); 6443 i++; 6444 } 6445 6446 // Make sure variadic args are scalar. 6447 unsigned FirstDataArg = i; 6448 while (i < NumArgs) { 6449 ExprResult Arg = DefaultVariadicArgumentPromotion( 6450 TheCall->getArg(i), VariadicFunction, nullptr); 6451 if (Arg.isInvalid()) 6452 return true; 6453 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6454 if (ArgSize.getQuantity() >= 0x100) { 6455 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6456 << i << (int)ArgSize.getQuantity() << 0xff 6457 << TheCall->getSourceRange(); 6458 } 6459 TheCall->setArg(i, Arg.get()); 6460 i++; 6461 } 6462 6463 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6464 // call to avoid duplicate diagnostics. 6465 if (!IsSizeCall) { 6466 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6467 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6468 bool Success = CheckFormatArguments( 6469 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6470 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6471 CheckedVarArgs); 6472 if (!Success) 6473 return true; 6474 } 6475 6476 if (IsSizeCall) { 6477 TheCall->setType(Context.getSizeType()); 6478 } else { 6479 TheCall->setType(Context.VoidPtrTy); 6480 } 6481 return false; 6482 } 6483 6484 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6485 /// TheCall is a constant expression. 6486 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6487 llvm::APSInt &Result) { 6488 Expr *Arg = TheCall->getArg(ArgNum); 6489 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6490 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6491 6492 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6493 6494 Optional<llvm::APSInt> R; 6495 if (!(R = Arg->getIntegerConstantExpr(Context))) 6496 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6497 << FDecl->getDeclName() << Arg->getSourceRange(); 6498 Result = *R; 6499 return false; 6500 } 6501 6502 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6503 /// TheCall is a constant expression in the range [Low, High]. 6504 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6505 int Low, int High, bool RangeIsError) { 6506 if (isConstantEvaluated()) 6507 return false; 6508 llvm::APSInt Result; 6509 6510 // We can't check the value of a dependent argument. 6511 Expr *Arg = TheCall->getArg(ArgNum); 6512 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6513 return false; 6514 6515 // Check constant-ness first. 6516 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6517 return true; 6518 6519 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6520 if (RangeIsError) 6521 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6522 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6523 else 6524 // Defer the warning until we know if the code will be emitted so that 6525 // dead code can ignore this. 6526 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6527 PDiag(diag::warn_argument_invalid_range) 6528 << Result.toString(10) << Low << High 6529 << Arg->getSourceRange()); 6530 } 6531 6532 return false; 6533 } 6534 6535 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6536 /// TheCall is a constant expression is a multiple of Num.. 6537 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6538 unsigned Num) { 6539 llvm::APSInt Result; 6540 6541 // We can't check the value of a dependent argument. 6542 Expr *Arg = TheCall->getArg(ArgNum); 6543 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6544 return false; 6545 6546 // Check constant-ness first. 6547 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6548 return true; 6549 6550 if (Result.getSExtValue() % Num != 0) 6551 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6552 << Num << Arg->getSourceRange(); 6553 6554 return false; 6555 } 6556 6557 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6558 /// constant expression representing a power of 2. 6559 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6560 llvm::APSInt Result; 6561 6562 // We can't check the value of a dependent argument. 6563 Expr *Arg = TheCall->getArg(ArgNum); 6564 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6565 return false; 6566 6567 // Check constant-ness first. 6568 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6569 return true; 6570 6571 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6572 // and only if x is a power of 2. 6573 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6574 return false; 6575 6576 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6577 << Arg->getSourceRange(); 6578 } 6579 6580 static bool IsShiftedByte(llvm::APSInt Value) { 6581 if (Value.isNegative()) 6582 return false; 6583 6584 // Check if it's a shifted byte, by shifting it down 6585 while (true) { 6586 // If the value fits in the bottom byte, the check passes. 6587 if (Value < 0x100) 6588 return true; 6589 6590 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6591 // fails. 6592 if ((Value & 0xFF) != 0) 6593 return false; 6594 6595 // If the bottom 8 bits are all 0, but something above that is nonzero, 6596 // then shifting the value right by 8 bits won't affect whether it's a 6597 // shifted byte or not. So do that, and go round again. 6598 Value >>= 8; 6599 } 6600 } 6601 6602 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6603 /// a constant expression representing an arbitrary byte value shifted left by 6604 /// a multiple of 8 bits. 6605 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6606 unsigned ArgBits) { 6607 llvm::APSInt Result; 6608 6609 // We can't check the value of a dependent argument. 6610 Expr *Arg = TheCall->getArg(ArgNum); 6611 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6612 return false; 6613 6614 // Check constant-ness first. 6615 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6616 return true; 6617 6618 // Truncate to the given size. 6619 Result = Result.getLoBits(ArgBits); 6620 Result.setIsUnsigned(true); 6621 6622 if (IsShiftedByte(Result)) 6623 return false; 6624 6625 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6626 << Arg->getSourceRange(); 6627 } 6628 6629 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6630 /// TheCall is a constant expression representing either a shifted byte value, 6631 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6632 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6633 /// Arm MVE intrinsics. 6634 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6635 int ArgNum, 6636 unsigned ArgBits) { 6637 llvm::APSInt Result; 6638 6639 // We can't check the value of a dependent argument. 6640 Expr *Arg = TheCall->getArg(ArgNum); 6641 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6642 return false; 6643 6644 // Check constant-ness first. 6645 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6646 return true; 6647 6648 // Truncate to the given size. 6649 Result = Result.getLoBits(ArgBits); 6650 Result.setIsUnsigned(true); 6651 6652 // Check to see if it's in either of the required forms. 6653 if (IsShiftedByte(Result) || 6654 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6655 return false; 6656 6657 return Diag(TheCall->getBeginLoc(), 6658 diag::err_argument_not_shifted_byte_or_xxff) 6659 << Arg->getSourceRange(); 6660 } 6661 6662 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6663 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6664 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6665 if (checkArgCount(*this, TheCall, 2)) 6666 return true; 6667 Expr *Arg0 = TheCall->getArg(0); 6668 Expr *Arg1 = TheCall->getArg(1); 6669 6670 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6671 if (FirstArg.isInvalid()) 6672 return true; 6673 QualType FirstArgType = FirstArg.get()->getType(); 6674 if (!FirstArgType->isAnyPointerType()) 6675 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6676 << "first" << FirstArgType << Arg0->getSourceRange(); 6677 TheCall->setArg(0, FirstArg.get()); 6678 6679 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6680 if (SecArg.isInvalid()) 6681 return true; 6682 QualType SecArgType = SecArg.get()->getType(); 6683 if (!SecArgType->isIntegerType()) 6684 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6685 << "second" << SecArgType << Arg1->getSourceRange(); 6686 6687 // Derive the return type from the pointer argument. 6688 TheCall->setType(FirstArgType); 6689 return false; 6690 } 6691 6692 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6693 if (checkArgCount(*this, TheCall, 2)) 6694 return true; 6695 6696 Expr *Arg0 = TheCall->getArg(0); 6697 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6698 if (FirstArg.isInvalid()) 6699 return true; 6700 QualType FirstArgType = FirstArg.get()->getType(); 6701 if (!FirstArgType->isAnyPointerType()) 6702 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6703 << "first" << FirstArgType << Arg0->getSourceRange(); 6704 TheCall->setArg(0, FirstArg.get()); 6705 6706 // Derive the return type from the pointer argument. 6707 TheCall->setType(FirstArgType); 6708 6709 // Second arg must be an constant in range [0,15] 6710 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6711 } 6712 6713 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6714 if (checkArgCount(*this, TheCall, 2)) 6715 return true; 6716 Expr *Arg0 = TheCall->getArg(0); 6717 Expr *Arg1 = TheCall->getArg(1); 6718 6719 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6720 if (FirstArg.isInvalid()) 6721 return true; 6722 QualType FirstArgType = FirstArg.get()->getType(); 6723 if (!FirstArgType->isAnyPointerType()) 6724 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6725 << "first" << FirstArgType << Arg0->getSourceRange(); 6726 6727 QualType SecArgType = Arg1->getType(); 6728 if (!SecArgType->isIntegerType()) 6729 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6730 << "second" << SecArgType << Arg1->getSourceRange(); 6731 TheCall->setType(Context.IntTy); 6732 return false; 6733 } 6734 6735 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6736 BuiltinID == AArch64::BI__builtin_arm_stg) { 6737 if (checkArgCount(*this, TheCall, 1)) 6738 return true; 6739 Expr *Arg0 = TheCall->getArg(0); 6740 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6741 if (FirstArg.isInvalid()) 6742 return true; 6743 6744 QualType FirstArgType = FirstArg.get()->getType(); 6745 if (!FirstArgType->isAnyPointerType()) 6746 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6747 << "first" << FirstArgType << Arg0->getSourceRange(); 6748 TheCall->setArg(0, FirstArg.get()); 6749 6750 // Derive the return type from the pointer argument. 6751 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6752 TheCall->setType(FirstArgType); 6753 return false; 6754 } 6755 6756 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6757 Expr *ArgA = TheCall->getArg(0); 6758 Expr *ArgB = TheCall->getArg(1); 6759 6760 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6761 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6762 6763 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6764 return true; 6765 6766 QualType ArgTypeA = ArgExprA.get()->getType(); 6767 QualType ArgTypeB = ArgExprB.get()->getType(); 6768 6769 auto isNull = [&] (Expr *E) -> bool { 6770 return E->isNullPointerConstant( 6771 Context, Expr::NPC_ValueDependentIsNotNull); }; 6772 6773 // argument should be either a pointer or null 6774 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6775 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6776 << "first" << ArgTypeA << ArgA->getSourceRange(); 6777 6778 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6779 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6780 << "second" << ArgTypeB << ArgB->getSourceRange(); 6781 6782 // Ensure Pointee types are compatible 6783 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6784 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6785 QualType pointeeA = ArgTypeA->getPointeeType(); 6786 QualType pointeeB = ArgTypeB->getPointeeType(); 6787 if (!Context.typesAreCompatible( 6788 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6789 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6790 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6791 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6792 << ArgB->getSourceRange(); 6793 } 6794 } 6795 6796 // at least one argument should be pointer type 6797 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6798 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6799 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6800 6801 if (isNull(ArgA)) // adopt type of the other pointer 6802 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6803 6804 if (isNull(ArgB)) 6805 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6806 6807 TheCall->setArg(0, ArgExprA.get()); 6808 TheCall->setArg(1, ArgExprB.get()); 6809 TheCall->setType(Context.LongLongTy); 6810 return false; 6811 } 6812 assert(false && "Unhandled ARM MTE intrinsic"); 6813 return true; 6814 } 6815 6816 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6817 /// TheCall is an ARM/AArch64 special register string literal. 6818 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6819 int ArgNum, unsigned ExpectedFieldNum, 6820 bool AllowName) { 6821 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6822 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6823 BuiltinID == ARM::BI__builtin_arm_rsr || 6824 BuiltinID == ARM::BI__builtin_arm_rsrp || 6825 BuiltinID == ARM::BI__builtin_arm_wsr || 6826 BuiltinID == ARM::BI__builtin_arm_wsrp; 6827 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6828 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6829 BuiltinID == AArch64::BI__builtin_arm_rsr || 6830 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6831 BuiltinID == AArch64::BI__builtin_arm_wsr || 6832 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6833 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6834 6835 // We can't check the value of a dependent argument. 6836 Expr *Arg = TheCall->getArg(ArgNum); 6837 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6838 return false; 6839 6840 // Check if the argument is a string literal. 6841 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6842 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6843 << Arg->getSourceRange(); 6844 6845 // Check the type of special register given. 6846 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6847 SmallVector<StringRef, 6> Fields; 6848 Reg.split(Fields, ":"); 6849 6850 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6851 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6852 << Arg->getSourceRange(); 6853 6854 // If the string is the name of a register then we cannot check that it is 6855 // valid here but if the string is of one the forms described in ACLE then we 6856 // can check that the supplied fields are integers and within the valid 6857 // ranges. 6858 if (Fields.size() > 1) { 6859 bool FiveFields = Fields.size() == 5; 6860 6861 bool ValidString = true; 6862 if (IsARMBuiltin) { 6863 ValidString &= Fields[0].startswith_lower("cp") || 6864 Fields[0].startswith_lower("p"); 6865 if (ValidString) 6866 Fields[0] = 6867 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6868 6869 ValidString &= Fields[2].startswith_lower("c"); 6870 if (ValidString) 6871 Fields[2] = Fields[2].drop_front(1); 6872 6873 if (FiveFields) { 6874 ValidString &= Fields[3].startswith_lower("c"); 6875 if (ValidString) 6876 Fields[3] = Fields[3].drop_front(1); 6877 } 6878 } 6879 6880 SmallVector<int, 5> Ranges; 6881 if (FiveFields) 6882 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6883 else 6884 Ranges.append({15, 7, 15}); 6885 6886 for (unsigned i=0; i<Fields.size(); ++i) { 6887 int IntField; 6888 ValidString &= !Fields[i].getAsInteger(10, IntField); 6889 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6890 } 6891 6892 if (!ValidString) 6893 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6894 << Arg->getSourceRange(); 6895 } else if (IsAArch64Builtin && Fields.size() == 1) { 6896 // If the register name is one of those that appear in the condition below 6897 // and the special register builtin being used is one of the write builtins, 6898 // then we require that the argument provided for writing to the register 6899 // is an integer constant expression. This is because it will be lowered to 6900 // an MSR (immediate) instruction, so we need to know the immediate at 6901 // compile time. 6902 if (TheCall->getNumArgs() != 2) 6903 return false; 6904 6905 std::string RegLower = Reg.lower(); 6906 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6907 RegLower != "pan" && RegLower != "uao") 6908 return false; 6909 6910 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6911 } 6912 6913 return false; 6914 } 6915 6916 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 6917 /// Emit an error and return true on failure; return false on success. 6918 /// TypeStr is a string containing the type descriptor of the value returned by 6919 /// the builtin and the descriptors of the expected type of the arguments. 6920 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 6921 6922 assert((TypeStr[0] != '\0') && 6923 "Invalid types in PPC MMA builtin declaration"); 6924 6925 unsigned Mask = 0; 6926 unsigned ArgNum = 0; 6927 6928 // The first type in TypeStr is the type of the value returned by the 6929 // builtin. So we first read that type and change the type of TheCall. 6930 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6931 TheCall->setType(type); 6932 6933 while (*TypeStr != '\0') { 6934 Mask = 0; 6935 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6936 if (ArgNum >= TheCall->getNumArgs()) { 6937 ArgNum++; 6938 break; 6939 } 6940 6941 Expr *Arg = TheCall->getArg(ArgNum); 6942 QualType ArgType = Arg->getType(); 6943 6944 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 6945 (!ExpectedType->isVoidPointerType() && 6946 ArgType.getCanonicalType() != ExpectedType)) 6947 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6948 << ArgType << ExpectedType << 1 << 0 << 0; 6949 6950 // If the value of the Mask is not 0, we have a constraint in the size of 6951 // the integer argument so here we ensure the argument is a constant that 6952 // is in the valid range. 6953 if (Mask != 0 && 6954 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 6955 return true; 6956 6957 ArgNum++; 6958 } 6959 6960 // In case we exited early from the previous loop, there are other types to 6961 // read from TypeStr. So we need to read them all to ensure we have the right 6962 // number of arguments in TheCall and if it is not the case, to display a 6963 // better error message. 6964 while (*TypeStr != '\0') { 6965 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6966 ArgNum++; 6967 } 6968 if (checkArgCount(*this, TheCall, ArgNum)) 6969 return true; 6970 6971 return false; 6972 } 6973 6974 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6975 /// This checks that the target supports __builtin_longjmp and 6976 /// that val is a constant 1. 6977 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6978 if (!Context.getTargetInfo().hasSjLjLowering()) 6979 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6980 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6981 6982 Expr *Arg = TheCall->getArg(1); 6983 llvm::APSInt Result; 6984 6985 // TODO: This is less than ideal. Overload this to take a value. 6986 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6987 return true; 6988 6989 if (Result != 1) 6990 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6991 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6992 6993 return false; 6994 } 6995 6996 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6997 /// This checks that the target supports __builtin_setjmp. 6998 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6999 if (!Context.getTargetInfo().hasSjLjLowering()) 7000 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7001 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7002 return false; 7003 } 7004 7005 namespace { 7006 7007 class UncoveredArgHandler { 7008 enum { Unknown = -1, AllCovered = -2 }; 7009 7010 signed FirstUncoveredArg = Unknown; 7011 SmallVector<const Expr *, 4> DiagnosticExprs; 7012 7013 public: 7014 UncoveredArgHandler() = default; 7015 7016 bool hasUncoveredArg() const { 7017 return (FirstUncoveredArg >= 0); 7018 } 7019 7020 unsigned getUncoveredArg() const { 7021 assert(hasUncoveredArg() && "no uncovered argument"); 7022 return FirstUncoveredArg; 7023 } 7024 7025 void setAllCovered() { 7026 // A string has been found with all arguments covered, so clear out 7027 // the diagnostics. 7028 DiagnosticExprs.clear(); 7029 FirstUncoveredArg = AllCovered; 7030 } 7031 7032 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7033 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7034 7035 // Don't update if a previous string covers all arguments. 7036 if (FirstUncoveredArg == AllCovered) 7037 return; 7038 7039 // UncoveredArgHandler tracks the highest uncovered argument index 7040 // and with it all the strings that match this index. 7041 if (NewFirstUncoveredArg == FirstUncoveredArg) 7042 DiagnosticExprs.push_back(StrExpr); 7043 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7044 DiagnosticExprs.clear(); 7045 DiagnosticExprs.push_back(StrExpr); 7046 FirstUncoveredArg = NewFirstUncoveredArg; 7047 } 7048 } 7049 7050 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7051 }; 7052 7053 enum StringLiteralCheckType { 7054 SLCT_NotALiteral, 7055 SLCT_UncheckedLiteral, 7056 SLCT_CheckedLiteral 7057 }; 7058 7059 } // namespace 7060 7061 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7062 BinaryOperatorKind BinOpKind, 7063 bool AddendIsRight) { 7064 unsigned BitWidth = Offset.getBitWidth(); 7065 unsigned AddendBitWidth = Addend.getBitWidth(); 7066 // There might be negative interim results. 7067 if (Addend.isUnsigned()) { 7068 Addend = Addend.zext(++AddendBitWidth); 7069 Addend.setIsSigned(true); 7070 } 7071 // Adjust the bit width of the APSInts. 7072 if (AddendBitWidth > BitWidth) { 7073 Offset = Offset.sext(AddendBitWidth); 7074 BitWidth = AddendBitWidth; 7075 } else if (BitWidth > AddendBitWidth) { 7076 Addend = Addend.sext(BitWidth); 7077 } 7078 7079 bool Ov = false; 7080 llvm::APSInt ResOffset = Offset; 7081 if (BinOpKind == BO_Add) 7082 ResOffset = Offset.sadd_ov(Addend, Ov); 7083 else { 7084 assert(AddendIsRight && BinOpKind == BO_Sub && 7085 "operator must be add or sub with addend on the right"); 7086 ResOffset = Offset.ssub_ov(Addend, Ov); 7087 } 7088 7089 // We add an offset to a pointer here so we should support an offset as big as 7090 // possible. 7091 if (Ov) { 7092 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7093 "index (intermediate) result too big"); 7094 Offset = Offset.sext(2 * BitWidth); 7095 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7096 return; 7097 } 7098 7099 Offset = ResOffset; 7100 } 7101 7102 namespace { 7103 7104 // This is a wrapper class around StringLiteral to support offsetted string 7105 // literals as format strings. It takes the offset into account when returning 7106 // the string and its length or the source locations to display notes correctly. 7107 class FormatStringLiteral { 7108 const StringLiteral *FExpr; 7109 int64_t Offset; 7110 7111 public: 7112 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7113 : FExpr(fexpr), Offset(Offset) {} 7114 7115 StringRef getString() const { 7116 return FExpr->getString().drop_front(Offset); 7117 } 7118 7119 unsigned getByteLength() const { 7120 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7121 } 7122 7123 unsigned getLength() const { return FExpr->getLength() - Offset; } 7124 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7125 7126 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7127 7128 QualType getType() const { return FExpr->getType(); } 7129 7130 bool isAscii() const { return FExpr->isAscii(); } 7131 bool isWide() const { return FExpr->isWide(); } 7132 bool isUTF8() const { return FExpr->isUTF8(); } 7133 bool isUTF16() const { return FExpr->isUTF16(); } 7134 bool isUTF32() const { return FExpr->isUTF32(); } 7135 bool isPascal() const { return FExpr->isPascal(); } 7136 7137 SourceLocation getLocationOfByte( 7138 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7139 const TargetInfo &Target, unsigned *StartToken = nullptr, 7140 unsigned *StartTokenByteOffset = nullptr) const { 7141 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7142 StartToken, StartTokenByteOffset); 7143 } 7144 7145 SourceLocation getBeginLoc() const LLVM_READONLY { 7146 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7147 } 7148 7149 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7150 }; 7151 7152 } // namespace 7153 7154 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7155 const Expr *OrigFormatExpr, 7156 ArrayRef<const Expr *> Args, 7157 bool HasVAListArg, unsigned format_idx, 7158 unsigned firstDataArg, 7159 Sema::FormatStringType Type, 7160 bool inFunctionCall, 7161 Sema::VariadicCallType CallType, 7162 llvm::SmallBitVector &CheckedVarArgs, 7163 UncoveredArgHandler &UncoveredArg, 7164 bool IgnoreStringsWithoutSpecifiers); 7165 7166 // Determine if an expression is a string literal or constant string. 7167 // If this function returns false on the arguments to a function expecting a 7168 // format string, we will usually need to emit a warning. 7169 // True string literals are then checked by CheckFormatString. 7170 static StringLiteralCheckType 7171 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7172 bool HasVAListArg, unsigned format_idx, 7173 unsigned firstDataArg, Sema::FormatStringType Type, 7174 Sema::VariadicCallType CallType, bool InFunctionCall, 7175 llvm::SmallBitVector &CheckedVarArgs, 7176 UncoveredArgHandler &UncoveredArg, 7177 llvm::APSInt Offset, 7178 bool IgnoreStringsWithoutSpecifiers = false) { 7179 if (S.isConstantEvaluated()) 7180 return SLCT_NotALiteral; 7181 tryAgain: 7182 assert(Offset.isSigned() && "invalid offset"); 7183 7184 if (E->isTypeDependent() || E->isValueDependent()) 7185 return SLCT_NotALiteral; 7186 7187 E = E->IgnoreParenCasts(); 7188 7189 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7190 // Technically -Wformat-nonliteral does not warn about this case. 7191 // The behavior of printf and friends in this case is implementation 7192 // dependent. Ideally if the format string cannot be null then 7193 // it should have a 'nonnull' attribute in the function prototype. 7194 return SLCT_UncheckedLiteral; 7195 7196 switch (E->getStmtClass()) { 7197 case Stmt::BinaryConditionalOperatorClass: 7198 case Stmt::ConditionalOperatorClass: { 7199 // The expression is a literal if both sub-expressions were, and it was 7200 // completely checked only if both sub-expressions were checked. 7201 const AbstractConditionalOperator *C = 7202 cast<AbstractConditionalOperator>(E); 7203 7204 // Determine whether it is necessary to check both sub-expressions, for 7205 // example, because the condition expression is a constant that can be 7206 // evaluated at compile time. 7207 bool CheckLeft = true, CheckRight = true; 7208 7209 bool Cond; 7210 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7211 S.isConstantEvaluated())) { 7212 if (Cond) 7213 CheckRight = false; 7214 else 7215 CheckLeft = false; 7216 } 7217 7218 // We need to maintain the offsets for the right and the left hand side 7219 // separately to check if every possible indexed expression is a valid 7220 // string literal. They might have different offsets for different string 7221 // literals in the end. 7222 StringLiteralCheckType Left; 7223 if (!CheckLeft) 7224 Left = SLCT_UncheckedLiteral; 7225 else { 7226 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7227 HasVAListArg, format_idx, firstDataArg, 7228 Type, CallType, InFunctionCall, 7229 CheckedVarArgs, UncoveredArg, Offset, 7230 IgnoreStringsWithoutSpecifiers); 7231 if (Left == SLCT_NotALiteral || !CheckRight) { 7232 return Left; 7233 } 7234 } 7235 7236 StringLiteralCheckType Right = checkFormatStringExpr( 7237 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7238 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7239 IgnoreStringsWithoutSpecifiers); 7240 7241 return (CheckLeft && Left < Right) ? Left : Right; 7242 } 7243 7244 case Stmt::ImplicitCastExprClass: 7245 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7246 goto tryAgain; 7247 7248 case Stmt::OpaqueValueExprClass: 7249 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7250 E = src; 7251 goto tryAgain; 7252 } 7253 return SLCT_NotALiteral; 7254 7255 case Stmt::PredefinedExprClass: 7256 // While __func__, etc., are technically not string literals, they 7257 // cannot contain format specifiers and thus are not a security 7258 // liability. 7259 return SLCT_UncheckedLiteral; 7260 7261 case Stmt::DeclRefExprClass: { 7262 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7263 7264 // As an exception, do not flag errors for variables binding to 7265 // const string literals. 7266 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7267 bool isConstant = false; 7268 QualType T = DR->getType(); 7269 7270 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7271 isConstant = AT->getElementType().isConstant(S.Context); 7272 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7273 isConstant = T.isConstant(S.Context) && 7274 PT->getPointeeType().isConstant(S.Context); 7275 } else if (T->isObjCObjectPointerType()) { 7276 // In ObjC, there is usually no "const ObjectPointer" type, 7277 // so don't check if the pointee type is constant. 7278 isConstant = T.isConstant(S.Context); 7279 } 7280 7281 if (isConstant) { 7282 if (const Expr *Init = VD->getAnyInitializer()) { 7283 // Look through initializers like const char c[] = { "foo" } 7284 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7285 if (InitList->isStringLiteralInit()) 7286 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7287 } 7288 return checkFormatStringExpr(S, Init, Args, 7289 HasVAListArg, format_idx, 7290 firstDataArg, Type, CallType, 7291 /*InFunctionCall*/ false, CheckedVarArgs, 7292 UncoveredArg, Offset); 7293 } 7294 } 7295 7296 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7297 // special check to see if the format string is a function parameter 7298 // of the function calling the printf function. If the function 7299 // has an attribute indicating it is a printf-like function, then we 7300 // should suppress warnings concerning non-literals being used in a call 7301 // to a vprintf function. For example: 7302 // 7303 // void 7304 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7305 // va_list ap; 7306 // va_start(ap, fmt); 7307 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7308 // ... 7309 // } 7310 if (HasVAListArg) { 7311 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7312 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7313 int PVIndex = PV->getFunctionScopeIndex() + 1; 7314 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7315 // adjust for implicit parameter 7316 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7317 if (MD->isInstance()) 7318 ++PVIndex; 7319 // We also check if the formats are compatible. 7320 // We can't pass a 'scanf' string to a 'printf' function. 7321 if (PVIndex == PVFormat->getFormatIdx() && 7322 Type == S.GetFormatStringType(PVFormat)) 7323 return SLCT_UncheckedLiteral; 7324 } 7325 } 7326 } 7327 } 7328 } 7329 7330 return SLCT_NotALiteral; 7331 } 7332 7333 case Stmt::CallExprClass: 7334 case Stmt::CXXMemberCallExprClass: { 7335 const CallExpr *CE = cast<CallExpr>(E); 7336 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7337 bool IsFirst = true; 7338 StringLiteralCheckType CommonResult; 7339 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7340 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7341 StringLiteralCheckType Result = checkFormatStringExpr( 7342 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7343 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7344 IgnoreStringsWithoutSpecifiers); 7345 if (IsFirst) { 7346 CommonResult = Result; 7347 IsFirst = false; 7348 } 7349 } 7350 if (!IsFirst) 7351 return CommonResult; 7352 7353 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7354 unsigned BuiltinID = FD->getBuiltinID(); 7355 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7356 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7357 const Expr *Arg = CE->getArg(0); 7358 return checkFormatStringExpr(S, Arg, Args, 7359 HasVAListArg, format_idx, 7360 firstDataArg, Type, CallType, 7361 InFunctionCall, CheckedVarArgs, 7362 UncoveredArg, Offset, 7363 IgnoreStringsWithoutSpecifiers); 7364 } 7365 } 7366 } 7367 7368 return SLCT_NotALiteral; 7369 } 7370 case Stmt::ObjCMessageExprClass: { 7371 const auto *ME = cast<ObjCMessageExpr>(E); 7372 if (const auto *MD = ME->getMethodDecl()) { 7373 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7374 // As a special case heuristic, if we're using the method -[NSBundle 7375 // localizedStringForKey:value:table:], ignore any key strings that lack 7376 // format specifiers. The idea is that if the key doesn't have any 7377 // format specifiers then its probably just a key to map to the 7378 // localized strings. If it does have format specifiers though, then its 7379 // likely that the text of the key is the format string in the 7380 // programmer's language, and should be checked. 7381 const ObjCInterfaceDecl *IFace; 7382 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7383 IFace->getIdentifier()->isStr("NSBundle") && 7384 MD->getSelector().isKeywordSelector( 7385 {"localizedStringForKey", "value", "table"})) { 7386 IgnoreStringsWithoutSpecifiers = true; 7387 } 7388 7389 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7390 return checkFormatStringExpr( 7391 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7392 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7393 IgnoreStringsWithoutSpecifiers); 7394 } 7395 } 7396 7397 return SLCT_NotALiteral; 7398 } 7399 case Stmt::ObjCStringLiteralClass: 7400 case Stmt::StringLiteralClass: { 7401 const StringLiteral *StrE = nullptr; 7402 7403 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7404 StrE = ObjCFExpr->getString(); 7405 else 7406 StrE = cast<StringLiteral>(E); 7407 7408 if (StrE) { 7409 if (Offset.isNegative() || Offset > StrE->getLength()) { 7410 // TODO: It would be better to have an explicit warning for out of 7411 // bounds literals. 7412 return SLCT_NotALiteral; 7413 } 7414 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7415 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7416 firstDataArg, Type, InFunctionCall, CallType, 7417 CheckedVarArgs, UncoveredArg, 7418 IgnoreStringsWithoutSpecifiers); 7419 return SLCT_CheckedLiteral; 7420 } 7421 7422 return SLCT_NotALiteral; 7423 } 7424 case Stmt::BinaryOperatorClass: { 7425 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7426 7427 // A string literal + an int offset is still a string literal. 7428 if (BinOp->isAdditiveOp()) { 7429 Expr::EvalResult LResult, RResult; 7430 7431 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7432 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7433 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7434 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7435 7436 if (LIsInt != RIsInt) { 7437 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7438 7439 if (LIsInt) { 7440 if (BinOpKind == BO_Add) { 7441 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7442 E = BinOp->getRHS(); 7443 goto tryAgain; 7444 } 7445 } else { 7446 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7447 E = BinOp->getLHS(); 7448 goto tryAgain; 7449 } 7450 } 7451 } 7452 7453 return SLCT_NotALiteral; 7454 } 7455 case Stmt::UnaryOperatorClass: { 7456 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7457 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7458 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7459 Expr::EvalResult IndexResult; 7460 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7461 Expr::SE_NoSideEffects, 7462 S.isConstantEvaluated())) { 7463 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7464 /*RHS is int*/ true); 7465 E = ASE->getBase(); 7466 goto tryAgain; 7467 } 7468 } 7469 7470 return SLCT_NotALiteral; 7471 } 7472 7473 default: 7474 return SLCT_NotALiteral; 7475 } 7476 } 7477 7478 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7479 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7480 .Case("scanf", FST_Scanf) 7481 .Cases("printf", "printf0", FST_Printf) 7482 .Cases("NSString", "CFString", FST_NSString) 7483 .Case("strftime", FST_Strftime) 7484 .Case("strfmon", FST_Strfmon) 7485 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7486 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7487 .Case("os_trace", FST_OSLog) 7488 .Case("os_log", FST_OSLog) 7489 .Default(FST_Unknown); 7490 } 7491 7492 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7493 /// functions) for correct use of format strings. 7494 /// Returns true if a format string has been fully checked. 7495 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7496 ArrayRef<const Expr *> Args, 7497 bool IsCXXMember, 7498 VariadicCallType CallType, 7499 SourceLocation Loc, SourceRange Range, 7500 llvm::SmallBitVector &CheckedVarArgs) { 7501 FormatStringInfo FSI; 7502 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7503 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7504 FSI.FirstDataArg, GetFormatStringType(Format), 7505 CallType, Loc, Range, CheckedVarArgs); 7506 return false; 7507 } 7508 7509 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7510 bool HasVAListArg, unsigned format_idx, 7511 unsigned firstDataArg, FormatStringType Type, 7512 VariadicCallType CallType, 7513 SourceLocation Loc, SourceRange Range, 7514 llvm::SmallBitVector &CheckedVarArgs) { 7515 // CHECK: printf/scanf-like function is called with no format string. 7516 if (format_idx >= Args.size()) { 7517 Diag(Loc, diag::warn_missing_format_string) << Range; 7518 return false; 7519 } 7520 7521 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7522 7523 // CHECK: format string is not a string literal. 7524 // 7525 // Dynamically generated format strings are difficult to 7526 // automatically vet at compile time. Requiring that format strings 7527 // are string literals: (1) permits the checking of format strings by 7528 // the compiler and thereby (2) can practically remove the source of 7529 // many format string exploits. 7530 7531 // Format string can be either ObjC string (e.g. @"%d") or 7532 // C string (e.g. "%d") 7533 // ObjC string uses the same format specifiers as C string, so we can use 7534 // the same format string checking logic for both ObjC and C strings. 7535 UncoveredArgHandler UncoveredArg; 7536 StringLiteralCheckType CT = 7537 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7538 format_idx, firstDataArg, Type, CallType, 7539 /*IsFunctionCall*/ true, CheckedVarArgs, 7540 UncoveredArg, 7541 /*no string offset*/ llvm::APSInt(64, false) = 0); 7542 7543 // Generate a diagnostic where an uncovered argument is detected. 7544 if (UncoveredArg.hasUncoveredArg()) { 7545 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7546 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7547 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7548 } 7549 7550 if (CT != SLCT_NotALiteral) 7551 // Literal format string found, check done! 7552 return CT == SLCT_CheckedLiteral; 7553 7554 // Strftime is particular as it always uses a single 'time' argument, 7555 // so it is safe to pass a non-literal string. 7556 if (Type == FST_Strftime) 7557 return false; 7558 7559 // Do not emit diag when the string param is a macro expansion and the 7560 // format is either NSString or CFString. This is a hack to prevent 7561 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7562 // which are usually used in place of NS and CF string literals. 7563 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7564 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7565 return false; 7566 7567 // If there are no arguments specified, warn with -Wformat-security, otherwise 7568 // warn only with -Wformat-nonliteral. 7569 if (Args.size() == firstDataArg) { 7570 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7571 << OrigFormatExpr->getSourceRange(); 7572 switch (Type) { 7573 default: 7574 break; 7575 case FST_Kprintf: 7576 case FST_FreeBSDKPrintf: 7577 case FST_Printf: 7578 Diag(FormatLoc, diag::note_format_security_fixit) 7579 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7580 break; 7581 case FST_NSString: 7582 Diag(FormatLoc, diag::note_format_security_fixit) 7583 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7584 break; 7585 } 7586 } else { 7587 Diag(FormatLoc, diag::warn_format_nonliteral) 7588 << OrigFormatExpr->getSourceRange(); 7589 } 7590 return false; 7591 } 7592 7593 namespace { 7594 7595 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7596 protected: 7597 Sema &S; 7598 const FormatStringLiteral *FExpr; 7599 const Expr *OrigFormatExpr; 7600 const Sema::FormatStringType FSType; 7601 const unsigned FirstDataArg; 7602 const unsigned NumDataArgs; 7603 const char *Beg; // Start of format string. 7604 const bool HasVAListArg; 7605 ArrayRef<const Expr *> Args; 7606 unsigned FormatIdx; 7607 llvm::SmallBitVector CoveredArgs; 7608 bool usesPositionalArgs = false; 7609 bool atFirstArg = true; 7610 bool inFunctionCall; 7611 Sema::VariadicCallType CallType; 7612 llvm::SmallBitVector &CheckedVarArgs; 7613 UncoveredArgHandler &UncoveredArg; 7614 7615 public: 7616 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7617 const Expr *origFormatExpr, 7618 const Sema::FormatStringType type, unsigned firstDataArg, 7619 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7620 ArrayRef<const Expr *> Args, unsigned formatIdx, 7621 bool inFunctionCall, Sema::VariadicCallType callType, 7622 llvm::SmallBitVector &CheckedVarArgs, 7623 UncoveredArgHandler &UncoveredArg) 7624 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7625 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7626 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7627 inFunctionCall(inFunctionCall), CallType(callType), 7628 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7629 CoveredArgs.resize(numDataArgs); 7630 CoveredArgs.reset(); 7631 } 7632 7633 void DoneProcessing(); 7634 7635 void HandleIncompleteSpecifier(const char *startSpecifier, 7636 unsigned specifierLen) override; 7637 7638 void HandleInvalidLengthModifier( 7639 const analyze_format_string::FormatSpecifier &FS, 7640 const analyze_format_string::ConversionSpecifier &CS, 7641 const char *startSpecifier, unsigned specifierLen, 7642 unsigned DiagID); 7643 7644 void HandleNonStandardLengthModifier( 7645 const analyze_format_string::FormatSpecifier &FS, 7646 const char *startSpecifier, unsigned specifierLen); 7647 7648 void HandleNonStandardConversionSpecifier( 7649 const analyze_format_string::ConversionSpecifier &CS, 7650 const char *startSpecifier, unsigned specifierLen); 7651 7652 void HandlePosition(const char *startPos, unsigned posLen) override; 7653 7654 void HandleInvalidPosition(const char *startSpecifier, 7655 unsigned specifierLen, 7656 analyze_format_string::PositionContext p) override; 7657 7658 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7659 7660 void HandleNullChar(const char *nullCharacter) override; 7661 7662 template <typename Range> 7663 static void 7664 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7665 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7666 bool IsStringLocation, Range StringRange, 7667 ArrayRef<FixItHint> Fixit = None); 7668 7669 protected: 7670 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7671 const char *startSpec, 7672 unsigned specifierLen, 7673 const char *csStart, unsigned csLen); 7674 7675 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7676 const char *startSpec, 7677 unsigned specifierLen); 7678 7679 SourceRange getFormatStringRange(); 7680 CharSourceRange getSpecifierRange(const char *startSpecifier, 7681 unsigned specifierLen); 7682 SourceLocation getLocationOfByte(const char *x); 7683 7684 const Expr *getDataArg(unsigned i) const; 7685 7686 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7687 const analyze_format_string::ConversionSpecifier &CS, 7688 const char *startSpecifier, unsigned specifierLen, 7689 unsigned argIndex); 7690 7691 template <typename Range> 7692 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7693 bool IsStringLocation, Range StringRange, 7694 ArrayRef<FixItHint> Fixit = None); 7695 }; 7696 7697 } // namespace 7698 7699 SourceRange CheckFormatHandler::getFormatStringRange() { 7700 return OrigFormatExpr->getSourceRange(); 7701 } 7702 7703 CharSourceRange CheckFormatHandler:: 7704 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7705 SourceLocation Start = getLocationOfByte(startSpecifier); 7706 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7707 7708 // Advance the end SourceLocation by one due to half-open ranges. 7709 End = End.getLocWithOffset(1); 7710 7711 return CharSourceRange::getCharRange(Start, End); 7712 } 7713 7714 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7715 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7716 S.getLangOpts(), S.Context.getTargetInfo()); 7717 } 7718 7719 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7720 unsigned specifierLen){ 7721 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7722 getLocationOfByte(startSpecifier), 7723 /*IsStringLocation*/true, 7724 getSpecifierRange(startSpecifier, specifierLen)); 7725 } 7726 7727 void CheckFormatHandler::HandleInvalidLengthModifier( 7728 const analyze_format_string::FormatSpecifier &FS, 7729 const analyze_format_string::ConversionSpecifier &CS, 7730 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7731 using namespace analyze_format_string; 7732 7733 const LengthModifier &LM = FS.getLengthModifier(); 7734 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7735 7736 // See if we know how to fix this length modifier. 7737 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7738 if (FixedLM) { 7739 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7740 getLocationOfByte(LM.getStart()), 7741 /*IsStringLocation*/true, 7742 getSpecifierRange(startSpecifier, specifierLen)); 7743 7744 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7745 << FixedLM->toString() 7746 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7747 7748 } else { 7749 FixItHint Hint; 7750 if (DiagID == diag::warn_format_nonsensical_length) 7751 Hint = FixItHint::CreateRemoval(LMRange); 7752 7753 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7754 getLocationOfByte(LM.getStart()), 7755 /*IsStringLocation*/true, 7756 getSpecifierRange(startSpecifier, specifierLen), 7757 Hint); 7758 } 7759 } 7760 7761 void CheckFormatHandler::HandleNonStandardLengthModifier( 7762 const analyze_format_string::FormatSpecifier &FS, 7763 const char *startSpecifier, unsigned specifierLen) { 7764 using namespace analyze_format_string; 7765 7766 const LengthModifier &LM = FS.getLengthModifier(); 7767 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7768 7769 // See if we know how to fix this length modifier. 7770 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7771 if (FixedLM) { 7772 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7773 << LM.toString() << 0, 7774 getLocationOfByte(LM.getStart()), 7775 /*IsStringLocation*/true, 7776 getSpecifierRange(startSpecifier, specifierLen)); 7777 7778 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7779 << FixedLM->toString() 7780 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7781 7782 } else { 7783 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7784 << LM.toString() << 0, 7785 getLocationOfByte(LM.getStart()), 7786 /*IsStringLocation*/true, 7787 getSpecifierRange(startSpecifier, specifierLen)); 7788 } 7789 } 7790 7791 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7792 const analyze_format_string::ConversionSpecifier &CS, 7793 const char *startSpecifier, unsigned specifierLen) { 7794 using namespace analyze_format_string; 7795 7796 // See if we know how to fix this conversion specifier. 7797 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7798 if (FixedCS) { 7799 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7800 << CS.toString() << /*conversion specifier*/1, 7801 getLocationOfByte(CS.getStart()), 7802 /*IsStringLocation*/true, 7803 getSpecifierRange(startSpecifier, specifierLen)); 7804 7805 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7806 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7807 << FixedCS->toString() 7808 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7809 } else { 7810 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7811 << CS.toString() << /*conversion specifier*/1, 7812 getLocationOfByte(CS.getStart()), 7813 /*IsStringLocation*/true, 7814 getSpecifierRange(startSpecifier, specifierLen)); 7815 } 7816 } 7817 7818 void CheckFormatHandler::HandlePosition(const char *startPos, 7819 unsigned posLen) { 7820 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7821 getLocationOfByte(startPos), 7822 /*IsStringLocation*/true, 7823 getSpecifierRange(startPos, posLen)); 7824 } 7825 7826 void 7827 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7828 analyze_format_string::PositionContext p) { 7829 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7830 << (unsigned) p, 7831 getLocationOfByte(startPos), /*IsStringLocation*/true, 7832 getSpecifierRange(startPos, posLen)); 7833 } 7834 7835 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7836 unsigned posLen) { 7837 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7838 getLocationOfByte(startPos), 7839 /*IsStringLocation*/true, 7840 getSpecifierRange(startPos, posLen)); 7841 } 7842 7843 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7844 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7845 // The presence of a null character is likely an error. 7846 EmitFormatDiagnostic( 7847 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7848 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7849 getFormatStringRange()); 7850 } 7851 } 7852 7853 // Note that this may return NULL if there was an error parsing or building 7854 // one of the argument expressions. 7855 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7856 return Args[FirstDataArg + i]; 7857 } 7858 7859 void CheckFormatHandler::DoneProcessing() { 7860 // Does the number of data arguments exceed the number of 7861 // format conversions in the format string? 7862 if (!HasVAListArg) { 7863 // Find any arguments that weren't covered. 7864 CoveredArgs.flip(); 7865 signed notCoveredArg = CoveredArgs.find_first(); 7866 if (notCoveredArg >= 0) { 7867 assert((unsigned)notCoveredArg < NumDataArgs); 7868 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7869 } else { 7870 UncoveredArg.setAllCovered(); 7871 } 7872 } 7873 } 7874 7875 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7876 const Expr *ArgExpr) { 7877 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7878 "Invalid state"); 7879 7880 if (!ArgExpr) 7881 return; 7882 7883 SourceLocation Loc = ArgExpr->getBeginLoc(); 7884 7885 if (S.getSourceManager().isInSystemMacro(Loc)) 7886 return; 7887 7888 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7889 for (auto E : DiagnosticExprs) 7890 PDiag << E->getSourceRange(); 7891 7892 CheckFormatHandler::EmitFormatDiagnostic( 7893 S, IsFunctionCall, DiagnosticExprs[0], 7894 PDiag, Loc, /*IsStringLocation*/false, 7895 DiagnosticExprs[0]->getSourceRange()); 7896 } 7897 7898 bool 7899 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7900 SourceLocation Loc, 7901 const char *startSpec, 7902 unsigned specifierLen, 7903 const char *csStart, 7904 unsigned csLen) { 7905 bool keepGoing = true; 7906 if (argIndex < NumDataArgs) { 7907 // Consider the argument coverered, even though the specifier doesn't 7908 // make sense. 7909 CoveredArgs.set(argIndex); 7910 } 7911 else { 7912 // If argIndex exceeds the number of data arguments we 7913 // don't issue a warning because that is just a cascade of warnings (and 7914 // they may have intended '%%' anyway). We don't want to continue processing 7915 // the format string after this point, however, as we will like just get 7916 // gibberish when trying to match arguments. 7917 keepGoing = false; 7918 } 7919 7920 StringRef Specifier(csStart, csLen); 7921 7922 // If the specifier in non-printable, it could be the first byte of a UTF-8 7923 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7924 // hex value. 7925 std::string CodePointStr; 7926 if (!llvm::sys::locale::isPrint(*csStart)) { 7927 llvm::UTF32 CodePoint; 7928 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7929 const llvm::UTF8 *E = 7930 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7931 llvm::ConversionResult Result = 7932 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7933 7934 if (Result != llvm::conversionOK) { 7935 unsigned char FirstChar = *csStart; 7936 CodePoint = (llvm::UTF32)FirstChar; 7937 } 7938 7939 llvm::raw_string_ostream OS(CodePointStr); 7940 if (CodePoint < 256) 7941 OS << "\\x" << llvm::format("%02x", CodePoint); 7942 else if (CodePoint <= 0xFFFF) 7943 OS << "\\u" << llvm::format("%04x", CodePoint); 7944 else 7945 OS << "\\U" << llvm::format("%08x", CodePoint); 7946 OS.flush(); 7947 Specifier = CodePointStr; 7948 } 7949 7950 EmitFormatDiagnostic( 7951 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7952 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7953 7954 return keepGoing; 7955 } 7956 7957 void 7958 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7959 const char *startSpec, 7960 unsigned specifierLen) { 7961 EmitFormatDiagnostic( 7962 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7963 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7964 } 7965 7966 bool 7967 CheckFormatHandler::CheckNumArgs( 7968 const analyze_format_string::FormatSpecifier &FS, 7969 const analyze_format_string::ConversionSpecifier &CS, 7970 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7971 7972 if (argIndex >= NumDataArgs) { 7973 PartialDiagnostic PDiag = FS.usesPositionalArg() 7974 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7975 << (argIndex+1) << NumDataArgs) 7976 : S.PDiag(diag::warn_printf_insufficient_data_args); 7977 EmitFormatDiagnostic( 7978 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7979 getSpecifierRange(startSpecifier, specifierLen)); 7980 7981 // Since more arguments than conversion tokens are given, by extension 7982 // all arguments are covered, so mark this as so. 7983 UncoveredArg.setAllCovered(); 7984 return false; 7985 } 7986 return true; 7987 } 7988 7989 template<typename Range> 7990 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7991 SourceLocation Loc, 7992 bool IsStringLocation, 7993 Range StringRange, 7994 ArrayRef<FixItHint> FixIt) { 7995 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7996 Loc, IsStringLocation, StringRange, FixIt); 7997 } 7998 7999 /// If the format string is not within the function call, emit a note 8000 /// so that the function call and string are in diagnostic messages. 8001 /// 8002 /// \param InFunctionCall if true, the format string is within the function 8003 /// call and only one diagnostic message will be produced. Otherwise, an 8004 /// extra note will be emitted pointing to location of the format string. 8005 /// 8006 /// \param ArgumentExpr the expression that is passed as the format string 8007 /// argument in the function call. Used for getting locations when two 8008 /// diagnostics are emitted. 8009 /// 8010 /// \param PDiag the callee should already have provided any strings for the 8011 /// diagnostic message. This function only adds locations and fixits 8012 /// to diagnostics. 8013 /// 8014 /// \param Loc primary location for diagnostic. If two diagnostics are 8015 /// required, one will be at Loc and a new SourceLocation will be created for 8016 /// the other one. 8017 /// 8018 /// \param IsStringLocation if true, Loc points to the format string should be 8019 /// used for the note. Otherwise, Loc points to the argument list and will 8020 /// be used with PDiag. 8021 /// 8022 /// \param StringRange some or all of the string to highlight. This is 8023 /// templated so it can accept either a CharSourceRange or a SourceRange. 8024 /// 8025 /// \param FixIt optional fix it hint for the format string. 8026 template <typename Range> 8027 void CheckFormatHandler::EmitFormatDiagnostic( 8028 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8029 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8030 Range StringRange, ArrayRef<FixItHint> FixIt) { 8031 if (InFunctionCall) { 8032 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8033 D << StringRange; 8034 D << FixIt; 8035 } else { 8036 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8037 << ArgumentExpr->getSourceRange(); 8038 8039 const Sema::SemaDiagnosticBuilder &Note = 8040 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8041 diag::note_format_string_defined); 8042 8043 Note << StringRange; 8044 Note << FixIt; 8045 } 8046 } 8047 8048 //===--- CHECK: Printf format string checking ------------------------------===// 8049 8050 namespace { 8051 8052 class CheckPrintfHandler : public CheckFormatHandler { 8053 public: 8054 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8055 const Expr *origFormatExpr, 8056 const Sema::FormatStringType type, unsigned firstDataArg, 8057 unsigned numDataArgs, bool isObjC, const char *beg, 8058 bool hasVAListArg, ArrayRef<const Expr *> Args, 8059 unsigned formatIdx, bool inFunctionCall, 8060 Sema::VariadicCallType CallType, 8061 llvm::SmallBitVector &CheckedVarArgs, 8062 UncoveredArgHandler &UncoveredArg) 8063 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8064 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8065 inFunctionCall, CallType, CheckedVarArgs, 8066 UncoveredArg) {} 8067 8068 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8069 8070 /// Returns true if '%@' specifiers are allowed in the format string. 8071 bool allowsObjCArg() const { 8072 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8073 FSType == Sema::FST_OSTrace; 8074 } 8075 8076 bool HandleInvalidPrintfConversionSpecifier( 8077 const analyze_printf::PrintfSpecifier &FS, 8078 const char *startSpecifier, 8079 unsigned specifierLen) override; 8080 8081 void handleInvalidMaskType(StringRef MaskType) override; 8082 8083 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8084 const char *startSpecifier, 8085 unsigned specifierLen) override; 8086 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8087 const char *StartSpecifier, 8088 unsigned SpecifierLen, 8089 const Expr *E); 8090 8091 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8092 const char *startSpecifier, unsigned specifierLen); 8093 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8094 const analyze_printf::OptionalAmount &Amt, 8095 unsigned type, 8096 const char *startSpecifier, unsigned specifierLen); 8097 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8098 const analyze_printf::OptionalFlag &flag, 8099 const char *startSpecifier, unsigned specifierLen); 8100 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8101 const analyze_printf::OptionalFlag &ignoredFlag, 8102 const analyze_printf::OptionalFlag &flag, 8103 const char *startSpecifier, unsigned specifierLen); 8104 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8105 const Expr *E); 8106 8107 void HandleEmptyObjCModifierFlag(const char *startFlag, 8108 unsigned flagLen) override; 8109 8110 void HandleInvalidObjCModifierFlag(const char *startFlag, 8111 unsigned flagLen) override; 8112 8113 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8114 const char *flagsEnd, 8115 const char *conversionPosition) 8116 override; 8117 }; 8118 8119 } // namespace 8120 8121 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8122 const analyze_printf::PrintfSpecifier &FS, 8123 const char *startSpecifier, 8124 unsigned specifierLen) { 8125 const analyze_printf::PrintfConversionSpecifier &CS = 8126 FS.getConversionSpecifier(); 8127 8128 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8129 getLocationOfByte(CS.getStart()), 8130 startSpecifier, specifierLen, 8131 CS.getStart(), CS.getLength()); 8132 } 8133 8134 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8135 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8136 } 8137 8138 bool CheckPrintfHandler::HandleAmount( 8139 const analyze_format_string::OptionalAmount &Amt, 8140 unsigned k, const char *startSpecifier, 8141 unsigned specifierLen) { 8142 if (Amt.hasDataArgument()) { 8143 if (!HasVAListArg) { 8144 unsigned argIndex = Amt.getArgIndex(); 8145 if (argIndex >= NumDataArgs) { 8146 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8147 << k, 8148 getLocationOfByte(Amt.getStart()), 8149 /*IsStringLocation*/true, 8150 getSpecifierRange(startSpecifier, specifierLen)); 8151 // Don't do any more checking. We will just emit 8152 // spurious errors. 8153 return false; 8154 } 8155 8156 // Type check the data argument. It should be an 'int'. 8157 // Although not in conformance with C99, we also allow the argument to be 8158 // an 'unsigned int' as that is a reasonably safe case. GCC also 8159 // doesn't emit a warning for that case. 8160 CoveredArgs.set(argIndex); 8161 const Expr *Arg = getDataArg(argIndex); 8162 if (!Arg) 8163 return false; 8164 8165 QualType T = Arg->getType(); 8166 8167 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8168 assert(AT.isValid()); 8169 8170 if (!AT.matchesType(S.Context, T)) { 8171 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8172 << k << AT.getRepresentativeTypeName(S.Context) 8173 << T << Arg->getSourceRange(), 8174 getLocationOfByte(Amt.getStart()), 8175 /*IsStringLocation*/true, 8176 getSpecifierRange(startSpecifier, specifierLen)); 8177 // Don't do any more checking. We will just emit 8178 // spurious errors. 8179 return false; 8180 } 8181 } 8182 } 8183 return true; 8184 } 8185 8186 void CheckPrintfHandler::HandleInvalidAmount( 8187 const analyze_printf::PrintfSpecifier &FS, 8188 const analyze_printf::OptionalAmount &Amt, 8189 unsigned type, 8190 const char *startSpecifier, 8191 unsigned specifierLen) { 8192 const analyze_printf::PrintfConversionSpecifier &CS = 8193 FS.getConversionSpecifier(); 8194 8195 FixItHint fixit = 8196 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8197 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8198 Amt.getConstantLength())) 8199 : FixItHint(); 8200 8201 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8202 << type << CS.toString(), 8203 getLocationOfByte(Amt.getStart()), 8204 /*IsStringLocation*/true, 8205 getSpecifierRange(startSpecifier, specifierLen), 8206 fixit); 8207 } 8208 8209 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8210 const analyze_printf::OptionalFlag &flag, 8211 const char *startSpecifier, 8212 unsigned specifierLen) { 8213 // Warn about pointless flag with a fixit removal. 8214 const analyze_printf::PrintfConversionSpecifier &CS = 8215 FS.getConversionSpecifier(); 8216 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8217 << flag.toString() << CS.toString(), 8218 getLocationOfByte(flag.getPosition()), 8219 /*IsStringLocation*/true, 8220 getSpecifierRange(startSpecifier, specifierLen), 8221 FixItHint::CreateRemoval( 8222 getSpecifierRange(flag.getPosition(), 1))); 8223 } 8224 8225 void CheckPrintfHandler::HandleIgnoredFlag( 8226 const analyze_printf::PrintfSpecifier &FS, 8227 const analyze_printf::OptionalFlag &ignoredFlag, 8228 const analyze_printf::OptionalFlag &flag, 8229 const char *startSpecifier, 8230 unsigned specifierLen) { 8231 // Warn about ignored flag with a fixit removal. 8232 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8233 << ignoredFlag.toString() << flag.toString(), 8234 getLocationOfByte(ignoredFlag.getPosition()), 8235 /*IsStringLocation*/true, 8236 getSpecifierRange(startSpecifier, specifierLen), 8237 FixItHint::CreateRemoval( 8238 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8239 } 8240 8241 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8242 unsigned flagLen) { 8243 // Warn about an empty flag. 8244 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8245 getLocationOfByte(startFlag), 8246 /*IsStringLocation*/true, 8247 getSpecifierRange(startFlag, flagLen)); 8248 } 8249 8250 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8251 unsigned flagLen) { 8252 // Warn about an invalid flag. 8253 auto Range = getSpecifierRange(startFlag, flagLen); 8254 StringRef flag(startFlag, flagLen); 8255 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8256 getLocationOfByte(startFlag), 8257 /*IsStringLocation*/true, 8258 Range, FixItHint::CreateRemoval(Range)); 8259 } 8260 8261 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8262 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8263 // Warn about using '[...]' without a '@' conversion. 8264 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8265 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8266 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8267 getLocationOfByte(conversionPosition), 8268 /*IsStringLocation*/true, 8269 Range, FixItHint::CreateRemoval(Range)); 8270 } 8271 8272 // Determines if the specified is a C++ class or struct containing 8273 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8274 // "c_str()"). 8275 template<typename MemberKind> 8276 static llvm::SmallPtrSet<MemberKind*, 1> 8277 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8278 const RecordType *RT = Ty->getAs<RecordType>(); 8279 llvm::SmallPtrSet<MemberKind*, 1> Results; 8280 8281 if (!RT) 8282 return Results; 8283 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8284 if (!RD || !RD->getDefinition()) 8285 return Results; 8286 8287 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8288 Sema::LookupMemberName); 8289 R.suppressDiagnostics(); 8290 8291 // We just need to include all members of the right kind turned up by the 8292 // filter, at this point. 8293 if (S.LookupQualifiedName(R, RT->getDecl())) 8294 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8295 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8296 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8297 Results.insert(FK); 8298 } 8299 return Results; 8300 } 8301 8302 /// Check if we could call '.c_str()' on an object. 8303 /// 8304 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8305 /// allow the call, or if it would be ambiguous). 8306 bool Sema::hasCStrMethod(const Expr *E) { 8307 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8308 8309 MethodSet Results = 8310 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8311 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8312 MI != ME; ++MI) 8313 if ((*MI)->getMinRequiredArguments() == 0) 8314 return true; 8315 return false; 8316 } 8317 8318 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8319 // better diagnostic if so. AT is assumed to be valid. 8320 // Returns true when a c_str() conversion method is found. 8321 bool CheckPrintfHandler::checkForCStrMembers( 8322 const analyze_printf::ArgType &AT, const Expr *E) { 8323 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8324 8325 MethodSet Results = 8326 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8327 8328 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8329 MI != ME; ++MI) { 8330 const CXXMethodDecl *Method = *MI; 8331 if (Method->getMinRequiredArguments() == 0 && 8332 AT.matchesType(S.Context, Method->getReturnType())) { 8333 // FIXME: Suggest parens if the expression needs them. 8334 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8335 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8336 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8337 return true; 8338 } 8339 } 8340 8341 return false; 8342 } 8343 8344 bool 8345 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8346 &FS, 8347 const char *startSpecifier, 8348 unsigned specifierLen) { 8349 using namespace analyze_format_string; 8350 using namespace analyze_printf; 8351 8352 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8353 8354 if (FS.consumesDataArgument()) { 8355 if (atFirstArg) { 8356 atFirstArg = false; 8357 usesPositionalArgs = FS.usesPositionalArg(); 8358 } 8359 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8360 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8361 startSpecifier, specifierLen); 8362 return false; 8363 } 8364 } 8365 8366 // First check if the field width, precision, and conversion specifier 8367 // have matching data arguments. 8368 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8369 startSpecifier, specifierLen)) { 8370 return false; 8371 } 8372 8373 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8374 startSpecifier, specifierLen)) { 8375 return false; 8376 } 8377 8378 if (!CS.consumesDataArgument()) { 8379 // FIXME: Technically specifying a precision or field width here 8380 // makes no sense. Worth issuing a warning at some point. 8381 return true; 8382 } 8383 8384 // Consume the argument. 8385 unsigned argIndex = FS.getArgIndex(); 8386 if (argIndex < NumDataArgs) { 8387 // The check to see if the argIndex is valid will come later. 8388 // We set the bit here because we may exit early from this 8389 // function if we encounter some other error. 8390 CoveredArgs.set(argIndex); 8391 } 8392 8393 // FreeBSD kernel extensions. 8394 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8395 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8396 // We need at least two arguments. 8397 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8398 return false; 8399 8400 // Claim the second argument. 8401 CoveredArgs.set(argIndex + 1); 8402 8403 // Type check the first argument (int for %b, pointer for %D) 8404 const Expr *Ex = getDataArg(argIndex); 8405 const analyze_printf::ArgType &AT = 8406 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8407 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8408 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8409 EmitFormatDiagnostic( 8410 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8411 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8412 << false << Ex->getSourceRange(), 8413 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8414 getSpecifierRange(startSpecifier, specifierLen)); 8415 8416 // Type check the second argument (char * for both %b and %D) 8417 Ex = getDataArg(argIndex + 1); 8418 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8419 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8420 EmitFormatDiagnostic( 8421 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8422 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8423 << false << Ex->getSourceRange(), 8424 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8425 getSpecifierRange(startSpecifier, specifierLen)); 8426 8427 return true; 8428 } 8429 8430 // Check for using an Objective-C specific conversion specifier 8431 // in a non-ObjC literal. 8432 if (!allowsObjCArg() && CS.isObjCArg()) { 8433 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8434 specifierLen); 8435 } 8436 8437 // %P can only be used with os_log. 8438 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8439 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8440 specifierLen); 8441 } 8442 8443 // %n is not allowed with os_log. 8444 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8445 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8446 getLocationOfByte(CS.getStart()), 8447 /*IsStringLocation*/ false, 8448 getSpecifierRange(startSpecifier, specifierLen)); 8449 8450 return true; 8451 } 8452 8453 // Only scalars are allowed for os_trace. 8454 if (FSType == Sema::FST_OSTrace && 8455 (CS.getKind() == ConversionSpecifier::PArg || 8456 CS.getKind() == ConversionSpecifier::sArg || 8457 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8458 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8459 specifierLen); 8460 } 8461 8462 // Check for use of public/private annotation outside of os_log(). 8463 if (FSType != Sema::FST_OSLog) { 8464 if (FS.isPublic().isSet()) { 8465 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8466 << "public", 8467 getLocationOfByte(FS.isPublic().getPosition()), 8468 /*IsStringLocation*/ false, 8469 getSpecifierRange(startSpecifier, specifierLen)); 8470 } 8471 if (FS.isPrivate().isSet()) { 8472 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8473 << "private", 8474 getLocationOfByte(FS.isPrivate().getPosition()), 8475 /*IsStringLocation*/ false, 8476 getSpecifierRange(startSpecifier, specifierLen)); 8477 } 8478 } 8479 8480 // Check for invalid use of field width 8481 if (!FS.hasValidFieldWidth()) { 8482 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8483 startSpecifier, specifierLen); 8484 } 8485 8486 // Check for invalid use of precision 8487 if (!FS.hasValidPrecision()) { 8488 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8489 startSpecifier, specifierLen); 8490 } 8491 8492 // Precision is mandatory for %P specifier. 8493 if (CS.getKind() == ConversionSpecifier::PArg && 8494 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8495 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8496 getLocationOfByte(startSpecifier), 8497 /*IsStringLocation*/ false, 8498 getSpecifierRange(startSpecifier, specifierLen)); 8499 } 8500 8501 // Check each flag does not conflict with any other component. 8502 if (!FS.hasValidThousandsGroupingPrefix()) 8503 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8504 if (!FS.hasValidLeadingZeros()) 8505 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8506 if (!FS.hasValidPlusPrefix()) 8507 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8508 if (!FS.hasValidSpacePrefix()) 8509 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8510 if (!FS.hasValidAlternativeForm()) 8511 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8512 if (!FS.hasValidLeftJustified()) 8513 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8514 8515 // Check that flags are not ignored by another flag 8516 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8517 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8518 startSpecifier, specifierLen); 8519 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8520 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8521 startSpecifier, specifierLen); 8522 8523 // Check the length modifier is valid with the given conversion specifier. 8524 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8525 S.getLangOpts())) 8526 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8527 diag::warn_format_nonsensical_length); 8528 else if (!FS.hasStandardLengthModifier()) 8529 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8530 else if (!FS.hasStandardLengthConversionCombination()) 8531 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8532 diag::warn_format_non_standard_conversion_spec); 8533 8534 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8535 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8536 8537 // The remaining checks depend on the data arguments. 8538 if (HasVAListArg) 8539 return true; 8540 8541 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8542 return false; 8543 8544 const Expr *Arg = getDataArg(argIndex); 8545 if (!Arg) 8546 return true; 8547 8548 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8549 } 8550 8551 static bool requiresParensToAddCast(const Expr *E) { 8552 // FIXME: We should have a general way to reason about operator 8553 // precedence and whether parens are actually needed here. 8554 // Take care of a few common cases where they aren't. 8555 const Expr *Inside = E->IgnoreImpCasts(); 8556 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8557 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8558 8559 switch (Inside->getStmtClass()) { 8560 case Stmt::ArraySubscriptExprClass: 8561 case Stmt::CallExprClass: 8562 case Stmt::CharacterLiteralClass: 8563 case Stmt::CXXBoolLiteralExprClass: 8564 case Stmt::DeclRefExprClass: 8565 case Stmt::FloatingLiteralClass: 8566 case Stmt::IntegerLiteralClass: 8567 case Stmt::MemberExprClass: 8568 case Stmt::ObjCArrayLiteralClass: 8569 case Stmt::ObjCBoolLiteralExprClass: 8570 case Stmt::ObjCBoxedExprClass: 8571 case Stmt::ObjCDictionaryLiteralClass: 8572 case Stmt::ObjCEncodeExprClass: 8573 case Stmt::ObjCIvarRefExprClass: 8574 case Stmt::ObjCMessageExprClass: 8575 case Stmt::ObjCPropertyRefExprClass: 8576 case Stmt::ObjCStringLiteralClass: 8577 case Stmt::ObjCSubscriptRefExprClass: 8578 case Stmt::ParenExprClass: 8579 case Stmt::StringLiteralClass: 8580 case Stmt::UnaryOperatorClass: 8581 return false; 8582 default: 8583 return true; 8584 } 8585 } 8586 8587 static std::pair<QualType, StringRef> 8588 shouldNotPrintDirectly(const ASTContext &Context, 8589 QualType IntendedTy, 8590 const Expr *E) { 8591 // Use a 'while' to peel off layers of typedefs. 8592 QualType TyTy = IntendedTy; 8593 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8594 StringRef Name = UserTy->getDecl()->getName(); 8595 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8596 .Case("CFIndex", Context.getNSIntegerType()) 8597 .Case("NSInteger", Context.getNSIntegerType()) 8598 .Case("NSUInteger", Context.getNSUIntegerType()) 8599 .Case("SInt32", Context.IntTy) 8600 .Case("UInt32", Context.UnsignedIntTy) 8601 .Default(QualType()); 8602 8603 if (!CastTy.isNull()) 8604 return std::make_pair(CastTy, Name); 8605 8606 TyTy = UserTy->desugar(); 8607 } 8608 8609 // Strip parens if necessary. 8610 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8611 return shouldNotPrintDirectly(Context, 8612 PE->getSubExpr()->getType(), 8613 PE->getSubExpr()); 8614 8615 // If this is a conditional expression, then its result type is constructed 8616 // via usual arithmetic conversions and thus there might be no necessary 8617 // typedef sugar there. Recurse to operands to check for NSInteger & 8618 // Co. usage condition. 8619 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8620 QualType TrueTy, FalseTy; 8621 StringRef TrueName, FalseName; 8622 8623 std::tie(TrueTy, TrueName) = 8624 shouldNotPrintDirectly(Context, 8625 CO->getTrueExpr()->getType(), 8626 CO->getTrueExpr()); 8627 std::tie(FalseTy, FalseName) = 8628 shouldNotPrintDirectly(Context, 8629 CO->getFalseExpr()->getType(), 8630 CO->getFalseExpr()); 8631 8632 if (TrueTy == FalseTy) 8633 return std::make_pair(TrueTy, TrueName); 8634 else if (TrueTy.isNull()) 8635 return std::make_pair(FalseTy, FalseName); 8636 else if (FalseTy.isNull()) 8637 return std::make_pair(TrueTy, TrueName); 8638 } 8639 8640 return std::make_pair(QualType(), StringRef()); 8641 } 8642 8643 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8644 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8645 /// type do not count. 8646 static bool 8647 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8648 QualType From = ICE->getSubExpr()->getType(); 8649 QualType To = ICE->getType(); 8650 // It's an integer promotion if the destination type is the promoted 8651 // source type. 8652 if (ICE->getCastKind() == CK_IntegralCast && 8653 From->isPromotableIntegerType() && 8654 S.Context.getPromotedIntegerType(From) == To) 8655 return true; 8656 // Look through vector types, since we do default argument promotion for 8657 // those in OpenCL. 8658 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8659 From = VecTy->getElementType(); 8660 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8661 To = VecTy->getElementType(); 8662 // It's a floating promotion if the source type is a lower rank. 8663 return ICE->getCastKind() == CK_FloatingCast && 8664 S.Context.getFloatingTypeOrder(From, To) < 0; 8665 } 8666 8667 bool 8668 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8669 const char *StartSpecifier, 8670 unsigned SpecifierLen, 8671 const Expr *E) { 8672 using namespace analyze_format_string; 8673 using namespace analyze_printf; 8674 8675 // Now type check the data expression that matches the 8676 // format specifier. 8677 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8678 if (!AT.isValid()) 8679 return true; 8680 8681 QualType ExprTy = E->getType(); 8682 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8683 ExprTy = TET->getUnderlyingExpr()->getType(); 8684 } 8685 8686 // Diagnose attempts to print a boolean value as a character. Unlike other 8687 // -Wformat diagnostics, this is fine from a type perspective, but it still 8688 // doesn't make sense. 8689 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8690 E->isKnownToHaveBooleanValue()) { 8691 const CharSourceRange &CSR = 8692 getSpecifierRange(StartSpecifier, SpecifierLen); 8693 SmallString<4> FSString; 8694 llvm::raw_svector_ostream os(FSString); 8695 FS.toString(os); 8696 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8697 << FSString, 8698 E->getExprLoc(), false, CSR); 8699 return true; 8700 } 8701 8702 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8703 if (Match == analyze_printf::ArgType::Match) 8704 return true; 8705 8706 // Look through argument promotions for our error message's reported type. 8707 // This includes the integral and floating promotions, but excludes array 8708 // and function pointer decay (seeing that an argument intended to be a 8709 // string has type 'char [6]' is probably more confusing than 'char *') and 8710 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8711 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8712 if (isArithmeticArgumentPromotion(S, ICE)) { 8713 E = ICE->getSubExpr(); 8714 ExprTy = E->getType(); 8715 8716 // Check if we didn't match because of an implicit cast from a 'char' 8717 // or 'short' to an 'int'. This is done because printf is a varargs 8718 // function. 8719 if (ICE->getType() == S.Context.IntTy || 8720 ICE->getType() == S.Context.UnsignedIntTy) { 8721 // All further checking is done on the subexpression 8722 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8723 AT.matchesType(S.Context, ExprTy); 8724 if (ImplicitMatch == analyze_printf::ArgType::Match) 8725 return true; 8726 if (ImplicitMatch == ArgType::NoMatchPedantic || 8727 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8728 Match = ImplicitMatch; 8729 } 8730 } 8731 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8732 // Special case for 'a', which has type 'int' in C. 8733 // Note, however, that we do /not/ want to treat multibyte constants like 8734 // 'MooV' as characters! This form is deprecated but still exists. In 8735 // addition, don't treat expressions as of type 'char' if one byte length 8736 // modifier is provided. 8737 if (ExprTy == S.Context.IntTy && 8738 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 8739 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8740 ExprTy = S.Context.CharTy; 8741 } 8742 8743 // Look through enums to their underlying type. 8744 bool IsEnum = false; 8745 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8746 ExprTy = EnumTy->getDecl()->getIntegerType(); 8747 IsEnum = true; 8748 } 8749 8750 // %C in an Objective-C context prints a unichar, not a wchar_t. 8751 // If the argument is an integer of some kind, believe the %C and suggest 8752 // a cast instead of changing the conversion specifier. 8753 QualType IntendedTy = ExprTy; 8754 if (isObjCContext() && 8755 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8756 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8757 !ExprTy->isCharType()) { 8758 // 'unichar' is defined as a typedef of unsigned short, but we should 8759 // prefer using the typedef if it is visible. 8760 IntendedTy = S.Context.UnsignedShortTy; 8761 8762 // While we are here, check if the value is an IntegerLiteral that happens 8763 // to be within the valid range. 8764 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8765 const llvm::APInt &V = IL->getValue(); 8766 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8767 return true; 8768 } 8769 8770 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8771 Sema::LookupOrdinaryName); 8772 if (S.LookupName(Result, S.getCurScope())) { 8773 NamedDecl *ND = Result.getFoundDecl(); 8774 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8775 if (TD->getUnderlyingType() == IntendedTy) 8776 IntendedTy = S.Context.getTypedefType(TD); 8777 } 8778 } 8779 } 8780 8781 // Special-case some of Darwin's platform-independence types by suggesting 8782 // casts to primitive types that are known to be large enough. 8783 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8784 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8785 QualType CastTy; 8786 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8787 if (!CastTy.isNull()) { 8788 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8789 // (long in ASTContext). Only complain to pedants. 8790 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8791 (AT.isSizeT() || AT.isPtrdiffT()) && 8792 AT.matchesType(S.Context, CastTy)) 8793 Match = ArgType::NoMatchPedantic; 8794 IntendedTy = CastTy; 8795 ShouldNotPrintDirectly = true; 8796 } 8797 } 8798 8799 // We may be able to offer a FixItHint if it is a supported type. 8800 PrintfSpecifier fixedFS = FS; 8801 bool Success = 8802 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8803 8804 if (Success) { 8805 // Get the fix string from the fixed format specifier 8806 SmallString<16> buf; 8807 llvm::raw_svector_ostream os(buf); 8808 fixedFS.toString(os); 8809 8810 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8811 8812 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8813 unsigned Diag; 8814 switch (Match) { 8815 case ArgType::Match: llvm_unreachable("expected non-matching"); 8816 case ArgType::NoMatchPedantic: 8817 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8818 break; 8819 case ArgType::NoMatchTypeConfusion: 8820 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8821 break; 8822 case ArgType::NoMatch: 8823 Diag = diag::warn_format_conversion_argument_type_mismatch; 8824 break; 8825 } 8826 8827 // In this case, the specifier is wrong and should be changed to match 8828 // the argument. 8829 EmitFormatDiagnostic(S.PDiag(Diag) 8830 << AT.getRepresentativeTypeName(S.Context) 8831 << IntendedTy << IsEnum << E->getSourceRange(), 8832 E->getBeginLoc(), 8833 /*IsStringLocation*/ false, SpecRange, 8834 FixItHint::CreateReplacement(SpecRange, os.str())); 8835 } else { 8836 // The canonical type for formatting this value is different from the 8837 // actual type of the expression. (This occurs, for example, with Darwin's 8838 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8839 // should be printed as 'long' for 64-bit compatibility.) 8840 // Rather than emitting a normal format/argument mismatch, we want to 8841 // add a cast to the recommended type (and correct the format string 8842 // if necessary). 8843 SmallString<16> CastBuf; 8844 llvm::raw_svector_ostream CastFix(CastBuf); 8845 CastFix << "("; 8846 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8847 CastFix << ")"; 8848 8849 SmallVector<FixItHint,4> Hints; 8850 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8851 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8852 8853 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8854 // If there's already a cast present, just replace it. 8855 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8856 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8857 8858 } else if (!requiresParensToAddCast(E)) { 8859 // If the expression has high enough precedence, 8860 // just write the C-style cast. 8861 Hints.push_back( 8862 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8863 } else { 8864 // Otherwise, add parens around the expression as well as the cast. 8865 CastFix << "("; 8866 Hints.push_back( 8867 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8868 8869 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8870 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8871 } 8872 8873 if (ShouldNotPrintDirectly) { 8874 // The expression has a type that should not be printed directly. 8875 // We extract the name from the typedef because we don't want to show 8876 // the underlying type in the diagnostic. 8877 StringRef Name; 8878 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8879 Name = TypedefTy->getDecl()->getName(); 8880 else 8881 Name = CastTyName; 8882 unsigned Diag = Match == ArgType::NoMatchPedantic 8883 ? diag::warn_format_argument_needs_cast_pedantic 8884 : diag::warn_format_argument_needs_cast; 8885 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8886 << E->getSourceRange(), 8887 E->getBeginLoc(), /*IsStringLocation=*/false, 8888 SpecRange, Hints); 8889 } else { 8890 // In this case, the expression could be printed using a different 8891 // specifier, but we've decided that the specifier is probably correct 8892 // and we should cast instead. Just use the normal warning message. 8893 EmitFormatDiagnostic( 8894 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8895 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8896 << E->getSourceRange(), 8897 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8898 } 8899 } 8900 } else { 8901 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8902 SpecifierLen); 8903 // Since the warning for passing non-POD types to variadic functions 8904 // was deferred until now, we emit a warning for non-POD 8905 // arguments here. 8906 switch (S.isValidVarArgType(ExprTy)) { 8907 case Sema::VAK_Valid: 8908 case Sema::VAK_ValidInCXX11: { 8909 unsigned Diag; 8910 switch (Match) { 8911 case ArgType::Match: llvm_unreachable("expected non-matching"); 8912 case ArgType::NoMatchPedantic: 8913 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8914 break; 8915 case ArgType::NoMatchTypeConfusion: 8916 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8917 break; 8918 case ArgType::NoMatch: 8919 Diag = diag::warn_format_conversion_argument_type_mismatch; 8920 break; 8921 } 8922 8923 EmitFormatDiagnostic( 8924 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8925 << IsEnum << CSR << E->getSourceRange(), 8926 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8927 break; 8928 } 8929 case Sema::VAK_Undefined: 8930 case Sema::VAK_MSVCUndefined: 8931 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8932 << S.getLangOpts().CPlusPlus11 << ExprTy 8933 << CallType 8934 << AT.getRepresentativeTypeName(S.Context) << CSR 8935 << E->getSourceRange(), 8936 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8937 checkForCStrMembers(AT, E); 8938 break; 8939 8940 case Sema::VAK_Invalid: 8941 if (ExprTy->isObjCObjectType()) 8942 EmitFormatDiagnostic( 8943 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8944 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8945 << AT.getRepresentativeTypeName(S.Context) << CSR 8946 << E->getSourceRange(), 8947 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8948 else 8949 // FIXME: If this is an initializer list, suggest removing the braces 8950 // or inserting a cast to the target type. 8951 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8952 << isa<InitListExpr>(E) << ExprTy << CallType 8953 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8954 break; 8955 } 8956 8957 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8958 "format string specifier index out of range"); 8959 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8960 } 8961 8962 return true; 8963 } 8964 8965 //===--- CHECK: Scanf format string checking ------------------------------===// 8966 8967 namespace { 8968 8969 class CheckScanfHandler : public CheckFormatHandler { 8970 public: 8971 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8972 const Expr *origFormatExpr, Sema::FormatStringType type, 8973 unsigned firstDataArg, unsigned numDataArgs, 8974 const char *beg, bool hasVAListArg, 8975 ArrayRef<const Expr *> Args, unsigned formatIdx, 8976 bool inFunctionCall, Sema::VariadicCallType CallType, 8977 llvm::SmallBitVector &CheckedVarArgs, 8978 UncoveredArgHandler &UncoveredArg) 8979 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8980 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8981 inFunctionCall, CallType, CheckedVarArgs, 8982 UncoveredArg) {} 8983 8984 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8985 const char *startSpecifier, 8986 unsigned specifierLen) override; 8987 8988 bool HandleInvalidScanfConversionSpecifier( 8989 const analyze_scanf::ScanfSpecifier &FS, 8990 const char *startSpecifier, 8991 unsigned specifierLen) override; 8992 8993 void HandleIncompleteScanList(const char *start, const char *end) override; 8994 }; 8995 8996 } // namespace 8997 8998 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8999 const char *end) { 9000 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9001 getLocationOfByte(end), /*IsStringLocation*/true, 9002 getSpecifierRange(start, end - start)); 9003 } 9004 9005 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9006 const analyze_scanf::ScanfSpecifier &FS, 9007 const char *startSpecifier, 9008 unsigned specifierLen) { 9009 const analyze_scanf::ScanfConversionSpecifier &CS = 9010 FS.getConversionSpecifier(); 9011 9012 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9013 getLocationOfByte(CS.getStart()), 9014 startSpecifier, specifierLen, 9015 CS.getStart(), CS.getLength()); 9016 } 9017 9018 bool CheckScanfHandler::HandleScanfSpecifier( 9019 const analyze_scanf::ScanfSpecifier &FS, 9020 const char *startSpecifier, 9021 unsigned specifierLen) { 9022 using namespace analyze_scanf; 9023 using namespace analyze_format_string; 9024 9025 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9026 9027 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9028 // be used to decide if we are using positional arguments consistently. 9029 if (FS.consumesDataArgument()) { 9030 if (atFirstArg) { 9031 atFirstArg = false; 9032 usesPositionalArgs = FS.usesPositionalArg(); 9033 } 9034 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9035 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9036 startSpecifier, specifierLen); 9037 return false; 9038 } 9039 } 9040 9041 // Check if the field with is non-zero. 9042 const OptionalAmount &Amt = FS.getFieldWidth(); 9043 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9044 if (Amt.getConstantAmount() == 0) { 9045 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9046 Amt.getConstantLength()); 9047 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9048 getLocationOfByte(Amt.getStart()), 9049 /*IsStringLocation*/true, R, 9050 FixItHint::CreateRemoval(R)); 9051 } 9052 } 9053 9054 if (!FS.consumesDataArgument()) { 9055 // FIXME: Technically specifying a precision or field width here 9056 // makes no sense. Worth issuing a warning at some point. 9057 return true; 9058 } 9059 9060 // Consume the argument. 9061 unsigned argIndex = FS.getArgIndex(); 9062 if (argIndex < NumDataArgs) { 9063 // The check to see if the argIndex is valid will come later. 9064 // We set the bit here because we may exit early from this 9065 // function if we encounter some other error. 9066 CoveredArgs.set(argIndex); 9067 } 9068 9069 // Check the length modifier is valid with the given conversion specifier. 9070 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9071 S.getLangOpts())) 9072 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9073 diag::warn_format_nonsensical_length); 9074 else if (!FS.hasStandardLengthModifier()) 9075 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9076 else if (!FS.hasStandardLengthConversionCombination()) 9077 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9078 diag::warn_format_non_standard_conversion_spec); 9079 9080 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9081 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9082 9083 // The remaining checks depend on the data arguments. 9084 if (HasVAListArg) 9085 return true; 9086 9087 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9088 return false; 9089 9090 // Check that the argument type matches the format specifier. 9091 const Expr *Ex = getDataArg(argIndex); 9092 if (!Ex) 9093 return true; 9094 9095 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9096 9097 if (!AT.isValid()) { 9098 return true; 9099 } 9100 9101 analyze_format_string::ArgType::MatchKind Match = 9102 AT.matchesType(S.Context, Ex->getType()); 9103 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9104 if (Match == analyze_format_string::ArgType::Match) 9105 return true; 9106 9107 ScanfSpecifier fixedFS = FS; 9108 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9109 S.getLangOpts(), S.Context); 9110 9111 unsigned Diag = 9112 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9113 : diag::warn_format_conversion_argument_type_mismatch; 9114 9115 if (Success) { 9116 // Get the fix string from the fixed format specifier. 9117 SmallString<128> buf; 9118 llvm::raw_svector_ostream os(buf); 9119 fixedFS.toString(os); 9120 9121 EmitFormatDiagnostic( 9122 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9123 << Ex->getType() << false << Ex->getSourceRange(), 9124 Ex->getBeginLoc(), 9125 /*IsStringLocation*/ false, 9126 getSpecifierRange(startSpecifier, specifierLen), 9127 FixItHint::CreateReplacement( 9128 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9129 } else { 9130 EmitFormatDiagnostic(S.PDiag(Diag) 9131 << AT.getRepresentativeTypeName(S.Context) 9132 << Ex->getType() << false << Ex->getSourceRange(), 9133 Ex->getBeginLoc(), 9134 /*IsStringLocation*/ false, 9135 getSpecifierRange(startSpecifier, specifierLen)); 9136 } 9137 9138 return true; 9139 } 9140 9141 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9142 const Expr *OrigFormatExpr, 9143 ArrayRef<const Expr *> Args, 9144 bool HasVAListArg, unsigned format_idx, 9145 unsigned firstDataArg, 9146 Sema::FormatStringType Type, 9147 bool inFunctionCall, 9148 Sema::VariadicCallType CallType, 9149 llvm::SmallBitVector &CheckedVarArgs, 9150 UncoveredArgHandler &UncoveredArg, 9151 bool IgnoreStringsWithoutSpecifiers) { 9152 // CHECK: is the format string a wide literal? 9153 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9154 CheckFormatHandler::EmitFormatDiagnostic( 9155 S, inFunctionCall, Args[format_idx], 9156 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9157 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9158 return; 9159 } 9160 9161 // Str - The format string. NOTE: this is NOT null-terminated! 9162 StringRef StrRef = FExpr->getString(); 9163 const char *Str = StrRef.data(); 9164 // Account for cases where the string literal is truncated in a declaration. 9165 const ConstantArrayType *T = 9166 S.Context.getAsConstantArrayType(FExpr->getType()); 9167 assert(T && "String literal not of constant array type!"); 9168 size_t TypeSize = T->getSize().getZExtValue(); 9169 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9170 const unsigned numDataArgs = Args.size() - firstDataArg; 9171 9172 if (IgnoreStringsWithoutSpecifiers && 9173 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9174 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9175 return; 9176 9177 // Emit a warning if the string literal is truncated and does not contain an 9178 // embedded null character. 9179 if (TypeSize <= StrRef.size() && 9180 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9181 CheckFormatHandler::EmitFormatDiagnostic( 9182 S, inFunctionCall, Args[format_idx], 9183 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9184 FExpr->getBeginLoc(), 9185 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9186 return; 9187 } 9188 9189 // CHECK: empty format string? 9190 if (StrLen == 0 && numDataArgs > 0) { 9191 CheckFormatHandler::EmitFormatDiagnostic( 9192 S, inFunctionCall, Args[format_idx], 9193 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9194 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9195 return; 9196 } 9197 9198 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9199 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9200 Type == Sema::FST_OSTrace) { 9201 CheckPrintfHandler H( 9202 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9203 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9204 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9205 CheckedVarArgs, UncoveredArg); 9206 9207 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9208 S.getLangOpts(), 9209 S.Context.getTargetInfo(), 9210 Type == Sema::FST_FreeBSDKPrintf)) 9211 H.DoneProcessing(); 9212 } else if (Type == Sema::FST_Scanf) { 9213 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9214 numDataArgs, Str, HasVAListArg, Args, format_idx, 9215 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9216 9217 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9218 S.getLangOpts(), 9219 S.Context.getTargetInfo())) 9220 H.DoneProcessing(); 9221 } // TODO: handle other formats 9222 } 9223 9224 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9225 // Str - The format string. NOTE: this is NOT null-terminated! 9226 StringRef StrRef = FExpr->getString(); 9227 const char *Str = StrRef.data(); 9228 // Account for cases where the string literal is truncated in a declaration. 9229 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9230 assert(T && "String literal not of constant array type!"); 9231 size_t TypeSize = T->getSize().getZExtValue(); 9232 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9233 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9234 getLangOpts(), 9235 Context.getTargetInfo()); 9236 } 9237 9238 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9239 9240 // Returns the related absolute value function that is larger, of 0 if one 9241 // does not exist. 9242 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9243 switch (AbsFunction) { 9244 default: 9245 return 0; 9246 9247 case Builtin::BI__builtin_abs: 9248 return Builtin::BI__builtin_labs; 9249 case Builtin::BI__builtin_labs: 9250 return Builtin::BI__builtin_llabs; 9251 case Builtin::BI__builtin_llabs: 9252 return 0; 9253 9254 case Builtin::BI__builtin_fabsf: 9255 return Builtin::BI__builtin_fabs; 9256 case Builtin::BI__builtin_fabs: 9257 return Builtin::BI__builtin_fabsl; 9258 case Builtin::BI__builtin_fabsl: 9259 return 0; 9260 9261 case Builtin::BI__builtin_cabsf: 9262 return Builtin::BI__builtin_cabs; 9263 case Builtin::BI__builtin_cabs: 9264 return Builtin::BI__builtin_cabsl; 9265 case Builtin::BI__builtin_cabsl: 9266 return 0; 9267 9268 case Builtin::BIabs: 9269 return Builtin::BIlabs; 9270 case Builtin::BIlabs: 9271 return Builtin::BIllabs; 9272 case Builtin::BIllabs: 9273 return 0; 9274 9275 case Builtin::BIfabsf: 9276 return Builtin::BIfabs; 9277 case Builtin::BIfabs: 9278 return Builtin::BIfabsl; 9279 case Builtin::BIfabsl: 9280 return 0; 9281 9282 case Builtin::BIcabsf: 9283 return Builtin::BIcabs; 9284 case Builtin::BIcabs: 9285 return Builtin::BIcabsl; 9286 case Builtin::BIcabsl: 9287 return 0; 9288 } 9289 } 9290 9291 // Returns the argument type of the absolute value function. 9292 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9293 unsigned AbsType) { 9294 if (AbsType == 0) 9295 return QualType(); 9296 9297 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9298 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9299 if (Error != ASTContext::GE_None) 9300 return QualType(); 9301 9302 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9303 if (!FT) 9304 return QualType(); 9305 9306 if (FT->getNumParams() != 1) 9307 return QualType(); 9308 9309 return FT->getParamType(0); 9310 } 9311 9312 // Returns the best absolute value function, or zero, based on type and 9313 // current absolute value function. 9314 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9315 unsigned AbsFunctionKind) { 9316 unsigned BestKind = 0; 9317 uint64_t ArgSize = Context.getTypeSize(ArgType); 9318 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9319 Kind = getLargerAbsoluteValueFunction(Kind)) { 9320 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9321 if (Context.getTypeSize(ParamType) >= ArgSize) { 9322 if (BestKind == 0) 9323 BestKind = Kind; 9324 else if (Context.hasSameType(ParamType, ArgType)) { 9325 BestKind = Kind; 9326 break; 9327 } 9328 } 9329 } 9330 return BestKind; 9331 } 9332 9333 enum AbsoluteValueKind { 9334 AVK_Integer, 9335 AVK_Floating, 9336 AVK_Complex 9337 }; 9338 9339 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9340 if (T->isIntegralOrEnumerationType()) 9341 return AVK_Integer; 9342 if (T->isRealFloatingType()) 9343 return AVK_Floating; 9344 if (T->isAnyComplexType()) 9345 return AVK_Complex; 9346 9347 llvm_unreachable("Type not integer, floating, or complex"); 9348 } 9349 9350 // Changes the absolute value function to a different type. Preserves whether 9351 // the function is a builtin. 9352 static unsigned changeAbsFunction(unsigned AbsKind, 9353 AbsoluteValueKind ValueKind) { 9354 switch (ValueKind) { 9355 case AVK_Integer: 9356 switch (AbsKind) { 9357 default: 9358 return 0; 9359 case Builtin::BI__builtin_fabsf: 9360 case Builtin::BI__builtin_fabs: 9361 case Builtin::BI__builtin_fabsl: 9362 case Builtin::BI__builtin_cabsf: 9363 case Builtin::BI__builtin_cabs: 9364 case Builtin::BI__builtin_cabsl: 9365 return Builtin::BI__builtin_abs; 9366 case Builtin::BIfabsf: 9367 case Builtin::BIfabs: 9368 case Builtin::BIfabsl: 9369 case Builtin::BIcabsf: 9370 case Builtin::BIcabs: 9371 case Builtin::BIcabsl: 9372 return Builtin::BIabs; 9373 } 9374 case AVK_Floating: 9375 switch (AbsKind) { 9376 default: 9377 return 0; 9378 case Builtin::BI__builtin_abs: 9379 case Builtin::BI__builtin_labs: 9380 case Builtin::BI__builtin_llabs: 9381 case Builtin::BI__builtin_cabsf: 9382 case Builtin::BI__builtin_cabs: 9383 case Builtin::BI__builtin_cabsl: 9384 return Builtin::BI__builtin_fabsf; 9385 case Builtin::BIabs: 9386 case Builtin::BIlabs: 9387 case Builtin::BIllabs: 9388 case Builtin::BIcabsf: 9389 case Builtin::BIcabs: 9390 case Builtin::BIcabsl: 9391 return Builtin::BIfabsf; 9392 } 9393 case AVK_Complex: 9394 switch (AbsKind) { 9395 default: 9396 return 0; 9397 case Builtin::BI__builtin_abs: 9398 case Builtin::BI__builtin_labs: 9399 case Builtin::BI__builtin_llabs: 9400 case Builtin::BI__builtin_fabsf: 9401 case Builtin::BI__builtin_fabs: 9402 case Builtin::BI__builtin_fabsl: 9403 return Builtin::BI__builtin_cabsf; 9404 case Builtin::BIabs: 9405 case Builtin::BIlabs: 9406 case Builtin::BIllabs: 9407 case Builtin::BIfabsf: 9408 case Builtin::BIfabs: 9409 case Builtin::BIfabsl: 9410 return Builtin::BIcabsf; 9411 } 9412 } 9413 llvm_unreachable("Unable to convert function"); 9414 } 9415 9416 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9417 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9418 if (!FnInfo) 9419 return 0; 9420 9421 switch (FDecl->getBuiltinID()) { 9422 default: 9423 return 0; 9424 case Builtin::BI__builtin_abs: 9425 case Builtin::BI__builtin_fabs: 9426 case Builtin::BI__builtin_fabsf: 9427 case Builtin::BI__builtin_fabsl: 9428 case Builtin::BI__builtin_labs: 9429 case Builtin::BI__builtin_llabs: 9430 case Builtin::BI__builtin_cabs: 9431 case Builtin::BI__builtin_cabsf: 9432 case Builtin::BI__builtin_cabsl: 9433 case Builtin::BIabs: 9434 case Builtin::BIlabs: 9435 case Builtin::BIllabs: 9436 case Builtin::BIfabs: 9437 case Builtin::BIfabsf: 9438 case Builtin::BIfabsl: 9439 case Builtin::BIcabs: 9440 case Builtin::BIcabsf: 9441 case Builtin::BIcabsl: 9442 return FDecl->getBuiltinID(); 9443 } 9444 llvm_unreachable("Unknown Builtin type"); 9445 } 9446 9447 // If the replacement is valid, emit a note with replacement function. 9448 // Additionally, suggest including the proper header if not already included. 9449 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9450 unsigned AbsKind, QualType ArgType) { 9451 bool EmitHeaderHint = true; 9452 const char *HeaderName = nullptr; 9453 const char *FunctionName = nullptr; 9454 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9455 FunctionName = "std::abs"; 9456 if (ArgType->isIntegralOrEnumerationType()) { 9457 HeaderName = "cstdlib"; 9458 } else if (ArgType->isRealFloatingType()) { 9459 HeaderName = "cmath"; 9460 } else { 9461 llvm_unreachable("Invalid Type"); 9462 } 9463 9464 // Lookup all std::abs 9465 if (NamespaceDecl *Std = S.getStdNamespace()) { 9466 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9467 R.suppressDiagnostics(); 9468 S.LookupQualifiedName(R, Std); 9469 9470 for (const auto *I : R) { 9471 const FunctionDecl *FDecl = nullptr; 9472 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9473 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9474 } else { 9475 FDecl = dyn_cast<FunctionDecl>(I); 9476 } 9477 if (!FDecl) 9478 continue; 9479 9480 // Found std::abs(), check that they are the right ones. 9481 if (FDecl->getNumParams() != 1) 9482 continue; 9483 9484 // Check that the parameter type can handle the argument. 9485 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9486 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9487 S.Context.getTypeSize(ArgType) <= 9488 S.Context.getTypeSize(ParamType)) { 9489 // Found a function, don't need the header hint. 9490 EmitHeaderHint = false; 9491 break; 9492 } 9493 } 9494 } 9495 } else { 9496 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9497 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9498 9499 if (HeaderName) { 9500 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9501 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9502 R.suppressDiagnostics(); 9503 S.LookupName(R, S.getCurScope()); 9504 9505 if (R.isSingleResult()) { 9506 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9507 if (FD && FD->getBuiltinID() == AbsKind) { 9508 EmitHeaderHint = false; 9509 } else { 9510 return; 9511 } 9512 } else if (!R.empty()) { 9513 return; 9514 } 9515 } 9516 } 9517 9518 S.Diag(Loc, diag::note_replace_abs_function) 9519 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9520 9521 if (!HeaderName) 9522 return; 9523 9524 if (!EmitHeaderHint) 9525 return; 9526 9527 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9528 << FunctionName; 9529 } 9530 9531 template <std::size_t StrLen> 9532 static bool IsStdFunction(const FunctionDecl *FDecl, 9533 const char (&Str)[StrLen]) { 9534 if (!FDecl) 9535 return false; 9536 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9537 return false; 9538 if (!FDecl->isInStdNamespace()) 9539 return false; 9540 9541 return true; 9542 } 9543 9544 // Warn when using the wrong abs() function. 9545 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9546 const FunctionDecl *FDecl) { 9547 if (Call->getNumArgs() != 1) 9548 return; 9549 9550 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9551 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9552 if (AbsKind == 0 && !IsStdAbs) 9553 return; 9554 9555 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9556 QualType ParamType = Call->getArg(0)->getType(); 9557 9558 // Unsigned types cannot be negative. Suggest removing the absolute value 9559 // function call. 9560 if (ArgType->isUnsignedIntegerType()) { 9561 const char *FunctionName = 9562 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9563 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9564 Diag(Call->getExprLoc(), diag::note_remove_abs) 9565 << FunctionName 9566 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9567 return; 9568 } 9569 9570 // Taking the absolute value of a pointer is very suspicious, they probably 9571 // wanted to index into an array, dereference a pointer, call a function, etc. 9572 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9573 unsigned DiagType = 0; 9574 if (ArgType->isFunctionType()) 9575 DiagType = 1; 9576 else if (ArgType->isArrayType()) 9577 DiagType = 2; 9578 9579 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9580 return; 9581 } 9582 9583 // std::abs has overloads which prevent most of the absolute value problems 9584 // from occurring. 9585 if (IsStdAbs) 9586 return; 9587 9588 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9589 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9590 9591 // The argument and parameter are the same kind. Check if they are the right 9592 // size. 9593 if (ArgValueKind == ParamValueKind) { 9594 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9595 return; 9596 9597 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9598 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9599 << FDecl << ArgType << ParamType; 9600 9601 if (NewAbsKind == 0) 9602 return; 9603 9604 emitReplacement(*this, Call->getExprLoc(), 9605 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9606 return; 9607 } 9608 9609 // ArgValueKind != ParamValueKind 9610 // The wrong type of absolute value function was used. Attempt to find the 9611 // proper one. 9612 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9613 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9614 if (NewAbsKind == 0) 9615 return; 9616 9617 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9618 << FDecl << ParamValueKind << ArgValueKind; 9619 9620 emitReplacement(*this, Call->getExprLoc(), 9621 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9622 } 9623 9624 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9625 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9626 const FunctionDecl *FDecl) { 9627 if (!Call || !FDecl) return; 9628 9629 // Ignore template specializations and macros. 9630 if (inTemplateInstantiation()) return; 9631 if (Call->getExprLoc().isMacroID()) return; 9632 9633 // Only care about the one template argument, two function parameter std::max 9634 if (Call->getNumArgs() != 2) return; 9635 if (!IsStdFunction(FDecl, "max")) return; 9636 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9637 if (!ArgList) return; 9638 if (ArgList->size() != 1) return; 9639 9640 // Check that template type argument is unsigned integer. 9641 const auto& TA = ArgList->get(0); 9642 if (TA.getKind() != TemplateArgument::Type) return; 9643 QualType ArgType = TA.getAsType(); 9644 if (!ArgType->isUnsignedIntegerType()) return; 9645 9646 // See if either argument is a literal zero. 9647 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9648 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9649 if (!MTE) return false; 9650 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9651 if (!Num) return false; 9652 if (Num->getValue() != 0) return false; 9653 return true; 9654 }; 9655 9656 const Expr *FirstArg = Call->getArg(0); 9657 const Expr *SecondArg = Call->getArg(1); 9658 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9659 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9660 9661 // Only warn when exactly one argument is zero. 9662 if (IsFirstArgZero == IsSecondArgZero) return; 9663 9664 SourceRange FirstRange = FirstArg->getSourceRange(); 9665 SourceRange SecondRange = SecondArg->getSourceRange(); 9666 9667 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9668 9669 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9670 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9671 9672 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9673 SourceRange RemovalRange; 9674 if (IsFirstArgZero) { 9675 RemovalRange = SourceRange(FirstRange.getBegin(), 9676 SecondRange.getBegin().getLocWithOffset(-1)); 9677 } else { 9678 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9679 SecondRange.getEnd()); 9680 } 9681 9682 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9683 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9684 << FixItHint::CreateRemoval(RemovalRange); 9685 } 9686 9687 //===--- CHECK: Standard memory functions ---------------------------------===// 9688 9689 /// Takes the expression passed to the size_t parameter of functions 9690 /// such as memcmp, strncat, etc and warns if it's a comparison. 9691 /// 9692 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9693 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9694 IdentifierInfo *FnName, 9695 SourceLocation FnLoc, 9696 SourceLocation RParenLoc) { 9697 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9698 if (!Size) 9699 return false; 9700 9701 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9702 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9703 return false; 9704 9705 SourceRange SizeRange = Size->getSourceRange(); 9706 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9707 << SizeRange << FnName; 9708 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9709 << FnName 9710 << FixItHint::CreateInsertion( 9711 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9712 << FixItHint::CreateRemoval(RParenLoc); 9713 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9714 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9715 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9716 ")"); 9717 9718 return true; 9719 } 9720 9721 /// Determine whether the given type is or contains a dynamic class type 9722 /// (e.g., whether it has a vtable). 9723 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9724 bool &IsContained) { 9725 // Look through array types while ignoring qualifiers. 9726 const Type *Ty = T->getBaseElementTypeUnsafe(); 9727 IsContained = false; 9728 9729 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9730 RD = RD ? RD->getDefinition() : nullptr; 9731 if (!RD || RD->isInvalidDecl()) 9732 return nullptr; 9733 9734 if (RD->isDynamicClass()) 9735 return RD; 9736 9737 // Check all the fields. If any bases were dynamic, the class is dynamic. 9738 // It's impossible for a class to transitively contain itself by value, so 9739 // infinite recursion is impossible. 9740 for (auto *FD : RD->fields()) { 9741 bool SubContained; 9742 if (const CXXRecordDecl *ContainedRD = 9743 getContainedDynamicClass(FD->getType(), SubContained)) { 9744 IsContained = true; 9745 return ContainedRD; 9746 } 9747 } 9748 9749 return nullptr; 9750 } 9751 9752 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9753 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9754 if (Unary->getKind() == UETT_SizeOf) 9755 return Unary; 9756 return nullptr; 9757 } 9758 9759 /// If E is a sizeof expression, returns its argument expression, 9760 /// otherwise returns NULL. 9761 static const Expr *getSizeOfExprArg(const Expr *E) { 9762 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9763 if (!SizeOf->isArgumentType()) 9764 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9765 return nullptr; 9766 } 9767 9768 /// If E is a sizeof expression, returns its argument type. 9769 static QualType getSizeOfArgType(const Expr *E) { 9770 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9771 return SizeOf->getTypeOfArgument(); 9772 return QualType(); 9773 } 9774 9775 namespace { 9776 9777 struct SearchNonTrivialToInitializeField 9778 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9779 using Super = 9780 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9781 9782 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9783 9784 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9785 SourceLocation SL) { 9786 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9787 asDerived().visitArray(PDIK, AT, SL); 9788 return; 9789 } 9790 9791 Super::visitWithKind(PDIK, FT, SL); 9792 } 9793 9794 void visitARCStrong(QualType FT, SourceLocation SL) { 9795 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9796 } 9797 void visitARCWeak(QualType FT, SourceLocation SL) { 9798 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9799 } 9800 void visitStruct(QualType FT, SourceLocation SL) { 9801 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9802 visit(FD->getType(), FD->getLocation()); 9803 } 9804 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9805 const ArrayType *AT, SourceLocation SL) { 9806 visit(getContext().getBaseElementType(AT), SL); 9807 } 9808 void visitTrivial(QualType FT, SourceLocation SL) {} 9809 9810 static void diag(QualType RT, const Expr *E, Sema &S) { 9811 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9812 } 9813 9814 ASTContext &getContext() { return S.getASTContext(); } 9815 9816 const Expr *E; 9817 Sema &S; 9818 }; 9819 9820 struct SearchNonTrivialToCopyField 9821 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9822 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9823 9824 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9825 9826 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9827 SourceLocation SL) { 9828 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9829 asDerived().visitArray(PCK, AT, SL); 9830 return; 9831 } 9832 9833 Super::visitWithKind(PCK, FT, SL); 9834 } 9835 9836 void visitARCStrong(QualType FT, SourceLocation SL) { 9837 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9838 } 9839 void visitARCWeak(QualType FT, SourceLocation SL) { 9840 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9841 } 9842 void visitStruct(QualType FT, SourceLocation SL) { 9843 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9844 visit(FD->getType(), FD->getLocation()); 9845 } 9846 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9847 SourceLocation SL) { 9848 visit(getContext().getBaseElementType(AT), SL); 9849 } 9850 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9851 SourceLocation SL) {} 9852 void visitTrivial(QualType FT, SourceLocation SL) {} 9853 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9854 9855 static void diag(QualType RT, const Expr *E, Sema &S) { 9856 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9857 } 9858 9859 ASTContext &getContext() { return S.getASTContext(); } 9860 9861 const Expr *E; 9862 Sema &S; 9863 }; 9864 9865 } 9866 9867 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9868 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9869 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9870 9871 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9872 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9873 return false; 9874 9875 return doesExprLikelyComputeSize(BO->getLHS()) || 9876 doesExprLikelyComputeSize(BO->getRHS()); 9877 } 9878 9879 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9880 } 9881 9882 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9883 /// 9884 /// \code 9885 /// #define MACRO 0 9886 /// foo(MACRO); 9887 /// foo(0); 9888 /// \endcode 9889 /// 9890 /// This should return true for the first call to foo, but not for the second 9891 /// (regardless of whether foo is a macro or function). 9892 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9893 SourceLocation CallLoc, 9894 SourceLocation ArgLoc) { 9895 if (!CallLoc.isMacroID()) 9896 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9897 9898 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9899 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9900 } 9901 9902 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9903 /// last two arguments transposed. 9904 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9905 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9906 return; 9907 9908 const Expr *SizeArg = 9909 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9910 9911 auto isLiteralZero = [](const Expr *E) { 9912 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9913 }; 9914 9915 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9916 SourceLocation CallLoc = Call->getRParenLoc(); 9917 SourceManager &SM = S.getSourceManager(); 9918 if (isLiteralZero(SizeArg) && 9919 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9920 9921 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9922 9923 // Some platforms #define bzero to __builtin_memset. See if this is the 9924 // case, and if so, emit a better diagnostic. 9925 if (BId == Builtin::BIbzero || 9926 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9927 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9928 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9929 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9930 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9931 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9932 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9933 } 9934 return; 9935 } 9936 9937 // If the second argument to a memset is a sizeof expression and the third 9938 // isn't, this is also likely an error. This should catch 9939 // 'memset(buf, sizeof(buf), 0xff)'. 9940 if (BId == Builtin::BImemset && 9941 doesExprLikelyComputeSize(Call->getArg(1)) && 9942 !doesExprLikelyComputeSize(Call->getArg(2))) { 9943 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9944 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9945 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9946 return; 9947 } 9948 } 9949 9950 /// Check for dangerous or invalid arguments to memset(). 9951 /// 9952 /// This issues warnings on known problematic, dangerous or unspecified 9953 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9954 /// function calls. 9955 /// 9956 /// \param Call The call expression to diagnose. 9957 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9958 unsigned BId, 9959 IdentifierInfo *FnName) { 9960 assert(BId != 0); 9961 9962 // It is possible to have a non-standard definition of memset. Validate 9963 // we have enough arguments, and if not, abort further checking. 9964 unsigned ExpectedNumArgs = 9965 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9966 if (Call->getNumArgs() < ExpectedNumArgs) 9967 return; 9968 9969 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9970 BId == Builtin::BIstrndup ? 1 : 2); 9971 unsigned LenArg = 9972 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9973 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9974 9975 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9976 Call->getBeginLoc(), Call->getRParenLoc())) 9977 return; 9978 9979 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9980 CheckMemaccessSize(*this, BId, Call); 9981 9982 // We have special checking when the length is a sizeof expression. 9983 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9984 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9985 llvm::FoldingSetNodeID SizeOfArgID; 9986 9987 // Although widely used, 'bzero' is not a standard function. Be more strict 9988 // with the argument types before allowing diagnostics and only allow the 9989 // form bzero(ptr, sizeof(...)). 9990 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9991 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9992 return; 9993 9994 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9995 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9996 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9997 9998 QualType DestTy = Dest->getType(); 9999 QualType PointeeTy; 10000 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10001 PointeeTy = DestPtrTy->getPointeeType(); 10002 10003 // Never warn about void type pointers. This can be used to suppress 10004 // false positives. 10005 if (PointeeTy->isVoidType()) 10006 continue; 10007 10008 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10009 // actually comparing the expressions for equality. Because computing the 10010 // expression IDs can be expensive, we only do this if the diagnostic is 10011 // enabled. 10012 if (SizeOfArg && 10013 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10014 SizeOfArg->getExprLoc())) { 10015 // We only compute IDs for expressions if the warning is enabled, and 10016 // cache the sizeof arg's ID. 10017 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10018 SizeOfArg->Profile(SizeOfArgID, Context, true); 10019 llvm::FoldingSetNodeID DestID; 10020 Dest->Profile(DestID, Context, true); 10021 if (DestID == SizeOfArgID) { 10022 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10023 // over sizeof(src) as well. 10024 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10025 StringRef ReadableName = FnName->getName(); 10026 10027 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10028 if (UnaryOp->getOpcode() == UO_AddrOf) 10029 ActionIdx = 1; // If its an address-of operator, just remove it. 10030 if (!PointeeTy->isIncompleteType() && 10031 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10032 ActionIdx = 2; // If the pointee's size is sizeof(char), 10033 // suggest an explicit length. 10034 10035 // If the function is defined as a builtin macro, do not show macro 10036 // expansion. 10037 SourceLocation SL = SizeOfArg->getExprLoc(); 10038 SourceRange DSR = Dest->getSourceRange(); 10039 SourceRange SSR = SizeOfArg->getSourceRange(); 10040 SourceManager &SM = getSourceManager(); 10041 10042 if (SM.isMacroArgExpansion(SL)) { 10043 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10044 SL = SM.getSpellingLoc(SL); 10045 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10046 SM.getSpellingLoc(DSR.getEnd())); 10047 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10048 SM.getSpellingLoc(SSR.getEnd())); 10049 } 10050 10051 DiagRuntimeBehavior(SL, SizeOfArg, 10052 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10053 << ReadableName 10054 << PointeeTy 10055 << DestTy 10056 << DSR 10057 << SSR); 10058 DiagRuntimeBehavior(SL, SizeOfArg, 10059 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10060 << ActionIdx 10061 << SSR); 10062 10063 break; 10064 } 10065 } 10066 10067 // Also check for cases where the sizeof argument is the exact same 10068 // type as the memory argument, and where it points to a user-defined 10069 // record type. 10070 if (SizeOfArgTy != QualType()) { 10071 if (PointeeTy->isRecordType() && 10072 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10073 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10074 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10075 << FnName << SizeOfArgTy << ArgIdx 10076 << PointeeTy << Dest->getSourceRange() 10077 << LenExpr->getSourceRange()); 10078 break; 10079 } 10080 } 10081 } else if (DestTy->isArrayType()) { 10082 PointeeTy = DestTy; 10083 } 10084 10085 if (PointeeTy == QualType()) 10086 continue; 10087 10088 // Always complain about dynamic classes. 10089 bool IsContained; 10090 if (const CXXRecordDecl *ContainedRD = 10091 getContainedDynamicClass(PointeeTy, IsContained)) { 10092 10093 unsigned OperationType = 0; 10094 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10095 // "overwritten" if we're warning about the destination for any call 10096 // but memcmp; otherwise a verb appropriate to the call. 10097 if (ArgIdx != 0 || IsCmp) { 10098 if (BId == Builtin::BImemcpy) 10099 OperationType = 1; 10100 else if(BId == Builtin::BImemmove) 10101 OperationType = 2; 10102 else if (IsCmp) 10103 OperationType = 3; 10104 } 10105 10106 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10107 PDiag(diag::warn_dyn_class_memaccess) 10108 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10109 << IsContained << ContainedRD << OperationType 10110 << Call->getCallee()->getSourceRange()); 10111 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10112 BId != Builtin::BImemset) 10113 DiagRuntimeBehavior( 10114 Dest->getExprLoc(), Dest, 10115 PDiag(diag::warn_arc_object_memaccess) 10116 << ArgIdx << FnName << PointeeTy 10117 << Call->getCallee()->getSourceRange()); 10118 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10119 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10120 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10121 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10122 PDiag(diag::warn_cstruct_memaccess) 10123 << ArgIdx << FnName << PointeeTy << 0); 10124 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10125 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10126 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10127 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10128 PDiag(diag::warn_cstruct_memaccess) 10129 << ArgIdx << FnName << PointeeTy << 1); 10130 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10131 } else { 10132 continue; 10133 } 10134 } else 10135 continue; 10136 10137 DiagRuntimeBehavior( 10138 Dest->getExprLoc(), Dest, 10139 PDiag(diag::note_bad_memaccess_silence) 10140 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10141 break; 10142 } 10143 } 10144 10145 // A little helper routine: ignore addition and subtraction of integer literals. 10146 // This intentionally does not ignore all integer constant expressions because 10147 // we don't want to remove sizeof(). 10148 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10149 Ex = Ex->IgnoreParenCasts(); 10150 10151 while (true) { 10152 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10153 if (!BO || !BO->isAdditiveOp()) 10154 break; 10155 10156 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10157 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10158 10159 if (isa<IntegerLiteral>(RHS)) 10160 Ex = LHS; 10161 else if (isa<IntegerLiteral>(LHS)) 10162 Ex = RHS; 10163 else 10164 break; 10165 } 10166 10167 return Ex; 10168 } 10169 10170 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10171 ASTContext &Context) { 10172 // Only handle constant-sized or VLAs, but not flexible members. 10173 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10174 // Only issue the FIXIT for arrays of size > 1. 10175 if (CAT->getSize().getSExtValue() <= 1) 10176 return false; 10177 } else if (!Ty->isVariableArrayType()) { 10178 return false; 10179 } 10180 return true; 10181 } 10182 10183 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10184 // be the size of the source, instead of the destination. 10185 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10186 IdentifierInfo *FnName) { 10187 10188 // Don't crash if the user has the wrong number of arguments 10189 unsigned NumArgs = Call->getNumArgs(); 10190 if ((NumArgs != 3) && (NumArgs != 4)) 10191 return; 10192 10193 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10194 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10195 const Expr *CompareWithSrc = nullptr; 10196 10197 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10198 Call->getBeginLoc(), Call->getRParenLoc())) 10199 return; 10200 10201 // Look for 'strlcpy(dst, x, sizeof(x))' 10202 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10203 CompareWithSrc = Ex; 10204 else { 10205 // Look for 'strlcpy(dst, x, strlen(x))' 10206 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10207 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10208 SizeCall->getNumArgs() == 1) 10209 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10210 } 10211 } 10212 10213 if (!CompareWithSrc) 10214 return; 10215 10216 // Determine if the argument to sizeof/strlen is equal to the source 10217 // argument. In principle there's all kinds of things you could do 10218 // here, for instance creating an == expression and evaluating it with 10219 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10220 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10221 if (!SrcArgDRE) 10222 return; 10223 10224 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10225 if (!CompareWithSrcDRE || 10226 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10227 return; 10228 10229 const Expr *OriginalSizeArg = Call->getArg(2); 10230 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10231 << OriginalSizeArg->getSourceRange() << FnName; 10232 10233 // Output a FIXIT hint if the destination is an array (rather than a 10234 // pointer to an array). This could be enhanced to handle some 10235 // pointers if we know the actual size, like if DstArg is 'array+2' 10236 // we could say 'sizeof(array)-2'. 10237 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10238 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10239 return; 10240 10241 SmallString<128> sizeString; 10242 llvm::raw_svector_ostream OS(sizeString); 10243 OS << "sizeof("; 10244 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10245 OS << ")"; 10246 10247 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10248 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10249 OS.str()); 10250 } 10251 10252 /// Check if two expressions refer to the same declaration. 10253 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10254 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10255 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10256 return D1->getDecl() == D2->getDecl(); 10257 return false; 10258 } 10259 10260 static const Expr *getStrlenExprArg(const Expr *E) { 10261 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10262 const FunctionDecl *FD = CE->getDirectCallee(); 10263 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10264 return nullptr; 10265 return CE->getArg(0)->IgnoreParenCasts(); 10266 } 10267 return nullptr; 10268 } 10269 10270 // Warn on anti-patterns as the 'size' argument to strncat. 10271 // The correct size argument should look like following: 10272 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10273 void Sema::CheckStrncatArguments(const CallExpr *CE, 10274 IdentifierInfo *FnName) { 10275 // Don't crash if the user has the wrong number of arguments. 10276 if (CE->getNumArgs() < 3) 10277 return; 10278 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10279 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10280 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10281 10282 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10283 CE->getRParenLoc())) 10284 return; 10285 10286 // Identify common expressions, which are wrongly used as the size argument 10287 // to strncat and may lead to buffer overflows. 10288 unsigned PatternType = 0; 10289 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10290 // - sizeof(dst) 10291 if (referToTheSameDecl(SizeOfArg, DstArg)) 10292 PatternType = 1; 10293 // - sizeof(src) 10294 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10295 PatternType = 2; 10296 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10297 if (BE->getOpcode() == BO_Sub) { 10298 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10299 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10300 // - sizeof(dst) - strlen(dst) 10301 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10302 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10303 PatternType = 1; 10304 // - sizeof(src) - (anything) 10305 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10306 PatternType = 2; 10307 } 10308 } 10309 10310 if (PatternType == 0) 10311 return; 10312 10313 // Generate the diagnostic. 10314 SourceLocation SL = LenArg->getBeginLoc(); 10315 SourceRange SR = LenArg->getSourceRange(); 10316 SourceManager &SM = getSourceManager(); 10317 10318 // If the function is defined as a builtin macro, do not show macro expansion. 10319 if (SM.isMacroArgExpansion(SL)) { 10320 SL = SM.getSpellingLoc(SL); 10321 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10322 SM.getSpellingLoc(SR.getEnd())); 10323 } 10324 10325 // Check if the destination is an array (rather than a pointer to an array). 10326 QualType DstTy = DstArg->getType(); 10327 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10328 Context); 10329 if (!isKnownSizeArray) { 10330 if (PatternType == 1) 10331 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10332 else 10333 Diag(SL, diag::warn_strncat_src_size) << SR; 10334 return; 10335 } 10336 10337 if (PatternType == 1) 10338 Diag(SL, diag::warn_strncat_large_size) << SR; 10339 else 10340 Diag(SL, diag::warn_strncat_src_size) << SR; 10341 10342 SmallString<128> sizeString; 10343 llvm::raw_svector_ostream OS(sizeString); 10344 OS << "sizeof("; 10345 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10346 OS << ") - "; 10347 OS << "strlen("; 10348 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10349 OS << ") - 1"; 10350 10351 Diag(SL, diag::note_strncat_wrong_size) 10352 << FixItHint::CreateReplacement(SR, OS.str()); 10353 } 10354 10355 namespace { 10356 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10357 const UnaryOperator *UnaryExpr, const Decl *D) { 10358 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10359 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10360 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10361 return; 10362 } 10363 } 10364 10365 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10366 const UnaryOperator *UnaryExpr) { 10367 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10368 const Decl *D = Lvalue->getDecl(); 10369 if (isa<VarDecl, FunctionDecl>(D)) 10370 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10371 } 10372 10373 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10374 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10375 Lvalue->getMemberDecl()); 10376 } 10377 10378 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10379 const UnaryOperator *UnaryExpr) { 10380 const auto *Lambda = dyn_cast<LambdaExpr>( 10381 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10382 if (!Lambda) 10383 return; 10384 10385 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10386 << CalleeName << 2 /*object: lambda expression*/; 10387 } 10388 10389 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10390 const DeclRefExpr *Lvalue) { 10391 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10392 if (Var == nullptr) 10393 return; 10394 10395 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10396 << CalleeName << 0 /*object: */ << Var; 10397 } 10398 10399 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10400 const CastExpr *Cast) { 10401 SmallString<128> SizeString; 10402 llvm::raw_svector_ostream OS(SizeString); 10403 10404 clang::CastKind Kind = Cast->getCastKind(); 10405 if (Kind == clang::CK_BitCast && 10406 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10407 return; 10408 if (Kind == clang::CK_IntegralToPointer && 10409 !isa<IntegerLiteral>( 10410 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10411 return; 10412 10413 switch (Cast->getCastKind()) { 10414 case clang::CK_BitCast: 10415 case clang::CK_IntegralToPointer: 10416 case clang::CK_FunctionToPointerDecay: 10417 OS << '\''; 10418 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10419 OS << '\''; 10420 break; 10421 default: 10422 return; 10423 } 10424 10425 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10426 << CalleeName << 0 /*object: */ << OS.str(); 10427 } 10428 } // namespace 10429 10430 /// Alerts the user that they are attempting to free a non-malloc'd object. 10431 void Sema::CheckFreeArguments(const CallExpr *E) { 10432 const std::string CalleeName = 10433 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10434 10435 { // Prefer something that doesn't involve a cast to make things simpler. 10436 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10437 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10438 switch (UnaryExpr->getOpcode()) { 10439 case UnaryOperator::Opcode::UO_AddrOf: 10440 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10441 case UnaryOperator::Opcode::UO_Plus: 10442 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10443 default: 10444 break; 10445 } 10446 10447 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10448 if (Lvalue->getType()->isArrayType()) 10449 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10450 10451 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10452 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10453 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10454 return; 10455 } 10456 10457 if (isa<BlockExpr>(Arg)) { 10458 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10459 << CalleeName << 1 /*object: block*/; 10460 return; 10461 } 10462 } 10463 // Maybe the cast was important, check after the other cases. 10464 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10465 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10466 } 10467 10468 void 10469 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10470 SourceLocation ReturnLoc, 10471 bool isObjCMethod, 10472 const AttrVec *Attrs, 10473 const FunctionDecl *FD) { 10474 // Check if the return value is null but should not be. 10475 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10476 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10477 CheckNonNullExpr(*this, RetValExp)) 10478 Diag(ReturnLoc, diag::warn_null_ret) 10479 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10480 10481 // C++11 [basic.stc.dynamic.allocation]p4: 10482 // If an allocation function declared with a non-throwing 10483 // exception-specification fails to allocate storage, it shall return 10484 // a null pointer. Any other allocation function that fails to allocate 10485 // storage shall indicate failure only by throwing an exception [...] 10486 if (FD) { 10487 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10488 if (Op == OO_New || Op == OO_Array_New) { 10489 const FunctionProtoType *Proto 10490 = FD->getType()->castAs<FunctionProtoType>(); 10491 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10492 CheckNonNullExpr(*this, RetValExp)) 10493 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10494 << FD << getLangOpts().CPlusPlus11; 10495 } 10496 } 10497 10498 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10499 // here prevent the user from using a PPC MMA type as trailing return type. 10500 if (Context.getTargetInfo().getTriple().isPPC64()) 10501 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10502 } 10503 10504 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10505 10506 /// Check for comparisons of floating point operands using != and ==. 10507 /// Issue a warning if these are no self-comparisons, as they are not likely 10508 /// to do what the programmer intended. 10509 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10510 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10511 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10512 10513 // Special case: check for x == x (which is OK). 10514 // Do not emit warnings for such cases. 10515 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10516 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10517 if (DRL->getDecl() == DRR->getDecl()) 10518 return; 10519 10520 // Special case: check for comparisons against literals that can be exactly 10521 // represented by APFloat. In such cases, do not emit a warning. This 10522 // is a heuristic: often comparison against such literals are used to 10523 // detect if a value in a variable has not changed. This clearly can 10524 // lead to false negatives. 10525 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10526 if (FLL->isExact()) 10527 return; 10528 } else 10529 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10530 if (FLR->isExact()) 10531 return; 10532 10533 // Check for comparisons with builtin types. 10534 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10535 if (CL->getBuiltinCallee()) 10536 return; 10537 10538 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10539 if (CR->getBuiltinCallee()) 10540 return; 10541 10542 // Emit the diagnostic. 10543 Diag(Loc, diag::warn_floatingpoint_eq) 10544 << LHS->getSourceRange() << RHS->getSourceRange(); 10545 } 10546 10547 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10548 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10549 10550 namespace { 10551 10552 /// Structure recording the 'active' range of an integer-valued 10553 /// expression. 10554 struct IntRange { 10555 /// The number of bits active in the int. Note that this includes exactly one 10556 /// sign bit if !NonNegative. 10557 unsigned Width; 10558 10559 /// True if the int is known not to have negative values. If so, all leading 10560 /// bits before Width are known zero, otherwise they are known to be the 10561 /// same as the MSB within Width. 10562 bool NonNegative; 10563 10564 IntRange(unsigned Width, bool NonNegative) 10565 : Width(Width), NonNegative(NonNegative) {} 10566 10567 /// Number of bits excluding the sign bit. 10568 unsigned valueBits() const { 10569 return NonNegative ? Width : Width - 1; 10570 } 10571 10572 /// Returns the range of the bool type. 10573 static IntRange forBoolType() { 10574 return IntRange(1, true); 10575 } 10576 10577 /// Returns the range of an opaque value of the given integral type. 10578 static IntRange forValueOfType(ASTContext &C, QualType T) { 10579 return forValueOfCanonicalType(C, 10580 T->getCanonicalTypeInternal().getTypePtr()); 10581 } 10582 10583 /// Returns the range of an opaque value of a canonical integral type. 10584 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10585 assert(T->isCanonicalUnqualified()); 10586 10587 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10588 T = VT->getElementType().getTypePtr(); 10589 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10590 T = CT->getElementType().getTypePtr(); 10591 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10592 T = AT->getValueType().getTypePtr(); 10593 10594 if (!C.getLangOpts().CPlusPlus) { 10595 // For enum types in C code, use the underlying datatype. 10596 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10597 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10598 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10599 // For enum types in C++, use the known bit width of the enumerators. 10600 EnumDecl *Enum = ET->getDecl(); 10601 // In C++11, enums can have a fixed underlying type. Use this type to 10602 // compute the range. 10603 if (Enum->isFixed()) { 10604 return IntRange(C.getIntWidth(QualType(T, 0)), 10605 !ET->isSignedIntegerOrEnumerationType()); 10606 } 10607 10608 unsigned NumPositive = Enum->getNumPositiveBits(); 10609 unsigned NumNegative = Enum->getNumNegativeBits(); 10610 10611 if (NumNegative == 0) 10612 return IntRange(NumPositive, true/*NonNegative*/); 10613 else 10614 return IntRange(std::max(NumPositive + 1, NumNegative), 10615 false/*NonNegative*/); 10616 } 10617 10618 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10619 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10620 10621 const BuiltinType *BT = cast<BuiltinType>(T); 10622 assert(BT->isInteger()); 10623 10624 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10625 } 10626 10627 /// Returns the "target" range of a canonical integral type, i.e. 10628 /// the range of values expressible in the type. 10629 /// 10630 /// This matches forValueOfCanonicalType except that enums have the 10631 /// full range of their type, not the range of their enumerators. 10632 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10633 assert(T->isCanonicalUnqualified()); 10634 10635 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10636 T = VT->getElementType().getTypePtr(); 10637 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10638 T = CT->getElementType().getTypePtr(); 10639 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10640 T = AT->getValueType().getTypePtr(); 10641 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10642 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10643 10644 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10645 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10646 10647 const BuiltinType *BT = cast<BuiltinType>(T); 10648 assert(BT->isInteger()); 10649 10650 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10651 } 10652 10653 /// Returns the supremum of two ranges: i.e. their conservative merge. 10654 static IntRange join(IntRange L, IntRange R) { 10655 bool Unsigned = L.NonNegative && R.NonNegative; 10656 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10657 L.NonNegative && R.NonNegative); 10658 } 10659 10660 /// Return the range of a bitwise-AND of the two ranges. 10661 static IntRange bit_and(IntRange L, IntRange R) { 10662 unsigned Bits = std::max(L.Width, R.Width); 10663 bool NonNegative = false; 10664 if (L.NonNegative) { 10665 Bits = std::min(Bits, L.Width); 10666 NonNegative = true; 10667 } 10668 if (R.NonNegative) { 10669 Bits = std::min(Bits, R.Width); 10670 NonNegative = true; 10671 } 10672 return IntRange(Bits, NonNegative); 10673 } 10674 10675 /// Return the range of a sum of the two ranges. 10676 static IntRange sum(IntRange L, IntRange R) { 10677 bool Unsigned = L.NonNegative && R.NonNegative; 10678 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10679 Unsigned); 10680 } 10681 10682 /// Return the range of a difference of the two ranges. 10683 static IntRange difference(IntRange L, IntRange R) { 10684 // We need a 1-bit-wider range if: 10685 // 1) LHS can be negative: least value can be reduced. 10686 // 2) RHS can be negative: greatest value can be increased. 10687 bool CanWiden = !L.NonNegative || !R.NonNegative; 10688 bool Unsigned = L.NonNegative && R.Width == 0; 10689 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10690 !Unsigned, 10691 Unsigned); 10692 } 10693 10694 /// Return the range of a product of the two ranges. 10695 static IntRange product(IntRange L, IntRange R) { 10696 // If both LHS and RHS can be negative, we can form 10697 // -2^L * -2^R = 2^(L + R) 10698 // which requires L + R + 1 value bits to represent. 10699 bool CanWiden = !L.NonNegative && !R.NonNegative; 10700 bool Unsigned = L.NonNegative && R.NonNegative; 10701 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10702 Unsigned); 10703 } 10704 10705 /// Return the range of a remainder operation between the two ranges. 10706 static IntRange rem(IntRange L, IntRange R) { 10707 // The result of a remainder can't be larger than the result of 10708 // either side. The sign of the result is the sign of the LHS. 10709 bool Unsigned = L.NonNegative; 10710 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10711 Unsigned); 10712 } 10713 }; 10714 10715 } // namespace 10716 10717 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10718 unsigned MaxWidth) { 10719 if (value.isSigned() && value.isNegative()) 10720 return IntRange(value.getMinSignedBits(), false); 10721 10722 if (value.getBitWidth() > MaxWidth) 10723 value = value.trunc(MaxWidth); 10724 10725 // isNonNegative() just checks the sign bit without considering 10726 // signedness. 10727 return IntRange(value.getActiveBits(), true); 10728 } 10729 10730 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10731 unsigned MaxWidth) { 10732 if (result.isInt()) 10733 return GetValueRange(C, result.getInt(), MaxWidth); 10734 10735 if (result.isVector()) { 10736 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10737 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10738 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10739 R = IntRange::join(R, El); 10740 } 10741 return R; 10742 } 10743 10744 if (result.isComplexInt()) { 10745 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10746 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10747 return IntRange::join(R, I); 10748 } 10749 10750 // This can happen with lossless casts to intptr_t of "based" lvalues. 10751 // Assume it might use arbitrary bits. 10752 // FIXME: The only reason we need to pass the type in here is to get 10753 // the sign right on this one case. It would be nice if APValue 10754 // preserved this. 10755 assert(result.isLValue() || result.isAddrLabelDiff()); 10756 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10757 } 10758 10759 static QualType GetExprType(const Expr *E) { 10760 QualType Ty = E->getType(); 10761 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10762 Ty = AtomicRHS->getValueType(); 10763 return Ty; 10764 } 10765 10766 /// Pseudo-evaluate the given integer expression, estimating the 10767 /// range of values it might take. 10768 /// 10769 /// \param MaxWidth The width to which the value will be truncated. 10770 /// \param Approximate If \c true, return a likely range for the result: in 10771 /// particular, assume that aritmetic on narrower types doesn't leave 10772 /// those types. If \c false, return a range including all possible 10773 /// result values. 10774 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10775 bool InConstantContext, bool Approximate) { 10776 E = E->IgnoreParens(); 10777 10778 // Try a full evaluation first. 10779 Expr::EvalResult result; 10780 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10781 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10782 10783 // I think we only want to look through implicit casts here; if the 10784 // user has an explicit widening cast, we should treat the value as 10785 // being of the new, wider type. 10786 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10787 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10788 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 10789 Approximate); 10790 10791 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10792 10793 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10794 CE->getCastKind() == CK_BooleanToSignedIntegral; 10795 10796 // Assume that non-integer casts can span the full range of the type. 10797 if (!isIntegerCast) 10798 return OutputTypeRange; 10799 10800 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10801 std::min(MaxWidth, OutputTypeRange.Width), 10802 InConstantContext, Approximate); 10803 10804 // Bail out if the subexpr's range is as wide as the cast type. 10805 if (SubRange.Width >= OutputTypeRange.Width) 10806 return OutputTypeRange; 10807 10808 // Otherwise, we take the smaller width, and we're non-negative if 10809 // either the output type or the subexpr is. 10810 return IntRange(SubRange.Width, 10811 SubRange.NonNegative || OutputTypeRange.NonNegative); 10812 } 10813 10814 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10815 // If we can fold the condition, just take that operand. 10816 bool CondResult; 10817 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10818 return GetExprRange(C, 10819 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10820 MaxWidth, InConstantContext, Approximate); 10821 10822 // Otherwise, conservatively merge. 10823 // GetExprRange requires an integer expression, but a throw expression 10824 // results in a void type. 10825 Expr *E = CO->getTrueExpr(); 10826 IntRange L = E->getType()->isVoidType() 10827 ? IntRange{0, true} 10828 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10829 E = CO->getFalseExpr(); 10830 IntRange R = E->getType()->isVoidType() 10831 ? IntRange{0, true} 10832 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10833 return IntRange::join(L, R); 10834 } 10835 10836 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10837 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 10838 10839 switch (BO->getOpcode()) { 10840 case BO_Cmp: 10841 llvm_unreachable("builtin <=> should have class type"); 10842 10843 // Boolean-valued operations are single-bit and positive. 10844 case BO_LAnd: 10845 case BO_LOr: 10846 case BO_LT: 10847 case BO_GT: 10848 case BO_LE: 10849 case BO_GE: 10850 case BO_EQ: 10851 case BO_NE: 10852 return IntRange::forBoolType(); 10853 10854 // The type of the assignments is the type of the LHS, so the RHS 10855 // is not necessarily the same type. 10856 case BO_MulAssign: 10857 case BO_DivAssign: 10858 case BO_RemAssign: 10859 case BO_AddAssign: 10860 case BO_SubAssign: 10861 case BO_XorAssign: 10862 case BO_OrAssign: 10863 // TODO: bitfields? 10864 return IntRange::forValueOfType(C, GetExprType(E)); 10865 10866 // Simple assignments just pass through the RHS, which will have 10867 // been coerced to the LHS type. 10868 case BO_Assign: 10869 // TODO: bitfields? 10870 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10871 Approximate); 10872 10873 // Operations with opaque sources are black-listed. 10874 case BO_PtrMemD: 10875 case BO_PtrMemI: 10876 return IntRange::forValueOfType(C, GetExprType(E)); 10877 10878 // Bitwise-and uses the *infinum* of the two source ranges. 10879 case BO_And: 10880 case BO_AndAssign: 10881 Combine = IntRange::bit_and; 10882 break; 10883 10884 // Left shift gets black-listed based on a judgement call. 10885 case BO_Shl: 10886 // ...except that we want to treat '1 << (blah)' as logically 10887 // positive. It's an important idiom. 10888 if (IntegerLiteral *I 10889 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10890 if (I->getValue() == 1) { 10891 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10892 return IntRange(R.Width, /*NonNegative*/ true); 10893 } 10894 } 10895 LLVM_FALLTHROUGH; 10896 10897 case BO_ShlAssign: 10898 return IntRange::forValueOfType(C, GetExprType(E)); 10899 10900 // Right shift by a constant can narrow its left argument. 10901 case BO_Shr: 10902 case BO_ShrAssign: { 10903 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 10904 Approximate); 10905 10906 // If the shift amount is a positive constant, drop the width by 10907 // that much. 10908 if (Optional<llvm::APSInt> shift = 10909 BO->getRHS()->getIntegerConstantExpr(C)) { 10910 if (shift->isNonNegative()) { 10911 unsigned zext = shift->getZExtValue(); 10912 if (zext >= L.Width) 10913 L.Width = (L.NonNegative ? 0 : 1); 10914 else 10915 L.Width -= zext; 10916 } 10917 } 10918 10919 return L; 10920 } 10921 10922 // Comma acts as its right operand. 10923 case BO_Comma: 10924 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10925 Approximate); 10926 10927 case BO_Add: 10928 if (!Approximate) 10929 Combine = IntRange::sum; 10930 break; 10931 10932 case BO_Sub: 10933 if (BO->getLHS()->getType()->isPointerType()) 10934 return IntRange::forValueOfType(C, GetExprType(E)); 10935 if (!Approximate) 10936 Combine = IntRange::difference; 10937 break; 10938 10939 case BO_Mul: 10940 if (!Approximate) 10941 Combine = IntRange::product; 10942 break; 10943 10944 // The width of a division result is mostly determined by the size 10945 // of the LHS. 10946 case BO_Div: { 10947 // Don't 'pre-truncate' the operands. 10948 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10949 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 10950 Approximate); 10951 10952 // If the divisor is constant, use that. 10953 if (Optional<llvm::APSInt> divisor = 10954 BO->getRHS()->getIntegerConstantExpr(C)) { 10955 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10956 if (log2 >= L.Width) 10957 L.Width = (L.NonNegative ? 0 : 1); 10958 else 10959 L.Width = std::min(L.Width - log2, MaxWidth); 10960 return L; 10961 } 10962 10963 // Otherwise, just use the LHS's width. 10964 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 10965 // could be -1. 10966 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 10967 Approximate); 10968 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10969 } 10970 10971 case BO_Rem: 10972 Combine = IntRange::rem; 10973 break; 10974 10975 // The default behavior is okay for these. 10976 case BO_Xor: 10977 case BO_Or: 10978 break; 10979 } 10980 10981 // Combine the two ranges, but limit the result to the type in which we 10982 // performed the computation. 10983 QualType T = GetExprType(E); 10984 unsigned opWidth = C.getIntWidth(T); 10985 IntRange L = 10986 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 10987 IntRange R = 10988 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 10989 IntRange C = Combine(L, R); 10990 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 10991 C.Width = std::min(C.Width, MaxWidth); 10992 return C; 10993 } 10994 10995 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10996 switch (UO->getOpcode()) { 10997 // Boolean-valued operations are white-listed. 10998 case UO_LNot: 10999 return IntRange::forBoolType(); 11000 11001 // Operations with opaque sources are black-listed. 11002 case UO_Deref: 11003 case UO_AddrOf: // should be impossible 11004 return IntRange::forValueOfType(C, GetExprType(E)); 11005 11006 default: 11007 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11008 Approximate); 11009 } 11010 } 11011 11012 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11013 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11014 Approximate); 11015 11016 if (const auto *BitField = E->getSourceBitField()) 11017 return IntRange(BitField->getBitWidthValue(C), 11018 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11019 11020 return IntRange::forValueOfType(C, GetExprType(E)); 11021 } 11022 11023 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11024 bool InConstantContext, bool Approximate) { 11025 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11026 Approximate); 11027 } 11028 11029 /// Checks whether the given value, which currently has the given 11030 /// source semantics, has the same value when coerced through the 11031 /// target semantics. 11032 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11033 const llvm::fltSemantics &Src, 11034 const llvm::fltSemantics &Tgt) { 11035 llvm::APFloat truncated = value; 11036 11037 bool ignored; 11038 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11039 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11040 11041 return truncated.bitwiseIsEqual(value); 11042 } 11043 11044 /// Checks whether the given value, which currently has the given 11045 /// source semantics, has the same value when coerced through the 11046 /// target semantics. 11047 /// 11048 /// The value might be a vector of floats (or a complex number). 11049 static bool IsSameFloatAfterCast(const APValue &value, 11050 const llvm::fltSemantics &Src, 11051 const llvm::fltSemantics &Tgt) { 11052 if (value.isFloat()) 11053 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11054 11055 if (value.isVector()) { 11056 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11057 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11058 return false; 11059 return true; 11060 } 11061 11062 assert(value.isComplexFloat()); 11063 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11064 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11065 } 11066 11067 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11068 bool IsListInit = false); 11069 11070 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11071 // Suppress cases where we are comparing against an enum constant. 11072 if (const DeclRefExpr *DR = 11073 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11074 if (isa<EnumConstantDecl>(DR->getDecl())) 11075 return true; 11076 11077 // Suppress cases where the value is expanded from a macro, unless that macro 11078 // is how a language represents a boolean literal. This is the case in both C 11079 // and Objective-C. 11080 SourceLocation BeginLoc = E->getBeginLoc(); 11081 if (BeginLoc.isMacroID()) { 11082 StringRef MacroName = Lexer::getImmediateMacroName( 11083 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11084 return MacroName != "YES" && MacroName != "NO" && 11085 MacroName != "true" && MacroName != "false"; 11086 } 11087 11088 return false; 11089 } 11090 11091 static bool isKnownToHaveUnsignedValue(Expr *E) { 11092 return E->getType()->isIntegerType() && 11093 (!E->getType()->isSignedIntegerType() || 11094 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11095 } 11096 11097 namespace { 11098 /// The promoted range of values of a type. In general this has the 11099 /// following structure: 11100 /// 11101 /// |-----------| . . . |-----------| 11102 /// ^ ^ ^ ^ 11103 /// Min HoleMin HoleMax Max 11104 /// 11105 /// ... where there is only a hole if a signed type is promoted to unsigned 11106 /// (in which case Min and Max are the smallest and largest representable 11107 /// values). 11108 struct PromotedRange { 11109 // Min, or HoleMax if there is a hole. 11110 llvm::APSInt PromotedMin; 11111 // Max, or HoleMin if there is a hole. 11112 llvm::APSInt PromotedMax; 11113 11114 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11115 if (R.Width == 0) 11116 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11117 else if (R.Width >= BitWidth && !Unsigned) { 11118 // Promotion made the type *narrower*. This happens when promoting 11119 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11120 // Treat all values of 'signed int' as being in range for now. 11121 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11122 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11123 } else { 11124 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11125 .extOrTrunc(BitWidth); 11126 PromotedMin.setIsUnsigned(Unsigned); 11127 11128 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11129 .extOrTrunc(BitWidth); 11130 PromotedMax.setIsUnsigned(Unsigned); 11131 } 11132 } 11133 11134 // Determine whether this range is contiguous (has no hole). 11135 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11136 11137 // Where a constant value is within the range. 11138 enum ComparisonResult { 11139 LT = 0x1, 11140 LE = 0x2, 11141 GT = 0x4, 11142 GE = 0x8, 11143 EQ = 0x10, 11144 NE = 0x20, 11145 InRangeFlag = 0x40, 11146 11147 Less = LE | LT | NE, 11148 Min = LE | InRangeFlag, 11149 InRange = InRangeFlag, 11150 Max = GE | InRangeFlag, 11151 Greater = GE | GT | NE, 11152 11153 OnlyValue = LE | GE | EQ | InRangeFlag, 11154 InHole = NE 11155 }; 11156 11157 ComparisonResult compare(const llvm::APSInt &Value) const { 11158 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11159 Value.isUnsigned() == PromotedMin.isUnsigned()); 11160 if (!isContiguous()) { 11161 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11162 if (Value.isMinValue()) return Min; 11163 if (Value.isMaxValue()) return Max; 11164 if (Value >= PromotedMin) return InRange; 11165 if (Value <= PromotedMax) return InRange; 11166 return InHole; 11167 } 11168 11169 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11170 case -1: return Less; 11171 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11172 case 1: 11173 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11174 case -1: return InRange; 11175 case 0: return Max; 11176 case 1: return Greater; 11177 } 11178 } 11179 11180 llvm_unreachable("impossible compare result"); 11181 } 11182 11183 static llvm::Optional<StringRef> 11184 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11185 if (Op == BO_Cmp) { 11186 ComparisonResult LTFlag = LT, GTFlag = GT; 11187 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11188 11189 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11190 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11191 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11192 return llvm::None; 11193 } 11194 11195 ComparisonResult TrueFlag, FalseFlag; 11196 if (Op == BO_EQ) { 11197 TrueFlag = EQ; 11198 FalseFlag = NE; 11199 } else if (Op == BO_NE) { 11200 TrueFlag = NE; 11201 FalseFlag = EQ; 11202 } else { 11203 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11204 TrueFlag = LT; 11205 FalseFlag = GE; 11206 } else { 11207 TrueFlag = GT; 11208 FalseFlag = LE; 11209 } 11210 if (Op == BO_GE || Op == BO_LE) 11211 std::swap(TrueFlag, FalseFlag); 11212 } 11213 if (R & TrueFlag) 11214 return StringRef("true"); 11215 if (R & FalseFlag) 11216 return StringRef("false"); 11217 return llvm::None; 11218 } 11219 }; 11220 } 11221 11222 static bool HasEnumType(Expr *E) { 11223 // Strip off implicit integral promotions. 11224 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11225 if (ICE->getCastKind() != CK_IntegralCast && 11226 ICE->getCastKind() != CK_NoOp) 11227 break; 11228 E = ICE->getSubExpr(); 11229 } 11230 11231 return E->getType()->isEnumeralType(); 11232 } 11233 11234 static int classifyConstantValue(Expr *Constant) { 11235 // The values of this enumeration are used in the diagnostics 11236 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11237 enum ConstantValueKind { 11238 Miscellaneous = 0, 11239 LiteralTrue, 11240 LiteralFalse 11241 }; 11242 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11243 return BL->getValue() ? ConstantValueKind::LiteralTrue 11244 : ConstantValueKind::LiteralFalse; 11245 return ConstantValueKind::Miscellaneous; 11246 } 11247 11248 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11249 Expr *Constant, Expr *Other, 11250 const llvm::APSInt &Value, 11251 bool RhsConstant) { 11252 if (S.inTemplateInstantiation()) 11253 return false; 11254 11255 Expr *OriginalOther = Other; 11256 11257 Constant = Constant->IgnoreParenImpCasts(); 11258 Other = Other->IgnoreParenImpCasts(); 11259 11260 // Suppress warnings on tautological comparisons between values of the same 11261 // enumeration type. There are only two ways we could warn on this: 11262 // - If the constant is outside the range of representable values of 11263 // the enumeration. In such a case, we should warn about the cast 11264 // to enumeration type, not about the comparison. 11265 // - If the constant is the maximum / minimum in-range value. For an 11266 // enumeratin type, such comparisons can be meaningful and useful. 11267 if (Constant->getType()->isEnumeralType() && 11268 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11269 return false; 11270 11271 IntRange OtherValueRange = GetExprRange( 11272 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11273 11274 QualType OtherT = Other->getType(); 11275 if (const auto *AT = OtherT->getAs<AtomicType>()) 11276 OtherT = AT->getValueType(); 11277 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11278 11279 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11280 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11281 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11282 S.NSAPIObj->isObjCBOOLType(OtherT) && 11283 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11284 11285 // Whether we're treating Other as being a bool because of the form of 11286 // expression despite it having another type (typically 'int' in C). 11287 bool OtherIsBooleanDespiteType = 11288 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11289 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11290 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11291 11292 // Check if all values in the range of possible values of this expression 11293 // lead to the same comparison outcome. 11294 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11295 Value.isUnsigned()); 11296 auto Cmp = OtherPromotedValueRange.compare(Value); 11297 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11298 if (!Result) 11299 return false; 11300 11301 // Also consider the range determined by the type alone. This allows us to 11302 // classify the warning under the proper diagnostic group. 11303 bool TautologicalTypeCompare = false; 11304 { 11305 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11306 Value.isUnsigned()); 11307 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11308 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11309 RhsConstant)) { 11310 TautologicalTypeCompare = true; 11311 Cmp = TypeCmp; 11312 Result = TypeResult; 11313 } 11314 } 11315 11316 // Don't warn if the non-constant operand actually always evaluates to the 11317 // same value. 11318 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11319 return false; 11320 11321 // Suppress the diagnostic for an in-range comparison if the constant comes 11322 // from a macro or enumerator. We don't want to diagnose 11323 // 11324 // some_long_value <= INT_MAX 11325 // 11326 // when sizeof(int) == sizeof(long). 11327 bool InRange = Cmp & PromotedRange::InRangeFlag; 11328 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11329 return false; 11330 11331 // A comparison of an unsigned bit-field against 0 is really a type problem, 11332 // even though at the type level the bit-field might promote to 'signed int'. 11333 if (Other->refersToBitField() && InRange && Value == 0 && 11334 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11335 TautologicalTypeCompare = true; 11336 11337 // If this is a comparison to an enum constant, include that 11338 // constant in the diagnostic. 11339 const EnumConstantDecl *ED = nullptr; 11340 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11341 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11342 11343 // Should be enough for uint128 (39 decimal digits) 11344 SmallString<64> PrettySourceValue; 11345 llvm::raw_svector_ostream OS(PrettySourceValue); 11346 if (ED) { 11347 OS << '\'' << *ED << "' (" << Value << ")"; 11348 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11349 Constant->IgnoreParenImpCasts())) { 11350 OS << (BL->getValue() ? "YES" : "NO"); 11351 } else { 11352 OS << Value; 11353 } 11354 11355 if (!TautologicalTypeCompare) { 11356 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11357 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11358 << E->getOpcodeStr() << OS.str() << *Result 11359 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11360 return true; 11361 } 11362 11363 if (IsObjCSignedCharBool) { 11364 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11365 S.PDiag(diag::warn_tautological_compare_objc_bool) 11366 << OS.str() << *Result); 11367 return true; 11368 } 11369 11370 // FIXME: We use a somewhat different formatting for the in-range cases and 11371 // cases involving boolean values for historical reasons. We should pick a 11372 // consistent way of presenting these diagnostics. 11373 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11374 11375 S.DiagRuntimeBehavior( 11376 E->getOperatorLoc(), E, 11377 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11378 : diag::warn_tautological_bool_compare) 11379 << OS.str() << classifyConstantValue(Constant) << OtherT 11380 << OtherIsBooleanDespiteType << *Result 11381 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11382 } else { 11383 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11384 ? (HasEnumType(OriginalOther) 11385 ? diag::warn_unsigned_enum_always_true_comparison 11386 : diag::warn_unsigned_always_true_comparison) 11387 : diag::warn_tautological_constant_compare; 11388 11389 S.Diag(E->getOperatorLoc(), Diag) 11390 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11391 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11392 } 11393 11394 return true; 11395 } 11396 11397 /// Analyze the operands of the given comparison. Implements the 11398 /// fallback case from AnalyzeComparison. 11399 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11400 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11401 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11402 } 11403 11404 /// Implements -Wsign-compare. 11405 /// 11406 /// \param E the binary operator to check for warnings 11407 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11408 // The type the comparison is being performed in. 11409 QualType T = E->getLHS()->getType(); 11410 11411 // Only analyze comparison operators where both sides have been converted to 11412 // the same type. 11413 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11414 return AnalyzeImpConvsInComparison(S, E); 11415 11416 // Don't analyze value-dependent comparisons directly. 11417 if (E->isValueDependent()) 11418 return AnalyzeImpConvsInComparison(S, E); 11419 11420 Expr *LHS = E->getLHS(); 11421 Expr *RHS = E->getRHS(); 11422 11423 if (T->isIntegralType(S.Context)) { 11424 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11425 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11426 11427 // We don't care about expressions whose result is a constant. 11428 if (RHSValue && LHSValue) 11429 return AnalyzeImpConvsInComparison(S, E); 11430 11431 // We only care about expressions where just one side is literal 11432 if ((bool)RHSValue ^ (bool)LHSValue) { 11433 // Is the constant on the RHS or LHS? 11434 const bool RhsConstant = (bool)RHSValue; 11435 Expr *Const = RhsConstant ? RHS : LHS; 11436 Expr *Other = RhsConstant ? LHS : RHS; 11437 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11438 11439 // Check whether an integer constant comparison results in a value 11440 // of 'true' or 'false'. 11441 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11442 return AnalyzeImpConvsInComparison(S, E); 11443 } 11444 } 11445 11446 if (!T->hasUnsignedIntegerRepresentation()) { 11447 // We don't do anything special if this isn't an unsigned integral 11448 // comparison: we're only interested in integral comparisons, and 11449 // signed comparisons only happen in cases we don't care to warn about. 11450 return AnalyzeImpConvsInComparison(S, E); 11451 } 11452 11453 LHS = LHS->IgnoreParenImpCasts(); 11454 RHS = RHS->IgnoreParenImpCasts(); 11455 11456 if (!S.getLangOpts().CPlusPlus) { 11457 // Avoid warning about comparison of integers with different signs when 11458 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11459 // the type of `E`. 11460 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11461 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11462 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11463 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11464 } 11465 11466 // Check to see if one of the (unmodified) operands is of different 11467 // signedness. 11468 Expr *signedOperand, *unsignedOperand; 11469 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11470 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11471 "unsigned comparison between two signed integer expressions?"); 11472 signedOperand = LHS; 11473 unsignedOperand = RHS; 11474 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11475 signedOperand = RHS; 11476 unsignedOperand = LHS; 11477 } else { 11478 return AnalyzeImpConvsInComparison(S, E); 11479 } 11480 11481 // Otherwise, calculate the effective range of the signed operand. 11482 IntRange signedRange = GetExprRange( 11483 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11484 11485 // Go ahead and analyze implicit conversions in the operands. Note 11486 // that we skip the implicit conversions on both sides. 11487 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11488 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11489 11490 // If the signed range is non-negative, -Wsign-compare won't fire. 11491 if (signedRange.NonNegative) 11492 return; 11493 11494 // For (in)equality comparisons, if the unsigned operand is a 11495 // constant which cannot collide with a overflowed signed operand, 11496 // then reinterpreting the signed operand as unsigned will not 11497 // change the result of the comparison. 11498 if (E->isEqualityOp()) { 11499 unsigned comparisonWidth = S.Context.getIntWidth(T); 11500 IntRange unsignedRange = 11501 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11502 /*Approximate*/ true); 11503 11504 // We should never be unable to prove that the unsigned operand is 11505 // non-negative. 11506 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11507 11508 if (unsignedRange.Width < comparisonWidth) 11509 return; 11510 } 11511 11512 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11513 S.PDiag(diag::warn_mixed_sign_comparison) 11514 << LHS->getType() << RHS->getType() 11515 << LHS->getSourceRange() << RHS->getSourceRange()); 11516 } 11517 11518 /// Analyzes an attempt to assign the given value to a bitfield. 11519 /// 11520 /// Returns true if there was something fishy about the attempt. 11521 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11522 SourceLocation InitLoc) { 11523 assert(Bitfield->isBitField()); 11524 if (Bitfield->isInvalidDecl()) 11525 return false; 11526 11527 // White-list bool bitfields. 11528 QualType BitfieldType = Bitfield->getType(); 11529 if (BitfieldType->isBooleanType()) 11530 return false; 11531 11532 if (BitfieldType->isEnumeralType()) { 11533 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11534 // If the underlying enum type was not explicitly specified as an unsigned 11535 // type and the enum contain only positive values, MSVC++ will cause an 11536 // inconsistency by storing this as a signed type. 11537 if (S.getLangOpts().CPlusPlus11 && 11538 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11539 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11540 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11541 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11542 << BitfieldEnumDecl; 11543 } 11544 } 11545 11546 if (Bitfield->getType()->isBooleanType()) 11547 return false; 11548 11549 // Ignore value- or type-dependent expressions. 11550 if (Bitfield->getBitWidth()->isValueDependent() || 11551 Bitfield->getBitWidth()->isTypeDependent() || 11552 Init->isValueDependent() || 11553 Init->isTypeDependent()) 11554 return false; 11555 11556 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11557 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11558 11559 Expr::EvalResult Result; 11560 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11561 Expr::SE_AllowSideEffects)) { 11562 // The RHS is not constant. If the RHS has an enum type, make sure the 11563 // bitfield is wide enough to hold all the values of the enum without 11564 // truncation. 11565 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11566 EnumDecl *ED = EnumTy->getDecl(); 11567 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11568 11569 // Enum types are implicitly signed on Windows, so check if there are any 11570 // negative enumerators to see if the enum was intended to be signed or 11571 // not. 11572 bool SignedEnum = ED->getNumNegativeBits() > 0; 11573 11574 // Check for surprising sign changes when assigning enum values to a 11575 // bitfield of different signedness. If the bitfield is signed and we 11576 // have exactly the right number of bits to store this unsigned enum, 11577 // suggest changing the enum to an unsigned type. This typically happens 11578 // on Windows where unfixed enums always use an underlying type of 'int'. 11579 unsigned DiagID = 0; 11580 if (SignedEnum && !SignedBitfield) { 11581 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11582 } else if (SignedBitfield && !SignedEnum && 11583 ED->getNumPositiveBits() == FieldWidth) { 11584 DiagID = diag::warn_signed_bitfield_enum_conversion; 11585 } 11586 11587 if (DiagID) { 11588 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11589 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11590 SourceRange TypeRange = 11591 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11592 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11593 << SignedEnum << TypeRange; 11594 } 11595 11596 // Compute the required bitwidth. If the enum has negative values, we need 11597 // one more bit than the normal number of positive bits to represent the 11598 // sign bit. 11599 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11600 ED->getNumNegativeBits()) 11601 : ED->getNumPositiveBits(); 11602 11603 // Check the bitwidth. 11604 if (BitsNeeded > FieldWidth) { 11605 Expr *WidthExpr = Bitfield->getBitWidth(); 11606 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11607 << Bitfield << ED; 11608 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11609 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11610 } 11611 } 11612 11613 return false; 11614 } 11615 11616 llvm::APSInt Value = Result.Val.getInt(); 11617 11618 unsigned OriginalWidth = Value.getBitWidth(); 11619 11620 if (!Value.isSigned() || Value.isNegative()) 11621 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11622 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11623 OriginalWidth = Value.getMinSignedBits(); 11624 11625 if (OriginalWidth <= FieldWidth) 11626 return false; 11627 11628 // Compute the value which the bitfield will contain. 11629 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11630 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11631 11632 // Check whether the stored value is equal to the original value. 11633 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11634 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11635 return false; 11636 11637 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11638 // therefore don't strictly fit into a signed bitfield of width 1. 11639 if (FieldWidth == 1 && Value == 1) 11640 return false; 11641 11642 std::string PrettyValue = Value.toString(10); 11643 std::string PrettyTrunc = TruncatedValue.toString(10); 11644 11645 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11646 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11647 << Init->getSourceRange(); 11648 11649 return true; 11650 } 11651 11652 /// Analyze the given simple or compound assignment for warning-worthy 11653 /// operations. 11654 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11655 // Just recurse on the LHS. 11656 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11657 11658 // We want to recurse on the RHS as normal unless we're assigning to 11659 // a bitfield. 11660 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11661 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11662 E->getOperatorLoc())) { 11663 // Recurse, ignoring any implicit conversions on the RHS. 11664 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11665 E->getOperatorLoc()); 11666 } 11667 } 11668 11669 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11670 11671 // Diagnose implicitly sequentially-consistent atomic assignment. 11672 if (E->getLHS()->getType()->isAtomicType()) 11673 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11674 } 11675 11676 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11677 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11678 SourceLocation CContext, unsigned diag, 11679 bool pruneControlFlow = false) { 11680 if (pruneControlFlow) { 11681 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11682 S.PDiag(diag) 11683 << SourceType << T << E->getSourceRange() 11684 << SourceRange(CContext)); 11685 return; 11686 } 11687 S.Diag(E->getExprLoc(), diag) 11688 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11689 } 11690 11691 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11692 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11693 SourceLocation CContext, 11694 unsigned diag, bool pruneControlFlow = false) { 11695 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11696 } 11697 11698 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11699 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11700 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11701 } 11702 11703 static void adornObjCBoolConversionDiagWithTernaryFixit( 11704 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11705 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11706 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11707 Ignored = OVE->getSourceExpr(); 11708 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11709 isa<BinaryOperator>(Ignored) || 11710 isa<CXXOperatorCallExpr>(Ignored); 11711 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11712 if (NeedsParens) 11713 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11714 << FixItHint::CreateInsertion(EndLoc, ")"); 11715 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11716 } 11717 11718 /// Diagnose an implicit cast from a floating point value to an integer value. 11719 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11720 SourceLocation CContext) { 11721 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11722 const bool PruneWarnings = S.inTemplateInstantiation(); 11723 11724 Expr *InnerE = E->IgnoreParenImpCasts(); 11725 // We also want to warn on, e.g., "int i = -1.234" 11726 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11727 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11728 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11729 11730 const bool IsLiteral = 11731 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11732 11733 llvm::APFloat Value(0.0); 11734 bool IsConstant = 11735 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11736 if (!IsConstant) { 11737 if (isObjCSignedCharBool(S, T)) { 11738 return adornObjCBoolConversionDiagWithTernaryFixit( 11739 S, E, 11740 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11741 << E->getType()); 11742 } 11743 11744 return DiagnoseImpCast(S, E, T, CContext, 11745 diag::warn_impcast_float_integer, PruneWarnings); 11746 } 11747 11748 bool isExact = false; 11749 11750 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11751 T->hasUnsignedIntegerRepresentation()); 11752 llvm::APFloat::opStatus Result = Value.convertToInteger( 11753 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11754 11755 // FIXME: Force the precision of the source value down so we don't print 11756 // digits which are usually useless (we don't really care here if we 11757 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11758 // would automatically print the shortest representation, but it's a bit 11759 // tricky to implement. 11760 SmallString<16> PrettySourceValue; 11761 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11762 precision = (precision * 59 + 195) / 196; 11763 Value.toString(PrettySourceValue, precision); 11764 11765 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11766 return adornObjCBoolConversionDiagWithTernaryFixit( 11767 S, E, 11768 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11769 << PrettySourceValue); 11770 } 11771 11772 if (Result == llvm::APFloat::opOK && isExact) { 11773 if (IsLiteral) return; 11774 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11775 PruneWarnings); 11776 } 11777 11778 // Conversion of a floating-point value to a non-bool integer where the 11779 // integral part cannot be represented by the integer type is undefined. 11780 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11781 return DiagnoseImpCast( 11782 S, E, T, CContext, 11783 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11784 : diag::warn_impcast_float_to_integer_out_of_range, 11785 PruneWarnings); 11786 11787 unsigned DiagID = 0; 11788 if (IsLiteral) { 11789 // Warn on floating point literal to integer. 11790 DiagID = diag::warn_impcast_literal_float_to_integer; 11791 } else if (IntegerValue == 0) { 11792 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11793 return DiagnoseImpCast(S, E, T, CContext, 11794 diag::warn_impcast_float_integer, PruneWarnings); 11795 } 11796 // Warn on non-zero to zero conversion. 11797 DiagID = diag::warn_impcast_float_to_integer_zero; 11798 } else { 11799 if (IntegerValue.isUnsigned()) { 11800 if (!IntegerValue.isMaxValue()) { 11801 return DiagnoseImpCast(S, E, T, CContext, 11802 diag::warn_impcast_float_integer, PruneWarnings); 11803 } 11804 } else { // IntegerValue.isSigned() 11805 if (!IntegerValue.isMaxSignedValue() && 11806 !IntegerValue.isMinSignedValue()) { 11807 return DiagnoseImpCast(S, E, T, CContext, 11808 diag::warn_impcast_float_integer, PruneWarnings); 11809 } 11810 } 11811 // Warn on evaluatable floating point expression to integer conversion. 11812 DiagID = diag::warn_impcast_float_to_integer; 11813 } 11814 11815 SmallString<16> PrettyTargetValue; 11816 if (IsBool) 11817 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11818 else 11819 IntegerValue.toString(PrettyTargetValue); 11820 11821 if (PruneWarnings) { 11822 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11823 S.PDiag(DiagID) 11824 << E->getType() << T.getUnqualifiedType() 11825 << PrettySourceValue << PrettyTargetValue 11826 << E->getSourceRange() << SourceRange(CContext)); 11827 } else { 11828 S.Diag(E->getExprLoc(), DiagID) 11829 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11830 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11831 } 11832 } 11833 11834 /// Analyze the given compound assignment for the possible losing of 11835 /// floating-point precision. 11836 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11837 assert(isa<CompoundAssignOperator>(E) && 11838 "Must be compound assignment operation"); 11839 // Recurse on the LHS and RHS in here 11840 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11841 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11842 11843 if (E->getLHS()->getType()->isAtomicType()) 11844 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11845 11846 // Now check the outermost expression 11847 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11848 const auto *RBT = cast<CompoundAssignOperator>(E) 11849 ->getComputationResultType() 11850 ->getAs<BuiltinType>(); 11851 11852 // The below checks assume source is floating point. 11853 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11854 11855 // If source is floating point but target is an integer. 11856 if (ResultBT->isInteger()) 11857 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11858 E->getExprLoc(), diag::warn_impcast_float_integer); 11859 11860 if (!ResultBT->isFloatingPoint()) 11861 return; 11862 11863 // If both source and target are floating points, warn about losing precision. 11864 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11865 QualType(ResultBT, 0), QualType(RBT, 0)); 11866 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11867 // warn about dropping FP rank. 11868 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11869 diag::warn_impcast_float_result_precision); 11870 } 11871 11872 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11873 IntRange Range) { 11874 if (!Range.Width) return "0"; 11875 11876 llvm::APSInt ValueInRange = Value; 11877 ValueInRange.setIsSigned(!Range.NonNegative); 11878 ValueInRange = ValueInRange.trunc(Range.Width); 11879 return ValueInRange.toString(10); 11880 } 11881 11882 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11883 if (!isa<ImplicitCastExpr>(Ex)) 11884 return false; 11885 11886 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11887 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11888 const Type *Source = 11889 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11890 if (Target->isDependentType()) 11891 return false; 11892 11893 const BuiltinType *FloatCandidateBT = 11894 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11895 const Type *BoolCandidateType = ToBool ? Target : Source; 11896 11897 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11898 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11899 } 11900 11901 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11902 SourceLocation CC) { 11903 unsigned NumArgs = TheCall->getNumArgs(); 11904 for (unsigned i = 0; i < NumArgs; ++i) { 11905 Expr *CurrA = TheCall->getArg(i); 11906 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11907 continue; 11908 11909 bool IsSwapped = ((i > 0) && 11910 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11911 IsSwapped |= ((i < (NumArgs - 1)) && 11912 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11913 if (IsSwapped) { 11914 // Warn on this floating-point to bool conversion. 11915 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11916 CurrA->getType(), CC, 11917 diag::warn_impcast_floating_point_to_bool); 11918 } 11919 } 11920 } 11921 11922 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11923 SourceLocation CC) { 11924 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11925 E->getExprLoc())) 11926 return; 11927 11928 // Don't warn on functions which have return type nullptr_t. 11929 if (isa<CallExpr>(E)) 11930 return; 11931 11932 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11933 const Expr::NullPointerConstantKind NullKind = 11934 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11935 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11936 return; 11937 11938 // Return if target type is a safe conversion. 11939 if (T->isAnyPointerType() || T->isBlockPointerType() || 11940 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11941 return; 11942 11943 SourceLocation Loc = E->getSourceRange().getBegin(); 11944 11945 // Venture through the macro stacks to get to the source of macro arguments. 11946 // The new location is a better location than the complete location that was 11947 // passed in. 11948 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11949 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11950 11951 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11952 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11953 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11954 Loc, S.SourceMgr, S.getLangOpts()); 11955 if (MacroName == "NULL") 11956 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11957 } 11958 11959 // Only warn if the null and context location are in the same macro expansion. 11960 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11961 return; 11962 11963 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11964 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11965 << FixItHint::CreateReplacement(Loc, 11966 S.getFixItZeroLiteralForType(T, Loc)); 11967 } 11968 11969 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11970 ObjCArrayLiteral *ArrayLiteral); 11971 11972 static void 11973 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11974 ObjCDictionaryLiteral *DictionaryLiteral); 11975 11976 /// Check a single element within a collection literal against the 11977 /// target element type. 11978 static void checkObjCCollectionLiteralElement(Sema &S, 11979 QualType TargetElementType, 11980 Expr *Element, 11981 unsigned ElementKind) { 11982 // Skip a bitcast to 'id' or qualified 'id'. 11983 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11984 if (ICE->getCastKind() == CK_BitCast && 11985 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11986 Element = ICE->getSubExpr(); 11987 } 11988 11989 QualType ElementType = Element->getType(); 11990 ExprResult ElementResult(Element); 11991 if (ElementType->getAs<ObjCObjectPointerType>() && 11992 S.CheckSingleAssignmentConstraints(TargetElementType, 11993 ElementResult, 11994 false, false) 11995 != Sema::Compatible) { 11996 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11997 << ElementType << ElementKind << TargetElementType 11998 << Element->getSourceRange(); 11999 } 12000 12001 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12002 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12003 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12004 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12005 } 12006 12007 /// Check an Objective-C array literal being converted to the given 12008 /// target type. 12009 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12010 ObjCArrayLiteral *ArrayLiteral) { 12011 if (!S.NSArrayDecl) 12012 return; 12013 12014 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12015 if (!TargetObjCPtr) 12016 return; 12017 12018 if (TargetObjCPtr->isUnspecialized() || 12019 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12020 != S.NSArrayDecl->getCanonicalDecl()) 12021 return; 12022 12023 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12024 if (TypeArgs.size() != 1) 12025 return; 12026 12027 QualType TargetElementType = TypeArgs[0]; 12028 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12029 checkObjCCollectionLiteralElement(S, TargetElementType, 12030 ArrayLiteral->getElement(I), 12031 0); 12032 } 12033 } 12034 12035 /// Check an Objective-C dictionary literal being converted to the given 12036 /// target type. 12037 static void 12038 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12039 ObjCDictionaryLiteral *DictionaryLiteral) { 12040 if (!S.NSDictionaryDecl) 12041 return; 12042 12043 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12044 if (!TargetObjCPtr) 12045 return; 12046 12047 if (TargetObjCPtr->isUnspecialized() || 12048 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12049 != S.NSDictionaryDecl->getCanonicalDecl()) 12050 return; 12051 12052 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12053 if (TypeArgs.size() != 2) 12054 return; 12055 12056 QualType TargetKeyType = TypeArgs[0]; 12057 QualType TargetObjectType = TypeArgs[1]; 12058 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12059 auto Element = DictionaryLiteral->getKeyValueElement(I); 12060 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12061 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12062 } 12063 } 12064 12065 // Helper function to filter out cases for constant width constant conversion. 12066 // Don't warn on char array initialization or for non-decimal values. 12067 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12068 SourceLocation CC) { 12069 // If initializing from a constant, and the constant starts with '0', 12070 // then it is a binary, octal, or hexadecimal. Allow these constants 12071 // to fill all the bits, even if there is a sign change. 12072 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12073 const char FirstLiteralCharacter = 12074 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12075 if (FirstLiteralCharacter == '0') 12076 return false; 12077 } 12078 12079 // If the CC location points to a '{', and the type is char, then assume 12080 // assume it is an array initialization. 12081 if (CC.isValid() && T->isCharType()) { 12082 const char FirstContextCharacter = 12083 S.getSourceManager().getCharacterData(CC)[0]; 12084 if (FirstContextCharacter == '{') 12085 return false; 12086 } 12087 12088 return true; 12089 } 12090 12091 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12092 const auto *IL = dyn_cast<IntegerLiteral>(E); 12093 if (!IL) { 12094 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12095 if (UO->getOpcode() == UO_Minus) 12096 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12097 } 12098 } 12099 12100 return IL; 12101 } 12102 12103 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12104 E = E->IgnoreParenImpCasts(); 12105 SourceLocation ExprLoc = E->getExprLoc(); 12106 12107 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12108 BinaryOperator::Opcode Opc = BO->getOpcode(); 12109 Expr::EvalResult Result; 12110 // Do not diagnose unsigned shifts. 12111 if (Opc == BO_Shl) { 12112 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12113 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12114 if (LHS && LHS->getValue() == 0) 12115 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12116 else if (!E->isValueDependent() && LHS && RHS && 12117 RHS->getValue().isNonNegative() && 12118 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12119 S.Diag(ExprLoc, diag::warn_left_shift_always) 12120 << (Result.Val.getInt() != 0); 12121 else if (E->getType()->isSignedIntegerType()) 12122 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12123 } 12124 } 12125 12126 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12127 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12128 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12129 if (!LHS || !RHS) 12130 return; 12131 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12132 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12133 // Do not diagnose common idioms. 12134 return; 12135 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12136 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12137 } 12138 } 12139 12140 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12141 SourceLocation CC, 12142 bool *ICContext = nullptr, 12143 bool IsListInit = false) { 12144 if (E->isTypeDependent() || E->isValueDependent()) return; 12145 12146 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12147 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12148 if (Source == Target) return; 12149 if (Target->isDependentType()) return; 12150 12151 // If the conversion context location is invalid don't complain. We also 12152 // don't want to emit a warning if the issue occurs from the expansion of 12153 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12154 // delay this check as long as possible. Once we detect we are in that 12155 // scenario, we just return. 12156 if (CC.isInvalid()) 12157 return; 12158 12159 if (Source->isAtomicType()) 12160 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12161 12162 // Diagnose implicit casts to bool. 12163 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12164 if (isa<StringLiteral>(E)) 12165 // Warn on string literal to bool. Checks for string literals in logical 12166 // and expressions, for instance, assert(0 && "error here"), are 12167 // prevented by a check in AnalyzeImplicitConversions(). 12168 return DiagnoseImpCast(S, E, T, CC, 12169 diag::warn_impcast_string_literal_to_bool); 12170 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12171 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12172 // This covers the literal expressions that evaluate to Objective-C 12173 // objects. 12174 return DiagnoseImpCast(S, E, T, CC, 12175 diag::warn_impcast_objective_c_literal_to_bool); 12176 } 12177 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12178 // Warn on pointer to bool conversion that is always true. 12179 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12180 SourceRange(CC)); 12181 } 12182 } 12183 12184 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12185 // is a typedef for signed char (macOS), then that constant value has to be 1 12186 // or 0. 12187 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12188 Expr::EvalResult Result; 12189 if (E->EvaluateAsInt(Result, S.getASTContext(), 12190 Expr::SE_AllowSideEffects)) { 12191 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12192 adornObjCBoolConversionDiagWithTernaryFixit( 12193 S, E, 12194 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12195 << Result.Val.getInt().toString(10)); 12196 } 12197 return; 12198 } 12199 } 12200 12201 // Check implicit casts from Objective-C collection literals to specialized 12202 // collection types, e.g., NSArray<NSString *> *. 12203 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12204 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12205 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12206 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12207 12208 // Strip vector types. 12209 if (const auto *SourceVT = dyn_cast<VectorType>(Source)) { 12210 if (Target->isVLSTBuiltinType()) { 12211 auto SourceVectorKind = SourceVT->getVectorKind(); 12212 if (SourceVectorKind == VectorType::SveFixedLengthDataVector || 12213 SourceVectorKind == VectorType::SveFixedLengthPredicateVector || 12214 (SourceVectorKind == VectorType::GenericVector && 12215 S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits)) 12216 return; 12217 } 12218 12219 if (!isa<VectorType>(Target)) { 12220 if (S.SourceMgr.isInSystemMacro(CC)) 12221 return; 12222 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12223 } 12224 12225 // If the vector cast is cast between two vectors of the same size, it is 12226 // a bitcast, not a conversion. 12227 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12228 return; 12229 12230 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12231 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12232 } 12233 if (auto VecTy = dyn_cast<VectorType>(Target)) 12234 Target = VecTy->getElementType().getTypePtr(); 12235 12236 // Strip complex types. 12237 if (isa<ComplexType>(Source)) { 12238 if (!isa<ComplexType>(Target)) { 12239 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12240 return; 12241 12242 return DiagnoseImpCast(S, E, T, CC, 12243 S.getLangOpts().CPlusPlus 12244 ? diag::err_impcast_complex_scalar 12245 : diag::warn_impcast_complex_scalar); 12246 } 12247 12248 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12249 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12250 } 12251 12252 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12253 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12254 12255 // If the source is floating point... 12256 if (SourceBT && SourceBT->isFloatingPoint()) { 12257 // ...and the target is floating point... 12258 if (TargetBT && TargetBT->isFloatingPoint()) { 12259 // ...then warn if we're dropping FP rank. 12260 12261 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12262 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12263 if (Order > 0) { 12264 // Don't warn about float constants that are precisely 12265 // representable in the target type. 12266 Expr::EvalResult result; 12267 if (E->EvaluateAsRValue(result, S.Context)) { 12268 // Value might be a float, a float vector, or a float complex. 12269 if (IsSameFloatAfterCast(result.Val, 12270 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12271 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12272 return; 12273 } 12274 12275 if (S.SourceMgr.isInSystemMacro(CC)) 12276 return; 12277 12278 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12279 } 12280 // ... or possibly if we're increasing rank, too 12281 else if (Order < 0) { 12282 if (S.SourceMgr.isInSystemMacro(CC)) 12283 return; 12284 12285 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12286 } 12287 return; 12288 } 12289 12290 // If the target is integral, always warn. 12291 if (TargetBT && TargetBT->isInteger()) { 12292 if (S.SourceMgr.isInSystemMacro(CC)) 12293 return; 12294 12295 DiagnoseFloatingImpCast(S, E, T, CC); 12296 } 12297 12298 // Detect the case where a call result is converted from floating-point to 12299 // to bool, and the final argument to the call is converted from bool, to 12300 // discover this typo: 12301 // 12302 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12303 // 12304 // FIXME: This is an incredibly special case; is there some more general 12305 // way to detect this class of misplaced-parentheses bug? 12306 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12307 // Check last argument of function call to see if it is an 12308 // implicit cast from a type matching the type the result 12309 // is being cast to. 12310 CallExpr *CEx = cast<CallExpr>(E); 12311 if (unsigned NumArgs = CEx->getNumArgs()) { 12312 Expr *LastA = CEx->getArg(NumArgs - 1); 12313 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12314 if (isa<ImplicitCastExpr>(LastA) && 12315 InnerE->getType()->isBooleanType()) { 12316 // Warn on this floating-point to bool conversion 12317 DiagnoseImpCast(S, E, T, CC, 12318 diag::warn_impcast_floating_point_to_bool); 12319 } 12320 } 12321 } 12322 return; 12323 } 12324 12325 // Valid casts involving fixed point types should be accounted for here. 12326 if (Source->isFixedPointType()) { 12327 if (Target->isUnsaturatedFixedPointType()) { 12328 Expr::EvalResult Result; 12329 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12330 S.isConstantEvaluated())) { 12331 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12332 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12333 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12334 if (Value > MaxVal || Value < MinVal) { 12335 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12336 S.PDiag(diag::warn_impcast_fixed_point_range) 12337 << Value.toString() << T 12338 << E->getSourceRange() 12339 << clang::SourceRange(CC)); 12340 return; 12341 } 12342 } 12343 } else if (Target->isIntegerType()) { 12344 Expr::EvalResult Result; 12345 if (!S.isConstantEvaluated() && 12346 E->EvaluateAsFixedPoint(Result, S.Context, 12347 Expr::SE_AllowSideEffects)) { 12348 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12349 12350 bool Overflowed; 12351 llvm::APSInt IntResult = FXResult.convertToInt( 12352 S.Context.getIntWidth(T), 12353 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12354 12355 if (Overflowed) { 12356 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12357 S.PDiag(diag::warn_impcast_fixed_point_range) 12358 << FXResult.toString() << T 12359 << E->getSourceRange() 12360 << clang::SourceRange(CC)); 12361 return; 12362 } 12363 } 12364 } 12365 } else if (Target->isUnsaturatedFixedPointType()) { 12366 if (Source->isIntegerType()) { 12367 Expr::EvalResult Result; 12368 if (!S.isConstantEvaluated() && 12369 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12370 llvm::APSInt Value = Result.Val.getInt(); 12371 12372 bool Overflowed; 12373 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12374 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12375 12376 if (Overflowed) { 12377 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12378 S.PDiag(diag::warn_impcast_fixed_point_range) 12379 << Value.toString(/*Radix=*/10) << T 12380 << E->getSourceRange() 12381 << clang::SourceRange(CC)); 12382 return; 12383 } 12384 } 12385 } 12386 } 12387 12388 // If we are casting an integer type to a floating point type without 12389 // initialization-list syntax, we might lose accuracy if the floating 12390 // point type has a narrower significand than the integer type. 12391 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12392 TargetBT->isFloatingType() && !IsListInit) { 12393 // Determine the number of precision bits in the source integer type. 12394 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12395 /*Approximate*/ true); 12396 unsigned int SourcePrecision = SourceRange.Width; 12397 12398 // Determine the number of precision bits in the 12399 // target floating point type. 12400 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12401 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12402 12403 if (SourcePrecision > 0 && TargetPrecision > 0 && 12404 SourcePrecision > TargetPrecision) { 12405 12406 if (Optional<llvm::APSInt> SourceInt = 12407 E->getIntegerConstantExpr(S.Context)) { 12408 // If the source integer is a constant, convert it to the target 12409 // floating point type. Issue a warning if the value changes 12410 // during the whole conversion. 12411 llvm::APFloat TargetFloatValue( 12412 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12413 llvm::APFloat::opStatus ConversionStatus = 12414 TargetFloatValue.convertFromAPInt( 12415 *SourceInt, SourceBT->isSignedInteger(), 12416 llvm::APFloat::rmNearestTiesToEven); 12417 12418 if (ConversionStatus != llvm::APFloat::opOK) { 12419 std::string PrettySourceValue = SourceInt->toString(10); 12420 SmallString<32> PrettyTargetValue; 12421 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12422 12423 S.DiagRuntimeBehavior( 12424 E->getExprLoc(), E, 12425 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12426 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12427 << E->getSourceRange() << clang::SourceRange(CC)); 12428 } 12429 } else { 12430 // Otherwise, the implicit conversion may lose precision. 12431 DiagnoseImpCast(S, E, T, CC, 12432 diag::warn_impcast_integer_float_precision); 12433 } 12434 } 12435 } 12436 12437 DiagnoseNullConversion(S, E, T, CC); 12438 12439 S.DiscardMisalignedMemberAddress(Target, E); 12440 12441 if (Target->isBooleanType()) 12442 DiagnoseIntInBoolContext(S, E); 12443 12444 if (!Source->isIntegerType() || !Target->isIntegerType()) 12445 return; 12446 12447 // TODO: remove this early return once the false positives for constant->bool 12448 // in templates, macros, etc, are reduced or removed. 12449 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12450 return; 12451 12452 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12453 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12454 return adornObjCBoolConversionDiagWithTernaryFixit( 12455 S, E, 12456 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12457 << E->getType()); 12458 } 12459 12460 IntRange SourceTypeRange = 12461 IntRange::forTargetOfCanonicalType(S.Context, Source); 12462 IntRange LikelySourceRange = 12463 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12464 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12465 12466 if (LikelySourceRange.Width > TargetRange.Width) { 12467 // If the source is a constant, use a default-on diagnostic. 12468 // TODO: this should happen for bitfield stores, too. 12469 Expr::EvalResult Result; 12470 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12471 S.isConstantEvaluated())) { 12472 llvm::APSInt Value(32); 12473 Value = Result.Val.getInt(); 12474 12475 if (S.SourceMgr.isInSystemMacro(CC)) 12476 return; 12477 12478 std::string PrettySourceValue = Value.toString(10); 12479 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12480 12481 S.DiagRuntimeBehavior( 12482 E->getExprLoc(), E, 12483 S.PDiag(diag::warn_impcast_integer_precision_constant) 12484 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12485 << E->getSourceRange() << SourceRange(CC)); 12486 return; 12487 } 12488 12489 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12490 if (S.SourceMgr.isInSystemMacro(CC)) 12491 return; 12492 12493 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12494 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12495 /* pruneControlFlow */ true); 12496 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12497 } 12498 12499 if (TargetRange.Width > SourceTypeRange.Width) { 12500 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12501 if (UO->getOpcode() == UO_Minus) 12502 if (Source->isUnsignedIntegerType()) { 12503 if (Target->isUnsignedIntegerType()) 12504 return DiagnoseImpCast(S, E, T, CC, 12505 diag::warn_impcast_high_order_zero_bits); 12506 if (Target->isSignedIntegerType()) 12507 return DiagnoseImpCast(S, E, T, CC, 12508 diag::warn_impcast_nonnegative_result); 12509 } 12510 } 12511 12512 if (TargetRange.Width == LikelySourceRange.Width && 12513 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12514 Source->isSignedIntegerType()) { 12515 // Warn when doing a signed to signed conversion, warn if the positive 12516 // source value is exactly the width of the target type, which will 12517 // cause a negative value to be stored. 12518 12519 Expr::EvalResult Result; 12520 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12521 !S.SourceMgr.isInSystemMacro(CC)) { 12522 llvm::APSInt Value = Result.Val.getInt(); 12523 if (isSameWidthConstantConversion(S, E, T, CC)) { 12524 std::string PrettySourceValue = Value.toString(10); 12525 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12526 12527 S.DiagRuntimeBehavior( 12528 E->getExprLoc(), E, 12529 S.PDiag(diag::warn_impcast_integer_precision_constant) 12530 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12531 << E->getSourceRange() << SourceRange(CC)); 12532 return; 12533 } 12534 } 12535 12536 // Fall through for non-constants to give a sign conversion warning. 12537 } 12538 12539 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12540 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12541 LikelySourceRange.Width == TargetRange.Width)) { 12542 if (S.SourceMgr.isInSystemMacro(CC)) 12543 return; 12544 12545 unsigned DiagID = diag::warn_impcast_integer_sign; 12546 12547 // Traditionally, gcc has warned about this under -Wsign-compare. 12548 // We also want to warn about it in -Wconversion. 12549 // So if -Wconversion is off, use a completely identical diagnostic 12550 // in the sign-compare group. 12551 // The conditional-checking code will 12552 if (ICContext) { 12553 DiagID = diag::warn_impcast_integer_sign_conditional; 12554 *ICContext = true; 12555 } 12556 12557 return DiagnoseImpCast(S, E, T, CC, DiagID); 12558 } 12559 12560 // Diagnose conversions between different enumeration types. 12561 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12562 // type, to give us better diagnostics. 12563 QualType SourceType = E->getType(); 12564 if (!S.getLangOpts().CPlusPlus) { 12565 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12566 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12567 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12568 SourceType = S.Context.getTypeDeclType(Enum); 12569 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12570 } 12571 } 12572 12573 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12574 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12575 if (SourceEnum->getDecl()->hasNameForLinkage() && 12576 TargetEnum->getDecl()->hasNameForLinkage() && 12577 SourceEnum != TargetEnum) { 12578 if (S.SourceMgr.isInSystemMacro(CC)) 12579 return; 12580 12581 return DiagnoseImpCast(S, E, SourceType, T, CC, 12582 diag::warn_impcast_different_enum_types); 12583 } 12584 } 12585 12586 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12587 SourceLocation CC, QualType T); 12588 12589 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12590 SourceLocation CC, bool &ICContext) { 12591 E = E->IgnoreParenImpCasts(); 12592 12593 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12594 return CheckConditionalOperator(S, CO, CC, T); 12595 12596 AnalyzeImplicitConversions(S, E, CC); 12597 if (E->getType() != T) 12598 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12599 } 12600 12601 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12602 SourceLocation CC, QualType T) { 12603 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12604 12605 Expr *TrueExpr = E->getTrueExpr(); 12606 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12607 TrueExpr = BCO->getCommon(); 12608 12609 bool Suspicious = false; 12610 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12611 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12612 12613 if (T->isBooleanType()) 12614 DiagnoseIntInBoolContext(S, E); 12615 12616 // If -Wconversion would have warned about either of the candidates 12617 // for a signedness conversion to the context type... 12618 if (!Suspicious) return; 12619 12620 // ...but it's currently ignored... 12621 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12622 return; 12623 12624 // ...then check whether it would have warned about either of the 12625 // candidates for a signedness conversion to the condition type. 12626 if (E->getType() == T) return; 12627 12628 Suspicious = false; 12629 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12630 E->getType(), CC, &Suspicious); 12631 if (!Suspicious) 12632 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12633 E->getType(), CC, &Suspicious); 12634 } 12635 12636 /// Check conversion of given expression to boolean. 12637 /// Input argument E is a logical expression. 12638 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12639 if (S.getLangOpts().Bool) 12640 return; 12641 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12642 return; 12643 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12644 } 12645 12646 namespace { 12647 struct AnalyzeImplicitConversionsWorkItem { 12648 Expr *E; 12649 SourceLocation CC; 12650 bool IsListInit; 12651 }; 12652 } 12653 12654 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12655 /// that should be visited are added to WorkList. 12656 static void AnalyzeImplicitConversions( 12657 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12658 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12659 Expr *OrigE = Item.E; 12660 SourceLocation CC = Item.CC; 12661 12662 QualType T = OrigE->getType(); 12663 Expr *E = OrigE->IgnoreParenImpCasts(); 12664 12665 // Propagate whether we are in a C++ list initialization expression. 12666 // If so, we do not issue warnings for implicit int-float conversion 12667 // precision loss, because C++11 narrowing already handles it. 12668 bool IsListInit = Item.IsListInit || 12669 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12670 12671 if (E->isTypeDependent() || E->isValueDependent()) 12672 return; 12673 12674 Expr *SourceExpr = E; 12675 // Examine, but don't traverse into the source expression of an 12676 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12677 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12678 // evaluate it in the context of checking the specific conversion to T though. 12679 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12680 if (auto *Src = OVE->getSourceExpr()) 12681 SourceExpr = Src; 12682 12683 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12684 if (UO->getOpcode() == UO_Not && 12685 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12686 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12687 << OrigE->getSourceRange() << T->isBooleanType() 12688 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12689 12690 // For conditional operators, we analyze the arguments as if they 12691 // were being fed directly into the output. 12692 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12693 CheckConditionalOperator(S, CO, CC, T); 12694 return; 12695 } 12696 12697 // Check implicit argument conversions for function calls. 12698 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12699 CheckImplicitArgumentConversions(S, Call, CC); 12700 12701 // Go ahead and check any implicit conversions we might have skipped. 12702 // The non-canonical typecheck is just an optimization; 12703 // CheckImplicitConversion will filter out dead implicit conversions. 12704 if (SourceExpr->getType() != T) 12705 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12706 12707 // Now continue drilling into this expression. 12708 12709 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12710 // The bound subexpressions in a PseudoObjectExpr are not reachable 12711 // as transitive children. 12712 // FIXME: Use a more uniform representation for this. 12713 for (auto *SE : POE->semantics()) 12714 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12715 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12716 } 12717 12718 // Skip past explicit casts. 12719 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12720 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12721 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12722 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12723 WorkList.push_back({E, CC, IsListInit}); 12724 return; 12725 } 12726 12727 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12728 // Do a somewhat different check with comparison operators. 12729 if (BO->isComparisonOp()) 12730 return AnalyzeComparison(S, BO); 12731 12732 // And with simple assignments. 12733 if (BO->getOpcode() == BO_Assign) 12734 return AnalyzeAssignment(S, BO); 12735 // And with compound assignments. 12736 if (BO->isAssignmentOp()) 12737 return AnalyzeCompoundAssignment(S, BO); 12738 } 12739 12740 // These break the otherwise-useful invariant below. Fortunately, 12741 // we don't really need to recurse into them, because any internal 12742 // expressions should have been analyzed already when they were 12743 // built into statements. 12744 if (isa<StmtExpr>(E)) return; 12745 12746 // Don't descend into unevaluated contexts. 12747 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12748 12749 // Now just recurse over the expression's children. 12750 CC = E->getExprLoc(); 12751 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12752 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12753 for (Stmt *SubStmt : E->children()) { 12754 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12755 if (!ChildExpr) 12756 continue; 12757 12758 if (IsLogicalAndOperator && 12759 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12760 // Ignore checking string literals that are in logical and operators. 12761 // This is a common pattern for asserts. 12762 continue; 12763 WorkList.push_back({ChildExpr, CC, IsListInit}); 12764 } 12765 12766 if (BO && BO->isLogicalOp()) { 12767 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12768 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12769 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12770 12771 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12772 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12773 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12774 } 12775 12776 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12777 if (U->getOpcode() == UO_LNot) { 12778 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12779 } else if (U->getOpcode() != UO_AddrOf) { 12780 if (U->getSubExpr()->getType()->isAtomicType()) 12781 S.Diag(U->getSubExpr()->getBeginLoc(), 12782 diag::warn_atomic_implicit_seq_cst); 12783 } 12784 } 12785 } 12786 12787 /// AnalyzeImplicitConversions - Find and report any interesting 12788 /// implicit conversions in the given expression. There are a couple 12789 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12790 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12791 bool IsListInit/*= false*/) { 12792 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12793 WorkList.push_back({OrigE, CC, IsListInit}); 12794 while (!WorkList.empty()) 12795 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12796 } 12797 12798 /// Diagnose integer type and any valid implicit conversion to it. 12799 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12800 // Taking into account implicit conversions, 12801 // allow any integer. 12802 if (!E->getType()->isIntegerType()) { 12803 S.Diag(E->getBeginLoc(), 12804 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12805 return true; 12806 } 12807 // Potentially emit standard warnings for implicit conversions if enabled 12808 // using -Wconversion. 12809 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12810 return false; 12811 } 12812 12813 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12814 // Returns true when emitting a warning about taking the address of a reference. 12815 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12816 const PartialDiagnostic &PD) { 12817 E = E->IgnoreParenImpCasts(); 12818 12819 const FunctionDecl *FD = nullptr; 12820 12821 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12822 if (!DRE->getDecl()->getType()->isReferenceType()) 12823 return false; 12824 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12825 if (!M->getMemberDecl()->getType()->isReferenceType()) 12826 return false; 12827 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12828 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12829 return false; 12830 FD = Call->getDirectCallee(); 12831 } else { 12832 return false; 12833 } 12834 12835 SemaRef.Diag(E->getExprLoc(), PD); 12836 12837 // If possible, point to location of function. 12838 if (FD) { 12839 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12840 } 12841 12842 return true; 12843 } 12844 12845 // Returns true if the SourceLocation is expanded from any macro body. 12846 // Returns false if the SourceLocation is invalid, is from not in a macro 12847 // expansion, or is from expanded from a top-level macro argument. 12848 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12849 if (Loc.isInvalid()) 12850 return false; 12851 12852 while (Loc.isMacroID()) { 12853 if (SM.isMacroBodyExpansion(Loc)) 12854 return true; 12855 Loc = SM.getImmediateMacroCallerLoc(Loc); 12856 } 12857 12858 return false; 12859 } 12860 12861 /// Diagnose pointers that are always non-null. 12862 /// \param E the expression containing the pointer 12863 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12864 /// compared to a null pointer 12865 /// \param IsEqual True when the comparison is equal to a null pointer 12866 /// \param Range Extra SourceRange to highlight in the diagnostic 12867 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12868 Expr::NullPointerConstantKind NullKind, 12869 bool IsEqual, SourceRange Range) { 12870 if (!E) 12871 return; 12872 12873 // Don't warn inside macros. 12874 if (E->getExprLoc().isMacroID()) { 12875 const SourceManager &SM = getSourceManager(); 12876 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12877 IsInAnyMacroBody(SM, Range.getBegin())) 12878 return; 12879 } 12880 E = E->IgnoreImpCasts(); 12881 12882 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12883 12884 if (isa<CXXThisExpr>(E)) { 12885 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12886 : diag::warn_this_bool_conversion; 12887 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12888 return; 12889 } 12890 12891 bool IsAddressOf = false; 12892 12893 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12894 if (UO->getOpcode() != UO_AddrOf) 12895 return; 12896 IsAddressOf = true; 12897 E = UO->getSubExpr(); 12898 } 12899 12900 if (IsAddressOf) { 12901 unsigned DiagID = IsCompare 12902 ? diag::warn_address_of_reference_null_compare 12903 : diag::warn_address_of_reference_bool_conversion; 12904 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12905 << IsEqual; 12906 if (CheckForReference(*this, E, PD)) { 12907 return; 12908 } 12909 } 12910 12911 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12912 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12913 std::string Str; 12914 llvm::raw_string_ostream S(Str); 12915 E->printPretty(S, nullptr, getPrintingPolicy()); 12916 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12917 : diag::warn_cast_nonnull_to_bool; 12918 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12919 << E->getSourceRange() << Range << IsEqual; 12920 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12921 }; 12922 12923 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12924 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12925 if (auto *Callee = Call->getDirectCallee()) { 12926 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12927 ComplainAboutNonnullParamOrCall(A); 12928 return; 12929 } 12930 } 12931 } 12932 12933 // Expect to find a single Decl. Skip anything more complicated. 12934 ValueDecl *D = nullptr; 12935 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12936 D = R->getDecl(); 12937 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12938 D = M->getMemberDecl(); 12939 } 12940 12941 // Weak Decls can be null. 12942 if (!D || D->isWeak()) 12943 return; 12944 12945 // Check for parameter decl with nonnull attribute 12946 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12947 if (getCurFunction() && 12948 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12949 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12950 ComplainAboutNonnullParamOrCall(A); 12951 return; 12952 } 12953 12954 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12955 // Skip function template not specialized yet. 12956 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12957 return; 12958 auto ParamIter = llvm::find(FD->parameters(), PV); 12959 assert(ParamIter != FD->param_end()); 12960 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12961 12962 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12963 if (!NonNull->args_size()) { 12964 ComplainAboutNonnullParamOrCall(NonNull); 12965 return; 12966 } 12967 12968 for (const ParamIdx &ArgNo : NonNull->args()) { 12969 if (ArgNo.getASTIndex() == ParamNo) { 12970 ComplainAboutNonnullParamOrCall(NonNull); 12971 return; 12972 } 12973 } 12974 } 12975 } 12976 } 12977 } 12978 12979 QualType T = D->getType(); 12980 const bool IsArray = T->isArrayType(); 12981 const bool IsFunction = T->isFunctionType(); 12982 12983 // Address of function is used to silence the function warning. 12984 if (IsAddressOf && IsFunction) { 12985 return; 12986 } 12987 12988 // Found nothing. 12989 if (!IsAddressOf && !IsFunction && !IsArray) 12990 return; 12991 12992 // Pretty print the expression for the diagnostic. 12993 std::string Str; 12994 llvm::raw_string_ostream S(Str); 12995 E->printPretty(S, nullptr, getPrintingPolicy()); 12996 12997 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12998 : diag::warn_impcast_pointer_to_bool; 12999 enum { 13000 AddressOf, 13001 FunctionPointer, 13002 ArrayPointer 13003 } DiagType; 13004 if (IsAddressOf) 13005 DiagType = AddressOf; 13006 else if (IsFunction) 13007 DiagType = FunctionPointer; 13008 else if (IsArray) 13009 DiagType = ArrayPointer; 13010 else 13011 llvm_unreachable("Could not determine diagnostic."); 13012 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13013 << Range << IsEqual; 13014 13015 if (!IsFunction) 13016 return; 13017 13018 // Suggest '&' to silence the function warning. 13019 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13020 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13021 13022 // Check to see if '()' fixit should be emitted. 13023 QualType ReturnType; 13024 UnresolvedSet<4> NonTemplateOverloads; 13025 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13026 if (ReturnType.isNull()) 13027 return; 13028 13029 if (IsCompare) { 13030 // There are two cases here. If there is null constant, the only suggest 13031 // for a pointer return type. If the null is 0, then suggest if the return 13032 // type is a pointer or an integer type. 13033 if (!ReturnType->isPointerType()) { 13034 if (NullKind == Expr::NPCK_ZeroExpression || 13035 NullKind == Expr::NPCK_ZeroLiteral) { 13036 if (!ReturnType->isIntegerType()) 13037 return; 13038 } else { 13039 return; 13040 } 13041 } 13042 } else { // !IsCompare 13043 // For function to bool, only suggest if the function pointer has bool 13044 // return type. 13045 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13046 return; 13047 } 13048 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13049 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13050 } 13051 13052 /// Diagnoses "dangerous" implicit conversions within the given 13053 /// expression (which is a full expression). Implements -Wconversion 13054 /// and -Wsign-compare. 13055 /// 13056 /// \param CC the "context" location of the implicit conversion, i.e. 13057 /// the most location of the syntactic entity requiring the implicit 13058 /// conversion 13059 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13060 // Don't diagnose in unevaluated contexts. 13061 if (isUnevaluatedContext()) 13062 return; 13063 13064 // Don't diagnose for value- or type-dependent expressions. 13065 if (E->isTypeDependent() || E->isValueDependent()) 13066 return; 13067 13068 // Check for array bounds violations in cases where the check isn't triggered 13069 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13070 // ArraySubscriptExpr is on the RHS of a variable initialization. 13071 CheckArrayAccess(E); 13072 13073 // This is not the right CC for (e.g.) a variable initialization. 13074 AnalyzeImplicitConversions(*this, E, CC); 13075 } 13076 13077 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13078 /// Input argument E is a logical expression. 13079 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13080 ::CheckBoolLikeConversion(*this, E, CC); 13081 } 13082 13083 /// Diagnose when expression is an integer constant expression and its evaluation 13084 /// results in integer overflow 13085 void Sema::CheckForIntOverflow (Expr *E) { 13086 // Use a work list to deal with nested struct initializers. 13087 SmallVector<Expr *, 2> Exprs(1, E); 13088 13089 do { 13090 Expr *OriginalE = Exprs.pop_back_val(); 13091 Expr *E = OriginalE->IgnoreParenCasts(); 13092 13093 if (isa<BinaryOperator>(E)) { 13094 E->EvaluateForOverflow(Context); 13095 continue; 13096 } 13097 13098 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13099 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13100 else if (isa<ObjCBoxedExpr>(OriginalE)) 13101 E->EvaluateForOverflow(Context); 13102 else if (auto Call = dyn_cast<CallExpr>(E)) 13103 Exprs.append(Call->arg_begin(), Call->arg_end()); 13104 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13105 Exprs.append(Message->arg_begin(), Message->arg_end()); 13106 } while (!Exprs.empty()); 13107 } 13108 13109 namespace { 13110 13111 /// Visitor for expressions which looks for unsequenced operations on the 13112 /// same object. 13113 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13114 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13115 13116 /// A tree of sequenced regions within an expression. Two regions are 13117 /// unsequenced if one is an ancestor or a descendent of the other. When we 13118 /// finish processing an expression with sequencing, such as a comma 13119 /// expression, we fold its tree nodes into its parent, since they are 13120 /// unsequenced with respect to nodes we will visit later. 13121 class SequenceTree { 13122 struct Value { 13123 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13124 unsigned Parent : 31; 13125 unsigned Merged : 1; 13126 }; 13127 SmallVector<Value, 8> Values; 13128 13129 public: 13130 /// A region within an expression which may be sequenced with respect 13131 /// to some other region. 13132 class Seq { 13133 friend class SequenceTree; 13134 13135 unsigned Index; 13136 13137 explicit Seq(unsigned N) : Index(N) {} 13138 13139 public: 13140 Seq() : Index(0) {} 13141 }; 13142 13143 SequenceTree() { Values.push_back(Value(0)); } 13144 Seq root() const { return Seq(0); } 13145 13146 /// Create a new sequence of operations, which is an unsequenced 13147 /// subset of \p Parent. This sequence of operations is sequenced with 13148 /// respect to other children of \p Parent. 13149 Seq allocate(Seq Parent) { 13150 Values.push_back(Value(Parent.Index)); 13151 return Seq(Values.size() - 1); 13152 } 13153 13154 /// Merge a sequence of operations into its parent. 13155 void merge(Seq S) { 13156 Values[S.Index].Merged = true; 13157 } 13158 13159 /// Determine whether two operations are unsequenced. This operation 13160 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13161 /// should have been merged into its parent as appropriate. 13162 bool isUnsequenced(Seq Cur, Seq Old) { 13163 unsigned C = representative(Cur.Index); 13164 unsigned Target = representative(Old.Index); 13165 while (C >= Target) { 13166 if (C == Target) 13167 return true; 13168 C = Values[C].Parent; 13169 } 13170 return false; 13171 } 13172 13173 private: 13174 /// Pick a representative for a sequence. 13175 unsigned representative(unsigned K) { 13176 if (Values[K].Merged) 13177 // Perform path compression as we go. 13178 return Values[K].Parent = representative(Values[K].Parent); 13179 return K; 13180 } 13181 }; 13182 13183 /// An object for which we can track unsequenced uses. 13184 using Object = const NamedDecl *; 13185 13186 /// Different flavors of object usage which we track. We only track the 13187 /// least-sequenced usage of each kind. 13188 enum UsageKind { 13189 /// A read of an object. Multiple unsequenced reads are OK. 13190 UK_Use, 13191 13192 /// A modification of an object which is sequenced before the value 13193 /// computation of the expression, such as ++n in C++. 13194 UK_ModAsValue, 13195 13196 /// A modification of an object which is not sequenced before the value 13197 /// computation of the expression, such as n++. 13198 UK_ModAsSideEffect, 13199 13200 UK_Count = UK_ModAsSideEffect + 1 13201 }; 13202 13203 /// Bundle together a sequencing region and the expression corresponding 13204 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13205 struct Usage { 13206 const Expr *UsageExpr; 13207 SequenceTree::Seq Seq; 13208 13209 Usage() : UsageExpr(nullptr), Seq() {} 13210 }; 13211 13212 struct UsageInfo { 13213 Usage Uses[UK_Count]; 13214 13215 /// Have we issued a diagnostic for this object already? 13216 bool Diagnosed; 13217 13218 UsageInfo() : Uses(), Diagnosed(false) {} 13219 }; 13220 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13221 13222 Sema &SemaRef; 13223 13224 /// Sequenced regions within the expression. 13225 SequenceTree Tree; 13226 13227 /// Declaration modifications and references which we have seen. 13228 UsageInfoMap UsageMap; 13229 13230 /// The region we are currently within. 13231 SequenceTree::Seq Region; 13232 13233 /// Filled in with declarations which were modified as a side-effect 13234 /// (that is, post-increment operations). 13235 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13236 13237 /// Expressions to check later. We defer checking these to reduce 13238 /// stack usage. 13239 SmallVectorImpl<const Expr *> &WorkList; 13240 13241 /// RAII object wrapping the visitation of a sequenced subexpression of an 13242 /// expression. At the end of this process, the side-effects of the evaluation 13243 /// become sequenced with respect to the value computation of the result, so 13244 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13245 /// UK_ModAsValue. 13246 struct SequencedSubexpression { 13247 SequencedSubexpression(SequenceChecker &Self) 13248 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13249 Self.ModAsSideEffect = &ModAsSideEffect; 13250 } 13251 13252 ~SequencedSubexpression() { 13253 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13254 // Add a new usage with usage kind UK_ModAsValue, and then restore 13255 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13256 // the previous one was empty). 13257 UsageInfo &UI = Self.UsageMap[M.first]; 13258 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13259 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13260 SideEffectUsage = M.second; 13261 } 13262 Self.ModAsSideEffect = OldModAsSideEffect; 13263 } 13264 13265 SequenceChecker &Self; 13266 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13267 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13268 }; 13269 13270 /// RAII object wrapping the visitation of a subexpression which we might 13271 /// choose to evaluate as a constant. If any subexpression is evaluated and 13272 /// found to be non-constant, this allows us to suppress the evaluation of 13273 /// the outer expression. 13274 class EvaluationTracker { 13275 public: 13276 EvaluationTracker(SequenceChecker &Self) 13277 : Self(Self), Prev(Self.EvalTracker) { 13278 Self.EvalTracker = this; 13279 } 13280 13281 ~EvaluationTracker() { 13282 Self.EvalTracker = Prev; 13283 if (Prev) 13284 Prev->EvalOK &= EvalOK; 13285 } 13286 13287 bool evaluate(const Expr *E, bool &Result) { 13288 if (!EvalOK || E->isValueDependent()) 13289 return false; 13290 EvalOK = E->EvaluateAsBooleanCondition( 13291 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13292 return EvalOK; 13293 } 13294 13295 private: 13296 SequenceChecker &Self; 13297 EvaluationTracker *Prev; 13298 bool EvalOK = true; 13299 } *EvalTracker = nullptr; 13300 13301 /// Find the object which is produced by the specified expression, 13302 /// if any. 13303 Object getObject(const Expr *E, bool Mod) const { 13304 E = E->IgnoreParenCasts(); 13305 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13306 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13307 return getObject(UO->getSubExpr(), Mod); 13308 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13309 if (BO->getOpcode() == BO_Comma) 13310 return getObject(BO->getRHS(), Mod); 13311 if (Mod && BO->isAssignmentOp()) 13312 return getObject(BO->getLHS(), Mod); 13313 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13314 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13315 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13316 return ME->getMemberDecl(); 13317 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13318 // FIXME: If this is a reference, map through to its value. 13319 return DRE->getDecl(); 13320 return nullptr; 13321 } 13322 13323 /// Note that an object \p O was modified or used by an expression 13324 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13325 /// the object \p O as obtained via the \p UsageMap. 13326 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13327 // Get the old usage for the given object and usage kind. 13328 Usage &U = UI.Uses[UK]; 13329 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13330 // If we have a modification as side effect and are in a sequenced 13331 // subexpression, save the old Usage so that we can restore it later 13332 // in SequencedSubexpression::~SequencedSubexpression. 13333 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13334 ModAsSideEffect->push_back(std::make_pair(O, U)); 13335 // Then record the new usage with the current sequencing region. 13336 U.UsageExpr = UsageExpr; 13337 U.Seq = Region; 13338 } 13339 } 13340 13341 /// Check whether a modification or use of an object \p O in an expression 13342 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13343 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13344 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13345 /// usage and false we are checking for a mod-use unsequenced usage. 13346 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13347 UsageKind OtherKind, bool IsModMod) { 13348 if (UI.Diagnosed) 13349 return; 13350 13351 const Usage &U = UI.Uses[OtherKind]; 13352 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13353 return; 13354 13355 const Expr *Mod = U.UsageExpr; 13356 const Expr *ModOrUse = UsageExpr; 13357 if (OtherKind == UK_Use) 13358 std::swap(Mod, ModOrUse); 13359 13360 SemaRef.DiagRuntimeBehavior( 13361 Mod->getExprLoc(), {Mod, ModOrUse}, 13362 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13363 : diag::warn_unsequenced_mod_use) 13364 << O << SourceRange(ModOrUse->getExprLoc())); 13365 UI.Diagnosed = true; 13366 } 13367 13368 // A note on note{Pre, Post}{Use, Mod}: 13369 // 13370 // (It helps to follow the algorithm with an expression such as 13371 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13372 // operations before C++17 and both are well-defined in C++17). 13373 // 13374 // When visiting a node which uses/modify an object we first call notePreUse 13375 // or notePreMod before visiting its sub-expression(s). At this point the 13376 // children of the current node have not yet been visited and so the eventual 13377 // uses/modifications resulting from the children of the current node have not 13378 // been recorded yet. 13379 // 13380 // We then visit the children of the current node. After that notePostUse or 13381 // notePostMod is called. These will 1) detect an unsequenced modification 13382 // as side effect (as in "k++ + k") and 2) add a new usage with the 13383 // appropriate usage kind. 13384 // 13385 // We also have to be careful that some operation sequences modification as 13386 // side effect as well (for example: || or ,). To account for this we wrap 13387 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13388 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13389 // which record usages which are modifications as side effect, and then 13390 // downgrade them (or more accurately restore the previous usage which was a 13391 // modification as side effect) when exiting the scope of the sequenced 13392 // subexpression. 13393 13394 void notePreUse(Object O, const Expr *UseExpr) { 13395 UsageInfo &UI = UsageMap[O]; 13396 // Uses conflict with other modifications. 13397 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13398 } 13399 13400 void notePostUse(Object O, const Expr *UseExpr) { 13401 UsageInfo &UI = UsageMap[O]; 13402 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13403 /*IsModMod=*/false); 13404 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13405 } 13406 13407 void notePreMod(Object O, const Expr *ModExpr) { 13408 UsageInfo &UI = UsageMap[O]; 13409 // Modifications conflict with other modifications and with uses. 13410 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13411 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13412 } 13413 13414 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13415 UsageInfo &UI = UsageMap[O]; 13416 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13417 /*IsModMod=*/true); 13418 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13419 } 13420 13421 public: 13422 SequenceChecker(Sema &S, const Expr *E, 13423 SmallVectorImpl<const Expr *> &WorkList) 13424 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13425 Visit(E); 13426 // Silence a -Wunused-private-field since WorkList is now unused. 13427 // TODO: Evaluate if it can be used, and if not remove it. 13428 (void)this->WorkList; 13429 } 13430 13431 void VisitStmt(const Stmt *S) { 13432 // Skip all statements which aren't expressions for now. 13433 } 13434 13435 void VisitExpr(const Expr *E) { 13436 // By default, just recurse to evaluated subexpressions. 13437 Base::VisitStmt(E); 13438 } 13439 13440 void VisitCastExpr(const CastExpr *E) { 13441 Object O = Object(); 13442 if (E->getCastKind() == CK_LValueToRValue) 13443 O = getObject(E->getSubExpr(), false); 13444 13445 if (O) 13446 notePreUse(O, E); 13447 VisitExpr(E); 13448 if (O) 13449 notePostUse(O, E); 13450 } 13451 13452 void VisitSequencedExpressions(const Expr *SequencedBefore, 13453 const Expr *SequencedAfter) { 13454 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13455 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13456 SequenceTree::Seq OldRegion = Region; 13457 13458 { 13459 SequencedSubexpression SeqBefore(*this); 13460 Region = BeforeRegion; 13461 Visit(SequencedBefore); 13462 } 13463 13464 Region = AfterRegion; 13465 Visit(SequencedAfter); 13466 13467 Region = OldRegion; 13468 13469 Tree.merge(BeforeRegion); 13470 Tree.merge(AfterRegion); 13471 } 13472 13473 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13474 // C++17 [expr.sub]p1: 13475 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13476 // expression E1 is sequenced before the expression E2. 13477 if (SemaRef.getLangOpts().CPlusPlus17) 13478 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13479 else { 13480 Visit(ASE->getLHS()); 13481 Visit(ASE->getRHS()); 13482 } 13483 } 13484 13485 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13486 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13487 void VisitBinPtrMem(const BinaryOperator *BO) { 13488 // C++17 [expr.mptr.oper]p4: 13489 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13490 // the expression E1 is sequenced before the expression E2. 13491 if (SemaRef.getLangOpts().CPlusPlus17) 13492 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13493 else { 13494 Visit(BO->getLHS()); 13495 Visit(BO->getRHS()); 13496 } 13497 } 13498 13499 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13500 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13501 void VisitBinShlShr(const BinaryOperator *BO) { 13502 // C++17 [expr.shift]p4: 13503 // The expression E1 is sequenced before the expression E2. 13504 if (SemaRef.getLangOpts().CPlusPlus17) 13505 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13506 else { 13507 Visit(BO->getLHS()); 13508 Visit(BO->getRHS()); 13509 } 13510 } 13511 13512 void VisitBinComma(const BinaryOperator *BO) { 13513 // C++11 [expr.comma]p1: 13514 // Every value computation and side effect associated with the left 13515 // expression is sequenced before every value computation and side 13516 // effect associated with the right expression. 13517 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13518 } 13519 13520 void VisitBinAssign(const BinaryOperator *BO) { 13521 SequenceTree::Seq RHSRegion; 13522 SequenceTree::Seq LHSRegion; 13523 if (SemaRef.getLangOpts().CPlusPlus17) { 13524 RHSRegion = Tree.allocate(Region); 13525 LHSRegion = Tree.allocate(Region); 13526 } else { 13527 RHSRegion = Region; 13528 LHSRegion = Region; 13529 } 13530 SequenceTree::Seq OldRegion = Region; 13531 13532 // C++11 [expr.ass]p1: 13533 // [...] the assignment is sequenced after the value computation 13534 // of the right and left operands, [...] 13535 // 13536 // so check it before inspecting the operands and update the 13537 // map afterwards. 13538 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13539 if (O) 13540 notePreMod(O, BO); 13541 13542 if (SemaRef.getLangOpts().CPlusPlus17) { 13543 // C++17 [expr.ass]p1: 13544 // [...] The right operand is sequenced before the left operand. [...] 13545 { 13546 SequencedSubexpression SeqBefore(*this); 13547 Region = RHSRegion; 13548 Visit(BO->getRHS()); 13549 } 13550 13551 Region = LHSRegion; 13552 Visit(BO->getLHS()); 13553 13554 if (O && isa<CompoundAssignOperator>(BO)) 13555 notePostUse(O, BO); 13556 13557 } else { 13558 // C++11 does not specify any sequencing between the LHS and RHS. 13559 Region = LHSRegion; 13560 Visit(BO->getLHS()); 13561 13562 if (O && isa<CompoundAssignOperator>(BO)) 13563 notePostUse(O, BO); 13564 13565 Region = RHSRegion; 13566 Visit(BO->getRHS()); 13567 } 13568 13569 // C++11 [expr.ass]p1: 13570 // the assignment is sequenced [...] before the value computation of the 13571 // assignment expression. 13572 // C11 6.5.16/3 has no such rule. 13573 Region = OldRegion; 13574 if (O) 13575 notePostMod(O, BO, 13576 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13577 : UK_ModAsSideEffect); 13578 if (SemaRef.getLangOpts().CPlusPlus17) { 13579 Tree.merge(RHSRegion); 13580 Tree.merge(LHSRegion); 13581 } 13582 } 13583 13584 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13585 VisitBinAssign(CAO); 13586 } 13587 13588 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13589 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13590 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13591 Object O = getObject(UO->getSubExpr(), true); 13592 if (!O) 13593 return VisitExpr(UO); 13594 13595 notePreMod(O, UO); 13596 Visit(UO->getSubExpr()); 13597 // C++11 [expr.pre.incr]p1: 13598 // the expression ++x is equivalent to x+=1 13599 notePostMod(O, UO, 13600 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13601 : UK_ModAsSideEffect); 13602 } 13603 13604 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13605 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13606 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13607 Object O = getObject(UO->getSubExpr(), true); 13608 if (!O) 13609 return VisitExpr(UO); 13610 13611 notePreMod(O, UO); 13612 Visit(UO->getSubExpr()); 13613 notePostMod(O, UO, UK_ModAsSideEffect); 13614 } 13615 13616 void VisitBinLOr(const BinaryOperator *BO) { 13617 // C++11 [expr.log.or]p2: 13618 // If the second expression is evaluated, every value computation and 13619 // side effect associated with the first expression is sequenced before 13620 // every value computation and side effect associated with the 13621 // second expression. 13622 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13623 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13624 SequenceTree::Seq OldRegion = Region; 13625 13626 EvaluationTracker Eval(*this); 13627 { 13628 SequencedSubexpression Sequenced(*this); 13629 Region = LHSRegion; 13630 Visit(BO->getLHS()); 13631 } 13632 13633 // C++11 [expr.log.or]p1: 13634 // [...] the second operand is not evaluated if the first operand 13635 // evaluates to true. 13636 bool EvalResult = false; 13637 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13638 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13639 if (ShouldVisitRHS) { 13640 Region = RHSRegion; 13641 Visit(BO->getRHS()); 13642 } 13643 13644 Region = OldRegion; 13645 Tree.merge(LHSRegion); 13646 Tree.merge(RHSRegion); 13647 } 13648 13649 void VisitBinLAnd(const BinaryOperator *BO) { 13650 // C++11 [expr.log.and]p2: 13651 // If the second expression is evaluated, every value computation and 13652 // side effect associated with the first expression is sequenced before 13653 // every value computation and side effect associated with the 13654 // second expression. 13655 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13656 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13657 SequenceTree::Seq OldRegion = Region; 13658 13659 EvaluationTracker Eval(*this); 13660 { 13661 SequencedSubexpression Sequenced(*this); 13662 Region = LHSRegion; 13663 Visit(BO->getLHS()); 13664 } 13665 13666 // C++11 [expr.log.and]p1: 13667 // [...] the second operand is not evaluated if the first operand is false. 13668 bool EvalResult = false; 13669 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13670 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13671 if (ShouldVisitRHS) { 13672 Region = RHSRegion; 13673 Visit(BO->getRHS()); 13674 } 13675 13676 Region = OldRegion; 13677 Tree.merge(LHSRegion); 13678 Tree.merge(RHSRegion); 13679 } 13680 13681 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13682 // C++11 [expr.cond]p1: 13683 // [...] Every value computation and side effect associated with the first 13684 // expression is sequenced before every value computation and side effect 13685 // associated with the second or third expression. 13686 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13687 13688 // No sequencing is specified between the true and false expression. 13689 // However since exactly one of both is going to be evaluated we can 13690 // consider them to be sequenced. This is needed to avoid warning on 13691 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13692 // both the true and false expressions because we can't evaluate x. 13693 // This will still allow us to detect an expression like (pre C++17) 13694 // "(x ? y += 1 : y += 2) = y". 13695 // 13696 // We don't wrap the visitation of the true and false expression with 13697 // SequencedSubexpression because we don't want to downgrade modifications 13698 // as side effect in the true and false expressions after the visition 13699 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13700 // not warn between the two "y++", but we should warn between the "y++" 13701 // and the "y". 13702 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13703 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13704 SequenceTree::Seq OldRegion = Region; 13705 13706 EvaluationTracker Eval(*this); 13707 { 13708 SequencedSubexpression Sequenced(*this); 13709 Region = ConditionRegion; 13710 Visit(CO->getCond()); 13711 } 13712 13713 // C++11 [expr.cond]p1: 13714 // [...] The first expression is contextually converted to bool (Clause 4). 13715 // It is evaluated and if it is true, the result of the conditional 13716 // expression is the value of the second expression, otherwise that of the 13717 // third expression. Only one of the second and third expressions is 13718 // evaluated. [...] 13719 bool EvalResult = false; 13720 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13721 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13722 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13723 if (ShouldVisitTrueExpr) { 13724 Region = TrueRegion; 13725 Visit(CO->getTrueExpr()); 13726 } 13727 if (ShouldVisitFalseExpr) { 13728 Region = FalseRegion; 13729 Visit(CO->getFalseExpr()); 13730 } 13731 13732 Region = OldRegion; 13733 Tree.merge(ConditionRegion); 13734 Tree.merge(TrueRegion); 13735 Tree.merge(FalseRegion); 13736 } 13737 13738 void VisitCallExpr(const CallExpr *CE) { 13739 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13740 13741 if (CE->isUnevaluatedBuiltinCall(Context)) 13742 return; 13743 13744 // C++11 [intro.execution]p15: 13745 // When calling a function [...], every value computation and side effect 13746 // associated with any argument expression, or with the postfix expression 13747 // designating the called function, is sequenced before execution of every 13748 // expression or statement in the body of the function [and thus before 13749 // the value computation of its result]. 13750 SequencedSubexpression Sequenced(*this); 13751 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13752 // C++17 [expr.call]p5 13753 // The postfix-expression is sequenced before each expression in the 13754 // expression-list and any default argument. [...] 13755 SequenceTree::Seq CalleeRegion; 13756 SequenceTree::Seq OtherRegion; 13757 if (SemaRef.getLangOpts().CPlusPlus17) { 13758 CalleeRegion = Tree.allocate(Region); 13759 OtherRegion = Tree.allocate(Region); 13760 } else { 13761 CalleeRegion = Region; 13762 OtherRegion = Region; 13763 } 13764 SequenceTree::Seq OldRegion = Region; 13765 13766 // Visit the callee expression first. 13767 Region = CalleeRegion; 13768 if (SemaRef.getLangOpts().CPlusPlus17) { 13769 SequencedSubexpression Sequenced(*this); 13770 Visit(CE->getCallee()); 13771 } else { 13772 Visit(CE->getCallee()); 13773 } 13774 13775 // Then visit the argument expressions. 13776 Region = OtherRegion; 13777 for (const Expr *Argument : CE->arguments()) 13778 Visit(Argument); 13779 13780 Region = OldRegion; 13781 if (SemaRef.getLangOpts().CPlusPlus17) { 13782 Tree.merge(CalleeRegion); 13783 Tree.merge(OtherRegion); 13784 } 13785 }); 13786 } 13787 13788 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13789 // C++17 [over.match.oper]p2: 13790 // [...] the operator notation is first transformed to the equivalent 13791 // function-call notation as summarized in Table 12 (where @ denotes one 13792 // of the operators covered in the specified subclause). However, the 13793 // operands are sequenced in the order prescribed for the built-in 13794 // operator (Clause 8). 13795 // 13796 // From the above only overloaded binary operators and overloaded call 13797 // operators have sequencing rules in C++17 that we need to handle 13798 // separately. 13799 if (!SemaRef.getLangOpts().CPlusPlus17 || 13800 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13801 return VisitCallExpr(CXXOCE); 13802 13803 enum { 13804 NoSequencing, 13805 LHSBeforeRHS, 13806 RHSBeforeLHS, 13807 LHSBeforeRest 13808 } SequencingKind; 13809 switch (CXXOCE->getOperator()) { 13810 case OO_Equal: 13811 case OO_PlusEqual: 13812 case OO_MinusEqual: 13813 case OO_StarEqual: 13814 case OO_SlashEqual: 13815 case OO_PercentEqual: 13816 case OO_CaretEqual: 13817 case OO_AmpEqual: 13818 case OO_PipeEqual: 13819 case OO_LessLessEqual: 13820 case OO_GreaterGreaterEqual: 13821 SequencingKind = RHSBeforeLHS; 13822 break; 13823 13824 case OO_LessLess: 13825 case OO_GreaterGreater: 13826 case OO_AmpAmp: 13827 case OO_PipePipe: 13828 case OO_Comma: 13829 case OO_ArrowStar: 13830 case OO_Subscript: 13831 SequencingKind = LHSBeforeRHS; 13832 break; 13833 13834 case OO_Call: 13835 SequencingKind = LHSBeforeRest; 13836 break; 13837 13838 default: 13839 SequencingKind = NoSequencing; 13840 break; 13841 } 13842 13843 if (SequencingKind == NoSequencing) 13844 return VisitCallExpr(CXXOCE); 13845 13846 // This is a call, so all subexpressions are sequenced before the result. 13847 SequencedSubexpression Sequenced(*this); 13848 13849 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13850 assert(SemaRef.getLangOpts().CPlusPlus17 && 13851 "Should only get there with C++17 and above!"); 13852 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13853 "Should only get there with an overloaded binary operator" 13854 " or an overloaded call operator!"); 13855 13856 if (SequencingKind == LHSBeforeRest) { 13857 assert(CXXOCE->getOperator() == OO_Call && 13858 "We should only have an overloaded call operator here!"); 13859 13860 // This is very similar to VisitCallExpr, except that we only have the 13861 // C++17 case. The postfix-expression is the first argument of the 13862 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13863 // are in the following arguments. 13864 // 13865 // Note that we intentionally do not visit the callee expression since 13866 // it is just a decayed reference to a function. 13867 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13868 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13869 SequenceTree::Seq OldRegion = Region; 13870 13871 assert(CXXOCE->getNumArgs() >= 1 && 13872 "An overloaded call operator must have at least one argument" 13873 " for the postfix-expression!"); 13874 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13875 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13876 CXXOCE->getNumArgs() - 1); 13877 13878 // Visit the postfix-expression first. 13879 { 13880 Region = PostfixExprRegion; 13881 SequencedSubexpression Sequenced(*this); 13882 Visit(PostfixExpr); 13883 } 13884 13885 // Then visit the argument expressions. 13886 Region = ArgsRegion; 13887 for (const Expr *Arg : Args) 13888 Visit(Arg); 13889 13890 Region = OldRegion; 13891 Tree.merge(PostfixExprRegion); 13892 Tree.merge(ArgsRegion); 13893 } else { 13894 assert(CXXOCE->getNumArgs() == 2 && 13895 "Should only have two arguments here!"); 13896 assert((SequencingKind == LHSBeforeRHS || 13897 SequencingKind == RHSBeforeLHS) && 13898 "Unexpected sequencing kind!"); 13899 13900 // We do not visit the callee expression since it is just a decayed 13901 // reference to a function. 13902 const Expr *E1 = CXXOCE->getArg(0); 13903 const Expr *E2 = CXXOCE->getArg(1); 13904 if (SequencingKind == RHSBeforeLHS) 13905 std::swap(E1, E2); 13906 13907 return VisitSequencedExpressions(E1, E2); 13908 } 13909 }); 13910 } 13911 13912 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13913 // This is a call, so all subexpressions are sequenced before the result. 13914 SequencedSubexpression Sequenced(*this); 13915 13916 if (!CCE->isListInitialization()) 13917 return VisitExpr(CCE); 13918 13919 // In C++11, list initializations are sequenced. 13920 SmallVector<SequenceTree::Seq, 32> Elts; 13921 SequenceTree::Seq Parent = Region; 13922 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13923 E = CCE->arg_end(); 13924 I != E; ++I) { 13925 Region = Tree.allocate(Parent); 13926 Elts.push_back(Region); 13927 Visit(*I); 13928 } 13929 13930 // Forget that the initializers are sequenced. 13931 Region = Parent; 13932 for (unsigned I = 0; I < Elts.size(); ++I) 13933 Tree.merge(Elts[I]); 13934 } 13935 13936 void VisitInitListExpr(const InitListExpr *ILE) { 13937 if (!SemaRef.getLangOpts().CPlusPlus11) 13938 return VisitExpr(ILE); 13939 13940 // In C++11, list initializations are sequenced. 13941 SmallVector<SequenceTree::Seq, 32> Elts; 13942 SequenceTree::Seq Parent = Region; 13943 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13944 const Expr *E = ILE->getInit(I); 13945 if (!E) 13946 continue; 13947 Region = Tree.allocate(Parent); 13948 Elts.push_back(Region); 13949 Visit(E); 13950 } 13951 13952 // Forget that the initializers are sequenced. 13953 Region = Parent; 13954 for (unsigned I = 0; I < Elts.size(); ++I) 13955 Tree.merge(Elts[I]); 13956 } 13957 }; 13958 13959 } // namespace 13960 13961 void Sema::CheckUnsequencedOperations(const Expr *E) { 13962 SmallVector<const Expr *, 8> WorkList; 13963 WorkList.push_back(E); 13964 while (!WorkList.empty()) { 13965 const Expr *Item = WorkList.pop_back_val(); 13966 SequenceChecker(*this, Item, WorkList); 13967 } 13968 } 13969 13970 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13971 bool IsConstexpr) { 13972 llvm::SaveAndRestore<bool> ConstantContext( 13973 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13974 CheckImplicitConversions(E, CheckLoc); 13975 if (!E->isInstantiationDependent()) 13976 CheckUnsequencedOperations(E); 13977 if (!IsConstexpr && !E->isValueDependent()) 13978 CheckForIntOverflow(E); 13979 DiagnoseMisalignedMembers(); 13980 } 13981 13982 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13983 FieldDecl *BitField, 13984 Expr *Init) { 13985 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13986 } 13987 13988 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13989 SourceLocation Loc) { 13990 if (!PType->isVariablyModifiedType()) 13991 return; 13992 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13993 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13994 return; 13995 } 13996 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13997 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13998 return; 13999 } 14000 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14001 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14002 return; 14003 } 14004 14005 const ArrayType *AT = S.Context.getAsArrayType(PType); 14006 if (!AT) 14007 return; 14008 14009 if (AT->getSizeModifier() != ArrayType::Star) { 14010 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14011 return; 14012 } 14013 14014 S.Diag(Loc, diag::err_array_star_in_function_definition); 14015 } 14016 14017 /// CheckParmsForFunctionDef - Check that the parameters of the given 14018 /// function are appropriate for the definition of a function. This 14019 /// takes care of any checks that cannot be performed on the 14020 /// declaration itself, e.g., that the types of each of the function 14021 /// parameters are complete. 14022 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14023 bool CheckParameterNames) { 14024 bool HasInvalidParm = false; 14025 for (ParmVarDecl *Param : Parameters) { 14026 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14027 // function declarator that is part of a function definition of 14028 // that function shall not have incomplete type. 14029 // 14030 // This is also C++ [dcl.fct]p6. 14031 if (!Param->isInvalidDecl() && 14032 RequireCompleteType(Param->getLocation(), Param->getType(), 14033 diag::err_typecheck_decl_incomplete_type)) { 14034 Param->setInvalidDecl(); 14035 HasInvalidParm = true; 14036 } 14037 14038 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14039 // declaration of each parameter shall include an identifier. 14040 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14041 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14042 // Diagnose this as an extension in C17 and earlier. 14043 if (!getLangOpts().C2x) 14044 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14045 } 14046 14047 // C99 6.7.5.3p12: 14048 // If the function declarator is not part of a definition of that 14049 // function, parameters may have incomplete type and may use the [*] 14050 // notation in their sequences of declarator specifiers to specify 14051 // variable length array types. 14052 QualType PType = Param->getOriginalType(); 14053 // FIXME: This diagnostic should point the '[*]' if source-location 14054 // information is added for it. 14055 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14056 14057 // If the parameter is a c++ class type and it has to be destructed in the 14058 // callee function, declare the destructor so that it can be called by the 14059 // callee function. Do not perform any direct access check on the dtor here. 14060 if (!Param->isInvalidDecl()) { 14061 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14062 if (!ClassDecl->isInvalidDecl() && 14063 !ClassDecl->hasIrrelevantDestructor() && 14064 !ClassDecl->isDependentContext() && 14065 ClassDecl->isParamDestroyedInCallee()) { 14066 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14067 MarkFunctionReferenced(Param->getLocation(), Destructor); 14068 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14069 } 14070 } 14071 } 14072 14073 // Parameters with the pass_object_size attribute only need to be marked 14074 // constant at function definitions. Because we lack information about 14075 // whether we're on a declaration or definition when we're instantiating the 14076 // attribute, we need to check for constness here. 14077 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14078 if (!Param->getType().isConstQualified()) 14079 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14080 << Attr->getSpelling() << 1; 14081 14082 // Check for parameter names shadowing fields from the class. 14083 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14084 // The owning context for the parameter should be the function, but we 14085 // want to see if this function's declaration context is a record. 14086 DeclContext *DC = Param->getDeclContext(); 14087 if (DC && DC->isFunctionOrMethod()) { 14088 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14089 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14090 RD, /*DeclIsField*/ false); 14091 } 14092 } 14093 } 14094 14095 return HasInvalidParm; 14096 } 14097 14098 Optional<std::pair<CharUnits, CharUnits>> 14099 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14100 14101 /// Compute the alignment and offset of the base class object given the 14102 /// derived-to-base cast expression and the alignment and offset of the derived 14103 /// class object. 14104 static std::pair<CharUnits, CharUnits> 14105 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14106 CharUnits BaseAlignment, CharUnits Offset, 14107 ASTContext &Ctx) { 14108 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14109 ++PathI) { 14110 const CXXBaseSpecifier *Base = *PathI; 14111 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14112 if (Base->isVirtual()) { 14113 // The complete object may have a lower alignment than the non-virtual 14114 // alignment of the base, in which case the base may be misaligned. Choose 14115 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14116 // conservative lower bound of the complete object alignment. 14117 CharUnits NonVirtualAlignment = 14118 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14119 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14120 Offset = CharUnits::Zero(); 14121 } else { 14122 const ASTRecordLayout &RL = 14123 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14124 Offset += RL.getBaseClassOffset(BaseDecl); 14125 } 14126 DerivedType = Base->getType(); 14127 } 14128 14129 return std::make_pair(BaseAlignment, Offset); 14130 } 14131 14132 /// Compute the alignment and offset of a binary additive operator. 14133 static Optional<std::pair<CharUnits, CharUnits>> 14134 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14135 bool IsSub, ASTContext &Ctx) { 14136 QualType PointeeType = PtrE->getType()->getPointeeType(); 14137 14138 if (!PointeeType->isConstantSizeType()) 14139 return llvm::None; 14140 14141 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14142 14143 if (!P) 14144 return llvm::None; 14145 14146 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14147 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14148 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14149 if (IsSub) 14150 Offset = -Offset; 14151 return std::make_pair(P->first, P->second + Offset); 14152 } 14153 14154 // If the integer expression isn't a constant expression, compute the lower 14155 // bound of the alignment using the alignment and offset of the pointer 14156 // expression and the element size. 14157 return std::make_pair( 14158 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14159 CharUnits::Zero()); 14160 } 14161 14162 /// This helper function takes an lvalue expression and returns the alignment of 14163 /// a VarDecl and a constant offset from the VarDecl. 14164 Optional<std::pair<CharUnits, CharUnits>> 14165 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14166 E = E->IgnoreParens(); 14167 switch (E->getStmtClass()) { 14168 default: 14169 break; 14170 case Stmt::CStyleCastExprClass: 14171 case Stmt::CXXStaticCastExprClass: 14172 case Stmt::ImplicitCastExprClass: { 14173 auto *CE = cast<CastExpr>(E); 14174 const Expr *From = CE->getSubExpr(); 14175 switch (CE->getCastKind()) { 14176 default: 14177 break; 14178 case CK_NoOp: 14179 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14180 case CK_UncheckedDerivedToBase: 14181 case CK_DerivedToBase: { 14182 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14183 if (!P) 14184 break; 14185 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14186 P->second, Ctx); 14187 } 14188 } 14189 break; 14190 } 14191 case Stmt::ArraySubscriptExprClass: { 14192 auto *ASE = cast<ArraySubscriptExpr>(E); 14193 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14194 false, Ctx); 14195 } 14196 case Stmt::DeclRefExprClass: { 14197 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14198 // FIXME: If VD is captured by copy or is an escaping __block variable, 14199 // use the alignment of VD's type. 14200 if (!VD->getType()->isReferenceType()) 14201 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14202 if (VD->hasInit()) 14203 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14204 } 14205 break; 14206 } 14207 case Stmt::MemberExprClass: { 14208 auto *ME = cast<MemberExpr>(E); 14209 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14210 if (!FD || FD->getType()->isReferenceType()) 14211 break; 14212 Optional<std::pair<CharUnits, CharUnits>> P; 14213 if (ME->isArrow()) 14214 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14215 else 14216 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14217 if (!P) 14218 break; 14219 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14220 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14221 return std::make_pair(P->first, 14222 P->second + CharUnits::fromQuantity(Offset)); 14223 } 14224 case Stmt::UnaryOperatorClass: { 14225 auto *UO = cast<UnaryOperator>(E); 14226 switch (UO->getOpcode()) { 14227 default: 14228 break; 14229 case UO_Deref: 14230 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14231 } 14232 break; 14233 } 14234 case Stmt::BinaryOperatorClass: { 14235 auto *BO = cast<BinaryOperator>(E); 14236 auto Opcode = BO->getOpcode(); 14237 switch (Opcode) { 14238 default: 14239 break; 14240 case BO_Comma: 14241 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14242 } 14243 break; 14244 } 14245 } 14246 return llvm::None; 14247 } 14248 14249 /// This helper function takes a pointer expression and returns the alignment of 14250 /// a VarDecl and a constant offset from the VarDecl. 14251 Optional<std::pair<CharUnits, CharUnits>> 14252 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14253 E = E->IgnoreParens(); 14254 switch (E->getStmtClass()) { 14255 default: 14256 break; 14257 case Stmt::CStyleCastExprClass: 14258 case Stmt::CXXStaticCastExprClass: 14259 case Stmt::ImplicitCastExprClass: { 14260 auto *CE = cast<CastExpr>(E); 14261 const Expr *From = CE->getSubExpr(); 14262 switch (CE->getCastKind()) { 14263 default: 14264 break; 14265 case CK_NoOp: 14266 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14267 case CK_ArrayToPointerDecay: 14268 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14269 case CK_UncheckedDerivedToBase: 14270 case CK_DerivedToBase: { 14271 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14272 if (!P) 14273 break; 14274 return getDerivedToBaseAlignmentAndOffset( 14275 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14276 } 14277 } 14278 break; 14279 } 14280 case Stmt::CXXThisExprClass: { 14281 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14282 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14283 return std::make_pair(Alignment, CharUnits::Zero()); 14284 } 14285 case Stmt::UnaryOperatorClass: { 14286 auto *UO = cast<UnaryOperator>(E); 14287 if (UO->getOpcode() == UO_AddrOf) 14288 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14289 break; 14290 } 14291 case Stmt::BinaryOperatorClass: { 14292 auto *BO = cast<BinaryOperator>(E); 14293 auto Opcode = BO->getOpcode(); 14294 switch (Opcode) { 14295 default: 14296 break; 14297 case BO_Add: 14298 case BO_Sub: { 14299 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14300 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14301 std::swap(LHS, RHS); 14302 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14303 Ctx); 14304 } 14305 case BO_Comma: 14306 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14307 } 14308 break; 14309 } 14310 } 14311 return llvm::None; 14312 } 14313 14314 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14315 // See if we can compute the alignment of a VarDecl and an offset from it. 14316 Optional<std::pair<CharUnits, CharUnits>> P = 14317 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14318 14319 if (P) 14320 return P->first.alignmentAtOffset(P->second); 14321 14322 // If that failed, return the type's alignment. 14323 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14324 } 14325 14326 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14327 /// pointer cast increases the alignment requirements. 14328 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14329 // This is actually a lot of work to potentially be doing on every 14330 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14331 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14332 return; 14333 14334 // Ignore dependent types. 14335 if (T->isDependentType() || Op->getType()->isDependentType()) 14336 return; 14337 14338 // Require that the destination be a pointer type. 14339 const PointerType *DestPtr = T->getAs<PointerType>(); 14340 if (!DestPtr) return; 14341 14342 // If the destination has alignment 1, we're done. 14343 QualType DestPointee = DestPtr->getPointeeType(); 14344 if (DestPointee->isIncompleteType()) return; 14345 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14346 if (DestAlign.isOne()) return; 14347 14348 // Require that the source be a pointer type. 14349 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14350 if (!SrcPtr) return; 14351 QualType SrcPointee = SrcPtr->getPointeeType(); 14352 14353 // Explicitly allow casts from cv void*. We already implicitly 14354 // allowed casts to cv void*, since they have alignment 1. 14355 // Also allow casts involving incomplete types, which implicitly 14356 // includes 'void'. 14357 if (SrcPointee->isIncompleteType()) return; 14358 14359 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14360 14361 if (SrcAlign >= DestAlign) return; 14362 14363 Diag(TRange.getBegin(), diag::warn_cast_align) 14364 << Op->getType() << T 14365 << static_cast<unsigned>(SrcAlign.getQuantity()) 14366 << static_cast<unsigned>(DestAlign.getQuantity()) 14367 << TRange << Op->getSourceRange(); 14368 } 14369 14370 /// Check whether this array fits the idiom of a size-one tail padded 14371 /// array member of a struct. 14372 /// 14373 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14374 /// commonly used to emulate flexible arrays in C89 code. 14375 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14376 const NamedDecl *ND) { 14377 if (Size != 1 || !ND) return false; 14378 14379 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14380 if (!FD) return false; 14381 14382 // Don't consider sizes resulting from macro expansions or template argument 14383 // substitution to form C89 tail-padded arrays. 14384 14385 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14386 while (TInfo) { 14387 TypeLoc TL = TInfo->getTypeLoc(); 14388 // Look through typedefs. 14389 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14390 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14391 TInfo = TDL->getTypeSourceInfo(); 14392 continue; 14393 } 14394 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14395 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14396 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14397 return false; 14398 } 14399 break; 14400 } 14401 14402 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14403 if (!RD) return false; 14404 if (RD->isUnion()) return false; 14405 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14406 if (!CRD->isStandardLayout()) return false; 14407 } 14408 14409 // See if this is the last field decl in the record. 14410 const Decl *D = FD; 14411 while ((D = D->getNextDeclInContext())) 14412 if (isa<FieldDecl>(D)) 14413 return false; 14414 return true; 14415 } 14416 14417 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14418 const ArraySubscriptExpr *ASE, 14419 bool AllowOnePastEnd, bool IndexNegated) { 14420 // Already diagnosed by the constant evaluator. 14421 if (isConstantEvaluated()) 14422 return; 14423 14424 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14425 if (IndexExpr->isValueDependent()) 14426 return; 14427 14428 const Type *EffectiveType = 14429 BaseExpr->getType()->getPointeeOrArrayElementType(); 14430 BaseExpr = BaseExpr->IgnoreParenCasts(); 14431 const ConstantArrayType *ArrayTy = 14432 Context.getAsConstantArrayType(BaseExpr->getType()); 14433 14434 if (!ArrayTy) 14435 return; 14436 14437 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 14438 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 14439 return; 14440 14441 Expr::EvalResult Result; 14442 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14443 return; 14444 14445 llvm::APSInt index = Result.Val.getInt(); 14446 if (IndexNegated) 14447 index = -index; 14448 14449 const NamedDecl *ND = nullptr; 14450 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14451 ND = DRE->getDecl(); 14452 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14453 ND = ME->getMemberDecl(); 14454 14455 if (index.isUnsigned() || !index.isNegative()) { 14456 // It is possible that the type of the base expression after 14457 // IgnoreParenCasts is incomplete, even though the type of the base 14458 // expression before IgnoreParenCasts is complete (see PR39746 for an 14459 // example). In this case we have no information about whether the array 14460 // access exceeds the array bounds. However we can still diagnose an array 14461 // access which precedes the array bounds. 14462 if (BaseType->isIncompleteType()) 14463 return; 14464 14465 llvm::APInt size = ArrayTy->getSize(); 14466 if (!size.isStrictlyPositive()) 14467 return; 14468 14469 if (BaseType != EffectiveType) { 14470 // Make sure we're comparing apples to apples when comparing index to size 14471 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14472 uint64_t array_typesize = Context.getTypeSize(BaseType); 14473 // Handle ptrarith_typesize being zero, such as when casting to void* 14474 if (!ptrarith_typesize) ptrarith_typesize = 1; 14475 if (ptrarith_typesize != array_typesize) { 14476 // There's a cast to a different size type involved 14477 uint64_t ratio = array_typesize / ptrarith_typesize; 14478 // TODO: Be smarter about handling cases where array_typesize is not a 14479 // multiple of ptrarith_typesize 14480 if (ptrarith_typesize * ratio == array_typesize) 14481 size *= llvm::APInt(size.getBitWidth(), ratio); 14482 } 14483 } 14484 14485 if (size.getBitWidth() > index.getBitWidth()) 14486 index = index.zext(size.getBitWidth()); 14487 else if (size.getBitWidth() < index.getBitWidth()) 14488 size = size.zext(index.getBitWidth()); 14489 14490 // For array subscripting the index must be less than size, but for pointer 14491 // arithmetic also allow the index (offset) to be equal to size since 14492 // computing the next address after the end of the array is legal and 14493 // commonly done e.g. in C++ iterators and range-based for loops. 14494 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14495 return; 14496 14497 // Also don't warn for arrays of size 1 which are members of some 14498 // structure. These are often used to approximate flexible arrays in C89 14499 // code. 14500 if (IsTailPaddedMemberArray(*this, size, ND)) 14501 return; 14502 14503 // Suppress the warning if the subscript expression (as identified by the 14504 // ']' location) and the index expression are both from macro expansions 14505 // within a system header. 14506 if (ASE) { 14507 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14508 ASE->getRBracketLoc()); 14509 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14510 SourceLocation IndexLoc = 14511 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14512 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14513 return; 14514 } 14515 } 14516 14517 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 14518 if (ASE) 14519 DiagID = diag::warn_array_index_exceeds_bounds; 14520 14521 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14522 PDiag(DiagID) << index.toString(10, true) 14523 << size.toString(10, true) 14524 << (unsigned)size.getLimitedValue(~0U) 14525 << IndexExpr->getSourceRange()); 14526 } else { 14527 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14528 if (!ASE) { 14529 DiagID = diag::warn_ptr_arith_precedes_bounds; 14530 if (index.isNegative()) index = -index; 14531 } 14532 14533 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14534 PDiag(DiagID) << index.toString(10, true) 14535 << IndexExpr->getSourceRange()); 14536 } 14537 14538 if (!ND) { 14539 // Try harder to find a NamedDecl to point at in the note. 14540 while (const ArraySubscriptExpr *ASE = 14541 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14542 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14543 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14544 ND = DRE->getDecl(); 14545 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14546 ND = ME->getMemberDecl(); 14547 } 14548 14549 if (ND) 14550 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14551 PDiag(diag::note_array_declared_here) << ND); 14552 } 14553 14554 void Sema::CheckArrayAccess(const Expr *expr) { 14555 int AllowOnePastEnd = 0; 14556 while (expr) { 14557 expr = expr->IgnoreParenImpCasts(); 14558 switch (expr->getStmtClass()) { 14559 case Stmt::ArraySubscriptExprClass: { 14560 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14561 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14562 AllowOnePastEnd > 0); 14563 expr = ASE->getBase(); 14564 break; 14565 } 14566 case Stmt::MemberExprClass: { 14567 expr = cast<MemberExpr>(expr)->getBase(); 14568 break; 14569 } 14570 case Stmt::OMPArraySectionExprClass: { 14571 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14572 if (ASE->getLowerBound()) 14573 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14574 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14575 return; 14576 } 14577 case Stmt::UnaryOperatorClass: { 14578 // Only unwrap the * and & unary operators 14579 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14580 expr = UO->getSubExpr(); 14581 switch (UO->getOpcode()) { 14582 case UO_AddrOf: 14583 AllowOnePastEnd++; 14584 break; 14585 case UO_Deref: 14586 AllowOnePastEnd--; 14587 break; 14588 default: 14589 return; 14590 } 14591 break; 14592 } 14593 case Stmt::ConditionalOperatorClass: { 14594 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14595 if (const Expr *lhs = cond->getLHS()) 14596 CheckArrayAccess(lhs); 14597 if (const Expr *rhs = cond->getRHS()) 14598 CheckArrayAccess(rhs); 14599 return; 14600 } 14601 case Stmt::CXXOperatorCallExprClass: { 14602 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14603 for (const auto *Arg : OCE->arguments()) 14604 CheckArrayAccess(Arg); 14605 return; 14606 } 14607 default: 14608 return; 14609 } 14610 } 14611 } 14612 14613 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14614 14615 namespace { 14616 14617 struct RetainCycleOwner { 14618 VarDecl *Variable = nullptr; 14619 SourceRange Range; 14620 SourceLocation Loc; 14621 bool Indirect = false; 14622 14623 RetainCycleOwner() = default; 14624 14625 void setLocsFrom(Expr *e) { 14626 Loc = e->getExprLoc(); 14627 Range = e->getSourceRange(); 14628 } 14629 }; 14630 14631 } // namespace 14632 14633 /// Consider whether capturing the given variable can possibly lead to 14634 /// a retain cycle. 14635 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14636 // In ARC, it's captured strongly iff the variable has __strong 14637 // lifetime. In MRR, it's captured strongly if the variable is 14638 // __block and has an appropriate type. 14639 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14640 return false; 14641 14642 owner.Variable = var; 14643 if (ref) 14644 owner.setLocsFrom(ref); 14645 return true; 14646 } 14647 14648 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14649 while (true) { 14650 e = e->IgnoreParens(); 14651 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14652 switch (cast->getCastKind()) { 14653 case CK_BitCast: 14654 case CK_LValueBitCast: 14655 case CK_LValueToRValue: 14656 case CK_ARCReclaimReturnedObject: 14657 e = cast->getSubExpr(); 14658 continue; 14659 14660 default: 14661 return false; 14662 } 14663 } 14664 14665 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14666 ObjCIvarDecl *ivar = ref->getDecl(); 14667 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14668 return false; 14669 14670 // Try to find a retain cycle in the base. 14671 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14672 return false; 14673 14674 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14675 owner.Indirect = true; 14676 return true; 14677 } 14678 14679 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14680 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14681 if (!var) return false; 14682 return considerVariable(var, ref, owner); 14683 } 14684 14685 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14686 if (member->isArrow()) return false; 14687 14688 // Don't count this as an indirect ownership. 14689 e = member->getBase(); 14690 continue; 14691 } 14692 14693 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14694 // Only pay attention to pseudo-objects on property references. 14695 ObjCPropertyRefExpr *pre 14696 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14697 ->IgnoreParens()); 14698 if (!pre) return false; 14699 if (pre->isImplicitProperty()) return false; 14700 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14701 if (!property->isRetaining() && 14702 !(property->getPropertyIvarDecl() && 14703 property->getPropertyIvarDecl()->getType() 14704 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14705 return false; 14706 14707 owner.Indirect = true; 14708 if (pre->isSuperReceiver()) { 14709 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14710 if (!owner.Variable) 14711 return false; 14712 owner.Loc = pre->getLocation(); 14713 owner.Range = pre->getSourceRange(); 14714 return true; 14715 } 14716 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14717 ->getSourceExpr()); 14718 continue; 14719 } 14720 14721 // Array ivars? 14722 14723 return false; 14724 } 14725 } 14726 14727 namespace { 14728 14729 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14730 ASTContext &Context; 14731 VarDecl *Variable; 14732 Expr *Capturer = nullptr; 14733 bool VarWillBeReased = false; 14734 14735 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14736 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14737 Context(Context), Variable(variable) {} 14738 14739 void VisitDeclRefExpr(DeclRefExpr *ref) { 14740 if (ref->getDecl() == Variable && !Capturer) 14741 Capturer = ref; 14742 } 14743 14744 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14745 if (Capturer) return; 14746 Visit(ref->getBase()); 14747 if (Capturer && ref->isFreeIvar()) 14748 Capturer = ref; 14749 } 14750 14751 void VisitBlockExpr(BlockExpr *block) { 14752 // Look inside nested blocks 14753 if (block->getBlockDecl()->capturesVariable(Variable)) 14754 Visit(block->getBlockDecl()->getBody()); 14755 } 14756 14757 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14758 if (Capturer) return; 14759 if (OVE->getSourceExpr()) 14760 Visit(OVE->getSourceExpr()); 14761 } 14762 14763 void VisitBinaryOperator(BinaryOperator *BinOp) { 14764 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14765 return; 14766 Expr *LHS = BinOp->getLHS(); 14767 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14768 if (DRE->getDecl() != Variable) 14769 return; 14770 if (Expr *RHS = BinOp->getRHS()) { 14771 RHS = RHS->IgnoreParenCasts(); 14772 Optional<llvm::APSInt> Value; 14773 VarWillBeReased = 14774 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14775 *Value == 0); 14776 } 14777 } 14778 } 14779 }; 14780 14781 } // namespace 14782 14783 /// Check whether the given argument is a block which captures a 14784 /// variable. 14785 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14786 assert(owner.Variable && owner.Loc.isValid()); 14787 14788 e = e->IgnoreParenCasts(); 14789 14790 // Look through [^{...} copy] and Block_copy(^{...}). 14791 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14792 Selector Cmd = ME->getSelector(); 14793 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14794 e = ME->getInstanceReceiver(); 14795 if (!e) 14796 return nullptr; 14797 e = e->IgnoreParenCasts(); 14798 } 14799 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14800 if (CE->getNumArgs() == 1) { 14801 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14802 if (Fn) { 14803 const IdentifierInfo *FnI = Fn->getIdentifier(); 14804 if (FnI && FnI->isStr("_Block_copy")) { 14805 e = CE->getArg(0)->IgnoreParenCasts(); 14806 } 14807 } 14808 } 14809 } 14810 14811 BlockExpr *block = dyn_cast<BlockExpr>(e); 14812 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14813 return nullptr; 14814 14815 FindCaptureVisitor visitor(S.Context, owner.Variable); 14816 visitor.Visit(block->getBlockDecl()->getBody()); 14817 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14818 } 14819 14820 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14821 RetainCycleOwner &owner) { 14822 assert(capturer); 14823 assert(owner.Variable && owner.Loc.isValid()); 14824 14825 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14826 << owner.Variable << capturer->getSourceRange(); 14827 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14828 << owner.Indirect << owner.Range; 14829 } 14830 14831 /// Check for a keyword selector that starts with the word 'add' or 14832 /// 'set'. 14833 static bool isSetterLikeSelector(Selector sel) { 14834 if (sel.isUnarySelector()) return false; 14835 14836 StringRef str = sel.getNameForSlot(0); 14837 while (!str.empty() && str.front() == '_') str = str.substr(1); 14838 if (str.startswith("set")) 14839 str = str.substr(3); 14840 else if (str.startswith("add")) { 14841 // Specially allow 'addOperationWithBlock:'. 14842 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14843 return false; 14844 str = str.substr(3); 14845 } 14846 else 14847 return false; 14848 14849 if (str.empty()) return true; 14850 return !isLowercase(str.front()); 14851 } 14852 14853 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14854 ObjCMessageExpr *Message) { 14855 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14856 Message->getReceiverInterface(), 14857 NSAPI::ClassId_NSMutableArray); 14858 if (!IsMutableArray) { 14859 return None; 14860 } 14861 14862 Selector Sel = Message->getSelector(); 14863 14864 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14865 S.NSAPIObj->getNSArrayMethodKind(Sel); 14866 if (!MKOpt) { 14867 return None; 14868 } 14869 14870 NSAPI::NSArrayMethodKind MK = *MKOpt; 14871 14872 switch (MK) { 14873 case NSAPI::NSMutableArr_addObject: 14874 case NSAPI::NSMutableArr_insertObjectAtIndex: 14875 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14876 return 0; 14877 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14878 return 1; 14879 14880 default: 14881 return None; 14882 } 14883 14884 return None; 14885 } 14886 14887 static 14888 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14889 ObjCMessageExpr *Message) { 14890 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14891 Message->getReceiverInterface(), 14892 NSAPI::ClassId_NSMutableDictionary); 14893 if (!IsMutableDictionary) { 14894 return None; 14895 } 14896 14897 Selector Sel = Message->getSelector(); 14898 14899 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14900 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14901 if (!MKOpt) { 14902 return None; 14903 } 14904 14905 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14906 14907 switch (MK) { 14908 case NSAPI::NSMutableDict_setObjectForKey: 14909 case NSAPI::NSMutableDict_setValueForKey: 14910 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14911 return 0; 14912 14913 default: 14914 return None; 14915 } 14916 14917 return None; 14918 } 14919 14920 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14921 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14922 Message->getReceiverInterface(), 14923 NSAPI::ClassId_NSMutableSet); 14924 14925 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14926 Message->getReceiverInterface(), 14927 NSAPI::ClassId_NSMutableOrderedSet); 14928 if (!IsMutableSet && !IsMutableOrderedSet) { 14929 return None; 14930 } 14931 14932 Selector Sel = Message->getSelector(); 14933 14934 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14935 if (!MKOpt) { 14936 return None; 14937 } 14938 14939 NSAPI::NSSetMethodKind MK = *MKOpt; 14940 14941 switch (MK) { 14942 case NSAPI::NSMutableSet_addObject: 14943 case NSAPI::NSOrderedSet_setObjectAtIndex: 14944 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14945 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14946 return 0; 14947 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14948 return 1; 14949 } 14950 14951 return None; 14952 } 14953 14954 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14955 if (!Message->isInstanceMessage()) { 14956 return; 14957 } 14958 14959 Optional<int> ArgOpt; 14960 14961 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14962 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14963 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14964 return; 14965 } 14966 14967 int ArgIndex = *ArgOpt; 14968 14969 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14970 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14971 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14972 } 14973 14974 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14975 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14976 if (ArgRE->isObjCSelfExpr()) { 14977 Diag(Message->getSourceRange().getBegin(), 14978 diag::warn_objc_circular_container) 14979 << ArgRE->getDecl() << StringRef("'super'"); 14980 } 14981 } 14982 } else { 14983 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14984 14985 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14986 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14987 } 14988 14989 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14990 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14991 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14992 ValueDecl *Decl = ReceiverRE->getDecl(); 14993 Diag(Message->getSourceRange().getBegin(), 14994 diag::warn_objc_circular_container) 14995 << Decl << Decl; 14996 if (!ArgRE->isObjCSelfExpr()) { 14997 Diag(Decl->getLocation(), 14998 diag::note_objc_circular_container_declared_here) 14999 << Decl; 15000 } 15001 } 15002 } 15003 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15004 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15005 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15006 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15007 Diag(Message->getSourceRange().getBegin(), 15008 diag::warn_objc_circular_container) 15009 << Decl << Decl; 15010 Diag(Decl->getLocation(), 15011 diag::note_objc_circular_container_declared_here) 15012 << Decl; 15013 } 15014 } 15015 } 15016 } 15017 } 15018 15019 /// Check a message send to see if it's likely to cause a retain cycle. 15020 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15021 // Only check instance methods whose selector looks like a setter. 15022 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15023 return; 15024 15025 // Try to find a variable that the receiver is strongly owned by. 15026 RetainCycleOwner owner; 15027 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15028 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15029 return; 15030 } else { 15031 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15032 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15033 owner.Loc = msg->getSuperLoc(); 15034 owner.Range = msg->getSuperLoc(); 15035 } 15036 15037 // Check whether the receiver is captured by any of the arguments. 15038 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15039 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15040 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15041 // noescape blocks should not be retained by the method. 15042 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15043 continue; 15044 return diagnoseRetainCycle(*this, capturer, owner); 15045 } 15046 } 15047 } 15048 15049 /// Check a property assign to see if it's likely to cause a retain cycle. 15050 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15051 RetainCycleOwner owner; 15052 if (!findRetainCycleOwner(*this, receiver, owner)) 15053 return; 15054 15055 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15056 diagnoseRetainCycle(*this, capturer, owner); 15057 } 15058 15059 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15060 RetainCycleOwner Owner; 15061 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15062 return; 15063 15064 // Because we don't have an expression for the variable, we have to set the 15065 // location explicitly here. 15066 Owner.Loc = Var->getLocation(); 15067 Owner.Range = Var->getSourceRange(); 15068 15069 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15070 diagnoseRetainCycle(*this, Capturer, Owner); 15071 } 15072 15073 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15074 Expr *RHS, bool isProperty) { 15075 // Check if RHS is an Objective-C object literal, which also can get 15076 // immediately zapped in a weak reference. Note that we explicitly 15077 // allow ObjCStringLiterals, since those are designed to never really die. 15078 RHS = RHS->IgnoreParenImpCasts(); 15079 15080 // This enum needs to match with the 'select' in 15081 // warn_objc_arc_literal_assign (off-by-1). 15082 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15083 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15084 return false; 15085 15086 S.Diag(Loc, diag::warn_arc_literal_assign) 15087 << (unsigned) Kind 15088 << (isProperty ? 0 : 1) 15089 << RHS->getSourceRange(); 15090 15091 return true; 15092 } 15093 15094 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15095 Qualifiers::ObjCLifetime LT, 15096 Expr *RHS, bool isProperty) { 15097 // Strip off any implicit cast added to get to the one ARC-specific. 15098 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15099 if (cast->getCastKind() == CK_ARCConsumeObject) { 15100 S.Diag(Loc, diag::warn_arc_retained_assign) 15101 << (LT == Qualifiers::OCL_ExplicitNone) 15102 << (isProperty ? 0 : 1) 15103 << RHS->getSourceRange(); 15104 return true; 15105 } 15106 RHS = cast->getSubExpr(); 15107 } 15108 15109 if (LT == Qualifiers::OCL_Weak && 15110 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15111 return true; 15112 15113 return false; 15114 } 15115 15116 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15117 QualType LHS, Expr *RHS) { 15118 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15119 15120 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15121 return false; 15122 15123 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15124 return true; 15125 15126 return false; 15127 } 15128 15129 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15130 Expr *LHS, Expr *RHS) { 15131 QualType LHSType; 15132 // PropertyRef on LHS type need be directly obtained from 15133 // its declaration as it has a PseudoType. 15134 ObjCPropertyRefExpr *PRE 15135 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15136 if (PRE && !PRE->isImplicitProperty()) { 15137 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15138 if (PD) 15139 LHSType = PD->getType(); 15140 } 15141 15142 if (LHSType.isNull()) 15143 LHSType = LHS->getType(); 15144 15145 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15146 15147 if (LT == Qualifiers::OCL_Weak) { 15148 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15149 getCurFunction()->markSafeWeakUse(LHS); 15150 } 15151 15152 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15153 return; 15154 15155 // FIXME. Check for other life times. 15156 if (LT != Qualifiers::OCL_None) 15157 return; 15158 15159 if (PRE) { 15160 if (PRE->isImplicitProperty()) 15161 return; 15162 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15163 if (!PD) 15164 return; 15165 15166 unsigned Attributes = PD->getPropertyAttributes(); 15167 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15168 // when 'assign' attribute was not explicitly specified 15169 // by user, ignore it and rely on property type itself 15170 // for lifetime info. 15171 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15172 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15173 LHSType->isObjCRetainableType()) 15174 return; 15175 15176 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15177 if (cast->getCastKind() == CK_ARCConsumeObject) { 15178 Diag(Loc, diag::warn_arc_retained_property_assign) 15179 << RHS->getSourceRange(); 15180 return; 15181 } 15182 RHS = cast->getSubExpr(); 15183 } 15184 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15185 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15186 return; 15187 } 15188 } 15189 } 15190 15191 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15192 15193 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15194 SourceLocation StmtLoc, 15195 const NullStmt *Body) { 15196 // Do not warn if the body is a macro that expands to nothing, e.g: 15197 // 15198 // #define CALL(x) 15199 // if (condition) 15200 // CALL(0); 15201 if (Body->hasLeadingEmptyMacro()) 15202 return false; 15203 15204 // Get line numbers of statement and body. 15205 bool StmtLineInvalid; 15206 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15207 &StmtLineInvalid); 15208 if (StmtLineInvalid) 15209 return false; 15210 15211 bool BodyLineInvalid; 15212 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15213 &BodyLineInvalid); 15214 if (BodyLineInvalid) 15215 return false; 15216 15217 // Warn if null statement and body are on the same line. 15218 if (StmtLine != BodyLine) 15219 return false; 15220 15221 return true; 15222 } 15223 15224 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15225 const Stmt *Body, 15226 unsigned DiagID) { 15227 // Since this is a syntactic check, don't emit diagnostic for template 15228 // instantiations, this just adds noise. 15229 if (CurrentInstantiationScope) 15230 return; 15231 15232 // The body should be a null statement. 15233 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15234 if (!NBody) 15235 return; 15236 15237 // Do the usual checks. 15238 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15239 return; 15240 15241 Diag(NBody->getSemiLoc(), DiagID); 15242 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15243 } 15244 15245 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15246 const Stmt *PossibleBody) { 15247 assert(!CurrentInstantiationScope); // Ensured by caller 15248 15249 SourceLocation StmtLoc; 15250 const Stmt *Body; 15251 unsigned DiagID; 15252 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15253 StmtLoc = FS->getRParenLoc(); 15254 Body = FS->getBody(); 15255 DiagID = diag::warn_empty_for_body; 15256 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15257 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15258 Body = WS->getBody(); 15259 DiagID = diag::warn_empty_while_body; 15260 } else 15261 return; // Neither `for' nor `while'. 15262 15263 // The body should be a null statement. 15264 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15265 if (!NBody) 15266 return; 15267 15268 // Skip expensive checks if diagnostic is disabled. 15269 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15270 return; 15271 15272 // Do the usual checks. 15273 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15274 return; 15275 15276 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15277 // noise level low, emit diagnostics only if for/while is followed by a 15278 // CompoundStmt, e.g.: 15279 // for (int i = 0; i < n; i++); 15280 // { 15281 // a(i); 15282 // } 15283 // or if for/while is followed by a statement with more indentation 15284 // than for/while itself: 15285 // for (int i = 0; i < n; i++); 15286 // a(i); 15287 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15288 if (!ProbableTypo) { 15289 bool BodyColInvalid; 15290 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15291 PossibleBody->getBeginLoc(), &BodyColInvalid); 15292 if (BodyColInvalid) 15293 return; 15294 15295 bool StmtColInvalid; 15296 unsigned StmtCol = 15297 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15298 if (StmtColInvalid) 15299 return; 15300 15301 if (BodyCol > StmtCol) 15302 ProbableTypo = true; 15303 } 15304 15305 if (ProbableTypo) { 15306 Diag(NBody->getSemiLoc(), DiagID); 15307 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15308 } 15309 } 15310 15311 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15312 15313 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15314 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15315 SourceLocation OpLoc) { 15316 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15317 return; 15318 15319 if (inTemplateInstantiation()) 15320 return; 15321 15322 // Strip parens and casts away. 15323 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15324 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15325 15326 // Check for a call expression 15327 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15328 if (!CE || CE->getNumArgs() != 1) 15329 return; 15330 15331 // Check for a call to std::move 15332 if (!CE->isCallToStdMove()) 15333 return; 15334 15335 // Get argument from std::move 15336 RHSExpr = CE->getArg(0); 15337 15338 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15339 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15340 15341 // Two DeclRefExpr's, check that the decls are the same. 15342 if (LHSDeclRef && RHSDeclRef) { 15343 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15344 return; 15345 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15346 RHSDeclRef->getDecl()->getCanonicalDecl()) 15347 return; 15348 15349 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15350 << LHSExpr->getSourceRange() 15351 << RHSExpr->getSourceRange(); 15352 return; 15353 } 15354 15355 // Member variables require a different approach to check for self moves. 15356 // MemberExpr's are the same if every nested MemberExpr refers to the same 15357 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15358 // the base Expr's are CXXThisExpr's. 15359 const Expr *LHSBase = LHSExpr; 15360 const Expr *RHSBase = RHSExpr; 15361 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15362 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15363 if (!LHSME || !RHSME) 15364 return; 15365 15366 while (LHSME && RHSME) { 15367 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15368 RHSME->getMemberDecl()->getCanonicalDecl()) 15369 return; 15370 15371 LHSBase = LHSME->getBase(); 15372 RHSBase = RHSME->getBase(); 15373 LHSME = dyn_cast<MemberExpr>(LHSBase); 15374 RHSME = dyn_cast<MemberExpr>(RHSBase); 15375 } 15376 15377 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15378 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15379 if (LHSDeclRef && RHSDeclRef) { 15380 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15381 return; 15382 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15383 RHSDeclRef->getDecl()->getCanonicalDecl()) 15384 return; 15385 15386 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15387 << LHSExpr->getSourceRange() 15388 << RHSExpr->getSourceRange(); 15389 return; 15390 } 15391 15392 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15393 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15394 << LHSExpr->getSourceRange() 15395 << RHSExpr->getSourceRange(); 15396 } 15397 15398 //===--- Layout compatibility ----------------------------------------------// 15399 15400 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15401 15402 /// Check if two enumeration types are layout-compatible. 15403 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15404 // C++11 [dcl.enum] p8: 15405 // Two enumeration types are layout-compatible if they have the same 15406 // underlying type. 15407 return ED1->isComplete() && ED2->isComplete() && 15408 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15409 } 15410 15411 /// Check if two fields are layout-compatible. 15412 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15413 FieldDecl *Field2) { 15414 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15415 return false; 15416 15417 if (Field1->isBitField() != Field2->isBitField()) 15418 return false; 15419 15420 if (Field1->isBitField()) { 15421 // Make sure that the bit-fields are the same length. 15422 unsigned Bits1 = Field1->getBitWidthValue(C); 15423 unsigned Bits2 = Field2->getBitWidthValue(C); 15424 15425 if (Bits1 != Bits2) 15426 return false; 15427 } 15428 15429 return true; 15430 } 15431 15432 /// Check if two standard-layout structs are layout-compatible. 15433 /// (C++11 [class.mem] p17) 15434 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15435 RecordDecl *RD2) { 15436 // If both records are C++ classes, check that base classes match. 15437 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15438 // If one of records is a CXXRecordDecl we are in C++ mode, 15439 // thus the other one is a CXXRecordDecl, too. 15440 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15441 // Check number of base classes. 15442 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15443 return false; 15444 15445 // Check the base classes. 15446 for (CXXRecordDecl::base_class_const_iterator 15447 Base1 = D1CXX->bases_begin(), 15448 BaseEnd1 = D1CXX->bases_end(), 15449 Base2 = D2CXX->bases_begin(); 15450 Base1 != BaseEnd1; 15451 ++Base1, ++Base2) { 15452 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15453 return false; 15454 } 15455 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15456 // If only RD2 is a C++ class, it should have zero base classes. 15457 if (D2CXX->getNumBases() > 0) 15458 return false; 15459 } 15460 15461 // Check the fields. 15462 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15463 Field2End = RD2->field_end(), 15464 Field1 = RD1->field_begin(), 15465 Field1End = RD1->field_end(); 15466 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15467 if (!isLayoutCompatible(C, *Field1, *Field2)) 15468 return false; 15469 } 15470 if (Field1 != Field1End || Field2 != Field2End) 15471 return false; 15472 15473 return true; 15474 } 15475 15476 /// Check if two standard-layout unions are layout-compatible. 15477 /// (C++11 [class.mem] p18) 15478 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15479 RecordDecl *RD2) { 15480 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15481 for (auto *Field2 : RD2->fields()) 15482 UnmatchedFields.insert(Field2); 15483 15484 for (auto *Field1 : RD1->fields()) { 15485 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15486 I = UnmatchedFields.begin(), 15487 E = UnmatchedFields.end(); 15488 15489 for ( ; I != E; ++I) { 15490 if (isLayoutCompatible(C, Field1, *I)) { 15491 bool Result = UnmatchedFields.erase(*I); 15492 (void) Result; 15493 assert(Result); 15494 break; 15495 } 15496 } 15497 if (I == E) 15498 return false; 15499 } 15500 15501 return UnmatchedFields.empty(); 15502 } 15503 15504 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15505 RecordDecl *RD2) { 15506 if (RD1->isUnion() != RD2->isUnion()) 15507 return false; 15508 15509 if (RD1->isUnion()) 15510 return isLayoutCompatibleUnion(C, RD1, RD2); 15511 else 15512 return isLayoutCompatibleStruct(C, RD1, RD2); 15513 } 15514 15515 /// Check if two types are layout-compatible in C++11 sense. 15516 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15517 if (T1.isNull() || T2.isNull()) 15518 return false; 15519 15520 // C++11 [basic.types] p11: 15521 // If two types T1 and T2 are the same type, then T1 and T2 are 15522 // layout-compatible types. 15523 if (C.hasSameType(T1, T2)) 15524 return true; 15525 15526 T1 = T1.getCanonicalType().getUnqualifiedType(); 15527 T2 = T2.getCanonicalType().getUnqualifiedType(); 15528 15529 const Type::TypeClass TC1 = T1->getTypeClass(); 15530 const Type::TypeClass TC2 = T2->getTypeClass(); 15531 15532 if (TC1 != TC2) 15533 return false; 15534 15535 if (TC1 == Type::Enum) { 15536 return isLayoutCompatible(C, 15537 cast<EnumType>(T1)->getDecl(), 15538 cast<EnumType>(T2)->getDecl()); 15539 } else if (TC1 == Type::Record) { 15540 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15541 return false; 15542 15543 return isLayoutCompatible(C, 15544 cast<RecordType>(T1)->getDecl(), 15545 cast<RecordType>(T2)->getDecl()); 15546 } 15547 15548 return false; 15549 } 15550 15551 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15552 15553 /// Given a type tag expression find the type tag itself. 15554 /// 15555 /// \param TypeExpr Type tag expression, as it appears in user's code. 15556 /// 15557 /// \param VD Declaration of an identifier that appears in a type tag. 15558 /// 15559 /// \param MagicValue Type tag magic value. 15560 /// 15561 /// \param isConstantEvaluated wether the evalaution should be performed in 15562 15563 /// constant context. 15564 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15565 const ValueDecl **VD, uint64_t *MagicValue, 15566 bool isConstantEvaluated) { 15567 while(true) { 15568 if (!TypeExpr) 15569 return false; 15570 15571 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15572 15573 switch (TypeExpr->getStmtClass()) { 15574 case Stmt::UnaryOperatorClass: { 15575 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15576 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15577 TypeExpr = UO->getSubExpr(); 15578 continue; 15579 } 15580 return false; 15581 } 15582 15583 case Stmt::DeclRefExprClass: { 15584 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15585 *VD = DRE->getDecl(); 15586 return true; 15587 } 15588 15589 case Stmt::IntegerLiteralClass: { 15590 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15591 llvm::APInt MagicValueAPInt = IL->getValue(); 15592 if (MagicValueAPInt.getActiveBits() <= 64) { 15593 *MagicValue = MagicValueAPInt.getZExtValue(); 15594 return true; 15595 } else 15596 return false; 15597 } 15598 15599 case Stmt::BinaryConditionalOperatorClass: 15600 case Stmt::ConditionalOperatorClass: { 15601 const AbstractConditionalOperator *ACO = 15602 cast<AbstractConditionalOperator>(TypeExpr); 15603 bool Result; 15604 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15605 isConstantEvaluated)) { 15606 if (Result) 15607 TypeExpr = ACO->getTrueExpr(); 15608 else 15609 TypeExpr = ACO->getFalseExpr(); 15610 continue; 15611 } 15612 return false; 15613 } 15614 15615 case Stmt::BinaryOperatorClass: { 15616 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15617 if (BO->getOpcode() == BO_Comma) { 15618 TypeExpr = BO->getRHS(); 15619 continue; 15620 } 15621 return false; 15622 } 15623 15624 default: 15625 return false; 15626 } 15627 } 15628 } 15629 15630 /// Retrieve the C type corresponding to type tag TypeExpr. 15631 /// 15632 /// \param TypeExpr Expression that specifies a type tag. 15633 /// 15634 /// \param MagicValues Registered magic values. 15635 /// 15636 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15637 /// kind. 15638 /// 15639 /// \param TypeInfo Information about the corresponding C type. 15640 /// 15641 /// \param isConstantEvaluated wether the evalaution should be performed in 15642 /// constant context. 15643 /// 15644 /// \returns true if the corresponding C type was found. 15645 static bool GetMatchingCType( 15646 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15647 const ASTContext &Ctx, 15648 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15649 *MagicValues, 15650 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15651 bool isConstantEvaluated) { 15652 FoundWrongKind = false; 15653 15654 // Variable declaration that has type_tag_for_datatype attribute. 15655 const ValueDecl *VD = nullptr; 15656 15657 uint64_t MagicValue; 15658 15659 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15660 return false; 15661 15662 if (VD) { 15663 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15664 if (I->getArgumentKind() != ArgumentKind) { 15665 FoundWrongKind = true; 15666 return false; 15667 } 15668 TypeInfo.Type = I->getMatchingCType(); 15669 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15670 TypeInfo.MustBeNull = I->getMustBeNull(); 15671 return true; 15672 } 15673 return false; 15674 } 15675 15676 if (!MagicValues) 15677 return false; 15678 15679 llvm::DenseMap<Sema::TypeTagMagicValue, 15680 Sema::TypeTagData>::const_iterator I = 15681 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15682 if (I == MagicValues->end()) 15683 return false; 15684 15685 TypeInfo = I->second; 15686 return true; 15687 } 15688 15689 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15690 uint64_t MagicValue, QualType Type, 15691 bool LayoutCompatible, 15692 bool MustBeNull) { 15693 if (!TypeTagForDatatypeMagicValues) 15694 TypeTagForDatatypeMagicValues.reset( 15695 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15696 15697 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15698 (*TypeTagForDatatypeMagicValues)[Magic] = 15699 TypeTagData(Type, LayoutCompatible, MustBeNull); 15700 } 15701 15702 static bool IsSameCharType(QualType T1, QualType T2) { 15703 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15704 if (!BT1) 15705 return false; 15706 15707 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15708 if (!BT2) 15709 return false; 15710 15711 BuiltinType::Kind T1Kind = BT1->getKind(); 15712 BuiltinType::Kind T2Kind = BT2->getKind(); 15713 15714 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15715 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15716 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15717 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15718 } 15719 15720 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15721 const ArrayRef<const Expr *> ExprArgs, 15722 SourceLocation CallSiteLoc) { 15723 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15724 bool IsPointerAttr = Attr->getIsPointer(); 15725 15726 // Retrieve the argument representing the 'type_tag'. 15727 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15728 if (TypeTagIdxAST >= ExprArgs.size()) { 15729 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15730 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15731 return; 15732 } 15733 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15734 bool FoundWrongKind; 15735 TypeTagData TypeInfo; 15736 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15737 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15738 TypeInfo, isConstantEvaluated())) { 15739 if (FoundWrongKind) 15740 Diag(TypeTagExpr->getExprLoc(), 15741 diag::warn_type_tag_for_datatype_wrong_kind) 15742 << TypeTagExpr->getSourceRange(); 15743 return; 15744 } 15745 15746 // Retrieve the argument representing the 'arg_idx'. 15747 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15748 if (ArgumentIdxAST >= ExprArgs.size()) { 15749 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15750 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15751 return; 15752 } 15753 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15754 if (IsPointerAttr) { 15755 // Skip implicit cast of pointer to `void *' (as a function argument). 15756 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15757 if (ICE->getType()->isVoidPointerType() && 15758 ICE->getCastKind() == CK_BitCast) 15759 ArgumentExpr = ICE->getSubExpr(); 15760 } 15761 QualType ArgumentType = ArgumentExpr->getType(); 15762 15763 // Passing a `void*' pointer shouldn't trigger a warning. 15764 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15765 return; 15766 15767 if (TypeInfo.MustBeNull) { 15768 // Type tag with matching void type requires a null pointer. 15769 if (!ArgumentExpr->isNullPointerConstant(Context, 15770 Expr::NPC_ValueDependentIsNotNull)) { 15771 Diag(ArgumentExpr->getExprLoc(), 15772 diag::warn_type_safety_null_pointer_required) 15773 << ArgumentKind->getName() 15774 << ArgumentExpr->getSourceRange() 15775 << TypeTagExpr->getSourceRange(); 15776 } 15777 return; 15778 } 15779 15780 QualType RequiredType = TypeInfo.Type; 15781 if (IsPointerAttr) 15782 RequiredType = Context.getPointerType(RequiredType); 15783 15784 bool mismatch = false; 15785 if (!TypeInfo.LayoutCompatible) { 15786 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15787 15788 // C++11 [basic.fundamental] p1: 15789 // Plain char, signed char, and unsigned char are three distinct types. 15790 // 15791 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15792 // char' depending on the current char signedness mode. 15793 if (mismatch) 15794 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15795 RequiredType->getPointeeType())) || 15796 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15797 mismatch = false; 15798 } else 15799 if (IsPointerAttr) 15800 mismatch = !isLayoutCompatible(Context, 15801 ArgumentType->getPointeeType(), 15802 RequiredType->getPointeeType()); 15803 else 15804 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15805 15806 if (mismatch) 15807 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15808 << ArgumentType << ArgumentKind 15809 << TypeInfo.LayoutCompatible << RequiredType 15810 << ArgumentExpr->getSourceRange() 15811 << TypeTagExpr->getSourceRange(); 15812 } 15813 15814 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15815 CharUnits Alignment) { 15816 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15817 } 15818 15819 void Sema::DiagnoseMisalignedMembers() { 15820 for (MisalignedMember &m : MisalignedMembers) { 15821 const NamedDecl *ND = m.RD; 15822 if (ND->getName().empty()) { 15823 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15824 ND = TD; 15825 } 15826 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15827 << m.MD << ND << m.E->getSourceRange(); 15828 } 15829 MisalignedMembers.clear(); 15830 } 15831 15832 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15833 E = E->IgnoreParens(); 15834 if (!T->isPointerType() && !T->isIntegerType()) 15835 return; 15836 if (isa<UnaryOperator>(E) && 15837 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15838 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15839 if (isa<MemberExpr>(Op)) { 15840 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15841 if (MA != MisalignedMembers.end() && 15842 (T->isIntegerType() || 15843 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15844 Context.getTypeAlignInChars( 15845 T->getPointeeType()) <= MA->Alignment)))) 15846 MisalignedMembers.erase(MA); 15847 } 15848 } 15849 } 15850 15851 void Sema::RefersToMemberWithReducedAlignment( 15852 Expr *E, 15853 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15854 Action) { 15855 const auto *ME = dyn_cast<MemberExpr>(E); 15856 if (!ME) 15857 return; 15858 15859 // No need to check expressions with an __unaligned-qualified type. 15860 if (E->getType().getQualifiers().hasUnaligned()) 15861 return; 15862 15863 // For a chain of MemberExpr like "a.b.c.d" this list 15864 // will keep FieldDecl's like [d, c, b]. 15865 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15866 const MemberExpr *TopME = nullptr; 15867 bool AnyIsPacked = false; 15868 do { 15869 QualType BaseType = ME->getBase()->getType(); 15870 if (BaseType->isDependentType()) 15871 return; 15872 if (ME->isArrow()) 15873 BaseType = BaseType->getPointeeType(); 15874 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15875 if (RD->isInvalidDecl()) 15876 return; 15877 15878 ValueDecl *MD = ME->getMemberDecl(); 15879 auto *FD = dyn_cast<FieldDecl>(MD); 15880 // We do not care about non-data members. 15881 if (!FD || FD->isInvalidDecl()) 15882 return; 15883 15884 AnyIsPacked = 15885 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15886 ReverseMemberChain.push_back(FD); 15887 15888 TopME = ME; 15889 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15890 } while (ME); 15891 assert(TopME && "We did not compute a topmost MemberExpr!"); 15892 15893 // Not the scope of this diagnostic. 15894 if (!AnyIsPacked) 15895 return; 15896 15897 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15898 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15899 // TODO: The innermost base of the member expression may be too complicated. 15900 // For now, just disregard these cases. This is left for future 15901 // improvement. 15902 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15903 return; 15904 15905 // Alignment expected by the whole expression. 15906 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15907 15908 // No need to do anything else with this case. 15909 if (ExpectedAlignment.isOne()) 15910 return; 15911 15912 // Synthesize offset of the whole access. 15913 CharUnits Offset; 15914 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15915 I++) { 15916 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15917 } 15918 15919 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15920 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15921 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15922 15923 // The base expression of the innermost MemberExpr may give 15924 // stronger guarantees than the class containing the member. 15925 if (DRE && !TopME->isArrow()) { 15926 const ValueDecl *VD = DRE->getDecl(); 15927 if (!VD->getType()->isReferenceType()) 15928 CompleteObjectAlignment = 15929 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15930 } 15931 15932 // Check if the synthesized offset fulfills the alignment. 15933 if (Offset % ExpectedAlignment != 0 || 15934 // It may fulfill the offset it but the effective alignment may still be 15935 // lower than the expected expression alignment. 15936 CompleteObjectAlignment < ExpectedAlignment) { 15937 // If this happens, we want to determine a sensible culprit of this. 15938 // Intuitively, watching the chain of member expressions from right to 15939 // left, we start with the required alignment (as required by the field 15940 // type) but some packed attribute in that chain has reduced the alignment. 15941 // It may happen that another packed structure increases it again. But if 15942 // we are here such increase has not been enough. So pointing the first 15943 // FieldDecl that either is packed or else its RecordDecl is, 15944 // seems reasonable. 15945 FieldDecl *FD = nullptr; 15946 CharUnits Alignment; 15947 for (FieldDecl *FDI : ReverseMemberChain) { 15948 if (FDI->hasAttr<PackedAttr>() || 15949 FDI->getParent()->hasAttr<PackedAttr>()) { 15950 FD = FDI; 15951 Alignment = std::min( 15952 Context.getTypeAlignInChars(FD->getType()), 15953 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15954 break; 15955 } 15956 } 15957 assert(FD && "We did not find a packed FieldDecl!"); 15958 Action(E, FD->getParent(), FD, Alignment); 15959 } 15960 } 15961 15962 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15963 using namespace std::placeholders; 15964 15965 RefersToMemberWithReducedAlignment( 15966 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15967 _2, _3, _4)); 15968 } 15969 15970 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15971 ExprResult CallResult) { 15972 if (checkArgCount(*this, TheCall, 1)) 15973 return ExprError(); 15974 15975 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15976 if (MatrixArg.isInvalid()) 15977 return MatrixArg; 15978 Expr *Matrix = MatrixArg.get(); 15979 15980 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15981 if (!MType) { 15982 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15983 return ExprError(); 15984 } 15985 15986 // Create returned matrix type by swapping rows and columns of the argument 15987 // matrix type. 15988 QualType ResultType = Context.getConstantMatrixType( 15989 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15990 15991 // Change the return type to the type of the returned matrix. 15992 TheCall->setType(ResultType); 15993 15994 // Update call argument to use the possibly converted matrix argument. 15995 TheCall->setArg(0, Matrix); 15996 return CallResult; 15997 } 15998 15999 // Get and verify the matrix dimensions. 16000 static llvm::Optional<unsigned> 16001 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16002 SourceLocation ErrorPos; 16003 Optional<llvm::APSInt> Value = 16004 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16005 if (!Value) { 16006 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16007 << Name; 16008 return {}; 16009 } 16010 uint64_t Dim = Value->getZExtValue(); 16011 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16012 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16013 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16014 return {}; 16015 } 16016 return Dim; 16017 } 16018 16019 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16020 ExprResult CallResult) { 16021 if (!getLangOpts().MatrixTypes) { 16022 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16023 return ExprError(); 16024 } 16025 16026 if (checkArgCount(*this, TheCall, 4)) 16027 return ExprError(); 16028 16029 unsigned PtrArgIdx = 0; 16030 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16031 Expr *RowsExpr = TheCall->getArg(1); 16032 Expr *ColumnsExpr = TheCall->getArg(2); 16033 Expr *StrideExpr = TheCall->getArg(3); 16034 16035 bool ArgError = false; 16036 16037 // Check pointer argument. 16038 { 16039 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16040 if (PtrConv.isInvalid()) 16041 return PtrConv; 16042 PtrExpr = PtrConv.get(); 16043 TheCall->setArg(0, PtrExpr); 16044 if (PtrExpr->isTypeDependent()) { 16045 TheCall->setType(Context.DependentTy); 16046 return TheCall; 16047 } 16048 } 16049 16050 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16051 QualType ElementTy; 16052 if (!PtrTy) { 16053 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16054 << PtrArgIdx + 1; 16055 ArgError = true; 16056 } else { 16057 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16058 16059 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16060 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16061 << PtrArgIdx + 1; 16062 ArgError = true; 16063 } 16064 } 16065 16066 // Apply default Lvalue conversions and convert the expression to size_t. 16067 auto ApplyArgumentConversions = [this](Expr *E) { 16068 ExprResult Conv = DefaultLvalueConversion(E); 16069 if (Conv.isInvalid()) 16070 return Conv; 16071 16072 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16073 }; 16074 16075 // Apply conversion to row and column expressions. 16076 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16077 if (!RowsConv.isInvalid()) { 16078 RowsExpr = RowsConv.get(); 16079 TheCall->setArg(1, RowsExpr); 16080 } else 16081 RowsExpr = nullptr; 16082 16083 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16084 if (!ColumnsConv.isInvalid()) { 16085 ColumnsExpr = ColumnsConv.get(); 16086 TheCall->setArg(2, ColumnsExpr); 16087 } else 16088 ColumnsExpr = nullptr; 16089 16090 // If any any part of the result matrix type is still pending, just use 16091 // Context.DependentTy, until all parts are resolved. 16092 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16093 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16094 TheCall->setType(Context.DependentTy); 16095 return CallResult; 16096 } 16097 16098 // Check row and column dimenions. 16099 llvm::Optional<unsigned> MaybeRows; 16100 if (RowsExpr) 16101 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16102 16103 llvm::Optional<unsigned> MaybeColumns; 16104 if (ColumnsExpr) 16105 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16106 16107 // Check stride argument. 16108 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16109 if (StrideConv.isInvalid()) 16110 return ExprError(); 16111 StrideExpr = StrideConv.get(); 16112 TheCall->setArg(3, StrideExpr); 16113 16114 if (MaybeRows) { 16115 if (Optional<llvm::APSInt> Value = 16116 StrideExpr->getIntegerConstantExpr(Context)) { 16117 uint64_t Stride = Value->getZExtValue(); 16118 if (Stride < *MaybeRows) { 16119 Diag(StrideExpr->getBeginLoc(), 16120 diag::err_builtin_matrix_stride_too_small); 16121 ArgError = true; 16122 } 16123 } 16124 } 16125 16126 if (ArgError || !MaybeRows || !MaybeColumns) 16127 return ExprError(); 16128 16129 TheCall->setType( 16130 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16131 return CallResult; 16132 } 16133 16134 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16135 ExprResult CallResult) { 16136 if (checkArgCount(*this, TheCall, 3)) 16137 return ExprError(); 16138 16139 unsigned PtrArgIdx = 1; 16140 Expr *MatrixExpr = TheCall->getArg(0); 16141 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16142 Expr *StrideExpr = TheCall->getArg(2); 16143 16144 bool ArgError = false; 16145 16146 { 16147 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16148 if (MatrixConv.isInvalid()) 16149 return MatrixConv; 16150 MatrixExpr = MatrixConv.get(); 16151 TheCall->setArg(0, MatrixExpr); 16152 } 16153 if (MatrixExpr->isTypeDependent()) { 16154 TheCall->setType(Context.DependentTy); 16155 return TheCall; 16156 } 16157 16158 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16159 if (!MatrixTy) { 16160 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16161 ArgError = true; 16162 } 16163 16164 { 16165 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16166 if (PtrConv.isInvalid()) 16167 return PtrConv; 16168 PtrExpr = PtrConv.get(); 16169 TheCall->setArg(1, PtrExpr); 16170 if (PtrExpr->isTypeDependent()) { 16171 TheCall->setType(Context.DependentTy); 16172 return TheCall; 16173 } 16174 } 16175 16176 // Check pointer argument. 16177 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16178 if (!PtrTy) { 16179 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16180 << PtrArgIdx + 1; 16181 ArgError = true; 16182 } else { 16183 QualType ElementTy = PtrTy->getPointeeType(); 16184 if (ElementTy.isConstQualified()) { 16185 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16186 ArgError = true; 16187 } 16188 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16189 if (MatrixTy && 16190 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16191 Diag(PtrExpr->getBeginLoc(), 16192 diag::err_builtin_matrix_pointer_arg_mismatch) 16193 << ElementTy << MatrixTy->getElementType(); 16194 ArgError = true; 16195 } 16196 } 16197 16198 // Apply default Lvalue conversions and convert the stride expression to 16199 // size_t. 16200 { 16201 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16202 if (StrideConv.isInvalid()) 16203 return StrideConv; 16204 16205 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16206 if (StrideConv.isInvalid()) 16207 return StrideConv; 16208 StrideExpr = StrideConv.get(); 16209 TheCall->setArg(2, StrideExpr); 16210 } 16211 16212 // Check stride argument. 16213 if (MatrixTy) { 16214 if (Optional<llvm::APSInt> Value = 16215 StrideExpr->getIntegerConstantExpr(Context)) { 16216 uint64_t Stride = Value->getZExtValue(); 16217 if (Stride < MatrixTy->getNumRows()) { 16218 Diag(StrideExpr->getBeginLoc(), 16219 diag::err_builtin_matrix_stride_too_small); 16220 ArgError = true; 16221 } 16222 } 16223 } 16224 16225 if (ArgError) 16226 return ExprError(); 16227 16228 return CallResult; 16229 } 16230 16231 /// \brief Enforce the bounds of a TCB 16232 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16233 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16234 /// and enforce_tcb_leaf attributes. 16235 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16236 const FunctionDecl *Callee) { 16237 const FunctionDecl *Caller = getCurFunctionDecl(); 16238 16239 // Calls to builtins are not enforced. 16240 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16241 Callee->getBuiltinID() != 0) 16242 return; 16243 16244 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16245 // all TCBs the callee is a part of. 16246 llvm::StringSet<> CalleeTCBs; 16247 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16248 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16249 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16250 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16251 16252 // Go through the TCBs the caller is a part of and emit warnings if Caller 16253 // is in a TCB that the Callee is not. 16254 for_each( 16255 Caller->specific_attrs<EnforceTCBAttr>(), 16256 [&](const auto *A) { 16257 StringRef CallerTCB = A->getTCBName(); 16258 if (CalleeTCBs.count(CallerTCB) == 0) { 16259 this->Diag(TheCall->getExprLoc(), 16260 diag::warn_tcb_enforcement_violation) << Callee 16261 << CallerTCB; 16262 } 16263 }); 16264 } 16265