1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 592 /// __builtin_*_chk function, then use the object size argument specified in the 593 /// source. Otherwise, infer the object size using __builtin_object_size. 594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 595 CallExpr *TheCall) { 596 // FIXME: There are some more useful checks we could be doing here: 597 // - Evaluate strlen of strcpy arguments, use as object size. 598 599 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 600 isConstantEvaluated()) 601 return; 602 603 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 604 if (!BuiltinID) 605 return; 606 607 const TargetInfo &TI = getASTContext().getTargetInfo(); 608 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 609 610 unsigned DiagID = 0; 611 bool IsChkVariant = false; 612 Optional<llvm::APSInt> UsedSize; 613 unsigned SizeIndex, ObjectIndex; 614 switch (BuiltinID) { 615 default: 616 return; 617 case Builtin::BIsprintf: 618 case Builtin::BI__builtin___sprintf_chk: { 619 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 620 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 621 622 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 623 624 if (!Format->isAscii() && !Format->isUTF8()) 625 return; 626 627 StringRef FormatStrRef = Format->getString(); 628 EstimateSizeFormatHandler H(FormatStrRef); 629 const char *FormatBytes = FormatStrRef.data(); 630 const ConstantArrayType *T = 631 Context.getAsConstantArrayType(Format->getType()); 632 assert(T && "String literal not of constant array type!"); 633 size_t TypeSize = T->getSize().getZExtValue(); 634 635 // In case there's a null byte somewhere. 636 size_t StrLen = 637 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 638 if (!analyze_format_string::ParsePrintfString( 639 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 640 Context.getTargetInfo(), false)) { 641 DiagID = diag::warn_fortify_source_format_overflow; 642 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 643 .extOrTrunc(SizeTypeWidth); 644 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 645 IsChkVariant = true; 646 ObjectIndex = 2; 647 } else { 648 IsChkVariant = false; 649 ObjectIndex = 0; 650 } 651 break; 652 } 653 } 654 return; 655 } 656 case Builtin::BI__builtin___memcpy_chk: 657 case Builtin::BI__builtin___memmove_chk: 658 case Builtin::BI__builtin___memset_chk: 659 case Builtin::BI__builtin___strlcat_chk: 660 case Builtin::BI__builtin___strlcpy_chk: 661 case Builtin::BI__builtin___strncat_chk: 662 case Builtin::BI__builtin___strncpy_chk: 663 case Builtin::BI__builtin___stpncpy_chk: 664 case Builtin::BI__builtin___memccpy_chk: 665 case Builtin::BI__builtin___mempcpy_chk: { 666 DiagID = diag::warn_builtin_chk_overflow; 667 IsChkVariant = true; 668 SizeIndex = TheCall->getNumArgs() - 2; 669 ObjectIndex = TheCall->getNumArgs() - 1; 670 break; 671 } 672 673 case Builtin::BI__builtin___snprintf_chk: 674 case Builtin::BI__builtin___vsnprintf_chk: { 675 DiagID = diag::warn_builtin_chk_overflow; 676 IsChkVariant = true; 677 SizeIndex = 1; 678 ObjectIndex = 3; 679 break; 680 } 681 682 case Builtin::BIstrncat: 683 case Builtin::BI__builtin_strncat: 684 case Builtin::BIstrncpy: 685 case Builtin::BI__builtin_strncpy: 686 case Builtin::BIstpncpy: 687 case Builtin::BI__builtin_stpncpy: { 688 // Whether these functions overflow depends on the runtime strlen of the 689 // string, not just the buffer size, so emitting the "always overflow" 690 // diagnostic isn't quite right. We should still diagnose passing a buffer 691 // size larger than the destination buffer though; this is a runtime abort 692 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 693 DiagID = diag::warn_fortify_source_size_mismatch; 694 SizeIndex = TheCall->getNumArgs() - 1; 695 ObjectIndex = 0; 696 break; 697 } 698 699 case Builtin::BImemcpy: 700 case Builtin::BI__builtin_memcpy: 701 case Builtin::BImemmove: 702 case Builtin::BI__builtin_memmove: 703 case Builtin::BImemset: 704 case Builtin::BI__builtin_memset: 705 case Builtin::BImempcpy: 706 case Builtin::BI__builtin_mempcpy: { 707 DiagID = diag::warn_fortify_source_overflow; 708 SizeIndex = TheCall->getNumArgs() - 1; 709 ObjectIndex = 0; 710 break; 711 } 712 case Builtin::BIsnprintf: 713 case Builtin::BI__builtin_snprintf: 714 case Builtin::BIvsnprintf: 715 case Builtin::BI__builtin_vsnprintf: { 716 DiagID = diag::warn_fortify_source_size_mismatch; 717 SizeIndex = 1; 718 ObjectIndex = 0; 719 break; 720 } 721 } 722 723 llvm::APSInt ObjectSize; 724 // For __builtin___*_chk, the object size is explicitly provided by the caller 725 // (usually using __builtin_object_size). Use that value to check this call. 726 if (IsChkVariant) { 727 Expr::EvalResult Result; 728 Expr *SizeArg = TheCall->getArg(ObjectIndex); 729 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 730 return; 731 ObjectSize = Result.Val.getInt(); 732 733 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 734 } else { 735 // If the parameter has a pass_object_size attribute, then we should use its 736 // (potentially) more strict checking mode. Otherwise, conservatively assume 737 // type 0. 738 int BOSType = 0; 739 if (const auto *POS = 740 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 741 BOSType = POS->getType(); 742 743 Expr *ObjArg = TheCall->getArg(ObjectIndex); 744 uint64_t Result; 745 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 746 return; 747 // Get the object size in the target's size_t width. 748 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 749 } 750 751 // Evaluate the number of bytes of the object that this call will use. 752 if (!UsedSize) { 753 Expr::EvalResult Result; 754 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 755 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 756 return; 757 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 758 } 759 760 if (UsedSize.getValue().ule(ObjectSize)) 761 return; 762 763 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 764 // Skim off the details of whichever builtin was called to produce a better 765 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 766 if (IsChkVariant) { 767 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 768 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 769 } else if (FunctionName.startswith("__builtin_")) { 770 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 771 } 772 773 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 774 PDiag(DiagID) 775 << FunctionName << toString(ObjectSize, /*Radix=*/10) 776 << toString(UsedSize.getValue(), /*Radix=*/10)); 777 } 778 779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 780 Scope::ScopeFlags NeededScopeFlags, 781 unsigned DiagID) { 782 // Scopes aren't available during instantiation. Fortunately, builtin 783 // functions cannot be template args so they cannot be formed through template 784 // instantiation. Therefore checking once during the parse is sufficient. 785 if (SemaRef.inTemplateInstantiation()) 786 return false; 787 788 Scope *S = SemaRef.getCurScope(); 789 while (S && !S->isSEHExceptScope()) 790 S = S->getParent(); 791 if (!S || !(S->getFlags() & NeededScopeFlags)) { 792 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 793 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 794 << DRE->getDecl()->getIdentifier(); 795 return true; 796 } 797 798 return false; 799 } 800 801 static inline bool isBlockPointer(Expr *Arg) { 802 return Arg->getType()->isBlockPointerType(); 803 } 804 805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 806 /// void*, which is a requirement of device side enqueue. 807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 808 const BlockPointerType *BPT = 809 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 810 ArrayRef<QualType> Params = 811 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 812 unsigned ArgCounter = 0; 813 bool IllegalParams = false; 814 // Iterate through the block parameters until either one is found that is not 815 // a local void*, or the block is valid. 816 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 817 I != E; ++I, ++ArgCounter) { 818 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 819 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 820 LangAS::opencl_local) { 821 // Get the location of the error. If a block literal has been passed 822 // (BlockExpr) then we can point straight to the offending argument, 823 // else we just point to the variable reference. 824 SourceLocation ErrorLoc; 825 if (isa<BlockExpr>(BlockArg)) { 826 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 827 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 828 } else if (isa<DeclRefExpr>(BlockArg)) { 829 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 830 } 831 S.Diag(ErrorLoc, 832 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 833 IllegalParams = true; 834 } 835 } 836 837 return IllegalParams; 838 } 839 840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 841 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 842 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 843 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 844 return true; 845 } 846 return false; 847 } 848 849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 850 if (checkArgCount(S, TheCall, 2)) 851 return true; 852 853 if (checkOpenCLSubgroupExt(S, TheCall)) 854 return true; 855 856 // First argument is an ndrange_t type. 857 Expr *NDRangeArg = TheCall->getArg(0); 858 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 859 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 860 << TheCall->getDirectCallee() << "'ndrange_t'"; 861 return true; 862 } 863 864 Expr *BlockArg = TheCall->getArg(1); 865 if (!isBlockPointer(BlockArg)) { 866 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 867 << TheCall->getDirectCallee() << "block"; 868 return true; 869 } 870 return checkOpenCLBlockArgs(S, BlockArg); 871 } 872 873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 874 /// get_kernel_work_group_size 875 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 877 if (checkArgCount(S, TheCall, 1)) 878 return true; 879 880 Expr *BlockArg = TheCall->getArg(0); 881 if (!isBlockPointer(BlockArg)) { 882 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 883 << TheCall->getDirectCallee() << "block"; 884 return true; 885 } 886 return checkOpenCLBlockArgs(S, BlockArg); 887 } 888 889 /// Diagnose integer type and any valid implicit conversion to it. 890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 891 const QualType &IntType); 892 893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 894 unsigned Start, unsigned End) { 895 bool IllegalParams = false; 896 for (unsigned I = Start; I <= End; ++I) 897 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 898 S.Context.getSizeType()); 899 return IllegalParams; 900 } 901 902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 903 /// 'local void*' parameter of passed block. 904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 905 Expr *BlockArg, 906 unsigned NumNonVarArgs) { 907 const BlockPointerType *BPT = 908 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 909 unsigned NumBlockParams = 910 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 911 unsigned TotalNumArgs = TheCall->getNumArgs(); 912 913 // For each argument passed to the block, a corresponding uint needs to 914 // be passed to describe the size of the local memory. 915 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 916 S.Diag(TheCall->getBeginLoc(), 917 diag::err_opencl_enqueue_kernel_local_size_args); 918 return true; 919 } 920 921 // Check that the sizes of the local memory are specified by integers. 922 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 923 TotalNumArgs - 1); 924 } 925 926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 927 /// overload formats specified in Table 6.13.17.1. 928 /// int enqueue_kernel(queue_t queue, 929 /// kernel_enqueue_flags_t flags, 930 /// const ndrange_t ndrange, 931 /// void (^block)(void)) 932 /// int enqueue_kernel(queue_t queue, 933 /// kernel_enqueue_flags_t flags, 934 /// const ndrange_t ndrange, 935 /// uint num_events_in_wait_list, 936 /// clk_event_t *event_wait_list, 937 /// clk_event_t *event_ret, 938 /// void (^block)(void)) 939 /// int enqueue_kernel(queue_t queue, 940 /// kernel_enqueue_flags_t flags, 941 /// const ndrange_t ndrange, 942 /// void (^block)(local void*, ...), 943 /// uint size0, ...) 944 /// int enqueue_kernel(queue_t queue, 945 /// kernel_enqueue_flags_t flags, 946 /// const ndrange_t ndrange, 947 /// uint num_events_in_wait_list, 948 /// clk_event_t *event_wait_list, 949 /// clk_event_t *event_ret, 950 /// void (^block)(local void*, ...), 951 /// uint size0, ...) 952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 953 unsigned NumArgs = TheCall->getNumArgs(); 954 955 if (NumArgs < 4) { 956 S.Diag(TheCall->getBeginLoc(), 957 diag::err_typecheck_call_too_few_args_at_least) 958 << 0 << 4 << NumArgs; 959 return true; 960 } 961 962 Expr *Arg0 = TheCall->getArg(0); 963 Expr *Arg1 = TheCall->getArg(1); 964 Expr *Arg2 = TheCall->getArg(2); 965 Expr *Arg3 = TheCall->getArg(3); 966 967 // First argument always needs to be a queue_t type. 968 if (!Arg0->getType()->isQueueT()) { 969 S.Diag(TheCall->getArg(0)->getBeginLoc(), 970 diag::err_opencl_builtin_expected_type) 971 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 972 return true; 973 } 974 975 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 976 if (!Arg1->getType()->isIntegerType()) { 977 S.Diag(TheCall->getArg(1)->getBeginLoc(), 978 diag::err_opencl_builtin_expected_type) 979 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 980 return true; 981 } 982 983 // Third argument is always an ndrange_t type. 984 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 985 S.Diag(TheCall->getArg(2)->getBeginLoc(), 986 diag::err_opencl_builtin_expected_type) 987 << TheCall->getDirectCallee() << "'ndrange_t'"; 988 return true; 989 } 990 991 // With four arguments, there is only one form that the function could be 992 // called in: no events and no variable arguments. 993 if (NumArgs == 4) { 994 // check that the last argument is the right block type. 995 if (!isBlockPointer(Arg3)) { 996 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 997 << TheCall->getDirectCallee() << "block"; 998 return true; 999 } 1000 // we have a block type, check the prototype 1001 const BlockPointerType *BPT = 1002 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1003 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1004 S.Diag(Arg3->getBeginLoc(), 1005 diag::err_opencl_enqueue_kernel_blocks_no_args); 1006 return true; 1007 } 1008 return false; 1009 } 1010 // we can have block + varargs. 1011 if (isBlockPointer(Arg3)) 1012 return (checkOpenCLBlockArgs(S, Arg3) || 1013 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1014 // last two cases with either exactly 7 args or 7 args and varargs. 1015 if (NumArgs >= 7) { 1016 // check common block argument. 1017 Expr *Arg6 = TheCall->getArg(6); 1018 if (!isBlockPointer(Arg6)) { 1019 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1020 << TheCall->getDirectCallee() << "block"; 1021 return true; 1022 } 1023 if (checkOpenCLBlockArgs(S, Arg6)) 1024 return true; 1025 1026 // Forth argument has to be any integer type. 1027 if (!Arg3->getType()->isIntegerType()) { 1028 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1029 diag::err_opencl_builtin_expected_type) 1030 << TheCall->getDirectCallee() << "integer"; 1031 return true; 1032 } 1033 // check remaining common arguments. 1034 Expr *Arg4 = TheCall->getArg(4); 1035 Expr *Arg5 = TheCall->getArg(5); 1036 1037 // Fifth argument is always passed as a pointer to clk_event_t. 1038 if (!Arg4->isNullPointerConstant(S.Context, 1039 Expr::NPC_ValueDependentIsNotNull) && 1040 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1041 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1042 diag::err_opencl_builtin_expected_type) 1043 << TheCall->getDirectCallee() 1044 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1045 return true; 1046 } 1047 1048 // Sixth argument is always passed as a pointer to clk_event_t. 1049 if (!Arg5->isNullPointerConstant(S.Context, 1050 Expr::NPC_ValueDependentIsNotNull) && 1051 !(Arg5->getType()->isPointerType() && 1052 Arg5->getType()->getPointeeType()->isClkEventT())) { 1053 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1054 diag::err_opencl_builtin_expected_type) 1055 << TheCall->getDirectCallee() 1056 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1057 return true; 1058 } 1059 1060 if (NumArgs == 7) 1061 return false; 1062 1063 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1064 } 1065 1066 // None of the specific case has been detected, give generic error 1067 S.Diag(TheCall->getBeginLoc(), 1068 diag::err_opencl_enqueue_kernel_incorrect_args); 1069 return true; 1070 } 1071 1072 /// Returns OpenCL access qual. 1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1074 return D->getAttr<OpenCLAccessAttr>(); 1075 } 1076 1077 /// Returns true if pipe element type is different from the pointer. 1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1079 const Expr *Arg0 = Call->getArg(0); 1080 // First argument type should always be pipe. 1081 if (!Arg0->getType()->isPipeType()) { 1082 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1083 << Call->getDirectCallee() << Arg0->getSourceRange(); 1084 return true; 1085 } 1086 OpenCLAccessAttr *AccessQual = 1087 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1088 // Validates the access qualifier is compatible with the call. 1089 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1090 // read_only and write_only, and assumed to be read_only if no qualifier is 1091 // specified. 1092 switch (Call->getDirectCallee()->getBuiltinID()) { 1093 case Builtin::BIread_pipe: 1094 case Builtin::BIreserve_read_pipe: 1095 case Builtin::BIcommit_read_pipe: 1096 case Builtin::BIwork_group_reserve_read_pipe: 1097 case Builtin::BIsub_group_reserve_read_pipe: 1098 case Builtin::BIwork_group_commit_read_pipe: 1099 case Builtin::BIsub_group_commit_read_pipe: 1100 if (!(!AccessQual || AccessQual->isReadOnly())) { 1101 S.Diag(Arg0->getBeginLoc(), 1102 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1103 << "read_only" << Arg0->getSourceRange(); 1104 return true; 1105 } 1106 break; 1107 case Builtin::BIwrite_pipe: 1108 case Builtin::BIreserve_write_pipe: 1109 case Builtin::BIcommit_write_pipe: 1110 case Builtin::BIwork_group_reserve_write_pipe: 1111 case Builtin::BIsub_group_reserve_write_pipe: 1112 case Builtin::BIwork_group_commit_write_pipe: 1113 case Builtin::BIsub_group_commit_write_pipe: 1114 if (!(AccessQual && AccessQual->isWriteOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "write_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 default: 1122 break; 1123 } 1124 return false; 1125 } 1126 1127 /// Returns true if pipe element type is different from the pointer. 1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1129 const Expr *Arg0 = Call->getArg(0); 1130 const Expr *ArgIdx = Call->getArg(Idx); 1131 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1132 const QualType EltTy = PipeTy->getElementType(); 1133 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1134 // The Idx argument should be a pointer and the type of the pointer and 1135 // the type of pipe element should also be the same. 1136 if (!ArgTy || 1137 !S.Context.hasSameType( 1138 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1139 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1140 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1141 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1142 return true; 1143 } 1144 return false; 1145 } 1146 1147 // Performs semantic analysis for the read/write_pipe call. 1148 // \param S Reference to the semantic analyzer. 1149 // \param Call A pointer to the builtin call. 1150 // \return True if a semantic error has been found, false otherwise. 1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1152 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1153 // functions have two forms. 1154 switch (Call->getNumArgs()) { 1155 case 2: 1156 if (checkOpenCLPipeArg(S, Call)) 1157 return true; 1158 // The call with 2 arguments should be 1159 // read/write_pipe(pipe T, T*). 1160 // Check packet type T. 1161 if (checkOpenCLPipePacketType(S, Call, 1)) 1162 return true; 1163 break; 1164 1165 case 4: { 1166 if (checkOpenCLPipeArg(S, Call)) 1167 return true; 1168 // The call with 4 arguments should be 1169 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1170 // Check reserve_id_t. 1171 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1172 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1173 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1174 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1175 return true; 1176 } 1177 1178 // Check the index. 1179 const Expr *Arg2 = Call->getArg(2); 1180 if (!Arg2->getType()->isIntegerType() && 1181 !Arg2->getType()->isUnsignedIntegerType()) { 1182 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1183 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1184 << Arg2->getType() << Arg2->getSourceRange(); 1185 return true; 1186 } 1187 1188 // Check packet type T. 1189 if (checkOpenCLPipePacketType(S, Call, 3)) 1190 return true; 1191 } break; 1192 default: 1193 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1194 << Call->getDirectCallee() << Call->getSourceRange(); 1195 return true; 1196 } 1197 1198 return false; 1199 } 1200 1201 // Performs a semantic analysis on the {work_group_/sub_group_ 1202 // /_}reserve_{read/write}_pipe 1203 // \param S Reference to the semantic analyzer. 1204 // \param Call The call to the builtin function to be analyzed. 1205 // \return True if a semantic error was found, false otherwise. 1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1207 if (checkArgCount(S, Call, 2)) 1208 return true; 1209 1210 if (checkOpenCLPipeArg(S, Call)) 1211 return true; 1212 1213 // Check the reserve size. 1214 if (!Call->getArg(1)->getType()->isIntegerType() && 1215 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1216 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1217 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1218 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1219 return true; 1220 } 1221 1222 // Since return type of reserve_read/write_pipe built-in function is 1223 // reserve_id_t, which is not defined in the builtin def file , we used int 1224 // as return type and need to override the return type of these functions. 1225 Call->setType(S.Context.OCLReserveIDTy); 1226 1227 return false; 1228 } 1229 1230 // Performs a semantic analysis on {work_group_/sub_group_ 1231 // /_}commit_{read/write}_pipe 1232 // \param S Reference to the semantic analyzer. 1233 // \param Call The call to the builtin function to be analyzed. 1234 // \return True if a semantic error was found, false otherwise. 1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1236 if (checkArgCount(S, Call, 2)) 1237 return true; 1238 1239 if (checkOpenCLPipeArg(S, Call)) 1240 return true; 1241 1242 // Check reserve_id_t. 1243 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1244 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1245 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1246 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1247 return true; 1248 } 1249 1250 return false; 1251 } 1252 1253 // Performs a semantic analysis on the call to built-in Pipe 1254 // Query Functions. 1255 // \param S Reference to the semantic analyzer. 1256 // \param Call The call to the builtin function to be analyzed. 1257 // \return True if a semantic error was found, false otherwise. 1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1259 if (checkArgCount(S, Call, 1)) 1260 return true; 1261 1262 if (!Call->getArg(0)->getType()->isPipeType()) { 1263 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1264 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1265 return true; 1266 } 1267 1268 return false; 1269 } 1270 1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1272 // Performs semantic analysis for the to_global/local/private call. 1273 // \param S Reference to the semantic analyzer. 1274 // \param BuiltinID ID of the builtin function. 1275 // \param Call A pointer to the builtin call. 1276 // \return True if a semantic error has been found, false otherwise. 1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1278 CallExpr *Call) { 1279 if (checkArgCount(S, Call, 1)) 1280 return true; 1281 1282 auto RT = Call->getArg(0)->getType(); 1283 if (!RT->isPointerType() || RT->getPointeeType() 1284 .getAddressSpace() == LangAS::opencl_constant) { 1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1286 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1287 return true; 1288 } 1289 1290 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1291 S.Diag(Call->getArg(0)->getBeginLoc(), 1292 diag::warn_opencl_generic_address_space_arg) 1293 << Call->getDirectCallee()->getNameInfo().getAsString() 1294 << Call->getArg(0)->getSourceRange(); 1295 } 1296 1297 RT = RT->getPointeeType(); 1298 auto Qual = RT.getQualifiers(); 1299 switch (BuiltinID) { 1300 case Builtin::BIto_global: 1301 Qual.setAddressSpace(LangAS::opencl_global); 1302 break; 1303 case Builtin::BIto_local: 1304 Qual.setAddressSpace(LangAS::opencl_local); 1305 break; 1306 case Builtin::BIto_private: 1307 Qual.setAddressSpace(LangAS::opencl_private); 1308 break; 1309 default: 1310 llvm_unreachable("Invalid builtin function"); 1311 } 1312 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1313 RT.getUnqualifiedType(), Qual))); 1314 1315 return false; 1316 } 1317 1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1319 if (checkArgCount(S, TheCall, 1)) 1320 return ExprError(); 1321 1322 // Compute __builtin_launder's parameter type from the argument. 1323 // The parameter type is: 1324 // * The type of the argument if it's not an array or function type, 1325 // Otherwise, 1326 // * The decayed argument type. 1327 QualType ParamTy = [&]() { 1328 QualType ArgTy = TheCall->getArg(0)->getType(); 1329 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1330 return S.Context.getPointerType(Ty->getElementType()); 1331 if (ArgTy->isFunctionType()) { 1332 return S.Context.getPointerType(ArgTy); 1333 } 1334 return ArgTy; 1335 }(); 1336 1337 TheCall->setType(ParamTy); 1338 1339 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1340 if (!ParamTy->isPointerType()) 1341 return 0; 1342 if (ParamTy->isFunctionPointerType()) 1343 return 1; 1344 if (ParamTy->isVoidPointerType()) 1345 return 2; 1346 return llvm::Optional<unsigned>{}; 1347 }(); 1348 if (DiagSelect.hasValue()) { 1349 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1350 << DiagSelect.getValue() << TheCall->getSourceRange(); 1351 return ExprError(); 1352 } 1353 1354 // We either have an incomplete class type, or we have a class template 1355 // whose instantiation has not been forced. Example: 1356 // 1357 // template <class T> struct Foo { T value; }; 1358 // Foo<int> *p = nullptr; 1359 // auto *d = __builtin_launder(p); 1360 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1361 diag::err_incomplete_type)) 1362 return ExprError(); 1363 1364 assert(ParamTy->getPointeeType()->isObjectType() && 1365 "Unhandled non-object pointer case"); 1366 1367 InitializedEntity Entity = 1368 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1369 ExprResult Arg = 1370 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1371 if (Arg.isInvalid()) 1372 return ExprError(); 1373 TheCall->setArg(0, Arg.get()); 1374 1375 return TheCall; 1376 } 1377 1378 // Emit an error and return true if the current architecture is not in the list 1379 // of supported architectures. 1380 static bool 1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1382 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1383 llvm::Triple::ArchType CurArch = 1384 S.getASTContext().getTargetInfo().getTriple().getArch(); 1385 if (llvm::is_contained(SupportedArchs, CurArch)) 1386 return false; 1387 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1388 << TheCall->getSourceRange(); 1389 return true; 1390 } 1391 1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1393 SourceLocation CallSiteLoc); 1394 1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1396 CallExpr *TheCall) { 1397 switch (TI.getTriple().getArch()) { 1398 default: 1399 // Some builtins don't require additional checking, so just consider these 1400 // acceptable. 1401 return false; 1402 case llvm::Triple::arm: 1403 case llvm::Triple::armeb: 1404 case llvm::Triple::thumb: 1405 case llvm::Triple::thumbeb: 1406 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1407 case llvm::Triple::aarch64: 1408 case llvm::Triple::aarch64_32: 1409 case llvm::Triple::aarch64_be: 1410 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1411 case llvm::Triple::bpfeb: 1412 case llvm::Triple::bpfel: 1413 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::hexagon: 1415 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1416 case llvm::Triple::mips: 1417 case llvm::Triple::mipsel: 1418 case llvm::Triple::mips64: 1419 case llvm::Triple::mips64el: 1420 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::systemz: 1422 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1423 case llvm::Triple::x86: 1424 case llvm::Triple::x86_64: 1425 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1426 case llvm::Triple::ppc: 1427 case llvm::Triple::ppcle: 1428 case llvm::Triple::ppc64: 1429 case llvm::Triple::ppc64le: 1430 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1431 case llvm::Triple::amdgcn: 1432 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1433 case llvm::Triple::riscv32: 1434 case llvm::Triple::riscv64: 1435 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1436 } 1437 } 1438 1439 ExprResult 1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1441 CallExpr *TheCall) { 1442 ExprResult TheCallResult(TheCall); 1443 1444 // Find out if any arguments are required to be integer constant expressions. 1445 unsigned ICEArguments = 0; 1446 ASTContext::GetBuiltinTypeError Error; 1447 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1448 if (Error != ASTContext::GE_None) 1449 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1450 1451 // If any arguments are required to be ICE's, check and diagnose. 1452 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1453 // Skip arguments not required to be ICE's. 1454 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1455 1456 llvm::APSInt Result; 1457 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1458 return true; 1459 ICEArguments &= ~(1 << ArgNo); 1460 } 1461 1462 switch (BuiltinID) { 1463 case Builtin::BI__builtin___CFStringMakeConstantString: 1464 assert(TheCall->getNumArgs() == 1 && 1465 "Wrong # arguments to builtin CFStringMakeConstantString"); 1466 if (CheckObjCString(TheCall->getArg(0))) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__builtin_ms_va_start: 1470 case Builtin::BI__builtin_stdarg_start: 1471 case Builtin::BI__builtin_va_start: 1472 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1473 return ExprError(); 1474 break; 1475 case Builtin::BI__va_start: { 1476 switch (Context.getTargetInfo().getTriple().getArch()) { 1477 case llvm::Triple::aarch64: 1478 case llvm::Triple::arm: 1479 case llvm::Triple::thumb: 1480 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1481 return ExprError(); 1482 break; 1483 default: 1484 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1485 return ExprError(); 1486 break; 1487 } 1488 break; 1489 } 1490 1491 // The acquire, release, and no fence variants are ARM and AArch64 only. 1492 case Builtin::BI_interlockedbittestandset_acq: 1493 case Builtin::BI_interlockedbittestandset_rel: 1494 case Builtin::BI_interlockedbittestandset_nf: 1495 case Builtin::BI_interlockedbittestandreset_acq: 1496 case Builtin::BI_interlockedbittestandreset_rel: 1497 case Builtin::BI_interlockedbittestandreset_nf: 1498 if (CheckBuiltinTargetSupport( 1499 *this, BuiltinID, TheCall, 1500 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1501 return ExprError(); 1502 break; 1503 1504 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1505 case Builtin::BI_bittest64: 1506 case Builtin::BI_bittestandcomplement64: 1507 case Builtin::BI_bittestandreset64: 1508 case Builtin::BI_bittestandset64: 1509 case Builtin::BI_interlockedbittestandreset64: 1510 case Builtin::BI_interlockedbittestandset64: 1511 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1512 {llvm::Triple::x86_64, llvm::Triple::arm, 1513 llvm::Triple::thumb, llvm::Triple::aarch64})) 1514 return ExprError(); 1515 break; 1516 1517 case Builtin::BI__builtin_isgreater: 1518 case Builtin::BI__builtin_isgreaterequal: 1519 case Builtin::BI__builtin_isless: 1520 case Builtin::BI__builtin_islessequal: 1521 case Builtin::BI__builtin_islessgreater: 1522 case Builtin::BI__builtin_isunordered: 1523 if (SemaBuiltinUnorderedCompare(TheCall)) 1524 return ExprError(); 1525 break; 1526 case Builtin::BI__builtin_fpclassify: 1527 if (SemaBuiltinFPClassification(TheCall, 6)) 1528 return ExprError(); 1529 break; 1530 case Builtin::BI__builtin_isfinite: 1531 case Builtin::BI__builtin_isinf: 1532 case Builtin::BI__builtin_isinf_sign: 1533 case Builtin::BI__builtin_isnan: 1534 case Builtin::BI__builtin_isnormal: 1535 case Builtin::BI__builtin_signbit: 1536 case Builtin::BI__builtin_signbitf: 1537 case Builtin::BI__builtin_signbitl: 1538 if (SemaBuiltinFPClassification(TheCall, 1)) 1539 return ExprError(); 1540 break; 1541 case Builtin::BI__builtin_shufflevector: 1542 return SemaBuiltinShuffleVector(TheCall); 1543 // TheCall will be freed by the smart pointer here, but that's fine, since 1544 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1545 case Builtin::BI__builtin_prefetch: 1546 if (SemaBuiltinPrefetch(TheCall)) 1547 return ExprError(); 1548 break; 1549 case Builtin::BI__builtin_alloca_with_align: 1550 if (SemaBuiltinAllocaWithAlign(TheCall)) 1551 return ExprError(); 1552 LLVM_FALLTHROUGH; 1553 case Builtin::BI__builtin_alloca: 1554 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1555 << TheCall->getDirectCallee(); 1556 break; 1557 case Builtin::BI__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 case Builtin::BI__builtin_get_device_side_mangled_name: { 1971 auto Check = [](CallExpr *TheCall) { 1972 if (TheCall->getNumArgs() != 1) 1973 return false; 1974 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1975 if (!DRE) 1976 return false; 1977 auto *D = DRE->getDecl(); 1978 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1979 return false; 1980 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1981 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 1982 }; 1983 if (!Check(TheCall)) { 1984 Diag(TheCall->getBeginLoc(), 1985 diag::err_hip_invalid_args_builtin_mangled_name); 1986 return ExprError(); 1987 } 1988 } 1989 } 1990 1991 // Since the target specific builtins for each arch overlap, only check those 1992 // of the arch we are compiling for. 1993 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1994 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1995 assert(Context.getAuxTargetInfo() && 1996 "Aux Target Builtin, but not an aux target?"); 1997 1998 if (CheckTSBuiltinFunctionCall( 1999 *Context.getAuxTargetInfo(), 2000 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2001 return ExprError(); 2002 } else { 2003 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2004 TheCall)) 2005 return ExprError(); 2006 } 2007 } 2008 2009 return TheCallResult; 2010 } 2011 2012 // Get the valid immediate range for the specified NEON type code. 2013 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2014 NeonTypeFlags Type(t); 2015 int IsQuad = ForceQuad ? true : Type.isQuad(); 2016 switch (Type.getEltType()) { 2017 case NeonTypeFlags::Int8: 2018 case NeonTypeFlags::Poly8: 2019 return shift ? 7 : (8 << IsQuad) - 1; 2020 case NeonTypeFlags::Int16: 2021 case NeonTypeFlags::Poly16: 2022 return shift ? 15 : (4 << IsQuad) - 1; 2023 case NeonTypeFlags::Int32: 2024 return shift ? 31 : (2 << IsQuad) - 1; 2025 case NeonTypeFlags::Int64: 2026 case NeonTypeFlags::Poly64: 2027 return shift ? 63 : (1 << IsQuad) - 1; 2028 case NeonTypeFlags::Poly128: 2029 return shift ? 127 : (1 << IsQuad) - 1; 2030 case NeonTypeFlags::Float16: 2031 assert(!shift && "cannot shift float types!"); 2032 return (4 << IsQuad) - 1; 2033 case NeonTypeFlags::Float32: 2034 assert(!shift && "cannot shift float types!"); 2035 return (2 << IsQuad) - 1; 2036 case NeonTypeFlags::Float64: 2037 assert(!shift && "cannot shift float types!"); 2038 return (1 << IsQuad) - 1; 2039 case NeonTypeFlags::BFloat16: 2040 assert(!shift && "cannot shift float types!"); 2041 return (4 << IsQuad) - 1; 2042 } 2043 llvm_unreachable("Invalid NeonTypeFlag!"); 2044 } 2045 2046 /// getNeonEltType - Return the QualType corresponding to the elements of 2047 /// the vector type specified by the NeonTypeFlags. This is used to check 2048 /// the pointer arguments for Neon load/store intrinsics. 2049 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2050 bool IsPolyUnsigned, bool IsInt64Long) { 2051 switch (Flags.getEltType()) { 2052 case NeonTypeFlags::Int8: 2053 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2054 case NeonTypeFlags::Int16: 2055 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2056 case NeonTypeFlags::Int32: 2057 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2058 case NeonTypeFlags::Int64: 2059 if (IsInt64Long) 2060 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2061 else 2062 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2063 : Context.LongLongTy; 2064 case NeonTypeFlags::Poly8: 2065 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2066 case NeonTypeFlags::Poly16: 2067 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2068 case NeonTypeFlags::Poly64: 2069 if (IsInt64Long) 2070 return Context.UnsignedLongTy; 2071 else 2072 return Context.UnsignedLongLongTy; 2073 case NeonTypeFlags::Poly128: 2074 break; 2075 case NeonTypeFlags::Float16: 2076 return Context.HalfTy; 2077 case NeonTypeFlags::Float32: 2078 return Context.FloatTy; 2079 case NeonTypeFlags::Float64: 2080 return Context.DoubleTy; 2081 case NeonTypeFlags::BFloat16: 2082 return Context.BFloat16Ty; 2083 } 2084 llvm_unreachable("Invalid NeonTypeFlag!"); 2085 } 2086 2087 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2088 // Range check SVE intrinsics that take immediate values. 2089 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2090 2091 switch (BuiltinID) { 2092 default: 2093 return false; 2094 #define GET_SVE_IMMEDIATE_CHECK 2095 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2096 #undef GET_SVE_IMMEDIATE_CHECK 2097 } 2098 2099 // Perform all the immediate checks for this builtin call. 2100 bool HasError = false; 2101 for (auto &I : ImmChecks) { 2102 int ArgNum, CheckTy, ElementSizeInBits; 2103 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2104 2105 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2106 2107 // Function that checks whether the operand (ArgNum) is an immediate 2108 // that is one of the predefined values. 2109 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2110 int ErrDiag) -> bool { 2111 // We can't check the value of a dependent argument. 2112 Expr *Arg = TheCall->getArg(ArgNum); 2113 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2114 return false; 2115 2116 // Check constant-ness first. 2117 llvm::APSInt Imm; 2118 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2119 return true; 2120 2121 if (!CheckImm(Imm.getSExtValue())) 2122 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2123 return false; 2124 }; 2125 2126 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2127 case SVETypeFlags::ImmCheck0_31: 2128 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2129 HasError = true; 2130 break; 2131 case SVETypeFlags::ImmCheck0_13: 2132 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2133 HasError = true; 2134 break; 2135 case SVETypeFlags::ImmCheck1_16: 2136 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2137 HasError = true; 2138 break; 2139 case SVETypeFlags::ImmCheck0_7: 2140 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2141 HasError = true; 2142 break; 2143 case SVETypeFlags::ImmCheckExtract: 2144 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2145 (2048 / ElementSizeInBits) - 1)) 2146 HasError = true; 2147 break; 2148 case SVETypeFlags::ImmCheckShiftRight: 2149 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2150 HasError = true; 2151 break; 2152 case SVETypeFlags::ImmCheckShiftRightNarrow: 2153 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2154 ElementSizeInBits / 2)) 2155 HasError = true; 2156 break; 2157 case SVETypeFlags::ImmCheckShiftLeft: 2158 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2159 ElementSizeInBits - 1)) 2160 HasError = true; 2161 break; 2162 case SVETypeFlags::ImmCheckLaneIndex: 2163 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2164 (128 / (1 * ElementSizeInBits)) - 1)) 2165 HasError = true; 2166 break; 2167 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2168 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2169 (128 / (2 * ElementSizeInBits)) - 1)) 2170 HasError = true; 2171 break; 2172 case SVETypeFlags::ImmCheckLaneIndexDot: 2173 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2174 (128 / (4 * ElementSizeInBits)) - 1)) 2175 HasError = true; 2176 break; 2177 case SVETypeFlags::ImmCheckComplexRot90_270: 2178 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2179 diag::err_rotation_argument_to_cadd)) 2180 HasError = true; 2181 break; 2182 case SVETypeFlags::ImmCheckComplexRotAll90: 2183 if (CheckImmediateInSet( 2184 [](int64_t V) { 2185 return V == 0 || V == 90 || V == 180 || V == 270; 2186 }, 2187 diag::err_rotation_argument_to_cmla)) 2188 HasError = true; 2189 break; 2190 case SVETypeFlags::ImmCheck0_1: 2191 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2192 HasError = true; 2193 break; 2194 case SVETypeFlags::ImmCheck0_2: 2195 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2196 HasError = true; 2197 break; 2198 case SVETypeFlags::ImmCheck0_3: 2199 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2200 HasError = true; 2201 break; 2202 } 2203 } 2204 2205 return HasError; 2206 } 2207 2208 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2209 unsigned BuiltinID, CallExpr *TheCall) { 2210 llvm::APSInt Result; 2211 uint64_t mask = 0; 2212 unsigned TV = 0; 2213 int PtrArgNum = -1; 2214 bool HasConstPtr = false; 2215 switch (BuiltinID) { 2216 #define GET_NEON_OVERLOAD_CHECK 2217 #include "clang/Basic/arm_neon.inc" 2218 #include "clang/Basic/arm_fp16.inc" 2219 #undef GET_NEON_OVERLOAD_CHECK 2220 } 2221 2222 // For NEON intrinsics which are overloaded on vector element type, validate 2223 // the immediate which specifies which variant to emit. 2224 unsigned ImmArg = TheCall->getNumArgs()-1; 2225 if (mask) { 2226 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2227 return true; 2228 2229 TV = Result.getLimitedValue(64); 2230 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2231 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2232 << TheCall->getArg(ImmArg)->getSourceRange(); 2233 } 2234 2235 if (PtrArgNum >= 0) { 2236 // Check that pointer arguments have the specified type. 2237 Expr *Arg = TheCall->getArg(PtrArgNum); 2238 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2239 Arg = ICE->getSubExpr(); 2240 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2241 QualType RHSTy = RHS.get()->getType(); 2242 2243 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2244 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2245 Arch == llvm::Triple::aarch64_32 || 2246 Arch == llvm::Triple::aarch64_be; 2247 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2248 QualType EltTy = 2249 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2250 if (HasConstPtr) 2251 EltTy = EltTy.withConst(); 2252 QualType LHSTy = Context.getPointerType(EltTy); 2253 AssignConvertType ConvTy; 2254 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2255 if (RHS.isInvalid()) 2256 return true; 2257 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2258 RHS.get(), AA_Assigning)) 2259 return true; 2260 } 2261 2262 // For NEON intrinsics which take an immediate value as part of the 2263 // instruction, range check them here. 2264 unsigned i = 0, l = 0, u = 0; 2265 switch (BuiltinID) { 2266 default: 2267 return false; 2268 #define GET_NEON_IMMEDIATE_CHECK 2269 #include "clang/Basic/arm_neon.inc" 2270 #include "clang/Basic/arm_fp16.inc" 2271 #undef GET_NEON_IMMEDIATE_CHECK 2272 } 2273 2274 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2275 } 2276 2277 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2278 switch (BuiltinID) { 2279 default: 2280 return false; 2281 #include "clang/Basic/arm_mve_builtin_sema.inc" 2282 } 2283 } 2284 2285 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2286 CallExpr *TheCall) { 2287 bool Err = false; 2288 switch (BuiltinID) { 2289 default: 2290 return false; 2291 #include "clang/Basic/arm_cde_builtin_sema.inc" 2292 } 2293 2294 if (Err) 2295 return true; 2296 2297 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2298 } 2299 2300 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2301 const Expr *CoprocArg, bool WantCDE) { 2302 if (isConstantEvaluated()) 2303 return false; 2304 2305 // We can't check the value of a dependent argument. 2306 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2307 return false; 2308 2309 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2310 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2311 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2312 2313 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2314 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2315 2316 if (IsCDECoproc != WantCDE) 2317 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2318 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2319 2320 return false; 2321 } 2322 2323 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2324 unsigned MaxWidth) { 2325 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2326 BuiltinID == ARM::BI__builtin_arm_ldaex || 2327 BuiltinID == ARM::BI__builtin_arm_strex || 2328 BuiltinID == ARM::BI__builtin_arm_stlex || 2329 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2330 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2331 BuiltinID == AArch64::BI__builtin_arm_strex || 2332 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2333 "unexpected ARM builtin"); 2334 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2335 BuiltinID == ARM::BI__builtin_arm_ldaex || 2336 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2337 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2338 2339 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2340 2341 // Ensure that we have the proper number of arguments. 2342 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2343 return true; 2344 2345 // Inspect the pointer argument of the atomic builtin. This should always be 2346 // a pointer type, whose element is an integral scalar or pointer type. 2347 // Because it is a pointer type, we don't have to worry about any implicit 2348 // casts here. 2349 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2350 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2351 if (PointerArgRes.isInvalid()) 2352 return true; 2353 PointerArg = PointerArgRes.get(); 2354 2355 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2356 if (!pointerType) { 2357 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2358 << PointerArg->getType() << PointerArg->getSourceRange(); 2359 return true; 2360 } 2361 2362 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2363 // task is to insert the appropriate casts into the AST. First work out just 2364 // what the appropriate type is. 2365 QualType ValType = pointerType->getPointeeType(); 2366 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2367 if (IsLdrex) 2368 AddrType.addConst(); 2369 2370 // Issue a warning if the cast is dodgy. 2371 CastKind CastNeeded = CK_NoOp; 2372 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2373 CastNeeded = CK_BitCast; 2374 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2375 << PointerArg->getType() << Context.getPointerType(AddrType) 2376 << AA_Passing << PointerArg->getSourceRange(); 2377 } 2378 2379 // Finally, do the cast and replace the argument with the corrected version. 2380 AddrType = Context.getPointerType(AddrType); 2381 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2382 if (PointerArgRes.isInvalid()) 2383 return true; 2384 PointerArg = PointerArgRes.get(); 2385 2386 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2387 2388 // In general, we allow ints, floats and pointers to be loaded and stored. 2389 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2390 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2391 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2392 << PointerArg->getType() << PointerArg->getSourceRange(); 2393 return true; 2394 } 2395 2396 // But ARM doesn't have instructions to deal with 128-bit versions. 2397 if (Context.getTypeSize(ValType) > MaxWidth) { 2398 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2399 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2400 << PointerArg->getType() << PointerArg->getSourceRange(); 2401 return true; 2402 } 2403 2404 switch (ValType.getObjCLifetime()) { 2405 case Qualifiers::OCL_None: 2406 case Qualifiers::OCL_ExplicitNone: 2407 // okay 2408 break; 2409 2410 case Qualifiers::OCL_Weak: 2411 case Qualifiers::OCL_Strong: 2412 case Qualifiers::OCL_Autoreleasing: 2413 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2414 << ValType << PointerArg->getSourceRange(); 2415 return true; 2416 } 2417 2418 if (IsLdrex) { 2419 TheCall->setType(ValType); 2420 return false; 2421 } 2422 2423 // Initialize the argument to be stored. 2424 ExprResult ValArg = TheCall->getArg(0); 2425 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2426 Context, ValType, /*consume*/ false); 2427 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2428 if (ValArg.isInvalid()) 2429 return true; 2430 TheCall->setArg(0, ValArg.get()); 2431 2432 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2433 // but the custom checker bypasses all default analysis. 2434 TheCall->setType(Context.IntTy); 2435 return false; 2436 } 2437 2438 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2439 CallExpr *TheCall) { 2440 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2441 BuiltinID == ARM::BI__builtin_arm_ldaex || 2442 BuiltinID == ARM::BI__builtin_arm_strex || 2443 BuiltinID == ARM::BI__builtin_arm_stlex) { 2444 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2445 } 2446 2447 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2448 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2449 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2450 } 2451 2452 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2453 BuiltinID == ARM::BI__builtin_arm_wsr64) 2454 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2455 2456 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2457 BuiltinID == ARM::BI__builtin_arm_rsrp || 2458 BuiltinID == ARM::BI__builtin_arm_wsr || 2459 BuiltinID == ARM::BI__builtin_arm_wsrp) 2460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2461 2462 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2463 return true; 2464 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2465 return true; 2466 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2467 return true; 2468 2469 // For intrinsics which take an immediate value as part of the instruction, 2470 // range check them here. 2471 // FIXME: VFP Intrinsics should error if VFP not present. 2472 switch (BuiltinID) { 2473 default: return false; 2474 case ARM::BI__builtin_arm_ssat: 2475 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2476 case ARM::BI__builtin_arm_usat: 2477 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2478 case ARM::BI__builtin_arm_ssat16: 2479 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2480 case ARM::BI__builtin_arm_usat16: 2481 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2482 case ARM::BI__builtin_arm_vcvtr_f: 2483 case ARM::BI__builtin_arm_vcvtr_d: 2484 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2485 case ARM::BI__builtin_arm_dmb: 2486 case ARM::BI__builtin_arm_dsb: 2487 case ARM::BI__builtin_arm_isb: 2488 case ARM::BI__builtin_arm_dbg: 2489 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2490 case ARM::BI__builtin_arm_cdp: 2491 case ARM::BI__builtin_arm_cdp2: 2492 case ARM::BI__builtin_arm_mcr: 2493 case ARM::BI__builtin_arm_mcr2: 2494 case ARM::BI__builtin_arm_mrc: 2495 case ARM::BI__builtin_arm_mrc2: 2496 case ARM::BI__builtin_arm_mcrr: 2497 case ARM::BI__builtin_arm_mcrr2: 2498 case ARM::BI__builtin_arm_mrrc: 2499 case ARM::BI__builtin_arm_mrrc2: 2500 case ARM::BI__builtin_arm_ldc: 2501 case ARM::BI__builtin_arm_ldcl: 2502 case ARM::BI__builtin_arm_ldc2: 2503 case ARM::BI__builtin_arm_ldc2l: 2504 case ARM::BI__builtin_arm_stc: 2505 case ARM::BI__builtin_arm_stcl: 2506 case ARM::BI__builtin_arm_stc2: 2507 case ARM::BI__builtin_arm_stc2l: 2508 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2509 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2510 /*WantCDE*/ false); 2511 } 2512 } 2513 2514 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2515 unsigned BuiltinID, 2516 CallExpr *TheCall) { 2517 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2518 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2519 BuiltinID == AArch64::BI__builtin_arm_strex || 2520 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2521 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2522 } 2523 2524 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2525 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2526 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2527 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2528 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2529 } 2530 2531 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2532 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2533 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2534 2535 // Memory Tagging Extensions (MTE) Intrinsics 2536 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2537 BuiltinID == AArch64::BI__builtin_arm_addg || 2538 BuiltinID == AArch64::BI__builtin_arm_gmi || 2539 BuiltinID == AArch64::BI__builtin_arm_ldg || 2540 BuiltinID == AArch64::BI__builtin_arm_stg || 2541 BuiltinID == AArch64::BI__builtin_arm_subp) { 2542 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2543 } 2544 2545 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2546 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2547 BuiltinID == AArch64::BI__builtin_arm_wsr || 2548 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2549 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2550 2551 // Only check the valid encoding range. Any constant in this range would be 2552 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2553 // an exception for incorrect registers. This matches MSVC behavior. 2554 if (BuiltinID == AArch64::BI_ReadStatusReg || 2555 BuiltinID == AArch64::BI_WriteStatusReg) 2556 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2557 2558 if (BuiltinID == AArch64::BI__getReg) 2559 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2560 2561 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2562 return true; 2563 2564 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2565 return true; 2566 2567 // For intrinsics which take an immediate value as part of the instruction, 2568 // range check them here. 2569 unsigned i = 0, l = 0, u = 0; 2570 switch (BuiltinID) { 2571 default: return false; 2572 case AArch64::BI__builtin_arm_dmb: 2573 case AArch64::BI__builtin_arm_dsb: 2574 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2575 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2576 } 2577 2578 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2579 } 2580 2581 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2582 if (Arg->getType()->getAsPlaceholderType()) 2583 return false; 2584 2585 // The first argument needs to be a record field access. 2586 // If it is an array element access, we delay decision 2587 // to BPF backend to check whether the access is a 2588 // field access or not. 2589 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2590 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2591 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2592 } 2593 2594 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2595 QualType VectorTy, QualType EltTy) { 2596 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2597 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2598 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2599 << Call->getSourceRange() << VectorEltTy << EltTy; 2600 return false; 2601 } 2602 return true; 2603 } 2604 2605 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2606 QualType ArgType = Arg->getType(); 2607 if (ArgType->getAsPlaceholderType()) 2608 return false; 2609 2610 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2611 // format: 2612 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2613 // 2. <type> var; 2614 // __builtin_preserve_type_info(var, flag); 2615 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2616 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2617 return false; 2618 2619 // Typedef type. 2620 if (ArgType->getAs<TypedefType>()) 2621 return true; 2622 2623 // Record type or Enum type. 2624 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2625 if (const auto *RT = Ty->getAs<RecordType>()) { 2626 if (!RT->getDecl()->getDeclName().isEmpty()) 2627 return true; 2628 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2629 if (!ET->getDecl()->getDeclName().isEmpty()) 2630 return true; 2631 } 2632 2633 return false; 2634 } 2635 2636 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2637 QualType ArgType = Arg->getType(); 2638 if (ArgType->getAsPlaceholderType()) 2639 return false; 2640 2641 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2642 // format: 2643 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2644 // flag); 2645 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2646 if (!UO) 2647 return false; 2648 2649 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2650 if (!CE) 2651 return false; 2652 if (CE->getCastKind() != CK_IntegralToPointer && 2653 CE->getCastKind() != CK_NullToPointer) 2654 return false; 2655 2656 // The integer must be from an EnumConstantDecl. 2657 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2658 if (!DR) 2659 return false; 2660 2661 const EnumConstantDecl *Enumerator = 2662 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2663 if (!Enumerator) 2664 return false; 2665 2666 // The type must be EnumType. 2667 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2668 const auto *ET = Ty->getAs<EnumType>(); 2669 if (!ET) 2670 return false; 2671 2672 // The enum value must be supported. 2673 for (auto *EDI : ET->getDecl()->enumerators()) { 2674 if (EDI == Enumerator) 2675 return true; 2676 } 2677 2678 return false; 2679 } 2680 2681 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2682 CallExpr *TheCall) { 2683 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2684 BuiltinID == BPF::BI__builtin_btf_type_id || 2685 BuiltinID == BPF::BI__builtin_preserve_type_info || 2686 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2687 "unexpected BPF builtin"); 2688 2689 if (checkArgCount(*this, TheCall, 2)) 2690 return true; 2691 2692 // The second argument needs to be a constant int 2693 Expr *Arg = TheCall->getArg(1); 2694 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2695 diag::kind kind; 2696 if (!Value) { 2697 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2698 kind = diag::err_preserve_field_info_not_const; 2699 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2700 kind = diag::err_btf_type_id_not_const; 2701 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2702 kind = diag::err_preserve_type_info_not_const; 2703 else 2704 kind = diag::err_preserve_enum_value_not_const; 2705 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2706 return true; 2707 } 2708 2709 // The first argument 2710 Arg = TheCall->getArg(0); 2711 bool InvalidArg = false; 2712 bool ReturnUnsignedInt = true; 2713 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2714 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2715 InvalidArg = true; 2716 kind = diag::err_preserve_field_info_not_field; 2717 } 2718 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2719 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2720 InvalidArg = true; 2721 kind = diag::err_preserve_type_info_invalid; 2722 } 2723 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2724 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2725 InvalidArg = true; 2726 kind = diag::err_preserve_enum_value_invalid; 2727 } 2728 ReturnUnsignedInt = false; 2729 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2730 ReturnUnsignedInt = false; 2731 } 2732 2733 if (InvalidArg) { 2734 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2735 return true; 2736 } 2737 2738 if (ReturnUnsignedInt) 2739 TheCall->setType(Context.UnsignedIntTy); 2740 else 2741 TheCall->setType(Context.UnsignedLongTy); 2742 return false; 2743 } 2744 2745 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2746 struct ArgInfo { 2747 uint8_t OpNum; 2748 bool IsSigned; 2749 uint8_t BitWidth; 2750 uint8_t Align; 2751 }; 2752 struct BuiltinInfo { 2753 unsigned BuiltinID; 2754 ArgInfo Infos[2]; 2755 }; 2756 2757 static BuiltinInfo Infos[] = { 2758 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2759 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2760 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2761 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2762 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2763 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2764 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2765 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2766 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2767 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2768 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2769 2770 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2781 2782 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2834 {{ 1, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2842 {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2849 { 2, false, 5, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2851 { 2, false, 6, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2853 { 3, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2855 { 3, false, 6, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2872 {{ 2, false, 4, 0 }, 2873 { 3, false, 5, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2875 {{ 2, false, 4, 0 }, 2876 { 3, false, 5, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2878 {{ 2, false, 4, 0 }, 2879 { 3, false, 5, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2881 {{ 2, false, 4, 0 }, 2882 { 3, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2894 { 2, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2896 { 2, false, 6, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2906 {{ 1, false, 4, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2909 {{ 1, false, 4, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2930 {{ 3, false, 1, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2935 {{ 3, false, 1, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2940 {{ 3, false, 1, 0 }} }, 2941 }; 2942 2943 // Use a dynamically initialized static to sort the table exactly once on 2944 // first run. 2945 static const bool SortOnce = 2946 (llvm::sort(Infos, 2947 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2948 return LHS.BuiltinID < RHS.BuiltinID; 2949 }), 2950 true); 2951 (void)SortOnce; 2952 2953 const BuiltinInfo *F = llvm::partition_point( 2954 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2955 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2956 return false; 2957 2958 bool Error = false; 2959 2960 for (const ArgInfo &A : F->Infos) { 2961 // Ignore empty ArgInfo elements. 2962 if (A.BitWidth == 0) 2963 continue; 2964 2965 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2966 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2967 if (!A.Align) { 2968 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2969 } else { 2970 unsigned M = 1 << A.Align; 2971 Min *= M; 2972 Max *= M; 2973 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2974 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2975 } 2976 } 2977 return Error; 2978 } 2979 2980 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2981 CallExpr *TheCall) { 2982 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2983 } 2984 2985 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2986 unsigned BuiltinID, CallExpr *TheCall) { 2987 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2988 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2989 } 2990 2991 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2992 CallExpr *TheCall) { 2993 2994 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2995 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2996 if (!TI.hasFeature("dsp")) 2997 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2998 } 2999 3000 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3001 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3002 if (!TI.hasFeature("dspr2")) 3003 return Diag(TheCall->getBeginLoc(), 3004 diag::err_mips_builtin_requires_dspr2); 3005 } 3006 3007 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3008 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3009 if (!TI.hasFeature("msa")) 3010 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3011 } 3012 3013 return false; 3014 } 3015 3016 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3017 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3018 // ordering for DSP is unspecified. MSA is ordered by the data format used 3019 // by the underlying instruction i.e., df/m, df/n and then by size. 3020 // 3021 // FIXME: The size tests here should instead be tablegen'd along with the 3022 // definitions from include/clang/Basic/BuiltinsMips.def. 3023 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3024 // be too. 3025 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3026 unsigned i = 0, l = 0, u = 0, m = 0; 3027 switch (BuiltinID) { 3028 default: return false; 3029 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3030 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3031 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3032 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3033 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3034 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3035 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3036 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3037 // df/m field. 3038 // These intrinsics take an unsigned 3 bit immediate. 3039 case Mips::BI__builtin_msa_bclri_b: 3040 case Mips::BI__builtin_msa_bnegi_b: 3041 case Mips::BI__builtin_msa_bseti_b: 3042 case Mips::BI__builtin_msa_sat_s_b: 3043 case Mips::BI__builtin_msa_sat_u_b: 3044 case Mips::BI__builtin_msa_slli_b: 3045 case Mips::BI__builtin_msa_srai_b: 3046 case Mips::BI__builtin_msa_srari_b: 3047 case Mips::BI__builtin_msa_srli_b: 3048 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3049 case Mips::BI__builtin_msa_binsli_b: 3050 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3051 // These intrinsics take an unsigned 4 bit immediate. 3052 case Mips::BI__builtin_msa_bclri_h: 3053 case Mips::BI__builtin_msa_bnegi_h: 3054 case Mips::BI__builtin_msa_bseti_h: 3055 case Mips::BI__builtin_msa_sat_s_h: 3056 case Mips::BI__builtin_msa_sat_u_h: 3057 case Mips::BI__builtin_msa_slli_h: 3058 case Mips::BI__builtin_msa_srai_h: 3059 case Mips::BI__builtin_msa_srari_h: 3060 case Mips::BI__builtin_msa_srli_h: 3061 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3062 case Mips::BI__builtin_msa_binsli_h: 3063 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3064 // These intrinsics take an unsigned 5 bit immediate. 3065 // The first block of intrinsics actually have an unsigned 5 bit field, 3066 // not a df/n field. 3067 case Mips::BI__builtin_msa_cfcmsa: 3068 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3069 case Mips::BI__builtin_msa_clei_u_b: 3070 case Mips::BI__builtin_msa_clei_u_h: 3071 case Mips::BI__builtin_msa_clei_u_w: 3072 case Mips::BI__builtin_msa_clei_u_d: 3073 case Mips::BI__builtin_msa_clti_u_b: 3074 case Mips::BI__builtin_msa_clti_u_h: 3075 case Mips::BI__builtin_msa_clti_u_w: 3076 case Mips::BI__builtin_msa_clti_u_d: 3077 case Mips::BI__builtin_msa_maxi_u_b: 3078 case Mips::BI__builtin_msa_maxi_u_h: 3079 case Mips::BI__builtin_msa_maxi_u_w: 3080 case Mips::BI__builtin_msa_maxi_u_d: 3081 case Mips::BI__builtin_msa_mini_u_b: 3082 case Mips::BI__builtin_msa_mini_u_h: 3083 case Mips::BI__builtin_msa_mini_u_w: 3084 case Mips::BI__builtin_msa_mini_u_d: 3085 case Mips::BI__builtin_msa_addvi_b: 3086 case Mips::BI__builtin_msa_addvi_h: 3087 case Mips::BI__builtin_msa_addvi_w: 3088 case Mips::BI__builtin_msa_addvi_d: 3089 case Mips::BI__builtin_msa_bclri_w: 3090 case Mips::BI__builtin_msa_bnegi_w: 3091 case Mips::BI__builtin_msa_bseti_w: 3092 case Mips::BI__builtin_msa_sat_s_w: 3093 case Mips::BI__builtin_msa_sat_u_w: 3094 case Mips::BI__builtin_msa_slli_w: 3095 case Mips::BI__builtin_msa_srai_w: 3096 case Mips::BI__builtin_msa_srari_w: 3097 case Mips::BI__builtin_msa_srli_w: 3098 case Mips::BI__builtin_msa_srlri_w: 3099 case Mips::BI__builtin_msa_subvi_b: 3100 case Mips::BI__builtin_msa_subvi_h: 3101 case Mips::BI__builtin_msa_subvi_w: 3102 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3103 case Mips::BI__builtin_msa_binsli_w: 3104 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3105 // These intrinsics take an unsigned 6 bit immediate. 3106 case Mips::BI__builtin_msa_bclri_d: 3107 case Mips::BI__builtin_msa_bnegi_d: 3108 case Mips::BI__builtin_msa_bseti_d: 3109 case Mips::BI__builtin_msa_sat_s_d: 3110 case Mips::BI__builtin_msa_sat_u_d: 3111 case Mips::BI__builtin_msa_slli_d: 3112 case Mips::BI__builtin_msa_srai_d: 3113 case Mips::BI__builtin_msa_srari_d: 3114 case Mips::BI__builtin_msa_srli_d: 3115 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3116 case Mips::BI__builtin_msa_binsli_d: 3117 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3118 // These intrinsics take a signed 5 bit immediate. 3119 case Mips::BI__builtin_msa_ceqi_b: 3120 case Mips::BI__builtin_msa_ceqi_h: 3121 case Mips::BI__builtin_msa_ceqi_w: 3122 case Mips::BI__builtin_msa_ceqi_d: 3123 case Mips::BI__builtin_msa_clti_s_b: 3124 case Mips::BI__builtin_msa_clti_s_h: 3125 case Mips::BI__builtin_msa_clti_s_w: 3126 case Mips::BI__builtin_msa_clti_s_d: 3127 case Mips::BI__builtin_msa_clei_s_b: 3128 case Mips::BI__builtin_msa_clei_s_h: 3129 case Mips::BI__builtin_msa_clei_s_w: 3130 case Mips::BI__builtin_msa_clei_s_d: 3131 case Mips::BI__builtin_msa_maxi_s_b: 3132 case Mips::BI__builtin_msa_maxi_s_h: 3133 case Mips::BI__builtin_msa_maxi_s_w: 3134 case Mips::BI__builtin_msa_maxi_s_d: 3135 case Mips::BI__builtin_msa_mini_s_b: 3136 case Mips::BI__builtin_msa_mini_s_h: 3137 case Mips::BI__builtin_msa_mini_s_w: 3138 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3139 // These intrinsics take an unsigned 8 bit immediate. 3140 case Mips::BI__builtin_msa_andi_b: 3141 case Mips::BI__builtin_msa_nori_b: 3142 case Mips::BI__builtin_msa_ori_b: 3143 case Mips::BI__builtin_msa_shf_b: 3144 case Mips::BI__builtin_msa_shf_h: 3145 case Mips::BI__builtin_msa_shf_w: 3146 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3147 case Mips::BI__builtin_msa_bseli_b: 3148 case Mips::BI__builtin_msa_bmnzi_b: 3149 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3150 // df/n format 3151 // These intrinsics take an unsigned 4 bit immediate. 3152 case Mips::BI__builtin_msa_copy_s_b: 3153 case Mips::BI__builtin_msa_copy_u_b: 3154 case Mips::BI__builtin_msa_insve_b: 3155 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3156 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3157 // These intrinsics take an unsigned 3 bit immediate. 3158 case Mips::BI__builtin_msa_copy_s_h: 3159 case Mips::BI__builtin_msa_copy_u_h: 3160 case Mips::BI__builtin_msa_insve_h: 3161 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3162 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3163 // These intrinsics take an unsigned 2 bit immediate. 3164 case Mips::BI__builtin_msa_copy_s_w: 3165 case Mips::BI__builtin_msa_copy_u_w: 3166 case Mips::BI__builtin_msa_insve_w: 3167 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3168 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3169 // These intrinsics take an unsigned 1 bit immediate. 3170 case Mips::BI__builtin_msa_copy_s_d: 3171 case Mips::BI__builtin_msa_copy_u_d: 3172 case Mips::BI__builtin_msa_insve_d: 3173 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3174 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3175 // Memory offsets and immediate loads. 3176 // These intrinsics take a signed 10 bit immediate. 3177 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3178 case Mips::BI__builtin_msa_ldi_h: 3179 case Mips::BI__builtin_msa_ldi_w: 3180 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3181 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3182 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3183 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3184 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3185 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3186 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3187 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3188 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3189 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3190 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3191 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3192 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3193 } 3194 3195 if (!m) 3196 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3197 3198 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3199 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3200 } 3201 3202 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3203 /// advancing the pointer over the consumed characters. The decoded type is 3204 /// returned. If the decoded type represents a constant integer with a 3205 /// constraint on its value then Mask is set to that value. The type descriptors 3206 /// used in Str are specific to PPC MMA builtins and are documented in the file 3207 /// defining the PPC builtins. 3208 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3209 unsigned &Mask) { 3210 bool RequireICE = false; 3211 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3212 switch (*Str++) { 3213 case 'V': 3214 return Context.getVectorType(Context.UnsignedCharTy, 16, 3215 VectorType::VectorKind::AltiVecVector); 3216 case 'i': { 3217 char *End; 3218 unsigned size = strtoul(Str, &End, 10); 3219 assert(End != Str && "Missing constant parameter constraint"); 3220 Str = End; 3221 Mask = size; 3222 return Context.IntTy; 3223 } 3224 case 'W': { 3225 char *End; 3226 unsigned size = strtoul(Str, &End, 10); 3227 assert(End != Str && "Missing PowerPC MMA type size"); 3228 Str = End; 3229 QualType Type; 3230 switch (size) { 3231 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3232 case size: Type = Context.Id##Ty; break; 3233 #include "clang/Basic/PPCTypes.def" 3234 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3235 } 3236 bool CheckVectorArgs = false; 3237 while (!CheckVectorArgs) { 3238 switch (*Str++) { 3239 case '*': 3240 Type = Context.getPointerType(Type); 3241 break; 3242 case 'C': 3243 Type = Type.withConst(); 3244 break; 3245 default: 3246 CheckVectorArgs = true; 3247 --Str; 3248 break; 3249 } 3250 } 3251 return Type; 3252 } 3253 default: 3254 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3255 } 3256 } 3257 3258 static bool isPPC_64Builtin(unsigned BuiltinID) { 3259 // These builtins only work on PPC 64bit targets. 3260 switch (BuiltinID) { 3261 case PPC::BI__builtin_divde: 3262 case PPC::BI__builtin_divdeu: 3263 case PPC::BI__builtin_bpermd: 3264 return true; 3265 } 3266 return false; 3267 } 3268 3269 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3270 StringRef FeatureToCheck, unsigned DiagID) { 3271 if (!S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3272 return S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3273 return false; 3274 } 3275 3276 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3277 CallExpr *TheCall) { 3278 unsigned i = 0, l = 0, u = 0; 3279 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3280 3281 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3282 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3283 << TheCall->getSourceRange(); 3284 3285 switch (BuiltinID) { 3286 default: return false; 3287 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3288 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3289 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3290 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3291 case PPC::BI__builtin_altivec_dss: 3292 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3293 case PPC::BI__builtin_tbegin: 3294 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3295 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3296 case PPC::BI__builtin_tabortwc: 3297 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3298 case PPC::BI__builtin_tabortwci: 3299 case PPC::BI__builtin_tabortdci: 3300 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3301 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3302 case PPC::BI__builtin_altivec_dst: 3303 case PPC::BI__builtin_altivec_dstt: 3304 case PPC::BI__builtin_altivec_dstst: 3305 case PPC::BI__builtin_altivec_dststt: 3306 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3307 case PPC::BI__builtin_vsx_xxpermdi: 3308 case PPC::BI__builtin_vsx_xxsldwi: 3309 return SemaBuiltinVSX(TheCall); 3310 case PPC::BI__builtin_divwe: 3311 case PPC::BI__builtin_divweu: 3312 case PPC::BI__builtin_divde: 3313 case PPC::BI__builtin_divdeu: 3314 return SemaFeatureCheck(*this, TheCall, "extdiv", 3315 diag::err_ppc_builtin_only_on_pwr7); 3316 case PPC::BI__builtin_bpermd: 3317 return SemaFeatureCheck(*this, TheCall, "bpermd", 3318 diag::err_ppc_builtin_only_on_pwr7); 3319 case PPC::BI__builtin_unpack_vector_int128: 3320 return SemaFeatureCheck(*this, TheCall, "vsx", 3321 diag::err_ppc_builtin_only_on_pwr7) || 3322 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3323 case PPC::BI__builtin_pack_vector_int128: 3324 return SemaFeatureCheck(*this, TheCall, "vsx", 3325 diag::err_ppc_builtin_only_on_pwr7); 3326 case PPC::BI__builtin_altivec_vgnb: 3327 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3328 case PPC::BI__builtin_altivec_vec_replace_elt: 3329 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3330 QualType VecTy = TheCall->getArg(0)->getType(); 3331 QualType EltTy = TheCall->getArg(1)->getType(); 3332 unsigned Width = Context.getIntWidth(EltTy); 3333 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3334 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3335 } 3336 case PPC::BI__builtin_vsx_xxeval: 3337 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3338 case PPC::BI__builtin_altivec_vsldbi: 3339 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3340 case PPC::BI__builtin_altivec_vsrdbi: 3341 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3342 case PPC::BI__builtin_vsx_xxpermx: 3343 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3344 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3345 case PPC::BI__builtin_##Name: \ 3346 return SemaBuiltinPPCMMACall(TheCall, Types); 3347 #include "clang/Basic/BuiltinsPPC.def" 3348 } 3349 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3350 } 3351 3352 // Check if the given type is a non-pointer PPC MMA type. This function is used 3353 // in Sema to prevent invalid uses of restricted PPC MMA types. 3354 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3355 if (Type->isPointerType() || Type->isArrayType()) 3356 return false; 3357 3358 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3359 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3360 if (false 3361 #include "clang/Basic/PPCTypes.def" 3362 ) { 3363 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3364 return true; 3365 } 3366 return false; 3367 } 3368 3369 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3370 CallExpr *TheCall) { 3371 // position of memory order and scope arguments in the builtin 3372 unsigned OrderIndex, ScopeIndex; 3373 switch (BuiltinID) { 3374 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3375 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3376 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3377 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3378 OrderIndex = 2; 3379 ScopeIndex = 3; 3380 break; 3381 case AMDGPU::BI__builtin_amdgcn_fence: 3382 OrderIndex = 0; 3383 ScopeIndex = 1; 3384 break; 3385 default: 3386 return false; 3387 } 3388 3389 ExprResult Arg = TheCall->getArg(OrderIndex); 3390 auto ArgExpr = Arg.get(); 3391 Expr::EvalResult ArgResult; 3392 3393 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3394 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3395 << ArgExpr->getType(); 3396 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3397 3398 // Check valididty of memory ordering as per C11 / C++11's memody model. 3399 // Only fence needs check. Atomic dec/inc allow all memory orders. 3400 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3401 return Diag(ArgExpr->getBeginLoc(), 3402 diag::warn_atomic_op_has_invalid_memory_order) 3403 << ArgExpr->getSourceRange(); 3404 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3405 case llvm::AtomicOrderingCABI::relaxed: 3406 case llvm::AtomicOrderingCABI::consume: 3407 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3408 return Diag(ArgExpr->getBeginLoc(), 3409 diag::warn_atomic_op_has_invalid_memory_order) 3410 << ArgExpr->getSourceRange(); 3411 break; 3412 case llvm::AtomicOrderingCABI::acquire: 3413 case llvm::AtomicOrderingCABI::release: 3414 case llvm::AtomicOrderingCABI::acq_rel: 3415 case llvm::AtomicOrderingCABI::seq_cst: 3416 break; 3417 } 3418 3419 Arg = TheCall->getArg(ScopeIndex); 3420 ArgExpr = Arg.get(); 3421 Expr::EvalResult ArgResult1; 3422 // Check that sync scope is a constant literal 3423 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3424 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3425 << ArgExpr->getType(); 3426 3427 return false; 3428 } 3429 3430 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3431 llvm::APSInt Result; 3432 3433 // We can't check the value of a dependent argument. 3434 Expr *Arg = TheCall->getArg(ArgNum); 3435 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3436 return false; 3437 3438 // Check constant-ness first. 3439 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3440 return true; 3441 3442 int64_t Val = Result.getSExtValue(); 3443 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3444 return false; 3445 3446 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3447 << Arg->getSourceRange(); 3448 } 3449 3450 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3451 unsigned BuiltinID, 3452 CallExpr *TheCall) { 3453 // CodeGenFunction can also detect this, but this gives a better error 3454 // message. 3455 bool FeatureMissing = false; 3456 SmallVector<StringRef> ReqFeatures; 3457 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3458 Features.split(ReqFeatures, ','); 3459 3460 // Check if each required feature is included 3461 for (StringRef F : ReqFeatures) { 3462 if (TI.hasFeature(F)) 3463 continue; 3464 3465 // If the feature is 64bit, alter the string so it will print better in 3466 // the diagnostic. 3467 if (F == "64bit") 3468 F = "RV64"; 3469 3470 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3471 F.consume_front("experimental-"); 3472 std::string FeatureStr = F.str(); 3473 FeatureStr[0] = std::toupper(FeatureStr[0]); 3474 3475 // Error message 3476 FeatureMissing = true; 3477 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3478 << TheCall->getSourceRange() << StringRef(FeatureStr); 3479 } 3480 3481 if (FeatureMissing) 3482 return true; 3483 3484 switch (BuiltinID) { 3485 case RISCV::BI__builtin_rvv_vsetvli: 3486 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3487 CheckRISCVLMUL(TheCall, 2); 3488 case RISCV::BI__builtin_rvv_vsetvlimax: 3489 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3490 CheckRISCVLMUL(TheCall, 1); 3491 } 3492 3493 return false; 3494 } 3495 3496 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3497 CallExpr *TheCall) { 3498 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3499 Expr *Arg = TheCall->getArg(0); 3500 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3501 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3502 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3503 << Arg->getSourceRange(); 3504 } 3505 3506 // For intrinsics which take an immediate value as part of the instruction, 3507 // range check them here. 3508 unsigned i = 0, l = 0, u = 0; 3509 switch (BuiltinID) { 3510 default: return false; 3511 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3512 case SystemZ::BI__builtin_s390_verimb: 3513 case SystemZ::BI__builtin_s390_verimh: 3514 case SystemZ::BI__builtin_s390_verimf: 3515 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3516 case SystemZ::BI__builtin_s390_vfaeb: 3517 case SystemZ::BI__builtin_s390_vfaeh: 3518 case SystemZ::BI__builtin_s390_vfaef: 3519 case SystemZ::BI__builtin_s390_vfaebs: 3520 case SystemZ::BI__builtin_s390_vfaehs: 3521 case SystemZ::BI__builtin_s390_vfaefs: 3522 case SystemZ::BI__builtin_s390_vfaezb: 3523 case SystemZ::BI__builtin_s390_vfaezh: 3524 case SystemZ::BI__builtin_s390_vfaezf: 3525 case SystemZ::BI__builtin_s390_vfaezbs: 3526 case SystemZ::BI__builtin_s390_vfaezhs: 3527 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3528 case SystemZ::BI__builtin_s390_vfisb: 3529 case SystemZ::BI__builtin_s390_vfidb: 3530 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3531 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3532 case SystemZ::BI__builtin_s390_vftcisb: 3533 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3534 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3535 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3536 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3537 case SystemZ::BI__builtin_s390_vstrcb: 3538 case SystemZ::BI__builtin_s390_vstrch: 3539 case SystemZ::BI__builtin_s390_vstrcf: 3540 case SystemZ::BI__builtin_s390_vstrczb: 3541 case SystemZ::BI__builtin_s390_vstrczh: 3542 case SystemZ::BI__builtin_s390_vstrczf: 3543 case SystemZ::BI__builtin_s390_vstrcbs: 3544 case SystemZ::BI__builtin_s390_vstrchs: 3545 case SystemZ::BI__builtin_s390_vstrcfs: 3546 case SystemZ::BI__builtin_s390_vstrczbs: 3547 case SystemZ::BI__builtin_s390_vstrczhs: 3548 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3549 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3550 case SystemZ::BI__builtin_s390_vfminsb: 3551 case SystemZ::BI__builtin_s390_vfmaxsb: 3552 case SystemZ::BI__builtin_s390_vfmindb: 3553 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3554 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3555 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3556 } 3557 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3558 } 3559 3560 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3561 /// This checks that the target supports __builtin_cpu_supports and 3562 /// that the string argument is constant and valid. 3563 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3564 CallExpr *TheCall) { 3565 Expr *Arg = TheCall->getArg(0); 3566 3567 // Check if the argument is a string literal. 3568 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3569 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3570 << Arg->getSourceRange(); 3571 3572 // Check the contents of the string. 3573 StringRef Feature = 3574 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3575 if (!TI.validateCpuSupports(Feature)) 3576 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3577 << Arg->getSourceRange(); 3578 return false; 3579 } 3580 3581 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3582 /// This checks that the target supports __builtin_cpu_is and 3583 /// that the string argument is constant and valid. 3584 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3585 Expr *Arg = TheCall->getArg(0); 3586 3587 // Check if the argument is a string literal. 3588 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3589 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3590 << Arg->getSourceRange(); 3591 3592 // Check the contents of the string. 3593 StringRef Feature = 3594 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3595 if (!TI.validateCpuIs(Feature)) 3596 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3597 << Arg->getSourceRange(); 3598 return false; 3599 } 3600 3601 // Check if the rounding mode is legal. 3602 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3603 // Indicates if this instruction has rounding control or just SAE. 3604 bool HasRC = false; 3605 3606 unsigned ArgNum = 0; 3607 switch (BuiltinID) { 3608 default: 3609 return false; 3610 case X86::BI__builtin_ia32_vcvttsd2si32: 3611 case X86::BI__builtin_ia32_vcvttsd2si64: 3612 case X86::BI__builtin_ia32_vcvttsd2usi32: 3613 case X86::BI__builtin_ia32_vcvttsd2usi64: 3614 case X86::BI__builtin_ia32_vcvttss2si32: 3615 case X86::BI__builtin_ia32_vcvttss2si64: 3616 case X86::BI__builtin_ia32_vcvttss2usi32: 3617 case X86::BI__builtin_ia32_vcvttss2usi64: 3618 ArgNum = 1; 3619 break; 3620 case X86::BI__builtin_ia32_maxpd512: 3621 case X86::BI__builtin_ia32_maxps512: 3622 case X86::BI__builtin_ia32_minpd512: 3623 case X86::BI__builtin_ia32_minps512: 3624 ArgNum = 2; 3625 break; 3626 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3627 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3628 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3629 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3630 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3631 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3632 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3633 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3634 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3635 case X86::BI__builtin_ia32_exp2pd_mask: 3636 case X86::BI__builtin_ia32_exp2ps_mask: 3637 case X86::BI__builtin_ia32_getexppd512_mask: 3638 case X86::BI__builtin_ia32_getexpps512_mask: 3639 case X86::BI__builtin_ia32_rcp28pd_mask: 3640 case X86::BI__builtin_ia32_rcp28ps_mask: 3641 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3642 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3643 case X86::BI__builtin_ia32_vcomisd: 3644 case X86::BI__builtin_ia32_vcomiss: 3645 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3646 ArgNum = 3; 3647 break; 3648 case X86::BI__builtin_ia32_cmppd512_mask: 3649 case X86::BI__builtin_ia32_cmpps512_mask: 3650 case X86::BI__builtin_ia32_cmpsd_mask: 3651 case X86::BI__builtin_ia32_cmpss_mask: 3652 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3653 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3654 case X86::BI__builtin_ia32_getexpss128_round_mask: 3655 case X86::BI__builtin_ia32_getmantpd512_mask: 3656 case X86::BI__builtin_ia32_getmantps512_mask: 3657 case X86::BI__builtin_ia32_maxsd_round_mask: 3658 case X86::BI__builtin_ia32_maxss_round_mask: 3659 case X86::BI__builtin_ia32_minsd_round_mask: 3660 case X86::BI__builtin_ia32_minss_round_mask: 3661 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3662 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3663 case X86::BI__builtin_ia32_reducepd512_mask: 3664 case X86::BI__builtin_ia32_reduceps512_mask: 3665 case X86::BI__builtin_ia32_rndscalepd_mask: 3666 case X86::BI__builtin_ia32_rndscaleps_mask: 3667 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3668 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3669 ArgNum = 4; 3670 break; 3671 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3672 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3673 case X86::BI__builtin_ia32_fixupimmps512_mask: 3674 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3675 case X86::BI__builtin_ia32_fixupimmsd_mask: 3676 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3677 case X86::BI__builtin_ia32_fixupimmss_mask: 3678 case X86::BI__builtin_ia32_fixupimmss_maskz: 3679 case X86::BI__builtin_ia32_getmantsd_round_mask: 3680 case X86::BI__builtin_ia32_getmantss_round_mask: 3681 case X86::BI__builtin_ia32_rangepd512_mask: 3682 case X86::BI__builtin_ia32_rangeps512_mask: 3683 case X86::BI__builtin_ia32_rangesd128_round_mask: 3684 case X86::BI__builtin_ia32_rangess128_round_mask: 3685 case X86::BI__builtin_ia32_reducesd_mask: 3686 case X86::BI__builtin_ia32_reducess_mask: 3687 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3688 case X86::BI__builtin_ia32_rndscaless_round_mask: 3689 ArgNum = 5; 3690 break; 3691 case X86::BI__builtin_ia32_vcvtsd2si64: 3692 case X86::BI__builtin_ia32_vcvtsd2si32: 3693 case X86::BI__builtin_ia32_vcvtsd2usi32: 3694 case X86::BI__builtin_ia32_vcvtsd2usi64: 3695 case X86::BI__builtin_ia32_vcvtss2si32: 3696 case X86::BI__builtin_ia32_vcvtss2si64: 3697 case X86::BI__builtin_ia32_vcvtss2usi32: 3698 case X86::BI__builtin_ia32_vcvtss2usi64: 3699 case X86::BI__builtin_ia32_sqrtpd512: 3700 case X86::BI__builtin_ia32_sqrtps512: 3701 ArgNum = 1; 3702 HasRC = true; 3703 break; 3704 case X86::BI__builtin_ia32_addpd512: 3705 case X86::BI__builtin_ia32_addps512: 3706 case X86::BI__builtin_ia32_divpd512: 3707 case X86::BI__builtin_ia32_divps512: 3708 case X86::BI__builtin_ia32_mulpd512: 3709 case X86::BI__builtin_ia32_mulps512: 3710 case X86::BI__builtin_ia32_subpd512: 3711 case X86::BI__builtin_ia32_subps512: 3712 case X86::BI__builtin_ia32_cvtsi2sd64: 3713 case X86::BI__builtin_ia32_cvtsi2ss32: 3714 case X86::BI__builtin_ia32_cvtsi2ss64: 3715 case X86::BI__builtin_ia32_cvtusi2sd64: 3716 case X86::BI__builtin_ia32_cvtusi2ss32: 3717 case X86::BI__builtin_ia32_cvtusi2ss64: 3718 ArgNum = 2; 3719 HasRC = true; 3720 break; 3721 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3722 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3723 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3724 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3725 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3726 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3727 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3728 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3729 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3730 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3731 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3732 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3733 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3734 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3735 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3736 ArgNum = 3; 3737 HasRC = true; 3738 break; 3739 case X86::BI__builtin_ia32_addss_round_mask: 3740 case X86::BI__builtin_ia32_addsd_round_mask: 3741 case X86::BI__builtin_ia32_divss_round_mask: 3742 case X86::BI__builtin_ia32_divsd_round_mask: 3743 case X86::BI__builtin_ia32_mulss_round_mask: 3744 case X86::BI__builtin_ia32_mulsd_round_mask: 3745 case X86::BI__builtin_ia32_subss_round_mask: 3746 case X86::BI__builtin_ia32_subsd_round_mask: 3747 case X86::BI__builtin_ia32_scalefpd512_mask: 3748 case X86::BI__builtin_ia32_scalefps512_mask: 3749 case X86::BI__builtin_ia32_scalefsd_round_mask: 3750 case X86::BI__builtin_ia32_scalefss_round_mask: 3751 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3752 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3753 case X86::BI__builtin_ia32_sqrtss_round_mask: 3754 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3755 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3756 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3757 case X86::BI__builtin_ia32_vfmaddss3_mask: 3758 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3759 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3760 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3761 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3762 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3763 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3764 case X86::BI__builtin_ia32_vfmaddps512_mask: 3765 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3766 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3767 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3768 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3769 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3770 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3771 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3772 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3773 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3774 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3775 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3776 ArgNum = 4; 3777 HasRC = true; 3778 break; 3779 } 3780 3781 llvm::APSInt Result; 3782 3783 // We can't check the value of a dependent argument. 3784 Expr *Arg = TheCall->getArg(ArgNum); 3785 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3786 return false; 3787 3788 // Check constant-ness first. 3789 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3790 return true; 3791 3792 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3793 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3794 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3795 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3796 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3797 Result == 8/*ROUND_NO_EXC*/ || 3798 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3799 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3800 return false; 3801 3802 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3803 << Arg->getSourceRange(); 3804 } 3805 3806 // Check if the gather/scatter scale is legal. 3807 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3808 CallExpr *TheCall) { 3809 unsigned ArgNum = 0; 3810 switch (BuiltinID) { 3811 default: 3812 return false; 3813 case X86::BI__builtin_ia32_gatherpfdpd: 3814 case X86::BI__builtin_ia32_gatherpfdps: 3815 case X86::BI__builtin_ia32_gatherpfqpd: 3816 case X86::BI__builtin_ia32_gatherpfqps: 3817 case X86::BI__builtin_ia32_scatterpfdpd: 3818 case X86::BI__builtin_ia32_scatterpfdps: 3819 case X86::BI__builtin_ia32_scatterpfqpd: 3820 case X86::BI__builtin_ia32_scatterpfqps: 3821 ArgNum = 3; 3822 break; 3823 case X86::BI__builtin_ia32_gatherd_pd: 3824 case X86::BI__builtin_ia32_gatherd_pd256: 3825 case X86::BI__builtin_ia32_gatherq_pd: 3826 case X86::BI__builtin_ia32_gatherq_pd256: 3827 case X86::BI__builtin_ia32_gatherd_ps: 3828 case X86::BI__builtin_ia32_gatherd_ps256: 3829 case X86::BI__builtin_ia32_gatherq_ps: 3830 case X86::BI__builtin_ia32_gatherq_ps256: 3831 case X86::BI__builtin_ia32_gatherd_q: 3832 case X86::BI__builtin_ia32_gatherd_q256: 3833 case X86::BI__builtin_ia32_gatherq_q: 3834 case X86::BI__builtin_ia32_gatherq_q256: 3835 case X86::BI__builtin_ia32_gatherd_d: 3836 case X86::BI__builtin_ia32_gatherd_d256: 3837 case X86::BI__builtin_ia32_gatherq_d: 3838 case X86::BI__builtin_ia32_gatherq_d256: 3839 case X86::BI__builtin_ia32_gather3div2df: 3840 case X86::BI__builtin_ia32_gather3div2di: 3841 case X86::BI__builtin_ia32_gather3div4df: 3842 case X86::BI__builtin_ia32_gather3div4di: 3843 case X86::BI__builtin_ia32_gather3div4sf: 3844 case X86::BI__builtin_ia32_gather3div4si: 3845 case X86::BI__builtin_ia32_gather3div8sf: 3846 case X86::BI__builtin_ia32_gather3div8si: 3847 case X86::BI__builtin_ia32_gather3siv2df: 3848 case X86::BI__builtin_ia32_gather3siv2di: 3849 case X86::BI__builtin_ia32_gather3siv4df: 3850 case X86::BI__builtin_ia32_gather3siv4di: 3851 case X86::BI__builtin_ia32_gather3siv4sf: 3852 case X86::BI__builtin_ia32_gather3siv4si: 3853 case X86::BI__builtin_ia32_gather3siv8sf: 3854 case X86::BI__builtin_ia32_gather3siv8si: 3855 case X86::BI__builtin_ia32_gathersiv8df: 3856 case X86::BI__builtin_ia32_gathersiv16sf: 3857 case X86::BI__builtin_ia32_gatherdiv8df: 3858 case X86::BI__builtin_ia32_gatherdiv16sf: 3859 case X86::BI__builtin_ia32_gathersiv8di: 3860 case X86::BI__builtin_ia32_gathersiv16si: 3861 case X86::BI__builtin_ia32_gatherdiv8di: 3862 case X86::BI__builtin_ia32_gatherdiv16si: 3863 case X86::BI__builtin_ia32_scatterdiv2df: 3864 case X86::BI__builtin_ia32_scatterdiv2di: 3865 case X86::BI__builtin_ia32_scatterdiv4df: 3866 case X86::BI__builtin_ia32_scatterdiv4di: 3867 case X86::BI__builtin_ia32_scatterdiv4sf: 3868 case X86::BI__builtin_ia32_scatterdiv4si: 3869 case X86::BI__builtin_ia32_scatterdiv8sf: 3870 case X86::BI__builtin_ia32_scatterdiv8si: 3871 case X86::BI__builtin_ia32_scattersiv2df: 3872 case X86::BI__builtin_ia32_scattersiv2di: 3873 case X86::BI__builtin_ia32_scattersiv4df: 3874 case X86::BI__builtin_ia32_scattersiv4di: 3875 case X86::BI__builtin_ia32_scattersiv4sf: 3876 case X86::BI__builtin_ia32_scattersiv4si: 3877 case X86::BI__builtin_ia32_scattersiv8sf: 3878 case X86::BI__builtin_ia32_scattersiv8si: 3879 case X86::BI__builtin_ia32_scattersiv8df: 3880 case X86::BI__builtin_ia32_scattersiv16sf: 3881 case X86::BI__builtin_ia32_scatterdiv8df: 3882 case X86::BI__builtin_ia32_scatterdiv16sf: 3883 case X86::BI__builtin_ia32_scattersiv8di: 3884 case X86::BI__builtin_ia32_scattersiv16si: 3885 case X86::BI__builtin_ia32_scatterdiv8di: 3886 case X86::BI__builtin_ia32_scatterdiv16si: 3887 ArgNum = 4; 3888 break; 3889 } 3890 3891 llvm::APSInt Result; 3892 3893 // We can't check the value of a dependent argument. 3894 Expr *Arg = TheCall->getArg(ArgNum); 3895 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3896 return false; 3897 3898 // Check constant-ness first. 3899 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3900 return true; 3901 3902 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3903 return false; 3904 3905 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3906 << Arg->getSourceRange(); 3907 } 3908 3909 enum { TileRegLow = 0, TileRegHigh = 7 }; 3910 3911 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3912 ArrayRef<int> ArgNums) { 3913 for (int ArgNum : ArgNums) { 3914 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3915 return true; 3916 } 3917 return false; 3918 } 3919 3920 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3921 ArrayRef<int> ArgNums) { 3922 // Because the max number of tile register is TileRegHigh + 1, so here we use 3923 // each bit to represent the usage of them in bitset. 3924 std::bitset<TileRegHigh + 1> ArgValues; 3925 for (int ArgNum : ArgNums) { 3926 Expr *Arg = TheCall->getArg(ArgNum); 3927 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3928 continue; 3929 3930 llvm::APSInt Result; 3931 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3932 return true; 3933 int ArgExtValue = Result.getExtValue(); 3934 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3935 "Incorrect tile register num."); 3936 if (ArgValues.test(ArgExtValue)) 3937 return Diag(TheCall->getBeginLoc(), 3938 diag::err_x86_builtin_tile_arg_duplicate) 3939 << TheCall->getArg(ArgNum)->getSourceRange(); 3940 ArgValues.set(ArgExtValue); 3941 } 3942 return false; 3943 } 3944 3945 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3946 ArrayRef<int> ArgNums) { 3947 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3948 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3949 } 3950 3951 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3952 switch (BuiltinID) { 3953 default: 3954 return false; 3955 case X86::BI__builtin_ia32_tileloadd64: 3956 case X86::BI__builtin_ia32_tileloaddt164: 3957 case X86::BI__builtin_ia32_tilestored64: 3958 case X86::BI__builtin_ia32_tilezero: 3959 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3960 case X86::BI__builtin_ia32_tdpbssd: 3961 case X86::BI__builtin_ia32_tdpbsud: 3962 case X86::BI__builtin_ia32_tdpbusd: 3963 case X86::BI__builtin_ia32_tdpbuud: 3964 case X86::BI__builtin_ia32_tdpbf16ps: 3965 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3966 } 3967 } 3968 static bool isX86_32Builtin(unsigned BuiltinID) { 3969 // These builtins only work on x86-32 targets. 3970 switch (BuiltinID) { 3971 case X86::BI__builtin_ia32_readeflags_u32: 3972 case X86::BI__builtin_ia32_writeeflags_u32: 3973 return true; 3974 } 3975 3976 return false; 3977 } 3978 3979 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3980 CallExpr *TheCall) { 3981 if (BuiltinID == X86::BI__builtin_cpu_supports) 3982 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3983 3984 if (BuiltinID == X86::BI__builtin_cpu_is) 3985 return SemaBuiltinCpuIs(*this, TI, TheCall); 3986 3987 // Check for 32-bit only builtins on a 64-bit target. 3988 const llvm::Triple &TT = TI.getTriple(); 3989 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3990 return Diag(TheCall->getCallee()->getBeginLoc(), 3991 diag::err_32_bit_builtin_64_bit_tgt); 3992 3993 // If the intrinsic has rounding or SAE make sure its valid. 3994 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3995 return true; 3996 3997 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3998 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3999 return true; 4000 4001 // If the intrinsic has a tile arguments, make sure they are valid. 4002 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4003 return true; 4004 4005 // For intrinsics which take an immediate value as part of the instruction, 4006 // range check them here. 4007 int i = 0, l = 0, u = 0; 4008 switch (BuiltinID) { 4009 default: 4010 return false; 4011 case X86::BI__builtin_ia32_vec_ext_v2si: 4012 case X86::BI__builtin_ia32_vec_ext_v2di: 4013 case X86::BI__builtin_ia32_vextractf128_pd256: 4014 case X86::BI__builtin_ia32_vextractf128_ps256: 4015 case X86::BI__builtin_ia32_vextractf128_si256: 4016 case X86::BI__builtin_ia32_extract128i256: 4017 case X86::BI__builtin_ia32_extractf64x4_mask: 4018 case X86::BI__builtin_ia32_extracti64x4_mask: 4019 case X86::BI__builtin_ia32_extractf32x8_mask: 4020 case X86::BI__builtin_ia32_extracti32x8_mask: 4021 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4022 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4023 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4024 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4025 i = 1; l = 0; u = 1; 4026 break; 4027 case X86::BI__builtin_ia32_vec_set_v2di: 4028 case X86::BI__builtin_ia32_vinsertf128_pd256: 4029 case X86::BI__builtin_ia32_vinsertf128_ps256: 4030 case X86::BI__builtin_ia32_vinsertf128_si256: 4031 case X86::BI__builtin_ia32_insert128i256: 4032 case X86::BI__builtin_ia32_insertf32x8: 4033 case X86::BI__builtin_ia32_inserti32x8: 4034 case X86::BI__builtin_ia32_insertf64x4: 4035 case X86::BI__builtin_ia32_inserti64x4: 4036 case X86::BI__builtin_ia32_insertf64x2_256: 4037 case X86::BI__builtin_ia32_inserti64x2_256: 4038 case X86::BI__builtin_ia32_insertf32x4_256: 4039 case X86::BI__builtin_ia32_inserti32x4_256: 4040 i = 2; l = 0; u = 1; 4041 break; 4042 case X86::BI__builtin_ia32_vpermilpd: 4043 case X86::BI__builtin_ia32_vec_ext_v4hi: 4044 case X86::BI__builtin_ia32_vec_ext_v4si: 4045 case X86::BI__builtin_ia32_vec_ext_v4sf: 4046 case X86::BI__builtin_ia32_vec_ext_v4di: 4047 case X86::BI__builtin_ia32_extractf32x4_mask: 4048 case X86::BI__builtin_ia32_extracti32x4_mask: 4049 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4050 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4051 i = 1; l = 0; u = 3; 4052 break; 4053 case X86::BI_mm_prefetch: 4054 case X86::BI__builtin_ia32_vec_ext_v8hi: 4055 case X86::BI__builtin_ia32_vec_ext_v8si: 4056 i = 1; l = 0; u = 7; 4057 break; 4058 case X86::BI__builtin_ia32_sha1rnds4: 4059 case X86::BI__builtin_ia32_blendpd: 4060 case X86::BI__builtin_ia32_shufpd: 4061 case X86::BI__builtin_ia32_vec_set_v4hi: 4062 case X86::BI__builtin_ia32_vec_set_v4si: 4063 case X86::BI__builtin_ia32_vec_set_v4di: 4064 case X86::BI__builtin_ia32_shuf_f32x4_256: 4065 case X86::BI__builtin_ia32_shuf_f64x2_256: 4066 case X86::BI__builtin_ia32_shuf_i32x4_256: 4067 case X86::BI__builtin_ia32_shuf_i64x2_256: 4068 case X86::BI__builtin_ia32_insertf64x2_512: 4069 case X86::BI__builtin_ia32_inserti64x2_512: 4070 case X86::BI__builtin_ia32_insertf32x4: 4071 case X86::BI__builtin_ia32_inserti32x4: 4072 i = 2; l = 0; u = 3; 4073 break; 4074 case X86::BI__builtin_ia32_vpermil2pd: 4075 case X86::BI__builtin_ia32_vpermil2pd256: 4076 case X86::BI__builtin_ia32_vpermil2ps: 4077 case X86::BI__builtin_ia32_vpermil2ps256: 4078 i = 3; l = 0; u = 3; 4079 break; 4080 case X86::BI__builtin_ia32_cmpb128_mask: 4081 case X86::BI__builtin_ia32_cmpw128_mask: 4082 case X86::BI__builtin_ia32_cmpd128_mask: 4083 case X86::BI__builtin_ia32_cmpq128_mask: 4084 case X86::BI__builtin_ia32_cmpb256_mask: 4085 case X86::BI__builtin_ia32_cmpw256_mask: 4086 case X86::BI__builtin_ia32_cmpd256_mask: 4087 case X86::BI__builtin_ia32_cmpq256_mask: 4088 case X86::BI__builtin_ia32_cmpb512_mask: 4089 case X86::BI__builtin_ia32_cmpw512_mask: 4090 case X86::BI__builtin_ia32_cmpd512_mask: 4091 case X86::BI__builtin_ia32_cmpq512_mask: 4092 case X86::BI__builtin_ia32_ucmpb128_mask: 4093 case X86::BI__builtin_ia32_ucmpw128_mask: 4094 case X86::BI__builtin_ia32_ucmpd128_mask: 4095 case X86::BI__builtin_ia32_ucmpq128_mask: 4096 case X86::BI__builtin_ia32_ucmpb256_mask: 4097 case X86::BI__builtin_ia32_ucmpw256_mask: 4098 case X86::BI__builtin_ia32_ucmpd256_mask: 4099 case X86::BI__builtin_ia32_ucmpq256_mask: 4100 case X86::BI__builtin_ia32_ucmpb512_mask: 4101 case X86::BI__builtin_ia32_ucmpw512_mask: 4102 case X86::BI__builtin_ia32_ucmpd512_mask: 4103 case X86::BI__builtin_ia32_ucmpq512_mask: 4104 case X86::BI__builtin_ia32_vpcomub: 4105 case X86::BI__builtin_ia32_vpcomuw: 4106 case X86::BI__builtin_ia32_vpcomud: 4107 case X86::BI__builtin_ia32_vpcomuq: 4108 case X86::BI__builtin_ia32_vpcomb: 4109 case X86::BI__builtin_ia32_vpcomw: 4110 case X86::BI__builtin_ia32_vpcomd: 4111 case X86::BI__builtin_ia32_vpcomq: 4112 case X86::BI__builtin_ia32_vec_set_v8hi: 4113 case X86::BI__builtin_ia32_vec_set_v8si: 4114 i = 2; l = 0; u = 7; 4115 break; 4116 case X86::BI__builtin_ia32_vpermilpd256: 4117 case X86::BI__builtin_ia32_roundps: 4118 case X86::BI__builtin_ia32_roundpd: 4119 case X86::BI__builtin_ia32_roundps256: 4120 case X86::BI__builtin_ia32_roundpd256: 4121 case X86::BI__builtin_ia32_getmantpd128_mask: 4122 case X86::BI__builtin_ia32_getmantpd256_mask: 4123 case X86::BI__builtin_ia32_getmantps128_mask: 4124 case X86::BI__builtin_ia32_getmantps256_mask: 4125 case X86::BI__builtin_ia32_getmantpd512_mask: 4126 case X86::BI__builtin_ia32_getmantps512_mask: 4127 case X86::BI__builtin_ia32_vec_ext_v16qi: 4128 case X86::BI__builtin_ia32_vec_ext_v16hi: 4129 i = 1; l = 0; u = 15; 4130 break; 4131 case X86::BI__builtin_ia32_pblendd128: 4132 case X86::BI__builtin_ia32_blendps: 4133 case X86::BI__builtin_ia32_blendpd256: 4134 case X86::BI__builtin_ia32_shufpd256: 4135 case X86::BI__builtin_ia32_roundss: 4136 case X86::BI__builtin_ia32_roundsd: 4137 case X86::BI__builtin_ia32_rangepd128_mask: 4138 case X86::BI__builtin_ia32_rangepd256_mask: 4139 case X86::BI__builtin_ia32_rangepd512_mask: 4140 case X86::BI__builtin_ia32_rangeps128_mask: 4141 case X86::BI__builtin_ia32_rangeps256_mask: 4142 case X86::BI__builtin_ia32_rangeps512_mask: 4143 case X86::BI__builtin_ia32_getmantsd_round_mask: 4144 case X86::BI__builtin_ia32_getmantss_round_mask: 4145 case X86::BI__builtin_ia32_vec_set_v16qi: 4146 case X86::BI__builtin_ia32_vec_set_v16hi: 4147 i = 2; l = 0; u = 15; 4148 break; 4149 case X86::BI__builtin_ia32_vec_ext_v32qi: 4150 i = 1; l = 0; u = 31; 4151 break; 4152 case X86::BI__builtin_ia32_cmpps: 4153 case X86::BI__builtin_ia32_cmpss: 4154 case X86::BI__builtin_ia32_cmppd: 4155 case X86::BI__builtin_ia32_cmpsd: 4156 case X86::BI__builtin_ia32_cmpps256: 4157 case X86::BI__builtin_ia32_cmppd256: 4158 case X86::BI__builtin_ia32_cmpps128_mask: 4159 case X86::BI__builtin_ia32_cmppd128_mask: 4160 case X86::BI__builtin_ia32_cmpps256_mask: 4161 case X86::BI__builtin_ia32_cmppd256_mask: 4162 case X86::BI__builtin_ia32_cmpps512_mask: 4163 case X86::BI__builtin_ia32_cmppd512_mask: 4164 case X86::BI__builtin_ia32_cmpsd_mask: 4165 case X86::BI__builtin_ia32_cmpss_mask: 4166 case X86::BI__builtin_ia32_vec_set_v32qi: 4167 i = 2; l = 0; u = 31; 4168 break; 4169 case X86::BI__builtin_ia32_permdf256: 4170 case X86::BI__builtin_ia32_permdi256: 4171 case X86::BI__builtin_ia32_permdf512: 4172 case X86::BI__builtin_ia32_permdi512: 4173 case X86::BI__builtin_ia32_vpermilps: 4174 case X86::BI__builtin_ia32_vpermilps256: 4175 case X86::BI__builtin_ia32_vpermilpd512: 4176 case X86::BI__builtin_ia32_vpermilps512: 4177 case X86::BI__builtin_ia32_pshufd: 4178 case X86::BI__builtin_ia32_pshufd256: 4179 case X86::BI__builtin_ia32_pshufd512: 4180 case X86::BI__builtin_ia32_pshufhw: 4181 case X86::BI__builtin_ia32_pshufhw256: 4182 case X86::BI__builtin_ia32_pshufhw512: 4183 case X86::BI__builtin_ia32_pshuflw: 4184 case X86::BI__builtin_ia32_pshuflw256: 4185 case X86::BI__builtin_ia32_pshuflw512: 4186 case X86::BI__builtin_ia32_vcvtps2ph: 4187 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4188 case X86::BI__builtin_ia32_vcvtps2ph256: 4189 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4190 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4191 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4192 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4193 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4194 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4195 case X86::BI__builtin_ia32_rndscaleps_mask: 4196 case X86::BI__builtin_ia32_rndscalepd_mask: 4197 case X86::BI__builtin_ia32_reducepd128_mask: 4198 case X86::BI__builtin_ia32_reducepd256_mask: 4199 case X86::BI__builtin_ia32_reducepd512_mask: 4200 case X86::BI__builtin_ia32_reduceps128_mask: 4201 case X86::BI__builtin_ia32_reduceps256_mask: 4202 case X86::BI__builtin_ia32_reduceps512_mask: 4203 case X86::BI__builtin_ia32_prold512: 4204 case X86::BI__builtin_ia32_prolq512: 4205 case X86::BI__builtin_ia32_prold128: 4206 case X86::BI__builtin_ia32_prold256: 4207 case X86::BI__builtin_ia32_prolq128: 4208 case X86::BI__builtin_ia32_prolq256: 4209 case X86::BI__builtin_ia32_prord512: 4210 case X86::BI__builtin_ia32_prorq512: 4211 case X86::BI__builtin_ia32_prord128: 4212 case X86::BI__builtin_ia32_prord256: 4213 case X86::BI__builtin_ia32_prorq128: 4214 case X86::BI__builtin_ia32_prorq256: 4215 case X86::BI__builtin_ia32_fpclasspd128_mask: 4216 case X86::BI__builtin_ia32_fpclasspd256_mask: 4217 case X86::BI__builtin_ia32_fpclassps128_mask: 4218 case X86::BI__builtin_ia32_fpclassps256_mask: 4219 case X86::BI__builtin_ia32_fpclassps512_mask: 4220 case X86::BI__builtin_ia32_fpclasspd512_mask: 4221 case X86::BI__builtin_ia32_fpclasssd_mask: 4222 case X86::BI__builtin_ia32_fpclassss_mask: 4223 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4224 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4225 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4226 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4227 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4228 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4229 case X86::BI__builtin_ia32_kshiftliqi: 4230 case X86::BI__builtin_ia32_kshiftlihi: 4231 case X86::BI__builtin_ia32_kshiftlisi: 4232 case X86::BI__builtin_ia32_kshiftlidi: 4233 case X86::BI__builtin_ia32_kshiftriqi: 4234 case X86::BI__builtin_ia32_kshiftrihi: 4235 case X86::BI__builtin_ia32_kshiftrisi: 4236 case X86::BI__builtin_ia32_kshiftridi: 4237 i = 1; l = 0; u = 255; 4238 break; 4239 case X86::BI__builtin_ia32_vperm2f128_pd256: 4240 case X86::BI__builtin_ia32_vperm2f128_ps256: 4241 case X86::BI__builtin_ia32_vperm2f128_si256: 4242 case X86::BI__builtin_ia32_permti256: 4243 case X86::BI__builtin_ia32_pblendw128: 4244 case X86::BI__builtin_ia32_pblendw256: 4245 case X86::BI__builtin_ia32_blendps256: 4246 case X86::BI__builtin_ia32_pblendd256: 4247 case X86::BI__builtin_ia32_palignr128: 4248 case X86::BI__builtin_ia32_palignr256: 4249 case X86::BI__builtin_ia32_palignr512: 4250 case X86::BI__builtin_ia32_alignq512: 4251 case X86::BI__builtin_ia32_alignd512: 4252 case X86::BI__builtin_ia32_alignd128: 4253 case X86::BI__builtin_ia32_alignd256: 4254 case X86::BI__builtin_ia32_alignq128: 4255 case X86::BI__builtin_ia32_alignq256: 4256 case X86::BI__builtin_ia32_vcomisd: 4257 case X86::BI__builtin_ia32_vcomiss: 4258 case X86::BI__builtin_ia32_shuf_f32x4: 4259 case X86::BI__builtin_ia32_shuf_f64x2: 4260 case X86::BI__builtin_ia32_shuf_i32x4: 4261 case X86::BI__builtin_ia32_shuf_i64x2: 4262 case X86::BI__builtin_ia32_shufpd512: 4263 case X86::BI__builtin_ia32_shufps: 4264 case X86::BI__builtin_ia32_shufps256: 4265 case X86::BI__builtin_ia32_shufps512: 4266 case X86::BI__builtin_ia32_dbpsadbw128: 4267 case X86::BI__builtin_ia32_dbpsadbw256: 4268 case X86::BI__builtin_ia32_dbpsadbw512: 4269 case X86::BI__builtin_ia32_vpshldd128: 4270 case X86::BI__builtin_ia32_vpshldd256: 4271 case X86::BI__builtin_ia32_vpshldd512: 4272 case X86::BI__builtin_ia32_vpshldq128: 4273 case X86::BI__builtin_ia32_vpshldq256: 4274 case X86::BI__builtin_ia32_vpshldq512: 4275 case X86::BI__builtin_ia32_vpshldw128: 4276 case X86::BI__builtin_ia32_vpshldw256: 4277 case X86::BI__builtin_ia32_vpshldw512: 4278 case X86::BI__builtin_ia32_vpshrdd128: 4279 case X86::BI__builtin_ia32_vpshrdd256: 4280 case X86::BI__builtin_ia32_vpshrdd512: 4281 case X86::BI__builtin_ia32_vpshrdq128: 4282 case X86::BI__builtin_ia32_vpshrdq256: 4283 case X86::BI__builtin_ia32_vpshrdq512: 4284 case X86::BI__builtin_ia32_vpshrdw128: 4285 case X86::BI__builtin_ia32_vpshrdw256: 4286 case X86::BI__builtin_ia32_vpshrdw512: 4287 i = 2; l = 0; u = 255; 4288 break; 4289 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4290 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4291 case X86::BI__builtin_ia32_fixupimmps512_mask: 4292 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4293 case X86::BI__builtin_ia32_fixupimmsd_mask: 4294 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4295 case X86::BI__builtin_ia32_fixupimmss_mask: 4296 case X86::BI__builtin_ia32_fixupimmss_maskz: 4297 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4298 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4299 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4300 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4301 case X86::BI__builtin_ia32_fixupimmps128_mask: 4302 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4303 case X86::BI__builtin_ia32_fixupimmps256_mask: 4304 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4305 case X86::BI__builtin_ia32_pternlogd512_mask: 4306 case X86::BI__builtin_ia32_pternlogd512_maskz: 4307 case X86::BI__builtin_ia32_pternlogq512_mask: 4308 case X86::BI__builtin_ia32_pternlogq512_maskz: 4309 case X86::BI__builtin_ia32_pternlogd128_mask: 4310 case X86::BI__builtin_ia32_pternlogd128_maskz: 4311 case X86::BI__builtin_ia32_pternlogd256_mask: 4312 case X86::BI__builtin_ia32_pternlogd256_maskz: 4313 case X86::BI__builtin_ia32_pternlogq128_mask: 4314 case X86::BI__builtin_ia32_pternlogq128_maskz: 4315 case X86::BI__builtin_ia32_pternlogq256_mask: 4316 case X86::BI__builtin_ia32_pternlogq256_maskz: 4317 i = 3; l = 0; u = 255; 4318 break; 4319 case X86::BI__builtin_ia32_gatherpfdpd: 4320 case X86::BI__builtin_ia32_gatherpfdps: 4321 case X86::BI__builtin_ia32_gatherpfqpd: 4322 case X86::BI__builtin_ia32_gatherpfqps: 4323 case X86::BI__builtin_ia32_scatterpfdpd: 4324 case X86::BI__builtin_ia32_scatterpfdps: 4325 case X86::BI__builtin_ia32_scatterpfqpd: 4326 case X86::BI__builtin_ia32_scatterpfqps: 4327 i = 4; l = 2; u = 3; 4328 break; 4329 case X86::BI__builtin_ia32_reducesd_mask: 4330 case X86::BI__builtin_ia32_reducess_mask: 4331 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4332 case X86::BI__builtin_ia32_rndscaless_round_mask: 4333 i = 4; l = 0; u = 255; 4334 break; 4335 } 4336 4337 // Note that we don't force a hard error on the range check here, allowing 4338 // template-generated or macro-generated dead code to potentially have out-of- 4339 // range values. These need to code generate, but don't need to necessarily 4340 // make any sense. We use a warning that defaults to an error. 4341 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4342 } 4343 4344 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4345 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4346 /// Returns true when the format fits the function and the FormatStringInfo has 4347 /// been populated. 4348 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4349 FormatStringInfo *FSI) { 4350 FSI->HasVAListArg = Format->getFirstArg() == 0; 4351 FSI->FormatIdx = Format->getFormatIdx() - 1; 4352 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4353 4354 // The way the format attribute works in GCC, the implicit this argument 4355 // of member functions is counted. However, it doesn't appear in our own 4356 // lists, so decrement format_idx in that case. 4357 if (IsCXXMember) { 4358 if(FSI->FormatIdx == 0) 4359 return false; 4360 --FSI->FormatIdx; 4361 if (FSI->FirstDataArg != 0) 4362 --FSI->FirstDataArg; 4363 } 4364 return true; 4365 } 4366 4367 /// Checks if a the given expression evaluates to null. 4368 /// 4369 /// Returns true if the value evaluates to null. 4370 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4371 // If the expression has non-null type, it doesn't evaluate to null. 4372 if (auto nullability 4373 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4374 if (*nullability == NullabilityKind::NonNull) 4375 return false; 4376 } 4377 4378 // As a special case, transparent unions initialized with zero are 4379 // considered null for the purposes of the nonnull attribute. 4380 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4381 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4382 if (const CompoundLiteralExpr *CLE = 4383 dyn_cast<CompoundLiteralExpr>(Expr)) 4384 if (const InitListExpr *ILE = 4385 dyn_cast<InitListExpr>(CLE->getInitializer())) 4386 Expr = ILE->getInit(0); 4387 } 4388 4389 bool Result; 4390 return (!Expr->isValueDependent() && 4391 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4392 !Result); 4393 } 4394 4395 static void CheckNonNullArgument(Sema &S, 4396 const Expr *ArgExpr, 4397 SourceLocation CallSiteLoc) { 4398 if (CheckNonNullExpr(S, ArgExpr)) 4399 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4400 S.PDiag(diag::warn_null_arg) 4401 << ArgExpr->getSourceRange()); 4402 } 4403 4404 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4405 FormatStringInfo FSI; 4406 if ((GetFormatStringType(Format) == FST_NSString) && 4407 getFormatStringInfo(Format, false, &FSI)) { 4408 Idx = FSI.FormatIdx; 4409 return true; 4410 } 4411 return false; 4412 } 4413 4414 /// Diagnose use of %s directive in an NSString which is being passed 4415 /// as formatting string to formatting method. 4416 static void 4417 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4418 const NamedDecl *FDecl, 4419 Expr **Args, 4420 unsigned NumArgs) { 4421 unsigned Idx = 0; 4422 bool Format = false; 4423 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4424 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4425 Idx = 2; 4426 Format = true; 4427 } 4428 else 4429 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4430 if (S.GetFormatNSStringIdx(I, Idx)) { 4431 Format = true; 4432 break; 4433 } 4434 } 4435 if (!Format || NumArgs <= Idx) 4436 return; 4437 const Expr *FormatExpr = Args[Idx]; 4438 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4439 FormatExpr = CSCE->getSubExpr(); 4440 const StringLiteral *FormatString; 4441 if (const ObjCStringLiteral *OSL = 4442 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4443 FormatString = OSL->getString(); 4444 else 4445 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4446 if (!FormatString) 4447 return; 4448 if (S.FormatStringHasSArg(FormatString)) { 4449 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4450 << "%s" << 1 << 1; 4451 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4452 << FDecl->getDeclName(); 4453 } 4454 } 4455 4456 /// Determine whether the given type has a non-null nullability annotation. 4457 static bool isNonNullType(ASTContext &ctx, QualType type) { 4458 if (auto nullability = type->getNullability(ctx)) 4459 return *nullability == NullabilityKind::NonNull; 4460 4461 return false; 4462 } 4463 4464 static void CheckNonNullArguments(Sema &S, 4465 const NamedDecl *FDecl, 4466 const FunctionProtoType *Proto, 4467 ArrayRef<const Expr *> Args, 4468 SourceLocation CallSiteLoc) { 4469 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4470 4471 // Already checked by by constant evaluator. 4472 if (S.isConstantEvaluated()) 4473 return; 4474 // Check the attributes attached to the method/function itself. 4475 llvm::SmallBitVector NonNullArgs; 4476 if (FDecl) { 4477 // Handle the nonnull attribute on the function/method declaration itself. 4478 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4479 if (!NonNull->args_size()) { 4480 // Easy case: all pointer arguments are nonnull. 4481 for (const auto *Arg : Args) 4482 if (S.isValidPointerAttrType(Arg->getType())) 4483 CheckNonNullArgument(S, Arg, CallSiteLoc); 4484 return; 4485 } 4486 4487 for (const ParamIdx &Idx : NonNull->args()) { 4488 unsigned IdxAST = Idx.getASTIndex(); 4489 if (IdxAST >= Args.size()) 4490 continue; 4491 if (NonNullArgs.empty()) 4492 NonNullArgs.resize(Args.size()); 4493 NonNullArgs.set(IdxAST); 4494 } 4495 } 4496 } 4497 4498 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4499 // Handle the nonnull attribute on the parameters of the 4500 // function/method. 4501 ArrayRef<ParmVarDecl*> parms; 4502 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4503 parms = FD->parameters(); 4504 else 4505 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4506 4507 unsigned ParamIndex = 0; 4508 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4509 I != E; ++I, ++ParamIndex) { 4510 const ParmVarDecl *PVD = *I; 4511 if (PVD->hasAttr<NonNullAttr>() || 4512 isNonNullType(S.Context, PVD->getType())) { 4513 if (NonNullArgs.empty()) 4514 NonNullArgs.resize(Args.size()); 4515 4516 NonNullArgs.set(ParamIndex); 4517 } 4518 } 4519 } else { 4520 // If we have a non-function, non-method declaration but no 4521 // function prototype, try to dig out the function prototype. 4522 if (!Proto) { 4523 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4524 QualType type = VD->getType().getNonReferenceType(); 4525 if (auto pointerType = type->getAs<PointerType>()) 4526 type = pointerType->getPointeeType(); 4527 else if (auto blockType = type->getAs<BlockPointerType>()) 4528 type = blockType->getPointeeType(); 4529 // FIXME: data member pointers? 4530 4531 // Dig out the function prototype, if there is one. 4532 Proto = type->getAs<FunctionProtoType>(); 4533 } 4534 } 4535 4536 // Fill in non-null argument information from the nullability 4537 // information on the parameter types (if we have them). 4538 if (Proto) { 4539 unsigned Index = 0; 4540 for (auto paramType : Proto->getParamTypes()) { 4541 if (isNonNullType(S.Context, paramType)) { 4542 if (NonNullArgs.empty()) 4543 NonNullArgs.resize(Args.size()); 4544 4545 NonNullArgs.set(Index); 4546 } 4547 4548 ++Index; 4549 } 4550 } 4551 } 4552 4553 // Check for non-null arguments. 4554 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4555 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4556 if (NonNullArgs[ArgIndex]) 4557 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4558 } 4559 } 4560 4561 /// Warn if a pointer or reference argument passed to a function points to an 4562 /// object that is less aligned than the parameter. This can happen when 4563 /// creating a typedef with a lower alignment than the original type and then 4564 /// calling functions defined in terms of the original type. 4565 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4566 StringRef ParamName, QualType ArgTy, 4567 QualType ParamTy) { 4568 4569 // If a function accepts a pointer or reference type 4570 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4571 return; 4572 4573 // If the parameter is a pointer type, get the pointee type for the 4574 // argument too. If the parameter is a reference type, don't try to get 4575 // the pointee type for the argument. 4576 if (ParamTy->isPointerType()) 4577 ArgTy = ArgTy->getPointeeType(); 4578 4579 // Remove reference or pointer 4580 ParamTy = ParamTy->getPointeeType(); 4581 4582 // Find expected alignment, and the actual alignment of the passed object. 4583 // getTypeAlignInChars requires complete types 4584 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 4585 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 4586 ArgTy->isUndeducedType()) 4587 return; 4588 4589 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4590 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4591 4592 // If the argument is less aligned than the parameter, there is a 4593 // potential alignment issue. 4594 if (ArgAlign < ParamAlign) 4595 Diag(Loc, diag::warn_param_mismatched_alignment) 4596 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4597 << ParamName << FDecl; 4598 } 4599 4600 /// Handles the checks for format strings, non-POD arguments to vararg 4601 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4602 /// attributes. 4603 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4604 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4605 bool IsMemberFunction, SourceLocation Loc, 4606 SourceRange Range, VariadicCallType CallType) { 4607 // FIXME: We should check as much as we can in the template definition. 4608 if (CurContext->isDependentContext()) 4609 return; 4610 4611 // Printf and scanf checking. 4612 llvm::SmallBitVector CheckedVarArgs; 4613 if (FDecl) { 4614 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4615 // Only create vector if there are format attributes. 4616 CheckedVarArgs.resize(Args.size()); 4617 4618 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4619 CheckedVarArgs); 4620 } 4621 } 4622 4623 // Refuse POD arguments that weren't caught by the format string 4624 // checks above. 4625 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4626 if (CallType != VariadicDoesNotApply && 4627 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4628 unsigned NumParams = Proto ? Proto->getNumParams() 4629 : FDecl && isa<FunctionDecl>(FDecl) 4630 ? cast<FunctionDecl>(FDecl)->getNumParams() 4631 : FDecl && isa<ObjCMethodDecl>(FDecl) 4632 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4633 : 0; 4634 4635 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4636 // Args[ArgIdx] can be null in malformed code. 4637 if (const Expr *Arg = Args[ArgIdx]) { 4638 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4639 checkVariadicArgument(Arg, CallType); 4640 } 4641 } 4642 } 4643 4644 if (FDecl || Proto) { 4645 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4646 4647 // Type safety checking. 4648 if (FDecl) { 4649 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4650 CheckArgumentWithTypeTag(I, Args, Loc); 4651 } 4652 } 4653 4654 // Check that passed arguments match the alignment of original arguments. 4655 // Try to get the missing prototype from the declaration. 4656 if (!Proto && FDecl) { 4657 const auto *FT = FDecl->getFunctionType(); 4658 if (isa_and_nonnull<FunctionProtoType>(FT)) 4659 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 4660 } 4661 if (Proto) { 4662 // For variadic functions, we may have more args than parameters. 4663 // For some K&R functions, we may have less args than parameters. 4664 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 4665 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 4666 // Args[ArgIdx] can be null in malformed code. 4667 if (const Expr *Arg = Args[ArgIdx]) { 4668 if (Arg->containsErrors()) 4669 continue; 4670 4671 QualType ParamTy = Proto->getParamType(ArgIdx); 4672 QualType ArgTy = Arg->getType(); 4673 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 4674 ArgTy, ParamTy); 4675 } 4676 } 4677 } 4678 4679 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4680 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4681 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4682 if (!Arg->isValueDependent()) { 4683 Expr::EvalResult Align; 4684 if (Arg->EvaluateAsInt(Align, Context)) { 4685 const llvm::APSInt &I = Align.Val.getInt(); 4686 if (!I.isPowerOf2()) 4687 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4688 << Arg->getSourceRange(); 4689 4690 if (I > Sema::MaximumAlignment) 4691 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4692 << Arg->getSourceRange() << Sema::MaximumAlignment; 4693 } 4694 } 4695 } 4696 4697 if (FD) 4698 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4699 } 4700 4701 /// CheckConstructorCall - Check a constructor call for correctness and safety 4702 /// properties not enforced by the C type system. 4703 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 4704 ArrayRef<const Expr *> Args, 4705 const FunctionProtoType *Proto, 4706 SourceLocation Loc) { 4707 VariadicCallType CallType = 4708 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4709 4710 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 4711 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 4712 Context.getPointerType(Ctor->getThisObjectType())); 4713 4714 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4715 Loc, SourceRange(), CallType); 4716 } 4717 4718 /// CheckFunctionCall - Check a direct function call for various correctness 4719 /// and safety properties not strictly enforced by the C type system. 4720 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4721 const FunctionProtoType *Proto) { 4722 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4723 isa<CXXMethodDecl>(FDecl); 4724 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4725 IsMemberOperatorCall; 4726 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4727 TheCall->getCallee()); 4728 Expr** Args = TheCall->getArgs(); 4729 unsigned NumArgs = TheCall->getNumArgs(); 4730 4731 Expr *ImplicitThis = nullptr; 4732 if (IsMemberOperatorCall) { 4733 // If this is a call to a member operator, hide the first argument 4734 // from checkCall. 4735 // FIXME: Our choice of AST representation here is less than ideal. 4736 ImplicitThis = Args[0]; 4737 ++Args; 4738 --NumArgs; 4739 } else if (IsMemberFunction) 4740 ImplicitThis = 4741 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4742 4743 if (ImplicitThis) { 4744 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 4745 // used. 4746 QualType ThisType = ImplicitThis->getType(); 4747 if (!ThisType->isPointerType()) { 4748 assert(!ThisType->isReferenceType()); 4749 ThisType = Context.getPointerType(ThisType); 4750 } 4751 4752 QualType ThisTypeFromDecl = 4753 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 4754 4755 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 4756 ThisTypeFromDecl); 4757 } 4758 4759 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4760 IsMemberFunction, TheCall->getRParenLoc(), 4761 TheCall->getCallee()->getSourceRange(), CallType); 4762 4763 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4764 // None of the checks below are needed for functions that don't have 4765 // simple names (e.g., C++ conversion functions). 4766 if (!FnInfo) 4767 return false; 4768 4769 CheckTCBEnforcement(TheCall, FDecl); 4770 4771 CheckAbsoluteValueFunction(TheCall, FDecl); 4772 CheckMaxUnsignedZero(TheCall, FDecl); 4773 4774 if (getLangOpts().ObjC) 4775 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4776 4777 unsigned CMId = FDecl->getMemoryFunctionKind(); 4778 4779 // Handle memory setting and copying functions. 4780 switch (CMId) { 4781 case 0: 4782 return false; 4783 case Builtin::BIstrlcpy: // fallthrough 4784 case Builtin::BIstrlcat: 4785 CheckStrlcpycatArguments(TheCall, FnInfo); 4786 break; 4787 case Builtin::BIstrncat: 4788 CheckStrncatArguments(TheCall, FnInfo); 4789 break; 4790 case Builtin::BIfree: 4791 CheckFreeArguments(TheCall); 4792 break; 4793 default: 4794 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4795 } 4796 4797 return false; 4798 } 4799 4800 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4801 ArrayRef<const Expr *> Args) { 4802 VariadicCallType CallType = 4803 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4804 4805 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4806 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4807 CallType); 4808 4809 return false; 4810 } 4811 4812 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4813 const FunctionProtoType *Proto) { 4814 QualType Ty; 4815 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4816 Ty = V->getType().getNonReferenceType(); 4817 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4818 Ty = F->getType().getNonReferenceType(); 4819 else 4820 return false; 4821 4822 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4823 !Ty->isFunctionProtoType()) 4824 return false; 4825 4826 VariadicCallType CallType; 4827 if (!Proto || !Proto->isVariadic()) { 4828 CallType = VariadicDoesNotApply; 4829 } else if (Ty->isBlockPointerType()) { 4830 CallType = VariadicBlock; 4831 } else { // Ty->isFunctionPointerType() 4832 CallType = VariadicFunction; 4833 } 4834 4835 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4836 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4837 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4838 TheCall->getCallee()->getSourceRange(), CallType); 4839 4840 return false; 4841 } 4842 4843 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4844 /// such as function pointers returned from functions. 4845 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4846 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4847 TheCall->getCallee()); 4848 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4849 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4850 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4851 TheCall->getCallee()->getSourceRange(), CallType); 4852 4853 return false; 4854 } 4855 4856 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4857 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4858 return false; 4859 4860 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4861 switch (Op) { 4862 case AtomicExpr::AO__c11_atomic_init: 4863 case AtomicExpr::AO__opencl_atomic_init: 4864 llvm_unreachable("There is no ordering argument for an init"); 4865 4866 case AtomicExpr::AO__c11_atomic_load: 4867 case AtomicExpr::AO__opencl_atomic_load: 4868 case AtomicExpr::AO__atomic_load_n: 4869 case AtomicExpr::AO__atomic_load: 4870 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4871 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4872 4873 case AtomicExpr::AO__c11_atomic_store: 4874 case AtomicExpr::AO__opencl_atomic_store: 4875 case AtomicExpr::AO__atomic_store: 4876 case AtomicExpr::AO__atomic_store_n: 4877 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4878 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4879 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4880 4881 default: 4882 return true; 4883 } 4884 } 4885 4886 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4887 AtomicExpr::AtomicOp Op) { 4888 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4889 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4890 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4891 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4892 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4893 Op); 4894 } 4895 4896 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4897 SourceLocation RParenLoc, MultiExprArg Args, 4898 AtomicExpr::AtomicOp Op, 4899 AtomicArgumentOrder ArgOrder) { 4900 // All the non-OpenCL operations take one of the following forms. 4901 // The OpenCL operations take the __c11 forms with one extra argument for 4902 // synchronization scope. 4903 enum { 4904 // C __c11_atomic_init(A *, C) 4905 Init, 4906 4907 // C __c11_atomic_load(A *, int) 4908 Load, 4909 4910 // void __atomic_load(A *, CP, int) 4911 LoadCopy, 4912 4913 // void __atomic_store(A *, CP, int) 4914 Copy, 4915 4916 // C __c11_atomic_add(A *, M, int) 4917 Arithmetic, 4918 4919 // C __atomic_exchange_n(A *, CP, int) 4920 Xchg, 4921 4922 // void __atomic_exchange(A *, C *, CP, int) 4923 GNUXchg, 4924 4925 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4926 C11CmpXchg, 4927 4928 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4929 GNUCmpXchg 4930 } Form = Init; 4931 4932 const unsigned NumForm = GNUCmpXchg + 1; 4933 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4934 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4935 // where: 4936 // C is an appropriate type, 4937 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4938 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4939 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4940 // the int parameters are for orderings. 4941 4942 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4943 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4944 "need to update code for modified forms"); 4945 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4946 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4947 AtomicExpr::AO__atomic_load, 4948 "need to update code for modified C11 atomics"); 4949 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4950 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4951 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4952 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4953 IsOpenCL; 4954 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4955 Op == AtomicExpr::AO__atomic_store_n || 4956 Op == AtomicExpr::AO__atomic_exchange_n || 4957 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4958 bool IsAddSub = false; 4959 4960 switch (Op) { 4961 case AtomicExpr::AO__c11_atomic_init: 4962 case AtomicExpr::AO__opencl_atomic_init: 4963 Form = Init; 4964 break; 4965 4966 case AtomicExpr::AO__c11_atomic_load: 4967 case AtomicExpr::AO__opencl_atomic_load: 4968 case AtomicExpr::AO__atomic_load_n: 4969 Form = Load; 4970 break; 4971 4972 case AtomicExpr::AO__atomic_load: 4973 Form = LoadCopy; 4974 break; 4975 4976 case AtomicExpr::AO__c11_atomic_store: 4977 case AtomicExpr::AO__opencl_atomic_store: 4978 case AtomicExpr::AO__atomic_store: 4979 case AtomicExpr::AO__atomic_store_n: 4980 Form = Copy; 4981 break; 4982 4983 case AtomicExpr::AO__c11_atomic_fetch_add: 4984 case AtomicExpr::AO__c11_atomic_fetch_sub: 4985 case AtomicExpr::AO__opencl_atomic_fetch_add: 4986 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4987 case AtomicExpr::AO__atomic_fetch_add: 4988 case AtomicExpr::AO__atomic_fetch_sub: 4989 case AtomicExpr::AO__atomic_add_fetch: 4990 case AtomicExpr::AO__atomic_sub_fetch: 4991 IsAddSub = true; 4992 Form = Arithmetic; 4993 break; 4994 case AtomicExpr::AO__c11_atomic_fetch_and: 4995 case AtomicExpr::AO__c11_atomic_fetch_or: 4996 case AtomicExpr::AO__c11_atomic_fetch_xor: 4997 case AtomicExpr::AO__opencl_atomic_fetch_and: 4998 case AtomicExpr::AO__opencl_atomic_fetch_or: 4999 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5000 case AtomicExpr::AO__atomic_fetch_and: 5001 case AtomicExpr::AO__atomic_fetch_or: 5002 case AtomicExpr::AO__atomic_fetch_xor: 5003 case AtomicExpr::AO__atomic_fetch_nand: 5004 case AtomicExpr::AO__atomic_and_fetch: 5005 case AtomicExpr::AO__atomic_or_fetch: 5006 case AtomicExpr::AO__atomic_xor_fetch: 5007 case AtomicExpr::AO__atomic_nand_fetch: 5008 Form = Arithmetic; 5009 break; 5010 case AtomicExpr::AO__c11_atomic_fetch_min: 5011 case AtomicExpr::AO__c11_atomic_fetch_max: 5012 case AtomicExpr::AO__opencl_atomic_fetch_min: 5013 case AtomicExpr::AO__opencl_atomic_fetch_max: 5014 case AtomicExpr::AO__atomic_min_fetch: 5015 case AtomicExpr::AO__atomic_max_fetch: 5016 case AtomicExpr::AO__atomic_fetch_min: 5017 case AtomicExpr::AO__atomic_fetch_max: 5018 Form = Arithmetic; 5019 break; 5020 5021 case AtomicExpr::AO__c11_atomic_exchange: 5022 case AtomicExpr::AO__opencl_atomic_exchange: 5023 case AtomicExpr::AO__atomic_exchange_n: 5024 Form = Xchg; 5025 break; 5026 5027 case AtomicExpr::AO__atomic_exchange: 5028 Form = GNUXchg; 5029 break; 5030 5031 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5032 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5033 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5034 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5035 Form = C11CmpXchg; 5036 break; 5037 5038 case AtomicExpr::AO__atomic_compare_exchange: 5039 case AtomicExpr::AO__atomic_compare_exchange_n: 5040 Form = GNUCmpXchg; 5041 break; 5042 } 5043 5044 unsigned AdjustedNumArgs = NumArgs[Form]; 5045 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5046 ++AdjustedNumArgs; 5047 // Check we have the right number of arguments. 5048 if (Args.size() < AdjustedNumArgs) { 5049 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5050 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5051 << ExprRange; 5052 return ExprError(); 5053 } else if (Args.size() > AdjustedNumArgs) { 5054 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5055 diag::err_typecheck_call_too_many_args) 5056 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5057 << ExprRange; 5058 return ExprError(); 5059 } 5060 5061 // Inspect the first argument of the atomic operation. 5062 Expr *Ptr = Args[0]; 5063 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5064 if (ConvertedPtr.isInvalid()) 5065 return ExprError(); 5066 5067 Ptr = ConvertedPtr.get(); 5068 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5069 if (!pointerType) { 5070 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5071 << Ptr->getType() << Ptr->getSourceRange(); 5072 return ExprError(); 5073 } 5074 5075 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5076 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5077 QualType ValType = AtomTy; // 'C' 5078 if (IsC11) { 5079 if (!AtomTy->isAtomicType()) { 5080 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5081 << Ptr->getType() << Ptr->getSourceRange(); 5082 return ExprError(); 5083 } 5084 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5085 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5086 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5087 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5088 << Ptr->getSourceRange(); 5089 return ExprError(); 5090 } 5091 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5092 } else if (Form != Load && Form != LoadCopy) { 5093 if (ValType.isConstQualified()) { 5094 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5095 << Ptr->getType() << Ptr->getSourceRange(); 5096 return ExprError(); 5097 } 5098 } 5099 5100 // For an arithmetic operation, the implied arithmetic must be well-formed. 5101 if (Form == Arithmetic) { 5102 // gcc does not enforce these rules for GNU atomics, but we do so for 5103 // sanity. 5104 auto IsAllowedValueType = [&](QualType ValType) { 5105 if (ValType->isIntegerType()) 5106 return true; 5107 if (ValType->isPointerType()) 5108 return true; 5109 if (!ValType->isFloatingType()) 5110 return false; 5111 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5112 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5113 &Context.getTargetInfo().getLongDoubleFormat() == 5114 &llvm::APFloat::x87DoubleExtended()) 5115 return false; 5116 return true; 5117 }; 5118 if (IsAddSub && !IsAllowedValueType(ValType)) { 5119 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5120 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5121 return ExprError(); 5122 } 5123 if (!IsAddSub && !ValType->isIntegerType()) { 5124 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5125 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5126 return ExprError(); 5127 } 5128 if (IsC11 && ValType->isPointerType() && 5129 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5130 diag::err_incomplete_type)) { 5131 return ExprError(); 5132 } 5133 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5134 // For __atomic_*_n operations, the value type must be a scalar integral or 5135 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5136 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5137 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5138 return ExprError(); 5139 } 5140 5141 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5142 !AtomTy->isScalarType()) { 5143 // For GNU atomics, require a trivially-copyable type. This is not part of 5144 // the GNU atomics specification, but we enforce it for sanity. 5145 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5146 << Ptr->getType() << Ptr->getSourceRange(); 5147 return ExprError(); 5148 } 5149 5150 switch (ValType.getObjCLifetime()) { 5151 case Qualifiers::OCL_None: 5152 case Qualifiers::OCL_ExplicitNone: 5153 // okay 5154 break; 5155 5156 case Qualifiers::OCL_Weak: 5157 case Qualifiers::OCL_Strong: 5158 case Qualifiers::OCL_Autoreleasing: 5159 // FIXME: Can this happen? By this point, ValType should be known 5160 // to be trivially copyable. 5161 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5162 << ValType << Ptr->getSourceRange(); 5163 return ExprError(); 5164 } 5165 5166 // All atomic operations have an overload which takes a pointer to a volatile 5167 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5168 // into the result or the other operands. Similarly atomic_load takes a 5169 // pointer to a const 'A'. 5170 ValType.removeLocalVolatile(); 5171 ValType.removeLocalConst(); 5172 QualType ResultType = ValType; 5173 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5174 Form == Init) 5175 ResultType = Context.VoidTy; 5176 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5177 ResultType = Context.BoolTy; 5178 5179 // The type of a parameter passed 'by value'. In the GNU atomics, such 5180 // arguments are actually passed as pointers. 5181 QualType ByValType = ValType; // 'CP' 5182 bool IsPassedByAddress = false; 5183 if (!IsC11 && !IsN) { 5184 ByValType = Ptr->getType(); 5185 IsPassedByAddress = true; 5186 } 5187 5188 SmallVector<Expr *, 5> APIOrderedArgs; 5189 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5190 APIOrderedArgs.push_back(Args[0]); 5191 switch (Form) { 5192 case Init: 5193 case Load: 5194 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5195 break; 5196 case LoadCopy: 5197 case Copy: 5198 case Arithmetic: 5199 case Xchg: 5200 APIOrderedArgs.push_back(Args[2]); // Val1 5201 APIOrderedArgs.push_back(Args[1]); // Order 5202 break; 5203 case GNUXchg: 5204 APIOrderedArgs.push_back(Args[2]); // Val1 5205 APIOrderedArgs.push_back(Args[3]); // Val2 5206 APIOrderedArgs.push_back(Args[1]); // Order 5207 break; 5208 case C11CmpXchg: 5209 APIOrderedArgs.push_back(Args[2]); // Val1 5210 APIOrderedArgs.push_back(Args[4]); // Val2 5211 APIOrderedArgs.push_back(Args[1]); // Order 5212 APIOrderedArgs.push_back(Args[3]); // OrderFail 5213 break; 5214 case GNUCmpXchg: 5215 APIOrderedArgs.push_back(Args[2]); // Val1 5216 APIOrderedArgs.push_back(Args[4]); // Val2 5217 APIOrderedArgs.push_back(Args[5]); // Weak 5218 APIOrderedArgs.push_back(Args[1]); // Order 5219 APIOrderedArgs.push_back(Args[3]); // OrderFail 5220 break; 5221 } 5222 } else 5223 APIOrderedArgs.append(Args.begin(), Args.end()); 5224 5225 // The first argument's non-CV pointer type is used to deduce the type of 5226 // subsequent arguments, except for: 5227 // - weak flag (always converted to bool) 5228 // - memory order (always converted to int) 5229 // - scope (always converted to int) 5230 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5231 QualType Ty; 5232 if (i < NumVals[Form] + 1) { 5233 switch (i) { 5234 case 0: 5235 // The first argument is always a pointer. It has a fixed type. 5236 // It is always dereferenced, a nullptr is undefined. 5237 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5238 // Nothing else to do: we already know all we want about this pointer. 5239 continue; 5240 case 1: 5241 // The second argument is the non-atomic operand. For arithmetic, this 5242 // is always passed by value, and for a compare_exchange it is always 5243 // passed by address. For the rest, GNU uses by-address and C11 uses 5244 // by-value. 5245 assert(Form != Load); 5246 if (Form == Arithmetic && ValType->isPointerType()) 5247 Ty = Context.getPointerDiffType(); 5248 else if (Form == Init || Form == Arithmetic) 5249 Ty = ValType; 5250 else if (Form == Copy || Form == Xchg) { 5251 if (IsPassedByAddress) { 5252 // The value pointer is always dereferenced, a nullptr is undefined. 5253 CheckNonNullArgument(*this, APIOrderedArgs[i], 5254 ExprRange.getBegin()); 5255 } 5256 Ty = ByValType; 5257 } else { 5258 Expr *ValArg = APIOrderedArgs[i]; 5259 // The value pointer is always dereferenced, a nullptr is undefined. 5260 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5261 LangAS AS = LangAS::Default; 5262 // Keep address space of non-atomic pointer type. 5263 if (const PointerType *PtrTy = 5264 ValArg->getType()->getAs<PointerType>()) { 5265 AS = PtrTy->getPointeeType().getAddressSpace(); 5266 } 5267 Ty = Context.getPointerType( 5268 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5269 } 5270 break; 5271 case 2: 5272 // The third argument to compare_exchange / GNU exchange is the desired 5273 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5274 if (IsPassedByAddress) 5275 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5276 Ty = ByValType; 5277 break; 5278 case 3: 5279 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5280 Ty = Context.BoolTy; 5281 break; 5282 } 5283 } else { 5284 // The order(s) and scope are always converted to int. 5285 Ty = Context.IntTy; 5286 } 5287 5288 InitializedEntity Entity = 5289 InitializedEntity::InitializeParameter(Context, Ty, false); 5290 ExprResult Arg = APIOrderedArgs[i]; 5291 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5292 if (Arg.isInvalid()) 5293 return true; 5294 APIOrderedArgs[i] = Arg.get(); 5295 } 5296 5297 // Permute the arguments into a 'consistent' order. 5298 SmallVector<Expr*, 5> SubExprs; 5299 SubExprs.push_back(Ptr); 5300 switch (Form) { 5301 case Init: 5302 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5303 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5304 break; 5305 case Load: 5306 SubExprs.push_back(APIOrderedArgs[1]); // Order 5307 break; 5308 case LoadCopy: 5309 case Copy: 5310 case Arithmetic: 5311 case Xchg: 5312 SubExprs.push_back(APIOrderedArgs[2]); // Order 5313 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5314 break; 5315 case GNUXchg: 5316 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5317 SubExprs.push_back(APIOrderedArgs[3]); // Order 5318 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5319 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5320 break; 5321 case C11CmpXchg: 5322 SubExprs.push_back(APIOrderedArgs[3]); // Order 5323 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5324 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5325 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5326 break; 5327 case GNUCmpXchg: 5328 SubExprs.push_back(APIOrderedArgs[4]); // Order 5329 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5330 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5331 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5332 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5333 break; 5334 } 5335 5336 if (SubExprs.size() >= 2 && Form != Init) { 5337 if (Optional<llvm::APSInt> Result = 5338 SubExprs[1]->getIntegerConstantExpr(Context)) 5339 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5340 Diag(SubExprs[1]->getBeginLoc(), 5341 diag::warn_atomic_op_has_invalid_memory_order) 5342 << SubExprs[1]->getSourceRange(); 5343 } 5344 5345 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5346 auto *Scope = Args[Args.size() - 1]; 5347 if (Optional<llvm::APSInt> Result = 5348 Scope->getIntegerConstantExpr(Context)) { 5349 if (!ScopeModel->isValid(Result->getZExtValue())) 5350 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5351 << Scope->getSourceRange(); 5352 } 5353 SubExprs.push_back(Scope); 5354 } 5355 5356 AtomicExpr *AE = new (Context) 5357 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5358 5359 if ((Op == AtomicExpr::AO__c11_atomic_load || 5360 Op == AtomicExpr::AO__c11_atomic_store || 5361 Op == AtomicExpr::AO__opencl_atomic_load || 5362 Op == AtomicExpr::AO__opencl_atomic_store ) && 5363 Context.AtomicUsesUnsupportedLibcall(AE)) 5364 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5365 << ((Op == AtomicExpr::AO__c11_atomic_load || 5366 Op == AtomicExpr::AO__opencl_atomic_load) 5367 ? 0 5368 : 1); 5369 5370 if (ValType->isExtIntType()) { 5371 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5372 return ExprError(); 5373 } 5374 5375 return AE; 5376 } 5377 5378 /// checkBuiltinArgument - Given a call to a builtin function, perform 5379 /// normal type-checking on the given argument, updating the call in 5380 /// place. This is useful when a builtin function requires custom 5381 /// type-checking for some of its arguments but not necessarily all of 5382 /// them. 5383 /// 5384 /// Returns true on error. 5385 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5386 FunctionDecl *Fn = E->getDirectCallee(); 5387 assert(Fn && "builtin call without direct callee!"); 5388 5389 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5390 InitializedEntity Entity = 5391 InitializedEntity::InitializeParameter(S.Context, Param); 5392 5393 ExprResult Arg = E->getArg(0); 5394 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5395 if (Arg.isInvalid()) 5396 return true; 5397 5398 E->setArg(ArgIndex, Arg.get()); 5399 return false; 5400 } 5401 5402 /// We have a call to a function like __sync_fetch_and_add, which is an 5403 /// overloaded function based on the pointer type of its first argument. 5404 /// The main BuildCallExpr routines have already promoted the types of 5405 /// arguments because all of these calls are prototyped as void(...). 5406 /// 5407 /// This function goes through and does final semantic checking for these 5408 /// builtins, as well as generating any warnings. 5409 ExprResult 5410 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5411 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5412 Expr *Callee = TheCall->getCallee(); 5413 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5414 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5415 5416 // Ensure that we have at least one argument to do type inference from. 5417 if (TheCall->getNumArgs() < 1) { 5418 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5419 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5420 return ExprError(); 5421 } 5422 5423 // Inspect the first argument of the atomic builtin. This should always be 5424 // a pointer type, whose element is an integral scalar or pointer type. 5425 // Because it is a pointer type, we don't have to worry about any implicit 5426 // casts here. 5427 // FIXME: We don't allow floating point scalars as input. 5428 Expr *FirstArg = TheCall->getArg(0); 5429 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5430 if (FirstArgResult.isInvalid()) 5431 return ExprError(); 5432 FirstArg = FirstArgResult.get(); 5433 TheCall->setArg(0, FirstArg); 5434 5435 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5436 if (!pointerType) { 5437 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5438 << FirstArg->getType() << FirstArg->getSourceRange(); 5439 return ExprError(); 5440 } 5441 5442 QualType ValType = pointerType->getPointeeType(); 5443 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5444 !ValType->isBlockPointerType()) { 5445 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5446 << FirstArg->getType() << FirstArg->getSourceRange(); 5447 return ExprError(); 5448 } 5449 5450 if (ValType.isConstQualified()) { 5451 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5452 << FirstArg->getType() << FirstArg->getSourceRange(); 5453 return ExprError(); 5454 } 5455 5456 switch (ValType.getObjCLifetime()) { 5457 case Qualifiers::OCL_None: 5458 case Qualifiers::OCL_ExplicitNone: 5459 // okay 5460 break; 5461 5462 case Qualifiers::OCL_Weak: 5463 case Qualifiers::OCL_Strong: 5464 case Qualifiers::OCL_Autoreleasing: 5465 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5466 << ValType << FirstArg->getSourceRange(); 5467 return ExprError(); 5468 } 5469 5470 // Strip any qualifiers off ValType. 5471 ValType = ValType.getUnqualifiedType(); 5472 5473 // The majority of builtins return a value, but a few have special return 5474 // types, so allow them to override appropriately below. 5475 QualType ResultType = ValType; 5476 5477 // We need to figure out which concrete builtin this maps onto. For example, 5478 // __sync_fetch_and_add with a 2 byte object turns into 5479 // __sync_fetch_and_add_2. 5480 #define BUILTIN_ROW(x) \ 5481 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5482 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5483 5484 static const unsigned BuiltinIndices[][5] = { 5485 BUILTIN_ROW(__sync_fetch_and_add), 5486 BUILTIN_ROW(__sync_fetch_and_sub), 5487 BUILTIN_ROW(__sync_fetch_and_or), 5488 BUILTIN_ROW(__sync_fetch_and_and), 5489 BUILTIN_ROW(__sync_fetch_and_xor), 5490 BUILTIN_ROW(__sync_fetch_and_nand), 5491 5492 BUILTIN_ROW(__sync_add_and_fetch), 5493 BUILTIN_ROW(__sync_sub_and_fetch), 5494 BUILTIN_ROW(__sync_and_and_fetch), 5495 BUILTIN_ROW(__sync_or_and_fetch), 5496 BUILTIN_ROW(__sync_xor_and_fetch), 5497 BUILTIN_ROW(__sync_nand_and_fetch), 5498 5499 BUILTIN_ROW(__sync_val_compare_and_swap), 5500 BUILTIN_ROW(__sync_bool_compare_and_swap), 5501 BUILTIN_ROW(__sync_lock_test_and_set), 5502 BUILTIN_ROW(__sync_lock_release), 5503 BUILTIN_ROW(__sync_swap) 5504 }; 5505 #undef BUILTIN_ROW 5506 5507 // Determine the index of the size. 5508 unsigned SizeIndex; 5509 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5510 case 1: SizeIndex = 0; break; 5511 case 2: SizeIndex = 1; break; 5512 case 4: SizeIndex = 2; break; 5513 case 8: SizeIndex = 3; break; 5514 case 16: SizeIndex = 4; break; 5515 default: 5516 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5517 << FirstArg->getType() << FirstArg->getSourceRange(); 5518 return ExprError(); 5519 } 5520 5521 // Each of these builtins has one pointer argument, followed by some number of 5522 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5523 // that we ignore. Find out which row of BuiltinIndices to read from as well 5524 // as the number of fixed args. 5525 unsigned BuiltinID = FDecl->getBuiltinID(); 5526 unsigned BuiltinIndex, NumFixed = 1; 5527 bool WarnAboutSemanticsChange = false; 5528 switch (BuiltinID) { 5529 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5530 case Builtin::BI__sync_fetch_and_add: 5531 case Builtin::BI__sync_fetch_and_add_1: 5532 case Builtin::BI__sync_fetch_and_add_2: 5533 case Builtin::BI__sync_fetch_and_add_4: 5534 case Builtin::BI__sync_fetch_and_add_8: 5535 case Builtin::BI__sync_fetch_and_add_16: 5536 BuiltinIndex = 0; 5537 break; 5538 5539 case Builtin::BI__sync_fetch_and_sub: 5540 case Builtin::BI__sync_fetch_and_sub_1: 5541 case Builtin::BI__sync_fetch_and_sub_2: 5542 case Builtin::BI__sync_fetch_and_sub_4: 5543 case Builtin::BI__sync_fetch_and_sub_8: 5544 case Builtin::BI__sync_fetch_and_sub_16: 5545 BuiltinIndex = 1; 5546 break; 5547 5548 case Builtin::BI__sync_fetch_and_or: 5549 case Builtin::BI__sync_fetch_and_or_1: 5550 case Builtin::BI__sync_fetch_and_or_2: 5551 case Builtin::BI__sync_fetch_and_or_4: 5552 case Builtin::BI__sync_fetch_and_or_8: 5553 case Builtin::BI__sync_fetch_and_or_16: 5554 BuiltinIndex = 2; 5555 break; 5556 5557 case Builtin::BI__sync_fetch_and_and: 5558 case Builtin::BI__sync_fetch_and_and_1: 5559 case Builtin::BI__sync_fetch_and_and_2: 5560 case Builtin::BI__sync_fetch_and_and_4: 5561 case Builtin::BI__sync_fetch_and_and_8: 5562 case Builtin::BI__sync_fetch_and_and_16: 5563 BuiltinIndex = 3; 5564 break; 5565 5566 case Builtin::BI__sync_fetch_and_xor: 5567 case Builtin::BI__sync_fetch_and_xor_1: 5568 case Builtin::BI__sync_fetch_and_xor_2: 5569 case Builtin::BI__sync_fetch_and_xor_4: 5570 case Builtin::BI__sync_fetch_and_xor_8: 5571 case Builtin::BI__sync_fetch_and_xor_16: 5572 BuiltinIndex = 4; 5573 break; 5574 5575 case Builtin::BI__sync_fetch_and_nand: 5576 case Builtin::BI__sync_fetch_and_nand_1: 5577 case Builtin::BI__sync_fetch_and_nand_2: 5578 case Builtin::BI__sync_fetch_and_nand_4: 5579 case Builtin::BI__sync_fetch_and_nand_8: 5580 case Builtin::BI__sync_fetch_and_nand_16: 5581 BuiltinIndex = 5; 5582 WarnAboutSemanticsChange = true; 5583 break; 5584 5585 case Builtin::BI__sync_add_and_fetch: 5586 case Builtin::BI__sync_add_and_fetch_1: 5587 case Builtin::BI__sync_add_and_fetch_2: 5588 case Builtin::BI__sync_add_and_fetch_4: 5589 case Builtin::BI__sync_add_and_fetch_8: 5590 case Builtin::BI__sync_add_and_fetch_16: 5591 BuiltinIndex = 6; 5592 break; 5593 5594 case Builtin::BI__sync_sub_and_fetch: 5595 case Builtin::BI__sync_sub_and_fetch_1: 5596 case Builtin::BI__sync_sub_and_fetch_2: 5597 case Builtin::BI__sync_sub_and_fetch_4: 5598 case Builtin::BI__sync_sub_and_fetch_8: 5599 case Builtin::BI__sync_sub_and_fetch_16: 5600 BuiltinIndex = 7; 5601 break; 5602 5603 case Builtin::BI__sync_and_and_fetch: 5604 case Builtin::BI__sync_and_and_fetch_1: 5605 case Builtin::BI__sync_and_and_fetch_2: 5606 case Builtin::BI__sync_and_and_fetch_4: 5607 case Builtin::BI__sync_and_and_fetch_8: 5608 case Builtin::BI__sync_and_and_fetch_16: 5609 BuiltinIndex = 8; 5610 break; 5611 5612 case Builtin::BI__sync_or_and_fetch: 5613 case Builtin::BI__sync_or_and_fetch_1: 5614 case Builtin::BI__sync_or_and_fetch_2: 5615 case Builtin::BI__sync_or_and_fetch_4: 5616 case Builtin::BI__sync_or_and_fetch_8: 5617 case Builtin::BI__sync_or_and_fetch_16: 5618 BuiltinIndex = 9; 5619 break; 5620 5621 case Builtin::BI__sync_xor_and_fetch: 5622 case Builtin::BI__sync_xor_and_fetch_1: 5623 case Builtin::BI__sync_xor_and_fetch_2: 5624 case Builtin::BI__sync_xor_and_fetch_4: 5625 case Builtin::BI__sync_xor_and_fetch_8: 5626 case Builtin::BI__sync_xor_and_fetch_16: 5627 BuiltinIndex = 10; 5628 break; 5629 5630 case Builtin::BI__sync_nand_and_fetch: 5631 case Builtin::BI__sync_nand_and_fetch_1: 5632 case Builtin::BI__sync_nand_and_fetch_2: 5633 case Builtin::BI__sync_nand_and_fetch_4: 5634 case Builtin::BI__sync_nand_and_fetch_8: 5635 case Builtin::BI__sync_nand_and_fetch_16: 5636 BuiltinIndex = 11; 5637 WarnAboutSemanticsChange = true; 5638 break; 5639 5640 case Builtin::BI__sync_val_compare_and_swap: 5641 case Builtin::BI__sync_val_compare_and_swap_1: 5642 case Builtin::BI__sync_val_compare_and_swap_2: 5643 case Builtin::BI__sync_val_compare_and_swap_4: 5644 case Builtin::BI__sync_val_compare_and_swap_8: 5645 case Builtin::BI__sync_val_compare_and_swap_16: 5646 BuiltinIndex = 12; 5647 NumFixed = 2; 5648 break; 5649 5650 case Builtin::BI__sync_bool_compare_and_swap: 5651 case Builtin::BI__sync_bool_compare_and_swap_1: 5652 case Builtin::BI__sync_bool_compare_and_swap_2: 5653 case Builtin::BI__sync_bool_compare_and_swap_4: 5654 case Builtin::BI__sync_bool_compare_and_swap_8: 5655 case Builtin::BI__sync_bool_compare_and_swap_16: 5656 BuiltinIndex = 13; 5657 NumFixed = 2; 5658 ResultType = Context.BoolTy; 5659 break; 5660 5661 case Builtin::BI__sync_lock_test_and_set: 5662 case Builtin::BI__sync_lock_test_and_set_1: 5663 case Builtin::BI__sync_lock_test_and_set_2: 5664 case Builtin::BI__sync_lock_test_and_set_4: 5665 case Builtin::BI__sync_lock_test_and_set_8: 5666 case Builtin::BI__sync_lock_test_and_set_16: 5667 BuiltinIndex = 14; 5668 break; 5669 5670 case Builtin::BI__sync_lock_release: 5671 case Builtin::BI__sync_lock_release_1: 5672 case Builtin::BI__sync_lock_release_2: 5673 case Builtin::BI__sync_lock_release_4: 5674 case Builtin::BI__sync_lock_release_8: 5675 case Builtin::BI__sync_lock_release_16: 5676 BuiltinIndex = 15; 5677 NumFixed = 0; 5678 ResultType = Context.VoidTy; 5679 break; 5680 5681 case Builtin::BI__sync_swap: 5682 case Builtin::BI__sync_swap_1: 5683 case Builtin::BI__sync_swap_2: 5684 case Builtin::BI__sync_swap_4: 5685 case Builtin::BI__sync_swap_8: 5686 case Builtin::BI__sync_swap_16: 5687 BuiltinIndex = 16; 5688 break; 5689 } 5690 5691 // Now that we know how many fixed arguments we expect, first check that we 5692 // have at least that many. 5693 if (TheCall->getNumArgs() < 1+NumFixed) { 5694 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5695 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5696 << Callee->getSourceRange(); 5697 return ExprError(); 5698 } 5699 5700 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5701 << Callee->getSourceRange(); 5702 5703 if (WarnAboutSemanticsChange) { 5704 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5705 << Callee->getSourceRange(); 5706 } 5707 5708 // Get the decl for the concrete builtin from this, we can tell what the 5709 // concrete integer type we should convert to is. 5710 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5711 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5712 FunctionDecl *NewBuiltinDecl; 5713 if (NewBuiltinID == BuiltinID) 5714 NewBuiltinDecl = FDecl; 5715 else { 5716 // Perform builtin lookup to avoid redeclaring it. 5717 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5718 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5719 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5720 assert(Res.getFoundDecl()); 5721 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5722 if (!NewBuiltinDecl) 5723 return ExprError(); 5724 } 5725 5726 // The first argument --- the pointer --- has a fixed type; we 5727 // deduce the types of the rest of the arguments accordingly. Walk 5728 // the remaining arguments, converting them to the deduced value type. 5729 for (unsigned i = 0; i != NumFixed; ++i) { 5730 ExprResult Arg = TheCall->getArg(i+1); 5731 5732 // GCC does an implicit conversion to the pointer or integer ValType. This 5733 // can fail in some cases (1i -> int**), check for this error case now. 5734 // Initialize the argument. 5735 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5736 ValType, /*consume*/ false); 5737 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5738 if (Arg.isInvalid()) 5739 return ExprError(); 5740 5741 // Okay, we have something that *can* be converted to the right type. Check 5742 // to see if there is a potentially weird extension going on here. This can 5743 // happen when you do an atomic operation on something like an char* and 5744 // pass in 42. The 42 gets converted to char. This is even more strange 5745 // for things like 45.123 -> char, etc. 5746 // FIXME: Do this check. 5747 TheCall->setArg(i+1, Arg.get()); 5748 } 5749 5750 // Create a new DeclRefExpr to refer to the new decl. 5751 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5752 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5753 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5754 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5755 5756 // Set the callee in the CallExpr. 5757 // FIXME: This loses syntactic information. 5758 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5759 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5760 CK_BuiltinFnToFnPtr); 5761 TheCall->setCallee(PromotedCall.get()); 5762 5763 // Change the result type of the call to match the original value type. This 5764 // is arbitrary, but the codegen for these builtins ins design to handle it 5765 // gracefully. 5766 TheCall->setType(ResultType); 5767 5768 // Prohibit use of _ExtInt with atomic builtins. 5769 // The arguments would have already been converted to the first argument's 5770 // type, so only need to check the first argument. 5771 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5772 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5773 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5774 return ExprError(); 5775 } 5776 5777 return TheCallResult; 5778 } 5779 5780 /// SemaBuiltinNontemporalOverloaded - We have a call to 5781 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5782 /// overloaded function based on the pointer type of its last argument. 5783 /// 5784 /// This function goes through and does final semantic checking for these 5785 /// builtins. 5786 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5787 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5788 DeclRefExpr *DRE = 5789 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5790 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5791 unsigned BuiltinID = FDecl->getBuiltinID(); 5792 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5793 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5794 "Unexpected nontemporal load/store builtin!"); 5795 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5796 unsigned numArgs = isStore ? 2 : 1; 5797 5798 // Ensure that we have the proper number of arguments. 5799 if (checkArgCount(*this, TheCall, numArgs)) 5800 return ExprError(); 5801 5802 // Inspect the last argument of the nontemporal builtin. This should always 5803 // be a pointer type, from which we imply the type of the memory access. 5804 // Because it is a pointer type, we don't have to worry about any implicit 5805 // casts here. 5806 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5807 ExprResult PointerArgResult = 5808 DefaultFunctionArrayLvalueConversion(PointerArg); 5809 5810 if (PointerArgResult.isInvalid()) 5811 return ExprError(); 5812 PointerArg = PointerArgResult.get(); 5813 TheCall->setArg(numArgs - 1, PointerArg); 5814 5815 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5816 if (!pointerType) { 5817 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5818 << PointerArg->getType() << PointerArg->getSourceRange(); 5819 return ExprError(); 5820 } 5821 5822 QualType ValType = pointerType->getPointeeType(); 5823 5824 // Strip any qualifiers off ValType. 5825 ValType = ValType.getUnqualifiedType(); 5826 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5827 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5828 !ValType->isVectorType()) { 5829 Diag(DRE->getBeginLoc(), 5830 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5831 << PointerArg->getType() << PointerArg->getSourceRange(); 5832 return ExprError(); 5833 } 5834 5835 if (!isStore) { 5836 TheCall->setType(ValType); 5837 return TheCallResult; 5838 } 5839 5840 ExprResult ValArg = TheCall->getArg(0); 5841 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5842 Context, ValType, /*consume*/ false); 5843 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5844 if (ValArg.isInvalid()) 5845 return ExprError(); 5846 5847 TheCall->setArg(0, ValArg.get()); 5848 TheCall->setType(Context.VoidTy); 5849 return TheCallResult; 5850 } 5851 5852 /// CheckObjCString - Checks that the argument to the builtin 5853 /// CFString constructor is correct 5854 /// Note: It might also make sense to do the UTF-16 conversion here (would 5855 /// simplify the backend). 5856 bool Sema::CheckObjCString(Expr *Arg) { 5857 Arg = Arg->IgnoreParenCasts(); 5858 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5859 5860 if (!Literal || !Literal->isAscii()) { 5861 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5862 << Arg->getSourceRange(); 5863 return true; 5864 } 5865 5866 if (Literal->containsNonAsciiOrNull()) { 5867 StringRef String = Literal->getString(); 5868 unsigned NumBytes = String.size(); 5869 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5870 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5871 llvm::UTF16 *ToPtr = &ToBuf[0]; 5872 5873 llvm::ConversionResult Result = 5874 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5875 ToPtr + NumBytes, llvm::strictConversion); 5876 // Check for conversion failure. 5877 if (Result != llvm::conversionOK) 5878 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5879 << Arg->getSourceRange(); 5880 } 5881 return false; 5882 } 5883 5884 /// CheckObjCString - Checks that the format string argument to the os_log() 5885 /// and os_trace() functions is correct, and converts it to const char *. 5886 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5887 Arg = Arg->IgnoreParenCasts(); 5888 auto *Literal = dyn_cast<StringLiteral>(Arg); 5889 if (!Literal) { 5890 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5891 Literal = ObjcLiteral->getString(); 5892 } 5893 } 5894 5895 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5896 return ExprError( 5897 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5898 << Arg->getSourceRange()); 5899 } 5900 5901 ExprResult Result(Literal); 5902 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5903 InitializedEntity Entity = 5904 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5905 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5906 return Result; 5907 } 5908 5909 /// Check that the user is calling the appropriate va_start builtin for the 5910 /// target and calling convention. 5911 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5912 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5913 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5914 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5915 TT.getArch() == llvm::Triple::aarch64_32); 5916 bool IsWindows = TT.isOSWindows(); 5917 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5918 if (IsX64 || IsAArch64) { 5919 CallingConv CC = CC_C; 5920 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5921 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5922 if (IsMSVAStart) { 5923 // Don't allow this in System V ABI functions. 5924 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5925 return S.Diag(Fn->getBeginLoc(), 5926 diag::err_ms_va_start_used_in_sysv_function); 5927 } else { 5928 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5929 // On x64 Windows, don't allow this in System V ABI functions. 5930 // (Yes, that means there's no corresponding way to support variadic 5931 // System V ABI functions on Windows.) 5932 if ((IsWindows && CC == CC_X86_64SysV) || 5933 (!IsWindows && CC == CC_Win64)) 5934 return S.Diag(Fn->getBeginLoc(), 5935 diag::err_va_start_used_in_wrong_abi_function) 5936 << !IsWindows; 5937 } 5938 return false; 5939 } 5940 5941 if (IsMSVAStart) 5942 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5943 return false; 5944 } 5945 5946 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5947 ParmVarDecl **LastParam = nullptr) { 5948 // Determine whether the current function, block, or obj-c method is variadic 5949 // and get its parameter list. 5950 bool IsVariadic = false; 5951 ArrayRef<ParmVarDecl *> Params; 5952 DeclContext *Caller = S.CurContext; 5953 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5954 IsVariadic = Block->isVariadic(); 5955 Params = Block->parameters(); 5956 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5957 IsVariadic = FD->isVariadic(); 5958 Params = FD->parameters(); 5959 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5960 IsVariadic = MD->isVariadic(); 5961 // FIXME: This isn't correct for methods (results in bogus warning). 5962 Params = MD->parameters(); 5963 } else if (isa<CapturedDecl>(Caller)) { 5964 // We don't support va_start in a CapturedDecl. 5965 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5966 return true; 5967 } else { 5968 // This must be some other declcontext that parses exprs. 5969 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5970 return true; 5971 } 5972 5973 if (!IsVariadic) { 5974 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5975 return true; 5976 } 5977 5978 if (LastParam) 5979 *LastParam = Params.empty() ? nullptr : Params.back(); 5980 5981 return false; 5982 } 5983 5984 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5985 /// for validity. Emit an error and return true on failure; return false 5986 /// on success. 5987 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5988 Expr *Fn = TheCall->getCallee(); 5989 5990 if (checkVAStartABI(*this, BuiltinID, Fn)) 5991 return true; 5992 5993 if (checkArgCount(*this, TheCall, 2)) 5994 return true; 5995 5996 // Type-check the first argument normally. 5997 if (checkBuiltinArgument(*this, TheCall, 0)) 5998 return true; 5999 6000 // Check that the current function is variadic, and get its last parameter. 6001 ParmVarDecl *LastParam; 6002 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6003 return true; 6004 6005 // Verify that the second argument to the builtin is the last argument of the 6006 // current function or method. 6007 bool SecondArgIsLastNamedArgument = false; 6008 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6009 6010 // These are valid if SecondArgIsLastNamedArgument is false after the next 6011 // block. 6012 QualType Type; 6013 SourceLocation ParamLoc; 6014 bool IsCRegister = false; 6015 6016 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6017 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6018 SecondArgIsLastNamedArgument = PV == LastParam; 6019 6020 Type = PV->getType(); 6021 ParamLoc = PV->getLocation(); 6022 IsCRegister = 6023 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6024 } 6025 } 6026 6027 if (!SecondArgIsLastNamedArgument) 6028 Diag(TheCall->getArg(1)->getBeginLoc(), 6029 diag::warn_second_arg_of_va_start_not_last_named_param); 6030 else if (IsCRegister || Type->isReferenceType() || 6031 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6032 // Promotable integers are UB, but enumerations need a bit of 6033 // extra checking to see what their promotable type actually is. 6034 if (!Type->isPromotableIntegerType()) 6035 return false; 6036 if (!Type->isEnumeralType()) 6037 return true; 6038 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6039 return !(ED && 6040 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6041 }()) { 6042 unsigned Reason = 0; 6043 if (Type->isReferenceType()) Reason = 1; 6044 else if (IsCRegister) Reason = 2; 6045 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6046 Diag(ParamLoc, diag::note_parameter_type) << Type; 6047 } 6048 6049 TheCall->setType(Context.VoidTy); 6050 return false; 6051 } 6052 6053 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6054 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6055 // const char *named_addr); 6056 6057 Expr *Func = Call->getCallee(); 6058 6059 if (Call->getNumArgs() < 3) 6060 return Diag(Call->getEndLoc(), 6061 diag::err_typecheck_call_too_few_args_at_least) 6062 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6063 6064 // Type-check the first argument normally. 6065 if (checkBuiltinArgument(*this, Call, 0)) 6066 return true; 6067 6068 // Check that the current function is variadic. 6069 if (checkVAStartIsInVariadicFunction(*this, Func)) 6070 return true; 6071 6072 // __va_start on Windows does not validate the parameter qualifiers 6073 6074 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6075 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6076 6077 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6078 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6079 6080 const QualType &ConstCharPtrTy = 6081 Context.getPointerType(Context.CharTy.withConst()); 6082 if (!Arg1Ty->isPointerType() || 6083 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 6084 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6085 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6086 << 0 /* qualifier difference */ 6087 << 3 /* parameter mismatch */ 6088 << 2 << Arg1->getType() << ConstCharPtrTy; 6089 6090 const QualType SizeTy = Context.getSizeType(); 6091 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6092 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6093 << Arg2->getType() << SizeTy << 1 /* different class */ 6094 << 0 /* qualifier difference */ 6095 << 3 /* parameter mismatch */ 6096 << 3 << Arg2->getType() << SizeTy; 6097 6098 return false; 6099 } 6100 6101 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6102 /// friends. This is declared to take (...), so we have to check everything. 6103 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6104 if (checkArgCount(*this, TheCall, 2)) 6105 return true; 6106 6107 ExprResult OrigArg0 = TheCall->getArg(0); 6108 ExprResult OrigArg1 = TheCall->getArg(1); 6109 6110 // Do standard promotions between the two arguments, returning their common 6111 // type. 6112 QualType Res = UsualArithmeticConversions( 6113 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6114 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6115 return true; 6116 6117 // Make sure any conversions are pushed back into the call; this is 6118 // type safe since unordered compare builtins are declared as "_Bool 6119 // foo(...)". 6120 TheCall->setArg(0, OrigArg0.get()); 6121 TheCall->setArg(1, OrigArg1.get()); 6122 6123 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6124 return false; 6125 6126 // If the common type isn't a real floating type, then the arguments were 6127 // invalid for this operation. 6128 if (Res.isNull() || !Res->isRealFloatingType()) 6129 return Diag(OrigArg0.get()->getBeginLoc(), 6130 diag::err_typecheck_call_invalid_ordered_compare) 6131 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6132 << SourceRange(OrigArg0.get()->getBeginLoc(), 6133 OrigArg1.get()->getEndLoc()); 6134 6135 return false; 6136 } 6137 6138 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6139 /// __builtin_isnan and friends. This is declared to take (...), so we have 6140 /// to check everything. We expect the last argument to be a floating point 6141 /// value. 6142 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6143 if (checkArgCount(*this, TheCall, NumArgs)) 6144 return true; 6145 6146 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6147 // on all preceding parameters just being int. Try all of those. 6148 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6149 Expr *Arg = TheCall->getArg(i); 6150 6151 if (Arg->isTypeDependent()) 6152 return false; 6153 6154 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6155 6156 if (Res.isInvalid()) 6157 return true; 6158 TheCall->setArg(i, Res.get()); 6159 } 6160 6161 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6162 6163 if (OrigArg->isTypeDependent()) 6164 return false; 6165 6166 // Usual Unary Conversions will convert half to float, which we want for 6167 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6168 // type how it is, but do normal L->Rvalue conversions. 6169 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6170 OrigArg = UsualUnaryConversions(OrigArg).get(); 6171 else 6172 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6173 TheCall->setArg(NumArgs - 1, OrigArg); 6174 6175 // This operation requires a non-_Complex floating-point number. 6176 if (!OrigArg->getType()->isRealFloatingType()) 6177 return Diag(OrigArg->getBeginLoc(), 6178 diag::err_typecheck_call_invalid_unary_fp) 6179 << OrigArg->getType() << OrigArg->getSourceRange(); 6180 6181 return false; 6182 } 6183 6184 /// Perform semantic analysis for a call to __builtin_complex. 6185 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6186 if (checkArgCount(*this, TheCall, 2)) 6187 return true; 6188 6189 bool Dependent = false; 6190 for (unsigned I = 0; I != 2; ++I) { 6191 Expr *Arg = TheCall->getArg(I); 6192 QualType T = Arg->getType(); 6193 if (T->isDependentType()) { 6194 Dependent = true; 6195 continue; 6196 } 6197 6198 // Despite supporting _Complex int, GCC requires a real floating point type 6199 // for the operands of __builtin_complex. 6200 if (!T->isRealFloatingType()) { 6201 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6202 << Arg->getType() << Arg->getSourceRange(); 6203 } 6204 6205 ExprResult Converted = DefaultLvalueConversion(Arg); 6206 if (Converted.isInvalid()) 6207 return true; 6208 TheCall->setArg(I, Converted.get()); 6209 } 6210 6211 if (Dependent) { 6212 TheCall->setType(Context.DependentTy); 6213 return false; 6214 } 6215 6216 Expr *Real = TheCall->getArg(0); 6217 Expr *Imag = TheCall->getArg(1); 6218 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6219 return Diag(Real->getBeginLoc(), 6220 diag::err_typecheck_call_different_arg_types) 6221 << Real->getType() << Imag->getType() 6222 << Real->getSourceRange() << Imag->getSourceRange(); 6223 } 6224 6225 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6226 // don't allow this builtin to form those types either. 6227 // FIXME: Should we allow these types? 6228 if (Real->getType()->isFloat16Type()) 6229 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6230 << "_Float16"; 6231 if (Real->getType()->isHalfType()) 6232 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6233 << "half"; 6234 6235 TheCall->setType(Context.getComplexType(Real->getType())); 6236 return false; 6237 } 6238 6239 // Customized Sema Checking for VSX builtins that have the following signature: 6240 // vector [...] builtinName(vector [...], vector [...], const int); 6241 // Which takes the same type of vectors (any legal vector type) for the first 6242 // two arguments and takes compile time constant for the third argument. 6243 // Example builtins are : 6244 // vector double vec_xxpermdi(vector double, vector double, int); 6245 // vector short vec_xxsldwi(vector short, vector short, int); 6246 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6247 unsigned ExpectedNumArgs = 3; 6248 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6249 return true; 6250 6251 // Check the third argument is a compile time constant 6252 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6253 return Diag(TheCall->getBeginLoc(), 6254 diag::err_vsx_builtin_nonconstant_argument) 6255 << 3 /* argument index */ << TheCall->getDirectCallee() 6256 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6257 TheCall->getArg(2)->getEndLoc()); 6258 6259 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6260 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6261 6262 // Check the type of argument 1 and argument 2 are vectors. 6263 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6264 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6265 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6266 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6267 << TheCall->getDirectCallee() 6268 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6269 TheCall->getArg(1)->getEndLoc()); 6270 } 6271 6272 // Check the first two arguments are the same type. 6273 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6274 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6275 << TheCall->getDirectCallee() 6276 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6277 TheCall->getArg(1)->getEndLoc()); 6278 } 6279 6280 // When default clang type checking is turned off and the customized type 6281 // checking is used, the returning type of the function must be explicitly 6282 // set. Otherwise it is _Bool by default. 6283 TheCall->setType(Arg1Ty); 6284 6285 return false; 6286 } 6287 6288 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6289 // This is declared to take (...), so we have to check everything. 6290 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6291 if (TheCall->getNumArgs() < 2) 6292 return ExprError(Diag(TheCall->getEndLoc(), 6293 diag::err_typecheck_call_too_few_args_at_least) 6294 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6295 << TheCall->getSourceRange()); 6296 6297 // Determine which of the following types of shufflevector we're checking: 6298 // 1) unary, vector mask: (lhs, mask) 6299 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6300 QualType resType = TheCall->getArg(0)->getType(); 6301 unsigned numElements = 0; 6302 6303 if (!TheCall->getArg(0)->isTypeDependent() && 6304 !TheCall->getArg(1)->isTypeDependent()) { 6305 QualType LHSType = TheCall->getArg(0)->getType(); 6306 QualType RHSType = TheCall->getArg(1)->getType(); 6307 6308 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6309 return ExprError( 6310 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6311 << TheCall->getDirectCallee() 6312 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6313 TheCall->getArg(1)->getEndLoc())); 6314 6315 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6316 unsigned numResElements = TheCall->getNumArgs() - 2; 6317 6318 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6319 // with mask. If so, verify that RHS is an integer vector type with the 6320 // same number of elts as lhs. 6321 if (TheCall->getNumArgs() == 2) { 6322 if (!RHSType->hasIntegerRepresentation() || 6323 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6324 return ExprError(Diag(TheCall->getBeginLoc(), 6325 diag::err_vec_builtin_incompatible_vector) 6326 << TheCall->getDirectCallee() 6327 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6328 TheCall->getArg(1)->getEndLoc())); 6329 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6330 return ExprError(Diag(TheCall->getBeginLoc(), 6331 diag::err_vec_builtin_incompatible_vector) 6332 << TheCall->getDirectCallee() 6333 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6334 TheCall->getArg(1)->getEndLoc())); 6335 } else if (numElements != numResElements) { 6336 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6337 resType = Context.getVectorType(eltType, numResElements, 6338 VectorType::GenericVector); 6339 } 6340 } 6341 6342 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6343 if (TheCall->getArg(i)->isTypeDependent() || 6344 TheCall->getArg(i)->isValueDependent()) 6345 continue; 6346 6347 Optional<llvm::APSInt> Result; 6348 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6349 return ExprError(Diag(TheCall->getBeginLoc(), 6350 diag::err_shufflevector_nonconstant_argument) 6351 << TheCall->getArg(i)->getSourceRange()); 6352 6353 // Allow -1 which will be translated to undef in the IR. 6354 if (Result->isSigned() && Result->isAllOnesValue()) 6355 continue; 6356 6357 if (Result->getActiveBits() > 64 || 6358 Result->getZExtValue() >= numElements * 2) 6359 return ExprError(Diag(TheCall->getBeginLoc(), 6360 diag::err_shufflevector_argument_too_large) 6361 << TheCall->getArg(i)->getSourceRange()); 6362 } 6363 6364 SmallVector<Expr*, 32> exprs; 6365 6366 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6367 exprs.push_back(TheCall->getArg(i)); 6368 TheCall->setArg(i, nullptr); 6369 } 6370 6371 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6372 TheCall->getCallee()->getBeginLoc(), 6373 TheCall->getRParenLoc()); 6374 } 6375 6376 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6377 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6378 SourceLocation BuiltinLoc, 6379 SourceLocation RParenLoc) { 6380 ExprValueKind VK = VK_PRValue; 6381 ExprObjectKind OK = OK_Ordinary; 6382 QualType DstTy = TInfo->getType(); 6383 QualType SrcTy = E->getType(); 6384 6385 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6386 return ExprError(Diag(BuiltinLoc, 6387 diag::err_convertvector_non_vector) 6388 << E->getSourceRange()); 6389 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6390 return ExprError(Diag(BuiltinLoc, 6391 diag::err_convertvector_non_vector_type)); 6392 6393 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6394 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6395 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6396 if (SrcElts != DstElts) 6397 return ExprError(Diag(BuiltinLoc, 6398 diag::err_convertvector_incompatible_vector) 6399 << E->getSourceRange()); 6400 } 6401 6402 return new (Context) 6403 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6404 } 6405 6406 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6407 // This is declared to take (const void*, ...) and can take two 6408 // optional constant int args. 6409 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6410 unsigned NumArgs = TheCall->getNumArgs(); 6411 6412 if (NumArgs > 3) 6413 return Diag(TheCall->getEndLoc(), 6414 diag::err_typecheck_call_too_many_args_at_most) 6415 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6416 6417 // Argument 0 is checked for us and the remaining arguments must be 6418 // constant integers. 6419 for (unsigned i = 1; i != NumArgs; ++i) 6420 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6421 return true; 6422 6423 return false; 6424 } 6425 6426 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6427 // __assume does not evaluate its arguments, and should warn if its argument 6428 // has side effects. 6429 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6430 Expr *Arg = TheCall->getArg(0); 6431 if (Arg->isInstantiationDependent()) return false; 6432 6433 if (Arg->HasSideEffects(Context)) 6434 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6435 << Arg->getSourceRange() 6436 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6437 6438 return false; 6439 } 6440 6441 /// Handle __builtin_alloca_with_align. This is declared 6442 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6443 /// than 8. 6444 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6445 // The alignment must be a constant integer. 6446 Expr *Arg = TheCall->getArg(1); 6447 6448 // We can't check the value of a dependent argument. 6449 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6450 if (const auto *UE = 6451 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6452 if (UE->getKind() == UETT_AlignOf || 6453 UE->getKind() == UETT_PreferredAlignOf) 6454 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6455 << Arg->getSourceRange(); 6456 6457 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6458 6459 if (!Result.isPowerOf2()) 6460 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6461 << Arg->getSourceRange(); 6462 6463 if (Result < Context.getCharWidth()) 6464 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6465 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6466 6467 if (Result > std::numeric_limits<int32_t>::max()) 6468 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6469 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6470 } 6471 6472 return false; 6473 } 6474 6475 /// Handle __builtin_assume_aligned. This is declared 6476 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6477 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6478 unsigned NumArgs = TheCall->getNumArgs(); 6479 6480 if (NumArgs > 3) 6481 return Diag(TheCall->getEndLoc(), 6482 diag::err_typecheck_call_too_many_args_at_most) 6483 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6484 6485 // The alignment must be a constant integer. 6486 Expr *Arg = TheCall->getArg(1); 6487 6488 // We can't check the value of a dependent argument. 6489 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6490 llvm::APSInt Result; 6491 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6492 return true; 6493 6494 if (!Result.isPowerOf2()) 6495 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6496 << Arg->getSourceRange(); 6497 6498 if (Result > Sema::MaximumAlignment) 6499 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6500 << Arg->getSourceRange() << Sema::MaximumAlignment; 6501 } 6502 6503 if (NumArgs > 2) { 6504 ExprResult Arg(TheCall->getArg(2)); 6505 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6506 Context.getSizeType(), false); 6507 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6508 if (Arg.isInvalid()) return true; 6509 TheCall->setArg(2, Arg.get()); 6510 } 6511 6512 return false; 6513 } 6514 6515 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6516 unsigned BuiltinID = 6517 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6518 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6519 6520 unsigned NumArgs = TheCall->getNumArgs(); 6521 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6522 if (NumArgs < NumRequiredArgs) { 6523 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6524 << 0 /* function call */ << NumRequiredArgs << NumArgs 6525 << TheCall->getSourceRange(); 6526 } 6527 if (NumArgs >= NumRequiredArgs + 0x100) { 6528 return Diag(TheCall->getEndLoc(), 6529 diag::err_typecheck_call_too_many_args_at_most) 6530 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6531 << TheCall->getSourceRange(); 6532 } 6533 unsigned i = 0; 6534 6535 // For formatting call, check buffer arg. 6536 if (!IsSizeCall) { 6537 ExprResult Arg(TheCall->getArg(i)); 6538 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6539 Context, Context.VoidPtrTy, false); 6540 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6541 if (Arg.isInvalid()) 6542 return true; 6543 TheCall->setArg(i, Arg.get()); 6544 i++; 6545 } 6546 6547 // Check string literal arg. 6548 unsigned FormatIdx = i; 6549 { 6550 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6551 if (Arg.isInvalid()) 6552 return true; 6553 TheCall->setArg(i, Arg.get()); 6554 i++; 6555 } 6556 6557 // Make sure variadic args are scalar. 6558 unsigned FirstDataArg = i; 6559 while (i < NumArgs) { 6560 ExprResult Arg = DefaultVariadicArgumentPromotion( 6561 TheCall->getArg(i), VariadicFunction, nullptr); 6562 if (Arg.isInvalid()) 6563 return true; 6564 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6565 if (ArgSize.getQuantity() >= 0x100) { 6566 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6567 << i << (int)ArgSize.getQuantity() << 0xff 6568 << TheCall->getSourceRange(); 6569 } 6570 TheCall->setArg(i, Arg.get()); 6571 i++; 6572 } 6573 6574 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6575 // call to avoid duplicate diagnostics. 6576 if (!IsSizeCall) { 6577 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6578 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6579 bool Success = CheckFormatArguments( 6580 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6581 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6582 CheckedVarArgs); 6583 if (!Success) 6584 return true; 6585 } 6586 6587 if (IsSizeCall) { 6588 TheCall->setType(Context.getSizeType()); 6589 } else { 6590 TheCall->setType(Context.VoidPtrTy); 6591 } 6592 return false; 6593 } 6594 6595 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6596 /// TheCall is a constant expression. 6597 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6598 llvm::APSInt &Result) { 6599 Expr *Arg = TheCall->getArg(ArgNum); 6600 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6601 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6602 6603 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6604 6605 Optional<llvm::APSInt> R; 6606 if (!(R = Arg->getIntegerConstantExpr(Context))) 6607 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6608 << FDecl->getDeclName() << Arg->getSourceRange(); 6609 Result = *R; 6610 return false; 6611 } 6612 6613 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6614 /// TheCall is a constant expression in the range [Low, High]. 6615 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6616 int Low, int High, bool RangeIsError) { 6617 if (isConstantEvaluated()) 6618 return false; 6619 llvm::APSInt Result; 6620 6621 // We can't check the value of a dependent argument. 6622 Expr *Arg = TheCall->getArg(ArgNum); 6623 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6624 return false; 6625 6626 // Check constant-ness first. 6627 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6628 return true; 6629 6630 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6631 if (RangeIsError) 6632 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6633 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 6634 else 6635 // Defer the warning until we know if the code will be emitted so that 6636 // dead code can ignore this. 6637 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6638 PDiag(diag::warn_argument_invalid_range) 6639 << toString(Result, 10) << Low << High 6640 << Arg->getSourceRange()); 6641 } 6642 6643 return false; 6644 } 6645 6646 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6647 /// TheCall is a constant expression is a multiple of Num.. 6648 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6649 unsigned Num) { 6650 llvm::APSInt Result; 6651 6652 // We can't check the value of a dependent argument. 6653 Expr *Arg = TheCall->getArg(ArgNum); 6654 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6655 return false; 6656 6657 // Check constant-ness first. 6658 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6659 return true; 6660 6661 if (Result.getSExtValue() % Num != 0) 6662 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6663 << Num << Arg->getSourceRange(); 6664 6665 return false; 6666 } 6667 6668 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6669 /// constant expression representing a power of 2. 6670 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6671 llvm::APSInt Result; 6672 6673 // We can't check the value of a dependent argument. 6674 Expr *Arg = TheCall->getArg(ArgNum); 6675 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6676 return false; 6677 6678 // Check constant-ness first. 6679 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6680 return true; 6681 6682 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6683 // and only if x is a power of 2. 6684 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6685 return false; 6686 6687 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6688 << Arg->getSourceRange(); 6689 } 6690 6691 static bool IsShiftedByte(llvm::APSInt Value) { 6692 if (Value.isNegative()) 6693 return false; 6694 6695 // Check if it's a shifted byte, by shifting it down 6696 while (true) { 6697 // If the value fits in the bottom byte, the check passes. 6698 if (Value < 0x100) 6699 return true; 6700 6701 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6702 // fails. 6703 if ((Value & 0xFF) != 0) 6704 return false; 6705 6706 // If the bottom 8 bits are all 0, but something above that is nonzero, 6707 // then shifting the value right by 8 bits won't affect whether it's a 6708 // shifted byte or not. So do that, and go round again. 6709 Value >>= 8; 6710 } 6711 } 6712 6713 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6714 /// a constant expression representing an arbitrary byte value shifted left by 6715 /// a multiple of 8 bits. 6716 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6717 unsigned ArgBits) { 6718 llvm::APSInt Result; 6719 6720 // We can't check the value of a dependent argument. 6721 Expr *Arg = TheCall->getArg(ArgNum); 6722 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6723 return false; 6724 6725 // Check constant-ness first. 6726 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6727 return true; 6728 6729 // Truncate to the given size. 6730 Result = Result.getLoBits(ArgBits); 6731 Result.setIsUnsigned(true); 6732 6733 if (IsShiftedByte(Result)) 6734 return false; 6735 6736 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6737 << Arg->getSourceRange(); 6738 } 6739 6740 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6741 /// TheCall is a constant expression representing either a shifted byte value, 6742 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6743 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6744 /// Arm MVE intrinsics. 6745 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6746 int ArgNum, 6747 unsigned ArgBits) { 6748 llvm::APSInt Result; 6749 6750 // We can't check the value of a dependent argument. 6751 Expr *Arg = TheCall->getArg(ArgNum); 6752 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6753 return false; 6754 6755 // Check constant-ness first. 6756 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6757 return true; 6758 6759 // Truncate to the given size. 6760 Result = Result.getLoBits(ArgBits); 6761 Result.setIsUnsigned(true); 6762 6763 // Check to see if it's in either of the required forms. 6764 if (IsShiftedByte(Result) || 6765 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6766 return false; 6767 6768 return Diag(TheCall->getBeginLoc(), 6769 diag::err_argument_not_shifted_byte_or_xxff) 6770 << Arg->getSourceRange(); 6771 } 6772 6773 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6774 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6775 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6776 if (checkArgCount(*this, TheCall, 2)) 6777 return true; 6778 Expr *Arg0 = TheCall->getArg(0); 6779 Expr *Arg1 = TheCall->getArg(1); 6780 6781 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6782 if (FirstArg.isInvalid()) 6783 return true; 6784 QualType FirstArgType = FirstArg.get()->getType(); 6785 if (!FirstArgType->isAnyPointerType()) 6786 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6787 << "first" << FirstArgType << Arg0->getSourceRange(); 6788 TheCall->setArg(0, FirstArg.get()); 6789 6790 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6791 if (SecArg.isInvalid()) 6792 return true; 6793 QualType SecArgType = SecArg.get()->getType(); 6794 if (!SecArgType->isIntegerType()) 6795 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6796 << "second" << SecArgType << Arg1->getSourceRange(); 6797 6798 // Derive the return type from the pointer argument. 6799 TheCall->setType(FirstArgType); 6800 return false; 6801 } 6802 6803 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6804 if (checkArgCount(*this, TheCall, 2)) 6805 return true; 6806 6807 Expr *Arg0 = TheCall->getArg(0); 6808 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6809 if (FirstArg.isInvalid()) 6810 return true; 6811 QualType FirstArgType = FirstArg.get()->getType(); 6812 if (!FirstArgType->isAnyPointerType()) 6813 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6814 << "first" << FirstArgType << Arg0->getSourceRange(); 6815 TheCall->setArg(0, FirstArg.get()); 6816 6817 // Derive the return type from the pointer argument. 6818 TheCall->setType(FirstArgType); 6819 6820 // Second arg must be an constant in range [0,15] 6821 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6822 } 6823 6824 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6825 if (checkArgCount(*this, TheCall, 2)) 6826 return true; 6827 Expr *Arg0 = TheCall->getArg(0); 6828 Expr *Arg1 = TheCall->getArg(1); 6829 6830 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6831 if (FirstArg.isInvalid()) 6832 return true; 6833 QualType FirstArgType = FirstArg.get()->getType(); 6834 if (!FirstArgType->isAnyPointerType()) 6835 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6836 << "first" << FirstArgType << Arg0->getSourceRange(); 6837 6838 QualType SecArgType = Arg1->getType(); 6839 if (!SecArgType->isIntegerType()) 6840 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6841 << "second" << SecArgType << Arg1->getSourceRange(); 6842 TheCall->setType(Context.IntTy); 6843 return false; 6844 } 6845 6846 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6847 BuiltinID == AArch64::BI__builtin_arm_stg) { 6848 if (checkArgCount(*this, TheCall, 1)) 6849 return true; 6850 Expr *Arg0 = TheCall->getArg(0); 6851 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6852 if (FirstArg.isInvalid()) 6853 return true; 6854 6855 QualType FirstArgType = FirstArg.get()->getType(); 6856 if (!FirstArgType->isAnyPointerType()) 6857 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6858 << "first" << FirstArgType << Arg0->getSourceRange(); 6859 TheCall->setArg(0, FirstArg.get()); 6860 6861 // Derive the return type from the pointer argument. 6862 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6863 TheCall->setType(FirstArgType); 6864 return false; 6865 } 6866 6867 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6868 Expr *ArgA = TheCall->getArg(0); 6869 Expr *ArgB = TheCall->getArg(1); 6870 6871 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6872 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6873 6874 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6875 return true; 6876 6877 QualType ArgTypeA = ArgExprA.get()->getType(); 6878 QualType ArgTypeB = ArgExprB.get()->getType(); 6879 6880 auto isNull = [&] (Expr *E) -> bool { 6881 return E->isNullPointerConstant( 6882 Context, Expr::NPC_ValueDependentIsNotNull); }; 6883 6884 // argument should be either a pointer or null 6885 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6886 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6887 << "first" << ArgTypeA << ArgA->getSourceRange(); 6888 6889 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6890 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6891 << "second" << ArgTypeB << ArgB->getSourceRange(); 6892 6893 // Ensure Pointee types are compatible 6894 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6895 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6896 QualType pointeeA = ArgTypeA->getPointeeType(); 6897 QualType pointeeB = ArgTypeB->getPointeeType(); 6898 if (!Context.typesAreCompatible( 6899 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6900 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6901 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6902 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6903 << ArgB->getSourceRange(); 6904 } 6905 } 6906 6907 // at least one argument should be pointer type 6908 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6909 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6910 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6911 6912 if (isNull(ArgA)) // adopt type of the other pointer 6913 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6914 6915 if (isNull(ArgB)) 6916 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6917 6918 TheCall->setArg(0, ArgExprA.get()); 6919 TheCall->setArg(1, ArgExprB.get()); 6920 TheCall->setType(Context.LongLongTy); 6921 return false; 6922 } 6923 assert(false && "Unhandled ARM MTE intrinsic"); 6924 return true; 6925 } 6926 6927 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6928 /// TheCall is an ARM/AArch64 special register string literal. 6929 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6930 int ArgNum, unsigned ExpectedFieldNum, 6931 bool AllowName) { 6932 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6933 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6934 BuiltinID == ARM::BI__builtin_arm_rsr || 6935 BuiltinID == ARM::BI__builtin_arm_rsrp || 6936 BuiltinID == ARM::BI__builtin_arm_wsr || 6937 BuiltinID == ARM::BI__builtin_arm_wsrp; 6938 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6939 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6940 BuiltinID == AArch64::BI__builtin_arm_rsr || 6941 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6942 BuiltinID == AArch64::BI__builtin_arm_wsr || 6943 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6944 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6945 6946 // We can't check the value of a dependent argument. 6947 Expr *Arg = TheCall->getArg(ArgNum); 6948 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6949 return false; 6950 6951 // Check if the argument is a string literal. 6952 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6953 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6954 << Arg->getSourceRange(); 6955 6956 // Check the type of special register given. 6957 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6958 SmallVector<StringRef, 6> Fields; 6959 Reg.split(Fields, ":"); 6960 6961 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6962 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6963 << Arg->getSourceRange(); 6964 6965 // If the string is the name of a register then we cannot check that it is 6966 // valid here but if the string is of one the forms described in ACLE then we 6967 // can check that the supplied fields are integers and within the valid 6968 // ranges. 6969 if (Fields.size() > 1) { 6970 bool FiveFields = Fields.size() == 5; 6971 6972 bool ValidString = true; 6973 if (IsARMBuiltin) { 6974 ValidString &= Fields[0].startswith_lower("cp") || 6975 Fields[0].startswith_lower("p"); 6976 if (ValidString) 6977 Fields[0] = 6978 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6979 6980 ValidString &= Fields[2].startswith_lower("c"); 6981 if (ValidString) 6982 Fields[2] = Fields[2].drop_front(1); 6983 6984 if (FiveFields) { 6985 ValidString &= Fields[3].startswith_lower("c"); 6986 if (ValidString) 6987 Fields[3] = Fields[3].drop_front(1); 6988 } 6989 } 6990 6991 SmallVector<int, 5> Ranges; 6992 if (FiveFields) 6993 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6994 else 6995 Ranges.append({15, 7, 15}); 6996 6997 for (unsigned i=0; i<Fields.size(); ++i) { 6998 int IntField; 6999 ValidString &= !Fields[i].getAsInteger(10, IntField); 7000 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7001 } 7002 7003 if (!ValidString) 7004 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7005 << Arg->getSourceRange(); 7006 } else if (IsAArch64Builtin && Fields.size() == 1) { 7007 // If the register name is one of those that appear in the condition below 7008 // and the special register builtin being used is one of the write builtins, 7009 // then we require that the argument provided for writing to the register 7010 // is an integer constant expression. This is because it will be lowered to 7011 // an MSR (immediate) instruction, so we need to know the immediate at 7012 // compile time. 7013 if (TheCall->getNumArgs() != 2) 7014 return false; 7015 7016 std::string RegLower = Reg.lower(); 7017 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7018 RegLower != "pan" && RegLower != "uao") 7019 return false; 7020 7021 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7022 } 7023 7024 return false; 7025 } 7026 7027 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7028 /// Emit an error and return true on failure; return false on success. 7029 /// TypeStr is a string containing the type descriptor of the value returned by 7030 /// the builtin and the descriptors of the expected type of the arguments. 7031 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 7032 7033 assert((TypeStr[0] != '\0') && 7034 "Invalid types in PPC MMA builtin declaration"); 7035 7036 unsigned Mask = 0; 7037 unsigned ArgNum = 0; 7038 7039 // The first type in TypeStr is the type of the value returned by the 7040 // builtin. So we first read that type and change the type of TheCall. 7041 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7042 TheCall->setType(type); 7043 7044 while (*TypeStr != '\0') { 7045 Mask = 0; 7046 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7047 if (ArgNum >= TheCall->getNumArgs()) { 7048 ArgNum++; 7049 break; 7050 } 7051 7052 Expr *Arg = TheCall->getArg(ArgNum); 7053 QualType ArgType = Arg->getType(); 7054 7055 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 7056 (!ExpectedType->isVoidPointerType() && 7057 ArgType.getCanonicalType() != ExpectedType)) 7058 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7059 << ArgType << ExpectedType << 1 << 0 << 0; 7060 7061 // If the value of the Mask is not 0, we have a constraint in the size of 7062 // the integer argument so here we ensure the argument is a constant that 7063 // is in the valid range. 7064 if (Mask != 0 && 7065 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7066 return true; 7067 7068 ArgNum++; 7069 } 7070 7071 // In case we exited early from the previous loop, there are other types to 7072 // read from TypeStr. So we need to read them all to ensure we have the right 7073 // number of arguments in TheCall and if it is not the case, to display a 7074 // better error message. 7075 while (*TypeStr != '\0') { 7076 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7077 ArgNum++; 7078 } 7079 if (checkArgCount(*this, TheCall, ArgNum)) 7080 return true; 7081 7082 return false; 7083 } 7084 7085 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7086 /// This checks that the target supports __builtin_longjmp and 7087 /// that val is a constant 1. 7088 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7089 if (!Context.getTargetInfo().hasSjLjLowering()) 7090 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7091 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7092 7093 Expr *Arg = TheCall->getArg(1); 7094 llvm::APSInt Result; 7095 7096 // TODO: This is less than ideal. Overload this to take a value. 7097 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7098 return true; 7099 7100 if (Result != 1) 7101 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7102 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7103 7104 return false; 7105 } 7106 7107 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7108 /// This checks that the target supports __builtin_setjmp. 7109 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7110 if (!Context.getTargetInfo().hasSjLjLowering()) 7111 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7112 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7113 return false; 7114 } 7115 7116 namespace { 7117 7118 class UncoveredArgHandler { 7119 enum { Unknown = -1, AllCovered = -2 }; 7120 7121 signed FirstUncoveredArg = Unknown; 7122 SmallVector<const Expr *, 4> DiagnosticExprs; 7123 7124 public: 7125 UncoveredArgHandler() = default; 7126 7127 bool hasUncoveredArg() const { 7128 return (FirstUncoveredArg >= 0); 7129 } 7130 7131 unsigned getUncoveredArg() const { 7132 assert(hasUncoveredArg() && "no uncovered argument"); 7133 return FirstUncoveredArg; 7134 } 7135 7136 void setAllCovered() { 7137 // A string has been found with all arguments covered, so clear out 7138 // the diagnostics. 7139 DiagnosticExprs.clear(); 7140 FirstUncoveredArg = AllCovered; 7141 } 7142 7143 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7144 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7145 7146 // Don't update if a previous string covers all arguments. 7147 if (FirstUncoveredArg == AllCovered) 7148 return; 7149 7150 // UncoveredArgHandler tracks the highest uncovered argument index 7151 // and with it all the strings that match this index. 7152 if (NewFirstUncoveredArg == FirstUncoveredArg) 7153 DiagnosticExprs.push_back(StrExpr); 7154 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7155 DiagnosticExprs.clear(); 7156 DiagnosticExprs.push_back(StrExpr); 7157 FirstUncoveredArg = NewFirstUncoveredArg; 7158 } 7159 } 7160 7161 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7162 }; 7163 7164 enum StringLiteralCheckType { 7165 SLCT_NotALiteral, 7166 SLCT_UncheckedLiteral, 7167 SLCT_CheckedLiteral 7168 }; 7169 7170 } // namespace 7171 7172 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7173 BinaryOperatorKind BinOpKind, 7174 bool AddendIsRight) { 7175 unsigned BitWidth = Offset.getBitWidth(); 7176 unsigned AddendBitWidth = Addend.getBitWidth(); 7177 // There might be negative interim results. 7178 if (Addend.isUnsigned()) { 7179 Addend = Addend.zext(++AddendBitWidth); 7180 Addend.setIsSigned(true); 7181 } 7182 // Adjust the bit width of the APSInts. 7183 if (AddendBitWidth > BitWidth) { 7184 Offset = Offset.sext(AddendBitWidth); 7185 BitWidth = AddendBitWidth; 7186 } else if (BitWidth > AddendBitWidth) { 7187 Addend = Addend.sext(BitWidth); 7188 } 7189 7190 bool Ov = false; 7191 llvm::APSInt ResOffset = Offset; 7192 if (BinOpKind == BO_Add) 7193 ResOffset = Offset.sadd_ov(Addend, Ov); 7194 else { 7195 assert(AddendIsRight && BinOpKind == BO_Sub && 7196 "operator must be add or sub with addend on the right"); 7197 ResOffset = Offset.ssub_ov(Addend, Ov); 7198 } 7199 7200 // We add an offset to a pointer here so we should support an offset as big as 7201 // possible. 7202 if (Ov) { 7203 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7204 "index (intermediate) result too big"); 7205 Offset = Offset.sext(2 * BitWidth); 7206 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7207 return; 7208 } 7209 7210 Offset = ResOffset; 7211 } 7212 7213 namespace { 7214 7215 // This is a wrapper class around StringLiteral to support offsetted string 7216 // literals as format strings. It takes the offset into account when returning 7217 // the string and its length or the source locations to display notes correctly. 7218 class FormatStringLiteral { 7219 const StringLiteral *FExpr; 7220 int64_t Offset; 7221 7222 public: 7223 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7224 : FExpr(fexpr), Offset(Offset) {} 7225 7226 StringRef getString() const { 7227 return FExpr->getString().drop_front(Offset); 7228 } 7229 7230 unsigned getByteLength() const { 7231 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7232 } 7233 7234 unsigned getLength() const { return FExpr->getLength() - Offset; } 7235 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7236 7237 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7238 7239 QualType getType() const { return FExpr->getType(); } 7240 7241 bool isAscii() const { return FExpr->isAscii(); } 7242 bool isWide() const { return FExpr->isWide(); } 7243 bool isUTF8() const { return FExpr->isUTF8(); } 7244 bool isUTF16() const { return FExpr->isUTF16(); } 7245 bool isUTF32() const { return FExpr->isUTF32(); } 7246 bool isPascal() const { return FExpr->isPascal(); } 7247 7248 SourceLocation getLocationOfByte( 7249 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7250 const TargetInfo &Target, unsigned *StartToken = nullptr, 7251 unsigned *StartTokenByteOffset = nullptr) const { 7252 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7253 StartToken, StartTokenByteOffset); 7254 } 7255 7256 SourceLocation getBeginLoc() const LLVM_READONLY { 7257 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7258 } 7259 7260 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7261 }; 7262 7263 } // namespace 7264 7265 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7266 const Expr *OrigFormatExpr, 7267 ArrayRef<const Expr *> Args, 7268 bool HasVAListArg, unsigned format_idx, 7269 unsigned firstDataArg, 7270 Sema::FormatStringType Type, 7271 bool inFunctionCall, 7272 Sema::VariadicCallType CallType, 7273 llvm::SmallBitVector &CheckedVarArgs, 7274 UncoveredArgHandler &UncoveredArg, 7275 bool IgnoreStringsWithoutSpecifiers); 7276 7277 // Determine if an expression is a string literal or constant string. 7278 // If this function returns false on the arguments to a function expecting a 7279 // format string, we will usually need to emit a warning. 7280 // True string literals are then checked by CheckFormatString. 7281 static StringLiteralCheckType 7282 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7283 bool HasVAListArg, unsigned format_idx, 7284 unsigned firstDataArg, Sema::FormatStringType Type, 7285 Sema::VariadicCallType CallType, bool InFunctionCall, 7286 llvm::SmallBitVector &CheckedVarArgs, 7287 UncoveredArgHandler &UncoveredArg, 7288 llvm::APSInt Offset, 7289 bool IgnoreStringsWithoutSpecifiers = false) { 7290 if (S.isConstantEvaluated()) 7291 return SLCT_NotALiteral; 7292 tryAgain: 7293 assert(Offset.isSigned() && "invalid offset"); 7294 7295 if (E->isTypeDependent() || E->isValueDependent()) 7296 return SLCT_NotALiteral; 7297 7298 E = E->IgnoreParenCasts(); 7299 7300 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7301 // Technically -Wformat-nonliteral does not warn about this case. 7302 // The behavior of printf and friends in this case is implementation 7303 // dependent. Ideally if the format string cannot be null then 7304 // it should have a 'nonnull' attribute in the function prototype. 7305 return SLCT_UncheckedLiteral; 7306 7307 switch (E->getStmtClass()) { 7308 case Stmt::BinaryConditionalOperatorClass: 7309 case Stmt::ConditionalOperatorClass: { 7310 // The expression is a literal if both sub-expressions were, and it was 7311 // completely checked only if both sub-expressions were checked. 7312 const AbstractConditionalOperator *C = 7313 cast<AbstractConditionalOperator>(E); 7314 7315 // Determine whether it is necessary to check both sub-expressions, for 7316 // example, because the condition expression is a constant that can be 7317 // evaluated at compile time. 7318 bool CheckLeft = true, CheckRight = true; 7319 7320 bool Cond; 7321 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7322 S.isConstantEvaluated())) { 7323 if (Cond) 7324 CheckRight = false; 7325 else 7326 CheckLeft = false; 7327 } 7328 7329 // We need to maintain the offsets for the right and the left hand side 7330 // separately to check if every possible indexed expression is a valid 7331 // string literal. They might have different offsets for different string 7332 // literals in the end. 7333 StringLiteralCheckType Left; 7334 if (!CheckLeft) 7335 Left = SLCT_UncheckedLiteral; 7336 else { 7337 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7338 HasVAListArg, format_idx, firstDataArg, 7339 Type, CallType, InFunctionCall, 7340 CheckedVarArgs, UncoveredArg, Offset, 7341 IgnoreStringsWithoutSpecifiers); 7342 if (Left == SLCT_NotALiteral || !CheckRight) { 7343 return Left; 7344 } 7345 } 7346 7347 StringLiteralCheckType Right = checkFormatStringExpr( 7348 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7349 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7350 IgnoreStringsWithoutSpecifiers); 7351 7352 return (CheckLeft && Left < Right) ? Left : Right; 7353 } 7354 7355 case Stmt::ImplicitCastExprClass: 7356 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7357 goto tryAgain; 7358 7359 case Stmt::OpaqueValueExprClass: 7360 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7361 E = src; 7362 goto tryAgain; 7363 } 7364 return SLCT_NotALiteral; 7365 7366 case Stmt::PredefinedExprClass: 7367 // While __func__, etc., are technically not string literals, they 7368 // cannot contain format specifiers and thus are not a security 7369 // liability. 7370 return SLCT_UncheckedLiteral; 7371 7372 case Stmt::DeclRefExprClass: { 7373 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7374 7375 // As an exception, do not flag errors for variables binding to 7376 // const string literals. 7377 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7378 bool isConstant = false; 7379 QualType T = DR->getType(); 7380 7381 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7382 isConstant = AT->getElementType().isConstant(S.Context); 7383 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7384 isConstant = T.isConstant(S.Context) && 7385 PT->getPointeeType().isConstant(S.Context); 7386 } else if (T->isObjCObjectPointerType()) { 7387 // In ObjC, there is usually no "const ObjectPointer" type, 7388 // so don't check if the pointee type is constant. 7389 isConstant = T.isConstant(S.Context); 7390 } 7391 7392 if (isConstant) { 7393 if (const Expr *Init = VD->getAnyInitializer()) { 7394 // Look through initializers like const char c[] = { "foo" } 7395 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7396 if (InitList->isStringLiteralInit()) 7397 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7398 } 7399 return checkFormatStringExpr(S, Init, Args, 7400 HasVAListArg, format_idx, 7401 firstDataArg, Type, CallType, 7402 /*InFunctionCall*/ false, CheckedVarArgs, 7403 UncoveredArg, Offset); 7404 } 7405 } 7406 7407 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7408 // special check to see if the format string is a function parameter 7409 // of the function calling the printf function. If the function 7410 // has an attribute indicating it is a printf-like function, then we 7411 // should suppress warnings concerning non-literals being used in a call 7412 // to a vprintf function. For example: 7413 // 7414 // void 7415 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7416 // va_list ap; 7417 // va_start(ap, fmt); 7418 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7419 // ... 7420 // } 7421 if (HasVAListArg) { 7422 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7423 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7424 int PVIndex = PV->getFunctionScopeIndex() + 1; 7425 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7426 // adjust for implicit parameter 7427 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7428 if (MD->isInstance()) 7429 ++PVIndex; 7430 // We also check if the formats are compatible. 7431 // We can't pass a 'scanf' string to a 'printf' function. 7432 if (PVIndex == PVFormat->getFormatIdx() && 7433 Type == S.GetFormatStringType(PVFormat)) 7434 return SLCT_UncheckedLiteral; 7435 } 7436 } 7437 } 7438 } 7439 } 7440 7441 return SLCT_NotALiteral; 7442 } 7443 7444 case Stmt::CallExprClass: 7445 case Stmt::CXXMemberCallExprClass: { 7446 const CallExpr *CE = cast<CallExpr>(E); 7447 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7448 bool IsFirst = true; 7449 StringLiteralCheckType CommonResult; 7450 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7451 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7452 StringLiteralCheckType Result = checkFormatStringExpr( 7453 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7454 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7455 IgnoreStringsWithoutSpecifiers); 7456 if (IsFirst) { 7457 CommonResult = Result; 7458 IsFirst = false; 7459 } 7460 } 7461 if (!IsFirst) 7462 return CommonResult; 7463 7464 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7465 unsigned BuiltinID = FD->getBuiltinID(); 7466 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7467 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7468 const Expr *Arg = CE->getArg(0); 7469 return checkFormatStringExpr(S, Arg, Args, 7470 HasVAListArg, format_idx, 7471 firstDataArg, Type, CallType, 7472 InFunctionCall, CheckedVarArgs, 7473 UncoveredArg, Offset, 7474 IgnoreStringsWithoutSpecifiers); 7475 } 7476 } 7477 } 7478 7479 return SLCT_NotALiteral; 7480 } 7481 case Stmt::ObjCMessageExprClass: { 7482 const auto *ME = cast<ObjCMessageExpr>(E); 7483 if (const auto *MD = ME->getMethodDecl()) { 7484 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7485 // As a special case heuristic, if we're using the method -[NSBundle 7486 // localizedStringForKey:value:table:], ignore any key strings that lack 7487 // format specifiers. The idea is that if the key doesn't have any 7488 // format specifiers then its probably just a key to map to the 7489 // localized strings. If it does have format specifiers though, then its 7490 // likely that the text of the key is the format string in the 7491 // programmer's language, and should be checked. 7492 const ObjCInterfaceDecl *IFace; 7493 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7494 IFace->getIdentifier()->isStr("NSBundle") && 7495 MD->getSelector().isKeywordSelector( 7496 {"localizedStringForKey", "value", "table"})) { 7497 IgnoreStringsWithoutSpecifiers = true; 7498 } 7499 7500 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7501 return checkFormatStringExpr( 7502 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7503 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7504 IgnoreStringsWithoutSpecifiers); 7505 } 7506 } 7507 7508 return SLCT_NotALiteral; 7509 } 7510 case Stmt::ObjCStringLiteralClass: 7511 case Stmt::StringLiteralClass: { 7512 const StringLiteral *StrE = nullptr; 7513 7514 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7515 StrE = ObjCFExpr->getString(); 7516 else 7517 StrE = cast<StringLiteral>(E); 7518 7519 if (StrE) { 7520 if (Offset.isNegative() || Offset > StrE->getLength()) { 7521 // TODO: It would be better to have an explicit warning for out of 7522 // bounds literals. 7523 return SLCT_NotALiteral; 7524 } 7525 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7526 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7527 firstDataArg, Type, InFunctionCall, CallType, 7528 CheckedVarArgs, UncoveredArg, 7529 IgnoreStringsWithoutSpecifiers); 7530 return SLCT_CheckedLiteral; 7531 } 7532 7533 return SLCT_NotALiteral; 7534 } 7535 case Stmt::BinaryOperatorClass: { 7536 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7537 7538 // A string literal + an int offset is still a string literal. 7539 if (BinOp->isAdditiveOp()) { 7540 Expr::EvalResult LResult, RResult; 7541 7542 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7543 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7544 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7545 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7546 7547 if (LIsInt != RIsInt) { 7548 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7549 7550 if (LIsInt) { 7551 if (BinOpKind == BO_Add) { 7552 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7553 E = BinOp->getRHS(); 7554 goto tryAgain; 7555 } 7556 } else { 7557 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7558 E = BinOp->getLHS(); 7559 goto tryAgain; 7560 } 7561 } 7562 } 7563 7564 return SLCT_NotALiteral; 7565 } 7566 case Stmt::UnaryOperatorClass: { 7567 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7568 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7569 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7570 Expr::EvalResult IndexResult; 7571 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7572 Expr::SE_NoSideEffects, 7573 S.isConstantEvaluated())) { 7574 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7575 /*RHS is int*/ true); 7576 E = ASE->getBase(); 7577 goto tryAgain; 7578 } 7579 } 7580 7581 return SLCT_NotALiteral; 7582 } 7583 7584 default: 7585 return SLCT_NotALiteral; 7586 } 7587 } 7588 7589 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7590 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7591 .Case("scanf", FST_Scanf) 7592 .Cases("printf", "printf0", FST_Printf) 7593 .Cases("NSString", "CFString", FST_NSString) 7594 .Case("strftime", FST_Strftime) 7595 .Case("strfmon", FST_Strfmon) 7596 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7597 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7598 .Case("os_trace", FST_OSLog) 7599 .Case("os_log", FST_OSLog) 7600 .Default(FST_Unknown); 7601 } 7602 7603 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7604 /// functions) for correct use of format strings. 7605 /// Returns true if a format string has been fully checked. 7606 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7607 ArrayRef<const Expr *> Args, 7608 bool IsCXXMember, 7609 VariadicCallType CallType, 7610 SourceLocation Loc, SourceRange Range, 7611 llvm::SmallBitVector &CheckedVarArgs) { 7612 FormatStringInfo FSI; 7613 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7614 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7615 FSI.FirstDataArg, GetFormatStringType(Format), 7616 CallType, Loc, Range, CheckedVarArgs); 7617 return false; 7618 } 7619 7620 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7621 bool HasVAListArg, unsigned format_idx, 7622 unsigned firstDataArg, FormatStringType Type, 7623 VariadicCallType CallType, 7624 SourceLocation Loc, SourceRange Range, 7625 llvm::SmallBitVector &CheckedVarArgs) { 7626 // CHECK: printf/scanf-like function is called with no format string. 7627 if (format_idx >= Args.size()) { 7628 Diag(Loc, diag::warn_missing_format_string) << Range; 7629 return false; 7630 } 7631 7632 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7633 7634 // CHECK: format string is not a string literal. 7635 // 7636 // Dynamically generated format strings are difficult to 7637 // automatically vet at compile time. Requiring that format strings 7638 // are string literals: (1) permits the checking of format strings by 7639 // the compiler and thereby (2) can practically remove the source of 7640 // many format string exploits. 7641 7642 // Format string can be either ObjC string (e.g. @"%d") or 7643 // C string (e.g. "%d") 7644 // ObjC string uses the same format specifiers as C string, so we can use 7645 // the same format string checking logic for both ObjC and C strings. 7646 UncoveredArgHandler UncoveredArg; 7647 StringLiteralCheckType CT = 7648 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7649 format_idx, firstDataArg, Type, CallType, 7650 /*IsFunctionCall*/ true, CheckedVarArgs, 7651 UncoveredArg, 7652 /*no string offset*/ llvm::APSInt(64, false) = 0); 7653 7654 // Generate a diagnostic where an uncovered argument is detected. 7655 if (UncoveredArg.hasUncoveredArg()) { 7656 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7657 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7658 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7659 } 7660 7661 if (CT != SLCT_NotALiteral) 7662 // Literal format string found, check done! 7663 return CT == SLCT_CheckedLiteral; 7664 7665 // Strftime is particular as it always uses a single 'time' argument, 7666 // so it is safe to pass a non-literal string. 7667 if (Type == FST_Strftime) 7668 return false; 7669 7670 // Do not emit diag when the string param is a macro expansion and the 7671 // format is either NSString or CFString. This is a hack to prevent 7672 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7673 // which are usually used in place of NS and CF string literals. 7674 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7675 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7676 return false; 7677 7678 // If there are no arguments specified, warn with -Wformat-security, otherwise 7679 // warn only with -Wformat-nonliteral. 7680 if (Args.size() == firstDataArg) { 7681 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7682 << OrigFormatExpr->getSourceRange(); 7683 switch (Type) { 7684 default: 7685 break; 7686 case FST_Kprintf: 7687 case FST_FreeBSDKPrintf: 7688 case FST_Printf: 7689 Diag(FormatLoc, diag::note_format_security_fixit) 7690 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7691 break; 7692 case FST_NSString: 7693 Diag(FormatLoc, diag::note_format_security_fixit) 7694 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7695 break; 7696 } 7697 } else { 7698 Diag(FormatLoc, diag::warn_format_nonliteral) 7699 << OrigFormatExpr->getSourceRange(); 7700 } 7701 return false; 7702 } 7703 7704 namespace { 7705 7706 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7707 protected: 7708 Sema &S; 7709 const FormatStringLiteral *FExpr; 7710 const Expr *OrigFormatExpr; 7711 const Sema::FormatStringType FSType; 7712 const unsigned FirstDataArg; 7713 const unsigned NumDataArgs; 7714 const char *Beg; // Start of format string. 7715 const bool HasVAListArg; 7716 ArrayRef<const Expr *> Args; 7717 unsigned FormatIdx; 7718 llvm::SmallBitVector CoveredArgs; 7719 bool usesPositionalArgs = false; 7720 bool atFirstArg = true; 7721 bool inFunctionCall; 7722 Sema::VariadicCallType CallType; 7723 llvm::SmallBitVector &CheckedVarArgs; 7724 UncoveredArgHandler &UncoveredArg; 7725 7726 public: 7727 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7728 const Expr *origFormatExpr, 7729 const Sema::FormatStringType type, unsigned firstDataArg, 7730 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7731 ArrayRef<const Expr *> Args, unsigned formatIdx, 7732 bool inFunctionCall, Sema::VariadicCallType callType, 7733 llvm::SmallBitVector &CheckedVarArgs, 7734 UncoveredArgHandler &UncoveredArg) 7735 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7736 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7737 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7738 inFunctionCall(inFunctionCall), CallType(callType), 7739 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7740 CoveredArgs.resize(numDataArgs); 7741 CoveredArgs.reset(); 7742 } 7743 7744 void DoneProcessing(); 7745 7746 void HandleIncompleteSpecifier(const char *startSpecifier, 7747 unsigned specifierLen) override; 7748 7749 void HandleInvalidLengthModifier( 7750 const analyze_format_string::FormatSpecifier &FS, 7751 const analyze_format_string::ConversionSpecifier &CS, 7752 const char *startSpecifier, unsigned specifierLen, 7753 unsigned DiagID); 7754 7755 void HandleNonStandardLengthModifier( 7756 const analyze_format_string::FormatSpecifier &FS, 7757 const char *startSpecifier, unsigned specifierLen); 7758 7759 void HandleNonStandardConversionSpecifier( 7760 const analyze_format_string::ConversionSpecifier &CS, 7761 const char *startSpecifier, unsigned specifierLen); 7762 7763 void HandlePosition(const char *startPos, unsigned posLen) override; 7764 7765 void HandleInvalidPosition(const char *startSpecifier, 7766 unsigned specifierLen, 7767 analyze_format_string::PositionContext p) override; 7768 7769 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7770 7771 void HandleNullChar(const char *nullCharacter) override; 7772 7773 template <typename Range> 7774 static void 7775 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7776 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7777 bool IsStringLocation, Range StringRange, 7778 ArrayRef<FixItHint> Fixit = None); 7779 7780 protected: 7781 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7782 const char *startSpec, 7783 unsigned specifierLen, 7784 const char *csStart, unsigned csLen); 7785 7786 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7787 const char *startSpec, 7788 unsigned specifierLen); 7789 7790 SourceRange getFormatStringRange(); 7791 CharSourceRange getSpecifierRange(const char *startSpecifier, 7792 unsigned specifierLen); 7793 SourceLocation getLocationOfByte(const char *x); 7794 7795 const Expr *getDataArg(unsigned i) const; 7796 7797 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7798 const analyze_format_string::ConversionSpecifier &CS, 7799 const char *startSpecifier, unsigned specifierLen, 7800 unsigned argIndex); 7801 7802 template <typename Range> 7803 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7804 bool IsStringLocation, Range StringRange, 7805 ArrayRef<FixItHint> Fixit = None); 7806 }; 7807 7808 } // namespace 7809 7810 SourceRange CheckFormatHandler::getFormatStringRange() { 7811 return OrigFormatExpr->getSourceRange(); 7812 } 7813 7814 CharSourceRange CheckFormatHandler:: 7815 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7816 SourceLocation Start = getLocationOfByte(startSpecifier); 7817 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7818 7819 // Advance the end SourceLocation by one due to half-open ranges. 7820 End = End.getLocWithOffset(1); 7821 7822 return CharSourceRange::getCharRange(Start, End); 7823 } 7824 7825 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7826 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7827 S.getLangOpts(), S.Context.getTargetInfo()); 7828 } 7829 7830 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7831 unsigned specifierLen){ 7832 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7833 getLocationOfByte(startSpecifier), 7834 /*IsStringLocation*/true, 7835 getSpecifierRange(startSpecifier, specifierLen)); 7836 } 7837 7838 void CheckFormatHandler::HandleInvalidLengthModifier( 7839 const analyze_format_string::FormatSpecifier &FS, 7840 const analyze_format_string::ConversionSpecifier &CS, 7841 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7842 using namespace analyze_format_string; 7843 7844 const LengthModifier &LM = FS.getLengthModifier(); 7845 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7846 7847 // See if we know how to fix this length modifier. 7848 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7849 if (FixedLM) { 7850 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7851 getLocationOfByte(LM.getStart()), 7852 /*IsStringLocation*/true, 7853 getSpecifierRange(startSpecifier, specifierLen)); 7854 7855 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7856 << FixedLM->toString() 7857 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7858 7859 } else { 7860 FixItHint Hint; 7861 if (DiagID == diag::warn_format_nonsensical_length) 7862 Hint = FixItHint::CreateRemoval(LMRange); 7863 7864 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7865 getLocationOfByte(LM.getStart()), 7866 /*IsStringLocation*/true, 7867 getSpecifierRange(startSpecifier, specifierLen), 7868 Hint); 7869 } 7870 } 7871 7872 void CheckFormatHandler::HandleNonStandardLengthModifier( 7873 const analyze_format_string::FormatSpecifier &FS, 7874 const char *startSpecifier, unsigned specifierLen) { 7875 using namespace analyze_format_string; 7876 7877 const LengthModifier &LM = FS.getLengthModifier(); 7878 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7879 7880 // See if we know how to fix this length modifier. 7881 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7882 if (FixedLM) { 7883 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7884 << LM.toString() << 0, 7885 getLocationOfByte(LM.getStart()), 7886 /*IsStringLocation*/true, 7887 getSpecifierRange(startSpecifier, specifierLen)); 7888 7889 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7890 << FixedLM->toString() 7891 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7892 7893 } else { 7894 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7895 << LM.toString() << 0, 7896 getLocationOfByte(LM.getStart()), 7897 /*IsStringLocation*/true, 7898 getSpecifierRange(startSpecifier, specifierLen)); 7899 } 7900 } 7901 7902 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7903 const analyze_format_string::ConversionSpecifier &CS, 7904 const char *startSpecifier, unsigned specifierLen) { 7905 using namespace analyze_format_string; 7906 7907 // See if we know how to fix this conversion specifier. 7908 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7909 if (FixedCS) { 7910 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7911 << CS.toString() << /*conversion specifier*/1, 7912 getLocationOfByte(CS.getStart()), 7913 /*IsStringLocation*/true, 7914 getSpecifierRange(startSpecifier, specifierLen)); 7915 7916 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7917 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7918 << FixedCS->toString() 7919 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7920 } else { 7921 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7922 << CS.toString() << /*conversion specifier*/1, 7923 getLocationOfByte(CS.getStart()), 7924 /*IsStringLocation*/true, 7925 getSpecifierRange(startSpecifier, specifierLen)); 7926 } 7927 } 7928 7929 void CheckFormatHandler::HandlePosition(const char *startPos, 7930 unsigned posLen) { 7931 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7932 getLocationOfByte(startPos), 7933 /*IsStringLocation*/true, 7934 getSpecifierRange(startPos, posLen)); 7935 } 7936 7937 void 7938 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7939 analyze_format_string::PositionContext p) { 7940 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7941 << (unsigned) p, 7942 getLocationOfByte(startPos), /*IsStringLocation*/true, 7943 getSpecifierRange(startPos, posLen)); 7944 } 7945 7946 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7947 unsigned posLen) { 7948 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7949 getLocationOfByte(startPos), 7950 /*IsStringLocation*/true, 7951 getSpecifierRange(startPos, posLen)); 7952 } 7953 7954 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7955 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7956 // The presence of a null character is likely an error. 7957 EmitFormatDiagnostic( 7958 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7959 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7960 getFormatStringRange()); 7961 } 7962 } 7963 7964 // Note that this may return NULL if there was an error parsing or building 7965 // one of the argument expressions. 7966 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7967 return Args[FirstDataArg + i]; 7968 } 7969 7970 void CheckFormatHandler::DoneProcessing() { 7971 // Does the number of data arguments exceed the number of 7972 // format conversions in the format string? 7973 if (!HasVAListArg) { 7974 // Find any arguments that weren't covered. 7975 CoveredArgs.flip(); 7976 signed notCoveredArg = CoveredArgs.find_first(); 7977 if (notCoveredArg >= 0) { 7978 assert((unsigned)notCoveredArg < NumDataArgs); 7979 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7980 } else { 7981 UncoveredArg.setAllCovered(); 7982 } 7983 } 7984 } 7985 7986 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7987 const Expr *ArgExpr) { 7988 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7989 "Invalid state"); 7990 7991 if (!ArgExpr) 7992 return; 7993 7994 SourceLocation Loc = ArgExpr->getBeginLoc(); 7995 7996 if (S.getSourceManager().isInSystemMacro(Loc)) 7997 return; 7998 7999 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8000 for (auto E : DiagnosticExprs) 8001 PDiag << E->getSourceRange(); 8002 8003 CheckFormatHandler::EmitFormatDiagnostic( 8004 S, IsFunctionCall, DiagnosticExprs[0], 8005 PDiag, Loc, /*IsStringLocation*/false, 8006 DiagnosticExprs[0]->getSourceRange()); 8007 } 8008 8009 bool 8010 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8011 SourceLocation Loc, 8012 const char *startSpec, 8013 unsigned specifierLen, 8014 const char *csStart, 8015 unsigned csLen) { 8016 bool keepGoing = true; 8017 if (argIndex < NumDataArgs) { 8018 // Consider the argument coverered, even though the specifier doesn't 8019 // make sense. 8020 CoveredArgs.set(argIndex); 8021 } 8022 else { 8023 // If argIndex exceeds the number of data arguments we 8024 // don't issue a warning because that is just a cascade of warnings (and 8025 // they may have intended '%%' anyway). We don't want to continue processing 8026 // the format string after this point, however, as we will like just get 8027 // gibberish when trying to match arguments. 8028 keepGoing = false; 8029 } 8030 8031 StringRef Specifier(csStart, csLen); 8032 8033 // If the specifier in non-printable, it could be the first byte of a UTF-8 8034 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8035 // hex value. 8036 std::string CodePointStr; 8037 if (!llvm::sys::locale::isPrint(*csStart)) { 8038 llvm::UTF32 CodePoint; 8039 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8040 const llvm::UTF8 *E = 8041 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8042 llvm::ConversionResult Result = 8043 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8044 8045 if (Result != llvm::conversionOK) { 8046 unsigned char FirstChar = *csStart; 8047 CodePoint = (llvm::UTF32)FirstChar; 8048 } 8049 8050 llvm::raw_string_ostream OS(CodePointStr); 8051 if (CodePoint < 256) 8052 OS << "\\x" << llvm::format("%02x", CodePoint); 8053 else if (CodePoint <= 0xFFFF) 8054 OS << "\\u" << llvm::format("%04x", CodePoint); 8055 else 8056 OS << "\\U" << llvm::format("%08x", CodePoint); 8057 OS.flush(); 8058 Specifier = CodePointStr; 8059 } 8060 8061 EmitFormatDiagnostic( 8062 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8063 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8064 8065 return keepGoing; 8066 } 8067 8068 void 8069 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8070 const char *startSpec, 8071 unsigned specifierLen) { 8072 EmitFormatDiagnostic( 8073 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8074 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8075 } 8076 8077 bool 8078 CheckFormatHandler::CheckNumArgs( 8079 const analyze_format_string::FormatSpecifier &FS, 8080 const analyze_format_string::ConversionSpecifier &CS, 8081 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8082 8083 if (argIndex >= NumDataArgs) { 8084 PartialDiagnostic PDiag = FS.usesPositionalArg() 8085 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8086 << (argIndex+1) << NumDataArgs) 8087 : S.PDiag(diag::warn_printf_insufficient_data_args); 8088 EmitFormatDiagnostic( 8089 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8090 getSpecifierRange(startSpecifier, specifierLen)); 8091 8092 // Since more arguments than conversion tokens are given, by extension 8093 // all arguments are covered, so mark this as so. 8094 UncoveredArg.setAllCovered(); 8095 return false; 8096 } 8097 return true; 8098 } 8099 8100 template<typename Range> 8101 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8102 SourceLocation Loc, 8103 bool IsStringLocation, 8104 Range StringRange, 8105 ArrayRef<FixItHint> FixIt) { 8106 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8107 Loc, IsStringLocation, StringRange, FixIt); 8108 } 8109 8110 /// If the format string is not within the function call, emit a note 8111 /// so that the function call and string are in diagnostic messages. 8112 /// 8113 /// \param InFunctionCall if true, the format string is within the function 8114 /// call and only one diagnostic message will be produced. Otherwise, an 8115 /// extra note will be emitted pointing to location of the format string. 8116 /// 8117 /// \param ArgumentExpr the expression that is passed as the format string 8118 /// argument in the function call. Used for getting locations when two 8119 /// diagnostics are emitted. 8120 /// 8121 /// \param PDiag the callee should already have provided any strings for the 8122 /// diagnostic message. This function only adds locations and fixits 8123 /// to diagnostics. 8124 /// 8125 /// \param Loc primary location for diagnostic. If two diagnostics are 8126 /// required, one will be at Loc and a new SourceLocation will be created for 8127 /// the other one. 8128 /// 8129 /// \param IsStringLocation if true, Loc points to the format string should be 8130 /// used for the note. Otherwise, Loc points to the argument list and will 8131 /// be used with PDiag. 8132 /// 8133 /// \param StringRange some or all of the string to highlight. This is 8134 /// templated so it can accept either a CharSourceRange or a SourceRange. 8135 /// 8136 /// \param FixIt optional fix it hint for the format string. 8137 template <typename Range> 8138 void CheckFormatHandler::EmitFormatDiagnostic( 8139 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8140 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8141 Range StringRange, ArrayRef<FixItHint> FixIt) { 8142 if (InFunctionCall) { 8143 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8144 D << StringRange; 8145 D << FixIt; 8146 } else { 8147 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8148 << ArgumentExpr->getSourceRange(); 8149 8150 const Sema::SemaDiagnosticBuilder &Note = 8151 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8152 diag::note_format_string_defined); 8153 8154 Note << StringRange; 8155 Note << FixIt; 8156 } 8157 } 8158 8159 //===--- CHECK: Printf format string checking ------------------------------===// 8160 8161 namespace { 8162 8163 class CheckPrintfHandler : public CheckFormatHandler { 8164 public: 8165 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8166 const Expr *origFormatExpr, 8167 const Sema::FormatStringType type, unsigned firstDataArg, 8168 unsigned numDataArgs, bool isObjC, const char *beg, 8169 bool hasVAListArg, ArrayRef<const Expr *> Args, 8170 unsigned formatIdx, bool inFunctionCall, 8171 Sema::VariadicCallType CallType, 8172 llvm::SmallBitVector &CheckedVarArgs, 8173 UncoveredArgHandler &UncoveredArg) 8174 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8175 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8176 inFunctionCall, CallType, CheckedVarArgs, 8177 UncoveredArg) {} 8178 8179 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8180 8181 /// Returns true if '%@' specifiers are allowed in the format string. 8182 bool allowsObjCArg() const { 8183 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8184 FSType == Sema::FST_OSTrace; 8185 } 8186 8187 bool HandleInvalidPrintfConversionSpecifier( 8188 const analyze_printf::PrintfSpecifier &FS, 8189 const char *startSpecifier, 8190 unsigned specifierLen) override; 8191 8192 void handleInvalidMaskType(StringRef MaskType) override; 8193 8194 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8195 const char *startSpecifier, 8196 unsigned specifierLen) override; 8197 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8198 const char *StartSpecifier, 8199 unsigned SpecifierLen, 8200 const Expr *E); 8201 8202 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8203 const char *startSpecifier, unsigned specifierLen); 8204 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8205 const analyze_printf::OptionalAmount &Amt, 8206 unsigned type, 8207 const char *startSpecifier, unsigned specifierLen); 8208 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8209 const analyze_printf::OptionalFlag &flag, 8210 const char *startSpecifier, unsigned specifierLen); 8211 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8212 const analyze_printf::OptionalFlag &ignoredFlag, 8213 const analyze_printf::OptionalFlag &flag, 8214 const char *startSpecifier, unsigned specifierLen); 8215 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8216 const Expr *E); 8217 8218 void HandleEmptyObjCModifierFlag(const char *startFlag, 8219 unsigned flagLen) override; 8220 8221 void HandleInvalidObjCModifierFlag(const char *startFlag, 8222 unsigned flagLen) override; 8223 8224 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8225 const char *flagsEnd, 8226 const char *conversionPosition) 8227 override; 8228 }; 8229 8230 } // namespace 8231 8232 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8233 const analyze_printf::PrintfSpecifier &FS, 8234 const char *startSpecifier, 8235 unsigned specifierLen) { 8236 const analyze_printf::PrintfConversionSpecifier &CS = 8237 FS.getConversionSpecifier(); 8238 8239 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8240 getLocationOfByte(CS.getStart()), 8241 startSpecifier, specifierLen, 8242 CS.getStart(), CS.getLength()); 8243 } 8244 8245 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8246 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8247 } 8248 8249 bool CheckPrintfHandler::HandleAmount( 8250 const analyze_format_string::OptionalAmount &Amt, 8251 unsigned k, const char *startSpecifier, 8252 unsigned specifierLen) { 8253 if (Amt.hasDataArgument()) { 8254 if (!HasVAListArg) { 8255 unsigned argIndex = Amt.getArgIndex(); 8256 if (argIndex >= NumDataArgs) { 8257 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8258 << k, 8259 getLocationOfByte(Amt.getStart()), 8260 /*IsStringLocation*/true, 8261 getSpecifierRange(startSpecifier, specifierLen)); 8262 // Don't do any more checking. We will just emit 8263 // spurious errors. 8264 return false; 8265 } 8266 8267 // Type check the data argument. It should be an 'int'. 8268 // Although not in conformance with C99, we also allow the argument to be 8269 // an 'unsigned int' as that is a reasonably safe case. GCC also 8270 // doesn't emit a warning for that case. 8271 CoveredArgs.set(argIndex); 8272 const Expr *Arg = getDataArg(argIndex); 8273 if (!Arg) 8274 return false; 8275 8276 QualType T = Arg->getType(); 8277 8278 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8279 assert(AT.isValid()); 8280 8281 if (!AT.matchesType(S.Context, T)) { 8282 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8283 << k << AT.getRepresentativeTypeName(S.Context) 8284 << T << Arg->getSourceRange(), 8285 getLocationOfByte(Amt.getStart()), 8286 /*IsStringLocation*/true, 8287 getSpecifierRange(startSpecifier, specifierLen)); 8288 // Don't do any more checking. We will just emit 8289 // spurious errors. 8290 return false; 8291 } 8292 } 8293 } 8294 return true; 8295 } 8296 8297 void CheckPrintfHandler::HandleInvalidAmount( 8298 const analyze_printf::PrintfSpecifier &FS, 8299 const analyze_printf::OptionalAmount &Amt, 8300 unsigned type, 8301 const char *startSpecifier, 8302 unsigned specifierLen) { 8303 const analyze_printf::PrintfConversionSpecifier &CS = 8304 FS.getConversionSpecifier(); 8305 8306 FixItHint fixit = 8307 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8308 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8309 Amt.getConstantLength())) 8310 : FixItHint(); 8311 8312 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8313 << type << CS.toString(), 8314 getLocationOfByte(Amt.getStart()), 8315 /*IsStringLocation*/true, 8316 getSpecifierRange(startSpecifier, specifierLen), 8317 fixit); 8318 } 8319 8320 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8321 const analyze_printf::OptionalFlag &flag, 8322 const char *startSpecifier, 8323 unsigned specifierLen) { 8324 // Warn about pointless flag with a fixit removal. 8325 const analyze_printf::PrintfConversionSpecifier &CS = 8326 FS.getConversionSpecifier(); 8327 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8328 << flag.toString() << CS.toString(), 8329 getLocationOfByte(flag.getPosition()), 8330 /*IsStringLocation*/true, 8331 getSpecifierRange(startSpecifier, specifierLen), 8332 FixItHint::CreateRemoval( 8333 getSpecifierRange(flag.getPosition(), 1))); 8334 } 8335 8336 void CheckPrintfHandler::HandleIgnoredFlag( 8337 const analyze_printf::PrintfSpecifier &FS, 8338 const analyze_printf::OptionalFlag &ignoredFlag, 8339 const analyze_printf::OptionalFlag &flag, 8340 const char *startSpecifier, 8341 unsigned specifierLen) { 8342 // Warn about ignored flag with a fixit removal. 8343 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8344 << ignoredFlag.toString() << flag.toString(), 8345 getLocationOfByte(ignoredFlag.getPosition()), 8346 /*IsStringLocation*/true, 8347 getSpecifierRange(startSpecifier, specifierLen), 8348 FixItHint::CreateRemoval( 8349 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8350 } 8351 8352 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8353 unsigned flagLen) { 8354 // Warn about an empty flag. 8355 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8356 getLocationOfByte(startFlag), 8357 /*IsStringLocation*/true, 8358 getSpecifierRange(startFlag, flagLen)); 8359 } 8360 8361 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8362 unsigned flagLen) { 8363 // Warn about an invalid flag. 8364 auto Range = getSpecifierRange(startFlag, flagLen); 8365 StringRef flag(startFlag, flagLen); 8366 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8367 getLocationOfByte(startFlag), 8368 /*IsStringLocation*/true, 8369 Range, FixItHint::CreateRemoval(Range)); 8370 } 8371 8372 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8373 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8374 // Warn about using '[...]' without a '@' conversion. 8375 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8376 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8377 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8378 getLocationOfByte(conversionPosition), 8379 /*IsStringLocation*/true, 8380 Range, FixItHint::CreateRemoval(Range)); 8381 } 8382 8383 // Determines if the specified is a C++ class or struct containing 8384 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8385 // "c_str()"). 8386 template<typename MemberKind> 8387 static llvm::SmallPtrSet<MemberKind*, 1> 8388 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8389 const RecordType *RT = Ty->getAs<RecordType>(); 8390 llvm::SmallPtrSet<MemberKind*, 1> Results; 8391 8392 if (!RT) 8393 return Results; 8394 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8395 if (!RD || !RD->getDefinition()) 8396 return Results; 8397 8398 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8399 Sema::LookupMemberName); 8400 R.suppressDiagnostics(); 8401 8402 // We just need to include all members of the right kind turned up by the 8403 // filter, at this point. 8404 if (S.LookupQualifiedName(R, RT->getDecl())) 8405 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8406 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8407 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8408 Results.insert(FK); 8409 } 8410 return Results; 8411 } 8412 8413 /// Check if we could call '.c_str()' on an object. 8414 /// 8415 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8416 /// allow the call, or if it would be ambiguous). 8417 bool Sema::hasCStrMethod(const Expr *E) { 8418 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8419 8420 MethodSet Results = 8421 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8422 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8423 MI != ME; ++MI) 8424 if ((*MI)->getMinRequiredArguments() == 0) 8425 return true; 8426 return false; 8427 } 8428 8429 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8430 // better diagnostic if so. AT is assumed to be valid. 8431 // Returns true when a c_str() conversion method is found. 8432 bool CheckPrintfHandler::checkForCStrMembers( 8433 const analyze_printf::ArgType &AT, const Expr *E) { 8434 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8435 8436 MethodSet Results = 8437 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8438 8439 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8440 MI != ME; ++MI) { 8441 const CXXMethodDecl *Method = *MI; 8442 if (Method->getMinRequiredArguments() == 0 && 8443 AT.matchesType(S.Context, Method->getReturnType())) { 8444 // FIXME: Suggest parens if the expression needs them. 8445 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8446 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8447 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8448 return true; 8449 } 8450 } 8451 8452 return false; 8453 } 8454 8455 bool 8456 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8457 &FS, 8458 const char *startSpecifier, 8459 unsigned specifierLen) { 8460 using namespace analyze_format_string; 8461 using namespace analyze_printf; 8462 8463 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8464 8465 if (FS.consumesDataArgument()) { 8466 if (atFirstArg) { 8467 atFirstArg = false; 8468 usesPositionalArgs = FS.usesPositionalArg(); 8469 } 8470 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8471 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8472 startSpecifier, specifierLen); 8473 return false; 8474 } 8475 } 8476 8477 // First check if the field width, precision, and conversion specifier 8478 // have matching data arguments. 8479 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8480 startSpecifier, specifierLen)) { 8481 return false; 8482 } 8483 8484 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8485 startSpecifier, specifierLen)) { 8486 return false; 8487 } 8488 8489 if (!CS.consumesDataArgument()) { 8490 // FIXME: Technically specifying a precision or field width here 8491 // makes no sense. Worth issuing a warning at some point. 8492 return true; 8493 } 8494 8495 // Consume the argument. 8496 unsigned argIndex = FS.getArgIndex(); 8497 if (argIndex < NumDataArgs) { 8498 // The check to see if the argIndex is valid will come later. 8499 // We set the bit here because we may exit early from this 8500 // function if we encounter some other error. 8501 CoveredArgs.set(argIndex); 8502 } 8503 8504 // FreeBSD kernel extensions. 8505 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8506 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8507 // We need at least two arguments. 8508 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8509 return false; 8510 8511 // Claim the second argument. 8512 CoveredArgs.set(argIndex + 1); 8513 8514 // Type check the first argument (int for %b, pointer for %D) 8515 const Expr *Ex = getDataArg(argIndex); 8516 const analyze_printf::ArgType &AT = 8517 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8518 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8519 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8520 EmitFormatDiagnostic( 8521 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8522 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8523 << false << Ex->getSourceRange(), 8524 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8525 getSpecifierRange(startSpecifier, specifierLen)); 8526 8527 // Type check the second argument (char * for both %b and %D) 8528 Ex = getDataArg(argIndex + 1); 8529 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8530 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8531 EmitFormatDiagnostic( 8532 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8533 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8534 << false << Ex->getSourceRange(), 8535 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8536 getSpecifierRange(startSpecifier, specifierLen)); 8537 8538 return true; 8539 } 8540 8541 // Check for using an Objective-C specific conversion specifier 8542 // in a non-ObjC literal. 8543 if (!allowsObjCArg() && CS.isObjCArg()) { 8544 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8545 specifierLen); 8546 } 8547 8548 // %P can only be used with os_log. 8549 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8550 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8551 specifierLen); 8552 } 8553 8554 // %n is not allowed with os_log. 8555 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8556 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8557 getLocationOfByte(CS.getStart()), 8558 /*IsStringLocation*/ false, 8559 getSpecifierRange(startSpecifier, specifierLen)); 8560 8561 return true; 8562 } 8563 8564 // Only scalars are allowed for os_trace. 8565 if (FSType == Sema::FST_OSTrace && 8566 (CS.getKind() == ConversionSpecifier::PArg || 8567 CS.getKind() == ConversionSpecifier::sArg || 8568 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8569 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8570 specifierLen); 8571 } 8572 8573 // Check for use of public/private annotation outside of os_log(). 8574 if (FSType != Sema::FST_OSLog) { 8575 if (FS.isPublic().isSet()) { 8576 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8577 << "public", 8578 getLocationOfByte(FS.isPublic().getPosition()), 8579 /*IsStringLocation*/ false, 8580 getSpecifierRange(startSpecifier, specifierLen)); 8581 } 8582 if (FS.isPrivate().isSet()) { 8583 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8584 << "private", 8585 getLocationOfByte(FS.isPrivate().getPosition()), 8586 /*IsStringLocation*/ false, 8587 getSpecifierRange(startSpecifier, specifierLen)); 8588 } 8589 } 8590 8591 // Check for invalid use of field width 8592 if (!FS.hasValidFieldWidth()) { 8593 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8594 startSpecifier, specifierLen); 8595 } 8596 8597 // Check for invalid use of precision 8598 if (!FS.hasValidPrecision()) { 8599 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8600 startSpecifier, specifierLen); 8601 } 8602 8603 // Precision is mandatory for %P specifier. 8604 if (CS.getKind() == ConversionSpecifier::PArg && 8605 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8606 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8607 getLocationOfByte(startSpecifier), 8608 /*IsStringLocation*/ false, 8609 getSpecifierRange(startSpecifier, specifierLen)); 8610 } 8611 8612 // Check each flag does not conflict with any other component. 8613 if (!FS.hasValidThousandsGroupingPrefix()) 8614 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8615 if (!FS.hasValidLeadingZeros()) 8616 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8617 if (!FS.hasValidPlusPrefix()) 8618 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8619 if (!FS.hasValidSpacePrefix()) 8620 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8621 if (!FS.hasValidAlternativeForm()) 8622 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8623 if (!FS.hasValidLeftJustified()) 8624 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8625 8626 // Check that flags are not ignored by another flag 8627 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8628 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8629 startSpecifier, specifierLen); 8630 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8631 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8632 startSpecifier, specifierLen); 8633 8634 // Check the length modifier is valid with the given conversion specifier. 8635 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8636 S.getLangOpts())) 8637 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8638 diag::warn_format_nonsensical_length); 8639 else if (!FS.hasStandardLengthModifier()) 8640 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8641 else if (!FS.hasStandardLengthConversionCombination()) 8642 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8643 diag::warn_format_non_standard_conversion_spec); 8644 8645 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8646 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8647 8648 // The remaining checks depend on the data arguments. 8649 if (HasVAListArg) 8650 return true; 8651 8652 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8653 return false; 8654 8655 const Expr *Arg = getDataArg(argIndex); 8656 if (!Arg) 8657 return true; 8658 8659 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8660 } 8661 8662 static bool requiresParensToAddCast(const Expr *E) { 8663 // FIXME: We should have a general way to reason about operator 8664 // precedence and whether parens are actually needed here. 8665 // Take care of a few common cases where they aren't. 8666 const Expr *Inside = E->IgnoreImpCasts(); 8667 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8668 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8669 8670 switch (Inside->getStmtClass()) { 8671 case Stmt::ArraySubscriptExprClass: 8672 case Stmt::CallExprClass: 8673 case Stmt::CharacterLiteralClass: 8674 case Stmt::CXXBoolLiteralExprClass: 8675 case Stmt::DeclRefExprClass: 8676 case Stmt::FloatingLiteralClass: 8677 case Stmt::IntegerLiteralClass: 8678 case Stmt::MemberExprClass: 8679 case Stmt::ObjCArrayLiteralClass: 8680 case Stmt::ObjCBoolLiteralExprClass: 8681 case Stmt::ObjCBoxedExprClass: 8682 case Stmt::ObjCDictionaryLiteralClass: 8683 case Stmt::ObjCEncodeExprClass: 8684 case Stmt::ObjCIvarRefExprClass: 8685 case Stmt::ObjCMessageExprClass: 8686 case Stmt::ObjCPropertyRefExprClass: 8687 case Stmt::ObjCStringLiteralClass: 8688 case Stmt::ObjCSubscriptRefExprClass: 8689 case Stmt::ParenExprClass: 8690 case Stmt::StringLiteralClass: 8691 case Stmt::UnaryOperatorClass: 8692 return false; 8693 default: 8694 return true; 8695 } 8696 } 8697 8698 static std::pair<QualType, StringRef> 8699 shouldNotPrintDirectly(const ASTContext &Context, 8700 QualType IntendedTy, 8701 const Expr *E) { 8702 // Use a 'while' to peel off layers of typedefs. 8703 QualType TyTy = IntendedTy; 8704 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8705 StringRef Name = UserTy->getDecl()->getName(); 8706 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8707 .Case("CFIndex", Context.getNSIntegerType()) 8708 .Case("NSInteger", Context.getNSIntegerType()) 8709 .Case("NSUInteger", Context.getNSUIntegerType()) 8710 .Case("SInt32", Context.IntTy) 8711 .Case("UInt32", Context.UnsignedIntTy) 8712 .Default(QualType()); 8713 8714 if (!CastTy.isNull()) 8715 return std::make_pair(CastTy, Name); 8716 8717 TyTy = UserTy->desugar(); 8718 } 8719 8720 // Strip parens if necessary. 8721 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8722 return shouldNotPrintDirectly(Context, 8723 PE->getSubExpr()->getType(), 8724 PE->getSubExpr()); 8725 8726 // If this is a conditional expression, then its result type is constructed 8727 // via usual arithmetic conversions and thus there might be no necessary 8728 // typedef sugar there. Recurse to operands to check for NSInteger & 8729 // Co. usage condition. 8730 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8731 QualType TrueTy, FalseTy; 8732 StringRef TrueName, FalseName; 8733 8734 std::tie(TrueTy, TrueName) = 8735 shouldNotPrintDirectly(Context, 8736 CO->getTrueExpr()->getType(), 8737 CO->getTrueExpr()); 8738 std::tie(FalseTy, FalseName) = 8739 shouldNotPrintDirectly(Context, 8740 CO->getFalseExpr()->getType(), 8741 CO->getFalseExpr()); 8742 8743 if (TrueTy == FalseTy) 8744 return std::make_pair(TrueTy, TrueName); 8745 else if (TrueTy.isNull()) 8746 return std::make_pair(FalseTy, FalseName); 8747 else if (FalseTy.isNull()) 8748 return std::make_pair(TrueTy, TrueName); 8749 } 8750 8751 return std::make_pair(QualType(), StringRef()); 8752 } 8753 8754 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8755 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8756 /// type do not count. 8757 static bool 8758 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8759 QualType From = ICE->getSubExpr()->getType(); 8760 QualType To = ICE->getType(); 8761 // It's an integer promotion if the destination type is the promoted 8762 // source type. 8763 if (ICE->getCastKind() == CK_IntegralCast && 8764 From->isPromotableIntegerType() && 8765 S.Context.getPromotedIntegerType(From) == To) 8766 return true; 8767 // Look through vector types, since we do default argument promotion for 8768 // those in OpenCL. 8769 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8770 From = VecTy->getElementType(); 8771 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8772 To = VecTy->getElementType(); 8773 // It's a floating promotion if the source type is a lower rank. 8774 return ICE->getCastKind() == CK_FloatingCast && 8775 S.Context.getFloatingTypeOrder(From, To) < 0; 8776 } 8777 8778 bool 8779 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8780 const char *StartSpecifier, 8781 unsigned SpecifierLen, 8782 const Expr *E) { 8783 using namespace analyze_format_string; 8784 using namespace analyze_printf; 8785 8786 // Now type check the data expression that matches the 8787 // format specifier. 8788 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8789 if (!AT.isValid()) 8790 return true; 8791 8792 QualType ExprTy = E->getType(); 8793 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8794 ExprTy = TET->getUnderlyingExpr()->getType(); 8795 } 8796 8797 // Diagnose attempts to print a boolean value as a character. Unlike other 8798 // -Wformat diagnostics, this is fine from a type perspective, but it still 8799 // doesn't make sense. 8800 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8801 E->isKnownToHaveBooleanValue()) { 8802 const CharSourceRange &CSR = 8803 getSpecifierRange(StartSpecifier, SpecifierLen); 8804 SmallString<4> FSString; 8805 llvm::raw_svector_ostream os(FSString); 8806 FS.toString(os); 8807 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8808 << FSString, 8809 E->getExprLoc(), false, CSR); 8810 return true; 8811 } 8812 8813 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8814 if (Match == analyze_printf::ArgType::Match) 8815 return true; 8816 8817 // Look through argument promotions for our error message's reported type. 8818 // This includes the integral and floating promotions, but excludes array 8819 // and function pointer decay (seeing that an argument intended to be a 8820 // string has type 'char [6]' is probably more confusing than 'char *') and 8821 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8822 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8823 if (isArithmeticArgumentPromotion(S, ICE)) { 8824 E = ICE->getSubExpr(); 8825 ExprTy = E->getType(); 8826 8827 // Check if we didn't match because of an implicit cast from a 'char' 8828 // or 'short' to an 'int'. This is done because printf is a varargs 8829 // function. 8830 if (ICE->getType() == S.Context.IntTy || 8831 ICE->getType() == S.Context.UnsignedIntTy) { 8832 // All further checking is done on the subexpression 8833 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8834 AT.matchesType(S.Context, ExprTy); 8835 if (ImplicitMatch == analyze_printf::ArgType::Match) 8836 return true; 8837 if (ImplicitMatch == ArgType::NoMatchPedantic || 8838 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8839 Match = ImplicitMatch; 8840 } 8841 } 8842 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8843 // Special case for 'a', which has type 'int' in C. 8844 // Note, however, that we do /not/ want to treat multibyte constants like 8845 // 'MooV' as characters! This form is deprecated but still exists. In 8846 // addition, don't treat expressions as of type 'char' if one byte length 8847 // modifier is provided. 8848 if (ExprTy == S.Context.IntTy && 8849 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 8850 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8851 ExprTy = S.Context.CharTy; 8852 } 8853 8854 // Look through enums to their underlying type. 8855 bool IsEnum = false; 8856 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8857 ExprTy = EnumTy->getDecl()->getIntegerType(); 8858 IsEnum = true; 8859 } 8860 8861 // %C in an Objective-C context prints a unichar, not a wchar_t. 8862 // If the argument is an integer of some kind, believe the %C and suggest 8863 // a cast instead of changing the conversion specifier. 8864 QualType IntendedTy = ExprTy; 8865 if (isObjCContext() && 8866 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8867 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8868 !ExprTy->isCharType()) { 8869 // 'unichar' is defined as a typedef of unsigned short, but we should 8870 // prefer using the typedef if it is visible. 8871 IntendedTy = S.Context.UnsignedShortTy; 8872 8873 // While we are here, check if the value is an IntegerLiteral that happens 8874 // to be within the valid range. 8875 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8876 const llvm::APInt &V = IL->getValue(); 8877 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8878 return true; 8879 } 8880 8881 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8882 Sema::LookupOrdinaryName); 8883 if (S.LookupName(Result, S.getCurScope())) { 8884 NamedDecl *ND = Result.getFoundDecl(); 8885 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8886 if (TD->getUnderlyingType() == IntendedTy) 8887 IntendedTy = S.Context.getTypedefType(TD); 8888 } 8889 } 8890 } 8891 8892 // Special-case some of Darwin's platform-independence types by suggesting 8893 // casts to primitive types that are known to be large enough. 8894 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8895 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8896 QualType CastTy; 8897 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8898 if (!CastTy.isNull()) { 8899 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8900 // (long in ASTContext). Only complain to pedants. 8901 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8902 (AT.isSizeT() || AT.isPtrdiffT()) && 8903 AT.matchesType(S.Context, CastTy)) 8904 Match = ArgType::NoMatchPedantic; 8905 IntendedTy = CastTy; 8906 ShouldNotPrintDirectly = true; 8907 } 8908 } 8909 8910 // We may be able to offer a FixItHint if it is a supported type. 8911 PrintfSpecifier fixedFS = FS; 8912 bool Success = 8913 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8914 8915 if (Success) { 8916 // Get the fix string from the fixed format specifier 8917 SmallString<16> buf; 8918 llvm::raw_svector_ostream os(buf); 8919 fixedFS.toString(os); 8920 8921 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8922 8923 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8924 unsigned Diag; 8925 switch (Match) { 8926 case ArgType::Match: llvm_unreachable("expected non-matching"); 8927 case ArgType::NoMatchPedantic: 8928 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8929 break; 8930 case ArgType::NoMatchTypeConfusion: 8931 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8932 break; 8933 case ArgType::NoMatch: 8934 Diag = diag::warn_format_conversion_argument_type_mismatch; 8935 break; 8936 } 8937 8938 // In this case, the specifier is wrong and should be changed to match 8939 // the argument. 8940 EmitFormatDiagnostic(S.PDiag(Diag) 8941 << AT.getRepresentativeTypeName(S.Context) 8942 << IntendedTy << IsEnum << E->getSourceRange(), 8943 E->getBeginLoc(), 8944 /*IsStringLocation*/ false, SpecRange, 8945 FixItHint::CreateReplacement(SpecRange, os.str())); 8946 } else { 8947 // The canonical type for formatting this value is different from the 8948 // actual type of the expression. (This occurs, for example, with Darwin's 8949 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8950 // should be printed as 'long' for 64-bit compatibility.) 8951 // Rather than emitting a normal format/argument mismatch, we want to 8952 // add a cast to the recommended type (and correct the format string 8953 // if necessary). 8954 SmallString<16> CastBuf; 8955 llvm::raw_svector_ostream CastFix(CastBuf); 8956 CastFix << "("; 8957 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8958 CastFix << ")"; 8959 8960 SmallVector<FixItHint,4> Hints; 8961 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8962 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8963 8964 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8965 // If there's already a cast present, just replace it. 8966 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8967 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8968 8969 } else if (!requiresParensToAddCast(E)) { 8970 // If the expression has high enough precedence, 8971 // just write the C-style cast. 8972 Hints.push_back( 8973 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8974 } else { 8975 // Otherwise, add parens around the expression as well as the cast. 8976 CastFix << "("; 8977 Hints.push_back( 8978 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8979 8980 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8981 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8982 } 8983 8984 if (ShouldNotPrintDirectly) { 8985 // The expression has a type that should not be printed directly. 8986 // We extract the name from the typedef because we don't want to show 8987 // the underlying type in the diagnostic. 8988 StringRef Name; 8989 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8990 Name = TypedefTy->getDecl()->getName(); 8991 else 8992 Name = CastTyName; 8993 unsigned Diag = Match == ArgType::NoMatchPedantic 8994 ? diag::warn_format_argument_needs_cast_pedantic 8995 : diag::warn_format_argument_needs_cast; 8996 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8997 << E->getSourceRange(), 8998 E->getBeginLoc(), /*IsStringLocation=*/false, 8999 SpecRange, Hints); 9000 } else { 9001 // In this case, the expression could be printed using a different 9002 // specifier, but we've decided that the specifier is probably correct 9003 // and we should cast instead. Just use the normal warning message. 9004 EmitFormatDiagnostic( 9005 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9006 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9007 << E->getSourceRange(), 9008 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9009 } 9010 } 9011 } else { 9012 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9013 SpecifierLen); 9014 // Since the warning for passing non-POD types to variadic functions 9015 // was deferred until now, we emit a warning for non-POD 9016 // arguments here. 9017 switch (S.isValidVarArgType(ExprTy)) { 9018 case Sema::VAK_Valid: 9019 case Sema::VAK_ValidInCXX11: { 9020 unsigned Diag; 9021 switch (Match) { 9022 case ArgType::Match: llvm_unreachable("expected non-matching"); 9023 case ArgType::NoMatchPedantic: 9024 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9025 break; 9026 case ArgType::NoMatchTypeConfusion: 9027 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9028 break; 9029 case ArgType::NoMatch: 9030 Diag = diag::warn_format_conversion_argument_type_mismatch; 9031 break; 9032 } 9033 9034 EmitFormatDiagnostic( 9035 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9036 << IsEnum << CSR << E->getSourceRange(), 9037 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9038 break; 9039 } 9040 case Sema::VAK_Undefined: 9041 case Sema::VAK_MSVCUndefined: 9042 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9043 << S.getLangOpts().CPlusPlus11 << ExprTy 9044 << CallType 9045 << AT.getRepresentativeTypeName(S.Context) << CSR 9046 << E->getSourceRange(), 9047 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9048 checkForCStrMembers(AT, E); 9049 break; 9050 9051 case Sema::VAK_Invalid: 9052 if (ExprTy->isObjCObjectType()) 9053 EmitFormatDiagnostic( 9054 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9055 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9056 << AT.getRepresentativeTypeName(S.Context) << CSR 9057 << E->getSourceRange(), 9058 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9059 else 9060 // FIXME: If this is an initializer list, suggest removing the braces 9061 // or inserting a cast to the target type. 9062 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9063 << isa<InitListExpr>(E) << ExprTy << CallType 9064 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9065 break; 9066 } 9067 9068 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9069 "format string specifier index out of range"); 9070 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9071 } 9072 9073 return true; 9074 } 9075 9076 //===--- CHECK: Scanf format string checking ------------------------------===// 9077 9078 namespace { 9079 9080 class CheckScanfHandler : public CheckFormatHandler { 9081 public: 9082 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9083 const Expr *origFormatExpr, Sema::FormatStringType type, 9084 unsigned firstDataArg, unsigned numDataArgs, 9085 const char *beg, bool hasVAListArg, 9086 ArrayRef<const Expr *> Args, unsigned formatIdx, 9087 bool inFunctionCall, Sema::VariadicCallType CallType, 9088 llvm::SmallBitVector &CheckedVarArgs, 9089 UncoveredArgHandler &UncoveredArg) 9090 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9091 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9092 inFunctionCall, CallType, CheckedVarArgs, 9093 UncoveredArg) {} 9094 9095 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9096 const char *startSpecifier, 9097 unsigned specifierLen) override; 9098 9099 bool HandleInvalidScanfConversionSpecifier( 9100 const analyze_scanf::ScanfSpecifier &FS, 9101 const char *startSpecifier, 9102 unsigned specifierLen) override; 9103 9104 void HandleIncompleteScanList(const char *start, const char *end) override; 9105 }; 9106 9107 } // namespace 9108 9109 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9110 const char *end) { 9111 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9112 getLocationOfByte(end), /*IsStringLocation*/true, 9113 getSpecifierRange(start, end - start)); 9114 } 9115 9116 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9117 const analyze_scanf::ScanfSpecifier &FS, 9118 const char *startSpecifier, 9119 unsigned specifierLen) { 9120 const analyze_scanf::ScanfConversionSpecifier &CS = 9121 FS.getConversionSpecifier(); 9122 9123 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9124 getLocationOfByte(CS.getStart()), 9125 startSpecifier, specifierLen, 9126 CS.getStart(), CS.getLength()); 9127 } 9128 9129 bool CheckScanfHandler::HandleScanfSpecifier( 9130 const analyze_scanf::ScanfSpecifier &FS, 9131 const char *startSpecifier, 9132 unsigned specifierLen) { 9133 using namespace analyze_scanf; 9134 using namespace analyze_format_string; 9135 9136 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9137 9138 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9139 // be used to decide if we are using positional arguments consistently. 9140 if (FS.consumesDataArgument()) { 9141 if (atFirstArg) { 9142 atFirstArg = false; 9143 usesPositionalArgs = FS.usesPositionalArg(); 9144 } 9145 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9146 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9147 startSpecifier, specifierLen); 9148 return false; 9149 } 9150 } 9151 9152 // Check if the field with is non-zero. 9153 const OptionalAmount &Amt = FS.getFieldWidth(); 9154 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9155 if (Amt.getConstantAmount() == 0) { 9156 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9157 Amt.getConstantLength()); 9158 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9159 getLocationOfByte(Amt.getStart()), 9160 /*IsStringLocation*/true, R, 9161 FixItHint::CreateRemoval(R)); 9162 } 9163 } 9164 9165 if (!FS.consumesDataArgument()) { 9166 // FIXME: Technically specifying a precision or field width here 9167 // makes no sense. Worth issuing a warning at some point. 9168 return true; 9169 } 9170 9171 // Consume the argument. 9172 unsigned argIndex = FS.getArgIndex(); 9173 if (argIndex < NumDataArgs) { 9174 // The check to see if the argIndex is valid will come later. 9175 // We set the bit here because we may exit early from this 9176 // function if we encounter some other error. 9177 CoveredArgs.set(argIndex); 9178 } 9179 9180 // Check the length modifier is valid with the given conversion specifier. 9181 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9182 S.getLangOpts())) 9183 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9184 diag::warn_format_nonsensical_length); 9185 else if (!FS.hasStandardLengthModifier()) 9186 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9187 else if (!FS.hasStandardLengthConversionCombination()) 9188 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9189 diag::warn_format_non_standard_conversion_spec); 9190 9191 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9192 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9193 9194 // The remaining checks depend on the data arguments. 9195 if (HasVAListArg) 9196 return true; 9197 9198 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9199 return false; 9200 9201 // Check that the argument type matches the format specifier. 9202 const Expr *Ex = getDataArg(argIndex); 9203 if (!Ex) 9204 return true; 9205 9206 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9207 9208 if (!AT.isValid()) { 9209 return true; 9210 } 9211 9212 analyze_format_string::ArgType::MatchKind Match = 9213 AT.matchesType(S.Context, Ex->getType()); 9214 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9215 if (Match == analyze_format_string::ArgType::Match) 9216 return true; 9217 9218 ScanfSpecifier fixedFS = FS; 9219 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9220 S.getLangOpts(), S.Context); 9221 9222 unsigned Diag = 9223 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9224 : diag::warn_format_conversion_argument_type_mismatch; 9225 9226 if (Success) { 9227 // Get the fix string from the fixed format specifier. 9228 SmallString<128> buf; 9229 llvm::raw_svector_ostream os(buf); 9230 fixedFS.toString(os); 9231 9232 EmitFormatDiagnostic( 9233 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9234 << Ex->getType() << false << Ex->getSourceRange(), 9235 Ex->getBeginLoc(), 9236 /*IsStringLocation*/ false, 9237 getSpecifierRange(startSpecifier, specifierLen), 9238 FixItHint::CreateReplacement( 9239 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9240 } else { 9241 EmitFormatDiagnostic(S.PDiag(Diag) 9242 << AT.getRepresentativeTypeName(S.Context) 9243 << Ex->getType() << false << Ex->getSourceRange(), 9244 Ex->getBeginLoc(), 9245 /*IsStringLocation*/ false, 9246 getSpecifierRange(startSpecifier, specifierLen)); 9247 } 9248 9249 return true; 9250 } 9251 9252 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9253 const Expr *OrigFormatExpr, 9254 ArrayRef<const Expr *> Args, 9255 bool HasVAListArg, unsigned format_idx, 9256 unsigned firstDataArg, 9257 Sema::FormatStringType Type, 9258 bool inFunctionCall, 9259 Sema::VariadicCallType CallType, 9260 llvm::SmallBitVector &CheckedVarArgs, 9261 UncoveredArgHandler &UncoveredArg, 9262 bool IgnoreStringsWithoutSpecifiers) { 9263 // CHECK: is the format string a wide literal? 9264 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9265 CheckFormatHandler::EmitFormatDiagnostic( 9266 S, inFunctionCall, Args[format_idx], 9267 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9268 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9269 return; 9270 } 9271 9272 // Str - The format string. NOTE: this is NOT null-terminated! 9273 StringRef StrRef = FExpr->getString(); 9274 const char *Str = StrRef.data(); 9275 // Account for cases where the string literal is truncated in a declaration. 9276 const ConstantArrayType *T = 9277 S.Context.getAsConstantArrayType(FExpr->getType()); 9278 assert(T && "String literal not of constant array type!"); 9279 size_t TypeSize = T->getSize().getZExtValue(); 9280 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9281 const unsigned numDataArgs = Args.size() - firstDataArg; 9282 9283 if (IgnoreStringsWithoutSpecifiers && 9284 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9285 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9286 return; 9287 9288 // Emit a warning if the string literal is truncated and does not contain an 9289 // embedded null character. 9290 if (TypeSize <= StrRef.size() && 9291 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9292 CheckFormatHandler::EmitFormatDiagnostic( 9293 S, inFunctionCall, Args[format_idx], 9294 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9295 FExpr->getBeginLoc(), 9296 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9297 return; 9298 } 9299 9300 // CHECK: empty format string? 9301 if (StrLen == 0 && numDataArgs > 0) { 9302 CheckFormatHandler::EmitFormatDiagnostic( 9303 S, inFunctionCall, Args[format_idx], 9304 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9305 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9306 return; 9307 } 9308 9309 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9310 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9311 Type == Sema::FST_OSTrace) { 9312 CheckPrintfHandler H( 9313 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9314 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9315 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9316 CheckedVarArgs, UncoveredArg); 9317 9318 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9319 S.getLangOpts(), 9320 S.Context.getTargetInfo(), 9321 Type == Sema::FST_FreeBSDKPrintf)) 9322 H.DoneProcessing(); 9323 } else if (Type == Sema::FST_Scanf) { 9324 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9325 numDataArgs, Str, HasVAListArg, Args, format_idx, 9326 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9327 9328 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9329 S.getLangOpts(), 9330 S.Context.getTargetInfo())) 9331 H.DoneProcessing(); 9332 } // TODO: handle other formats 9333 } 9334 9335 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9336 // Str - The format string. NOTE: this is NOT null-terminated! 9337 StringRef StrRef = FExpr->getString(); 9338 const char *Str = StrRef.data(); 9339 // Account for cases where the string literal is truncated in a declaration. 9340 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9341 assert(T && "String literal not of constant array type!"); 9342 size_t TypeSize = T->getSize().getZExtValue(); 9343 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9344 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9345 getLangOpts(), 9346 Context.getTargetInfo()); 9347 } 9348 9349 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9350 9351 // Returns the related absolute value function that is larger, of 0 if one 9352 // does not exist. 9353 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9354 switch (AbsFunction) { 9355 default: 9356 return 0; 9357 9358 case Builtin::BI__builtin_abs: 9359 return Builtin::BI__builtin_labs; 9360 case Builtin::BI__builtin_labs: 9361 return Builtin::BI__builtin_llabs; 9362 case Builtin::BI__builtin_llabs: 9363 return 0; 9364 9365 case Builtin::BI__builtin_fabsf: 9366 return Builtin::BI__builtin_fabs; 9367 case Builtin::BI__builtin_fabs: 9368 return Builtin::BI__builtin_fabsl; 9369 case Builtin::BI__builtin_fabsl: 9370 return 0; 9371 9372 case Builtin::BI__builtin_cabsf: 9373 return Builtin::BI__builtin_cabs; 9374 case Builtin::BI__builtin_cabs: 9375 return Builtin::BI__builtin_cabsl; 9376 case Builtin::BI__builtin_cabsl: 9377 return 0; 9378 9379 case Builtin::BIabs: 9380 return Builtin::BIlabs; 9381 case Builtin::BIlabs: 9382 return Builtin::BIllabs; 9383 case Builtin::BIllabs: 9384 return 0; 9385 9386 case Builtin::BIfabsf: 9387 return Builtin::BIfabs; 9388 case Builtin::BIfabs: 9389 return Builtin::BIfabsl; 9390 case Builtin::BIfabsl: 9391 return 0; 9392 9393 case Builtin::BIcabsf: 9394 return Builtin::BIcabs; 9395 case Builtin::BIcabs: 9396 return Builtin::BIcabsl; 9397 case Builtin::BIcabsl: 9398 return 0; 9399 } 9400 } 9401 9402 // Returns the argument type of the absolute value function. 9403 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9404 unsigned AbsType) { 9405 if (AbsType == 0) 9406 return QualType(); 9407 9408 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9409 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9410 if (Error != ASTContext::GE_None) 9411 return QualType(); 9412 9413 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9414 if (!FT) 9415 return QualType(); 9416 9417 if (FT->getNumParams() != 1) 9418 return QualType(); 9419 9420 return FT->getParamType(0); 9421 } 9422 9423 // Returns the best absolute value function, or zero, based on type and 9424 // current absolute value function. 9425 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9426 unsigned AbsFunctionKind) { 9427 unsigned BestKind = 0; 9428 uint64_t ArgSize = Context.getTypeSize(ArgType); 9429 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9430 Kind = getLargerAbsoluteValueFunction(Kind)) { 9431 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9432 if (Context.getTypeSize(ParamType) >= ArgSize) { 9433 if (BestKind == 0) 9434 BestKind = Kind; 9435 else if (Context.hasSameType(ParamType, ArgType)) { 9436 BestKind = Kind; 9437 break; 9438 } 9439 } 9440 } 9441 return BestKind; 9442 } 9443 9444 enum AbsoluteValueKind { 9445 AVK_Integer, 9446 AVK_Floating, 9447 AVK_Complex 9448 }; 9449 9450 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9451 if (T->isIntegralOrEnumerationType()) 9452 return AVK_Integer; 9453 if (T->isRealFloatingType()) 9454 return AVK_Floating; 9455 if (T->isAnyComplexType()) 9456 return AVK_Complex; 9457 9458 llvm_unreachable("Type not integer, floating, or complex"); 9459 } 9460 9461 // Changes the absolute value function to a different type. Preserves whether 9462 // the function is a builtin. 9463 static unsigned changeAbsFunction(unsigned AbsKind, 9464 AbsoluteValueKind ValueKind) { 9465 switch (ValueKind) { 9466 case AVK_Integer: 9467 switch (AbsKind) { 9468 default: 9469 return 0; 9470 case Builtin::BI__builtin_fabsf: 9471 case Builtin::BI__builtin_fabs: 9472 case Builtin::BI__builtin_fabsl: 9473 case Builtin::BI__builtin_cabsf: 9474 case Builtin::BI__builtin_cabs: 9475 case Builtin::BI__builtin_cabsl: 9476 return Builtin::BI__builtin_abs; 9477 case Builtin::BIfabsf: 9478 case Builtin::BIfabs: 9479 case Builtin::BIfabsl: 9480 case Builtin::BIcabsf: 9481 case Builtin::BIcabs: 9482 case Builtin::BIcabsl: 9483 return Builtin::BIabs; 9484 } 9485 case AVK_Floating: 9486 switch (AbsKind) { 9487 default: 9488 return 0; 9489 case Builtin::BI__builtin_abs: 9490 case Builtin::BI__builtin_labs: 9491 case Builtin::BI__builtin_llabs: 9492 case Builtin::BI__builtin_cabsf: 9493 case Builtin::BI__builtin_cabs: 9494 case Builtin::BI__builtin_cabsl: 9495 return Builtin::BI__builtin_fabsf; 9496 case Builtin::BIabs: 9497 case Builtin::BIlabs: 9498 case Builtin::BIllabs: 9499 case Builtin::BIcabsf: 9500 case Builtin::BIcabs: 9501 case Builtin::BIcabsl: 9502 return Builtin::BIfabsf; 9503 } 9504 case AVK_Complex: 9505 switch (AbsKind) { 9506 default: 9507 return 0; 9508 case Builtin::BI__builtin_abs: 9509 case Builtin::BI__builtin_labs: 9510 case Builtin::BI__builtin_llabs: 9511 case Builtin::BI__builtin_fabsf: 9512 case Builtin::BI__builtin_fabs: 9513 case Builtin::BI__builtin_fabsl: 9514 return Builtin::BI__builtin_cabsf; 9515 case Builtin::BIabs: 9516 case Builtin::BIlabs: 9517 case Builtin::BIllabs: 9518 case Builtin::BIfabsf: 9519 case Builtin::BIfabs: 9520 case Builtin::BIfabsl: 9521 return Builtin::BIcabsf; 9522 } 9523 } 9524 llvm_unreachable("Unable to convert function"); 9525 } 9526 9527 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9528 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9529 if (!FnInfo) 9530 return 0; 9531 9532 switch (FDecl->getBuiltinID()) { 9533 default: 9534 return 0; 9535 case Builtin::BI__builtin_abs: 9536 case Builtin::BI__builtin_fabs: 9537 case Builtin::BI__builtin_fabsf: 9538 case Builtin::BI__builtin_fabsl: 9539 case Builtin::BI__builtin_labs: 9540 case Builtin::BI__builtin_llabs: 9541 case Builtin::BI__builtin_cabs: 9542 case Builtin::BI__builtin_cabsf: 9543 case Builtin::BI__builtin_cabsl: 9544 case Builtin::BIabs: 9545 case Builtin::BIlabs: 9546 case Builtin::BIllabs: 9547 case Builtin::BIfabs: 9548 case Builtin::BIfabsf: 9549 case Builtin::BIfabsl: 9550 case Builtin::BIcabs: 9551 case Builtin::BIcabsf: 9552 case Builtin::BIcabsl: 9553 return FDecl->getBuiltinID(); 9554 } 9555 llvm_unreachable("Unknown Builtin type"); 9556 } 9557 9558 // If the replacement is valid, emit a note with replacement function. 9559 // Additionally, suggest including the proper header if not already included. 9560 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9561 unsigned AbsKind, QualType ArgType) { 9562 bool EmitHeaderHint = true; 9563 const char *HeaderName = nullptr; 9564 const char *FunctionName = nullptr; 9565 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9566 FunctionName = "std::abs"; 9567 if (ArgType->isIntegralOrEnumerationType()) { 9568 HeaderName = "cstdlib"; 9569 } else if (ArgType->isRealFloatingType()) { 9570 HeaderName = "cmath"; 9571 } else { 9572 llvm_unreachable("Invalid Type"); 9573 } 9574 9575 // Lookup all std::abs 9576 if (NamespaceDecl *Std = S.getStdNamespace()) { 9577 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9578 R.suppressDiagnostics(); 9579 S.LookupQualifiedName(R, Std); 9580 9581 for (const auto *I : R) { 9582 const FunctionDecl *FDecl = nullptr; 9583 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9584 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9585 } else { 9586 FDecl = dyn_cast<FunctionDecl>(I); 9587 } 9588 if (!FDecl) 9589 continue; 9590 9591 // Found std::abs(), check that they are the right ones. 9592 if (FDecl->getNumParams() != 1) 9593 continue; 9594 9595 // Check that the parameter type can handle the argument. 9596 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9597 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9598 S.Context.getTypeSize(ArgType) <= 9599 S.Context.getTypeSize(ParamType)) { 9600 // Found a function, don't need the header hint. 9601 EmitHeaderHint = false; 9602 break; 9603 } 9604 } 9605 } 9606 } else { 9607 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9608 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9609 9610 if (HeaderName) { 9611 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9612 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9613 R.suppressDiagnostics(); 9614 S.LookupName(R, S.getCurScope()); 9615 9616 if (R.isSingleResult()) { 9617 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9618 if (FD && FD->getBuiltinID() == AbsKind) { 9619 EmitHeaderHint = false; 9620 } else { 9621 return; 9622 } 9623 } else if (!R.empty()) { 9624 return; 9625 } 9626 } 9627 } 9628 9629 S.Diag(Loc, diag::note_replace_abs_function) 9630 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9631 9632 if (!HeaderName) 9633 return; 9634 9635 if (!EmitHeaderHint) 9636 return; 9637 9638 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9639 << FunctionName; 9640 } 9641 9642 template <std::size_t StrLen> 9643 static bool IsStdFunction(const FunctionDecl *FDecl, 9644 const char (&Str)[StrLen]) { 9645 if (!FDecl) 9646 return false; 9647 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9648 return false; 9649 if (!FDecl->isInStdNamespace()) 9650 return false; 9651 9652 return true; 9653 } 9654 9655 // Warn when using the wrong abs() function. 9656 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9657 const FunctionDecl *FDecl) { 9658 if (Call->getNumArgs() != 1) 9659 return; 9660 9661 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9662 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9663 if (AbsKind == 0 && !IsStdAbs) 9664 return; 9665 9666 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9667 QualType ParamType = Call->getArg(0)->getType(); 9668 9669 // Unsigned types cannot be negative. Suggest removing the absolute value 9670 // function call. 9671 if (ArgType->isUnsignedIntegerType()) { 9672 const char *FunctionName = 9673 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9674 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9675 Diag(Call->getExprLoc(), diag::note_remove_abs) 9676 << FunctionName 9677 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9678 return; 9679 } 9680 9681 // Taking the absolute value of a pointer is very suspicious, they probably 9682 // wanted to index into an array, dereference a pointer, call a function, etc. 9683 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9684 unsigned DiagType = 0; 9685 if (ArgType->isFunctionType()) 9686 DiagType = 1; 9687 else if (ArgType->isArrayType()) 9688 DiagType = 2; 9689 9690 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9691 return; 9692 } 9693 9694 // std::abs has overloads which prevent most of the absolute value problems 9695 // from occurring. 9696 if (IsStdAbs) 9697 return; 9698 9699 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9700 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9701 9702 // The argument and parameter are the same kind. Check if they are the right 9703 // size. 9704 if (ArgValueKind == ParamValueKind) { 9705 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9706 return; 9707 9708 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9709 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9710 << FDecl << ArgType << ParamType; 9711 9712 if (NewAbsKind == 0) 9713 return; 9714 9715 emitReplacement(*this, Call->getExprLoc(), 9716 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9717 return; 9718 } 9719 9720 // ArgValueKind != ParamValueKind 9721 // The wrong type of absolute value function was used. Attempt to find the 9722 // proper one. 9723 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9724 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9725 if (NewAbsKind == 0) 9726 return; 9727 9728 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9729 << FDecl << ParamValueKind << ArgValueKind; 9730 9731 emitReplacement(*this, Call->getExprLoc(), 9732 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9733 } 9734 9735 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9736 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9737 const FunctionDecl *FDecl) { 9738 if (!Call || !FDecl) return; 9739 9740 // Ignore template specializations and macros. 9741 if (inTemplateInstantiation()) return; 9742 if (Call->getExprLoc().isMacroID()) return; 9743 9744 // Only care about the one template argument, two function parameter std::max 9745 if (Call->getNumArgs() != 2) return; 9746 if (!IsStdFunction(FDecl, "max")) return; 9747 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9748 if (!ArgList) return; 9749 if (ArgList->size() != 1) return; 9750 9751 // Check that template type argument is unsigned integer. 9752 const auto& TA = ArgList->get(0); 9753 if (TA.getKind() != TemplateArgument::Type) return; 9754 QualType ArgType = TA.getAsType(); 9755 if (!ArgType->isUnsignedIntegerType()) return; 9756 9757 // See if either argument is a literal zero. 9758 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9759 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9760 if (!MTE) return false; 9761 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9762 if (!Num) return false; 9763 if (Num->getValue() != 0) return false; 9764 return true; 9765 }; 9766 9767 const Expr *FirstArg = Call->getArg(0); 9768 const Expr *SecondArg = Call->getArg(1); 9769 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9770 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9771 9772 // Only warn when exactly one argument is zero. 9773 if (IsFirstArgZero == IsSecondArgZero) return; 9774 9775 SourceRange FirstRange = FirstArg->getSourceRange(); 9776 SourceRange SecondRange = SecondArg->getSourceRange(); 9777 9778 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9779 9780 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9781 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9782 9783 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9784 SourceRange RemovalRange; 9785 if (IsFirstArgZero) { 9786 RemovalRange = SourceRange(FirstRange.getBegin(), 9787 SecondRange.getBegin().getLocWithOffset(-1)); 9788 } else { 9789 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9790 SecondRange.getEnd()); 9791 } 9792 9793 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9794 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9795 << FixItHint::CreateRemoval(RemovalRange); 9796 } 9797 9798 //===--- CHECK: Standard memory functions ---------------------------------===// 9799 9800 /// Takes the expression passed to the size_t parameter of functions 9801 /// such as memcmp, strncat, etc and warns if it's a comparison. 9802 /// 9803 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9804 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9805 IdentifierInfo *FnName, 9806 SourceLocation FnLoc, 9807 SourceLocation RParenLoc) { 9808 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9809 if (!Size) 9810 return false; 9811 9812 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9813 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9814 return false; 9815 9816 SourceRange SizeRange = Size->getSourceRange(); 9817 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9818 << SizeRange << FnName; 9819 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9820 << FnName 9821 << FixItHint::CreateInsertion( 9822 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9823 << FixItHint::CreateRemoval(RParenLoc); 9824 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9825 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9826 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9827 ")"); 9828 9829 return true; 9830 } 9831 9832 /// Determine whether the given type is or contains a dynamic class type 9833 /// (e.g., whether it has a vtable). 9834 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9835 bool &IsContained) { 9836 // Look through array types while ignoring qualifiers. 9837 const Type *Ty = T->getBaseElementTypeUnsafe(); 9838 IsContained = false; 9839 9840 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9841 RD = RD ? RD->getDefinition() : nullptr; 9842 if (!RD || RD->isInvalidDecl()) 9843 return nullptr; 9844 9845 if (RD->isDynamicClass()) 9846 return RD; 9847 9848 // Check all the fields. If any bases were dynamic, the class is dynamic. 9849 // It's impossible for a class to transitively contain itself by value, so 9850 // infinite recursion is impossible. 9851 for (auto *FD : RD->fields()) { 9852 bool SubContained; 9853 if (const CXXRecordDecl *ContainedRD = 9854 getContainedDynamicClass(FD->getType(), SubContained)) { 9855 IsContained = true; 9856 return ContainedRD; 9857 } 9858 } 9859 9860 return nullptr; 9861 } 9862 9863 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9864 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9865 if (Unary->getKind() == UETT_SizeOf) 9866 return Unary; 9867 return nullptr; 9868 } 9869 9870 /// If E is a sizeof expression, returns its argument expression, 9871 /// otherwise returns NULL. 9872 static const Expr *getSizeOfExprArg(const Expr *E) { 9873 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9874 if (!SizeOf->isArgumentType()) 9875 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9876 return nullptr; 9877 } 9878 9879 /// If E is a sizeof expression, returns its argument type. 9880 static QualType getSizeOfArgType(const Expr *E) { 9881 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9882 return SizeOf->getTypeOfArgument(); 9883 return QualType(); 9884 } 9885 9886 namespace { 9887 9888 struct SearchNonTrivialToInitializeField 9889 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9890 using Super = 9891 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9892 9893 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9894 9895 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9896 SourceLocation SL) { 9897 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9898 asDerived().visitArray(PDIK, AT, SL); 9899 return; 9900 } 9901 9902 Super::visitWithKind(PDIK, FT, SL); 9903 } 9904 9905 void visitARCStrong(QualType FT, SourceLocation SL) { 9906 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9907 } 9908 void visitARCWeak(QualType FT, SourceLocation SL) { 9909 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9910 } 9911 void visitStruct(QualType FT, SourceLocation SL) { 9912 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9913 visit(FD->getType(), FD->getLocation()); 9914 } 9915 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9916 const ArrayType *AT, SourceLocation SL) { 9917 visit(getContext().getBaseElementType(AT), SL); 9918 } 9919 void visitTrivial(QualType FT, SourceLocation SL) {} 9920 9921 static void diag(QualType RT, const Expr *E, Sema &S) { 9922 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9923 } 9924 9925 ASTContext &getContext() { return S.getASTContext(); } 9926 9927 const Expr *E; 9928 Sema &S; 9929 }; 9930 9931 struct SearchNonTrivialToCopyField 9932 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9933 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9934 9935 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9936 9937 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9938 SourceLocation SL) { 9939 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9940 asDerived().visitArray(PCK, AT, SL); 9941 return; 9942 } 9943 9944 Super::visitWithKind(PCK, FT, SL); 9945 } 9946 9947 void visitARCStrong(QualType FT, SourceLocation SL) { 9948 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9949 } 9950 void visitARCWeak(QualType FT, SourceLocation SL) { 9951 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9952 } 9953 void visitStruct(QualType FT, SourceLocation SL) { 9954 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9955 visit(FD->getType(), FD->getLocation()); 9956 } 9957 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9958 SourceLocation SL) { 9959 visit(getContext().getBaseElementType(AT), SL); 9960 } 9961 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9962 SourceLocation SL) {} 9963 void visitTrivial(QualType FT, SourceLocation SL) {} 9964 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9965 9966 static void diag(QualType RT, const Expr *E, Sema &S) { 9967 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9968 } 9969 9970 ASTContext &getContext() { return S.getASTContext(); } 9971 9972 const Expr *E; 9973 Sema &S; 9974 }; 9975 9976 } 9977 9978 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9979 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9980 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9981 9982 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9983 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9984 return false; 9985 9986 return doesExprLikelyComputeSize(BO->getLHS()) || 9987 doesExprLikelyComputeSize(BO->getRHS()); 9988 } 9989 9990 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9991 } 9992 9993 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9994 /// 9995 /// \code 9996 /// #define MACRO 0 9997 /// foo(MACRO); 9998 /// foo(0); 9999 /// \endcode 10000 /// 10001 /// This should return true for the first call to foo, but not for the second 10002 /// (regardless of whether foo is a macro or function). 10003 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10004 SourceLocation CallLoc, 10005 SourceLocation ArgLoc) { 10006 if (!CallLoc.isMacroID()) 10007 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10008 10009 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10010 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10011 } 10012 10013 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10014 /// last two arguments transposed. 10015 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10016 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10017 return; 10018 10019 const Expr *SizeArg = 10020 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10021 10022 auto isLiteralZero = [](const Expr *E) { 10023 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10024 }; 10025 10026 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10027 SourceLocation CallLoc = Call->getRParenLoc(); 10028 SourceManager &SM = S.getSourceManager(); 10029 if (isLiteralZero(SizeArg) && 10030 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10031 10032 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10033 10034 // Some platforms #define bzero to __builtin_memset. See if this is the 10035 // case, and if so, emit a better diagnostic. 10036 if (BId == Builtin::BIbzero || 10037 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10038 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10039 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10040 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10041 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10042 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10043 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10044 } 10045 return; 10046 } 10047 10048 // If the second argument to a memset is a sizeof expression and the third 10049 // isn't, this is also likely an error. This should catch 10050 // 'memset(buf, sizeof(buf), 0xff)'. 10051 if (BId == Builtin::BImemset && 10052 doesExprLikelyComputeSize(Call->getArg(1)) && 10053 !doesExprLikelyComputeSize(Call->getArg(2))) { 10054 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10055 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10056 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10057 return; 10058 } 10059 } 10060 10061 /// Check for dangerous or invalid arguments to memset(). 10062 /// 10063 /// This issues warnings on known problematic, dangerous or unspecified 10064 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10065 /// function calls. 10066 /// 10067 /// \param Call The call expression to diagnose. 10068 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10069 unsigned BId, 10070 IdentifierInfo *FnName) { 10071 assert(BId != 0); 10072 10073 // It is possible to have a non-standard definition of memset. Validate 10074 // we have enough arguments, and if not, abort further checking. 10075 unsigned ExpectedNumArgs = 10076 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10077 if (Call->getNumArgs() < ExpectedNumArgs) 10078 return; 10079 10080 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10081 BId == Builtin::BIstrndup ? 1 : 2); 10082 unsigned LenArg = 10083 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10084 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10085 10086 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10087 Call->getBeginLoc(), Call->getRParenLoc())) 10088 return; 10089 10090 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10091 CheckMemaccessSize(*this, BId, Call); 10092 10093 // We have special checking when the length is a sizeof expression. 10094 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10095 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10096 llvm::FoldingSetNodeID SizeOfArgID; 10097 10098 // Although widely used, 'bzero' is not a standard function. Be more strict 10099 // with the argument types before allowing diagnostics and only allow the 10100 // form bzero(ptr, sizeof(...)). 10101 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10102 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10103 return; 10104 10105 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10106 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10107 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10108 10109 QualType DestTy = Dest->getType(); 10110 QualType PointeeTy; 10111 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10112 PointeeTy = DestPtrTy->getPointeeType(); 10113 10114 // Never warn about void type pointers. This can be used to suppress 10115 // false positives. 10116 if (PointeeTy->isVoidType()) 10117 continue; 10118 10119 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10120 // actually comparing the expressions for equality. Because computing the 10121 // expression IDs can be expensive, we only do this if the diagnostic is 10122 // enabled. 10123 if (SizeOfArg && 10124 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10125 SizeOfArg->getExprLoc())) { 10126 // We only compute IDs for expressions if the warning is enabled, and 10127 // cache the sizeof arg's ID. 10128 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10129 SizeOfArg->Profile(SizeOfArgID, Context, true); 10130 llvm::FoldingSetNodeID DestID; 10131 Dest->Profile(DestID, Context, true); 10132 if (DestID == SizeOfArgID) { 10133 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10134 // over sizeof(src) as well. 10135 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10136 StringRef ReadableName = FnName->getName(); 10137 10138 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10139 if (UnaryOp->getOpcode() == UO_AddrOf) 10140 ActionIdx = 1; // If its an address-of operator, just remove it. 10141 if (!PointeeTy->isIncompleteType() && 10142 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10143 ActionIdx = 2; // If the pointee's size is sizeof(char), 10144 // suggest an explicit length. 10145 10146 // If the function is defined as a builtin macro, do not show macro 10147 // expansion. 10148 SourceLocation SL = SizeOfArg->getExprLoc(); 10149 SourceRange DSR = Dest->getSourceRange(); 10150 SourceRange SSR = SizeOfArg->getSourceRange(); 10151 SourceManager &SM = getSourceManager(); 10152 10153 if (SM.isMacroArgExpansion(SL)) { 10154 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10155 SL = SM.getSpellingLoc(SL); 10156 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10157 SM.getSpellingLoc(DSR.getEnd())); 10158 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10159 SM.getSpellingLoc(SSR.getEnd())); 10160 } 10161 10162 DiagRuntimeBehavior(SL, SizeOfArg, 10163 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10164 << ReadableName 10165 << PointeeTy 10166 << DestTy 10167 << DSR 10168 << SSR); 10169 DiagRuntimeBehavior(SL, SizeOfArg, 10170 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10171 << ActionIdx 10172 << SSR); 10173 10174 break; 10175 } 10176 } 10177 10178 // Also check for cases where the sizeof argument is the exact same 10179 // type as the memory argument, and where it points to a user-defined 10180 // record type. 10181 if (SizeOfArgTy != QualType()) { 10182 if (PointeeTy->isRecordType() && 10183 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10184 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10185 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10186 << FnName << SizeOfArgTy << ArgIdx 10187 << PointeeTy << Dest->getSourceRange() 10188 << LenExpr->getSourceRange()); 10189 break; 10190 } 10191 } 10192 } else if (DestTy->isArrayType()) { 10193 PointeeTy = DestTy; 10194 } 10195 10196 if (PointeeTy == QualType()) 10197 continue; 10198 10199 // Always complain about dynamic classes. 10200 bool IsContained; 10201 if (const CXXRecordDecl *ContainedRD = 10202 getContainedDynamicClass(PointeeTy, IsContained)) { 10203 10204 unsigned OperationType = 0; 10205 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10206 // "overwritten" if we're warning about the destination for any call 10207 // but memcmp; otherwise a verb appropriate to the call. 10208 if (ArgIdx != 0 || IsCmp) { 10209 if (BId == Builtin::BImemcpy) 10210 OperationType = 1; 10211 else if(BId == Builtin::BImemmove) 10212 OperationType = 2; 10213 else if (IsCmp) 10214 OperationType = 3; 10215 } 10216 10217 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10218 PDiag(diag::warn_dyn_class_memaccess) 10219 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10220 << IsContained << ContainedRD << OperationType 10221 << Call->getCallee()->getSourceRange()); 10222 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10223 BId != Builtin::BImemset) 10224 DiagRuntimeBehavior( 10225 Dest->getExprLoc(), Dest, 10226 PDiag(diag::warn_arc_object_memaccess) 10227 << ArgIdx << FnName << PointeeTy 10228 << Call->getCallee()->getSourceRange()); 10229 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10230 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10231 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10232 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10233 PDiag(diag::warn_cstruct_memaccess) 10234 << ArgIdx << FnName << PointeeTy << 0); 10235 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10236 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10237 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10238 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10239 PDiag(diag::warn_cstruct_memaccess) 10240 << ArgIdx << FnName << PointeeTy << 1); 10241 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10242 } else { 10243 continue; 10244 } 10245 } else 10246 continue; 10247 10248 DiagRuntimeBehavior( 10249 Dest->getExprLoc(), Dest, 10250 PDiag(diag::note_bad_memaccess_silence) 10251 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10252 break; 10253 } 10254 } 10255 10256 // A little helper routine: ignore addition and subtraction of integer literals. 10257 // This intentionally does not ignore all integer constant expressions because 10258 // we don't want to remove sizeof(). 10259 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10260 Ex = Ex->IgnoreParenCasts(); 10261 10262 while (true) { 10263 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10264 if (!BO || !BO->isAdditiveOp()) 10265 break; 10266 10267 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10268 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10269 10270 if (isa<IntegerLiteral>(RHS)) 10271 Ex = LHS; 10272 else if (isa<IntegerLiteral>(LHS)) 10273 Ex = RHS; 10274 else 10275 break; 10276 } 10277 10278 return Ex; 10279 } 10280 10281 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10282 ASTContext &Context) { 10283 // Only handle constant-sized or VLAs, but not flexible members. 10284 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10285 // Only issue the FIXIT for arrays of size > 1. 10286 if (CAT->getSize().getSExtValue() <= 1) 10287 return false; 10288 } else if (!Ty->isVariableArrayType()) { 10289 return false; 10290 } 10291 return true; 10292 } 10293 10294 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10295 // be the size of the source, instead of the destination. 10296 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10297 IdentifierInfo *FnName) { 10298 10299 // Don't crash if the user has the wrong number of arguments 10300 unsigned NumArgs = Call->getNumArgs(); 10301 if ((NumArgs != 3) && (NumArgs != 4)) 10302 return; 10303 10304 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10305 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10306 const Expr *CompareWithSrc = nullptr; 10307 10308 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10309 Call->getBeginLoc(), Call->getRParenLoc())) 10310 return; 10311 10312 // Look for 'strlcpy(dst, x, sizeof(x))' 10313 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10314 CompareWithSrc = Ex; 10315 else { 10316 // Look for 'strlcpy(dst, x, strlen(x))' 10317 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10318 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10319 SizeCall->getNumArgs() == 1) 10320 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10321 } 10322 } 10323 10324 if (!CompareWithSrc) 10325 return; 10326 10327 // Determine if the argument to sizeof/strlen is equal to the source 10328 // argument. In principle there's all kinds of things you could do 10329 // here, for instance creating an == expression and evaluating it with 10330 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10331 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10332 if (!SrcArgDRE) 10333 return; 10334 10335 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10336 if (!CompareWithSrcDRE || 10337 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10338 return; 10339 10340 const Expr *OriginalSizeArg = Call->getArg(2); 10341 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10342 << OriginalSizeArg->getSourceRange() << FnName; 10343 10344 // Output a FIXIT hint if the destination is an array (rather than a 10345 // pointer to an array). This could be enhanced to handle some 10346 // pointers if we know the actual size, like if DstArg is 'array+2' 10347 // we could say 'sizeof(array)-2'. 10348 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10349 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10350 return; 10351 10352 SmallString<128> sizeString; 10353 llvm::raw_svector_ostream OS(sizeString); 10354 OS << "sizeof("; 10355 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10356 OS << ")"; 10357 10358 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10359 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10360 OS.str()); 10361 } 10362 10363 /// Check if two expressions refer to the same declaration. 10364 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10365 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10366 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10367 return D1->getDecl() == D2->getDecl(); 10368 return false; 10369 } 10370 10371 static const Expr *getStrlenExprArg(const Expr *E) { 10372 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10373 const FunctionDecl *FD = CE->getDirectCallee(); 10374 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10375 return nullptr; 10376 return CE->getArg(0)->IgnoreParenCasts(); 10377 } 10378 return nullptr; 10379 } 10380 10381 // Warn on anti-patterns as the 'size' argument to strncat. 10382 // The correct size argument should look like following: 10383 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10384 void Sema::CheckStrncatArguments(const CallExpr *CE, 10385 IdentifierInfo *FnName) { 10386 // Don't crash if the user has the wrong number of arguments. 10387 if (CE->getNumArgs() < 3) 10388 return; 10389 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10390 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10391 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10392 10393 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10394 CE->getRParenLoc())) 10395 return; 10396 10397 // Identify common expressions, which are wrongly used as the size argument 10398 // to strncat and may lead to buffer overflows. 10399 unsigned PatternType = 0; 10400 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10401 // - sizeof(dst) 10402 if (referToTheSameDecl(SizeOfArg, DstArg)) 10403 PatternType = 1; 10404 // - sizeof(src) 10405 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10406 PatternType = 2; 10407 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10408 if (BE->getOpcode() == BO_Sub) { 10409 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10410 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10411 // - sizeof(dst) - strlen(dst) 10412 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10413 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10414 PatternType = 1; 10415 // - sizeof(src) - (anything) 10416 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10417 PatternType = 2; 10418 } 10419 } 10420 10421 if (PatternType == 0) 10422 return; 10423 10424 // Generate the diagnostic. 10425 SourceLocation SL = LenArg->getBeginLoc(); 10426 SourceRange SR = LenArg->getSourceRange(); 10427 SourceManager &SM = getSourceManager(); 10428 10429 // If the function is defined as a builtin macro, do not show macro expansion. 10430 if (SM.isMacroArgExpansion(SL)) { 10431 SL = SM.getSpellingLoc(SL); 10432 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10433 SM.getSpellingLoc(SR.getEnd())); 10434 } 10435 10436 // Check if the destination is an array (rather than a pointer to an array). 10437 QualType DstTy = DstArg->getType(); 10438 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10439 Context); 10440 if (!isKnownSizeArray) { 10441 if (PatternType == 1) 10442 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10443 else 10444 Diag(SL, diag::warn_strncat_src_size) << SR; 10445 return; 10446 } 10447 10448 if (PatternType == 1) 10449 Diag(SL, diag::warn_strncat_large_size) << SR; 10450 else 10451 Diag(SL, diag::warn_strncat_src_size) << SR; 10452 10453 SmallString<128> sizeString; 10454 llvm::raw_svector_ostream OS(sizeString); 10455 OS << "sizeof("; 10456 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10457 OS << ") - "; 10458 OS << "strlen("; 10459 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10460 OS << ") - 1"; 10461 10462 Diag(SL, diag::note_strncat_wrong_size) 10463 << FixItHint::CreateReplacement(SR, OS.str()); 10464 } 10465 10466 namespace { 10467 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10468 const UnaryOperator *UnaryExpr, const Decl *D) { 10469 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10470 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10471 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10472 return; 10473 } 10474 } 10475 10476 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10477 const UnaryOperator *UnaryExpr) { 10478 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10479 const Decl *D = Lvalue->getDecl(); 10480 if (isa<VarDecl, FunctionDecl>(D)) 10481 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10482 } 10483 10484 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10485 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10486 Lvalue->getMemberDecl()); 10487 } 10488 10489 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10490 const UnaryOperator *UnaryExpr) { 10491 const auto *Lambda = dyn_cast<LambdaExpr>( 10492 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10493 if (!Lambda) 10494 return; 10495 10496 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10497 << CalleeName << 2 /*object: lambda expression*/; 10498 } 10499 10500 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10501 const DeclRefExpr *Lvalue) { 10502 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10503 if (Var == nullptr) 10504 return; 10505 10506 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10507 << CalleeName << 0 /*object: */ << Var; 10508 } 10509 10510 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10511 const CastExpr *Cast) { 10512 SmallString<128> SizeString; 10513 llvm::raw_svector_ostream OS(SizeString); 10514 10515 clang::CastKind Kind = Cast->getCastKind(); 10516 if (Kind == clang::CK_BitCast && 10517 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10518 return; 10519 if (Kind == clang::CK_IntegralToPointer && 10520 !isa<IntegerLiteral>( 10521 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10522 return; 10523 10524 switch (Cast->getCastKind()) { 10525 case clang::CK_BitCast: 10526 case clang::CK_IntegralToPointer: 10527 case clang::CK_FunctionToPointerDecay: 10528 OS << '\''; 10529 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10530 OS << '\''; 10531 break; 10532 default: 10533 return; 10534 } 10535 10536 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10537 << CalleeName << 0 /*object: */ << OS.str(); 10538 } 10539 } // namespace 10540 10541 /// Alerts the user that they are attempting to free a non-malloc'd object. 10542 void Sema::CheckFreeArguments(const CallExpr *E) { 10543 const std::string CalleeName = 10544 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10545 10546 { // Prefer something that doesn't involve a cast to make things simpler. 10547 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10548 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10549 switch (UnaryExpr->getOpcode()) { 10550 case UnaryOperator::Opcode::UO_AddrOf: 10551 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10552 case UnaryOperator::Opcode::UO_Plus: 10553 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10554 default: 10555 break; 10556 } 10557 10558 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10559 if (Lvalue->getType()->isArrayType()) 10560 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10561 10562 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10563 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10564 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10565 return; 10566 } 10567 10568 if (isa<BlockExpr>(Arg)) { 10569 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10570 << CalleeName << 1 /*object: block*/; 10571 return; 10572 } 10573 } 10574 // Maybe the cast was important, check after the other cases. 10575 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10576 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10577 } 10578 10579 void 10580 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10581 SourceLocation ReturnLoc, 10582 bool isObjCMethod, 10583 const AttrVec *Attrs, 10584 const FunctionDecl *FD) { 10585 // Check if the return value is null but should not be. 10586 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10587 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10588 CheckNonNullExpr(*this, RetValExp)) 10589 Diag(ReturnLoc, diag::warn_null_ret) 10590 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10591 10592 // C++11 [basic.stc.dynamic.allocation]p4: 10593 // If an allocation function declared with a non-throwing 10594 // exception-specification fails to allocate storage, it shall return 10595 // a null pointer. Any other allocation function that fails to allocate 10596 // storage shall indicate failure only by throwing an exception [...] 10597 if (FD) { 10598 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10599 if (Op == OO_New || Op == OO_Array_New) { 10600 const FunctionProtoType *Proto 10601 = FD->getType()->castAs<FunctionProtoType>(); 10602 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10603 CheckNonNullExpr(*this, RetValExp)) 10604 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10605 << FD << getLangOpts().CPlusPlus11; 10606 } 10607 } 10608 10609 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10610 // here prevent the user from using a PPC MMA type as trailing return type. 10611 if (Context.getTargetInfo().getTriple().isPPC64()) 10612 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10613 } 10614 10615 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10616 10617 /// Check for comparisons of floating point operands using != and ==. 10618 /// Issue a warning if these are no self-comparisons, as they are not likely 10619 /// to do what the programmer intended. 10620 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10621 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10622 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10623 10624 // Special case: check for x == x (which is OK). 10625 // Do not emit warnings for such cases. 10626 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10627 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10628 if (DRL->getDecl() == DRR->getDecl()) 10629 return; 10630 10631 // Special case: check for comparisons against literals that can be exactly 10632 // represented by APFloat. In such cases, do not emit a warning. This 10633 // is a heuristic: often comparison against such literals are used to 10634 // detect if a value in a variable has not changed. This clearly can 10635 // lead to false negatives. 10636 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10637 if (FLL->isExact()) 10638 return; 10639 } else 10640 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10641 if (FLR->isExact()) 10642 return; 10643 10644 // Check for comparisons with builtin types. 10645 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10646 if (CL->getBuiltinCallee()) 10647 return; 10648 10649 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10650 if (CR->getBuiltinCallee()) 10651 return; 10652 10653 // Emit the diagnostic. 10654 Diag(Loc, diag::warn_floatingpoint_eq) 10655 << LHS->getSourceRange() << RHS->getSourceRange(); 10656 } 10657 10658 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10659 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10660 10661 namespace { 10662 10663 /// Structure recording the 'active' range of an integer-valued 10664 /// expression. 10665 struct IntRange { 10666 /// The number of bits active in the int. Note that this includes exactly one 10667 /// sign bit if !NonNegative. 10668 unsigned Width; 10669 10670 /// True if the int is known not to have negative values. If so, all leading 10671 /// bits before Width are known zero, otherwise they are known to be the 10672 /// same as the MSB within Width. 10673 bool NonNegative; 10674 10675 IntRange(unsigned Width, bool NonNegative) 10676 : Width(Width), NonNegative(NonNegative) {} 10677 10678 /// Number of bits excluding the sign bit. 10679 unsigned valueBits() const { 10680 return NonNegative ? Width : Width - 1; 10681 } 10682 10683 /// Returns the range of the bool type. 10684 static IntRange forBoolType() { 10685 return IntRange(1, true); 10686 } 10687 10688 /// Returns the range of an opaque value of the given integral type. 10689 static IntRange forValueOfType(ASTContext &C, QualType T) { 10690 return forValueOfCanonicalType(C, 10691 T->getCanonicalTypeInternal().getTypePtr()); 10692 } 10693 10694 /// Returns the range of an opaque value of a canonical integral type. 10695 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10696 assert(T->isCanonicalUnqualified()); 10697 10698 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10699 T = VT->getElementType().getTypePtr(); 10700 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10701 T = CT->getElementType().getTypePtr(); 10702 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10703 T = AT->getValueType().getTypePtr(); 10704 10705 if (!C.getLangOpts().CPlusPlus) { 10706 // For enum types in C code, use the underlying datatype. 10707 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10708 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10709 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10710 // For enum types in C++, use the known bit width of the enumerators. 10711 EnumDecl *Enum = ET->getDecl(); 10712 // In C++11, enums can have a fixed underlying type. Use this type to 10713 // compute the range. 10714 if (Enum->isFixed()) { 10715 return IntRange(C.getIntWidth(QualType(T, 0)), 10716 !ET->isSignedIntegerOrEnumerationType()); 10717 } 10718 10719 unsigned NumPositive = Enum->getNumPositiveBits(); 10720 unsigned NumNegative = Enum->getNumNegativeBits(); 10721 10722 if (NumNegative == 0) 10723 return IntRange(NumPositive, true/*NonNegative*/); 10724 else 10725 return IntRange(std::max(NumPositive + 1, NumNegative), 10726 false/*NonNegative*/); 10727 } 10728 10729 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10730 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10731 10732 const BuiltinType *BT = cast<BuiltinType>(T); 10733 assert(BT->isInteger()); 10734 10735 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10736 } 10737 10738 /// Returns the "target" range of a canonical integral type, i.e. 10739 /// the range of values expressible in the type. 10740 /// 10741 /// This matches forValueOfCanonicalType except that enums have the 10742 /// full range of their type, not the range of their enumerators. 10743 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10744 assert(T->isCanonicalUnqualified()); 10745 10746 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10747 T = VT->getElementType().getTypePtr(); 10748 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10749 T = CT->getElementType().getTypePtr(); 10750 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10751 T = AT->getValueType().getTypePtr(); 10752 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10753 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10754 10755 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10756 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10757 10758 const BuiltinType *BT = cast<BuiltinType>(T); 10759 assert(BT->isInteger()); 10760 10761 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10762 } 10763 10764 /// Returns the supremum of two ranges: i.e. their conservative merge. 10765 static IntRange join(IntRange L, IntRange R) { 10766 bool Unsigned = L.NonNegative && R.NonNegative; 10767 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10768 L.NonNegative && R.NonNegative); 10769 } 10770 10771 /// Return the range of a bitwise-AND of the two ranges. 10772 static IntRange bit_and(IntRange L, IntRange R) { 10773 unsigned Bits = std::max(L.Width, R.Width); 10774 bool NonNegative = false; 10775 if (L.NonNegative) { 10776 Bits = std::min(Bits, L.Width); 10777 NonNegative = true; 10778 } 10779 if (R.NonNegative) { 10780 Bits = std::min(Bits, R.Width); 10781 NonNegative = true; 10782 } 10783 return IntRange(Bits, NonNegative); 10784 } 10785 10786 /// Return the range of a sum of the two ranges. 10787 static IntRange sum(IntRange L, IntRange R) { 10788 bool Unsigned = L.NonNegative && R.NonNegative; 10789 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10790 Unsigned); 10791 } 10792 10793 /// Return the range of a difference of the two ranges. 10794 static IntRange difference(IntRange L, IntRange R) { 10795 // We need a 1-bit-wider range if: 10796 // 1) LHS can be negative: least value can be reduced. 10797 // 2) RHS can be negative: greatest value can be increased. 10798 bool CanWiden = !L.NonNegative || !R.NonNegative; 10799 bool Unsigned = L.NonNegative && R.Width == 0; 10800 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10801 !Unsigned, 10802 Unsigned); 10803 } 10804 10805 /// Return the range of a product of the two ranges. 10806 static IntRange product(IntRange L, IntRange R) { 10807 // If both LHS and RHS can be negative, we can form 10808 // -2^L * -2^R = 2^(L + R) 10809 // which requires L + R + 1 value bits to represent. 10810 bool CanWiden = !L.NonNegative && !R.NonNegative; 10811 bool Unsigned = L.NonNegative && R.NonNegative; 10812 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10813 Unsigned); 10814 } 10815 10816 /// Return the range of a remainder operation between the two ranges. 10817 static IntRange rem(IntRange L, IntRange R) { 10818 // The result of a remainder can't be larger than the result of 10819 // either side. The sign of the result is the sign of the LHS. 10820 bool Unsigned = L.NonNegative; 10821 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10822 Unsigned); 10823 } 10824 }; 10825 10826 } // namespace 10827 10828 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10829 unsigned MaxWidth) { 10830 if (value.isSigned() && value.isNegative()) 10831 return IntRange(value.getMinSignedBits(), false); 10832 10833 if (value.getBitWidth() > MaxWidth) 10834 value = value.trunc(MaxWidth); 10835 10836 // isNonNegative() just checks the sign bit without considering 10837 // signedness. 10838 return IntRange(value.getActiveBits(), true); 10839 } 10840 10841 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10842 unsigned MaxWidth) { 10843 if (result.isInt()) 10844 return GetValueRange(C, result.getInt(), MaxWidth); 10845 10846 if (result.isVector()) { 10847 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10848 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10849 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10850 R = IntRange::join(R, El); 10851 } 10852 return R; 10853 } 10854 10855 if (result.isComplexInt()) { 10856 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10857 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10858 return IntRange::join(R, I); 10859 } 10860 10861 // This can happen with lossless casts to intptr_t of "based" lvalues. 10862 // Assume it might use arbitrary bits. 10863 // FIXME: The only reason we need to pass the type in here is to get 10864 // the sign right on this one case. It would be nice if APValue 10865 // preserved this. 10866 assert(result.isLValue() || result.isAddrLabelDiff()); 10867 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10868 } 10869 10870 static QualType GetExprType(const Expr *E) { 10871 QualType Ty = E->getType(); 10872 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10873 Ty = AtomicRHS->getValueType(); 10874 return Ty; 10875 } 10876 10877 /// Pseudo-evaluate the given integer expression, estimating the 10878 /// range of values it might take. 10879 /// 10880 /// \param MaxWidth The width to which the value will be truncated. 10881 /// \param Approximate If \c true, return a likely range for the result: in 10882 /// particular, assume that aritmetic on narrower types doesn't leave 10883 /// those types. If \c false, return a range including all possible 10884 /// result values. 10885 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10886 bool InConstantContext, bool Approximate) { 10887 E = E->IgnoreParens(); 10888 10889 // Try a full evaluation first. 10890 Expr::EvalResult result; 10891 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10892 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10893 10894 // I think we only want to look through implicit casts here; if the 10895 // user has an explicit widening cast, we should treat the value as 10896 // being of the new, wider type. 10897 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10898 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10899 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 10900 Approximate); 10901 10902 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10903 10904 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10905 CE->getCastKind() == CK_BooleanToSignedIntegral; 10906 10907 // Assume that non-integer casts can span the full range of the type. 10908 if (!isIntegerCast) 10909 return OutputTypeRange; 10910 10911 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10912 std::min(MaxWidth, OutputTypeRange.Width), 10913 InConstantContext, Approximate); 10914 10915 // Bail out if the subexpr's range is as wide as the cast type. 10916 if (SubRange.Width >= OutputTypeRange.Width) 10917 return OutputTypeRange; 10918 10919 // Otherwise, we take the smaller width, and we're non-negative if 10920 // either the output type or the subexpr is. 10921 return IntRange(SubRange.Width, 10922 SubRange.NonNegative || OutputTypeRange.NonNegative); 10923 } 10924 10925 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10926 // If we can fold the condition, just take that operand. 10927 bool CondResult; 10928 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10929 return GetExprRange(C, 10930 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10931 MaxWidth, InConstantContext, Approximate); 10932 10933 // Otherwise, conservatively merge. 10934 // GetExprRange requires an integer expression, but a throw expression 10935 // results in a void type. 10936 Expr *E = CO->getTrueExpr(); 10937 IntRange L = E->getType()->isVoidType() 10938 ? IntRange{0, true} 10939 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10940 E = CO->getFalseExpr(); 10941 IntRange R = E->getType()->isVoidType() 10942 ? IntRange{0, true} 10943 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10944 return IntRange::join(L, R); 10945 } 10946 10947 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10948 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 10949 10950 switch (BO->getOpcode()) { 10951 case BO_Cmp: 10952 llvm_unreachable("builtin <=> should have class type"); 10953 10954 // Boolean-valued operations are single-bit and positive. 10955 case BO_LAnd: 10956 case BO_LOr: 10957 case BO_LT: 10958 case BO_GT: 10959 case BO_LE: 10960 case BO_GE: 10961 case BO_EQ: 10962 case BO_NE: 10963 return IntRange::forBoolType(); 10964 10965 // The type of the assignments is the type of the LHS, so the RHS 10966 // is not necessarily the same type. 10967 case BO_MulAssign: 10968 case BO_DivAssign: 10969 case BO_RemAssign: 10970 case BO_AddAssign: 10971 case BO_SubAssign: 10972 case BO_XorAssign: 10973 case BO_OrAssign: 10974 // TODO: bitfields? 10975 return IntRange::forValueOfType(C, GetExprType(E)); 10976 10977 // Simple assignments just pass through the RHS, which will have 10978 // been coerced to the LHS type. 10979 case BO_Assign: 10980 // TODO: bitfields? 10981 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10982 Approximate); 10983 10984 // Operations with opaque sources are black-listed. 10985 case BO_PtrMemD: 10986 case BO_PtrMemI: 10987 return IntRange::forValueOfType(C, GetExprType(E)); 10988 10989 // Bitwise-and uses the *infinum* of the two source ranges. 10990 case BO_And: 10991 case BO_AndAssign: 10992 Combine = IntRange::bit_and; 10993 break; 10994 10995 // Left shift gets black-listed based on a judgement call. 10996 case BO_Shl: 10997 // ...except that we want to treat '1 << (blah)' as logically 10998 // positive. It's an important idiom. 10999 if (IntegerLiteral *I 11000 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11001 if (I->getValue() == 1) { 11002 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11003 return IntRange(R.Width, /*NonNegative*/ true); 11004 } 11005 } 11006 LLVM_FALLTHROUGH; 11007 11008 case BO_ShlAssign: 11009 return IntRange::forValueOfType(C, GetExprType(E)); 11010 11011 // Right shift by a constant can narrow its left argument. 11012 case BO_Shr: 11013 case BO_ShrAssign: { 11014 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11015 Approximate); 11016 11017 // If the shift amount is a positive constant, drop the width by 11018 // that much. 11019 if (Optional<llvm::APSInt> shift = 11020 BO->getRHS()->getIntegerConstantExpr(C)) { 11021 if (shift->isNonNegative()) { 11022 unsigned zext = shift->getZExtValue(); 11023 if (zext >= L.Width) 11024 L.Width = (L.NonNegative ? 0 : 1); 11025 else 11026 L.Width -= zext; 11027 } 11028 } 11029 11030 return L; 11031 } 11032 11033 // Comma acts as its right operand. 11034 case BO_Comma: 11035 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11036 Approximate); 11037 11038 case BO_Add: 11039 if (!Approximate) 11040 Combine = IntRange::sum; 11041 break; 11042 11043 case BO_Sub: 11044 if (BO->getLHS()->getType()->isPointerType()) 11045 return IntRange::forValueOfType(C, GetExprType(E)); 11046 if (!Approximate) 11047 Combine = IntRange::difference; 11048 break; 11049 11050 case BO_Mul: 11051 if (!Approximate) 11052 Combine = IntRange::product; 11053 break; 11054 11055 // The width of a division result is mostly determined by the size 11056 // of the LHS. 11057 case BO_Div: { 11058 // Don't 'pre-truncate' the operands. 11059 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11060 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11061 Approximate); 11062 11063 // If the divisor is constant, use that. 11064 if (Optional<llvm::APSInt> divisor = 11065 BO->getRHS()->getIntegerConstantExpr(C)) { 11066 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11067 if (log2 >= L.Width) 11068 L.Width = (L.NonNegative ? 0 : 1); 11069 else 11070 L.Width = std::min(L.Width - log2, MaxWidth); 11071 return L; 11072 } 11073 11074 // Otherwise, just use the LHS's width. 11075 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11076 // could be -1. 11077 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11078 Approximate); 11079 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11080 } 11081 11082 case BO_Rem: 11083 Combine = IntRange::rem; 11084 break; 11085 11086 // The default behavior is okay for these. 11087 case BO_Xor: 11088 case BO_Or: 11089 break; 11090 } 11091 11092 // Combine the two ranges, but limit the result to the type in which we 11093 // performed the computation. 11094 QualType T = GetExprType(E); 11095 unsigned opWidth = C.getIntWidth(T); 11096 IntRange L = 11097 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11098 IntRange R = 11099 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11100 IntRange C = Combine(L, R); 11101 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11102 C.Width = std::min(C.Width, MaxWidth); 11103 return C; 11104 } 11105 11106 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11107 switch (UO->getOpcode()) { 11108 // Boolean-valued operations are white-listed. 11109 case UO_LNot: 11110 return IntRange::forBoolType(); 11111 11112 // Operations with opaque sources are black-listed. 11113 case UO_Deref: 11114 case UO_AddrOf: // should be impossible 11115 return IntRange::forValueOfType(C, GetExprType(E)); 11116 11117 default: 11118 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11119 Approximate); 11120 } 11121 } 11122 11123 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11124 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11125 Approximate); 11126 11127 if (const auto *BitField = E->getSourceBitField()) 11128 return IntRange(BitField->getBitWidthValue(C), 11129 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11130 11131 return IntRange::forValueOfType(C, GetExprType(E)); 11132 } 11133 11134 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11135 bool InConstantContext, bool Approximate) { 11136 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11137 Approximate); 11138 } 11139 11140 /// Checks whether the given value, which currently has the given 11141 /// source semantics, has the same value when coerced through the 11142 /// target semantics. 11143 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11144 const llvm::fltSemantics &Src, 11145 const llvm::fltSemantics &Tgt) { 11146 llvm::APFloat truncated = value; 11147 11148 bool ignored; 11149 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11150 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11151 11152 return truncated.bitwiseIsEqual(value); 11153 } 11154 11155 /// Checks whether the given value, which currently has the given 11156 /// source semantics, has the same value when coerced through the 11157 /// target semantics. 11158 /// 11159 /// The value might be a vector of floats (or a complex number). 11160 static bool IsSameFloatAfterCast(const APValue &value, 11161 const llvm::fltSemantics &Src, 11162 const llvm::fltSemantics &Tgt) { 11163 if (value.isFloat()) 11164 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11165 11166 if (value.isVector()) { 11167 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11168 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11169 return false; 11170 return true; 11171 } 11172 11173 assert(value.isComplexFloat()); 11174 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11175 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11176 } 11177 11178 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11179 bool IsListInit = false); 11180 11181 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11182 // Suppress cases where we are comparing against an enum constant. 11183 if (const DeclRefExpr *DR = 11184 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11185 if (isa<EnumConstantDecl>(DR->getDecl())) 11186 return true; 11187 11188 // Suppress cases where the value is expanded from a macro, unless that macro 11189 // is how a language represents a boolean literal. This is the case in both C 11190 // and Objective-C. 11191 SourceLocation BeginLoc = E->getBeginLoc(); 11192 if (BeginLoc.isMacroID()) { 11193 StringRef MacroName = Lexer::getImmediateMacroName( 11194 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11195 return MacroName != "YES" && MacroName != "NO" && 11196 MacroName != "true" && MacroName != "false"; 11197 } 11198 11199 return false; 11200 } 11201 11202 static bool isKnownToHaveUnsignedValue(Expr *E) { 11203 return E->getType()->isIntegerType() && 11204 (!E->getType()->isSignedIntegerType() || 11205 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11206 } 11207 11208 namespace { 11209 /// The promoted range of values of a type. In general this has the 11210 /// following structure: 11211 /// 11212 /// |-----------| . . . |-----------| 11213 /// ^ ^ ^ ^ 11214 /// Min HoleMin HoleMax Max 11215 /// 11216 /// ... where there is only a hole if a signed type is promoted to unsigned 11217 /// (in which case Min and Max are the smallest and largest representable 11218 /// values). 11219 struct PromotedRange { 11220 // Min, or HoleMax if there is a hole. 11221 llvm::APSInt PromotedMin; 11222 // Max, or HoleMin if there is a hole. 11223 llvm::APSInt PromotedMax; 11224 11225 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11226 if (R.Width == 0) 11227 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11228 else if (R.Width >= BitWidth && !Unsigned) { 11229 // Promotion made the type *narrower*. This happens when promoting 11230 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11231 // Treat all values of 'signed int' as being in range for now. 11232 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11233 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11234 } else { 11235 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11236 .extOrTrunc(BitWidth); 11237 PromotedMin.setIsUnsigned(Unsigned); 11238 11239 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11240 .extOrTrunc(BitWidth); 11241 PromotedMax.setIsUnsigned(Unsigned); 11242 } 11243 } 11244 11245 // Determine whether this range is contiguous (has no hole). 11246 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11247 11248 // Where a constant value is within the range. 11249 enum ComparisonResult { 11250 LT = 0x1, 11251 LE = 0x2, 11252 GT = 0x4, 11253 GE = 0x8, 11254 EQ = 0x10, 11255 NE = 0x20, 11256 InRangeFlag = 0x40, 11257 11258 Less = LE | LT | NE, 11259 Min = LE | InRangeFlag, 11260 InRange = InRangeFlag, 11261 Max = GE | InRangeFlag, 11262 Greater = GE | GT | NE, 11263 11264 OnlyValue = LE | GE | EQ | InRangeFlag, 11265 InHole = NE 11266 }; 11267 11268 ComparisonResult compare(const llvm::APSInt &Value) const { 11269 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11270 Value.isUnsigned() == PromotedMin.isUnsigned()); 11271 if (!isContiguous()) { 11272 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11273 if (Value.isMinValue()) return Min; 11274 if (Value.isMaxValue()) return Max; 11275 if (Value >= PromotedMin) return InRange; 11276 if (Value <= PromotedMax) return InRange; 11277 return InHole; 11278 } 11279 11280 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11281 case -1: return Less; 11282 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11283 case 1: 11284 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11285 case -1: return InRange; 11286 case 0: return Max; 11287 case 1: return Greater; 11288 } 11289 } 11290 11291 llvm_unreachable("impossible compare result"); 11292 } 11293 11294 static llvm::Optional<StringRef> 11295 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11296 if (Op == BO_Cmp) { 11297 ComparisonResult LTFlag = LT, GTFlag = GT; 11298 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11299 11300 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11301 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11302 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11303 return llvm::None; 11304 } 11305 11306 ComparisonResult TrueFlag, FalseFlag; 11307 if (Op == BO_EQ) { 11308 TrueFlag = EQ; 11309 FalseFlag = NE; 11310 } else if (Op == BO_NE) { 11311 TrueFlag = NE; 11312 FalseFlag = EQ; 11313 } else { 11314 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11315 TrueFlag = LT; 11316 FalseFlag = GE; 11317 } else { 11318 TrueFlag = GT; 11319 FalseFlag = LE; 11320 } 11321 if (Op == BO_GE || Op == BO_LE) 11322 std::swap(TrueFlag, FalseFlag); 11323 } 11324 if (R & TrueFlag) 11325 return StringRef("true"); 11326 if (R & FalseFlag) 11327 return StringRef("false"); 11328 return llvm::None; 11329 } 11330 }; 11331 } 11332 11333 static bool HasEnumType(Expr *E) { 11334 // Strip off implicit integral promotions. 11335 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11336 if (ICE->getCastKind() != CK_IntegralCast && 11337 ICE->getCastKind() != CK_NoOp) 11338 break; 11339 E = ICE->getSubExpr(); 11340 } 11341 11342 return E->getType()->isEnumeralType(); 11343 } 11344 11345 static int classifyConstantValue(Expr *Constant) { 11346 // The values of this enumeration are used in the diagnostics 11347 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11348 enum ConstantValueKind { 11349 Miscellaneous = 0, 11350 LiteralTrue, 11351 LiteralFalse 11352 }; 11353 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11354 return BL->getValue() ? ConstantValueKind::LiteralTrue 11355 : ConstantValueKind::LiteralFalse; 11356 return ConstantValueKind::Miscellaneous; 11357 } 11358 11359 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11360 Expr *Constant, Expr *Other, 11361 const llvm::APSInt &Value, 11362 bool RhsConstant) { 11363 if (S.inTemplateInstantiation()) 11364 return false; 11365 11366 Expr *OriginalOther = Other; 11367 11368 Constant = Constant->IgnoreParenImpCasts(); 11369 Other = Other->IgnoreParenImpCasts(); 11370 11371 // Suppress warnings on tautological comparisons between values of the same 11372 // enumeration type. There are only two ways we could warn on this: 11373 // - If the constant is outside the range of representable values of 11374 // the enumeration. In such a case, we should warn about the cast 11375 // to enumeration type, not about the comparison. 11376 // - If the constant is the maximum / minimum in-range value. For an 11377 // enumeratin type, such comparisons can be meaningful and useful. 11378 if (Constant->getType()->isEnumeralType() && 11379 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11380 return false; 11381 11382 IntRange OtherValueRange = GetExprRange( 11383 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11384 11385 QualType OtherT = Other->getType(); 11386 if (const auto *AT = OtherT->getAs<AtomicType>()) 11387 OtherT = AT->getValueType(); 11388 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11389 11390 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11391 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11392 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11393 S.NSAPIObj->isObjCBOOLType(OtherT) && 11394 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11395 11396 // Whether we're treating Other as being a bool because of the form of 11397 // expression despite it having another type (typically 'int' in C). 11398 bool OtherIsBooleanDespiteType = 11399 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11400 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11401 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11402 11403 // Check if all values in the range of possible values of this expression 11404 // lead to the same comparison outcome. 11405 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11406 Value.isUnsigned()); 11407 auto Cmp = OtherPromotedValueRange.compare(Value); 11408 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11409 if (!Result) 11410 return false; 11411 11412 // Also consider the range determined by the type alone. This allows us to 11413 // classify the warning under the proper diagnostic group. 11414 bool TautologicalTypeCompare = false; 11415 { 11416 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11417 Value.isUnsigned()); 11418 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11419 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11420 RhsConstant)) { 11421 TautologicalTypeCompare = true; 11422 Cmp = TypeCmp; 11423 Result = TypeResult; 11424 } 11425 } 11426 11427 // Don't warn if the non-constant operand actually always evaluates to the 11428 // same value. 11429 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11430 return false; 11431 11432 // Suppress the diagnostic for an in-range comparison if the constant comes 11433 // from a macro or enumerator. We don't want to diagnose 11434 // 11435 // some_long_value <= INT_MAX 11436 // 11437 // when sizeof(int) == sizeof(long). 11438 bool InRange = Cmp & PromotedRange::InRangeFlag; 11439 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11440 return false; 11441 11442 // A comparison of an unsigned bit-field against 0 is really a type problem, 11443 // even though at the type level the bit-field might promote to 'signed int'. 11444 if (Other->refersToBitField() && InRange && Value == 0 && 11445 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11446 TautologicalTypeCompare = true; 11447 11448 // If this is a comparison to an enum constant, include that 11449 // constant in the diagnostic. 11450 const EnumConstantDecl *ED = nullptr; 11451 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11452 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11453 11454 // Should be enough for uint128 (39 decimal digits) 11455 SmallString<64> PrettySourceValue; 11456 llvm::raw_svector_ostream OS(PrettySourceValue); 11457 if (ED) { 11458 OS << '\'' << *ED << "' (" << Value << ")"; 11459 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11460 Constant->IgnoreParenImpCasts())) { 11461 OS << (BL->getValue() ? "YES" : "NO"); 11462 } else { 11463 OS << Value; 11464 } 11465 11466 if (!TautologicalTypeCompare) { 11467 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11468 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11469 << E->getOpcodeStr() << OS.str() << *Result 11470 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11471 return true; 11472 } 11473 11474 if (IsObjCSignedCharBool) { 11475 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11476 S.PDiag(diag::warn_tautological_compare_objc_bool) 11477 << OS.str() << *Result); 11478 return true; 11479 } 11480 11481 // FIXME: We use a somewhat different formatting for the in-range cases and 11482 // cases involving boolean values for historical reasons. We should pick a 11483 // consistent way of presenting these diagnostics. 11484 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11485 11486 S.DiagRuntimeBehavior( 11487 E->getOperatorLoc(), E, 11488 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11489 : diag::warn_tautological_bool_compare) 11490 << OS.str() << classifyConstantValue(Constant) << OtherT 11491 << OtherIsBooleanDespiteType << *Result 11492 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11493 } else { 11494 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11495 unsigned Diag = 11496 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11497 ? (HasEnumType(OriginalOther) 11498 ? diag::warn_unsigned_enum_always_true_comparison 11499 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11500 : diag::warn_unsigned_always_true_comparison) 11501 : diag::warn_tautological_constant_compare; 11502 11503 S.Diag(E->getOperatorLoc(), Diag) 11504 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11505 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11506 } 11507 11508 return true; 11509 } 11510 11511 /// Analyze the operands of the given comparison. Implements the 11512 /// fallback case from AnalyzeComparison. 11513 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11514 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11515 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11516 } 11517 11518 /// Implements -Wsign-compare. 11519 /// 11520 /// \param E the binary operator to check for warnings 11521 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11522 // The type the comparison is being performed in. 11523 QualType T = E->getLHS()->getType(); 11524 11525 // Only analyze comparison operators where both sides have been converted to 11526 // the same type. 11527 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11528 return AnalyzeImpConvsInComparison(S, E); 11529 11530 // Don't analyze value-dependent comparisons directly. 11531 if (E->isValueDependent()) 11532 return AnalyzeImpConvsInComparison(S, E); 11533 11534 Expr *LHS = E->getLHS(); 11535 Expr *RHS = E->getRHS(); 11536 11537 if (T->isIntegralType(S.Context)) { 11538 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11539 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11540 11541 // We don't care about expressions whose result is a constant. 11542 if (RHSValue && LHSValue) 11543 return AnalyzeImpConvsInComparison(S, E); 11544 11545 // We only care about expressions where just one side is literal 11546 if ((bool)RHSValue ^ (bool)LHSValue) { 11547 // Is the constant on the RHS or LHS? 11548 const bool RhsConstant = (bool)RHSValue; 11549 Expr *Const = RhsConstant ? RHS : LHS; 11550 Expr *Other = RhsConstant ? LHS : RHS; 11551 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11552 11553 // Check whether an integer constant comparison results in a value 11554 // of 'true' or 'false'. 11555 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11556 return AnalyzeImpConvsInComparison(S, E); 11557 } 11558 } 11559 11560 if (!T->hasUnsignedIntegerRepresentation()) { 11561 // We don't do anything special if this isn't an unsigned integral 11562 // comparison: we're only interested in integral comparisons, and 11563 // signed comparisons only happen in cases we don't care to warn about. 11564 return AnalyzeImpConvsInComparison(S, E); 11565 } 11566 11567 LHS = LHS->IgnoreParenImpCasts(); 11568 RHS = RHS->IgnoreParenImpCasts(); 11569 11570 if (!S.getLangOpts().CPlusPlus) { 11571 // Avoid warning about comparison of integers with different signs when 11572 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11573 // the type of `E`. 11574 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11575 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11576 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11577 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11578 } 11579 11580 // Check to see if one of the (unmodified) operands is of different 11581 // signedness. 11582 Expr *signedOperand, *unsignedOperand; 11583 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11584 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11585 "unsigned comparison between two signed integer expressions?"); 11586 signedOperand = LHS; 11587 unsignedOperand = RHS; 11588 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11589 signedOperand = RHS; 11590 unsignedOperand = LHS; 11591 } else { 11592 return AnalyzeImpConvsInComparison(S, E); 11593 } 11594 11595 // Otherwise, calculate the effective range of the signed operand. 11596 IntRange signedRange = GetExprRange( 11597 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11598 11599 // Go ahead and analyze implicit conversions in the operands. Note 11600 // that we skip the implicit conversions on both sides. 11601 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11602 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11603 11604 // If the signed range is non-negative, -Wsign-compare won't fire. 11605 if (signedRange.NonNegative) 11606 return; 11607 11608 // For (in)equality comparisons, if the unsigned operand is a 11609 // constant which cannot collide with a overflowed signed operand, 11610 // then reinterpreting the signed operand as unsigned will not 11611 // change the result of the comparison. 11612 if (E->isEqualityOp()) { 11613 unsigned comparisonWidth = S.Context.getIntWidth(T); 11614 IntRange unsignedRange = 11615 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11616 /*Approximate*/ true); 11617 11618 // We should never be unable to prove that the unsigned operand is 11619 // non-negative. 11620 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11621 11622 if (unsignedRange.Width < comparisonWidth) 11623 return; 11624 } 11625 11626 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11627 S.PDiag(diag::warn_mixed_sign_comparison) 11628 << LHS->getType() << RHS->getType() 11629 << LHS->getSourceRange() << RHS->getSourceRange()); 11630 } 11631 11632 /// Analyzes an attempt to assign the given value to a bitfield. 11633 /// 11634 /// Returns true if there was something fishy about the attempt. 11635 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11636 SourceLocation InitLoc) { 11637 assert(Bitfield->isBitField()); 11638 if (Bitfield->isInvalidDecl()) 11639 return false; 11640 11641 // White-list bool bitfields. 11642 QualType BitfieldType = Bitfield->getType(); 11643 if (BitfieldType->isBooleanType()) 11644 return false; 11645 11646 if (BitfieldType->isEnumeralType()) { 11647 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11648 // If the underlying enum type was not explicitly specified as an unsigned 11649 // type and the enum contain only positive values, MSVC++ will cause an 11650 // inconsistency by storing this as a signed type. 11651 if (S.getLangOpts().CPlusPlus11 && 11652 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11653 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11654 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11655 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11656 << BitfieldEnumDecl; 11657 } 11658 } 11659 11660 if (Bitfield->getType()->isBooleanType()) 11661 return false; 11662 11663 // Ignore value- or type-dependent expressions. 11664 if (Bitfield->getBitWidth()->isValueDependent() || 11665 Bitfield->getBitWidth()->isTypeDependent() || 11666 Init->isValueDependent() || 11667 Init->isTypeDependent()) 11668 return false; 11669 11670 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11671 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11672 11673 Expr::EvalResult Result; 11674 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11675 Expr::SE_AllowSideEffects)) { 11676 // The RHS is not constant. If the RHS has an enum type, make sure the 11677 // bitfield is wide enough to hold all the values of the enum without 11678 // truncation. 11679 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11680 EnumDecl *ED = EnumTy->getDecl(); 11681 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11682 11683 // Enum types are implicitly signed on Windows, so check if there are any 11684 // negative enumerators to see if the enum was intended to be signed or 11685 // not. 11686 bool SignedEnum = ED->getNumNegativeBits() > 0; 11687 11688 // Check for surprising sign changes when assigning enum values to a 11689 // bitfield of different signedness. If the bitfield is signed and we 11690 // have exactly the right number of bits to store this unsigned enum, 11691 // suggest changing the enum to an unsigned type. This typically happens 11692 // on Windows where unfixed enums always use an underlying type of 'int'. 11693 unsigned DiagID = 0; 11694 if (SignedEnum && !SignedBitfield) { 11695 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11696 } else if (SignedBitfield && !SignedEnum && 11697 ED->getNumPositiveBits() == FieldWidth) { 11698 DiagID = diag::warn_signed_bitfield_enum_conversion; 11699 } 11700 11701 if (DiagID) { 11702 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11703 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11704 SourceRange TypeRange = 11705 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11706 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11707 << SignedEnum << TypeRange; 11708 } 11709 11710 // Compute the required bitwidth. If the enum has negative values, we need 11711 // one more bit than the normal number of positive bits to represent the 11712 // sign bit. 11713 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11714 ED->getNumNegativeBits()) 11715 : ED->getNumPositiveBits(); 11716 11717 // Check the bitwidth. 11718 if (BitsNeeded > FieldWidth) { 11719 Expr *WidthExpr = Bitfield->getBitWidth(); 11720 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11721 << Bitfield << ED; 11722 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11723 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11724 } 11725 } 11726 11727 return false; 11728 } 11729 11730 llvm::APSInt Value = Result.Val.getInt(); 11731 11732 unsigned OriginalWidth = Value.getBitWidth(); 11733 11734 if (!Value.isSigned() || Value.isNegative()) 11735 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11736 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11737 OriginalWidth = Value.getMinSignedBits(); 11738 11739 if (OriginalWidth <= FieldWidth) 11740 return false; 11741 11742 // Compute the value which the bitfield will contain. 11743 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11744 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11745 11746 // Check whether the stored value is equal to the original value. 11747 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11748 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11749 return false; 11750 11751 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11752 // therefore don't strictly fit into a signed bitfield of width 1. 11753 if (FieldWidth == 1 && Value == 1) 11754 return false; 11755 11756 std::string PrettyValue = toString(Value, 10); 11757 std::string PrettyTrunc = toString(TruncatedValue, 10); 11758 11759 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11760 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11761 << Init->getSourceRange(); 11762 11763 return true; 11764 } 11765 11766 /// Analyze the given simple or compound assignment for warning-worthy 11767 /// operations. 11768 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11769 // Just recurse on the LHS. 11770 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11771 11772 // We want to recurse on the RHS as normal unless we're assigning to 11773 // a bitfield. 11774 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11775 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11776 E->getOperatorLoc())) { 11777 // Recurse, ignoring any implicit conversions on the RHS. 11778 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11779 E->getOperatorLoc()); 11780 } 11781 } 11782 11783 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11784 11785 // Diagnose implicitly sequentially-consistent atomic assignment. 11786 if (E->getLHS()->getType()->isAtomicType()) 11787 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11788 } 11789 11790 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11791 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11792 SourceLocation CContext, unsigned diag, 11793 bool pruneControlFlow = false) { 11794 if (pruneControlFlow) { 11795 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11796 S.PDiag(diag) 11797 << SourceType << T << E->getSourceRange() 11798 << SourceRange(CContext)); 11799 return; 11800 } 11801 S.Diag(E->getExprLoc(), diag) 11802 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11803 } 11804 11805 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11806 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11807 SourceLocation CContext, 11808 unsigned diag, bool pruneControlFlow = false) { 11809 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11810 } 11811 11812 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11813 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11814 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11815 } 11816 11817 static void adornObjCBoolConversionDiagWithTernaryFixit( 11818 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11819 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11820 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11821 Ignored = OVE->getSourceExpr(); 11822 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11823 isa<BinaryOperator>(Ignored) || 11824 isa<CXXOperatorCallExpr>(Ignored); 11825 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11826 if (NeedsParens) 11827 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11828 << FixItHint::CreateInsertion(EndLoc, ")"); 11829 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11830 } 11831 11832 /// Diagnose an implicit cast from a floating point value to an integer value. 11833 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11834 SourceLocation CContext) { 11835 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11836 const bool PruneWarnings = S.inTemplateInstantiation(); 11837 11838 Expr *InnerE = E->IgnoreParenImpCasts(); 11839 // We also want to warn on, e.g., "int i = -1.234" 11840 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11841 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11842 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11843 11844 const bool IsLiteral = 11845 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11846 11847 llvm::APFloat Value(0.0); 11848 bool IsConstant = 11849 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11850 if (!IsConstant) { 11851 if (isObjCSignedCharBool(S, T)) { 11852 return adornObjCBoolConversionDiagWithTernaryFixit( 11853 S, E, 11854 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11855 << E->getType()); 11856 } 11857 11858 return DiagnoseImpCast(S, E, T, CContext, 11859 diag::warn_impcast_float_integer, PruneWarnings); 11860 } 11861 11862 bool isExact = false; 11863 11864 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11865 T->hasUnsignedIntegerRepresentation()); 11866 llvm::APFloat::opStatus Result = Value.convertToInteger( 11867 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11868 11869 // FIXME: Force the precision of the source value down so we don't print 11870 // digits which are usually useless (we don't really care here if we 11871 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11872 // would automatically print the shortest representation, but it's a bit 11873 // tricky to implement. 11874 SmallString<16> PrettySourceValue; 11875 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11876 precision = (precision * 59 + 195) / 196; 11877 Value.toString(PrettySourceValue, precision); 11878 11879 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11880 return adornObjCBoolConversionDiagWithTernaryFixit( 11881 S, E, 11882 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11883 << PrettySourceValue); 11884 } 11885 11886 if (Result == llvm::APFloat::opOK && isExact) { 11887 if (IsLiteral) return; 11888 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11889 PruneWarnings); 11890 } 11891 11892 // Conversion of a floating-point value to a non-bool integer where the 11893 // integral part cannot be represented by the integer type is undefined. 11894 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11895 return DiagnoseImpCast( 11896 S, E, T, CContext, 11897 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11898 : diag::warn_impcast_float_to_integer_out_of_range, 11899 PruneWarnings); 11900 11901 unsigned DiagID = 0; 11902 if (IsLiteral) { 11903 // Warn on floating point literal to integer. 11904 DiagID = diag::warn_impcast_literal_float_to_integer; 11905 } else if (IntegerValue == 0) { 11906 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11907 return DiagnoseImpCast(S, E, T, CContext, 11908 diag::warn_impcast_float_integer, PruneWarnings); 11909 } 11910 // Warn on non-zero to zero conversion. 11911 DiagID = diag::warn_impcast_float_to_integer_zero; 11912 } else { 11913 if (IntegerValue.isUnsigned()) { 11914 if (!IntegerValue.isMaxValue()) { 11915 return DiagnoseImpCast(S, E, T, CContext, 11916 diag::warn_impcast_float_integer, PruneWarnings); 11917 } 11918 } else { // IntegerValue.isSigned() 11919 if (!IntegerValue.isMaxSignedValue() && 11920 !IntegerValue.isMinSignedValue()) { 11921 return DiagnoseImpCast(S, E, T, CContext, 11922 diag::warn_impcast_float_integer, PruneWarnings); 11923 } 11924 } 11925 // Warn on evaluatable floating point expression to integer conversion. 11926 DiagID = diag::warn_impcast_float_to_integer; 11927 } 11928 11929 SmallString<16> PrettyTargetValue; 11930 if (IsBool) 11931 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11932 else 11933 IntegerValue.toString(PrettyTargetValue); 11934 11935 if (PruneWarnings) { 11936 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11937 S.PDiag(DiagID) 11938 << E->getType() << T.getUnqualifiedType() 11939 << PrettySourceValue << PrettyTargetValue 11940 << E->getSourceRange() << SourceRange(CContext)); 11941 } else { 11942 S.Diag(E->getExprLoc(), DiagID) 11943 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11944 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11945 } 11946 } 11947 11948 /// Analyze the given compound assignment for the possible losing of 11949 /// floating-point precision. 11950 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11951 assert(isa<CompoundAssignOperator>(E) && 11952 "Must be compound assignment operation"); 11953 // Recurse on the LHS and RHS in here 11954 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11955 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11956 11957 if (E->getLHS()->getType()->isAtomicType()) 11958 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11959 11960 // Now check the outermost expression 11961 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11962 const auto *RBT = cast<CompoundAssignOperator>(E) 11963 ->getComputationResultType() 11964 ->getAs<BuiltinType>(); 11965 11966 // The below checks assume source is floating point. 11967 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11968 11969 // If source is floating point but target is an integer. 11970 if (ResultBT->isInteger()) 11971 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11972 E->getExprLoc(), diag::warn_impcast_float_integer); 11973 11974 if (!ResultBT->isFloatingPoint()) 11975 return; 11976 11977 // If both source and target are floating points, warn about losing precision. 11978 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11979 QualType(ResultBT, 0), QualType(RBT, 0)); 11980 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11981 // warn about dropping FP rank. 11982 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11983 diag::warn_impcast_float_result_precision); 11984 } 11985 11986 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11987 IntRange Range) { 11988 if (!Range.Width) return "0"; 11989 11990 llvm::APSInt ValueInRange = Value; 11991 ValueInRange.setIsSigned(!Range.NonNegative); 11992 ValueInRange = ValueInRange.trunc(Range.Width); 11993 return toString(ValueInRange, 10); 11994 } 11995 11996 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11997 if (!isa<ImplicitCastExpr>(Ex)) 11998 return false; 11999 12000 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12001 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12002 const Type *Source = 12003 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12004 if (Target->isDependentType()) 12005 return false; 12006 12007 const BuiltinType *FloatCandidateBT = 12008 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12009 const Type *BoolCandidateType = ToBool ? Target : Source; 12010 12011 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12012 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12013 } 12014 12015 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12016 SourceLocation CC) { 12017 unsigned NumArgs = TheCall->getNumArgs(); 12018 for (unsigned i = 0; i < NumArgs; ++i) { 12019 Expr *CurrA = TheCall->getArg(i); 12020 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12021 continue; 12022 12023 bool IsSwapped = ((i > 0) && 12024 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12025 IsSwapped |= ((i < (NumArgs - 1)) && 12026 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12027 if (IsSwapped) { 12028 // Warn on this floating-point to bool conversion. 12029 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12030 CurrA->getType(), CC, 12031 diag::warn_impcast_floating_point_to_bool); 12032 } 12033 } 12034 } 12035 12036 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12037 SourceLocation CC) { 12038 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12039 E->getExprLoc())) 12040 return; 12041 12042 // Don't warn on functions which have return type nullptr_t. 12043 if (isa<CallExpr>(E)) 12044 return; 12045 12046 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12047 const Expr::NullPointerConstantKind NullKind = 12048 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12049 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12050 return; 12051 12052 // Return if target type is a safe conversion. 12053 if (T->isAnyPointerType() || T->isBlockPointerType() || 12054 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12055 return; 12056 12057 SourceLocation Loc = E->getSourceRange().getBegin(); 12058 12059 // Venture through the macro stacks to get to the source of macro arguments. 12060 // The new location is a better location than the complete location that was 12061 // passed in. 12062 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12063 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12064 12065 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12066 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12067 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12068 Loc, S.SourceMgr, S.getLangOpts()); 12069 if (MacroName == "NULL") 12070 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12071 } 12072 12073 // Only warn if the null and context location are in the same macro expansion. 12074 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12075 return; 12076 12077 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12078 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12079 << FixItHint::CreateReplacement(Loc, 12080 S.getFixItZeroLiteralForType(T, Loc)); 12081 } 12082 12083 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12084 ObjCArrayLiteral *ArrayLiteral); 12085 12086 static void 12087 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12088 ObjCDictionaryLiteral *DictionaryLiteral); 12089 12090 /// Check a single element within a collection literal against the 12091 /// target element type. 12092 static void checkObjCCollectionLiteralElement(Sema &S, 12093 QualType TargetElementType, 12094 Expr *Element, 12095 unsigned ElementKind) { 12096 // Skip a bitcast to 'id' or qualified 'id'. 12097 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12098 if (ICE->getCastKind() == CK_BitCast && 12099 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12100 Element = ICE->getSubExpr(); 12101 } 12102 12103 QualType ElementType = Element->getType(); 12104 ExprResult ElementResult(Element); 12105 if (ElementType->getAs<ObjCObjectPointerType>() && 12106 S.CheckSingleAssignmentConstraints(TargetElementType, 12107 ElementResult, 12108 false, false) 12109 != Sema::Compatible) { 12110 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12111 << ElementType << ElementKind << TargetElementType 12112 << Element->getSourceRange(); 12113 } 12114 12115 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12116 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12117 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12118 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12119 } 12120 12121 /// Check an Objective-C array literal being converted to the given 12122 /// target type. 12123 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12124 ObjCArrayLiteral *ArrayLiteral) { 12125 if (!S.NSArrayDecl) 12126 return; 12127 12128 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12129 if (!TargetObjCPtr) 12130 return; 12131 12132 if (TargetObjCPtr->isUnspecialized() || 12133 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12134 != S.NSArrayDecl->getCanonicalDecl()) 12135 return; 12136 12137 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12138 if (TypeArgs.size() != 1) 12139 return; 12140 12141 QualType TargetElementType = TypeArgs[0]; 12142 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12143 checkObjCCollectionLiteralElement(S, TargetElementType, 12144 ArrayLiteral->getElement(I), 12145 0); 12146 } 12147 } 12148 12149 /// Check an Objective-C dictionary literal being converted to the given 12150 /// target type. 12151 static void 12152 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12153 ObjCDictionaryLiteral *DictionaryLiteral) { 12154 if (!S.NSDictionaryDecl) 12155 return; 12156 12157 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12158 if (!TargetObjCPtr) 12159 return; 12160 12161 if (TargetObjCPtr->isUnspecialized() || 12162 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12163 != S.NSDictionaryDecl->getCanonicalDecl()) 12164 return; 12165 12166 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12167 if (TypeArgs.size() != 2) 12168 return; 12169 12170 QualType TargetKeyType = TypeArgs[0]; 12171 QualType TargetObjectType = TypeArgs[1]; 12172 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12173 auto Element = DictionaryLiteral->getKeyValueElement(I); 12174 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12175 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12176 } 12177 } 12178 12179 // Helper function to filter out cases for constant width constant conversion. 12180 // Don't warn on char array initialization or for non-decimal values. 12181 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12182 SourceLocation CC) { 12183 // If initializing from a constant, and the constant starts with '0', 12184 // then it is a binary, octal, or hexadecimal. Allow these constants 12185 // to fill all the bits, even if there is a sign change. 12186 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12187 const char FirstLiteralCharacter = 12188 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12189 if (FirstLiteralCharacter == '0') 12190 return false; 12191 } 12192 12193 // If the CC location points to a '{', and the type is char, then assume 12194 // assume it is an array initialization. 12195 if (CC.isValid() && T->isCharType()) { 12196 const char FirstContextCharacter = 12197 S.getSourceManager().getCharacterData(CC)[0]; 12198 if (FirstContextCharacter == '{') 12199 return false; 12200 } 12201 12202 return true; 12203 } 12204 12205 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12206 const auto *IL = dyn_cast<IntegerLiteral>(E); 12207 if (!IL) { 12208 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12209 if (UO->getOpcode() == UO_Minus) 12210 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12211 } 12212 } 12213 12214 return IL; 12215 } 12216 12217 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12218 E = E->IgnoreParenImpCasts(); 12219 SourceLocation ExprLoc = E->getExprLoc(); 12220 12221 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12222 BinaryOperator::Opcode Opc = BO->getOpcode(); 12223 Expr::EvalResult Result; 12224 // Do not diagnose unsigned shifts. 12225 if (Opc == BO_Shl) { 12226 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12227 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12228 if (LHS && LHS->getValue() == 0) 12229 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12230 else if (!E->isValueDependent() && LHS && RHS && 12231 RHS->getValue().isNonNegative() && 12232 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12233 S.Diag(ExprLoc, diag::warn_left_shift_always) 12234 << (Result.Val.getInt() != 0); 12235 else if (E->getType()->isSignedIntegerType()) 12236 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12237 } 12238 } 12239 12240 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12241 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12242 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12243 if (!LHS || !RHS) 12244 return; 12245 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12246 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12247 // Do not diagnose common idioms. 12248 return; 12249 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12250 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12251 } 12252 } 12253 12254 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12255 SourceLocation CC, 12256 bool *ICContext = nullptr, 12257 bool IsListInit = false) { 12258 if (E->isTypeDependent() || E->isValueDependent()) return; 12259 12260 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12261 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12262 if (Source == Target) return; 12263 if (Target->isDependentType()) return; 12264 12265 // If the conversion context location is invalid don't complain. We also 12266 // don't want to emit a warning if the issue occurs from the expansion of 12267 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12268 // delay this check as long as possible. Once we detect we are in that 12269 // scenario, we just return. 12270 if (CC.isInvalid()) 12271 return; 12272 12273 if (Source->isAtomicType()) 12274 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12275 12276 // Diagnose implicit casts to bool. 12277 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12278 if (isa<StringLiteral>(E)) 12279 // Warn on string literal to bool. Checks for string literals in logical 12280 // and expressions, for instance, assert(0 && "error here"), are 12281 // prevented by a check in AnalyzeImplicitConversions(). 12282 return DiagnoseImpCast(S, E, T, CC, 12283 diag::warn_impcast_string_literal_to_bool); 12284 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12285 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12286 // This covers the literal expressions that evaluate to Objective-C 12287 // objects. 12288 return DiagnoseImpCast(S, E, T, CC, 12289 diag::warn_impcast_objective_c_literal_to_bool); 12290 } 12291 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12292 // Warn on pointer to bool conversion that is always true. 12293 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12294 SourceRange(CC)); 12295 } 12296 } 12297 12298 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12299 // is a typedef for signed char (macOS), then that constant value has to be 1 12300 // or 0. 12301 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12302 Expr::EvalResult Result; 12303 if (E->EvaluateAsInt(Result, S.getASTContext(), 12304 Expr::SE_AllowSideEffects)) { 12305 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12306 adornObjCBoolConversionDiagWithTernaryFixit( 12307 S, E, 12308 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12309 << toString(Result.Val.getInt(), 10)); 12310 } 12311 return; 12312 } 12313 } 12314 12315 // Check implicit casts from Objective-C collection literals to specialized 12316 // collection types, e.g., NSArray<NSString *> *. 12317 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12318 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12319 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12320 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12321 12322 // Strip vector types. 12323 if (const auto *SourceVT = dyn_cast<VectorType>(Source)) { 12324 if (Target->isVLSTBuiltinType()) { 12325 auto SourceVectorKind = SourceVT->getVectorKind(); 12326 if (SourceVectorKind == VectorType::SveFixedLengthDataVector || 12327 SourceVectorKind == VectorType::SveFixedLengthPredicateVector || 12328 (SourceVectorKind == VectorType::GenericVector && 12329 S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits)) 12330 return; 12331 } 12332 12333 if (!isa<VectorType>(Target)) { 12334 if (S.SourceMgr.isInSystemMacro(CC)) 12335 return; 12336 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12337 } 12338 12339 // If the vector cast is cast between two vectors of the same size, it is 12340 // a bitcast, not a conversion. 12341 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12342 return; 12343 12344 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12345 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12346 } 12347 if (auto VecTy = dyn_cast<VectorType>(Target)) 12348 Target = VecTy->getElementType().getTypePtr(); 12349 12350 // Strip complex types. 12351 if (isa<ComplexType>(Source)) { 12352 if (!isa<ComplexType>(Target)) { 12353 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12354 return; 12355 12356 return DiagnoseImpCast(S, E, T, CC, 12357 S.getLangOpts().CPlusPlus 12358 ? diag::err_impcast_complex_scalar 12359 : diag::warn_impcast_complex_scalar); 12360 } 12361 12362 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12363 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12364 } 12365 12366 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12367 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12368 12369 // If the source is floating point... 12370 if (SourceBT && SourceBT->isFloatingPoint()) { 12371 // ...and the target is floating point... 12372 if (TargetBT && TargetBT->isFloatingPoint()) { 12373 // ...then warn if we're dropping FP rank. 12374 12375 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12376 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12377 if (Order > 0) { 12378 // Don't warn about float constants that are precisely 12379 // representable in the target type. 12380 Expr::EvalResult result; 12381 if (E->EvaluateAsRValue(result, S.Context)) { 12382 // Value might be a float, a float vector, or a float complex. 12383 if (IsSameFloatAfterCast(result.Val, 12384 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12385 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12386 return; 12387 } 12388 12389 if (S.SourceMgr.isInSystemMacro(CC)) 12390 return; 12391 12392 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12393 } 12394 // ... or possibly if we're increasing rank, too 12395 else if (Order < 0) { 12396 if (S.SourceMgr.isInSystemMacro(CC)) 12397 return; 12398 12399 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12400 } 12401 return; 12402 } 12403 12404 // If the target is integral, always warn. 12405 if (TargetBT && TargetBT->isInteger()) { 12406 if (S.SourceMgr.isInSystemMacro(CC)) 12407 return; 12408 12409 DiagnoseFloatingImpCast(S, E, T, CC); 12410 } 12411 12412 // Detect the case where a call result is converted from floating-point to 12413 // to bool, and the final argument to the call is converted from bool, to 12414 // discover this typo: 12415 // 12416 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12417 // 12418 // FIXME: This is an incredibly special case; is there some more general 12419 // way to detect this class of misplaced-parentheses bug? 12420 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12421 // Check last argument of function call to see if it is an 12422 // implicit cast from a type matching the type the result 12423 // is being cast to. 12424 CallExpr *CEx = cast<CallExpr>(E); 12425 if (unsigned NumArgs = CEx->getNumArgs()) { 12426 Expr *LastA = CEx->getArg(NumArgs - 1); 12427 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12428 if (isa<ImplicitCastExpr>(LastA) && 12429 InnerE->getType()->isBooleanType()) { 12430 // Warn on this floating-point to bool conversion 12431 DiagnoseImpCast(S, E, T, CC, 12432 diag::warn_impcast_floating_point_to_bool); 12433 } 12434 } 12435 } 12436 return; 12437 } 12438 12439 // Valid casts involving fixed point types should be accounted for here. 12440 if (Source->isFixedPointType()) { 12441 if (Target->isUnsaturatedFixedPointType()) { 12442 Expr::EvalResult Result; 12443 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12444 S.isConstantEvaluated())) { 12445 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12446 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12447 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12448 if (Value > MaxVal || Value < MinVal) { 12449 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12450 S.PDiag(diag::warn_impcast_fixed_point_range) 12451 << Value.toString() << T 12452 << E->getSourceRange() 12453 << clang::SourceRange(CC)); 12454 return; 12455 } 12456 } 12457 } else if (Target->isIntegerType()) { 12458 Expr::EvalResult Result; 12459 if (!S.isConstantEvaluated() && 12460 E->EvaluateAsFixedPoint(Result, S.Context, 12461 Expr::SE_AllowSideEffects)) { 12462 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12463 12464 bool Overflowed; 12465 llvm::APSInt IntResult = FXResult.convertToInt( 12466 S.Context.getIntWidth(T), 12467 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12468 12469 if (Overflowed) { 12470 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12471 S.PDiag(diag::warn_impcast_fixed_point_range) 12472 << FXResult.toString() << T 12473 << E->getSourceRange() 12474 << clang::SourceRange(CC)); 12475 return; 12476 } 12477 } 12478 } 12479 } else if (Target->isUnsaturatedFixedPointType()) { 12480 if (Source->isIntegerType()) { 12481 Expr::EvalResult Result; 12482 if (!S.isConstantEvaluated() && 12483 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12484 llvm::APSInt Value = Result.Val.getInt(); 12485 12486 bool Overflowed; 12487 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12488 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12489 12490 if (Overflowed) { 12491 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12492 S.PDiag(diag::warn_impcast_fixed_point_range) 12493 << toString(Value, /*Radix=*/10) << T 12494 << E->getSourceRange() 12495 << clang::SourceRange(CC)); 12496 return; 12497 } 12498 } 12499 } 12500 } 12501 12502 // If we are casting an integer type to a floating point type without 12503 // initialization-list syntax, we might lose accuracy if the floating 12504 // point type has a narrower significand than the integer type. 12505 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12506 TargetBT->isFloatingType() && !IsListInit) { 12507 // Determine the number of precision bits in the source integer type. 12508 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12509 /*Approximate*/ true); 12510 unsigned int SourcePrecision = SourceRange.Width; 12511 12512 // Determine the number of precision bits in the 12513 // target floating point type. 12514 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12515 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12516 12517 if (SourcePrecision > 0 && TargetPrecision > 0 && 12518 SourcePrecision > TargetPrecision) { 12519 12520 if (Optional<llvm::APSInt> SourceInt = 12521 E->getIntegerConstantExpr(S.Context)) { 12522 // If the source integer is a constant, convert it to the target 12523 // floating point type. Issue a warning if the value changes 12524 // during the whole conversion. 12525 llvm::APFloat TargetFloatValue( 12526 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12527 llvm::APFloat::opStatus ConversionStatus = 12528 TargetFloatValue.convertFromAPInt( 12529 *SourceInt, SourceBT->isSignedInteger(), 12530 llvm::APFloat::rmNearestTiesToEven); 12531 12532 if (ConversionStatus != llvm::APFloat::opOK) { 12533 SmallString<32> PrettySourceValue; 12534 SourceInt->toString(PrettySourceValue, 10); 12535 SmallString<32> PrettyTargetValue; 12536 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12537 12538 S.DiagRuntimeBehavior( 12539 E->getExprLoc(), E, 12540 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12541 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12542 << E->getSourceRange() << clang::SourceRange(CC)); 12543 } 12544 } else { 12545 // Otherwise, the implicit conversion may lose precision. 12546 DiagnoseImpCast(S, E, T, CC, 12547 diag::warn_impcast_integer_float_precision); 12548 } 12549 } 12550 } 12551 12552 DiagnoseNullConversion(S, E, T, CC); 12553 12554 S.DiscardMisalignedMemberAddress(Target, E); 12555 12556 if (Target->isBooleanType()) 12557 DiagnoseIntInBoolContext(S, E); 12558 12559 if (!Source->isIntegerType() || !Target->isIntegerType()) 12560 return; 12561 12562 // TODO: remove this early return once the false positives for constant->bool 12563 // in templates, macros, etc, are reduced or removed. 12564 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12565 return; 12566 12567 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12568 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12569 return adornObjCBoolConversionDiagWithTernaryFixit( 12570 S, E, 12571 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12572 << E->getType()); 12573 } 12574 12575 IntRange SourceTypeRange = 12576 IntRange::forTargetOfCanonicalType(S.Context, Source); 12577 IntRange LikelySourceRange = 12578 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12579 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12580 12581 if (LikelySourceRange.Width > TargetRange.Width) { 12582 // If the source is a constant, use a default-on diagnostic. 12583 // TODO: this should happen for bitfield stores, too. 12584 Expr::EvalResult Result; 12585 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12586 S.isConstantEvaluated())) { 12587 llvm::APSInt Value(32); 12588 Value = Result.Val.getInt(); 12589 12590 if (S.SourceMgr.isInSystemMacro(CC)) 12591 return; 12592 12593 std::string PrettySourceValue = toString(Value, 10); 12594 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12595 12596 S.DiagRuntimeBehavior( 12597 E->getExprLoc(), E, 12598 S.PDiag(diag::warn_impcast_integer_precision_constant) 12599 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12600 << E->getSourceRange() << SourceRange(CC)); 12601 return; 12602 } 12603 12604 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12605 if (S.SourceMgr.isInSystemMacro(CC)) 12606 return; 12607 12608 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12609 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12610 /* pruneControlFlow */ true); 12611 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12612 } 12613 12614 if (TargetRange.Width > SourceTypeRange.Width) { 12615 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12616 if (UO->getOpcode() == UO_Minus) 12617 if (Source->isUnsignedIntegerType()) { 12618 if (Target->isUnsignedIntegerType()) 12619 return DiagnoseImpCast(S, E, T, CC, 12620 diag::warn_impcast_high_order_zero_bits); 12621 if (Target->isSignedIntegerType()) 12622 return DiagnoseImpCast(S, E, T, CC, 12623 diag::warn_impcast_nonnegative_result); 12624 } 12625 } 12626 12627 if (TargetRange.Width == LikelySourceRange.Width && 12628 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12629 Source->isSignedIntegerType()) { 12630 // Warn when doing a signed to signed conversion, warn if the positive 12631 // source value is exactly the width of the target type, which will 12632 // cause a negative value to be stored. 12633 12634 Expr::EvalResult Result; 12635 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12636 !S.SourceMgr.isInSystemMacro(CC)) { 12637 llvm::APSInt Value = Result.Val.getInt(); 12638 if (isSameWidthConstantConversion(S, E, T, CC)) { 12639 std::string PrettySourceValue = toString(Value, 10); 12640 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12641 12642 S.DiagRuntimeBehavior( 12643 E->getExprLoc(), E, 12644 S.PDiag(diag::warn_impcast_integer_precision_constant) 12645 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12646 << E->getSourceRange() << SourceRange(CC)); 12647 return; 12648 } 12649 } 12650 12651 // Fall through for non-constants to give a sign conversion warning. 12652 } 12653 12654 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12655 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12656 LikelySourceRange.Width == TargetRange.Width)) { 12657 if (S.SourceMgr.isInSystemMacro(CC)) 12658 return; 12659 12660 unsigned DiagID = diag::warn_impcast_integer_sign; 12661 12662 // Traditionally, gcc has warned about this under -Wsign-compare. 12663 // We also want to warn about it in -Wconversion. 12664 // So if -Wconversion is off, use a completely identical diagnostic 12665 // in the sign-compare group. 12666 // The conditional-checking code will 12667 if (ICContext) { 12668 DiagID = diag::warn_impcast_integer_sign_conditional; 12669 *ICContext = true; 12670 } 12671 12672 return DiagnoseImpCast(S, E, T, CC, DiagID); 12673 } 12674 12675 // Diagnose conversions between different enumeration types. 12676 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12677 // type, to give us better diagnostics. 12678 QualType SourceType = E->getType(); 12679 if (!S.getLangOpts().CPlusPlus) { 12680 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12681 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12682 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12683 SourceType = S.Context.getTypeDeclType(Enum); 12684 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12685 } 12686 } 12687 12688 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12689 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12690 if (SourceEnum->getDecl()->hasNameForLinkage() && 12691 TargetEnum->getDecl()->hasNameForLinkage() && 12692 SourceEnum != TargetEnum) { 12693 if (S.SourceMgr.isInSystemMacro(CC)) 12694 return; 12695 12696 return DiagnoseImpCast(S, E, SourceType, T, CC, 12697 diag::warn_impcast_different_enum_types); 12698 } 12699 } 12700 12701 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12702 SourceLocation CC, QualType T); 12703 12704 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12705 SourceLocation CC, bool &ICContext) { 12706 E = E->IgnoreParenImpCasts(); 12707 12708 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12709 return CheckConditionalOperator(S, CO, CC, T); 12710 12711 AnalyzeImplicitConversions(S, E, CC); 12712 if (E->getType() != T) 12713 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12714 } 12715 12716 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12717 SourceLocation CC, QualType T) { 12718 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12719 12720 Expr *TrueExpr = E->getTrueExpr(); 12721 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12722 TrueExpr = BCO->getCommon(); 12723 12724 bool Suspicious = false; 12725 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12726 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12727 12728 if (T->isBooleanType()) 12729 DiagnoseIntInBoolContext(S, E); 12730 12731 // If -Wconversion would have warned about either of the candidates 12732 // for a signedness conversion to the context type... 12733 if (!Suspicious) return; 12734 12735 // ...but it's currently ignored... 12736 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12737 return; 12738 12739 // ...then check whether it would have warned about either of the 12740 // candidates for a signedness conversion to the condition type. 12741 if (E->getType() == T) return; 12742 12743 Suspicious = false; 12744 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12745 E->getType(), CC, &Suspicious); 12746 if (!Suspicious) 12747 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12748 E->getType(), CC, &Suspicious); 12749 } 12750 12751 /// Check conversion of given expression to boolean. 12752 /// Input argument E is a logical expression. 12753 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12754 if (S.getLangOpts().Bool) 12755 return; 12756 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12757 return; 12758 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12759 } 12760 12761 namespace { 12762 struct AnalyzeImplicitConversionsWorkItem { 12763 Expr *E; 12764 SourceLocation CC; 12765 bool IsListInit; 12766 }; 12767 } 12768 12769 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12770 /// that should be visited are added to WorkList. 12771 static void AnalyzeImplicitConversions( 12772 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12773 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12774 Expr *OrigE = Item.E; 12775 SourceLocation CC = Item.CC; 12776 12777 QualType T = OrigE->getType(); 12778 Expr *E = OrigE->IgnoreParenImpCasts(); 12779 12780 // Propagate whether we are in a C++ list initialization expression. 12781 // If so, we do not issue warnings for implicit int-float conversion 12782 // precision loss, because C++11 narrowing already handles it. 12783 bool IsListInit = Item.IsListInit || 12784 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12785 12786 if (E->isTypeDependent() || E->isValueDependent()) 12787 return; 12788 12789 Expr *SourceExpr = E; 12790 // Examine, but don't traverse into the source expression of an 12791 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12792 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12793 // evaluate it in the context of checking the specific conversion to T though. 12794 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12795 if (auto *Src = OVE->getSourceExpr()) 12796 SourceExpr = Src; 12797 12798 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12799 if (UO->getOpcode() == UO_Not && 12800 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12801 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12802 << OrigE->getSourceRange() << T->isBooleanType() 12803 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12804 12805 // For conditional operators, we analyze the arguments as if they 12806 // were being fed directly into the output. 12807 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12808 CheckConditionalOperator(S, CO, CC, T); 12809 return; 12810 } 12811 12812 // Check implicit argument conversions for function calls. 12813 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12814 CheckImplicitArgumentConversions(S, Call, CC); 12815 12816 // Go ahead and check any implicit conversions we might have skipped. 12817 // The non-canonical typecheck is just an optimization; 12818 // CheckImplicitConversion will filter out dead implicit conversions. 12819 if (SourceExpr->getType() != T) 12820 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12821 12822 // Now continue drilling into this expression. 12823 12824 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12825 // The bound subexpressions in a PseudoObjectExpr are not reachable 12826 // as transitive children. 12827 // FIXME: Use a more uniform representation for this. 12828 for (auto *SE : POE->semantics()) 12829 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12830 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12831 } 12832 12833 // Skip past explicit casts. 12834 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12835 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12836 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12837 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12838 WorkList.push_back({E, CC, IsListInit}); 12839 return; 12840 } 12841 12842 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12843 // Do a somewhat different check with comparison operators. 12844 if (BO->isComparisonOp()) 12845 return AnalyzeComparison(S, BO); 12846 12847 // And with simple assignments. 12848 if (BO->getOpcode() == BO_Assign) 12849 return AnalyzeAssignment(S, BO); 12850 // And with compound assignments. 12851 if (BO->isAssignmentOp()) 12852 return AnalyzeCompoundAssignment(S, BO); 12853 } 12854 12855 // These break the otherwise-useful invariant below. Fortunately, 12856 // we don't really need to recurse into them, because any internal 12857 // expressions should have been analyzed already when they were 12858 // built into statements. 12859 if (isa<StmtExpr>(E)) return; 12860 12861 // Don't descend into unevaluated contexts. 12862 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12863 12864 // Now just recurse over the expression's children. 12865 CC = E->getExprLoc(); 12866 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12867 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12868 for (Stmt *SubStmt : E->children()) { 12869 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12870 if (!ChildExpr) 12871 continue; 12872 12873 if (IsLogicalAndOperator && 12874 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12875 // Ignore checking string literals that are in logical and operators. 12876 // This is a common pattern for asserts. 12877 continue; 12878 WorkList.push_back({ChildExpr, CC, IsListInit}); 12879 } 12880 12881 if (BO && BO->isLogicalOp()) { 12882 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12883 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12884 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12885 12886 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12887 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12888 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12889 } 12890 12891 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12892 if (U->getOpcode() == UO_LNot) { 12893 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12894 } else if (U->getOpcode() != UO_AddrOf) { 12895 if (U->getSubExpr()->getType()->isAtomicType()) 12896 S.Diag(U->getSubExpr()->getBeginLoc(), 12897 diag::warn_atomic_implicit_seq_cst); 12898 } 12899 } 12900 } 12901 12902 /// AnalyzeImplicitConversions - Find and report any interesting 12903 /// implicit conversions in the given expression. There are a couple 12904 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12905 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12906 bool IsListInit/*= false*/) { 12907 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12908 WorkList.push_back({OrigE, CC, IsListInit}); 12909 while (!WorkList.empty()) 12910 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12911 } 12912 12913 /// Diagnose integer type and any valid implicit conversion to it. 12914 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12915 // Taking into account implicit conversions, 12916 // allow any integer. 12917 if (!E->getType()->isIntegerType()) { 12918 S.Diag(E->getBeginLoc(), 12919 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12920 return true; 12921 } 12922 // Potentially emit standard warnings for implicit conversions if enabled 12923 // using -Wconversion. 12924 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12925 return false; 12926 } 12927 12928 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12929 // Returns true when emitting a warning about taking the address of a reference. 12930 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12931 const PartialDiagnostic &PD) { 12932 E = E->IgnoreParenImpCasts(); 12933 12934 const FunctionDecl *FD = nullptr; 12935 12936 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12937 if (!DRE->getDecl()->getType()->isReferenceType()) 12938 return false; 12939 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12940 if (!M->getMemberDecl()->getType()->isReferenceType()) 12941 return false; 12942 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12943 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12944 return false; 12945 FD = Call->getDirectCallee(); 12946 } else { 12947 return false; 12948 } 12949 12950 SemaRef.Diag(E->getExprLoc(), PD); 12951 12952 // If possible, point to location of function. 12953 if (FD) { 12954 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12955 } 12956 12957 return true; 12958 } 12959 12960 // Returns true if the SourceLocation is expanded from any macro body. 12961 // Returns false if the SourceLocation is invalid, is from not in a macro 12962 // expansion, or is from expanded from a top-level macro argument. 12963 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12964 if (Loc.isInvalid()) 12965 return false; 12966 12967 while (Loc.isMacroID()) { 12968 if (SM.isMacroBodyExpansion(Loc)) 12969 return true; 12970 Loc = SM.getImmediateMacroCallerLoc(Loc); 12971 } 12972 12973 return false; 12974 } 12975 12976 /// Diagnose pointers that are always non-null. 12977 /// \param E the expression containing the pointer 12978 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12979 /// compared to a null pointer 12980 /// \param IsEqual True when the comparison is equal to a null pointer 12981 /// \param Range Extra SourceRange to highlight in the diagnostic 12982 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12983 Expr::NullPointerConstantKind NullKind, 12984 bool IsEqual, SourceRange Range) { 12985 if (!E) 12986 return; 12987 12988 // Don't warn inside macros. 12989 if (E->getExprLoc().isMacroID()) { 12990 const SourceManager &SM = getSourceManager(); 12991 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12992 IsInAnyMacroBody(SM, Range.getBegin())) 12993 return; 12994 } 12995 E = E->IgnoreImpCasts(); 12996 12997 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12998 12999 if (isa<CXXThisExpr>(E)) { 13000 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13001 : diag::warn_this_bool_conversion; 13002 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13003 return; 13004 } 13005 13006 bool IsAddressOf = false; 13007 13008 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13009 if (UO->getOpcode() != UO_AddrOf) 13010 return; 13011 IsAddressOf = true; 13012 E = UO->getSubExpr(); 13013 } 13014 13015 if (IsAddressOf) { 13016 unsigned DiagID = IsCompare 13017 ? diag::warn_address_of_reference_null_compare 13018 : diag::warn_address_of_reference_bool_conversion; 13019 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13020 << IsEqual; 13021 if (CheckForReference(*this, E, PD)) { 13022 return; 13023 } 13024 } 13025 13026 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13027 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13028 std::string Str; 13029 llvm::raw_string_ostream S(Str); 13030 E->printPretty(S, nullptr, getPrintingPolicy()); 13031 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13032 : diag::warn_cast_nonnull_to_bool; 13033 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13034 << E->getSourceRange() << Range << IsEqual; 13035 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13036 }; 13037 13038 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13039 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13040 if (auto *Callee = Call->getDirectCallee()) { 13041 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13042 ComplainAboutNonnullParamOrCall(A); 13043 return; 13044 } 13045 } 13046 } 13047 13048 // Expect to find a single Decl. Skip anything more complicated. 13049 ValueDecl *D = nullptr; 13050 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13051 D = R->getDecl(); 13052 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13053 D = M->getMemberDecl(); 13054 } 13055 13056 // Weak Decls can be null. 13057 if (!D || D->isWeak()) 13058 return; 13059 13060 // Check for parameter decl with nonnull attribute 13061 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13062 if (getCurFunction() && 13063 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13064 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13065 ComplainAboutNonnullParamOrCall(A); 13066 return; 13067 } 13068 13069 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13070 // Skip function template not specialized yet. 13071 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13072 return; 13073 auto ParamIter = llvm::find(FD->parameters(), PV); 13074 assert(ParamIter != FD->param_end()); 13075 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13076 13077 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13078 if (!NonNull->args_size()) { 13079 ComplainAboutNonnullParamOrCall(NonNull); 13080 return; 13081 } 13082 13083 for (const ParamIdx &ArgNo : NonNull->args()) { 13084 if (ArgNo.getASTIndex() == ParamNo) { 13085 ComplainAboutNonnullParamOrCall(NonNull); 13086 return; 13087 } 13088 } 13089 } 13090 } 13091 } 13092 } 13093 13094 QualType T = D->getType(); 13095 const bool IsArray = T->isArrayType(); 13096 const bool IsFunction = T->isFunctionType(); 13097 13098 // Address of function is used to silence the function warning. 13099 if (IsAddressOf && IsFunction) { 13100 return; 13101 } 13102 13103 // Found nothing. 13104 if (!IsAddressOf && !IsFunction && !IsArray) 13105 return; 13106 13107 // Pretty print the expression for the diagnostic. 13108 std::string Str; 13109 llvm::raw_string_ostream S(Str); 13110 E->printPretty(S, nullptr, getPrintingPolicy()); 13111 13112 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13113 : diag::warn_impcast_pointer_to_bool; 13114 enum { 13115 AddressOf, 13116 FunctionPointer, 13117 ArrayPointer 13118 } DiagType; 13119 if (IsAddressOf) 13120 DiagType = AddressOf; 13121 else if (IsFunction) 13122 DiagType = FunctionPointer; 13123 else if (IsArray) 13124 DiagType = ArrayPointer; 13125 else 13126 llvm_unreachable("Could not determine diagnostic."); 13127 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13128 << Range << IsEqual; 13129 13130 if (!IsFunction) 13131 return; 13132 13133 // Suggest '&' to silence the function warning. 13134 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13135 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13136 13137 // Check to see if '()' fixit should be emitted. 13138 QualType ReturnType; 13139 UnresolvedSet<4> NonTemplateOverloads; 13140 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13141 if (ReturnType.isNull()) 13142 return; 13143 13144 if (IsCompare) { 13145 // There are two cases here. If there is null constant, the only suggest 13146 // for a pointer return type. If the null is 0, then suggest if the return 13147 // type is a pointer or an integer type. 13148 if (!ReturnType->isPointerType()) { 13149 if (NullKind == Expr::NPCK_ZeroExpression || 13150 NullKind == Expr::NPCK_ZeroLiteral) { 13151 if (!ReturnType->isIntegerType()) 13152 return; 13153 } else { 13154 return; 13155 } 13156 } 13157 } else { // !IsCompare 13158 // For function to bool, only suggest if the function pointer has bool 13159 // return type. 13160 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13161 return; 13162 } 13163 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13164 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13165 } 13166 13167 /// Diagnoses "dangerous" implicit conversions within the given 13168 /// expression (which is a full expression). Implements -Wconversion 13169 /// and -Wsign-compare. 13170 /// 13171 /// \param CC the "context" location of the implicit conversion, i.e. 13172 /// the most location of the syntactic entity requiring the implicit 13173 /// conversion 13174 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13175 // Don't diagnose in unevaluated contexts. 13176 if (isUnevaluatedContext()) 13177 return; 13178 13179 // Don't diagnose for value- or type-dependent expressions. 13180 if (E->isTypeDependent() || E->isValueDependent()) 13181 return; 13182 13183 // Check for array bounds violations in cases where the check isn't triggered 13184 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13185 // ArraySubscriptExpr is on the RHS of a variable initialization. 13186 CheckArrayAccess(E); 13187 13188 // This is not the right CC for (e.g.) a variable initialization. 13189 AnalyzeImplicitConversions(*this, E, CC); 13190 } 13191 13192 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13193 /// Input argument E is a logical expression. 13194 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13195 ::CheckBoolLikeConversion(*this, E, CC); 13196 } 13197 13198 /// Diagnose when expression is an integer constant expression and its evaluation 13199 /// results in integer overflow 13200 void Sema::CheckForIntOverflow (Expr *E) { 13201 // Use a work list to deal with nested struct initializers. 13202 SmallVector<Expr *, 2> Exprs(1, E); 13203 13204 do { 13205 Expr *OriginalE = Exprs.pop_back_val(); 13206 Expr *E = OriginalE->IgnoreParenCasts(); 13207 13208 if (isa<BinaryOperator>(E)) { 13209 E->EvaluateForOverflow(Context); 13210 continue; 13211 } 13212 13213 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13214 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13215 else if (isa<ObjCBoxedExpr>(OriginalE)) 13216 E->EvaluateForOverflow(Context); 13217 else if (auto Call = dyn_cast<CallExpr>(E)) 13218 Exprs.append(Call->arg_begin(), Call->arg_end()); 13219 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13220 Exprs.append(Message->arg_begin(), Message->arg_end()); 13221 } while (!Exprs.empty()); 13222 } 13223 13224 namespace { 13225 13226 /// Visitor for expressions which looks for unsequenced operations on the 13227 /// same object. 13228 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13229 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13230 13231 /// A tree of sequenced regions within an expression. Two regions are 13232 /// unsequenced if one is an ancestor or a descendent of the other. When we 13233 /// finish processing an expression with sequencing, such as a comma 13234 /// expression, we fold its tree nodes into its parent, since they are 13235 /// unsequenced with respect to nodes we will visit later. 13236 class SequenceTree { 13237 struct Value { 13238 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13239 unsigned Parent : 31; 13240 unsigned Merged : 1; 13241 }; 13242 SmallVector<Value, 8> Values; 13243 13244 public: 13245 /// A region within an expression which may be sequenced with respect 13246 /// to some other region. 13247 class Seq { 13248 friend class SequenceTree; 13249 13250 unsigned Index; 13251 13252 explicit Seq(unsigned N) : Index(N) {} 13253 13254 public: 13255 Seq() : Index(0) {} 13256 }; 13257 13258 SequenceTree() { Values.push_back(Value(0)); } 13259 Seq root() const { return Seq(0); } 13260 13261 /// Create a new sequence of operations, which is an unsequenced 13262 /// subset of \p Parent. This sequence of operations is sequenced with 13263 /// respect to other children of \p Parent. 13264 Seq allocate(Seq Parent) { 13265 Values.push_back(Value(Parent.Index)); 13266 return Seq(Values.size() - 1); 13267 } 13268 13269 /// Merge a sequence of operations into its parent. 13270 void merge(Seq S) { 13271 Values[S.Index].Merged = true; 13272 } 13273 13274 /// Determine whether two operations are unsequenced. This operation 13275 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13276 /// should have been merged into its parent as appropriate. 13277 bool isUnsequenced(Seq Cur, Seq Old) { 13278 unsigned C = representative(Cur.Index); 13279 unsigned Target = representative(Old.Index); 13280 while (C >= Target) { 13281 if (C == Target) 13282 return true; 13283 C = Values[C].Parent; 13284 } 13285 return false; 13286 } 13287 13288 private: 13289 /// Pick a representative for a sequence. 13290 unsigned representative(unsigned K) { 13291 if (Values[K].Merged) 13292 // Perform path compression as we go. 13293 return Values[K].Parent = representative(Values[K].Parent); 13294 return K; 13295 } 13296 }; 13297 13298 /// An object for which we can track unsequenced uses. 13299 using Object = const NamedDecl *; 13300 13301 /// Different flavors of object usage which we track. We only track the 13302 /// least-sequenced usage of each kind. 13303 enum UsageKind { 13304 /// A read of an object. Multiple unsequenced reads are OK. 13305 UK_Use, 13306 13307 /// A modification of an object which is sequenced before the value 13308 /// computation of the expression, such as ++n in C++. 13309 UK_ModAsValue, 13310 13311 /// A modification of an object which is not sequenced before the value 13312 /// computation of the expression, such as n++. 13313 UK_ModAsSideEffect, 13314 13315 UK_Count = UK_ModAsSideEffect + 1 13316 }; 13317 13318 /// Bundle together a sequencing region and the expression corresponding 13319 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13320 struct Usage { 13321 const Expr *UsageExpr; 13322 SequenceTree::Seq Seq; 13323 13324 Usage() : UsageExpr(nullptr), Seq() {} 13325 }; 13326 13327 struct UsageInfo { 13328 Usage Uses[UK_Count]; 13329 13330 /// Have we issued a diagnostic for this object already? 13331 bool Diagnosed; 13332 13333 UsageInfo() : Uses(), Diagnosed(false) {} 13334 }; 13335 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13336 13337 Sema &SemaRef; 13338 13339 /// Sequenced regions within the expression. 13340 SequenceTree Tree; 13341 13342 /// Declaration modifications and references which we have seen. 13343 UsageInfoMap UsageMap; 13344 13345 /// The region we are currently within. 13346 SequenceTree::Seq Region; 13347 13348 /// Filled in with declarations which were modified as a side-effect 13349 /// (that is, post-increment operations). 13350 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13351 13352 /// Expressions to check later. We defer checking these to reduce 13353 /// stack usage. 13354 SmallVectorImpl<const Expr *> &WorkList; 13355 13356 /// RAII object wrapping the visitation of a sequenced subexpression of an 13357 /// expression. At the end of this process, the side-effects of the evaluation 13358 /// become sequenced with respect to the value computation of the result, so 13359 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13360 /// UK_ModAsValue. 13361 struct SequencedSubexpression { 13362 SequencedSubexpression(SequenceChecker &Self) 13363 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13364 Self.ModAsSideEffect = &ModAsSideEffect; 13365 } 13366 13367 ~SequencedSubexpression() { 13368 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13369 // Add a new usage with usage kind UK_ModAsValue, and then restore 13370 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13371 // the previous one was empty). 13372 UsageInfo &UI = Self.UsageMap[M.first]; 13373 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13374 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13375 SideEffectUsage = M.second; 13376 } 13377 Self.ModAsSideEffect = OldModAsSideEffect; 13378 } 13379 13380 SequenceChecker &Self; 13381 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13382 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13383 }; 13384 13385 /// RAII object wrapping the visitation of a subexpression which we might 13386 /// choose to evaluate as a constant. If any subexpression is evaluated and 13387 /// found to be non-constant, this allows us to suppress the evaluation of 13388 /// the outer expression. 13389 class EvaluationTracker { 13390 public: 13391 EvaluationTracker(SequenceChecker &Self) 13392 : Self(Self), Prev(Self.EvalTracker) { 13393 Self.EvalTracker = this; 13394 } 13395 13396 ~EvaluationTracker() { 13397 Self.EvalTracker = Prev; 13398 if (Prev) 13399 Prev->EvalOK &= EvalOK; 13400 } 13401 13402 bool evaluate(const Expr *E, bool &Result) { 13403 if (!EvalOK || E->isValueDependent()) 13404 return false; 13405 EvalOK = E->EvaluateAsBooleanCondition( 13406 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13407 return EvalOK; 13408 } 13409 13410 private: 13411 SequenceChecker &Self; 13412 EvaluationTracker *Prev; 13413 bool EvalOK = true; 13414 } *EvalTracker = nullptr; 13415 13416 /// Find the object which is produced by the specified expression, 13417 /// if any. 13418 Object getObject(const Expr *E, bool Mod) const { 13419 E = E->IgnoreParenCasts(); 13420 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13421 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13422 return getObject(UO->getSubExpr(), Mod); 13423 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13424 if (BO->getOpcode() == BO_Comma) 13425 return getObject(BO->getRHS(), Mod); 13426 if (Mod && BO->isAssignmentOp()) 13427 return getObject(BO->getLHS(), Mod); 13428 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13429 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13430 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13431 return ME->getMemberDecl(); 13432 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13433 // FIXME: If this is a reference, map through to its value. 13434 return DRE->getDecl(); 13435 return nullptr; 13436 } 13437 13438 /// Note that an object \p O was modified or used by an expression 13439 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13440 /// the object \p O as obtained via the \p UsageMap. 13441 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13442 // Get the old usage for the given object and usage kind. 13443 Usage &U = UI.Uses[UK]; 13444 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13445 // If we have a modification as side effect and are in a sequenced 13446 // subexpression, save the old Usage so that we can restore it later 13447 // in SequencedSubexpression::~SequencedSubexpression. 13448 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13449 ModAsSideEffect->push_back(std::make_pair(O, U)); 13450 // Then record the new usage with the current sequencing region. 13451 U.UsageExpr = UsageExpr; 13452 U.Seq = Region; 13453 } 13454 } 13455 13456 /// Check whether a modification or use of an object \p O in an expression 13457 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13458 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13459 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13460 /// usage and false we are checking for a mod-use unsequenced usage. 13461 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13462 UsageKind OtherKind, bool IsModMod) { 13463 if (UI.Diagnosed) 13464 return; 13465 13466 const Usage &U = UI.Uses[OtherKind]; 13467 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13468 return; 13469 13470 const Expr *Mod = U.UsageExpr; 13471 const Expr *ModOrUse = UsageExpr; 13472 if (OtherKind == UK_Use) 13473 std::swap(Mod, ModOrUse); 13474 13475 SemaRef.DiagRuntimeBehavior( 13476 Mod->getExprLoc(), {Mod, ModOrUse}, 13477 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13478 : diag::warn_unsequenced_mod_use) 13479 << O << SourceRange(ModOrUse->getExprLoc())); 13480 UI.Diagnosed = true; 13481 } 13482 13483 // A note on note{Pre, Post}{Use, Mod}: 13484 // 13485 // (It helps to follow the algorithm with an expression such as 13486 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13487 // operations before C++17 and both are well-defined in C++17). 13488 // 13489 // When visiting a node which uses/modify an object we first call notePreUse 13490 // or notePreMod before visiting its sub-expression(s). At this point the 13491 // children of the current node have not yet been visited and so the eventual 13492 // uses/modifications resulting from the children of the current node have not 13493 // been recorded yet. 13494 // 13495 // We then visit the children of the current node. After that notePostUse or 13496 // notePostMod is called. These will 1) detect an unsequenced modification 13497 // as side effect (as in "k++ + k") and 2) add a new usage with the 13498 // appropriate usage kind. 13499 // 13500 // We also have to be careful that some operation sequences modification as 13501 // side effect as well (for example: || or ,). To account for this we wrap 13502 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13503 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13504 // which record usages which are modifications as side effect, and then 13505 // downgrade them (or more accurately restore the previous usage which was a 13506 // modification as side effect) when exiting the scope of the sequenced 13507 // subexpression. 13508 13509 void notePreUse(Object O, const Expr *UseExpr) { 13510 UsageInfo &UI = UsageMap[O]; 13511 // Uses conflict with other modifications. 13512 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13513 } 13514 13515 void notePostUse(Object O, const Expr *UseExpr) { 13516 UsageInfo &UI = UsageMap[O]; 13517 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13518 /*IsModMod=*/false); 13519 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13520 } 13521 13522 void notePreMod(Object O, const Expr *ModExpr) { 13523 UsageInfo &UI = UsageMap[O]; 13524 // Modifications conflict with other modifications and with uses. 13525 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13526 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13527 } 13528 13529 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13530 UsageInfo &UI = UsageMap[O]; 13531 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13532 /*IsModMod=*/true); 13533 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13534 } 13535 13536 public: 13537 SequenceChecker(Sema &S, const Expr *E, 13538 SmallVectorImpl<const Expr *> &WorkList) 13539 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13540 Visit(E); 13541 // Silence a -Wunused-private-field since WorkList is now unused. 13542 // TODO: Evaluate if it can be used, and if not remove it. 13543 (void)this->WorkList; 13544 } 13545 13546 void VisitStmt(const Stmt *S) { 13547 // Skip all statements which aren't expressions for now. 13548 } 13549 13550 void VisitExpr(const Expr *E) { 13551 // By default, just recurse to evaluated subexpressions. 13552 Base::VisitStmt(E); 13553 } 13554 13555 void VisitCastExpr(const CastExpr *E) { 13556 Object O = Object(); 13557 if (E->getCastKind() == CK_LValueToRValue) 13558 O = getObject(E->getSubExpr(), false); 13559 13560 if (O) 13561 notePreUse(O, E); 13562 VisitExpr(E); 13563 if (O) 13564 notePostUse(O, E); 13565 } 13566 13567 void VisitSequencedExpressions(const Expr *SequencedBefore, 13568 const Expr *SequencedAfter) { 13569 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13570 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13571 SequenceTree::Seq OldRegion = Region; 13572 13573 { 13574 SequencedSubexpression SeqBefore(*this); 13575 Region = BeforeRegion; 13576 Visit(SequencedBefore); 13577 } 13578 13579 Region = AfterRegion; 13580 Visit(SequencedAfter); 13581 13582 Region = OldRegion; 13583 13584 Tree.merge(BeforeRegion); 13585 Tree.merge(AfterRegion); 13586 } 13587 13588 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13589 // C++17 [expr.sub]p1: 13590 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13591 // expression E1 is sequenced before the expression E2. 13592 if (SemaRef.getLangOpts().CPlusPlus17) 13593 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13594 else { 13595 Visit(ASE->getLHS()); 13596 Visit(ASE->getRHS()); 13597 } 13598 } 13599 13600 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13601 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13602 void VisitBinPtrMem(const BinaryOperator *BO) { 13603 // C++17 [expr.mptr.oper]p4: 13604 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13605 // the expression E1 is sequenced before the expression E2. 13606 if (SemaRef.getLangOpts().CPlusPlus17) 13607 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13608 else { 13609 Visit(BO->getLHS()); 13610 Visit(BO->getRHS()); 13611 } 13612 } 13613 13614 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13615 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13616 void VisitBinShlShr(const BinaryOperator *BO) { 13617 // C++17 [expr.shift]p4: 13618 // The expression E1 is sequenced before the expression E2. 13619 if (SemaRef.getLangOpts().CPlusPlus17) 13620 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13621 else { 13622 Visit(BO->getLHS()); 13623 Visit(BO->getRHS()); 13624 } 13625 } 13626 13627 void VisitBinComma(const BinaryOperator *BO) { 13628 // C++11 [expr.comma]p1: 13629 // Every value computation and side effect associated with the left 13630 // expression is sequenced before every value computation and side 13631 // effect associated with the right expression. 13632 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13633 } 13634 13635 void VisitBinAssign(const BinaryOperator *BO) { 13636 SequenceTree::Seq RHSRegion; 13637 SequenceTree::Seq LHSRegion; 13638 if (SemaRef.getLangOpts().CPlusPlus17) { 13639 RHSRegion = Tree.allocate(Region); 13640 LHSRegion = Tree.allocate(Region); 13641 } else { 13642 RHSRegion = Region; 13643 LHSRegion = Region; 13644 } 13645 SequenceTree::Seq OldRegion = Region; 13646 13647 // C++11 [expr.ass]p1: 13648 // [...] the assignment is sequenced after the value computation 13649 // of the right and left operands, [...] 13650 // 13651 // so check it before inspecting the operands and update the 13652 // map afterwards. 13653 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13654 if (O) 13655 notePreMod(O, BO); 13656 13657 if (SemaRef.getLangOpts().CPlusPlus17) { 13658 // C++17 [expr.ass]p1: 13659 // [...] The right operand is sequenced before the left operand. [...] 13660 { 13661 SequencedSubexpression SeqBefore(*this); 13662 Region = RHSRegion; 13663 Visit(BO->getRHS()); 13664 } 13665 13666 Region = LHSRegion; 13667 Visit(BO->getLHS()); 13668 13669 if (O && isa<CompoundAssignOperator>(BO)) 13670 notePostUse(O, BO); 13671 13672 } else { 13673 // C++11 does not specify any sequencing between the LHS and RHS. 13674 Region = LHSRegion; 13675 Visit(BO->getLHS()); 13676 13677 if (O && isa<CompoundAssignOperator>(BO)) 13678 notePostUse(O, BO); 13679 13680 Region = RHSRegion; 13681 Visit(BO->getRHS()); 13682 } 13683 13684 // C++11 [expr.ass]p1: 13685 // the assignment is sequenced [...] before the value computation of the 13686 // assignment expression. 13687 // C11 6.5.16/3 has no such rule. 13688 Region = OldRegion; 13689 if (O) 13690 notePostMod(O, BO, 13691 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13692 : UK_ModAsSideEffect); 13693 if (SemaRef.getLangOpts().CPlusPlus17) { 13694 Tree.merge(RHSRegion); 13695 Tree.merge(LHSRegion); 13696 } 13697 } 13698 13699 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13700 VisitBinAssign(CAO); 13701 } 13702 13703 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13704 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13705 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13706 Object O = getObject(UO->getSubExpr(), true); 13707 if (!O) 13708 return VisitExpr(UO); 13709 13710 notePreMod(O, UO); 13711 Visit(UO->getSubExpr()); 13712 // C++11 [expr.pre.incr]p1: 13713 // the expression ++x is equivalent to x+=1 13714 notePostMod(O, UO, 13715 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13716 : UK_ModAsSideEffect); 13717 } 13718 13719 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13720 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13721 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13722 Object O = getObject(UO->getSubExpr(), true); 13723 if (!O) 13724 return VisitExpr(UO); 13725 13726 notePreMod(O, UO); 13727 Visit(UO->getSubExpr()); 13728 notePostMod(O, UO, UK_ModAsSideEffect); 13729 } 13730 13731 void VisitBinLOr(const BinaryOperator *BO) { 13732 // C++11 [expr.log.or]p2: 13733 // If the second expression is evaluated, every value computation and 13734 // side effect associated with the first expression is sequenced before 13735 // every value computation and side effect associated with the 13736 // second expression. 13737 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13738 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13739 SequenceTree::Seq OldRegion = Region; 13740 13741 EvaluationTracker Eval(*this); 13742 { 13743 SequencedSubexpression Sequenced(*this); 13744 Region = LHSRegion; 13745 Visit(BO->getLHS()); 13746 } 13747 13748 // C++11 [expr.log.or]p1: 13749 // [...] the second operand is not evaluated if the first operand 13750 // evaluates to true. 13751 bool EvalResult = false; 13752 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13753 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13754 if (ShouldVisitRHS) { 13755 Region = RHSRegion; 13756 Visit(BO->getRHS()); 13757 } 13758 13759 Region = OldRegion; 13760 Tree.merge(LHSRegion); 13761 Tree.merge(RHSRegion); 13762 } 13763 13764 void VisitBinLAnd(const BinaryOperator *BO) { 13765 // C++11 [expr.log.and]p2: 13766 // If the second expression is evaluated, every value computation and 13767 // side effect associated with the first expression is sequenced before 13768 // every value computation and side effect associated with the 13769 // second expression. 13770 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13771 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13772 SequenceTree::Seq OldRegion = Region; 13773 13774 EvaluationTracker Eval(*this); 13775 { 13776 SequencedSubexpression Sequenced(*this); 13777 Region = LHSRegion; 13778 Visit(BO->getLHS()); 13779 } 13780 13781 // C++11 [expr.log.and]p1: 13782 // [...] the second operand is not evaluated if the first operand is false. 13783 bool EvalResult = false; 13784 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13785 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13786 if (ShouldVisitRHS) { 13787 Region = RHSRegion; 13788 Visit(BO->getRHS()); 13789 } 13790 13791 Region = OldRegion; 13792 Tree.merge(LHSRegion); 13793 Tree.merge(RHSRegion); 13794 } 13795 13796 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13797 // C++11 [expr.cond]p1: 13798 // [...] Every value computation and side effect associated with the first 13799 // expression is sequenced before every value computation and side effect 13800 // associated with the second or third expression. 13801 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13802 13803 // No sequencing is specified between the true and false expression. 13804 // However since exactly one of both is going to be evaluated we can 13805 // consider them to be sequenced. This is needed to avoid warning on 13806 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13807 // both the true and false expressions because we can't evaluate x. 13808 // This will still allow us to detect an expression like (pre C++17) 13809 // "(x ? y += 1 : y += 2) = y". 13810 // 13811 // We don't wrap the visitation of the true and false expression with 13812 // SequencedSubexpression because we don't want to downgrade modifications 13813 // as side effect in the true and false expressions after the visition 13814 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13815 // not warn between the two "y++", but we should warn between the "y++" 13816 // and the "y". 13817 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13818 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13819 SequenceTree::Seq OldRegion = Region; 13820 13821 EvaluationTracker Eval(*this); 13822 { 13823 SequencedSubexpression Sequenced(*this); 13824 Region = ConditionRegion; 13825 Visit(CO->getCond()); 13826 } 13827 13828 // C++11 [expr.cond]p1: 13829 // [...] The first expression is contextually converted to bool (Clause 4). 13830 // It is evaluated and if it is true, the result of the conditional 13831 // expression is the value of the second expression, otherwise that of the 13832 // third expression. Only one of the second and third expressions is 13833 // evaluated. [...] 13834 bool EvalResult = false; 13835 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13836 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13837 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13838 if (ShouldVisitTrueExpr) { 13839 Region = TrueRegion; 13840 Visit(CO->getTrueExpr()); 13841 } 13842 if (ShouldVisitFalseExpr) { 13843 Region = FalseRegion; 13844 Visit(CO->getFalseExpr()); 13845 } 13846 13847 Region = OldRegion; 13848 Tree.merge(ConditionRegion); 13849 Tree.merge(TrueRegion); 13850 Tree.merge(FalseRegion); 13851 } 13852 13853 void VisitCallExpr(const CallExpr *CE) { 13854 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13855 13856 if (CE->isUnevaluatedBuiltinCall(Context)) 13857 return; 13858 13859 // C++11 [intro.execution]p15: 13860 // When calling a function [...], every value computation and side effect 13861 // associated with any argument expression, or with the postfix expression 13862 // designating the called function, is sequenced before execution of every 13863 // expression or statement in the body of the function [and thus before 13864 // the value computation of its result]. 13865 SequencedSubexpression Sequenced(*this); 13866 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13867 // C++17 [expr.call]p5 13868 // The postfix-expression is sequenced before each expression in the 13869 // expression-list and any default argument. [...] 13870 SequenceTree::Seq CalleeRegion; 13871 SequenceTree::Seq OtherRegion; 13872 if (SemaRef.getLangOpts().CPlusPlus17) { 13873 CalleeRegion = Tree.allocate(Region); 13874 OtherRegion = Tree.allocate(Region); 13875 } else { 13876 CalleeRegion = Region; 13877 OtherRegion = Region; 13878 } 13879 SequenceTree::Seq OldRegion = Region; 13880 13881 // Visit the callee expression first. 13882 Region = CalleeRegion; 13883 if (SemaRef.getLangOpts().CPlusPlus17) { 13884 SequencedSubexpression Sequenced(*this); 13885 Visit(CE->getCallee()); 13886 } else { 13887 Visit(CE->getCallee()); 13888 } 13889 13890 // Then visit the argument expressions. 13891 Region = OtherRegion; 13892 for (const Expr *Argument : CE->arguments()) 13893 Visit(Argument); 13894 13895 Region = OldRegion; 13896 if (SemaRef.getLangOpts().CPlusPlus17) { 13897 Tree.merge(CalleeRegion); 13898 Tree.merge(OtherRegion); 13899 } 13900 }); 13901 } 13902 13903 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13904 // C++17 [over.match.oper]p2: 13905 // [...] the operator notation is first transformed to the equivalent 13906 // function-call notation as summarized in Table 12 (where @ denotes one 13907 // of the operators covered in the specified subclause). However, the 13908 // operands are sequenced in the order prescribed for the built-in 13909 // operator (Clause 8). 13910 // 13911 // From the above only overloaded binary operators and overloaded call 13912 // operators have sequencing rules in C++17 that we need to handle 13913 // separately. 13914 if (!SemaRef.getLangOpts().CPlusPlus17 || 13915 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13916 return VisitCallExpr(CXXOCE); 13917 13918 enum { 13919 NoSequencing, 13920 LHSBeforeRHS, 13921 RHSBeforeLHS, 13922 LHSBeforeRest 13923 } SequencingKind; 13924 switch (CXXOCE->getOperator()) { 13925 case OO_Equal: 13926 case OO_PlusEqual: 13927 case OO_MinusEqual: 13928 case OO_StarEqual: 13929 case OO_SlashEqual: 13930 case OO_PercentEqual: 13931 case OO_CaretEqual: 13932 case OO_AmpEqual: 13933 case OO_PipeEqual: 13934 case OO_LessLessEqual: 13935 case OO_GreaterGreaterEqual: 13936 SequencingKind = RHSBeforeLHS; 13937 break; 13938 13939 case OO_LessLess: 13940 case OO_GreaterGreater: 13941 case OO_AmpAmp: 13942 case OO_PipePipe: 13943 case OO_Comma: 13944 case OO_ArrowStar: 13945 case OO_Subscript: 13946 SequencingKind = LHSBeforeRHS; 13947 break; 13948 13949 case OO_Call: 13950 SequencingKind = LHSBeforeRest; 13951 break; 13952 13953 default: 13954 SequencingKind = NoSequencing; 13955 break; 13956 } 13957 13958 if (SequencingKind == NoSequencing) 13959 return VisitCallExpr(CXXOCE); 13960 13961 // This is a call, so all subexpressions are sequenced before the result. 13962 SequencedSubexpression Sequenced(*this); 13963 13964 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13965 assert(SemaRef.getLangOpts().CPlusPlus17 && 13966 "Should only get there with C++17 and above!"); 13967 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13968 "Should only get there with an overloaded binary operator" 13969 " or an overloaded call operator!"); 13970 13971 if (SequencingKind == LHSBeforeRest) { 13972 assert(CXXOCE->getOperator() == OO_Call && 13973 "We should only have an overloaded call operator here!"); 13974 13975 // This is very similar to VisitCallExpr, except that we only have the 13976 // C++17 case. The postfix-expression is the first argument of the 13977 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13978 // are in the following arguments. 13979 // 13980 // Note that we intentionally do not visit the callee expression since 13981 // it is just a decayed reference to a function. 13982 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13983 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13984 SequenceTree::Seq OldRegion = Region; 13985 13986 assert(CXXOCE->getNumArgs() >= 1 && 13987 "An overloaded call operator must have at least one argument" 13988 " for the postfix-expression!"); 13989 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13990 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13991 CXXOCE->getNumArgs() - 1); 13992 13993 // Visit the postfix-expression first. 13994 { 13995 Region = PostfixExprRegion; 13996 SequencedSubexpression Sequenced(*this); 13997 Visit(PostfixExpr); 13998 } 13999 14000 // Then visit the argument expressions. 14001 Region = ArgsRegion; 14002 for (const Expr *Arg : Args) 14003 Visit(Arg); 14004 14005 Region = OldRegion; 14006 Tree.merge(PostfixExprRegion); 14007 Tree.merge(ArgsRegion); 14008 } else { 14009 assert(CXXOCE->getNumArgs() == 2 && 14010 "Should only have two arguments here!"); 14011 assert((SequencingKind == LHSBeforeRHS || 14012 SequencingKind == RHSBeforeLHS) && 14013 "Unexpected sequencing kind!"); 14014 14015 // We do not visit the callee expression since it is just a decayed 14016 // reference to a function. 14017 const Expr *E1 = CXXOCE->getArg(0); 14018 const Expr *E2 = CXXOCE->getArg(1); 14019 if (SequencingKind == RHSBeforeLHS) 14020 std::swap(E1, E2); 14021 14022 return VisitSequencedExpressions(E1, E2); 14023 } 14024 }); 14025 } 14026 14027 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14028 // This is a call, so all subexpressions are sequenced before the result. 14029 SequencedSubexpression Sequenced(*this); 14030 14031 if (!CCE->isListInitialization()) 14032 return VisitExpr(CCE); 14033 14034 // In C++11, list initializations are sequenced. 14035 SmallVector<SequenceTree::Seq, 32> Elts; 14036 SequenceTree::Seq Parent = Region; 14037 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14038 E = CCE->arg_end(); 14039 I != E; ++I) { 14040 Region = Tree.allocate(Parent); 14041 Elts.push_back(Region); 14042 Visit(*I); 14043 } 14044 14045 // Forget that the initializers are sequenced. 14046 Region = Parent; 14047 for (unsigned I = 0; I < Elts.size(); ++I) 14048 Tree.merge(Elts[I]); 14049 } 14050 14051 void VisitInitListExpr(const InitListExpr *ILE) { 14052 if (!SemaRef.getLangOpts().CPlusPlus11) 14053 return VisitExpr(ILE); 14054 14055 // In C++11, list initializations are sequenced. 14056 SmallVector<SequenceTree::Seq, 32> Elts; 14057 SequenceTree::Seq Parent = Region; 14058 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14059 const Expr *E = ILE->getInit(I); 14060 if (!E) 14061 continue; 14062 Region = Tree.allocate(Parent); 14063 Elts.push_back(Region); 14064 Visit(E); 14065 } 14066 14067 // Forget that the initializers are sequenced. 14068 Region = Parent; 14069 for (unsigned I = 0; I < Elts.size(); ++I) 14070 Tree.merge(Elts[I]); 14071 } 14072 }; 14073 14074 } // namespace 14075 14076 void Sema::CheckUnsequencedOperations(const Expr *E) { 14077 SmallVector<const Expr *, 8> WorkList; 14078 WorkList.push_back(E); 14079 while (!WorkList.empty()) { 14080 const Expr *Item = WorkList.pop_back_val(); 14081 SequenceChecker(*this, Item, WorkList); 14082 } 14083 } 14084 14085 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14086 bool IsConstexpr) { 14087 llvm::SaveAndRestore<bool> ConstantContext( 14088 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14089 CheckImplicitConversions(E, CheckLoc); 14090 if (!E->isInstantiationDependent()) 14091 CheckUnsequencedOperations(E); 14092 if (!IsConstexpr && !E->isValueDependent()) 14093 CheckForIntOverflow(E); 14094 DiagnoseMisalignedMembers(); 14095 } 14096 14097 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14098 FieldDecl *BitField, 14099 Expr *Init) { 14100 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14101 } 14102 14103 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14104 SourceLocation Loc) { 14105 if (!PType->isVariablyModifiedType()) 14106 return; 14107 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14108 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14109 return; 14110 } 14111 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14112 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14113 return; 14114 } 14115 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14116 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14117 return; 14118 } 14119 14120 const ArrayType *AT = S.Context.getAsArrayType(PType); 14121 if (!AT) 14122 return; 14123 14124 if (AT->getSizeModifier() != ArrayType::Star) { 14125 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14126 return; 14127 } 14128 14129 S.Diag(Loc, diag::err_array_star_in_function_definition); 14130 } 14131 14132 /// CheckParmsForFunctionDef - Check that the parameters of the given 14133 /// function are appropriate for the definition of a function. This 14134 /// takes care of any checks that cannot be performed on the 14135 /// declaration itself, e.g., that the types of each of the function 14136 /// parameters are complete. 14137 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14138 bool CheckParameterNames) { 14139 bool HasInvalidParm = false; 14140 for (ParmVarDecl *Param : Parameters) { 14141 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14142 // function declarator that is part of a function definition of 14143 // that function shall not have incomplete type. 14144 // 14145 // This is also C++ [dcl.fct]p6. 14146 if (!Param->isInvalidDecl() && 14147 RequireCompleteType(Param->getLocation(), Param->getType(), 14148 diag::err_typecheck_decl_incomplete_type)) { 14149 Param->setInvalidDecl(); 14150 HasInvalidParm = true; 14151 } 14152 14153 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14154 // declaration of each parameter shall include an identifier. 14155 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14156 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14157 // Diagnose this as an extension in C17 and earlier. 14158 if (!getLangOpts().C2x) 14159 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14160 } 14161 14162 // C99 6.7.5.3p12: 14163 // If the function declarator is not part of a definition of that 14164 // function, parameters may have incomplete type and may use the [*] 14165 // notation in their sequences of declarator specifiers to specify 14166 // variable length array types. 14167 QualType PType = Param->getOriginalType(); 14168 // FIXME: This diagnostic should point the '[*]' if source-location 14169 // information is added for it. 14170 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14171 14172 // If the parameter is a c++ class type and it has to be destructed in the 14173 // callee function, declare the destructor so that it can be called by the 14174 // callee function. Do not perform any direct access check on the dtor here. 14175 if (!Param->isInvalidDecl()) { 14176 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14177 if (!ClassDecl->isInvalidDecl() && 14178 !ClassDecl->hasIrrelevantDestructor() && 14179 !ClassDecl->isDependentContext() && 14180 ClassDecl->isParamDestroyedInCallee()) { 14181 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14182 MarkFunctionReferenced(Param->getLocation(), Destructor); 14183 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14184 } 14185 } 14186 } 14187 14188 // Parameters with the pass_object_size attribute only need to be marked 14189 // constant at function definitions. Because we lack information about 14190 // whether we're on a declaration or definition when we're instantiating the 14191 // attribute, we need to check for constness here. 14192 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14193 if (!Param->getType().isConstQualified()) 14194 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14195 << Attr->getSpelling() << 1; 14196 14197 // Check for parameter names shadowing fields from the class. 14198 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14199 // The owning context for the parameter should be the function, but we 14200 // want to see if this function's declaration context is a record. 14201 DeclContext *DC = Param->getDeclContext(); 14202 if (DC && DC->isFunctionOrMethod()) { 14203 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14204 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14205 RD, /*DeclIsField*/ false); 14206 } 14207 } 14208 } 14209 14210 return HasInvalidParm; 14211 } 14212 14213 Optional<std::pair<CharUnits, CharUnits>> 14214 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14215 14216 /// Compute the alignment and offset of the base class object given the 14217 /// derived-to-base cast expression and the alignment and offset of the derived 14218 /// class object. 14219 static std::pair<CharUnits, CharUnits> 14220 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14221 CharUnits BaseAlignment, CharUnits Offset, 14222 ASTContext &Ctx) { 14223 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14224 ++PathI) { 14225 const CXXBaseSpecifier *Base = *PathI; 14226 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14227 if (Base->isVirtual()) { 14228 // The complete object may have a lower alignment than the non-virtual 14229 // alignment of the base, in which case the base may be misaligned. Choose 14230 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14231 // conservative lower bound of the complete object alignment. 14232 CharUnits NonVirtualAlignment = 14233 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14234 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14235 Offset = CharUnits::Zero(); 14236 } else { 14237 const ASTRecordLayout &RL = 14238 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14239 Offset += RL.getBaseClassOffset(BaseDecl); 14240 } 14241 DerivedType = Base->getType(); 14242 } 14243 14244 return std::make_pair(BaseAlignment, Offset); 14245 } 14246 14247 /// Compute the alignment and offset of a binary additive operator. 14248 static Optional<std::pair<CharUnits, CharUnits>> 14249 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14250 bool IsSub, ASTContext &Ctx) { 14251 QualType PointeeType = PtrE->getType()->getPointeeType(); 14252 14253 if (!PointeeType->isConstantSizeType()) 14254 return llvm::None; 14255 14256 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14257 14258 if (!P) 14259 return llvm::None; 14260 14261 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14262 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14263 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14264 if (IsSub) 14265 Offset = -Offset; 14266 return std::make_pair(P->first, P->second + Offset); 14267 } 14268 14269 // If the integer expression isn't a constant expression, compute the lower 14270 // bound of the alignment using the alignment and offset of the pointer 14271 // expression and the element size. 14272 return std::make_pair( 14273 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14274 CharUnits::Zero()); 14275 } 14276 14277 /// This helper function takes an lvalue expression and returns the alignment of 14278 /// a VarDecl and a constant offset from the VarDecl. 14279 Optional<std::pair<CharUnits, CharUnits>> 14280 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14281 E = E->IgnoreParens(); 14282 switch (E->getStmtClass()) { 14283 default: 14284 break; 14285 case Stmt::CStyleCastExprClass: 14286 case Stmt::CXXStaticCastExprClass: 14287 case Stmt::ImplicitCastExprClass: { 14288 auto *CE = cast<CastExpr>(E); 14289 const Expr *From = CE->getSubExpr(); 14290 switch (CE->getCastKind()) { 14291 default: 14292 break; 14293 case CK_NoOp: 14294 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14295 case CK_UncheckedDerivedToBase: 14296 case CK_DerivedToBase: { 14297 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14298 if (!P) 14299 break; 14300 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14301 P->second, Ctx); 14302 } 14303 } 14304 break; 14305 } 14306 case Stmt::ArraySubscriptExprClass: { 14307 auto *ASE = cast<ArraySubscriptExpr>(E); 14308 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14309 false, Ctx); 14310 } 14311 case Stmt::DeclRefExprClass: { 14312 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14313 // FIXME: If VD is captured by copy or is an escaping __block variable, 14314 // use the alignment of VD's type. 14315 if (!VD->getType()->isReferenceType()) 14316 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14317 if (VD->hasInit()) 14318 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14319 } 14320 break; 14321 } 14322 case Stmt::MemberExprClass: { 14323 auto *ME = cast<MemberExpr>(E); 14324 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14325 if (!FD || FD->getType()->isReferenceType()) 14326 break; 14327 Optional<std::pair<CharUnits, CharUnits>> P; 14328 if (ME->isArrow()) 14329 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14330 else 14331 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14332 if (!P) 14333 break; 14334 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14335 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14336 return std::make_pair(P->first, 14337 P->second + CharUnits::fromQuantity(Offset)); 14338 } 14339 case Stmt::UnaryOperatorClass: { 14340 auto *UO = cast<UnaryOperator>(E); 14341 switch (UO->getOpcode()) { 14342 default: 14343 break; 14344 case UO_Deref: 14345 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14346 } 14347 break; 14348 } 14349 case Stmt::BinaryOperatorClass: { 14350 auto *BO = cast<BinaryOperator>(E); 14351 auto Opcode = BO->getOpcode(); 14352 switch (Opcode) { 14353 default: 14354 break; 14355 case BO_Comma: 14356 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14357 } 14358 break; 14359 } 14360 } 14361 return llvm::None; 14362 } 14363 14364 /// This helper function takes a pointer expression and returns the alignment of 14365 /// a VarDecl and a constant offset from the VarDecl. 14366 Optional<std::pair<CharUnits, CharUnits>> 14367 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14368 E = E->IgnoreParens(); 14369 switch (E->getStmtClass()) { 14370 default: 14371 break; 14372 case Stmt::CStyleCastExprClass: 14373 case Stmt::CXXStaticCastExprClass: 14374 case Stmt::ImplicitCastExprClass: { 14375 auto *CE = cast<CastExpr>(E); 14376 const Expr *From = CE->getSubExpr(); 14377 switch (CE->getCastKind()) { 14378 default: 14379 break; 14380 case CK_NoOp: 14381 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14382 case CK_ArrayToPointerDecay: 14383 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14384 case CK_UncheckedDerivedToBase: 14385 case CK_DerivedToBase: { 14386 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14387 if (!P) 14388 break; 14389 return getDerivedToBaseAlignmentAndOffset( 14390 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14391 } 14392 } 14393 break; 14394 } 14395 case Stmt::CXXThisExprClass: { 14396 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14397 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14398 return std::make_pair(Alignment, CharUnits::Zero()); 14399 } 14400 case Stmt::UnaryOperatorClass: { 14401 auto *UO = cast<UnaryOperator>(E); 14402 if (UO->getOpcode() == UO_AddrOf) 14403 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14404 break; 14405 } 14406 case Stmt::BinaryOperatorClass: { 14407 auto *BO = cast<BinaryOperator>(E); 14408 auto Opcode = BO->getOpcode(); 14409 switch (Opcode) { 14410 default: 14411 break; 14412 case BO_Add: 14413 case BO_Sub: { 14414 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14415 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14416 std::swap(LHS, RHS); 14417 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14418 Ctx); 14419 } 14420 case BO_Comma: 14421 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14422 } 14423 break; 14424 } 14425 } 14426 return llvm::None; 14427 } 14428 14429 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14430 // See if we can compute the alignment of a VarDecl and an offset from it. 14431 Optional<std::pair<CharUnits, CharUnits>> P = 14432 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14433 14434 if (P) 14435 return P->first.alignmentAtOffset(P->second); 14436 14437 // If that failed, return the type's alignment. 14438 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14439 } 14440 14441 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14442 /// pointer cast increases the alignment requirements. 14443 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14444 // This is actually a lot of work to potentially be doing on every 14445 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14446 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14447 return; 14448 14449 // Ignore dependent types. 14450 if (T->isDependentType() || Op->getType()->isDependentType()) 14451 return; 14452 14453 // Require that the destination be a pointer type. 14454 const PointerType *DestPtr = T->getAs<PointerType>(); 14455 if (!DestPtr) return; 14456 14457 // If the destination has alignment 1, we're done. 14458 QualType DestPointee = DestPtr->getPointeeType(); 14459 if (DestPointee->isIncompleteType()) return; 14460 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14461 if (DestAlign.isOne()) return; 14462 14463 // Require that the source be a pointer type. 14464 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14465 if (!SrcPtr) return; 14466 QualType SrcPointee = SrcPtr->getPointeeType(); 14467 14468 // Explicitly allow casts from cv void*. We already implicitly 14469 // allowed casts to cv void*, since they have alignment 1. 14470 // Also allow casts involving incomplete types, which implicitly 14471 // includes 'void'. 14472 if (SrcPointee->isIncompleteType()) return; 14473 14474 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14475 14476 if (SrcAlign >= DestAlign) return; 14477 14478 Diag(TRange.getBegin(), diag::warn_cast_align) 14479 << Op->getType() << T 14480 << static_cast<unsigned>(SrcAlign.getQuantity()) 14481 << static_cast<unsigned>(DestAlign.getQuantity()) 14482 << TRange << Op->getSourceRange(); 14483 } 14484 14485 /// Check whether this array fits the idiom of a size-one tail padded 14486 /// array member of a struct. 14487 /// 14488 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14489 /// commonly used to emulate flexible arrays in C89 code. 14490 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14491 const NamedDecl *ND) { 14492 if (Size != 1 || !ND) return false; 14493 14494 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14495 if (!FD) return false; 14496 14497 // Don't consider sizes resulting from macro expansions or template argument 14498 // substitution to form C89 tail-padded arrays. 14499 14500 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14501 while (TInfo) { 14502 TypeLoc TL = TInfo->getTypeLoc(); 14503 // Look through typedefs. 14504 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14505 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14506 TInfo = TDL->getTypeSourceInfo(); 14507 continue; 14508 } 14509 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14510 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14511 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14512 return false; 14513 } 14514 break; 14515 } 14516 14517 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14518 if (!RD) return false; 14519 if (RD->isUnion()) return false; 14520 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14521 if (!CRD->isStandardLayout()) return false; 14522 } 14523 14524 // See if this is the last field decl in the record. 14525 const Decl *D = FD; 14526 while ((D = D->getNextDeclInContext())) 14527 if (isa<FieldDecl>(D)) 14528 return false; 14529 return true; 14530 } 14531 14532 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14533 const ArraySubscriptExpr *ASE, 14534 bool AllowOnePastEnd, bool IndexNegated) { 14535 // Already diagnosed by the constant evaluator. 14536 if (isConstantEvaluated()) 14537 return; 14538 14539 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14540 if (IndexExpr->isValueDependent()) 14541 return; 14542 14543 const Type *EffectiveType = 14544 BaseExpr->getType()->getPointeeOrArrayElementType(); 14545 BaseExpr = BaseExpr->IgnoreParenCasts(); 14546 const ConstantArrayType *ArrayTy = 14547 Context.getAsConstantArrayType(BaseExpr->getType()); 14548 14549 const Type *BaseType = 14550 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 14551 bool IsUnboundedArray = (BaseType == nullptr); 14552 if (EffectiveType->isDependentType() || 14553 (!IsUnboundedArray && BaseType->isDependentType())) 14554 return; 14555 14556 Expr::EvalResult Result; 14557 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14558 return; 14559 14560 llvm::APSInt index = Result.Val.getInt(); 14561 if (IndexNegated) { 14562 index.setIsUnsigned(false); 14563 index = -index; 14564 } 14565 14566 const NamedDecl *ND = nullptr; 14567 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14568 ND = DRE->getDecl(); 14569 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14570 ND = ME->getMemberDecl(); 14571 14572 if (IsUnboundedArray) { 14573 if (index.isUnsigned() || !index.isNegative()) { 14574 const auto &ASTC = getASTContext(); 14575 unsigned AddrBits = 14576 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 14577 EffectiveType->getCanonicalTypeInternal())); 14578 if (index.getBitWidth() < AddrBits) 14579 index = index.zext(AddrBits); 14580 Optional<CharUnits> ElemCharUnits = 14581 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 14582 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 14583 // pointer) bounds-checking isn't meaningful. 14584 if (!ElemCharUnits) 14585 return; 14586 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 14587 // If index has more active bits than address space, we already know 14588 // we have a bounds violation to warn about. Otherwise, compute 14589 // address of (index + 1)th element, and warn about bounds violation 14590 // only if that address exceeds address space. 14591 if (index.getActiveBits() <= AddrBits) { 14592 bool Overflow; 14593 llvm::APInt Product(index); 14594 Product += 1; 14595 Product = Product.umul_ov(ElemBytes, Overflow); 14596 if (!Overflow && Product.getActiveBits() <= AddrBits) 14597 return; 14598 } 14599 14600 // Need to compute max possible elements in address space, since that 14601 // is included in diag message. 14602 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 14603 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 14604 MaxElems += 1; 14605 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 14606 MaxElems = MaxElems.udiv(ElemBytes); 14607 14608 unsigned DiagID = 14609 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 14610 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 14611 14612 // Diag message shows element size in bits and in "bytes" (platform- 14613 // dependent CharUnits) 14614 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14615 PDiag(DiagID) 14616 << toString(index, 10, true) << AddrBits 14617 << (unsigned)ASTC.toBits(*ElemCharUnits) 14618 << toString(ElemBytes, 10, false) 14619 << toString(MaxElems, 10, false) 14620 << (unsigned)MaxElems.getLimitedValue(~0U) 14621 << IndexExpr->getSourceRange()); 14622 14623 if (!ND) { 14624 // Try harder to find a NamedDecl to point at in the note. 14625 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14626 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14627 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14628 ND = DRE->getDecl(); 14629 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 14630 ND = ME->getMemberDecl(); 14631 } 14632 14633 if (ND) 14634 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14635 PDiag(diag::note_array_declared_here) << ND); 14636 } 14637 return; 14638 } 14639 14640 if (index.isUnsigned() || !index.isNegative()) { 14641 // It is possible that the type of the base expression after 14642 // IgnoreParenCasts is incomplete, even though the type of the base 14643 // expression before IgnoreParenCasts is complete (see PR39746 for an 14644 // example). In this case we have no information about whether the array 14645 // access exceeds the array bounds. However we can still diagnose an array 14646 // access which precedes the array bounds. 14647 if (BaseType->isIncompleteType()) 14648 return; 14649 14650 llvm::APInt size = ArrayTy->getSize(); 14651 if (!size.isStrictlyPositive()) 14652 return; 14653 14654 if (BaseType != EffectiveType) { 14655 // Make sure we're comparing apples to apples when comparing index to size 14656 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14657 uint64_t array_typesize = Context.getTypeSize(BaseType); 14658 // Handle ptrarith_typesize being zero, such as when casting to void* 14659 if (!ptrarith_typesize) ptrarith_typesize = 1; 14660 if (ptrarith_typesize != array_typesize) { 14661 // There's a cast to a different size type involved 14662 uint64_t ratio = array_typesize / ptrarith_typesize; 14663 // TODO: Be smarter about handling cases where array_typesize is not a 14664 // multiple of ptrarith_typesize 14665 if (ptrarith_typesize * ratio == array_typesize) 14666 size *= llvm::APInt(size.getBitWidth(), ratio); 14667 } 14668 } 14669 14670 if (size.getBitWidth() > index.getBitWidth()) 14671 index = index.zext(size.getBitWidth()); 14672 else if (size.getBitWidth() < index.getBitWidth()) 14673 size = size.zext(index.getBitWidth()); 14674 14675 // For array subscripting the index must be less than size, but for pointer 14676 // arithmetic also allow the index (offset) to be equal to size since 14677 // computing the next address after the end of the array is legal and 14678 // commonly done e.g. in C++ iterators and range-based for loops. 14679 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14680 return; 14681 14682 // Also don't warn for arrays of size 1 which are members of some 14683 // structure. These are often used to approximate flexible arrays in C89 14684 // code. 14685 if (IsTailPaddedMemberArray(*this, size, ND)) 14686 return; 14687 14688 // Suppress the warning if the subscript expression (as identified by the 14689 // ']' location) and the index expression are both from macro expansions 14690 // within a system header. 14691 if (ASE) { 14692 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14693 ASE->getRBracketLoc()); 14694 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14695 SourceLocation IndexLoc = 14696 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14697 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14698 return; 14699 } 14700 } 14701 14702 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 14703 : diag::warn_ptr_arith_exceeds_bounds; 14704 14705 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14706 PDiag(DiagID) << toString(index, 10, true) 14707 << toString(size, 10, true) 14708 << (unsigned)size.getLimitedValue(~0U) 14709 << IndexExpr->getSourceRange()); 14710 } else { 14711 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14712 if (!ASE) { 14713 DiagID = diag::warn_ptr_arith_precedes_bounds; 14714 if (index.isNegative()) index = -index; 14715 } 14716 14717 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14718 PDiag(DiagID) << toString(index, 10, true) 14719 << IndexExpr->getSourceRange()); 14720 } 14721 14722 if (!ND) { 14723 // Try harder to find a NamedDecl to point at in the note. 14724 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14725 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14726 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14727 ND = DRE->getDecl(); 14728 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 14729 ND = ME->getMemberDecl(); 14730 } 14731 14732 if (ND) 14733 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14734 PDiag(diag::note_array_declared_here) << ND); 14735 } 14736 14737 void Sema::CheckArrayAccess(const Expr *expr) { 14738 int AllowOnePastEnd = 0; 14739 while (expr) { 14740 expr = expr->IgnoreParenImpCasts(); 14741 switch (expr->getStmtClass()) { 14742 case Stmt::ArraySubscriptExprClass: { 14743 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14744 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14745 AllowOnePastEnd > 0); 14746 expr = ASE->getBase(); 14747 break; 14748 } 14749 case Stmt::MemberExprClass: { 14750 expr = cast<MemberExpr>(expr)->getBase(); 14751 break; 14752 } 14753 case Stmt::OMPArraySectionExprClass: { 14754 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14755 if (ASE->getLowerBound()) 14756 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14757 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14758 return; 14759 } 14760 case Stmt::UnaryOperatorClass: { 14761 // Only unwrap the * and & unary operators 14762 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14763 expr = UO->getSubExpr(); 14764 switch (UO->getOpcode()) { 14765 case UO_AddrOf: 14766 AllowOnePastEnd++; 14767 break; 14768 case UO_Deref: 14769 AllowOnePastEnd--; 14770 break; 14771 default: 14772 return; 14773 } 14774 break; 14775 } 14776 case Stmt::ConditionalOperatorClass: { 14777 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14778 if (const Expr *lhs = cond->getLHS()) 14779 CheckArrayAccess(lhs); 14780 if (const Expr *rhs = cond->getRHS()) 14781 CheckArrayAccess(rhs); 14782 return; 14783 } 14784 case Stmt::CXXOperatorCallExprClass: { 14785 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14786 for (const auto *Arg : OCE->arguments()) 14787 CheckArrayAccess(Arg); 14788 return; 14789 } 14790 default: 14791 return; 14792 } 14793 } 14794 } 14795 14796 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14797 14798 namespace { 14799 14800 struct RetainCycleOwner { 14801 VarDecl *Variable = nullptr; 14802 SourceRange Range; 14803 SourceLocation Loc; 14804 bool Indirect = false; 14805 14806 RetainCycleOwner() = default; 14807 14808 void setLocsFrom(Expr *e) { 14809 Loc = e->getExprLoc(); 14810 Range = e->getSourceRange(); 14811 } 14812 }; 14813 14814 } // namespace 14815 14816 /// Consider whether capturing the given variable can possibly lead to 14817 /// a retain cycle. 14818 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14819 // In ARC, it's captured strongly iff the variable has __strong 14820 // lifetime. In MRR, it's captured strongly if the variable is 14821 // __block and has an appropriate type. 14822 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14823 return false; 14824 14825 owner.Variable = var; 14826 if (ref) 14827 owner.setLocsFrom(ref); 14828 return true; 14829 } 14830 14831 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14832 while (true) { 14833 e = e->IgnoreParens(); 14834 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14835 switch (cast->getCastKind()) { 14836 case CK_BitCast: 14837 case CK_LValueBitCast: 14838 case CK_LValueToRValue: 14839 case CK_ARCReclaimReturnedObject: 14840 e = cast->getSubExpr(); 14841 continue; 14842 14843 default: 14844 return false; 14845 } 14846 } 14847 14848 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14849 ObjCIvarDecl *ivar = ref->getDecl(); 14850 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14851 return false; 14852 14853 // Try to find a retain cycle in the base. 14854 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14855 return false; 14856 14857 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14858 owner.Indirect = true; 14859 return true; 14860 } 14861 14862 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14863 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14864 if (!var) return false; 14865 return considerVariable(var, ref, owner); 14866 } 14867 14868 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14869 if (member->isArrow()) return false; 14870 14871 // Don't count this as an indirect ownership. 14872 e = member->getBase(); 14873 continue; 14874 } 14875 14876 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14877 // Only pay attention to pseudo-objects on property references. 14878 ObjCPropertyRefExpr *pre 14879 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14880 ->IgnoreParens()); 14881 if (!pre) return false; 14882 if (pre->isImplicitProperty()) return false; 14883 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14884 if (!property->isRetaining() && 14885 !(property->getPropertyIvarDecl() && 14886 property->getPropertyIvarDecl()->getType() 14887 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14888 return false; 14889 14890 owner.Indirect = true; 14891 if (pre->isSuperReceiver()) { 14892 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14893 if (!owner.Variable) 14894 return false; 14895 owner.Loc = pre->getLocation(); 14896 owner.Range = pre->getSourceRange(); 14897 return true; 14898 } 14899 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14900 ->getSourceExpr()); 14901 continue; 14902 } 14903 14904 // Array ivars? 14905 14906 return false; 14907 } 14908 } 14909 14910 namespace { 14911 14912 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14913 ASTContext &Context; 14914 VarDecl *Variable; 14915 Expr *Capturer = nullptr; 14916 bool VarWillBeReased = false; 14917 14918 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14919 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14920 Context(Context), Variable(variable) {} 14921 14922 void VisitDeclRefExpr(DeclRefExpr *ref) { 14923 if (ref->getDecl() == Variable && !Capturer) 14924 Capturer = ref; 14925 } 14926 14927 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14928 if (Capturer) return; 14929 Visit(ref->getBase()); 14930 if (Capturer && ref->isFreeIvar()) 14931 Capturer = ref; 14932 } 14933 14934 void VisitBlockExpr(BlockExpr *block) { 14935 // Look inside nested blocks 14936 if (block->getBlockDecl()->capturesVariable(Variable)) 14937 Visit(block->getBlockDecl()->getBody()); 14938 } 14939 14940 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14941 if (Capturer) return; 14942 if (OVE->getSourceExpr()) 14943 Visit(OVE->getSourceExpr()); 14944 } 14945 14946 void VisitBinaryOperator(BinaryOperator *BinOp) { 14947 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14948 return; 14949 Expr *LHS = BinOp->getLHS(); 14950 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14951 if (DRE->getDecl() != Variable) 14952 return; 14953 if (Expr *RHS = BinOp->getRHS()) { 14954 RHS = RHS->IgnoreParenCasts(); 14955 Optional<llvm::APSInt> Value; 14956 VarWillBeReased = 14957 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14958 *Value == 0); 14959 } 14960 } 14961 } 14962 }; 14963 14964 } // namespace 14965 14966 /// Check whether the given argument is a block which captures a 14967 /// variable. 14968 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14969 assert(owner.Variable && owner.Loc.isValid()); 14970 14971 e = e->IgnoreParenCasts(); 14972 14973 // Look through [^{...} copy] and Block_copy(^{...}). 14974 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14975 Selector Cmd = ME->getSelector(); 14976 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14977 e = ME->getInstanceReceiver(); 14978 if (!e) 14979 return nullptr; 14980 e = e->IgnoreParenCasts(); 14981 } 14982 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14983 if (CE->getNumArgs() == 1) { 14984 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14985 if (Fn) { 14986 const IdentifierInfo *FnI = Fn->getIdentifier(); 14987 if (FnI && FnI->isStr("_Block_copy")) { 14988 e = CE->getArg(0)->IgnoreParenCasts(); 14989 } 14990 } 14991 } 14992 } 14993 14994 BlockExpr *block = dyn_cast<BlockExpr>(e); 14995 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14996 return nullptr; 14997 14998 FindCaptureVisitor visitor(S.Context, owner.Variable); 14999 visitor.Visit(block->getBlockDecl()->getBody()); 15000 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15001 } 15002 15003 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15004 RetainCycleOwner &owner) { 15005 assert(capturer); 15006 assert(owner.Variable && owner.Loc.isValid()); 15007 15008 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15009 << owner.Variable << capturer->getSourceRange(); 15010 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15011 << owner.Indirect << owner.Range; 15012 } 15013 15014 /// Check for a keyword selector that starts with the word 'add' or 15015 /// 'set'. 15016 static bool isSetterLikeSelector(Selector sel) { 15017 if (sel.isUnarySelector()) return false; 15018 15019 StringRef str = sel.getNameForSlot(0); 15020 while (!str.empty() && str.front() == '_') str = str.substr(1); 15021 if (str.startswith("set")) 15022 str = str.substr(3); 15023 else if (str.startswith("add")) { 15024 // Specially allow 'addOperationWithBlock:'. 15025 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15026 return false; 15027 str = str.substr(3); 15028 } 15029 else 15030 return false; 15031 15032 if (str.empty()) return true; 15033 return !isLowercase(str.front()); 15034 } 15035 15036 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15037 ObjCMessageExpr *Message) { 15038 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15039 Message->getReceiverInterface(), 15040 NSAPI::ClassId_NSMutableArray); 15041 if (!IsMutableArray) { 15042 return None; 15043 } 15044 15045 Selector Sel = Message->getSelector(); 15046 15047 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15048 S.NSAPIObj->getNSArrayMethodKind(Sel); 15049 if (!MKOpt) { 15050 return None; 15051 } 15052 15053 NSAPI::NSArrayMethodKind MK = *MKOpt; 15054 15055 switch (MK) { 15056 case NSAPI::NSMutableArr_addObject: 15057 case NSAPI::NSMutableArr_insertObjectAtIndex: 15058 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15059 return 0; 15060 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15061 return 1; 15062 15063 default: 15064 return None; 15065 } 15066 15067 return None; 15068 } 15069 15070 static 15071 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15072 ObjCMessageExpr *Message) { 15073 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15074 Message->getReceiverInterface(), 15075 NSAPI::ClassId_NSMutableDictionary); 15076 if (!IsMutableDictionary) { 15077 return None; 15078 } 15079 15080 Selector Sel = Message->getSelector(); 15081 15082 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15083 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15084 if (!MKOpt) { 15085 return None; 15086 } 15087 15088 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15089 15090 switch (MK) { 15091 case NSAPI::NSMutableDict_setObjectForKey: 15092 case NSAPI::NSMutableDict_setValueForKey: 15093 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15094 return 0; 15095 15096 default: 15097 return None; 15098 } 15099 15100 return None; 15101 } 15102 15103 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15104 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15105 Message->getReceiverInterface(), 15106 NSAPI::ClassId_NSMutableSet); 15107 15108 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15109 Message->getReceiverInterface(), 15110 NSAPI::ClassId_NSMutableOrderedSet); 15111 if (!IsMutableSet && !IsMutableOrderedSet) { 15112 return None; 15113 } 15114 15115 Selector Sel = Message->getSelector(); 15116 15117 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15118 if (!MKOpt) { 15119 return None; 15120 } 15121 15122 NSAPI::NSSetMethodKind MK = *MKOpt; 15123 15124 switch (MK) { 15125 case NSAPI::NSMutableSet_addObject: 15126 case NSAPI::NSOrderedSet_setObjectAtIndex: 15127 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15128 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15129 return 0; 15130 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15131 return 1; 15132 } 15133 15134 return None; 15135 } 15136 15137 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15138 if (!Message->isInstanceMessage()) { 15139 return; 15140 } 15141 15142 Optional<int> ArgOpt; 15143 15144 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15145 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15146 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15147 return; 15148 } 15149 15150 int ArgIndex = *ArgOpt; 15151 15152 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15153 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15154 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15155 } 15156 15157 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15158 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15159 if (ArgRE->isObjCSelfExpr()) { 15160 Diag(Message->getSourceRange().getBegin(), 15161 diag::warn_objc_circular_container) 15162 << ArgRE->getDecl() << StringRef("'super'"); 15163 } 15164 } 15165 } else { 15166 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15167 15168 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15169 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15170 } 15171 15172 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15173 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15174 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15175 ValueDecl *Decl = ReceiverRE->getDecl(); 15176 Diag(Message->getSourceRange().getBegin(), 15177 diag::warn_objc_circular_container) 15178 << Decl << Decl; 15179 if (!ArgRE->isObjCSelfExpr()) { 15180 Diag(Decl->getLocation(), 15181 diag::note_objc_circular_container_declared_here) 15182 << Decl; 15183 } 15184 } 15185 } 15186 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15187 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15188 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15189 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15190 Diag(Message->getSourceRange().getBegin(), 15191 diag::warn_objc_circular_container) 15192 << Decl << Decl; 15193 Diag(Decl->getLocation(), 15194 diag::note_objc_circular_container_declared_here) 15195 << Decl; 15196 } 15197 } 15198 } 15199 } 15200 } 15201 15202 /// Check a message send to see if it's likely to cause a retain cycle. 15203 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15204 // Only check instance methods whose selector looks like a setter. 15205 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15206 return; 15207 15208 // Try to find a variable that the receiver is strongly owned by. 15209 RetainCycleOwner owner; 15210 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15211 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15212 return; 15213 } else { 15214 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15215 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15216 owner.Loc = msg->getSuperLoc(); 15217 owner.Range = msg->getSuperLoc(); 15218 } 15219 15220 // Check whether the receiver is captured by any of the arguments. 15221 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15222 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15223 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15224 // noescape blocks should not be retained by the method. 15225 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15226 continue; 15227 return diagnoseRetainCycle(*this, capturer, owner); 15228 } 15229 } 15230 } 15231 15232 /// Check a property assign to see if it's likely to cause a retain cycle. 15233 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15234 RetainCycleOwner owner; 15235 if (!findRetainCycleOwner(*this, receiver, owner)) 15236 return; 15237 15238 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15239 diagnoseRetainCycle(*this, capturer, owner); 15240 } 15241 15242 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15243 RetainCycleOwner Owner; 15244 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15245 return; 15246 15247 // Because we don't have an expression for the variable, we have to set the 15248 // location explicitly here. 15249 Owner.Loc = Var->getLocation(); 15250 Owner.Range = Var->getSourceRange(); 15251 15252 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15253 diagnoseRetainCycle(*this, Capturer, Owner); 15254 } 15255 15256 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15257 Expr *RHS, bool isProperty) { 15258 // Check if RHS is an Objective-C object literal, which also can get 15259 // immediately zapped in a weak reference. Note that we explicitly 15260 // allow ObjCStringLiterals, since those are designed to never really die. 15261 RHS = RHS->IgnoreParenImpCasts(); 15262 15263 // This enum needs to match with the 'select' in 15264 // warn_objc_arc_literal_assign (off-by-1). 15265 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15266 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15267 return false; 15268 15269 S.Diag(Loc, diag::warn_arc_literal_assign) 15270 << (unsigned) Kind 15271 << (isProperty ? 0 : 1) 15272 << RHS->getSourceRange(); 15273 15274 return true; 15275 } 15276 15277 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15278 Qualifiers::ObjCLifetime LT, 15279 Expr *RHS, bool isProperty) { 15280 // Strip off any implicit cast added to get to the one ARC-specific. 15281 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15282 if (cast->getCastKind() == CK_ARCConsumeObject) { 15283 S.Diag(Loc, diag::warn_arc_retained_assign) 15284 << (LT == Qualifiers::OCL_ExplicitNone) 15285 << (isProperty ? 0 : 1) 15286 << RHS->getSourceRange(); 15287 return true; 15288 } 15289 RHS = cast->getSubExpr(); 15290 } 15291 15292 if (LT == Qualifiers::OCL_Weak && 15293 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15294 return true; 15295 15296 return false; 15297 } 15298 15299 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15300 QualType LHS, Expr *RHS) { 15301 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15302 15303 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15304 return false; 15305 15306 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15307 return true; 15308 15309 return false; 15310 } 15311 15312 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15313 Expr *LHS, Expr *RHS) { 15314 QualType LHSType; 15315 // PropertyRef on LHS type need be directly obtained from 15316 // its declaration as it has a PseudoType. 15317 ObjCPropertyRefExpr *PRE 15318 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15319 if (PRE && !PRE->isImplicitProperty()) { 15320 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15321 if (PD) 15322 LHSType = PD->getType(); 15323 } 15324 15325 if (LHSType.isNull()) 15326 LHSType = LHS->getType(); 15327 15328 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15329 15330 if (LT == Qualifiers::OCL_Weak) { 15331 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15332 getCurFunction()->markSafeWeakUse(LHS); 15333 } 15334 15335 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15336 return; 15337 15338 // FIXME. Check for other life times. 15339 if (LT != Qualifiers::OCL_None) 15340 return; 15341 15342 if (PRE) { 15343 if (PRE->isImplicitProperty()) 15344 return; 15345 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15346 if (!PD) 15347 return; 15348 15349 unsigned Attributes = PD->getPropertyAttributes(); 15350 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15351 // when 'assign' attribute was not explicitly specified 15352 // by user, ignore it and rely on property type itself 15353 // for lifetime info. 15354 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15355 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15356 LHSType->isObjCRetainableType()) 15357 return; 15358 15359 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15360 if (cast->getCastKind() == CK_ARCConsumeObject) { 15361 Diag(Loc, diag::warn_arc_retained_property_assign) 15362 << RHS->getSourceRange(); 15363 return; 15364 } 15365 RHS = cast->getSubExpr(); 15366 } 15367 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15368 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15369 return; 15370 } 15371 } 15372 } 15373 15374 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15375 15376 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15377 SourceLocation StmtLoc, 15378 const NullStmt *Body) { 15379 // Do not warn if the body is a macro that expands to nothing, e.g: 15380 // 15381 // #define CALL(x) 15382 // if (condition) 15383 // CALL(0); 15384 if (Body->hasLeadingEmptyMacro()) 15385 return false; 15386 15387 // Get line numbers of statement and body. 15388 bool StmtLineInvalid; 15389 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15390 &StmtLineInvalid); 15391 if (StmtLineInvalid) 15392 return false; 15393 15394 bool BodyLineInvalid; 15395 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15396 &BodyLineInvalid); 15397 if (BodyLineInvalid) 15398 return false; 15399 15400 // Warn if null statement and body are on the same line. 15401 if (StmtLine != BodyLine) 15402 return false; 15403 15404 return true; 15405 } 15406 15407 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15408 const Stmt *Body, 15409 unsigned DiagID) { 15410 // Since this is a syntactic check, don't emit diagnostic for template 15411 // instantiations, this just adds noise. 15412 if (CurrentInstantiationScope) 15413 return; 15414 15415 // The body should be a null statement. 15416 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15417 if (!NBody) 15418 return; 15419 15420 // Do the usual checks. 15421 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15422 return; 15423 15424 Diag(NBody->getSemiLoc(), DiagID); 15425 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15426 } 15427 15428 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15429 const Stmt *PossibleBody) { 15430 assert(!CurrentInstantiationScope); // Ensured by caller 15431 15432 SourceLocation StmtLoc; 15433 const Stmt *Body; 15434 unsigned DiagID; 15435 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15436 StmtLoc = FS->getRParenLoc(); 15437 Body = FS->getBody(); 15438 DiagID = diag::warn_empty_for_body; 15439 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15440 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15441 Body = WS->getBody(); 15442 DiagID = diag::warn_empty_while_body; 15443 } else 15444 return; // Neither `for' nor `while'. 15445 15446 // The body should be a null statement. 15447 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15448 if (!NBody) 15449 return; 15450 15451 // Skip expensive checks if diagnostic is disabled. 15452 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15453 return; 15454 15455 // Do the usual checks. 15456 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15457 return; 15458 15459 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15460 // noise level low, emit diagnostics only if for/while is followed by a 15461 // CompoundStmt, e.g.: 15462 // for (int i = 0; i < n; i++); 15463 // { 15464 // a(i); 15465 // } 15466 // or if for/while is followed by a statement with more indentation 15467 // than for/while itself: 15468 // for (int i = 0; i < n; i++); 15469 // a(i); 15470 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15471 if (!ProbableTypo) { 15472 bool BodyColInvalid; 15473 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15474 PossibleBody->getBeginLoc(), &BodyColInvalid); 15475 if (BodyColInvalid) 15476 return; 15477 15478 bool StmtColInvalid; 15479 unsigned StmtCol = 15480 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15481 if (StmtColInvalid) 15482 return; 15483 15484 if (BodyCol > StmtCol) 15485 ProbableTypo = true; 15486 } 15487 15488 if (ProbableTypo) { 15489 Diag(NBody->getSemiLoc(), DiagID); 15490 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15491 } 15492 } 15493 15494 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15495 15496 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15497 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15498 SourceLocation OpLoc) { 15499 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15500 return; 15501 15502 if (inTemplateInstantiation()) 15503 return; 15504 15505 // Strip parens and casts away. 15506 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15507 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15508 15509 // Check for a call expression 15510 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15511 if (!CE || CE->getNumArgs() != 1) 15512 return; 15513 15514 // Check for a call to std::move 15515 if (!CE->isCallToStdMove()) 15516 return; 15517 15518 // Get argument from std::move 15519 RHSExpr = CE->getArg(0); 15520 15521 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15522 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15523 15524 // Two DeclRefExpr's, check that the decls are the same. 15525 if (LHSDeclRef && RHSDeclRef) { 15526 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15527 return; 15528 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15529 RHSDeclRef->getDecl()->getCanonicalDecl()) 15530 return; 15531 15532 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15533 << LHSExpr->getSourceRange() 15534 << RHSExpr->getSourceRange(); 15535 return; 15536 } 15537 15538 // Member variables require a different approach to check for self moves. 15539 // MemberExpr's are the same if every nested MemberExpr refers to the same 15540 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15541 // the base Expr's are CXXThisExpr's. 15542 const Expr *LHSBase = LHSExpr; 15543 const Expr *RHSBase = RHSExpr; 15544 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15545 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15546 if (!LHSME || !RHSME) 15547 return; 15548 15549 while (LHSME && RHSME) { 15550 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15551 RHSME->getMemberDecl()->getCanonicalDecl()) 15552 return; 15553 15554 LHSBase = LHSME->getBase(); 15555 RHSBase = RHSME->getBase(); 15556 LHSME = dyn_cast<MemberExpr>(LHSBase); 15557 RHSME = dyn_cast<MemberExpr>(RHSBase); 15558 } 15559 15560 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15561 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15562 if (LHSDeclRef && RHSDeclRef) { 15563 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15564 return; 15565 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15566 RHSDeclRef->getDecl()->getCanonicalDecl()) 15567 return; 15568 15569 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15570 << LHSExpr->getSourceRange() 15571 << RHSExpr->getSourceRange(); 15572 return; 15573 } 15574 15575 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15576 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15577 << LHSExpr->getSourceRange() 15578 << RHSExpr->getSourceRange(); 15579 } 15580 15581 //===--- Layout compatibility ----------------------------------------------// 15582 15583 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15584 15585 /// Check if two enumeration types are layout-compatible. 15586 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15587 // C++11 [dcl.enum] p8: 15588 // Two enumeration types are layout-compatible if they have the same 15589 // underlying type. 15590 return ED1->isComplete() && ED2->isComplete() && 15591 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15592 } 15593 15594 /// Check if two fields are layout-compatible. 15595 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15596 FieldDecl *Field2) { 15597 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15598 return false; 15599 15600 if (Field1->isBitField() != Field2->isBitField()) 15601 return false; 15602 15603 if (Field1->isBitField()) { 15604 // Make sure that the bit-fields are the same length. 15605 unsigned Bits1 = Field1->getBitWidthValue(C); 15606 unsigned Bits2 = Field2->getBitWidthValue(C); 15607 15608 if (Bits1 != Bits2) 15609 return false; 15610 } 15611 15612 return true; 15613 } 15614 15615 /// Check if two standard-layout structs are layout-compatible. 15616 /// (C++11 [class.mem] p17) 15617 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15618 RecordDecl *RD2) { 15619 // If both records are C++ classes, check that base classes match. 15620 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15621 // If one of records is a CXXRecordDecl we are in C++ mode, 15622 // thus the other one is a CXXRecordDecl, too. 15623 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15624 // Check number of base classes. 15625 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15626 return false; 15627 15628 // Check the base classes. 15629 for (CXXRecordDecl::base_class_const_iterator 15630 Base1 = D1CXX->bases_begin(), 15631 BaseEnd1 = D1CXX->bases_end(), 15632 Base2 = D2CXX->bases_begin(); 15633 Base1 != BaseEnd1; 15634 ++Base1, ++Base2) { 15635 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15636 return false; 15637 } 15638 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15639 // If only RD2 is a C++ class, it should have zero base classes. 15640 if (D2CXX->getNumBases() > 0) 15641 return false; 15642 } 15643 15644 // Check the fields. 15645 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15646 Field2End = RD2->field_end(), 15647 Field1 = RD1->field_begin(), 15648 Field1End = RD1->field_end(); 15649 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15650 if (!isLayoutCompatible(C, *Field1, *Field2)) 15651 return false; 15652 } 15653 if (Field1 != Field1End || Field2 != Field2End) 15654 return false; 15655 15656 return true; 15657 } 15658 15659 /// Check if two standard-layout unions are layout-compatible. 15660 /// (C++11 [class.mem] p18) 15661 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15662 RecordDecl *RD2) { 15663 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15664 for (auto *Field2 : RD2->fields()) 15665 UnmatchedFields.insert(Field2); 15666 15667 for (auto *Field1 : RD1->fields()) { 15668 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15669 I = UnmatchedFields.begin(), 15670 E = UnmatchedFields.end(); 15671 15672 for ( ; I != E; ++I) { 15673 if (isLayoutCompatible(C, Field1, *I)) { 15674 bool Result = UnmatchedFields.erase(*I); 15675 (void) Result; 15676 assert(Result); 15677 break; 15678 } 15679 } 15680 if (I == E) 15681 return false; 15682 } 15683 15684 return UnmatchedFields.empty(); 15685 } 15686 15687 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15688 RecordDecl *RD2) { 15689 if (RD1->isUnion() != RD2->isUnion()) 15690 return false; 15691 15692 if (RD1->isUnion()) 15693 return isLayoutCompatibleUnion(C, RD1, RD2); 15694 else 15695 return isLayoutCompatibleStruct(C, RD1, RD2); 15696 } 15697 15698 /// Check if two types are layout-compatible in C++11 sense. 15699 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15700 if (T1.isNull() || T2.isNull()) 15701 return false; 15702 15703 // C++11 [basic.types] p11: 15704 // If two types T1 and T2 are the same type, then T1 and T2 are 15705 // layout-compatible types. 15706 if (C.hasSameType(T1, T2)) 15707 return true; 15708 15709 T1 = T1.getCanonicalType().getUnqualifiedType(); 15710 T2 = T2.getCanonicalType().getUnqualifiedType(); 15711 15712 const Type::TypeClass TC1 = T1->getTypeClass(); 15713 const Type::TypeClass TC2 = T2->getTypeClass(); 15714 15715 if (TC1 != TC2) 15716 return false; 15717 15718 if (TC1 == Type::Enum) { 15719 return isLayoutCompatible(C, 15720 cast<EnumType>(T1)->getDecl(), 15721 cast<EnumType>(T2)->getDecl()); 15722 } else if (TC1 == Type::Record) { 15723 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15724 return false; 15725 15726 return isLayoutCompatible(C, 15727 cast<RecordType>(T1)->getDecl(), 15728 cast<RecordType>(T2)->getDecl()); 15729 } 15730 15731 return false; 15732 } 15733 15734 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15735 15736 /// Given a type tag expression find the type tag itself. 15737 /// 15738 /// \param TypeExpr Type tag expression, as it appears in user's code. 15739 /// 15740 /// \param VD Declaration of an identifier that appears in a type tag. 15741 /// 15742 /// \param MagicValue Type tag magic value. 15743 /// 15744 /// \param isConstantEvaluated wether the evalaution should be performed in 15745 15746 /// constant context. 15747 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15748 const ValueDecl **VD, uint64_t *MagicValue, 15749 bool isConstantEvaluated) { 15750 while(true) { 15751 if (!TypeExpr) 15752 return false; 15753 15754 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15755 15756 switch (TypeExpr->getStmtClass()) { 15757 case Stmt::UnaryOperatorClass: { 15758 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15759 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15760 TypeExpr = UO->getSubExpr(); 15761 continue; 15762 } 15763 return false; 15764 } 15765 15766 case Stmt::DeclRefExprClass: { 15767 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15768 *VD = DRE->getDecl(); 15769 return true; 15770 } 15771 15772 case Stmt::IntegerLiteralClass: { 15773 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15774 llvm::APInt MagicValueAPInt = IL->getValue(); 15775 if (MagicValueAPInt.getActiveBits() <= 64) { 15776 *MagicValue = MagicValueAPInt.getZExtValue(); 15777 return true; 15778 } else 15779 return false; 15780 } 15781 15782 case Stmt::BinaryConditionalOperatorClass: 15783 case Stmt::ConditionalOperatorClass: { 15784 const AbstractConditionalOperator *ACO = 15785 cast<AbstractConditionalOperator>(TypeExpr); 15786 bool Result; 15787 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15788 isConstantEvaluated)) { 15789 if (Result) 15790 TypeExpr = ACO->getTrueExpr(); 15791 else 15792 TypeExpr = ACO->getFalseExpr(); 15793 continue; 15794 } 15795 return false; 15796 } 15797 15798 case Stmt::BinaryOperatorClass: { 15799 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15800 if (BO->getOpcode() == BO_Comma) { 15801 TypeExpr = BO->getRHS(); 15802 continue; 15803 } 15804 return false; 15805 } 15806 15807 default: 15808 return false; 15809 } 15810 } 15811 } 15812 15813 /// Retrieve the C type corresponding to type tag TypeExpr. 15814 /// 15815 /// \param TypeExpr Expression that specifies a type tag. 15816 /// 15817 /// \param MagicValues Registered magic values. 15818 /// 15819 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15820 /// kind. 15821 /// 15822 /// \param TypeInfo Information about the corresponding C type. 15823 /// 15824 /// \param isConstantEvaluated wether the evalaution should be performed in 15825 /// constant context. 15826 /// 15827 /// \returns true if the corresponding C type was found. 15828 static bool GetMatchingCType( 15829 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15830 const ASTContext &Ctx, 15831 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15832 *MagicValues, 15833 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15834 bool isConstantEvaluated) { 15835 FoundWrongKind = false; 15836 15837 // Variable declaration that has type_tag_for_datatype attribute. 15838 const ValueDecl *VD = nullptr; 15839 15840 uint64_t MagicValue; 15841 15842 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15843 return false; 15844 15845 if (VD) { 15846 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15847 if (I->getArgumentKind() != ArgumentKind) { 15848 FoundWrongKind = true; 15849 return false; 15850 } 15851 TypeInfo.Type = I->getMatchingCType(); 15852 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15853 TypeInfo.MustBeNull = I->getMustBeNull(); 15854 return true; 15855 } 15856 return false; 15857 } 15858 15859 if (!MagicValues) 15860 return false; 15861 15862 llvm::DenseMap<Sema::TypeTagMagicValue, 15863 Sema::TypeTagData>::const_iterator I = 15864 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15865 if (I == MagicValues->end()) 15866 return false; 15867 15868 TypeInfo = I->second; 15869 return true; 15870 } 15871 15872 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15873 uint64_t MagicValue, QualType Type, 15874 bool LayoutCompatible, 15875 bool MustBeNull) { 15876 if (!TypeTagForDatatypeMagicValues) 15877 TypeTagForDatatypeMagicValues.reset( 15878 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15879 15880 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15881 (*TypeTagForDatatypeMagicValues)[Magic] = 15882 TypeTagData(Type, LayoutCompatible, MustBeNull); 15883 } 15884 15885 static bool IsSameCharType(QualType T1, QualType T2) { 15886 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15887 if (!BT1) 15888 return false; 15889 15890 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15891 if (!BT2) 15892 return false; 15893 15894 BuiltinType::Kind T1Kind = BT1->getKind(); 15895 BuiltinType::Kind T2Kind = BT2->getKind(); 15896 15897 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15898 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15899 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15900 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15901 } 15902 15903 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15904 const ArrayRef<const Expr *> ExprArgs, 15905 SourceLocation CallSiteLoc) { 15906 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15907 bool IsPointerAttr = Attr->getIsPointer(); 15908 15909 // Retrieve the argument representing the 'type_tag'. 15910 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15911 if (TypeTagIdxAST >= ExprArgs.size()) { 15912 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15913 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15914 return; 15915 } 15916 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15917 bool FoundWrongKind; 15918 TypeTagData TypeInfo; 15919 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15920 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15921 TypeInfo, isConstantEvaluated())) { 15922 if (FoundWrongKind) 15923 Diag(TypeTagExpr->getExprLoc(), 15924 diag::warn_type_tag_for_datatype_wrong_kind) 15925 << TypeTagExpr->getSourceRange(); 15926 return; 15927 } 15928 15929 // Retrieve the argument representing the 'arg_idx'. 15930 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15931 if (ArgumentIdxAST >= ExprArgs.size()) { 15932 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15933 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15934 return; 15935 } 15936 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15937 if (IsPointerAttr) { 15938 // Skip implicit cast of pointer to `void *' (as a function argument). 15939 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15940 if (ICE->getType()->isVoidPointerType() && 15941 ICE->getCastKind() == CK_BitCast) 15942 ArgumentExpr = ICE->getSubExpr(); 15943 } 15944 QualType ArgumentType = ArgumentExpr->getType(); 15945 15946 // Passing a `void*' pointer shouldn't trigger a warning. 15947 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15948 return; 15949 15950 if (TypeInfo.MustBeNull) { 15951 // Type tag with matching void type requires a null pointer. 15952 if (!ArgumentExpr->isNullPointerConstant(Context, 15953 Expr::NPC_ValueDependentIsNotNull)) { 15954 Diag(ArgumentExpr->getExprLoc(), 15955 diag::warn_type_safety_null_pointer_required) 15956 << ArgumentKind->getName() 15957 << ArgumentExpr->getSourceRange() 15958 << TypeTagExpr->getSourceRange(); 15959 } 15960 return; 15961 } 15962 15963 QualType RequiredType = TypeInfo.Type; 15964 if (IsPointerAttr) 15965 RequiredType = Context.getPointerType(RequiredType); 15966 15967 bool mismatch = false; 15968 if (!TypeInfo.LayoutCompatible) { 15969 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15970 15971 // C++11 [basic.fundamental] p1: 15972 // Plain char, signed char, and unsigned char are three distinct types. 15973 // 15974 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15975 // char' depending on the current char signedness mode. 15976 if (mismatch) 15977 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15978 RequiredType->getPointeeType())) || 15979 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15980 mismatch = false; 15981 } else 15982 if (IsPointerAttr) 15983 mismatch = !isLayoutCompatible(Context, 15984 ArgumentType->getPointeeType(), 15985 RequiredType->getPointeeType()); 15986 else 15987 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15988 15989 if (mismatch) 15990 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15991 << ArgumentType << ArgumentKind 15992 << TypeInfo.LayoutCompatible << RequiredType 15993 << ArgumentExpr->getSourceRange() 15994 << TypeTagExpr->getSourceRange(); 15995 } 15996 15997 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15998 CharUnits Alignment) { 15999 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16000 } 16001 16002 void Sema::DiagnoseMisalignedMembers() { 16003 for (MisalignedMember &m : MisalignedMembers) { 16004 const NamedDecl *ND = m.RD; 16005 if (ND->getName().empty()) { 16006 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16007 ND = TD; 16008 } 16009 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16010 << m.MD << ND << m.E->getSourceRange(); 16011 } 16012 MisalignedMembers.clear(); 16013 } 16014 16015 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16016 E = E->IgnoreParens(); 16017 if (!T->isPointerType() && !T->isIntegerType()) 16018 return; 16019 if (isa<UnaryOperator>(E) && 16020 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16021 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16022 if (isa<MemberExpr>(Op)) { 16023 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16024 if (MA != MisalignedMembers.end() && 16025 (T->isIntegerType() || 16026 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16027 Context.getTypeAlignInChars( 16028 T->getPointeeType()) <= MA->Alignment)))) 16029 MisalignedMembers.erase(MA); 16030 } 16031 } 16032 } 16033 16034 void Sema::RefersToMemberWithReducedAlignment( 16035 Expr *E, 16036 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16037 Action) { 16038 const auto *ME = dyn_cast<MemberExpr>(E); 16039 if (!ME) 16040 return; 16041 16042 // No need to check expressions with an __unaligned-qualified type. 16043 if (E->getType().getQualifiers().hasUnaligned()) 16044 return; 16045 16046 // For a chain of MemberExpr like "a.b.c.d" this list 16047 // will keep FieldDecl's like [d, c, b]. 16048 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16049 const MemberExpr *TopME = nullptr; 16050 bool AnyIsPacked = false; 16051 do { 16052 QualType BaseType = ME->getBase()->getType(); 16053 if (BaseType->isDependentType()) 16054 return; 16055 if (ME->isArrow()) 16056 BaseType = BaseType->getPointeeType(); 16057 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16058 if (RD->isInvalidDecl()) 16059 return; 16060 16061 ValueDecl *MD = ME->getMemberDecl(); 16062 auto *FD = dyn_cast<FieldDecl>(MD); 16063 // We do not care about non-data members. 16064 if (!FD || FD->isInvalidDecl()) 16065 return; 16066 16067 AnyIsPacked = 16068 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16069 ReverseMemberChain.push_back(FD); 16070 16071 TopME = ME; 16072 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16073 } while (ME); 16074 assert(TopME && "We did not compute a topmost MemberExpr!"); 16075 16076 // Not the scope of this diagnostic. 16077 if (!AnyIsPacked) 16078 return; 16079 16080 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16081 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16082 // TODO: The innermost base of the member expression may be too complicated. 16083 // For now, just disregard these cases. This is left for future 16084 // improvement. 16085 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16086 return; 16087 16088 // Alignment expected by the whole expression. 16089 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16090 16091 // No need to do anything else with this case. 16092 if (ExpectedAlignment.isOne()) 16093 return; 16094 16095 // Synthesize offset of the whole access. 16096 CharUnits Offset; 16097 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16098 I++) { 16099 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16100 } 16101 16102 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16103 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16104 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16105 16106 // The base expression of the innermost MemberExpr may give 16107 // stronger guarantees than the class containing the member. 16108 if (DRE && !TopME->isArrow()) { 16109 const ValueDecl *VD = DRE->getDecl(); 16110 if (!VD->getType()->isReferenceType()) 16111 CompleteObjectAlignment = 16112 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16113 } 16114 16115 // Check if the synthesized offset fulfills the alignment. 16116 if (Offset % ExpectedAlignment != 0 || 16117 // It may fulfill the offset it but the effective alignment may still be 16118 // lower than the expected expression alignment. 16119 CompleteObjectAlignment < ExpectedAlignment) { 16120 // If this happens, we want to determine a sensible culprit of this. 16121 // Intuitively, watching the chain of member expressions from right to 16122 // left, we start with the required alignment (as required by the field 16123 // type) but some packed attribute in that chain has reduced the alignment. 16124 // It may happen that another packed structure increases it again. But if 16125 // we are here such increase has not been enough. So pointing the first 16126 // FieldDecl that either is packed or else its RecordDecl is, 16127 // seems reasonable. 16128 FieldDecl *FD = nullptr; 16129 CharUnits Alignment; 16130 for (FieldDecl *FDI : ReverseMemberChain) { 16131 if (FDI->hasAttr<PackedAttr>() || 16132 FDI->getParent()->hasAttr<PackedAttr>()) { 16133 FD = FDI; 16134 Alignment = std::min( 16135 Context.getTypeAlignInChars(FD->getType()), 16136 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16137 break; 16138 } 16139 } 16140 assert(FD && "We did not find a packed FieldDecl!"); 16141 Action(E, FD->getParent(), FD, Alignment); 16142 } 16143 } 16144 16145 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16146 using namespace std::placeholders; 16147 16148 RefersToMemberWithReducedAlignment( 16149 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16150 _2, _3, _4)); 16151 } 16152 16153 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16154 ExprResult CallResult) { 16155 if (checkArgCount(*this, TheCall, 1)) 16156 return ExprError(); 16157 16158 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16159 if (MatrixArg.isInvalid()) 16160 return MatrixArg; 16161 Expr *Matrix = MatrixArg.get(); 16162 16163 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16164 if (!MType) { 16165 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16166 return ExprError(); 16167 } 16168 16169 // Create returned matrix type by swapping rows and columns of the argument 16170 // matrix type. 16171 QualType ResultType = Context.getConstantMatrixType( 16172 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16173 16174 // Change the return type to the type of the returned matrix. 16175 TheCall->setType(ResultType); 16176 16177 // Update call argument to use the possibly converted matrix argument. 16178 TheCall->setArg(0, Matrix); 16179 return CallResult; 16180 } 16181 16182 // Get and verify the matrix dimensions. 16183 static llvm::Optional<unsigned> 16184 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16185 SourceLocation ErrorPos; 16186 Optional<llvm::APSInt> Value = 16187 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16188 if (!Value) { 16189 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16190 << Name; 16191 return {}; 16192 } 16193 uint64_t Dim = Value->getZExtValue(); 16194 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16195 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16196 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16197 return {}; 16198 } 16199 return Dim; 16200 } 16201 16202 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16203 ExprResult CallResult) { 16204 if (!getLangOpts().MatrixTypes) { 16205 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16206 return ExprError(); 16207 } 16208 16209 if (checkArgCount(*this, TheCall, 4)) 16210 return ExprError(); 16211 16212 unsigned PtrArgIdx = 0; 16213 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16214 Expr *RowsExpr = TheCall->getArg(1); 16215 Expr *ColumnsExpr = TheCall->getArg(2); 16216 Expr *StrideExpr = TheCall->getArg(3); 16217 16218 bool ArgError = false; 16219 16220 // Check pointer argument. 16221 { 16222 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16223 if (PtrConv.isInvalid()) 16224 return PtrConv; 16225 PtrExpr = PtrConv.get(); 16226 TheCall->setArg(0, PtrExpr); 16227 if (PtrExpr->isTypeDependent()) { 16228 TheCall->setType(Context.DependentTy); 16229 return TheCall; 16230 } 16231 } 16232 16233 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16234 QualType ElementTy; 16235 if (!PtrTy) { 16236 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16237 << PtrArgIdx + 1; 16238 ArgError = true; 16239 } else { 16240 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16241 16242 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16243 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16244 << PtrArgIdx + 1; 16245 ArgError = true; 16246 } 16247 } 16248 16249 // Apply default Lvalue conversions and convert the expression to size_t. 16250 auto ApplyArgumentConversions = [this](Expr *E) { 16251 ExprResult Conv = DefaultLvalueConversion(E); 16252 if (Conv.isInvalid()) 16253 return Conv; 16254 16255 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16256 }; 16257 16258 // Apply conversion to row and column expressions. 16259 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16260 if (!RowsConv.isInvalid()) { 16261 RowsExpr = RowsConv.get(); 16262 TheCall->setArg(1, RowsExpr); 16263 } else 16264 RowsExpr = nullptr; 16265 16266 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16267 if (!ColumnsConv.isInvalid()) { 16268 ColumnsExpr = ColumnsConv.get(); 16269 TheCall->setArg(2, ColumnsExpr); 16270 } else 16271 ColumnsExpr = nullptr; 16272 16273 // If any any part of the result matrix type is still pending, just use 16274 // Context.DependentTy, until all parts are resolved. 16275 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16276 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16277 TheCall->setType(Context.DependentTy); 16278 return CallResult; 16279 } 16280 16281 // Check row and column dimenions. 16282 llvm::Optional<unsigned> MaybeRows; 16283 if (RowsExpr) 16284 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16285 16286 llvm::Optional<unsigned> MaybeColumns; 16287 if (ColumnsExpr) 16288 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16289 16290 // Check stride argument. 16291 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16292 if (StrideConv.isInvalid()) 16293 return ExprError(); 16294 StrideExpr = StrideConv.get(); 16295 TheCall->setArg(3, StrideExpr); 16296 16297 if (MaybeRows) { 16298 if (Optional<llvm::APSInt> Value = 16299 StrideExpr->getIntegerConstantExpr(Context)) { 16300 uint64_t Stride = Value->getZExtValue(); 16301 if (Stride < *MaybeRows) { 16302 Diag(StrideExpr->getBeginLoc(), 16303 diag::err_builtin_matrix_stride_too_small); 16304 ArgError = true; 16305 } 16306 } 16307 } 16308 16309 if (ArgError || !MaybeRows || !MaybeColumns) 16310 return ExprError(); 16311 16312 TheCall->setType( 16313 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16314 return CallResult; 16315 } 16316 16317 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16318 ExprResult CallResult) { 16319 if (checkArgCount(*this, TheCall, 3)) 16320 return ExprError(); 16321 16322 unsigned PtrArgIdx = 1; 16323 Expr *MatrixExpr = TheCall->getArg(0); 16324 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16325 Expr *StrideExpr = TheCall->getArg(2); 16326 16327 bool ArgError = false; 16328 16329 { 16330 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16331 if (MatrixConv.isInvalid()) 16332 return MatrixConv; 16333 MatrixExpr = MatrixConv.get(); 16334 TheCall->setArg(0, MatrixExpr); 16335 } 16336 if (MatrixExpr->isTypeDependent()) { 16337 TheCall->setType(Context.DependentTy); 16338 return TheCall; 16339 } 16340 16341 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16342 if (!MatrixTy) { 16343 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16344 ArgError = true; 16345 } 16346 16347 { 16348 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16349 if (PtrConv.isInvalid()) 16350 return PtrConv; 16351 PtrExpr = PtrConv.get(); 16352 TheCall->setArg(1, PtrExpr); 16353 if (PtrExpr->isTypeDependent()) { 16354 TheCall->setType(Context.DependentTy); 16355 return TheCall; 16356 } 16357 } 16358 16359 // Check pointer argument. 16360 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16361 if (!PtrTy) { 16362 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16363 << PtrArgIdx + 1; 16364 ArgError = true; 16365 } else { 16366 QualType ElementTy = PtrTy->getPointeeType(); 16367 if (ElementTy.isConstQualified()) { 16368 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16369 ArgError = true; 16370 } 16371 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16372 if (MatrixTy && 16373 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16374 Diag(PtrExpr->getBeginLoc(), 16375 diag::err_builtin_matrix_pointer_arg_mismatch) 16376 << ElementTy << MatrixTy->getElementType(); 16377 ArgError = true; 16378 } 16379 } 16380 16381 // Apply default Lvalue conversions and convert the stride expression to 16382 // size_t. 16383 { 16384 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16385 if (StrideConv.isInvalid()) 16386 return StrideConv; 16387 16388 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16389 if (StrideConv.isInvalid()) 16390 return StrideConv; 16391 StrideExpr = StrideConv.get(); 16392 TheCall->setArg(2, StrideExpr); 16393 } 16394 16395 // Check stride argument. 16396 if (MatrixTy) { 16397 if (Optional<llvm::APSInt> Value = 16398 StrideExpr->getIntegerConstantExpr(Context)) { 16399 uint64_t Stride = Value->getZExtValue(); 16400 if (Stride < MatrixTy->getNumRows()) { 16401 Diag(StrideExpr->getBeginLoc(), 16402 diag::err_builtin_matrix_stride_too_small); 16403 ArgError = true; 16404 } 16405 } 16406 } 16407 16408 if (ArgError) 16409 return ExprError(); 16410 16411 return CallResult; 16412 } 16413 16414 /// \brief Enforce the bounds of a TCB 16415 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16416 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16417 /// and enforce_tcb_leaf attributes. 16418 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16419 const FunctionDecl *Callee) { 16420 const FunctionDecl *Caller = getCurFunctionDecl(); 16421 16422 // Calls to builtins are not enforced. 16423 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16424 Callee->getBuiltinID() != 0) 16425 return; 16426 16427 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16428 // all TCBs the callee is a part of. 16429 llvm::StringSet<> CalleeTCBs; 16430 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16431 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16432 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16433 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16434 16435 // Go through the TCBs the caller is a part of and emit warnings if Caller 16436 // is in a TCB that the Callee is not. 16437 for_each( 16438 Caller->specific_attrs<EnforceTCBAttr>(), 16439 [&](const auto *A) { 16440 StringRef CallerTCB = A->getTCBName(); 16441 if (CalleeTCBs.count(CallerTCB) == 0) { 16442 this->Diag(TheCall->getExprLoc(), 16443 diag::warn_tcb_enforcement_violation) << Callee 16444 << CallerTCB; 16445 } 16446 }); 16447 } 16448