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/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/SaveAndRestore.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstddef> 93 #include <cstdint> 94 #include <functional> 95 #include <limits> 96 #include <string> 97 #include <tuple> 98 #include <utility> 99 100 using namespace clang; 101 using namespace sema; 102 103 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 104 unsigned ByteNo) const { 105 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 106 Context.getTargetInfo()); 107 } 108 109 /// Checks that a call expression's argument count is the desired number. 110 /// This is useful when doing custom type-checking. Returns true on error. 111 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 112 unsigned argCount = call->getNumArgs(); 113 if (argCount == desiredArgCount) return false; 114 115 if (argCount < desiredArgCount) 116 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 117 << 0 /*function call*/ << desiredArgCount << argCount 118 << call->getSourceRange(); 119 120 // Highlight all the excess arguments. 121 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 122 call->getArg(argCount - 1)->getEndLoc()); 123 124 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 125 << 0 /*function call*/ << desiredArgCount << argCount 126 << call->getArg(1)->getSourceRange(); 127 } 128 129 /// Check that the first argument to __builtin_annotation is an integer 130 /// and the second argument is a non-wide string literal. 131 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 132 if (checkArgCount(S, TheCall, 2)) 133 return true; 134 135 // First argument should be an integer. 136 Expr *ValArg = TheCall->getArg(0); 137 QualType Ty = ValArg->getType(); 138 if (!Ty->isIntegerType()) { 139 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 140 << ValArg->getSourceRange(); 141 return true; 142 } 143 144 // Second argument should be a constant string. 145 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 146 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 147 if (!Literal || !Literal->isAscii()) { 148 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 149 << StrArg->getSourceRange(); 150 return true; 151 } 152 153 TheCall->setType(Ty); 154 return false; 155 } 156 157 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 158 // We need at least one argument. 159 if (TheCall->getNumArgs() < 1) { 160 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 161 << 0 << 1 << TheCall->getNumArgs() 162 << TheCall->getCallee()->getSourceRange(); 163 return true; 164 } 165 166 // All arguments should be wide string literals. 167 for (Expr *Arg : TheCall->arguments()) { 168 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 169 if (!Literal || !Literal->isWide()) { 170 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 171 << Arg->getSourceRange(); 172 return true; 173 } 174 } 175 176 return false; 177 } 178 179 /// Check that the argument to __builtin_addressof is a glvalue, and set the 180 /// result type to the corresponding pointer type. 181 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 182 if (checkArgCount(S, TheCall, 1)) 183 return true; 184 185 ExprResult Arg(TheCall->getArg(0)); 186 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 187 if (ResultType.isNull()) 188 return true; 189 190 TheCall->setArg(0, Arg.get()); 191 TheCall->setType(ResultType); 192 return false; 193 } 194 195 /// Check the number of arguments and set the result type to 196 /// the argument type. 197 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 198 if (checkArgCount(S, TheCall, 1)) 199 return true; 200 201 TheCall->setType(TheCall->getArg(0)->getType()); 202 return false; 203 } 204 205 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 206 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 207 /// type (but not a function pointer) and that the alignment is a power-of-two. 208 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 209 if (checkArgCount(S, TheCall, 2)) 210 return true; 211 212 clang::Expr *Source = TheCall->getArg(0); 213 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 214 215 auto IsValidIntegerType = [](QualType Ty) { 216 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 217 }; 218 QualType SrcTy = Source->getType(); 219 // We should also be able to use it with arrays (but not functions!). 220 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 221 SrcTy = S.Context.getDecayedType(SrcTy); 222 } 223 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 224 SrcTy->isFunctionPointerType()) { 225 // FIXME: this is not quite the right error message since we don't allow 226 // floating point types, or member pointers. 227 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 228 << SrcTy; 229 return true; 230 } 231 232 clang::Expr *AlignOp = TheCall->getArg(1); 233 if (!IsValidIntegerType(AlignOp->getType())) { 234 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 235 << AlignOp->getType(); 236 return true; 237 } 238 Expr::EvalResult AlignResult; 239 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 240 // We can't check validity of alignment if it is type dependent. 241 if (!AlignOp->isInstantiationDependent() && 242 AlignOp->EvaluateAsInt(AlignResult, S.Context, 243 Expr::SE_AllowSideEffects)) { 244 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 245 llvm::APSInt MaxValue( 246 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 247 if (AlignValue < 1) { 248 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 249 return true; 250 } 251 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 252 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 253 << MaxValue.toString(10); 254 return true; 255 } 256 if (!AlignValue.isPowerOf2()) { 257 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 258 return true; 259 } 260 if (AlignValue == 1) { 261 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 262 << IsBooleanAlignBuiltin; 263 } 264 } 265 266 ExprResult SrcArg = S.PerformCopyInitialization( 267 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 268 SourceLocation(), Source); 269 if (SrcArg.isInvalid()) 270 return true; 271 TheCall->setArg(0, SrcArg.get()); 272 ExprResult AlignArg = 273 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 274 S.Context, AlignOp->getType(), false), 275 SourceLocation(), AlignOp); 276 if (AlignArg.isInvalid()) 277 return true; 278 TheCall->setArg(1, AlignArg.get()); 279 // For align_up/align_down, the return type is the same as the (potentially 280 // decayed) argument type including qualifiers. For is_aligned(), the result 281 // is always bool. 282 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 283 return false; 284 } 285 286 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 287 if (checkArgCount(S, TheCall, 3)) 288 return true; 289 290 // First two arguments should be integers. 291 for (unsigned I = 0; I < 2; ++I) { 292 ExprResult Arg = TheCall->getArg(I); 293 QualType Ty = Arg.get()->getType(); 294 if (!Ty->isIntegerType()) { 295 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 296 << Ty << Arg.get()->getSourceRange(); 297 return true; 298 } 299 InitializedEntity Entity = InitializedEntity::InitializeParameter( 300 S.getASTContext(), Ty, /*consume*/ false); 301 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 302 if (Arg.isInvalid()) 303 return true; 304 TheCall->setArg(I, Arg.get()); 305 } 306 307 // Third argument should be a pointer to a non-const integer. 308 // IRGen correctly handles volatile, restrict, and address spaces, and 309 // the other qualifiers aren't possible. 310 { 311 ExprResult Arg = TheCall->getArg(2); 312 QualType Ty = Arg.get()->getType(); 313 const auto *PtrTy = Ty->getAs<PointerType>(); 314 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 315 !PtrTy->getPointeeType().isConstQualified())) { 316 S.Diag(Arg.get()->getBeginLoc(), 317 diag::err_overflow_builtin_must_be_ptr_int) 318 << Ty << Arg.get()->getSourceRange(); 319 return true; 320 } 321 InitializedEntity Entity = InitializedEntity::InitializeParameter( 322 S.getASTContext(), Ty, /*consume*/ false); 323 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 324 if (Arg.isInvalid()) 325 return true; 326 TheCall->setArg(2, Arg.get()); 327 } 328 return false; 329 } 330 331 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 332 if (checkArgCount(S, BuiltinCall, 2)) 333 return true; 334 335 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 336 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 337 Expr *Call = BuiltinCall->getArg(0); 338 Expr *Chain = BuiltinCall->getArg(1); 339 340 if (Call->getStmtClass() != Stmt::CallExprClass) { 341 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 342 << Call->getSourceRange(); 343 return true; 344 } 345 346 auto CE = cast<CallExpr>(Call); 347 if (CE->getCallee()->getType()->isBlockPointerType()) { 348 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 349 << Call->getSourceRange(); 350 return true; 351 } 352 353 const Decl *TargetDecl = CE->getCalleeDecl(); 354 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 355 if (FD->getBuiltinID()) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 362 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 363 << Call->getSourceRange(); 364 return true; 365 } 366 367 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 368 if (ChainResult.isInvalid()) 369 return true; 370 if (!ChainResult.get()->getType()->isPointerType()) { 371 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 372 << Chain->getSourceRange(); 373 return true; 374 } 375 376 QualType ReturnTy = CE->getCallReturnType(S.Context); 377 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 378 QualType BuiltinTy = S.Context.getFunctionType( 379 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 380 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 381 382 Builtin = 383 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 384 385 BuiltinCall->setType(CE->getType()); 386 BuiltinCall->setValueKind(CE->getValueKind()); 387 BuiltinCall->setObjectKind(CE->getObjectKind()); 388 BuiltinCall->setCallee(Builtin); 389 BuiltinCall->setArg(1, ChainResult.get()); 390 391 return false; 392 } 393 394 namespace { 395 396 class EstimateSizeFormatHandler 397 : public analyze_format_string::FormatStringHandler { 398 size_t Size; 399 400 public: 401 EstimateSizeFormatHandler(StringRef Format) 402 : Size(std::min(Format.find(0), Format.size()) + 403 1 /* null byte always written by sprintf */) {} 404 405 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 406 const char *, unsigned SpecifierLen) override { 407 408 const size_t FieldWidth = computeFieldWidth(FS); 409 const size_t Precision = computePrecision(FS); 410 411 // The actual format. 412 switch (FS.getConversionSpecifier().getKind()) { 413 // Just a char. 414 case analyze_format_string::ConversionSpecifier::cArg: 415 case analyze_format_string::ConversionSpecifier::CArg: 416 Size += std::max(FieldWidth, (size_t)1); 417 break; 418 // Just an integer. 419 case analyze_format_string::ConversionSpecifier::dArg: 420 case analyze_format_string::ConversionSpecifier::DArg: 421 case analyze_format_string::ConversionSpecifier::iArg: 422 case analyze_format_string::ConversionSpecifier::oArg: 423 case analyze_format_string::ConversionSpecifier::OArg: 424 case analyze_format_string::ConversionSpecifier::uArg: 425 case analyze_format_string::ConversionSpecifier::UArg: 426 case analyze_format_string::ConversionSpecifier::xArg: 427 case analyze_format_string::ConversionSpecifier::XArg: 428 Size += std::max(FieldWidth, Precision); 429 break; 430 431 // %g style conversion switches between %f or %e style dynamically. 432 // %f always takes less space, so default to it. 433 case analyze_format_string::ConversionSpecifier::gArg: 434 case analyze_format_string::ConversionSpecifier::GArg: 435 436 // Floating point number in the form '[+]ddd.ddd'. 437 case analyze_format_string::ConversionSpecifier::fArg: 438 case analyze_format_string::ConversionSpecifier::FArg: 439 Size += std::max(FieldWidth, 1 /* integer part */ + 440 (Precision ? 1 + Precision 441 : 0) /* period + decimal */); 442 break; 443 444 // Floating point number in the form '[-]d.ddde[+-]dd'. 445 case analyze_format_string::ConversionSpecifier::eArg: 446 case analyze_format_string::ConversionSpecifier::EArg: 447 Size += 448 std::max(FieldWidth, 449 1 /* integer part */ + 450 (Precision ? 1 + Precision : 0) /* period + decimal */ + 451 1 /* e or E letter */ + 2 /* exponent */); 452 break; 453 454 // Floating point number in the form '[-]0xh.hhhhp±dd'. 455 case analyze_format_string::ConversionSpecifier::aArg: 456 case analyze_format_string::ConversionSpecifier::AArg: 457 Size += 458 std::max(FieldWidth, 459 2 /* 0x */ + 1 /* integer part */ + 460 (Precision ? 1 + Precision : 0) /* period + decimal */ + 461 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 462 break; 463 464 // Just a string. 465 case analyze_format_string::ConversionSpecifier::sArg: 466 case analyze_format_string::ConversionSpecifier::SArg: 467 Size += FieldWidth; 468 break; 469 470 // Just a pointer in the form '0xddd'. 471 case analyze_format_string::ConversionSpecifier::pArg: 472 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 473 break; 474 475 // A plain percent. 476 case analyze_format_string::ConversionSpecifier::PercentArg: 477 Size += 1; 478 break; 479 480 default: 481 break; 482 } 483 484 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 485 486 if (FS.hasAlternativeForm()) { 487 switch (FS.getConversionSpecifier().getKind()) { 488 default: 489 break; 490 // Force a leading '0'. 491 case analyze_format_string::ConversionSpecifier::oArg: 492 Size += 1; 493 break; 494 // Force a leading '0x'. 495 case analyze_format_string::ConversionSpecifier::xArg: 496 case analyze_format_string::ConversionSpecifier::XArg: 497 Size += 2; 498 break; 499 // Force a period '.' before decimal, even if precision is 0. 500 case analyze_format_string::ConversionSpecifier::aArg: 501 case analyze_format_string::ConversionSpecifier::AArg: 502 case analyze_format_string::ConversionSpecifier::eArg: 503 case analyze_format_string::ConversionSpecifier::EArg: 504 case analyze_format_string::ConversionSpecifier::fArg: 505 case analyze_format_string::ConversionSpecifier::FArg: 506 case analyze_format_string::ConversionSpecifier::gArg: 507 case analyze_format_string::ConversionSpecifier::GArg: 508 Size += (Precision ? 0 : 1); 509 break; 510 } 511 } 512 assert(SpecifierLen <= Size && "no underflow"); 513 Size -= SpecifierLen; 514 return true; 515 } 516 517 size_t getSizeLowerBound() const { return Size; } 518 519 private: 520 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 521 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 522 size_t FieldWidth = 0; 523 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 524 FieldWidth = FW.getConstantAmount(); 525 return FieldWidth; 526 } 527 528 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 529 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 530 size_t Precision = 0; 531 532 // See man 3 printf for default precision value based on the specifier. 533 switch (FW.getHowSpecified()) { 534 case analyze_format_string::OptionalAmount::NotSpecified: 535 switch (FS.getConversionSpecifier().getKind()) { 536 default: 537 break; 538 case analyze_format_string::ConversionSpecifier::dArg: // %d 539 case analyze_format_string::ConversionSpecifier::DArg: // %D 540 case analyze_format_string::ConversionSpecifier::iArg: // %i 541 Precision = 1; 542 break; 543 case analyze_format_string::ConversionSpecifier::oArg: // %d 544 case analyze_format_string::ConversionSpecifier::OArg: // %D 545 case analyze_format_string::ConversionSpecifier::uArg: // %d 546 case analyze_format_string::ConversionSpecifier::UArg: // %D 547 case analyze_format_string::ConversionSpecifier::xArg: // %d 548 case analyze_format_string::ConversionSpecifier::XArg: // %D 549 Precision = 1; 550 break; 551 case analyze_format_string::ConversionSpecifier::fArg: // %f 552 case analyze_format_string::ConversionSpecifier::FArg: // %F 553 case analyze_format_string::ConversionSpecifier::eArg: // %e 554 case analyze_format_string::ConversionSpecifier::EArg: // %E 555 case analyze_format_string::ConversionSpecifier::gArg: // %g 556 case analyze_format_string::ConversionSpecifier::GArg: // %G 557 Precision = 6; 558 break; 559 case analyze_format_string::ConversionSpecifier::pArg: // %d 560 Precision = 1; 561 break; 562 } 563 break; 564 case analyze_format_string::OptionalAmount::Constant: 565 Precision = FW.getConstantAmount(); 566 break; 567 default: 568 break; 569 } 570 return Precision; 571 } 572 }; 573 574 } // namespace 575 576 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 577 /// __builtin_*_chk function, then use the object size argument specified in the 578 /// source. Otherwise, infer the object size using __builtin_object_size. 579 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 580 CallExpr *TheCall) { 581 // FIXME: There are some more useful checks we could be doing here: 582 // - Evaluate strlen of strcpy arguments, use as object size. 583 584 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 585 isConstantEvaluated()) 586 return; 587 588 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 589 if (!BuiltinID) 590 return; 591 592 const TargetInfo &TI = getASTContext().getTargetInfo(); 593 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 594 595 unsigned DiagID = 0; 596 bool IsChkVariant = false; 597 Optional<llvm::APSInt> UsedSize; 598 unsigned SizeIndex, ObjectIndex; 599 switch (BuiltinID) { 600 default: 601 return; 602 case Builtin::BIsprintf: 603 case Builtin::BI__builtin___sprintf_chk: { 604 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 605 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 606 607 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 608 609 if (!Format->isAscii() && !Format->isUTF8()) 610 return; 611 612 StringRef FormatStrRef = Format->getString(); 613 EstimateSizeFormatHandler H(FormatStrRef); 614 const char *FormatBytes = FormatStrRef.data(); 615 const ConstantArrayType *T = 616 Context.getAsConstantArrayType(Format->getType()); 617 assert(T && "String literal not of constant array type!"); 618 size_t TypeSize = T->getSize().getZExtValue(); 619 620 // In case there's a null byte somewhere. 621 size_t StrLen = 622 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 623 if (!analyze_format_string::ParsePrintfString( 624 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 625 Context.getTargetInfo(), false)) { 626 DiagID = diag::warn_fortify_source_format_overflow; 627 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 628 .extOrTrunc(SizeTypeWidth); 629 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 630 IsChkVariant = true; 631 ObjectIndex = 2; 632 } else { 633 IsChkVariant = false; 634 ObjectIndex = 0; 635 } 636 break; 637 } 638 } 639 return; 640 } 641 case Builtin::BI__builtin___memcpy_chk: 642 case Builtin::BI__builtin___memmove_chk: 643 case Builtin::BI__builtin___memset_chk: 644 case Builtin::BI__builtin___strlcat_chk: 645 case Builtin::BI__builtin___strlcpy_chk: 646 case Builtin::BI__builtin___strncat_chk: 647 case Builtin::BI__builtin___strncpy_chk: 648 case Builtin::BI__builtin___stpncpy_chk: 649 case Builtin::BI__builtin___memccpy_chk: 650 case Builtin::BI__builtin___mempcpy_chk: { 651 DiagID = diag::warn_builtin_chk_overflow; 652 IsChkVariant = true; 653 SizeIndex = TheCall->getNumArgs() - 2; 654 ObjectIndex = TheCall->getNumArgs() - 1; 655 break; 656 } 657 658 case Builtin::BI__builtin___snprintf_chk: 659 case Builtin::BI__builtin___vsnprintf_chk: { 660 DiagID = diag::warn_builtin_chk_overflow; 661 IsChkVariant = true; 662 SizeIndex = 1; 663 ObjectIndex = 3; 664 break; 665 } 666 667 case Builtin::BIstrncat: 668 case Builtin::BI__builtin_strncat: 669 case Builtin::BIstrncpy: 670 case Builtin::BI__builtin_strncpy: 671 case Builtin::BIstpncpy: 672 case Builtin::BI__builtin_stpncpy: { 673 // Whether these functions overflow depends on the runtime strlen of the 674 // string, not just the buffer size, so emitting the "always overflow" 675 // diagnostic isn't quite right. We should still diagnose passing a buffer 676 // size larger than the destination buffer though; this is a runtime abort 677 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 678 DiagID = diag::warn_fortify_source_size_mismatch; 679 SizeIndex = TheCall->getNumArgs() - 1; 680 ObjectIndex = 0; 681 break; 682 } 683 684 case Builtin::BImemcpy: 685 case Builtin::BI__builtin_memcpy: 686 case Builtin::BImemmove: 687 case Builtin::BI__builtin_memmove: 688 case Builtin::BImemset: 689 case Builtin::BI__builtin_memset: 690 case Builtin::BImempcpy: 691 case Builtin::BI__builtin_mempcpy: { 692 DiagID = diag::warn_fortify_source_overflow; 693 SizeIndex = TheCall->getNumArgs() - 1; 694 ObjectIndex = 0; 695 break; 696 } 697 case Builtin::BIsnprintf: 698 case Builtin::BI__builtin_snprintf: 699 case Builtin::BIvsnprintf: 700 case Builtin::BI__builtin_vsnprintf: { 701 DiagID = diag::warn_fortify_source_size_mismatch; 702 SizeIndex = 1; 703 ObjectIndex = 0; 704 break; 705 } 706 } 707 708 llvm::APSInt ObjectSize; 709 // For __builtin___*_chk, the object size is explicitly provided by the caller 710 // (usually using __builtin_object_size). Use that value to check this call. 711 if (IsChkVariant) { 712 Expr::EvalResult Result; 713 Expr *SizeArg = TheCall->getArg(ObjectIndex); 714 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 715 return; 716 ObjectSize = Result.Val.getInt(); 717 718 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 719 } else { 720 // If the parameter has a pass_object_size attribute, then we should use its 721 // (potentially) more strict checking mode. Otherwise, conservatively assume 722 // type 0. 723 int BOSType = 0; 724 if (const auto *POS = 725 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 726 BOSType = POS->getType(); 727 728 Expr *ObjArg = TheCall->getArg(ObjectIndex); 729 uint64_t Result; 730 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 731 return; 732 // Get the object size in the target's size_t width. 733 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 734 } 735 736 // Evaluate the number of bytes of the object that this call will use. 737 if (!UsedSize) { 738 Expr::EvalResult Result; 739 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 740 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 741 return; 742 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 743 } 744 745 if (UsedSize.getValue().ule(ObjectSize)) 746 return; 747 748 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 749 // Skim off the details of whichever builtin was called to produce a better 750 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 751 if (IsChkVariant) { 752 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 753 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 754 } else if (FunctionName.startswith("__builtin_")) { 755 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 756 } 757 758 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 759 PDiag(DiagID) 760 << FunctionName << ObjectSize.toString(/*Radix=*/10) 761 << UsedSize.getValue().toString(/*Radix=*/10)); 762 } 763 764 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 765 Scope::ScopeFlags NeededScopeFlags, 766 unsigned DiagID) { 767 // Scopes aren't available during instantiation. Fortunately, builtin 768 // functions cannot be template args so they cannot be formed through template 769 // instantiation. Therefore checking once during the parse is sufficient. 770 if (SemaRef.inTemplateInstantiation()) 771 return false; 772 773 Scope *S = SemaRef.getCurScope(); 774 while (S && !S->isSEHExceptScope()) 775 S = S->getParent(); 776 if (!S || !(S->getFlags() & NeededScopeFlags)) { 777 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 778 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 779 << DRE->getDecl()->getIdentifier(); 780 return true; 781 } 782 783 return false; 784 } 785 786 static inline bool isBlockPointer(Expr *Arg) { 787 return Arg->getType()->isBlockPointerType(); 788 } 789 790 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 791 /// void*, which is a requirement of device side enqueue. 792 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 793 const BlockPointerType *BPT = 794 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 795 ArrayRef<QualType> Params = 796 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 797 unsigned ArgCounter = 0; 798 bool IllegalParams = false; 799 // Iterate through the block parameters until either one is found that is not 800 // a local void*, or the block is valid. 801 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 802 I != E; ++I, ++ArgCounter) { 803 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 804 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 805 LangAS::opencl_local) { 806 // Get the location of the error. If a block literal has been passed 807 // (BlockExpr) then we can point straight to the offending argument, 808 // else we just point to the variable reference. 809 SourceLocation ErrorLoc; 810 if (isa<BlockExpr>(BlockArg)) { 811 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 812 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 813 } else if (isa<DeclRefExpr>(BlockArg)) { 814 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 815 } 816 S.Diag(ErrorLoc, 817 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 818 IllegalParams = true; 819 } 820 } 821 822 return IllegalParams; 823 } 824 825 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 826 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 827 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 828 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 829 return true; 830 } 831 return false; 832 } 833 834 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 835 if (checkArgCount(S, TheCall, 2)) 836 return true; 837 838 if (checkOpenCLSubgroupExt(S, TheCall)) 839 return true; 840 841 // First argument is an ndrange_t type. 842 Expr *NDRangeArg = TheCall->getArg(0); 843 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 844 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 845 << TheCall->getDirectCallee() << "'ndrange_t'"; 846 return true; 847 } 848 849 Expr *BlockArg = TheCall->getArg(1); 850 if (!isBlockPointer(BlockArg)) { 851 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 852 << TheCall->getDirectCallee() << "block"; 853 return true; 854 } 855 return checkOpenCLBlockArgs(S, BlockArg); 856 } 857 858 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 859 /// get_kernel_work_group_size 860 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 861 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 862 if (checkArgCount(S, TheCall, 1)) 863 return true; 864 865 Expr *BlockArg = TheCall->getArg(0); 866 if (!isBlockPointer(BlockArg)) { 867 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 868 << TheCall->getDirectCallee() << "block"; 869 return true; 870 } 871 return checkOpenCLBlockArgs(S, BlockArg); 872 } 873 874 /// Diagnose integer type and any valid implicit conversion to it. 875 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 876 const QualType &IntType); 877 878 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 879 unsigned Start, unsigned End) { 880 bool IllegalParams = false; 881 for (unsigned I = Start; I <= End; ++I) 882 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 883 S.Context.getSizeType()); 884 return IllegalParams; 885 } 886 887 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 888 /// 'local void*' parameter of passed block. 889 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 890 Expr *BlockArg, 891 unsigned NumNonVarArgs) { 892 const BlockPointerType *BPT = 893 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 894 unsigned NumBlockParams = 895 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 896 unsigned TotalNumArgs = TheCall->getNumArgs(); 897 898 // For each argument passed to the block, a corresponding uint needs to 899 // be passed to describe the size of the local memory. 900 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 901 S.Diag(TheCall->getBeginLoc(), 902 diag::err_opencl_enqueue_kernel_local_size_args); 903 return true; 904 } 905 906 // Check that the sizes of the local memory are specified by integers. 907 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 908 TotalNumArgs - 1); 909 } 910 911 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 912 /// overload formats specified in Table 6.13.17.1. 913 /// int enqueue_kernel(queue_t queue, 914 /// kernel_enqueue_flags_t flags, 915 /// const ndrange_t ndrange, 916 /// void (^block)(void)) 917 /// int enqueue_kernel(queue_t queue, 918 /// kernel_enqueue_flags_t flags, 919 /// const ndrange_t ndrange, 920 /// uint num_events_in_wait_list, 921 /// clk_event_t *event_wait_list, 922 /// clk_event_t *event_ret, 923 /// void (^block)(void)) 924 /// int enqueue_kernel(queue_t queue, 925 /// kernel_enqueue_flags_t flags, 926 /// const ndrange_t ndrange, 927 /// void (^block)(local void*, ...), 928 /// uint size0, ...) 929 /// int enqueue_kernel(queue_t queue, 930 /// kernel_enqueue_flags_t flags, 931 /// const ndrange_t ndrange, 932 /// uint num_events_in_wait_list, 933 /// clk_event_t *event_wait_list, 934 /// clk_event_t *event_ret, 935 /// void (^block)(local void*, ...), 936 /// uint size0, ...) 937 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 938 unsigned NumArgs = TheCall->getNumArgs(); 939 940 if (NumArgs < 4) { 941 S.Diag(TheCall->getBeginLoc(), 942 diag::err_typecheck_call_too_few_args_at_least) 943 << 0 << 4 << NumArgs; 944 return true; 945 } 946 947 Expr *Arg0 = TheCall->getArg(0); 948 Expr *Arg1 = TheCall->getArg(1); 949 Expr *Arg2 = TheCall->getArg(2); 950 Expr *Arg3 = TheCall->getArg(3); 951 952 // First argument always needs to be a queue_t type. 953 if (!Arg0->getType()->isQueueT()) { 954 S.Diag(TheCall->getArg(0)->getBeginLoc(), 955 diag::err_opencl_builtin_expected_type) 956 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 957 return true; 958 } 959 960 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 961 if (!Arg1->getType()->isIntegerType()) { 962 S.Diag(TheCall->getArg(1)->getBeginLoc(), 963 diag::err_opencl_builtin_expected_type) 964 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 965 return true; 966 } 967 968 // Third argument is always an ndrange_t type. 969 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 970 S.Diag(TheCall->getArg(2)->getBeginLoc(), 971 diag::err_opencl_builtin_expected_type) 972 << TheCall->getDirectCallee() << "'ndrange_t'"; 973 return true; 974 } 975 976 // With four arguments, there is only one form that the function could be 977 // called in: no events and no variable arguments. 978 if (NumArgs == 4) { 979 // check that the last argument is the right block type. 980 if (!isBlockPointer(Arg3)) { 981 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 982 << TheCall->getDirectCallee() << "block"; 983 return true; 984 } 985 // we have a block type, check the prototype 986 const BlockPointerType *BPT = 987 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 988 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 989 S.Diag(Arg3->getBeginLoc(), 990 diag::err_opencl_enqueue_kernel_blocks_no_args); 991 return true; 992 } 993 return false; 994 } 995 // we can have block + varargs. 996 if (isBlockPointer(Arg3)) 997 return (checkOpenCLBlockArgs(S, Arg3) || 998 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 999 // last two cases with either exactly 7 args or 7 args and varargs. 1000 if (NumArgs >= 7) { 1001 // check common block argument. 1002 Expr *Arg6 = TheCall->getArg(6); 1003 if (!isBlockPointer(Arg6)) { 1004 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1005 << TheCall->getDirectCallee() << "block"; 1006 return true; 1007 } 1008 if (checkOpenCLBlockArgs(S, Arg6)) 1009 return true; 1010 1011 // Forth argument has to be any integer type. 1012 if (!Arg3->getType()->isIntegerType()) { 1013 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1014 diag::err_opencl_builtin_expected_type) 1015 << TheCall->getDirectCallee() << "integer"; 1016 return true; 1017 } 1018 // check remaining common arguments. 1019 Expr *Arg4 = TheCall->getArg(4); 1020 Expr *Arg5 = TheCall->getArg(5); 1021 1022 // Fifth argument is always passed as a pointer to clk_event_t. 1023 if (!Arg4->isNullPointerConstant(S.Context, 1024 Expr::NPC_ValueDependentIsNotNull) && 1025 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1026 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1027 diag::err_opencl_builtin_expected_type) 1028 << TheCall->getDirectCallee() 1029 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1030 return true; 1031 } 1032 1033 // Sixth argument is always passed as a pointer to clk_event_t. 1034 if (!Arg5->isNullPointerConstant(S.Context, 1035 Expr::NPC_ValueDependentIsNotNull) && 1036 !(Arg5->getType()->isPointerType() && 1037 Arg5->getType()->getPointeeType()->isClkEventT())) { 1038 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1039 diag::err_opencl_builtin_expected_type) 1040 << TheCall->getDirectCallee() 1041 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1042 return true; 1043 } 1044 1045 if (NumArgs == 7) 1046 return false; 1047 1048 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1049 } 1050 1051 // None of the specific case has been detected, give generic error 1052 S.Diag(TheCall->getBeginLoc(), 1053 diag::err_opencl_enqueue_kernel_incorrect_args); 1054 return true; 1055 } 1056 1057 /// Returns OpenCL access qual. 1058 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1059 return D->getAttr<OpenCLAccessAttr>(); 1060 } 1061 1062 /// Returns true if pipe element type is different from the pointer. 1063 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1064 const Expr *Arg0 = Call->getArg(0); 1065 // First argument type should always be pipe. 1066 if (!Arg0->getType()->isPipeType()) { 1067 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1068 << Call->getDirectCallee() << Arg0->getSourceRange(); 1069 return true; 1070 } 1071 OpenCLAccessAttr *AccessQual = 1072 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1073 // Validates the access qualifier is compatible with the call. 1074 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1075 // read_only and write_only, and assumed to be read_only if no qualifier is 1076 // specified. 1077 switch (Call->getDirectCallee()->getBuiltinID()) { 1078 case Builtin::BIread_pipe: 1079 case Builtin::BIreserve_read_pipe: 1080 case Builtin::BIcommit_read_pipe: 1081 case Builtin::BIwork_group_reserve_read_pipe: 1082 case Builtin::BIsub_group_reserve_read_pipe: 1083 case Builtin::BIwork_group_commit_read_pipe: 1084 case Builtin::BIsub_group_commit_read_pipe: 1085 if (!(!AccessQual || AccessQual->isReadOnly())) { 1086 S.Diag(Arg0->getBeginLoc(), 1087 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1088 << "read_only" << Arg0->getSourceRange(); 1089 return true; 1090 } 1091 break; 1092 case Builtin::BIwrite_pipe: 1093 case Builtin::BIreserve_write_pipe: 1094 case Builtin::BIcommit_write_pipe: 1095 case Builtin::BIwork_group_reserve_write_pipe: 1096 case Builtin::BIsub_group_reserve_write_pipe: 1097 case Builtin::BIwork_group_commit_write_pipe: 1098 case Builtin::BIsub_group_commit_write_pipe: 1099 if (!(AccessQual && AccessQual->isWriteOnly())) { 1100 S.Diag(Arg0->getBeginLoc(), 1101 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1102 << "write_only" << Arg0->getSourceRange(); 1103 return true; 1104 } 1105 break; 1106 default: 1107 break; 1108 } 1109 return false; 1110 } 1111 1112 /// Returns true if pipe element type is different from the pointer. 1113 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1114 const Expr *Arg0 = Call->getArg(0); 1115 const Expr *ArgIdx = Call->getArg(Idx); 1116 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1117 const QualType EltTy = PipeTy->getElementType(); 1118 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1119 // The Idx argument should be a pointer and the type of the pointer and 1120 // the type of pipe element should also be the same. 1121 if (!ArgTy || 1122 !S.Context.hasSameType( 1123 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1124 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1125 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1126 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1127 return true; 1128 } 1129 return false; 1130 } 1131 1132 // Performs semantic analysis for the read/write_pipe call. 1133 // \param S Reference to the semantic analyzer. 1134 // \param Call A pointer to the builtin call. 1135 // \return True if a semantic error has been found, false otherwise. 1136 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1137 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1138 // functions have two forms. 1139 switch (Call->getNumArgs()) { 1140 case 2: 1141 if (checkOpenCLPipeArg(S, Call)) 1142 return true; 1143 // The call with 2 arguments should be 1144 // read/write_pipe(pipe T, T*). 1145 // Check packet type T. 1146 if (checkOpenCLPipePacketType(S, Call, 1)) 1147 return true; 1148 break; 1149 1150 case 4: { 1151 if (checkOpenCLPipeArg(S, Call)) 1152 return true; 1153 // The call with 4 arguments should be 1154 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1155 // Check reserve_id_t. 1156 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1157 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1158 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1159 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1160 return true; 1161 } 1162 1163 // Check the index. 1164 const Expr *Arg2 = Call->getArg(2); 1165 if (!Arg2->getType()->isIntegerType() && 1166 !Arg2->getType()->isUnsignedIntegerType()) { 1167 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1168 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1169 << Arg2->getType() << Arg2->getSourceRange(); 1170 return true; 1171 } 1172 1173 // Check packet type T. 1174 if (checkOpenCLPipePacketType(S, Call, 3)) 1175 return true; 1176 } break; 1177 default: 1178 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1179 << Call->getDirectCallee() << Call->getSourceRange(); 1180 return true; 1181 } 1182 1183 return false; 1184 } 1185 1186 // Performs a semantic analysis on the {work_group_/sub_group_ 1187 // /_}reserve_{read/write}_pipe 1188 // \param S Reference to the semantic analyzer. 1189 // \param Call The call to the builtin function to be analyzed. 1190 // \return True if a semantic error was found, false otherwise. 1191 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1192 if (checkArgCount(S, Call, 2)) 1193 return true; 1194 1195 if (checkOpenCLPipeArg(S, Call)) 1196 return true; 1197 1198 // Check the reserve size. 1199 if (!Call->getArg(1)->getType()->isIntegerType() && 1200 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1201 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1202 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1203 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1204 return true; 1205 } 1206 1207 // Since return type of reserve_read/write_pipe built-in function is 1208 // reserve_id_t, which is not defined in the builtin def file , we used int 1209 // as return type and need to override the return type of these functions. 1210 Call->setType(S.Context.OCLReserveIDTy); 1211 1212 return false; 1213 } 1214 1215 // Performs a semantic analysis on {work_group_/sub_group_ 1216 // /_}commit_{read/write}_pipe 1217 // \param S Reference to the semantic analyzer. 1218 // \param Call The call to the builtin function to be analyzed. 1219 // \return True if a semantic error was found, false otherwise. 1220 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1221 if (checkArgCount(S, Call, 2)) 1222 return true; 1223 1224 if (checkOpenCLPipeArg(S, Call)) 1225 return true; 1226 1227 // Check reserve_id_t. 1228 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1229 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1230 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1231 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1232 return true; 1233 } 1234 1235 return false; 1236 } 1237 1238 // Performs a semantic analysis on the call to built-in Pipe 1239 // Query Functions. 1240 // \param S Reference to the semantic analyzer. 1241 // \param Call The call to the builtin function to be analyzed. 1242 // \return True if a semantic error was found, false otherwise. 1243 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1244 if (checkArgCount(S, Call, 1)) 1245 return true; 1246 1247 if (!Call->getArg(0)->getType()->isPipeType()) { 1248 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1249 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1250 return true; 1251 } 1252 1253 return false; 1254 } 1255 1256 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1257 // Performs semantic analysis for the to_global/local/private call. 1258 // \param S Reference to the semantic analyzer. 1259 // \param BuiltinID ID of the builtin function. 1260 // \param Call A pointer to the builtin call. 1261 // \return True if a semantic error has been found, false otherwise. 1262 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1263 CallExpr *Call) { 1264 if (Call->getNumArgs() != 1) { 1265 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 1266 << Call->getDirectCallee() << Call->getSourceRange(); 1267 return true; 1268 } 1269 1270 auto RT = Call->getArg(0)->getType(); 1271 if (!RT->isPointerType() || RT->getPointeeType() 1272 .getAddressSpace() == LangAS::opencl_constant) { 1273 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1274 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1275 return true; 1276 } 1277 1278 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1279 S.Diag(Call->getArg(0)->getBeginLoc(), 1280 diag::warn_opencl_generic_address_space_arg) 1281 << Call->getDirectCallee()->getNameInfo().getAsString() 1282 << Call->getArg(0)->getSourceRange(); 1283 } 1284 1285 RT = RT->getPointeeType(); 1286 auto Qual = RT.getQualifiers(); 1287 switch (BuiltinID) { 1288 case Builtin::BIto_global: 1289 Qual.setAddressSpace(LangAS::opencl_global); 1290 break; 1291 case Builtin::BIto_local: 1292 Qual.setAddressSpace(LangAS::opencl_local); 1293 break; 1294 case Builtin::BIto_private: 1295 Qual.setAddressSpace(LangAS::opencl_private); 1296 break; 1297 default: 1298 llvm_unreachable("Invalid builtin function"); 1299 } 1300 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1301 RT.getUnqualifiedType(), Qual))); 1302 1303 return false; 1304 } 1305 1306 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1307 if (checkArgCount(S, TheCall, 1)) 1308 return ExprError(); 1309 1310 // Compute __builtin_launder's parameter type from the argument. 1311 // The parameter type is: 1312 // * The type of the argument if it's not an array or function type, 1313 // Otherwise, 1314 // * The decayed argument type. 1315 QualType ParamTy = [&]() { 1316 QualType ArgTy = TheCall->getArg(0)->getType(); 1317 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1318 return S.Context.getPointerType(Ty->getElementType()); 1319 if (ArgTy->isFunctionType()) { 1320 return S.Context.getPointerType(ArgTy); 1321 } 1322 return ArgTy; 1323 }(); 1324 1325 TheCall->setType(ParamTy); 1326 1327 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1328 if (!ParamTy->isPointerType()) 1329 return 0; 1330 if (ParamTy->isFunctionPointerType()) 1331 return 1; 1332 if (ParamTy->isVoidPointerType()) 1333 return 2; 1334 return llvm::Optional<unsigned>{}; 1335 }(); 1336 if (DiagSelect.hasValue()) { 1337 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1338 << DiagSelect.getValue() << TheCall->getSourceRange(); 1339 return ExprError(); 1340 } 1341 1342 // We either have an incomplete class type, or we have a class template 1343 // whose instantiation has not been forced. Example: 1344 // 1345 // template <class T> struct Foo { T value; }; 1346 // Foo<int> *p = nullptr; 1347 // auto *d = __builtin_launder(p); 1348 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1349 diag::err_incomplete_type)) 1350 return ExprError(); 1351 1352 assert(ParamTy->getPointeeType()->isObjectType() && 1353 "Unhandled non-object pointer case"); 1354 1355 InitializedEntity Entity = 1356 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1357 ExprResult Arg = 1358 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1359 if (Arg.isInvalid()) 1360 return ExprError(); 1361 TheCall->setArg(0, Arg.get()); 1362 1363 return TheCall; 1364 } 1365 1366 // Emit an error and return true if the current architecture is not in the list 1367 // of supported architectures. 1368 static bool 1369 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1370 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1371 llvm::Triple::ArchType CurArch = 1372 S.getASTContext().getTargetInfo().getTriple().getArch(); 1373 if (llvm::is_contained(SupportedArchs, CurArch)) 1374 return false; 1375 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1376 << TheCall->getSourceRange(); 1377 return true; 1378 } 1379 1380 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1381 SourceLocation CallSiteLoc); 1382 1383 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1384 CallExpr *TheCall) { 1385 switch (TI.getTriple().getArch()) { 1386 default: 1387 // Some builtins don't require additional checking, so just consider these 1388 // acceptable. 1389 return false; 1390 case llvm::Triple::arm: 1391 case llvm::Triple::armeb: 1392 case llvm::Triple::thumb: 1393 case llvm::Triple::thumbeb: 1394 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1395 case llvm::Triple::aarch64: 1396 case llvm::Triple::aarch64_32: 1397 case llvm::Triple::aarch64_be: 1398 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1399 case llvm::Triple::bpfeb: 1400 case llvm::Triple::bpfel: 1401 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1402 case llvm::Triple::hexagon: 1403 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1404 case llvm::Triple::mips: 1405 case llvm::Triple::mipsel: 1406 case llvm::Triple::mips64: 1407 case llvm::Triple::mips64el: 1408 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1409 case llvm::Triple::systemz: 1410 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1411 case llvm::Triple::x86: 1412 case llvm::Triple::x86_64: 1413 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1414 case llvm::Triple::ppc: 1415 case llvm::Triple::ppc64: 1416 case llvm::Triple::ppc64le: 1417 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1418 case llvm::Triple::amdgcn: 1419 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1420 } 1421 } 1422 1423 ExprResult 1424 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1425 CallExpr *TheCall) { 1426 ExprResult TheCallResult(TheCall); 1427 1428 // Find out if any arguments are required to be integer constant expressions. 1429 unsigned ICEArguments = 0; 1430 ASTContext::GetBuiltinTypeError Error; 1431 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1432 if (Error != ASTContext::GE_None) 1433 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1434 1435 // If any arguments are required to be ICE's, check and diagnose. 1436 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1437 // Skip arguments not required to be ICE's. 1438 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1439 1440 llvm::APSInt Result; 1441 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1442 return true; 1443 ICEArguments &= ~(1 << ArgNo); 1444 } 1445 1446 switch (BuiltinID) { 1447 case Builtin::BI__builtin___CFStringMakeConstantString: 1448 assert(TheCall->getNumArgs() == 1 && 1449 "Wrong # arguments to builtin CFStringMakeConstantString"); 1450 if (CheckObjCString(TheCall->getArg(0))) 1451 return ExprError(); 1452 break; 1453 case Builtin::BI__builtin_ms_va_start: 1454 case Builtin::BI__builtin_stdarg_start: 1455 case Builtin::BI__builtin_va_start: 1456 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1457 return ExprError(); 1458 break; 1459 case Builtin::BI__va_start: { 1460 switch (Context.getTargetInfo().getTriple().getArch()) { 1461 case llvm::Triple::aarch64: 1462 case llvm::Triple::arm: 1463 case llvm::Triple::thumb: 1464 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1465 return ExprError(); 1466 break; 1467 default: 1468 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1469 return ExprError(); 1470 break; 1471 } 1472 break; 1473 } 1474 1475 // The acquire, release, and no fence variants are ARM and AArch64 only. 1476 case Builtin::BI_interlockedbittestandset_acq: 1477 case Builtin::BI_interlockedbittestandset_rel: 1478 case Builtin::BI_interlockedbittestandset_nf: 1479 case Builtin::BI_interlockedbittestandreset_acq: 1480 case Builtin::BI_interlockedbittestandreset_rel: 1481 case Builtin::BI_interlockedbittestandreset_nf: 1482 if (CheckBuiltinTargetSupport( 1483 *this, BuiltinID, TheCall, 1484 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1485 return ExprError(); 1486 break; 1487 1488 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1489 case Builtin::BI_bittest64: 1490 case Builtin::BI_bittestandcomplement64: 1491 case Builtin::BI_bittestandreset64: 1492 case Builtin::BI_bittestandset64: 1493 case Builtin::BI_interlockedbittestandreset64: 1494 case Builtin::BI_interlockedbittestandset64: 1495 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1496 {llvm::Triple::x86_64, llvm::Triple::arm, 1497 llvm::Triple::thumb, llvm::Triple::aarch64})) 1498 return ExprError(); 1499 break; 1500 1501 case Builtin::BI__builtin_isgreater: 1502 case Builtin::BI__builtin_isgreaterequal: 1503 case Builtin::BI__builtin_isless: 1504 case Builtin::BI__builtin_islessequal: 1505 case Builtin::BI__builtin_islessgreater: 1506 case Builtin::BI__builtin_isunordered: 1507 if (SemaBuiltinUnorderedCompare(TheCall)) 1508 return ExprError(); 1509 break; 1510 case Builtin::BI__builtin_fpclassify: 1511 if (SemaBuiltinFPClassification(TheCall, 6)) 1512 return ExprError(); 1513 break; 1514 case Builtin::BI__builtin_isfinite: 1515 case Builtin::BI__builtin_isinf: 1516 case Builtin::BI__builtin_isinf_sign: 1517 case Builtin::BI__builtin_isnan: 1518 case Builtin::BI__builtin_isnormal: 1519 case Builtin::BI__builtin_signbit: 1520 case Builtin::BI__builtin_signbitf: 1521 case Builtin::BI__builtin_signbitl: 1522 if (SemaBuiltinFPClassification(TheCall, 1)) 1523 return ExprError(); 1524 break; 1525 case Builtin::BI__builtin_shufflevector: 1526 return SemaBuiltinShuffleVector(TheCall); 1527 // TheCall will be freed by the smart pointer here, but that's fine, since 1528 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1529 case Builtin::BI__builtin_prefetch: 1530 if (SemaBuiltinPrefetch(TheCall)) 1531 return ExprError(); 1532 break; 1533 case Builtin::BI__builtin_alloca_with_align: 1534 if (SemaBuiltinAllocaWithAlign(TheCall)) 1535 return ExprError(); 1536 LLVM_FALLTHROUGH; 1537 case Builtin::BI__builtin_alloca: 1538 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1539 << TheCall->getDirectCallee(); 1540 break; 1541 case Builtin::BI__assume: 1542 case Builtin::BI__builtin_assume: 1543 if (SemaBuiltinAssume(TheCall)) 1544 return ExprError(); 1545 break; 1546 case Builtin::BI__builtin_assume_aligned: 1547 if (SemaBuiltinAssumeAligned(TheCall)) 1548 return ExprError(); 1549 break; 1550 case Builtin::BI__builtin_dynamic_object_size: 1551 case Builtin::BI__builtin_object_size: 1552 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1553 return ExprError(); 1554 break; 1555 case Builtin::BI__builtin_longjmp: 1556 if (SemaBuiltinLongjmp(TheCall)) 1557 return ExprError(); 1558 break; 1559 case Builtin::BI__builtin_setjmp: 1560 if (SemaBuiltinSetjmp(TheCall)) 1561 return ExprError(); 1562 break; 1563 case Builtin::BI_setjmp: 1564 case Builtin::BI_setjmpex: 1565 if (checkArgCount(*this, TheCall, 1)) 1566 return true; 1567 break; 1568 case Builtin::BI__builtin_classify_type: 1569 if (checkArgCount(*this, TheCall, 1)) return true; 1570 TheCall->setType(Context.IntTy); 1571 break; 1572 case Builtin::BI__builtin_constant_p: { 1573 if (checkArgCount(*this, TheCall, 1)) return true; 1574 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1575 if (Arg.isInvalid()) return true; 1576 TheCall->setArg(0, Arg.get()); 1577 TheCall->setType(Context.IntTy); 1578 break; 1579 } 1580 case Builtin::BI__builtin_launder: 1581 return SemaBuiltinLaunder(*this, TheCall); 1582 case Builtin::BI__sync_fetch_and_add: 1583 case Builtin::BI__sync_fetch_and_add_1: 1584 case Builtin::BI__sync_fetch_and_add_2: 1585 case Builtin::BI__sync_fetch_and_add_4: 1586 case Builtin::BI__sync_fetch_and_add_8: 1587 case Builtin::BI__sync_fetch_and_add_16: 1588 case Builtin::BI__sync_fetch_and_sub: 1589 case Builtin::BI__sync_fetch_and_sub_1: 1590 case Builtin::BI__sync_fetch_and_sub_2: 1591 case Builtin::BI__sync_fetch_and_sub_4: 1592 case Builtin::BI__sync_fetch_and_sub_8: 1593 case Builtin::BI__sync_fetch_and_sub_16: 1594 case Builtin::BI__sync_fetch_and_or: 1595 case Builtin::BI__sync_fetch_and_or_1: 1596 case Builtin::BI__sync_fetch_and_or_2: 1597 case Builtin::BI__sync_fetch_and_or_4: 1598 case Builtin::BI__sync_fetch_and_or_8: 1599 case Builtin::BI__sync_fetch_and_or_16: 1600 case Builtin::BI__sync_fetch_and_and: 1601 case Builtin::BI__sync_fetch_and_and_1: 1602 case Builtin::BI__sync_fetch_and_and_2: 1603 case Builtin::BI__sync_fetch_and_and_4: 1604 case Builtin::BI__sync_fetch_and_and_8: 1605 case Builtin::BI__sync_fetch_and_and_16: 1606 case Builtin::BI__sync_fetch_and_xor: 1607 case Builtin::BI__sync_fetch_and_xor_1: 1608 case Builtin::BI__sync_fetch_and_xor_2: 1609 case Builtin::BI__sync_fetch_and_xor_4: 1610 case Builtin::BI__sync_fetch_and_xor_8: 1611 case Builtin::BI__sync_fetch_and_xor_16: 1612 case Builtin::BI__sync_fetch_and_nand: 1613 case Builtin::BI__sync_fetch_and_nand_1: 1614 case Builtin::BI__sync_fetch_and_nand_2: 1615 case Builtin::BI__sync_fetch_and_nand_4: 1616 case Builtin::BI__sync_fetch_and_nand_8: 1617 case Builtin::BI__sync_fetch_and_nand_16: 1618 case Builtin::BI__sync_add_and_fetch: 1619 case Builtin::BI__sync_add_and_fetch_1: 1620 case Builtin::BI__sync_add_and_fetch_2: 1621 case Builtin::BI__sync_add_and_fetch_4: 1622 case Builtin::BI__sync_add_and_fetch_8: 1623 case Builtin::BI__sync_add_and_fetch_16: 1624 case Builtin::BI__sync_sub_and_fetch: 1625 case Builtin::BI__sync_sub_and_fetch_1: 1626 case Builtin::BI__sync_sub_and_fetch_2: 1627 case Builtin::BI__sync_sub_and_fetch_4: 1628 case Builtin::BI__sync_sub_and_fetch_8: 1629 case Builtin::BI__sync_sub_and_fetch_16: 1630 case Builtin::BI__sync_and_and_fetch: 1631 case Builtin::BI__sync_and_and_fetch_1: 1632 case Builtin::BI__sync_and_and_fetch_2: 1633 case Builtin::BI__sync_and_and_fetch_4: 1634 case Builtin::BI__sync_and_and_fetch_8: 1635 case Builtin::BI__sync_and_and_fetch_16: 1636 case Builtin::BI__sync_or_and_fetch: 1637 case Builtin::BI__sync_or_and_fetch_1: 1638 case Builtin::BI__sync_or_and_fetch_2: 1639 case Builtin::BI__sync_or_and_fetch_4: 1640 case Builtin::BI__sync_or_and_fetch_8: 1641 case Builtin::BI__sync_or_and_fetch_16: 1642 case Builtin::BI__sync_xor_and_fetch: 1643 case Builtin::BI__sync_xor_and_fetch_1: 1644 case Builtin::BI__sync_xor_and_fetch_2: 1645 case Builtin::BI__sync_xor_and_fetch_4: 1646 case Builtin::BI__sync_xor_and_fetch_8: 1647 case Builtin::BI__sync_xor_and_fetch_16: 1648 case Builtin::BI__sync_nand_and_fetch: 1649 case Builtin::BI__sync_nand_and_fetch_1: 1650 case Builtin::BI__sync_nand_and_fetch_2: 1651 case Builtin::BI__sync_nand_and_fetch_4: 1652 case Builtin::BI__sync_nand_and_fetch_8: 1653 case Builtin::BI__sync_nand_and_fetch_16: 1654 case Builtin::BI__sync_val_compare_and_swap: 1655 case Builtin::BI__sync_val_compare_and_swap_1: 1656 case Builtin::BI__sync_val_compare_and_swap_2: 1657 case Builtin::BI__sync_val_compare_and_swap_4: 1658 case Builtin::BI__sync_val_compare_and_swap_8: 1659 case Builtin::BI__sync_val_compare_and_swap_16: 1660 case Builtin::BI__sync_bool_compare_and_swap: 1661 case Builtin::BI__sync_bool_compare_and_swap_1: 1662 case Builtin::BI__sync_bool_compare_and_swap_2: 1663 case Builtin::BI__sync_bool_compare_and_swap_4: 1664 case Builtin::BI__sync_bool_compare_and_swap_8: 1665 case Builtin::BI__sync_bool_compare_and_swap_16: 1666 case Builtin::BI__sync_lock_test_and_set: 1667 case Builtin::BI__sync_lock_test_and_set_1: 1668 case Builtin::BI__sync_lock_test_and_set_2: 1669 case Builtin::BI__sync_lock_test_and_set_4: 1670 case Builtin::BI__sync_lock_test_and_set_8: 1671 case Builtin::BI__sync_lock_test_and_set_16: 1672 case Builtin::BI__sync_lock_release: 1673 case Builtin::BI__sync_lock_release_1: 1674 case Builtin::BI__sync_lock_release_2: 1675 case Builtin::BI__sync_lock_release_4: 1676 case Builtin::BI__sync_lock_release_8: 1677 case Builtin::BI__sync_lock_release_16: 1678 case Builtin::BI__sync_swap: 1679 case Builtin::BI__sync_swap_1: 1680 case Builtin::BI__sync_swap_2: 1681 case Builtin::BI__sync_swap_4: 1682 case Builtin::BI__sync_swap_8: 1683 case Builtin::BI__sync_swap_16: 1684 return SemaBuiltinAtomicOverloaded(TheCallResult); 1685 case Builtin::BI__sync_synchronize: 1686 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1687 << TheCall->getCallee()->getSourceRange(); 1688 break; 1689 case Builtin::BI__builtin_nontemporal_load: 1690 case Builtin::BI__builtin_nontemporal_store: 1691 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1692 case Builtin::BI__builtin_memcpy_inline: { 1693 clang::Expr *SizeOp = TheCall->getArg(2); 1694 // We warn about copying to or from `nullptr` pointers when `size` is 1695 // greater than 0. When `size` is value dependent we cannot evaluate its 1696 // value so we bail out. 1697 if (SizeOp->isValueDependent()) 1698 break; 1699 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1700 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1701 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1702 } 1703 break; 1704 } 1705 #define BUILTIN(ID, TYPE, ATTRS) 1706 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1707 case Builtin::BI##ID: \ 1708 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1709 #include "clang/Basic/Builtins.def" 1710 case Builtin::BI__annotation: 1711 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1712 return ExprError(); 1713 break; 1714 case Builtin::BI__builtin_annotation: 1715 if (SemaBuiltinAnnotation(*this, TheCall)) 1716 return ExprError(); 1717 break; 1718 case Builtin::BI__builtin_addressof: 1719 if (SemaBuiltinAddressof(*this, TheCall)) 1720 return ExprError(); 1721 break; 1722 case Builtin::BI__builtin_is_aligned: 1723 case Builtin::BI__builtin_align_up: 1724 case Builtin::BI__builtin_align_down: 1725 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1726 return ExprError(); 1727 break; 1728 case Builtin::BI__builtin_add_overflow: 1729 case Builtin::BI__builtin_sub_overflow: 1730 case Builtin::BI__builtin_mul_overflow: 1731 if (SemaBuiltinOverflow(*this, TheCall)) 1732 return ExprError(); 1733 break; 1734 case Builtin::BI__builtin_operator_new: 1735 case Builtin::BI__builtin_operator_delete: { 1736 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1737 ExprResult Res = 1738 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1739 if (Res.isInvalid()) 1740 CorrectDelayedTyposInExpr(TheCallResult.get()); 1741 return Res; 1742 } 1743 case Builtin::BI__builtin_dump_struct: { 1744 // We first want to ensure we are called with 2 arguments 1745 if (checkArgCount(*this, TheCall, 2)) 1746 return ExprError(); 1747 // Ensure that the first argument is of type 'struct XX *' 1748 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1749 const QualType PtrArgType = PtrArg->getType(); 1750 if (!PtrArgType->isPointerType() || 1751 !PtrArgType->getPointeeType()->isRecordType()) { 1752 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1753 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1754 << "structure pointer"; 1755 return ExprError(); 1756 } 1757 1758 // Ensure that the second argument is of type 'FunctionType' 1759 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1760 const QualType FnPtrArgType = FnPtrArg->getType(); 1761 if (!FnPtrArgType->isPointerType()) { 1762 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1763 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1764 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1765 return ExprError(); 1766 } 1767 1768 const auto *FuncType = 1769 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1770 1771 if (!FuncType) { 1772 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1773 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1774 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1775 return ExprError(); 1776 } 1777 1778 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1779 if (!FT->getNumParams()) { 1780 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1781 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1782 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1783 return ExprError(); 1784 } 1785 QualType PT = FT->getParamType(0); 1786 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1787 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1788 !PT->getPointeeType().isConstQualified()) { 1789 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1790 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1791 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1792 return ExprError(); 1793 } 1794 } 1795 1796 TheCall->setType(Context.IntTy); 1797 break; 1798 } 1799 case Builtin::BI__builtin_preserve_access_index: 1800 if (SemaBuiltinPreserveAI(*this, TheCall)) 1801 return ExprError(); 1802 break; 1803 case Builtin::BI__builtin_call_with_static_chain: 1804 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1805 return ExprError(); 1806 break; 1807 case Builtin::BI__exception_code: 1808 case Builtin::BI_exception_code: 1809 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1810 diag::err_seh___except_block)) 1811 return ExprError(); 1812 break; 1813 case Builtin::BI__exception_info: 1814 case Builtin::BI_exception_info: 1815 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1816 diag::err_seh___except_filter)) 1817 return ExprError(); 1818 break; 1819 case Builtin::BI__GetExceptionInfo: 1820 if (checkArgCount(*this, TheCall, 1)) 1821 return ExprError(); 1822 1823 if (CheckCXXThrowOperand( 1824 TheCall->getBeginLoc(), 1825 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1826 TheCall)) 1827 return ExprError(); 1828 1829 TheCall->setType(Context.VoidPtrTy); 1830 break; 1831 // OpenCL v2.0, s6.13.16 - Pipe functions 1832 case Builtin::BIread_pipe: 1833 case Builtin::BIwrite_pipe: 1834 // Since those two functions are declared with var args, we need a semantic 1835 // check for the argument. 1836 if (SemaBuiltinRWPipe(*this, TheCall)) 1837 return ExprError(); 1838 break; 1839 case Builtin::BIreserve_read_pipe: 1840 case Builtin::BIreserve_write_pipe: 1841 case Builtin::BIwork_group_reserve_read_pipe: 1842 case Builtin::BIwork_group_reserve_write_pipe: 1843 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1844 return ExprError(); 1845 break; 1846 case Builtin::BIsub_group_reserve_read_pipe: 1847 case Builtin::BIsub_group_reserve_write_pipe: 1848 if (checkOpenCLSubgroupExt(*this, TheCall) || 1849 SemaBuiltinReserveRWPipe(*this, TheCall)) 1850 return ExprError(); 1851 break; 1852 case Builtin::BIcommit_read_pipe: 1853 case Builtin::BIcommit_write_pipe: 1854 case Builtin::BIwork_group_commit_read_pipe: 1855 case Builtin::BIwork_group_commit_write_pipe: 1856 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1857 return ExprError(); 1858 break; 1859 case Builtin::BIsub_group_commit_read_pipe: 1860 case Builtin::BIsub_group_commit_write_pipe: 1861 if (checkOpenCLSubgroupExt(*this, TheCall) || 1862 SemaBuiltinCommitRWPipe(*this, TheCall)) 1863 return ExprError(); 1864 break; 1865 case Builtin::BIget_pipe_num_packets: 1866 case Builtin::BIget_pipe_max_packets: 1867 if (SemaBuiltinPipePackets(*this, TheCall)) 1868 return ExprError(); 1869 break; 1870 case Builtin::BIto_global: 1871 case Builtin::BIto_local: 1872 case Builtin::BIto_private: 1873 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1874 return ExprError(); 1875 break; 1876 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1877 case Builtin::BIenqueue_kernel: 1878 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1879 return ExprError(); 1880 break; 1881 case Builtin::BIget_kernel_work_group_size: 1882 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1883 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1884 return ExprError(); 1885 break; 1886 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1887 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1888 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1889 return ExprError(); 1890 break; 1891 case Builtin::BI__builtin_os_log_format: 1892 Cleanup.setExprNeedsCleanups(true); 1893 LLVM_FALLTHROUGH; 1894 case Builtin::BI__builtin_os_log_format_buffer_size: 1895 if (SemaBuiltinOSLogFormat(TheCall)) 1896 return ExprError(); 1897 break; 1898 case Builtin::BI__builtin_frame_address: 1899 case Builtin::BI__builtin_return_address: { 1900 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1901 return ExprError(); 1902 1903 // -Wframe-address warning if non-zero passed to builtin 1904 // return/frame address. 1905 Expr::EvalResult Result; 1906 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1907 Result.Val.getInt() != 0) 1908 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1909 << ((BuiltinID == Builtin::BI__builtin_return_address) 1910 ? "__builtin_return_address" 1911 : "__builtin_frame_address") 1912 << TheCall->getSourceRange(); 1913 break; 1914 } 1915 1916 case Builtin::BI__builtin_matrix_transpose: 1917 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1918 } 1919 1920 // Since the target specific builtins for each arch overlap, only check those 1921 // of the arch we are compiling for. 1922 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1923 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1924 assert(Context.getAuxTargetInfo() && 1925 "Aux Target Builtin, but not an aux target?"); 1926 1927 if (CheckTSBuiltinFunctionCall( 1928 *Context.getAuxTargetInfo(), 1929 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1930 return ExprError(); 1931 } else { 1932 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 1933 TheCall)) 1934 return ExprError(); 1935 } 1936 } 1937 1938 return TheCallResult; 1939 } 1940 1941 // Get the valid immediate range for the specified NEON type code. 1942 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1943 NeonTypeFlags Type(t); 1944 int IsQuad = ForceQuad ? true : Type.isQuad(); 1945 switch (Type.getEltType()) { 1946 case NeonTypeFlags::Int8: 1947 case NeonTypeFlags::Poly8: 1948 return shift ? 7 : (8 << IsQuad) - 1; 1949 case NeonTypeFlags::Int16: 1950 case NeonTypeFlags::Poly16: 1951 return shift ? 15 : (4 << IsQuad) - 1; 1952 case NeonTypeFlags::Int32: 1953 return shift ? 31 : (2 << IsQuad) - 1; 1954 case NeonTypeFlags::Int64: 1955 case NeonTypeFlags::Poly64: 1956 return shift ? 63 : (1 << IsQuad) - 1; 1957 case NeonTypeFlags::Poly128: 1958 return shift ? 127 : (1 << IsQuad) - 1; 1959 case NeonTypeFlags::Float16: 1960 assert(!shift && "cannot shift float types!"); 1961 return (4 << IsQuad) - 1; 1962 case NeonTypeFlags::Float32: 1963 assert(!shift && "cannot shift float types!"); 1964 return (2 << IsQuad) - 1; 1965 case NeonTypeFlags::Float64: 1966 assert(!shift && "cannot shift float types!"); 1967 return (1 << IsQuad) - 1; 1968 case NeonTypeFlags::BFloat16: 1969 assert(!shift && "cannot shift float types!"); 1970 return (4 << IsQuad) - 1; 1971 } 1972 llvm_unreachable("Invalid NeonTypeFlag!"); 1973 } 1974 1975 /// getNeonEltType - Return the QualType corresponding to the elements of 1976 /// the vector type specified by the NeonTypeFlags. This is used to check 1977 /// the pointer arguments for Neon load/store intrinsics. 1978 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1979 bool IsPolyUnsigned, bool IsInt64Long) { 1980 switch (Flags.getEltType()) { 1981 case NeonTypeFlags::Int8: 1982 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1983 case NeonTypeFlags::Int16: 1984 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1985 case NeonTypeFlags::Int32: 1986 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1987 case NeonTypeFlags::Int64: 1988 if (IsInt64Long) 1989 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1990 else 1991 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1992 : Context.LongLongTy; 1993 case NeonTypeFlags::Poly8: 1994 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1995 case NeonTypeFlags::Poly16: 1996 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1997 case NeonTypeFlags::Poly64: 1998 if (IsInt64Long) 1999 return Context.UnsignedLongTy; 2000 else 2001 return Context.UnsignedLongLongTy; 2002 case NeonTypeFlags::Poly128: 2003 break; 2004 case NeonTypeFlags::Float16: 2005 return Context.HalfTy; 2006 case NeonTypeFlags::Float32: 2007 return Context.FloatTy; 2008 case NeonTypeFlags::Float64: 2009 return Context.DoubleTy; 2010 case NeonTypeFlags::BFloat16: 2011 return Context.BFloat16Ty; 2012 } 2013 llvm_unreachable("Invalid NeonTypeFlag!"); 2014 } 2015 2016 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2017 // Range check SVE intrinsics that take immediate values. 2018 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2019 2020 switch (BuiltinID) { 2021 default: 2022 return false; 2023 #define GET_SVE_IMMEDIATE_CHECK 2024 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2025 #undef GET_SVE_IMMEDIATE_CHECK 2026 } 2027 2028 // Perform all the immediate checks for this builtin call. 2029 bool HasError = false; 2030 for (auto &I : ImmChecks) { 2031 int ArgNum, CheckTy, ElementSizeInBits; 2032 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2033 2034 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2035 2036 // Function that checks whether the operand (ArgNum) is an immediate 2037 // that is one of the predefined values. 2038 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2039 int ErrDiag) -> bool { 2040 // We can't check the value of a dependent argument. 2041 Expr *Arg = TheCall->getArg(ArgNum); 2042 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2043 return false; 2044 2045 // Check constant-ness first. 2046 llvm::APSInt Imm; 2047 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2048 return true; 2049 2050 if (!CheckImm(Imm.getSExtValue())) 2051 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2052 return false; 2053 }; 2054 2055 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2056 case SVETypeFlags::ImmCheck0_31: 2057 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2058 HasError = true; 2059 break; 2060 case SVETypeFlags::ImmCheck0_13: 2061 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2062 HasError = true; 2063 break; 2064 case SVETypeFlags::ImmCheck1_16: 2065 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2066 HasError = true; 2067 break; 2068 case SVETypeFlags::ImmCheck0_7: 2069 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2070 HasError = true; 2071 break; 2072 case SVETypeFlags::ImmCheckExtract: 2073 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2074 (2048 / ElementSizeInBits) - 1)) 2075 HasError = true; 2076 break; 2077 case SVETypeFlags::ImmCheckShiftRight: 2078 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2079 HasError = true; 2080 break; 2081 case SVETypeFlags::ImmCheckShiftRightNarrow: 2082 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2083 ElementSizeInBits / 2)) 2084 HasError = true; 2085 break; 2086 case SVETypeFlags::ImmCheckShiftLeft: 2087 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2088 ElementSizeInBits - 1)) 2089 HasError = true; 2090 break; 2091 case SVETypeFlags::ImmCheckLaneIndex: 2092 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2093 (128 / (1 * ElementSizeInBits)) - 1)) 2094 HasError = true; 2095 break; 2096 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2097 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2098 (128 / (2 * ElementSizeInBits)) - 1)) 2099 HasError = true; 2100 break; 2101 case SVETypeFlags::ImmCheckLaneIndexDot: 2102 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2103 (128 / (4 * ElementSizeInBits)) - 1)) 2104 HasError = true; 2105 break; 2106 case SVETypeFlags::ImmCheckComplexRot90_270: 2107 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2108 diag::err_rotation_argument_to_cadd)) 2109 HasError = true; 2110 break; 2111 case SVETypeFlags::ImmCheckComplexRotAll90: 2112 if (CheckImmediateInSet( 2113 [](int64_t V) { 2114 return V == 0 || V == 90 || V == 180 || V == 270; 2115 }, 2116 diag::err_rotation_argument_to_cmla)) 2117 HasError = true; 2118 break; 2119 } 2120 } 2121 2122 return HasError; 2123 } 2124 2125 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2126 unsigned BuiltinID, CallExpr *TheCall) { 2127 llvm::APSInt Result; 2128 uint64_t mask = 0; 2129 unsigned TV = 0; 2130 int PtrArgNum = -1; 2131 bool HasConstPtr = false; 2132 switch (BuiltinID) { 2133 #define GET_NEON_OVERLOAD_CHECK 2134 #include "clang/Basic/arm_neon.inc" 2135 #include "clang/Basic/arm_fp16.inc" 2136 #undef GET_NEON_OVERLOAD_CHECK 2137 } 2138 2139 // For NEON intrinsics which are overloaded on vector element type, validate 2140 // the immediate which specifies which variant to emit. 2141 unsigned ImmArg = TheCall->getNumArgs()-1; 2142 if (mask) { 2143 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2144 return true; 2145 2146 TV = Result.getLimitedValue(64); 2147 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2148 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2149 << TheCall->getArg(ImmArg)->getSourceRange(); 2150 } 2151 2152 if (PtrArgNum >= 0) { 2153 // Check that pointer arguments have the specified type. 2154 Expr *Arg = TheCall->getArg(PtrArgNum); 2155 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2156 Arg = ICE->getSubExpr(); 2157 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2158 QualType RHSTy = RHS.get()->getType(); 2159 2160 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2161 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2162 Arch == llvm::Triple::aarch64_32 || 2163 Arch == llvm::Triple::aarch64_be; 2164 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2165 QualType EltTy = 2166 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2167 if (HasConstPtr) 2168 EltTy = EltTy.withConst(); 2169 QualType LHSTy = Context.getPointerType(EltTy); 2170 AssignConvertType ConvTy; 2171 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2172 if (RHS.isInvalid()) 2173 return true; 2174 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2175 RHS.get(), AA_Assigning)) 2176 return true; 2177 } 2178 2179 // For NEON intrinsics which take an immediate value as part of the 2180 // instruction, range check them here. 2181 unsigned i = 0, l = 0, u = 0; 2182 switch (BuiltinID) { 2183 default: 2184 return false; 2185 #define GET_NEON_IMMEDIATE_CHECK 2186 #include "clang/Basic/arm_neon.inc" 2187 #include "clang/Basic/arm_fp16.inc" 2188 #undef GET_NEON_IMMEDIATE_CHECK 2189 } 2190 2191 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2192 } 2193 2194 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2195 switch (BuiltinID) { 2196 default: 2197 return false; 2198 #include "clang/Basic/arm_mve_builtin_sema.inc" 2199 } 2200 } 2201 2202 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2203 CallExpr *TheCall) { 2204 bool Err = false; 2205 switch (BuiltinID) { 2206 default: 2207 return false; 2208 #include "clang/Basic/arm_cde_builtin_sema.inc" 2209 } 2210 2211 if (Err) 2212 return true; 2213 2214 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2215 } 2216 2217 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2218 const Expr *CoprocArg, bool WantCDE) { 2219 if (isConstantEvaluated()) 2220 return false; 2221 2222 // We can't check the value of a dependent argument. 2223 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2224 return false; 2225 2226 llvm::APSInt CoprocNoAP; 2227 bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context); 2228 (void)IsICE; 2229 assert(IsICE && "Coprocossor immediate is not a constant expression"); 2230 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2231 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2232 2233 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2234 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2235 2236 if (IsCDECoproc != WantCDE) 2237 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2238 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2239 2240 return false; 2241 } 2242 2243 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2244 unsigned MaxWidth) { 2245 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2246 BuiltinID == ARM::BI__builtin_arm_ldaex || 2247 BuiltinID == ARM::BI__builtin_arm_strex || 2248 BuiltinID == ARM::BI__builtin_arm_stlex || 2249 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2250 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2251 BuiltinID == AArch64::BI__builtin_arm_strex || 2252 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2253 "unexpected ARM builtin"); 2254 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2255 BuiltinID == ARM::BI__builtin_arm_ldaex || 2256 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2257 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2258 2259 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2260 2261 // Ensure that we have the proper number of arguments. 2262 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2263 return true; 2264 2265 // Inspect the pointer argument of the atomic builtin. This should always be 2266 // a pointer type, whose element is an integral scalar or pointer type. 2267 // Because it is a pointer type, we don't have to worry about any implicit 2268 // casts here. 2269 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2270 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2271 if (PointerArgRes.isInvalid()) 2272 return true; 2273 PointerArg = PointerArgRes.get(); 2274 2275 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2276 if (!pointerType) { 2277 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2278 << PointerArg->getType() << PointerArg->getSourceRange(); 2279 return true; 2280 } 2281 2282 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2283 // task is to insert the appropriate casts into the AST. First work out just 2284 // what the appropriate type is. 2285 QualType ValType = pointerType->getPointeeType(); 2286 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2287 if (IsLdrex) 2288 AddrType.addConst(); 2289 2290 // Issue a warning if the cast is dodgy. 2291 CastKind CastNeeded = CK_NoOp; 2292 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2293 CastNeeded = CK_BitCast; 2294 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2295 << PointerArg->getType() << Context.getPointerType(AddrType) 2296 << AA_Passing << PointerArg->getSourceRange(); 2297 } 2298 2299 // Finally, do the cast and replace the argument with the corrected version. 2300 AddrType = Context.getPointerType(AddrType); 2301 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2302 if (PointerArgRes.isInvalid()) 2303 return true; 2304 PointerArg = PointerArgRes.get(); 2305 2306 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2307 2308 // In general, we allow ints, floats and pointers to be loaded and stored. 2309 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2310 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2311 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2312 << PointerArg->getType() << PointerArg->getSourceRange(); 2313 return true; 2314 } 2315 2316 // But ARM doesn't have instructions to deal with 128-bit versions. 2317 if (Context.getTypeSize(ValType) > MaxWidth) { 2318 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2319 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2320 << PointerArg->getType() << PointerArg->getSourceRange(); 2321 return true; 2322 } 2323 2324 switch (ValType.getObjCLifetime()) { 2325 case Qualifiers::OCL_None: 2326 case Qualifiers::OCL_ExplicitNone: 2327 // okay 2328 break; 2329 2330 case Qualifiers::OCL_Weak: 2331 case Qualifiers::OCL_Strong: 2332 case Qualifiers::OCL_Autoreleasing: 2333 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2334 << ValType << PointerArg->getSourceRange(); 2335 return true; 2336 } 2337 2338 if (IsLdrex) { 2339 TheCall->setType(ValType); 2340 return false; 2341 } 2342 2343 // Initialize the argument to be stored. 2344 ExprResult ValArg = TheCall->getArg(0); 2345 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2346 Context, ValType, /*consume*/ false); 2347 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2348 if (ValArg.isInvalid()) 2349 return true; 2350 TheCall->setArg(0, ValArg.get()); 2351 2352 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2353 // but the custom checker bypasses all default analysis. 2354 TheCall->setType(Context.IntTy); 2355 return false; 2356 } 2357 2358 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2359 CallExpr *TheCall) { 2360 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2361 BuiltinID == ARM::BI__builtin_arm_ldaex || 2362 BuiltinID == ARM::BI__builtin_arm_strex || 2363 BuiltinID == ARM::BI__builtin_arm_stlex) { 2364 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2365 } 2366 2367 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2368 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2369 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2370 } 2371 2372 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2373 BuiltinID == ARM::BI__builtin_arm_wsr64) 2374 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2375 2376 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2377 BuiltinID == ARM::BI__builtin_arm_rsrp || 2378 BuiltinID == ARM::BI__builtin_arm_wsr || 2379 BuiltinID == ARM::BI__builtin_arm_wsrp) 2380 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2381 2382 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2383 return true; 2384 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2385 return true; 2386 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2387 return true; 2388 2389 // For intrinsics which take an immediate value as part of the instruction, 2390 // range check them here. 2391 // FIXME: VFP Intrinsics should error if VFP not present. 2392 switch (BuiltinID) { 2393 default: return false; 2394 case ARM::BI__builtin_arm_ssat: 2395 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2396 case ARM::BI__builtin_arm_usat: 2397 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2398 case ARM::BI__builtin_arm_ssat16: 2399 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2400 case ARM::BI__builtin_arm_usat16: 2401 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2402 case ARM::BI__builtin_arm_vcvtr_f: 2403 case ARM::BI__builtin_arm_vcvtr_d: 2404 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2405 case ARM::BI__builtin_arm_dmb: 2406 case ARM::BI__builtin_arm_dsb: 2407 case ARM::BI__builtin_arm_isb: 2408 case ARM::BI__builtin_arm_dbg: 2409 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2410 case ARM::BI__builtin_arm_cdp: 2411 case ARM::BI__builtin_arm_cdp2: 2412 case ARM::BI__builtin_arm_mcr: 2413 case ARM::BI__builtin_arm_mcr2: 2414 case ARM::BI__builtin_arm_mrc: 2415 case ARM::BI__builtin_arm_mrc2: 2416 case ARM::BI__builtin_arm_mcrr: 2417 case ARM::BI__builtin_arm_mcrr2: 2418 case ARM::BI__builtin_arm_mrrc: 2419 case ARM::BI__builtin_arm_mrrc2: 2420 case ARM::BI__builtin_arm_ldc: 2421 case ARM::BI__builtin_arm_ldcl: 2422 case ARM::BI__builtin_arm_ldc2: 2423 case ARM::BI__builtin_arm_ldc2l: 2424 case ARM::BI__builtin_arm_stc: 2425 case ARM::BI__builtin_arm_stcl: 2426 case ARM::BI__builtin_arm_stc2: 2427 case ARM::BI__builtin_arm_stc2l: 2428 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2429 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2430 /*WantCDE*/ false); 2431 } 2432 } 2433 2434 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2435 unsigned BuiltinID, 2436 CallExpr *TheCall) { 2437 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2438 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2439 BuiltinID == AArch64::BI__builtin_arm_strex || 2440 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2441 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2442 } 2443 2444 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2445 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2446 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2447 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2448 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2449 } 2450 2451 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2452 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2453 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2454 2455 // Memory Tagging Extensions (MTE) Intrinsics 2456 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2457 BuiltinID == AArch64::BI__builtin_arm_addg || 2458 BuiltinID == AArch64::BI__builtin_arm_gmi || 2459 BuiltinID == AArch64::BI__builtin_arm_ldg || 2460 BuiltinID == AArch64::BI__builtin_arm_stg || 2461 BuiltinID == AArch64::BI__builtin_arm_subp) { 2462 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2463 } 2464 2465 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2466 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2467 BuiltinID == AArch64::BI__builtin_arm_wsr || 2468 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2469 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2470 2471 // Only check the valid encoding range. Any constant in this range would be 2472 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2473 // an exception for incorrect registers. This matches MSVC behavior. 2474 if (BuiltinID == AArch64::BI_ReadStatusReg || 2475 BuiltinID == AArch64::BI_WriteStatusReg) 2476 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2477 2478 if (BuiltinID == AArch64::BI__getReg) 2479 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2480 2481 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2482 return true; 2483 2484 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2485 return true; 2486 2487 // For intrinsics which take an immediate value as part of the instruction, 2488 // range check them here. 2489 unsigned i = 0, l = 0, u = 0; 2490 switch (BuiltinID) { 2491 default: return false; 2492 case AArch64::BI__builtin_arm_dmb: 2493 case AArch64::BI__builtin_arm_dsb: 2494 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2495 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2496 } 2497 2498 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2499 } 2500 2501 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2502 CallExpr *TheCall) { 2503 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2504 BuiltinID == BPF::BI__builtin_btf_type_id) && 2505 "unexpected ARM builtin"); 2506 2507 if (checkArgCount(*this, TheCall, 2)) 2508 return true; 2509 2510 Expr *Arg; 2511 if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2512 // The second argument needs to be a constant int 2513 llvm::APSInt Value; 2514 Arg = TheCall->getArg(1); 2515 if (!Arg->isIntegerConstantExpr(Value, Context)) { 2516 Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const) 2517 << 2 << Arg->getSourceRange(); 2518 return true; 2519 } 2520 2521 TheCall->setType(Context.UnsignedIntTy); 2522 return false; 2523 } 2524 2525 // The first argument needs to be a record field access. 2526 // If it is an array element access, we delay decision 2527 // to BPF backend to check whether the access is a 2528 // field access or not. 2529 Arg = TheCall->getArg(0); 2530 if (Arg->getType()->getAsPlaceholderType() || 2531 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2532 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2533 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2534 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2535 << 1 << Arg->getSourceRange(); 2536 return true; 2537 } 2538 2539 // The second argument needs to be a constant int 2540 Arg = TheCall->getArg(1); 2541 llvm::APSInt Value; 2542 if (!Arg->isIntegerConstantExpr(Value, Context)) { 2543 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2544 << 2 << Arg->getSourceRange(); 2545 return true; 2546 } 2547 2548 TheCall->setType(Context.UnsignedIntTy); 2549 return false; 2550 } 2551 2552 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2553 struct ArgInfo { 2554 uint8_t OpNum; 2555 bool IsSigned; 2556 uint8_t BitWidth; 2557 uint8_t Align; 2558 }; 2559 struct BuiltinInfo { 2560 unsigned BuiltinID; 2561 ArgInfo Infos[2]; 2562 }; 2563 2564 static BuiltinInfo Infos[] = { 2565 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2566 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2567 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2568 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2569 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2570 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2571 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2572 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2573 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2574 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2575 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2576 2577 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2578 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2579 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2580 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2581 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2582 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2583 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2584 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2585 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2586 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2587 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2588 2589 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2590 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2591 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2592 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2593 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2594 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2595 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2596 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2597 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2598 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2599 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2600 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2601 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2602 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2603 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2604 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2605 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2606 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2607 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2608 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2609 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2610 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2611 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2612 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2613 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2614 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2615 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2616 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2617 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2618 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2619 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2620 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2621 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2622 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2623 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2624 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2625 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2626 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2627 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2628 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2629 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2630 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2631 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2632 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2633 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2634 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2635 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2636 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2637 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2639 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2641 {{ 1, false, 6, 0 }} }, 2642 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2645 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2646 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2648 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2649 {{ 1, false, 5, 0 }} }, 2650 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2652 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2653 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2656 { 2, false, 5, 0 }} }, 2657 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2658 { 2, false, 6, 0 }} }, 2659 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2660 { 3, false, 5, 0 }} }, 2661 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2662 { 3, false, 6, 0 }} }, 2663 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2668 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2670 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2672 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2673 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2675 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2676 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2679 {{ 2, false, 4, 0 }, 2680 { 3, false, 5, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2682 {{ 2, false, 4, 0 }, 2683 { 3, false, 5, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2685 {{ 2, false, 4, 0 }, 2686 { 3, false, 5, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2688 {{ 2, false, 4, 0 }, 2689 { 3, false, 5, 0 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2697 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2698 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2701 { 2, false, 5, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2703 { 2, false, 6, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2706 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2709 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2713 {{ 1, false, 4, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2715 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2716 {{ 1, false, 4, 0 }} }, 2717 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2718 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2719 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2720 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2721 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2722 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2724 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2725 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2727 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2728 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2730 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2731 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2732 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2733 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2737 {{ 3, false, 1, 0 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2739 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2742 {{ 3, false, 1, 0 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2745 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2747 {{ 3, false, 1, 0 }} }, 2748 }; 2749 2750 // Use a dynamically initialized static to sort the table exactly once on 2751 // first run. 2752 static const bool SortOnce = 2753 (llvm::sort(Infos, 2754 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2755 return LHS.BuiltinID < RHS.BuiltinID; 2756 }), 2757 true); 2758 (void)SortOnce; 2759 2760 const BuiltinInfo *F = llvm::partition_point( 2761 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2762 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2763 return false; 2764 2765 bool Error = false; 2766 2767 for (const ArgInfo &A : F->Infos) { 2768 // Ignore empty ArgInfo elements. 2769 if (A.BitWidth == 0) 2770 continue; 2771 2772 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2773 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2774 if (!A.Align) { 2775 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2776 } else { 2777 unsigned M = 1 << A.Align; 2778 Min *= M; 2779 Max *= M; 2780 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2781 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2782 } 2783 } 2784 return Error; 2785 } 2786 2787 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2788 CallExpr *TheCall) { 2789 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2790 } 2791 2792 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2793 unsigned BuiltinID, CallExpr *TheCall) { 2794 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2795 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2796 } 2797 2798 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2799 CallExpr *TheCall) { 2800 2801 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2802 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2803 if (!TI.hasFeature("dsp")) 2804 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2805 } 2806 2807 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2808 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2809 if (!TI.hasFeature("dspr2")) 2810 return Diag(TheCall->getBeginLoc(), 2811 diag::err_mips_builtin_requires_dspr2); 2812 } 2813 2814 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2815 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2816 if (!TI.hasFeature("msa")) 2817 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2818 } 2819 2820 return false; 2821 } 2822 2823 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2824 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2825 // ordering for DSP is unspecified. MSA is ordered by the data format used 2826 // by the underlying instruction i.e., df/m, df/n and then by size. 2827 // 2828 // FIXME: The size tests here should instead be tablegen'd along with the 2829 // definitions from include/clang/Basic/BuiltinsMips.def. 2830 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2831 // be too. 2832 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2833 unsigned i = 0, l = 0, u = 0, m = 0; 2834 switch (BuiltinID) { 2835 default: return false; 2836 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2837 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2838 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2839 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2840 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2841 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2842 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2843 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2844 // df/m field. 2845 // These intrinsics take an unsigned 3 bit immediate. 2846 case Mips::BI__builtin_msa_bclri_b: 2847 case Mips::BI__builtin_msa_bnegi_b: 2848 case Mips::BI__builtin_msa_bseti_b: 2849 case Mips::BI__builtin_msa_sat_s_b: 2850 case Mips::BI__builtin_msa_sat_u_b: 2851 case Mips::BI__builtin_msa_slli_b: 2852 case Mips::BI__builtin_msa_srai_b: 2853 case Mips::BI__builtin_msa_srari_b: 2854 case Mips::BI__builtin_msa_srli_b: 2855 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2856 case Mips::BI__builtin_msa_binsli_b: 2857 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2858 // These intrinsics take an unsigned 4 bit immediate. 2859 case Mips::BI__builtin_msa_bclri_h: 2860 case Mips::BI__builtin_msa_bnegi_h: 2861 case Mips::BI__builtin_msa_bseti_h: 2862 case Mips::BI__builtin_msa_sat_s_h: 2863 case Mips::BI__builtin_msa_sat_u_h: 2864 case Mips::BI__builtin_msa_slli_h: 2865 case Mips::BI__builtin_msa_srai_h: 2866 case Mips::BI__builtin_msa_srari_h: 2867 case Mips::BI__builtin_msa_srli_h: 2868 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2869 case Mips::BI__builtin_msa_binsli_h: 2870 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2871 // These intrinsics take an unsigned 5 bit immediate. 2872 // The first block of intrinsics actually have an unsigned 5 bit field, 2873 // not a df/n field. 2874 case Mips::BI__builtin_msa_cfcmsa: 2875 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 2876 case Mips::BI__builtin_msa_clei_u_b: 2877 case Mips::BI__builtin_msa_clei_u_h: 2878 case Mips::BI__builtin_msa_clei_u_w: 2879 case Mips::BI__builtin_msa_clei_u_d: 2880 case Mips::BI__builtin_msa_clti_u_b: 2881 case Mips::BI__builtin_msa_clti_u_h: 2882 case Mips::BI__builtin_msa_clti_u_w: 2883 case Mips::BI__builtin_msa_clti_u_d: 2884 case Mips::BI__builtin_msa_maxi_u_b: 2885 case Mips::BI__builtin_msa_maxi_u_h: 2886 case Mips::BI__builtin_msa_maxi_u_w: 2887 case Mips::BI__builtin_msa_maxi_u_d: 2888 case Mips::BI__builtin_msa_mini_u_b: 2889 case Mips::BI__builtin_msa_mini_u_h: 2890 case Mips::BI__builtin_msa_mini_u_w: 2891 case Mips::BI__builtin_msa_mini_u_d: 2892 case Mips::BI__builtin_msa_addvi_b: 2893 case Mips::BI__builtin_msa_addvi_h: 2894 case Mips::BI__builtin_msa_addvi_w: 2895 case Mips::BI__builtin_msa_addvi_d: 2896 case Mips::BI__builtin_msa_bclri_w: 2897 case Mips::BI__builtin_msa_bnegi_w: 2898 case Mips::BI__builtin_msa_bseti_w: 2899 case Mips::BI__builtin_msa_sat_s_w: 2900 case Mips::BI__builtin_msa_sat_u_w: 2901 case Mips::BI__builtin_msa_slli_w: 2902 case Mips::BI__builtin_msa_srai_w: 2903 case Mips::BI__builtin_msa_srari_w: 2904 case Mips::BI__builtin_msa_srli_w: 2905 case Mips::BI__builtin_msa_srlri_w: 2906 case Mips::BI__builtin_msa_subvi_b: 2907 case Mips::BI__builtin_msa_subvi_h: 2908 case Mips::BI__builtin_msa_subvi_w: 2909 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2910 case Mips::BI__builtin_msa_binsli_w: 2911 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2912 // These intrinsics take an unsigned 6 bit immediate. 2913 case Mips::BI__builtin_msa_bclri_d: 2914 case Mips::BI__builtin_msa_bnegi_d: 2915 case Mips::BI__builtin_msa_bseti_d: 2916 case Mips::BI__builtin_msa_sat_s_d: 2917 case Mips::BI__builtin_msa_sat_u_d: 2918 case Mips::BI__builtin_msa_slli_d: 2919 case Mips::BI__builtin_msa_srai_d: 2920 case Mips::BI__builtin_msa_srari_d: 2921 case Mips::BI__builtin_msa_srli_d: 2922 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2923 case Mips::BI__builtin_msa_binsli_d: 2924 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2925 // These intrinsics take a signed 5 bit immediate. 2926 case Mips::BI__builtin_msa_ceqi_b: 2927 case Mips::BI__builtin_msa_ceqi_h: 2928 case Mips::BI__builtin_msa_ceqi_w: 2929 case Mips::BI__builtin_msa_ceqi_d: 2930 case Mips::BI__builtin_msa_clti_s_b: 2931 case Mips::BI__builtin_msa_clti_s_h: 2932 case Mips::BI__builtin_msa_clti_s_w: 2933 case Mips::BI__builtin_msa_clti_s_d: 2934 case Mips::BI__builtin_msa_clei_s_b: 2935 case Mips::BI__builtin_msa_clei_s_h: 2936 case Mips::BI__builtin_msa_clei_s_w: 2937 case Mips::BI__builtin_msa_clei_s_d: 2938 case Mips::BI__builtin_msa_maxi_s_b: 2939 case Mips::BI__builtin_msa_maxi_s_h: 2940 case Mips::BI__builtin_msa_maxi_s_w: 2941 case Mips::BI__builtin_msa_maxi_s_d: 2942 case Mips::BI__builtin_msa_mini_s_b: 2943 case Mips::BI__builtin_msa_mini_s_h: 2944 case Mips::BI__builtin_msa_mini_s_w: 2945 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2946 // These intrinsics take an unsigned 8 bit immediate. 2947 case Mips::BI__builtin_msa_andi_b: 2948 case Mips::BI__builtin_msa_nori_b: 2949 case Mips::BI__builtin_msa_ori_b: 2950 case Mips::BI__builtin_msa_shf_b: 2951 case Mips::BI__builtin_msa_shf_h: 2952 case Mips::BI__builtin_msa_shf_w: 2953 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2954 case Mips::BI__builtin_msa_bseli_b: 2955 case Mips::BI__builtin_msa_bmnzi_b: 2956 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2957 // df/n format 2958 // These intrinsics take an unsigned 4 bit immediate. 2959 case Mips::BI__builtin_msa_copy_s_b: 2960 case Mips::BI__builtin_msa_copy_u_b: 2961 case Mips::BI__builtin_msa_insve_b: 2962 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2963 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2964 // These intrinsics take an unsigned 3 bit immediate. 2965 case Mips::BI__builtin_msa_copy_s_h: 2966 case Mips::BI__builtin_msa_copy_u_h: 2967 case Mips::BI__builtin_msa_insve_h: 2968 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2969 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2970 // These intrinsics take an unsigned 2 bit immediate. 2971 case Mips::BI__builtin_msa_copy_s_w: 2972 case Mips::BI__builtin_msa_copy_u_w: 2973 case Mips::BI__builtin_msa_insve_w: 2974 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2975 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2976 // These intrinsics take an unsigned 1 bit immediate. 2977 case Mips::BI__builtin_msa_copy_s_d: 2978 case Mips::BI__builtin_msa_copy_u_d: 2979 case Mips::BI__builtin_msa_insve_d: 2980 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2981 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2982 // Memory offsets and immediate loads. 2983 // These intrinsics take a signed 10 bit immediate. 2984 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2985 case Mips::BI__builtin_msa_ldi_h: 2986 case Mips::BI__builtin_msa_ldi_w: 2987 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2988 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 2989 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 2990 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 2991 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 2992 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 2993 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 2994 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 2995 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 2996 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 2997 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 2998 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 2999 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3000 } 3001 3002 if (!m) 3003 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3004 3005 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3006 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3007 } 3008 3009 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3010 CallExpr *TheCall) { 3011 unsigned i = 0, l = 0, u = 0; 3012 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3013 BuiltinID == PPC::BI__builtin_divdeu || 3014 BuiltinID == PPC::BI__builtin_bpermd; 3015 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3016 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3017 BuiltinID == PPC::BI__builtin_divweu || 3018 BuiltinID == PPC::BI__builtin_divde || 3019 BuiltinID == PPC::BI__builtin_divdeu; 3020 3021 if (Is64BitBltin && !IsTarget64Bit) 3022 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3023 << TheCall->getSourceRange(); 3024 3025 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3026 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3027 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3028 << TheCall->getSourceRange(); 3029 3030 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3031 if (!TI.hasFeature("vsx")) 3032 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3033 << TheCall->getSourceRange(); 3034 return false; 3035 }; 3036 3037 switch (BuiltinID) { 3038 default: return false; 3039 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3040 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3041 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3042 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3043 case PPC::BI__builtin_altivec_dss: 3044 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3045 case PPC::BI__builtin_tbegin: 3046 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3047 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3048 case PPC::BI__builtin_tabortwc: 3049 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3050 case PPC::BI__builtin_tabortwci: 3051 case PPC::BI__builtin_tabortdci: 3052 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3053 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3054 case PPC::BI__builtin_altivec_dst: 3055 case PPC::BI__builtin_altivec_dstt: 3056 case PPC::BI__builtin_altivec_dstst: 3057 case PPC::BI__builtin_altivec_dststt: 3058 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3059 case PPC::BI__builtin_vsx_xxpermdi: 3060 case PPC::BI__builtin_vsx_xxsldwi: 3061 return SemaBuiltinVSX(TheCall); 3062 case PPC::BI__builtin_unpack_vector_int128: 3063 return SemaVSXCheck(TheCall) || 3064 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3065 case PPC::BI__builtin_pack_vector_int128: 3066 return SemaVSXCheck(TheCall); 3067 } 3068 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3069 } 3070 3071 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3072 CallExpr *TheCall) { 3073 // position of memory order and scope arguments in the builtin 3074 unsigned OrderIndex, ScopeIndex; 3075 switch (BuiltinID) { 3076 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3077 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3078 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3079 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3080 OrderIndex = 2; 3081 ScopeIndex = 3; 3082 break; 3083 case AMDGPU::BI__builtin_amdgcn_fence: 3084 OrderIndex = 0; 3085 ScopeIndex = 1; 3086 break; 3087 default: 3088 return false; 3089 } 3090 3091 ExprResult Arg = TheCall->getArg(OrderIndex); 3092 auto ArgExpr = Arg.get(); 3093 Expr::EvalResult ArgResult; 3094 3095 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3096 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3097 << ArgExpr->getType(); 3098 int ord = ArgResult.Val.getInt().getZExtValue(); 3099 3100 // Check valididty of memory ordering as per C11 / C++11's memody model. 3101 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3102 case llvm::AtomicOrderingCABI::acquire: 3103 case llvm::AtomicOrderingCABI::release: 3104 case llvm::AtomicOrderingCABI::acq_rel: 3105 case llvm::AtomicOrderingCABI::seq_cst: 3106 break; 3107 default: { 3108 return Diag(ArgExpr->getBeginLoc(), 3109 diag::warn_atomic_op_has_invalid_memory_order) 3110 << ArgExpr->getSourceRange(); 3111 } 3112 } 3113 3114 Arg = TheCall->getArg(ScopeIndex); 3115 ArgExpr = Arg.get(); 3116 Expr::EvalResult ArgResult1; 3117 // Check that sync scope is a constant literal 3118 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen, 3119 Context)) 3120 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3121 << ArgExpr->getType(); 3122 3123 return false; 3124 } 3125 3126 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3127 CallExpr *TheCall) { 3128 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3129 Expr *Arg = TheCall->getArg(0); 3130 llvm::APSInt AbortCode(32); 3131 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3132 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3133 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3134 << Arg->getSourceRange(); 3135 } 3136 3137 // For intrinsics which take an immediate value as part of the instruction, 3138 // range check them here. 3139 unsigned i = 0, l = 0, u = 0; 3140 switch (BuiltinID) { 3141 default: return false; 3142 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3143 case SystemZ::BI__builtin_s390_verimb: 3144 case SystemZ::BI__builtin_s390_verimh: 3145 case SystemZ::BI__builtin_s390_verimf: 3146 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3147 case SystemZ::BI__builtin_s390_vfaeb: 3148 case SystemZ::BI__builtin_s390_vfaeh: 3149 case SystemZ::BI__builtin_s390_vfaef: 3150 case SystemZ::BI__builtin_s390_vfaebs: 3151 case SystemZ::BI__builtin_s390_vfaehs: 3152 case SystemZ::BI__builtin_s390_vfaefs: 3153 case SystemZ::BI__builtin_s390_vfaezb: 3154 case SystemZ::BI__builtin_s390_vfaezh: 3155 case SystemZ::BI__builtin_s390_vfaezf: 3156 case SystemZ::BI__builtin_s390_vfaezbs: 3157 case SystemZ::BI__builtin_s390_vfaezhs: 3158 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3159 case SystemZ::BI__builtin_s390_vfisb: 3160 case SystemZ::BI__builtin_s390_vfidb: 3161 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3162 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3163 case SystemZ::BI__builtin_s390_vftcisb: 3164 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3165 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3166 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3167 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3168 case SystemZ::BI__builtin_s390_vstrcb: 3169 case SystemZ::BI__builtin_s390_vstrch: 3170 case SystemZ::BI__builtin_s390_vstrcf: 3171 case SystemZ::BI__builtin_s390_vstrczb: 3172 case SystemZ::BI__builtin_s390_vstrczh: 3173 case SystemZ::BI__builtin_s390_vstrczf: 3174 case SystemZ::BI__builtin_s390_vstrcbs: 3175 case SystemZ::BI__builtin_s390_vstrchs: 3176 case SystemZ::BI__builtin_s390_vstrcfs: 3177 case SystemZ::BI__builtin_s390_vstrczbs: 3178 case SystemZ::BI__builtin_s390_vstrczhs: 3179 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3180 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3181 case SystemZ::BI__builtin_s390_vfminsb: 3182 case SystemZ::BI__builtin_s390_vfmaxsb: 3183 case SystemZ::BI__builtin_s390_vfmindb: 3184 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3185 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3186 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3187 } 3188 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3189 } 3190 3191 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3192 /// This checks that the target supports __builtin_cpu_supports and 3193 /// that the string argument is constant and valid. 3194 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3195 CallExpr *TheCall) { 3196 Expr *Arg = TheCall->getArg(0); 3197 3198 // Check if the argument is a string literal. 3199 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3200 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3201 << Arg->getSourceRange(); 3202 3203 // Check the contents of the string. 3204 StringRef Feature = 3205 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3206 if (!TI.validateCpuSupports(Feature)) 3207 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3208 << Arg->getSourceRange(); 3209 return false; 3210 } 3211 3212 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3213 /// This checks that the target supports __builtin_cpu_is and 3214 /// that the string argument is constant and valid. 3215 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3216 Expr *Arg = TheCall->getArg(0); 3217 3218 // Check if the argument is a string literal. 3219 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3220 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3221 << Arg->getSourceRange(); 3222 3223 // Check the contents of the string. 3224 StringRef Feature = 3225 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3226 if (!TI.validateCpuIs(Feature)) 3227 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3228 << Arg->getSourceRange(); 3229 return false; 3230 } 3231 3232 // Check if the rounding mode is legal. 3233 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3234 // Indicates if this instruction has rounding control or just SAE. 3235 bool HasRC = false; 3236 3237 unsigned ArgNum = 0; 3238 switch (BuiltinID) { 3239 default: 3240 return false; 3241 case X86::BI__builtin_ia32_vcvttsd2si32: 3242 case X86::BI__builtin_ia32_vcvttsd2si64: 3243 case X86::BI__builtin_ia32_vcvttsd2usi32: 3244 case X86::BI__builtin_ia32_vcvttsd2usi64: 3245 case X86::BI__builtin_ia32_vcvttss2si32: 3246 case X86::BI__builtin_ia32_vcvttss2si64: 3247 case X86::BI__builtin_ia32_vcvttss2usi32: 3248 case X86::BI__builtin_ia32_vcvttss2usi64: 3249 ArgNum = 1; 3250 break; 3251 case X86::BI__builtin_ia32_maxpd512: 3252 case X86::BI__builtin_ia32_maxps512: 3253 case X86::BI__builtin_ia32_minpd512: 3254 case X86::BI__builtin_ia32_minps512: 3255 ArgNum = 2; 3256 break; 3257 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3258 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3259 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3260 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3261 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3262 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3263 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3264 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3265 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3266 case X86::BI__builtin_ia32_exp2pd_mask: 3267 case X86::BI__builtin_ia32_exp2ps_mask: 3268 case X86::BI__builtin_ia32_getexppd512_mask: 3269 case X86::BI__builtin_ia32_getexpps512_mask: 3270 case X86::BI__builtin_ia32_rcp28pd_mask: 3271 case X86::BI__builtin_ia32_rcp28ps_mask: 3272 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3273 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3274 case X86::BI__builtin_ia32_vcomisd: 3275 case X86::BI__builtin_ia32_vcomiss: 3276 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3277 ArgNum = 3; 3278 break; 3279 case X86::BI__builtin_ia32_cmppd512_mask: 3280 case X86::BI__builtin_ia32_cmpps512_mask: 3281 case X86::BI__builtin_ia32_cmpsd_mask: 3282 case X86::BI__builtin_ia32_cmpss_mask: 3283 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3284 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3285 case X86::BI__builtin_ia32_getexpss128_round_mask: 3286 case X86::BI__builtin_ia32_getmantpd512_mask: 3287 case X86::BI__builtin_ia32_getmantps512_mask: 3288 case X86::BI__builtin_ia32_maxsd_round_mask: 3289 case X86::BI__builtin_ia32_maxss_round_mask: 3290 case X86::BI__builtin_ia32_minsd_round_mask: 3291 case X86::BI__builtin_ia32_minss_round_mask: 3292 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3293 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3294 case X86::BI__builtin_ia32_reducepd512_mask: 3295 case X86::BI__builtin_ia32_reduceps512_mask: 3296 case X86::BI__builtin_ia32_rndscalepd_mask: 3297 case X86::BI__builtin_ia32_rndscaleps_mask: 3298 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3299 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3300 ArgNum = 4; 3301 break; 3302 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3303 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3304 case X86::BI__builtin_ia32_fixupimmps512_mask: 3305 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3306 case X86::BI__builtin_ia32_fixupimmsd_mask: 3307 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3308 case X86::BI__builtin_ia32_fixupimmss_mask: 3309 case X86::BI__builtin_ia32_fixupimmss_maskz: 3310 case X86::BI__builtin_ia32_getmantsd_round_mask: 3311 case X86::BI__builtin_ia32_getmantss_round_mask: 3312 case X86::BI__builtin_ia32_rangepd512_mask: 3313 case X86::BI__builtin_ia32_rangeps512_mask: 3314 case X86::BI__builtin_ia32_rangesd128_round_mask: 3315 case X86::BI__builtin_ia32_rangess128_round_mask: 3316 case X86::BI__builtin_ia32_reducesd_mask: 3317 case X86::BI__builtin_ia32_reducess_mask: 3318 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3319 case X86::BI__builtin_ia32_rndscaless_round_mask: 3320 ArgNum = 5; 3321 break; 3322 case X86::BI__builtin_ia32_vcvtsd2si64: 3323 case X86::BI__builtin_ia32_vcvtsd2si32: 3324 case X86::BI__builtin_ia32_vcvtsd2usi32: 3325 case X86::BI__builtin_ia32_vcvtsd2usi64: 3326 case X86::BI__builtin_ia32_vcvtss2si32: 3327 case X86::BI__builtin_ia32_vcvtss2si64: 3328 case X86::BI__builtin_ia32_vcvtss2usi32: 3329 case X86::BI__builtin_ia32_vcvtss2usi64: 3330 case X86::BI__builtin_ia32_sqrtpd512: 3331 case X86::BI__builtin_ia32_sqrtps512: 3332 ArgNum = 1; 3333 HasRC = true; 3334 break; 3335 case X86::BI__builtin_ia32_addpd512: 3336 case X86::BI__builtin_ia32_addps512: 3337 case X86::BI__builtin_ia32_divpd512: 3338 case X86::BI__builtin_ia32_divps512: 3339 case X86::BI__builtin_ia32_mulpd512: 3340 case X86::BI__builtin_ia32_mulps512: 3341 case X86::BI__builtin_ia32_subpd512: 3342 case X86::BI__builtin_ia32_subps512: 3343 case X86::BI__builtin_ia32_cvtsi2sd64: 3344 case X86::BI__builtin_ia32_cvtsi2ss32: 3345 case X86::BI__builtin_ia32_cvtsi2ss64: 3346 case X86::BI__builtin_ia32_cvtusi2sd64: 3347 case X86::BI__builtin_ia32_cvtusi2ss32: 3348 case X86::BI__builtin_ia32_cvtusi2ss64: 3349 ArgNum = 2; 3350 HasRC = true; 3351 break; 3352 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3353 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3354 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3355 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3356 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3357 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3358 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3359 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3360 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3361 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3362 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3363 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3364 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3365 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3366 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3367 ArgNum = 3; 3368 HasRC = true; 3369 break; 3370 case X86::BI__builtin_ia32_addss_round_mask: 3371 case X86::BI__builtin_ia32_addsd_round_mask: 3372 case X86::BI__builtin_ia32_divss_round_mask: 3373 case X86::BI__builtin_ia32_divsd_round_mask: 3374 case X86::BI__builtin_ia32_mulss_round_mask: 3375 case X86::BI__builtin_ia32_mulsd_round_mask: 3376 case X86::BI__builtin_ia32_subss_round_mask: 3377 case X86::BI__builtin_ia32_subsd_round_mask: 3378 case X86::BI__builtin_ia32_scalefpd512_mask: 3379 case X86::BI__builtin_ia32_scalefps512_mask: 3380 case X86::BI__builtin_ia32_scalefsd_round_mask: 3381 case X86::BI__builtin_ia32_scalefss_round_mask: 3382 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3383 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3384 case X86::BI__builtin_ia32_sqrtss_round_mask: 3385 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3386 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3387 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3388 case X86::BI__builtin_ia32_vfmaddss3_mask: 3389 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3390 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3391 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3392 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3393 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3394 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3395 case X86::BI__builtin_ia32_vfmaddps512_mask: 3396 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3397 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3398 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3399 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3400 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3401 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3402 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3403 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3404 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3405 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3406 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3407 ArgNum = 4; 3408 HasRC = true; 3409 break; 3410 } 3411 3412 llvm::APSInt Result; 3413 3414 // We can't check the value of a dependent argument. 3415 Expr *Arg = TheCall->getArg(ArgNum); 3416 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3417 return false; 3418 3419 // Check constant-ness first. 3420 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3421 return true; 3422 3423 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3424 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3425 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3426 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3427 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3428 Result == 8/*ROUND_NO_EXC*/ || 3429 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3430 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3431 return false; 3432 3433 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3434 << Arg->getSourceRange(); 3435 } 3436 3437 // Check if the gather/scatter scale is legal. 3438 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3439 CallExpr *TheCall) { 3440 unsigned ArgNum = 0; 3441 switch (BuiltinID) { 3442 default: 3443 return false; 3444 case X86::BI__builtin_ia32_gatherpfdpd: 3445 case X86::BI__builtin_ia32_gatherpfdps: 3446 case X86::BI__builtin_ia32_gatherpfqpd: 3447 case X86::BI__builtin_ia32_gatherpfqps: 3448 case X86::BI__builtin_ia32_scatterpfdpd: 3449 case X86::BI__builtin_ia32_scatterpfdps: 3450 case X86::BI__builtin_ia32_scatterpfqpd: 3451 case X86::BI__builtin_ia32_scatterpfqps: 3452 ArgNum = 3; 3453 break; 3454 case X86::BI__builtin_ia32_gatherd_pd: 3455 case X86::BI__builtin_ia32_gatherd_pd256: 3456 case X86::BI__builtin_ia32_gatherq_pd: 3457 case X86::BI__builtin_ia32_gatherq_pd256: 3458 case X86::BI__builtin_ia32_gatherd_ps: 3459 case X86::BI__builtin_ia32_gatherd_ps256: 3460 case X86::BI__builtin_ia32_gatherq_ps: 3461 case X86::BI__builtin_ia32_gatherq_ps256: 3462 case X86::BI__builtin_ia32_gatherd_q: 3463 case X86::BI__builtin_ia32_gatherd_q256: 3464 case X86::BI__builtin_ia32_gatherq_q: 3465 case X86::BI__builtin_ia32_gatherq_q256: 3466 case X86::BI__builtin_ia32_gatherd_d: 3467 case X86::BI__builtin_ia32_gatherd_d256: 3468 case X86::BI__builtin_ia32_gatherq_d: 3469 case X86::BI__builtin_ia32_gatherq_d256: 3470 case X86::BI__builtin_ia32_gather3div2df: 3471 case X86::BI__builtin_ia32_gather3div2di: 3472 case X86::BI__builtin_ia32_gather3div4df: 3473 case X86::BI__builtin_ia32_gather3div4di: 3474 case X86::BI__builtin_ia32_gather3div4sf: 3475 case X86::BI__builtin_ia32_gather3div4si: 3476 case X86::BI__builtin_ia32_gather3div8sf: 3477 case X86::BI__builtin_ia32_gather3div8si: 3478 case X86::BI__builtin_ia32_gather3siv2df: 3479 case X86::BI__builtin_ia32_gather3siv2di: 3480 case X86::BI__builtin_ia32_gather3siv4df: 3481 case X86::BI__builtin_ia32_gather3siv4di: 3482 case X86::BI__builtin_ia32_gather3siv4sf: 3483 case X86::BI__builtin_ia32_gather3siv4si: 3484 case X86::BI__builtin_ia32_gather3siv8sf: 3485 case X86::BI__builtin_ia32_gather3siv8si: 3486 case X86::BI__builtin_ia32_gathersiv8df: 3487 case X86::BI__builtin_ia32_gathersiv16sf: 3488 case X86::BI__builtin_ia32_gatherdiv8df: 3489 case X86::BI__builtin_ia32_gatherdiv16sf: 3490 case X86::BI__builtin_ia32_gathersiv8di: 3491 case X86::BI__builtin_ia32_gathersiv16si: 3492 case X86::BI__builtin_ia32_gatherdiv8di: 3493 case X86::BI__builtin_ia32_gatherdiv16si: 3494 case X86::BI__builtin_ia32_scatterdiv2df: 3495 case X86::BI__builtin_ia32_scatterdiv2di: 3496 case X86::BI__builtin_ia32_scatterdiv4df: 3497 case X86::BI__builtin_ia32_scatterdiv4di: 3498 case X86::BI__builtin_ia32_scatterdiv4sf: 3499 case X86::BI__builtin_ia32_scatterdiv4si: 3500 case X86::BI__builtin_ia32_scatterdiv8sf: 3501 case X86::BI__builtin_ia32_scatterdiv8si: 3502 case X86::BI__builtin_ia32_scattersiv2df: 3503 case X86::BI__builtin_ia32_scattersiv2di: 3504 case X86::BI__builtin_ia32_scattersiv4df: 3505 case X86::BI__builtin_ia32_scattersiv4di: 3506 case X86::BI__builtin_ia32_scattersiv4sf: 3507 case X86::BI__builtin_ia32_scattersiv4si: 3508 case X86::BI__builtin_ia32_scattersiv8sf: 3509 case X86::BI__builtin_ia32_scattersiv8si: 3510 case X86::BI__builtin_ia32_scattersiv8df: 3511 case X86::BI__builtin_ia32_scattersiv16sf: 3512 case X86::BI__builtin_ia32_scatterdiv8df: 3513 case X86::BI__builtin_ia32_scatterdiv16sf: 3514 case X86::BI__builtin_ia32_scattersiv8di: 3515 case X86::BI__builtin_ia32_scattersiv16si: 3516 case X86::BI__builtin_ia32_scatterdiv8di: 3517 case X86::BI__builtin_ia32_scatterdiv16si: 3518 ArgNum = 4; 3519 break; 3520 } 3521 3522 llvm::APSInt Result; 3523 3524 // We can't check the value of a dependent argument. 3525 Expr *Arg = TheCall->getArg(ArgNum); 3526 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3527 return false; 3528 3529 // Check constant-ness first. 3530 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3531 return true; 3532 3533 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3534 return false; 3535 3536 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3537 << Arg->getSourceRange(); 3538 } 3539 3540 static bool isX86_32Builtin(unsigned BuiltinID) { 3541 // These builtins only work on x86-32 targets. 3542 switch (BuiltinID) { 3543 case X86::BI__builtin_ia32_readeflags_u32: 3544 case X86::BI__builtin_ia32_writeeflags_u32: 3545 return true; 3546 } 3547 3548 return false; 3549 } 3550 3551 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3552 CallExpr *TheCall) { 3553 if (BuiltinID == X86::BI__builtin_cpu_supports) 3554 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3555 3556 if (BuiltinID == X86::BI__builtin_cpu_is) 3557 return SemaBuiltinCpuIs(*this, TI, TheCall); 3558 3559 // Check for 32-bit only builtins on a 64-bit target. 3560 const llvm::Triple &TT = TI.getTriple(); 3561 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3562 return Diag(TheCall->getCallee()->getBeginLoc(), 3563 diag::err_32_bit_builtin_64_bit_tgt); 3564 3565 // If the intrinsic has rounding or SAE make sure its valid. 3566 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3567 return true; 3568 3569 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3570 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3571 return true; 3572 3573 // For intrinsics which take an immediate value as part of the instruction, 3574 // range check them here. 3575 int i = 0, l = 0, u = 0; 3576 switch (BuiltinID) { 3577 default: 3578 return false; 3579 case X86::BI__builtin_ia32_vec_ext_v2si: 3580 case X86::BI__builtin_ia32_vec_ext_v2di: 3581 case X86::BI__builtin_ia32_vextractf128_pd256: 3582 case X86::BI__builtin_ia32_vextractf128_ps256: 3583 case X86::BI__builtin_ia32_vextractf128_si256: 3584 case X86::BI__builtin_ia32_extract128i256: 3585 case X86::BI__builtin_ia32_extractf64x4_mask: 3586 case X86::BI__builtin_ia32_extracti64x4_mask: 3587 case X86::BI__builtin_ia32_extractf32x8_mask: 3588 case X86::BI__builtin_ia32_extracti32x8_mask: 3589 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3590 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3591 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3592 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3593 i = 1; l = 0; u = 1; 3594 break; 3595 case X86::BI__builtin_ia32_vec_set_v2di: 3596 case X86::BI__builtin_ia32_vinsertf128_pd256: 3597 case X86::BI__builtin_ia32_vinsertf128_ps256: 3598 case X86::BI__builtin_ia32_vinsertf128_si256: 3599 case X86::BI__builtin_ia32_insert128i256: 3600 case X86::BI__builtin_ia32_insertf32x8: 3601 case X86::BI__builtin_ia32_inserti32x8: 3602 case X86::BI__builtin_ia32_insertf64x4: 3603 case X86::BI__builtin_ia32_inserti64x4: 3604 case X86::BI__builtin_ia32_insertf64x2_256: 3605 case X86::BI__builtin_ia32_inserti64x2_256: 3606 case X86::BI__builtin_ia32_insertf32x4_256: 3607 case X86::BI__builtin_ia32_inserti32x4_256: 3608 i = 2; l = 0; u = 1; 3609 break; 3610 case X86::BI__builtin_ia32_vpermilpd: 3611 case X86::BI__builtin_ia32_vec_ext_v4hi: 3612 case X86::BI__builtin_ia32_vec_ext_v4si: 3613 case X86::BI__builtin_ia32_vec_ext_v4sf: 3614 case X86::BI__builtin_ia32_vec_ext_v4di: 3615 case X86::BI__builtin_ia32_extractf32x4_mask: 3616 case X86::BI__builtin_ia32_extracti32x4_mask: 3617 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3618 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3619 i = 1; l = 0; u = 3; 3620 break; 3621 case X86::BI_mm_prefetch: 3622 case X86::BI__builtin_ia32_vec_ext_v8hi: 3623 case X86::BI__builtin_ia32_vec_ext_v8si: 3624 i = 1; l = 0; u = 7; 3625 break; 3626 case X86::BI__builtin_ia32_sha1rnds4: 3627 case X86::BI__builtin_ia32_blendpd: 3628 case X86::BI__builtin_ia32_shufpd: 3629 case X86::BI__builtin_ia32_vec_set_v4hi: 3630 case X86::BI__builtin_ia32_vec_set_v4si: 3631 case X86::BI__builtin_ia32_vec_set_v4di: 3632 case X86::BI__builtin_ia32_shuf_f32x4_256: 3633 case X86::BI__builtin_ia32_shuf_f64x2_256: 3634 case X86::BI__builtin_ia32_shuf_i32x4_256: 3635 case X86::BI__builtin_ia32_shuf_i64x2_256: 3636 case X86::BI__builtin_ia32_insertf64x2_512: 3637 case X86::BI__builtin_ia32_inserti64x2_512: 3638 case X86::BI__builtin_ia32_insertf32x4: 3639 case X86::BI__builtin_ia32_inserti32x4: 3640 i = 2; l = 0; u = 3; 3641 break; 3642 case X86::BI__builtin_ia32_vpermil2pd: 3643 case X86::BI__builtin_ia32_vpermil2pd256: 3644 case X86::BI__builtin_ia32_vpermil2ps: 3645 case X86::BI__builtin_ia32_vpermil2ps256: 3646 i = 3; l = 0; u = 3; 3647 break; 3648 case X86::BI__builtin_ia32_cmpb128_mask: 3649 case X86::BI__builtin_ia32_cmpw128_mask: 3650 case X86::BI__builtin_ia32_cmpd128_mask: 3651 case X86::BI__builtin_ia32_cmpq128_mask: 3652 case X86::BI__builtin_ia32_cmpb256_mask: 3653 case X86::BI__builtin_ia32_cmpw256_mask: 3654 case X86::BI__builtin_ia32_cmpd256_mask: 3655 case X86::BI__builtin_ia32_cmpq256_mask: 3656 case X86::BI__builtin_ia32_cmpb512_mask: 3657 case X86::BI__builtin_ia32_cmpw512_mask: 3658 case X86::BI__builtin_ia32_cmpd512_mask: 3659 case X86::BI__builtin_ia32_cmpq512_mask: 3660 case X86::BI__builtin_ia32_ucmpb128_mask: 3661 case X86::BI__builtin_ia32_ucmpw128_mask: 3662 case X86::BI__builtin_ia32_ucmpd128_mask: 3663 case X86::BI__builtin_ia32_ucmpq128_mask: 3664 case X86::BI__builtin_ia32_ucmpb256_mask: 3665 case X86::BI__builtin_ia32_ucmpw256_mask: 3666 case X86::BI__builtin_ia32_ucmpd256_mask: 3667 case X86::BI__builtin_ia32_ucmpq256_mask: 3668 case X86::BI__builtin_ia32_ucmpb512_mask: 3669 case X86::BI__builtin_ia32_ucmpw512_mask: 3670 case X86::BI__builtin_ia32_ucmpd512_mask: 3671 case X86::BI__builtin_ia32_ucmpq512_mask: 3672 case X86::BI__builtin_ia32_vpcomub: 3673 case X86::BI__builtin_ia32_vpcomuw: 3674 case X86::BI__builtin_ia32_vpcomud: 3675 case X86::BI__builtin_ia32_vpcomuq: 3676 case X86::BI__builtin_ia32_vpcomb: 3677 case X86::BI__builtin_ia32_vpcomw: 3678 case X86::BI__builtin_ia32_vpcomd: 3679 case X86::BI__builtin_ia32_vpcomq: 3680 case X86::BI__builtin_ia32_vec_set_v8hi: 3681 case X86::BI__builtin_ia32_vec_set_v8si: 3682 i = 2; l = 0; u = 7; 3683 break; 3684 case X86::BI__builtin_ia32_vpermilpd256: 3685 case X86::BI__builtin_ia32_roundps: 3686 case X86::BI__builtin_ia32_roundpd: 3687 case X86::BI__builtin_ia32_roundps256: 3688 case X86::BI__builtin_ia32_roundpd256: 3689 case X86::BI__builtin_ia32_getmantpd128_mask: 3690 case X86::BI__builtin_ia32_getmantpd256_mask: 3691 case X86::BI__builtin_ia32_getmantps128_mask: 3692 case X86::BI__builtin_ia32_getmantps256_mask: 3693 case X86::BI__builtin_ia32_getmantpd512_mask: 3694 case X86::BI__builtin_ia32_getmantps512_mask: 3695 case X86::BI__builtin_ia32_vec_ext_v16qi: 3696 case X86::BI__builtin_ia32_vec_ext_v16hi: 3697 i = 1; l = 0; u = 15; 3698 break; 3699 case X86::BI__builtin_ia32_pblendd128: 3700 case X86::BI__builtin_ia32_blendps: 3701 case X86::BI__builtin_ia32_blendpd256: 3702 case X86::BI__builtin_ia32_shufpd256: 3703 case X86::BI__builtin_ia32_roundss: 3704 case X86::BI__builtin_ia32_roundsd: 3705 case X86::BI__builtin_ia32_rangepd128_mask: 3706 case X86::BI__builtin_ia32_rangepd256_mask: 3707 case X86::BI__builtin_ia32_rangepd512_mask: 3708 case X86::BI__builtin_ia32_rangeps128_mask: 3709 case X86::BI__builtin_ia32_rangeps256_mask: 3710 case X86::BI__builtin_ia32_rangeps512_mask: 3711 case X86::BI__builtin_ia32_getmantsd_round_mask: 3712 case X86::BI__builtin_ia32_getmantss_round_mask: 3713 case X86::BI__builtin_ia32_vec_set_v16qi: 3714 case X86::BI__builtin_ia32_vec_set_v16hi: 3715 i = 2; l = 0; u = 15; 3716 break; 3717 case X86::BI__builtin_ia32_vec_ext_v32qi: 3718 i = 1; l = 0; u = 31; 3719 break; 3720 case X86::BI__builtin_ia32_cmpps: 3721 case X86::BI__builtin_ia32_cmpss: 3722 case X86::BI__builtin_ia32_cmppd: 3723 case X86::BI__builtin_ia32_cmpsd: 3724 case X86::BI__builtin_ia32_cmpps256: 3725 case X86::BI__builtin_ia32_cmppd256: 3726 case X86::BI__builtin_ia32_cmpps128_mask: 3727 case X86::BI__builtin_ia32_cmppd128_mask: 3728 case X86::BI__builtin_ia32_cmpps256_mask: 3729 case X86::BI__builtin_ia32_cmppd256_mask: 3730 case X86::BI__builtin_ia32_cmpps512_mask: 3731 case X86::BI__builtin_ia32_cmppd512_mask: 3732 case X86::BI__builtin_ia32_cmpsd_mask: 3733 case X86::BI__builtin_ia32_cmpss_mask: 3734 case X86::BI__builtin_ia32_vec_set_v32qi: 3735 i = 2; l = 0; u = 31; 3736 break; 3737 case X86::BI__builtin_ia32_permdf256: 3738 case X86::BI__builtin_ia32_permdi256: 3739 case X86::BI__builtin_ia32_permdf512: 3740 case X86::BI__builtin_ia32_permdi512: 3741 case X86::BI__builtin_ia32_vpermilps: 3742 case X86::BI__builtin_ia32_vpermilps256: 3743 case X86::BI__builtin_ia32_vpermilpd512: 3744 case X86::BI__builtin_ia32_vpermilps512: 3745 case X86::BI__builtin_ia32_pshufd: 3746 case X86::BI__builtin_ia32_pshufd256: 3747 case X86::BI__builtin_ia32_pshufd512: 3748 case X86::BI__builtin_ia32_pshufhw: 3749 case X86::BI__builtin_ia32_pshufhw256: 3750 case X86::BI__builtin_ia32_pshufhw512: 3751 case X86::BI__builtin_ia32_pshuflw: 3752 case X86::BI__builtin_ia32_pshuflw256: 3753 case X86::BI__builtin_ia32_pshuflw512: 3754 case X86::BI__builtin_ia32_vcvtps2ph: 3755 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3756 case X86::BI__builtin_ia32_vcvtps2ph256: 3757 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3758 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3759 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3760 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3761 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3762 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3763 case X86::BI__builtin_ia32_rndscaleps_mask: 3764 case X86::BI__builtin_ia32_rndscalepd_mask: 3765 case X86::BI__builtin_ia32_reducepd128_mask: 3766 case X86::BI__builtin_ia32_reducepd256_mask: 3767 case X86::BI__builtin_ia32_reducepd512_mask: 3768 case X86::BI__builtin_ia32_reduceps128_mask: 3769 case X86::BI__builtin_ia32_reduceps256_mask: 3770 case X86::BI__builtin_ia32_reduceps512_mask: 3771 case X86::BI__builtin_ia32_prold512: 3772 case X86::BI__builtin_ia32_prolq512: 3773 case X86::BI__builtin_ia32_prold128: 3774 case X86::BI__builtin_ia32_prold256: 3775 case X86::BI__builtin_ia32_prolq128: 3776 case X86::BI__builtin_ia32_prolq256: 3777 case X86::BI__builtin_ia32_prord512: 3778 case X86::BI__builtin_ia32_prorq512: 3779 case X86::BI__builtin_ia32_prord128: 3780 case X86::BI__builtin_ia32_prord256: 3781 case X86::BI__builtin_ia32_prorq128: 3782 case X86::BI__builtin_ia32_prorq256: 3783 case X86::BI__builtin_ia32_fpclasspd128_mask: 3784 case X86::BI__builtin_ia32_fpclasspd256_mask: 3785 case X86::BI__builtin_ia32_fpclassps128_mask: 3786 case X86::BI__builtin_ia32_fpclassps256_mask: 3787 case X86::BI__builtin_ia32_fpclassps512_mask: 3788 case X86::BI__builtin_ia32_fpclasspd512_mask: 3789 case X86::BI__builtin_ia32_fpclasssd_mask: 3790 case X86::BI__builtin_ia32_fpclassss_mask: 3791 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3792 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3793 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3794 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3795 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3796 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3797 case X86::BI__builtin_ia32_kshiftliqi: 3798 case X86::BI__builtin_ia32_kshiftlihi: 3799 case X86::BI__builtin_ia32_kshiftlisi: 3800 case X86::BI__builtin_ia32_kshiftlidi: 3801 case X86::BI__builtin_ia32_kshiftriqi: 3802 case X86::BI__builtin_ia32_kshiftrihi: 3803 case X86::BI__builtin_ia32_kshiftrisi: 3804 case X86::BI__builtin_ia32_kshiftridi: 3805 i = 1; l = 0; u = 255; 3806 break; 3807 case X86::BI__builtin_ia32_vperm2f128_pd256: 3808 case X86::BI__builtin_ia32_vperm2f128_ps256: 3809 case X86::BI__builtin_ia32_vperm2f128_si256: 3810 case X86::BI__builtin_ia32_permti256: 3811 case X86::BI__builtin_ia32_pblendw128: 3812 case X86::BI__builtin_ia32_pblendw256: 3813 case X86::BI__builtin_ia32_blendps256: 3814 case X86::BI__builtin_ia32_pblendd256: 3815 case X86::BI__builtin_ia32_palignr128: 3816 case X86::BI__builtin_ia32_palignr256: 3817 case X86::BI__builtin_ia32_palignr512: 3818 case X86::BI__builtin_ia32_alignq512: 3819 case X86::BI__builtin_ia32_alignd512: 3820 case X86::BI__builtin_ia32_alignd128: 3821 case X86::BI__builtin_ia32_alignd256: 3822 case X86::BI__builtin_ia32_alignq128: 3823 case X86::BI__builtin_ia32_alignq256: 3824 case X86::BI__builtin_ia32_vcomisd: 3825 case X86::BI__builtin_ia32_vcomiss: 3826 case X86::BI__builtin_ia32_shuf_f32x4: 3827 case X86::BI__builtin_ia32_shuf_f64x2: 3828 case X86::BI__builtin_ia32_shuf_i32x4: 3829 case X86::BI__builtin_ia32_shuf_i64x2: 3830 case X86::BI__builtin_ia32_shufpd512: 3831 case X86::BI__builtin_ia32_shufps: 3832 case X86::BI__builtin_ia32_shufps256: 3833 case X86::BI__builtin_ia32_shufps512: 3834 case X86::BI__builtin_ia32_dbpsadbw128: 3835 case X86::BI__builtin_ia32_dbpsadbw256: 3836 case X86::BI__builtin_ia32_dbpsadbw512: 3837 case X86::BI__builtin_ia32_vpshldd128: 3838 case X86::BI__builtin_ia32_vpshldd256: 3839 case X86::BI__builtin_ia32_vpshldd512: 3840 case X86::BI__builtin_ia32_vpshldq128: 3841 case X86::BI__builtin_ia32_vpshldq256: 3842 case X86::BI__builtin_ia32_vpshldq512: 3843 case X86::BI__builtin_ia32_vpshldw128: 3844 case X86::BI__builtin_ia32_vpshldw256: 3845 case X86::BI__builtin_ia32_vpshldw512: 3846 case X86::BI__builtin_ia32_vpshrdd128: 3847 case X86::BI__builtin_ia32_vpshrdd256: 3848 case X86::BI__builtin_ia32_vpshrdd512: 3849 case X86::BI__builtin_ia32_vpshrdq128: 3850 case X86::BI__builtin_ia32_vpshrdq256: 3851 case X86::BI__builtin_ia32_vpshrdq512: 3852 case X86::BI__builtin_ia32_vpshrdw128: 3853 case X86::BI__builtin_ia32_vpshrdw256: 3854 case X86::BI__builtin_ia32_vpshrdw512: 3855 i = 2; l = 0; u = 255; 3856 break; 3857 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3858 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3859 case X86::BI__builtin_ia32_fixupimmps512_mask: 3860 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3861 case X86::BI__builtin_ia32_fixupimmsd_mask: 3862 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3863 case X86::BI__builtin_ia32_fixupimmss_mask: 3864 case X86::BI__builtin_ia32_fixupimmss_maskz: 3865 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3866 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3867 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3868 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3869 case X86::BI__builtin_ia32_fixupimmps128_mask: 3870 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3871 case X86::BI__builtin_ia32_fixupimmps256_mask: 3872 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3873 case X86::BI__builtin_ia32_pternlogd512_mask: 3874 case X86::BI__builtin_ia32_pternlogd512_maskz: 3875 case X86::BI__builtin_ia32_pternlogq512_mask: 3876 case X86::BI__builtin_ia32_pternlogq512_maskz: 3877 case X86::BI__builtin_ia32_pternlogd128_mask: 3878 case X86::BI__builtin_ia32_pternlogd128_maskz: 3879 case X86::BI__builtin_ia32_pternlogd256_mask: 3880 case X86::BI__builtin_ia32_pternlogd256_maskz: 3881 case X86::BI__builtin_ia32_pternlogq128_mask: 3882 case X86::BI__builtin_ia32_pternlogq128_maskz: 3883 case X86::BI__builtin_ia32_pternlogq256_mask: 3884 case X86::BI__builtin_ia32_pternlogq256_maskz: 3885 i = 3; l = 0; u = 255; 3886 break; 3887 case X86::BI__builtin_ia32_gatherpfdpd: 3888 case X86::BI__builtin_ia32_gatherpfdps: 3889 case X86::BI__builtin_ia32_gatherpfqpd: 3890 case X86::BI__builtin_ia32_gatherpfqps: 3891 case X86::BI__builtin_ia32_scatterpfdpd: 3892 case X86::BI__builtin_ia32_scatterpfdps: 3893 case X86::BI__builtin_ia32_scatterpfqpd: 3894 case X86::BI__builtin_ia32_scatterpfqps: 3895 i = 4; l = 2; u = 3; 3896 break; 3897 case X86::BI__builtin_ia32_reducesd_mask: 3898 case X86::BI__builtin_ia32_reducess_mask: 3899 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3900 case X86::BI__builtin_ia32_rndscaless_round_mask: 3901 i = 4; l = 0; u = 255; 3902 break; 3903 } 3904 3905 // Note that we don't force a hard error on the range check here, allowing 3906 // template-generated or macro-generated dead code to potentially have out-of- 3907 // range values. These need to code generate, but don't need to necessarily 3908 // make any sense. We use a warning that defaults to an error. 3909 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3910 } 3911 3912 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3913 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3914 /// Returns true when the format fits the function and the FormatStringInfo has 3915 /// been populated. 3916 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3917 FormatStringInfo *FSI) { 3918 FSI->HasVAListArg = Format->getFirstArg() == 0; 3919 FSI->FormatIdx = Format->getFormatIdx() - 1; 3920 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3921 3922 // The way the format attribute works in GCC, the implicit this argument 3923 // of member functions is counted. However, it doesn't appear in our own 3924 // lists, so decrement format_idx in that case. 3925 if (IsCXXMember) { 3926 if(FSI->FormatIdx == 0) 3927 return false; 3928 --FSI->FormatIdx; 3929 if (FSI->FirstDataArg != 0) 3930 --FSI->FirstDataArg; 3931 } 3932 return true; 3933 } 3934 3935 /// Checks if a the given expression evaluates to null. 3936 /// 3937 /// Returns true if the value evaluates to null. 3938 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3939 // If the expression has non-null type, it doesn't evaluate to null. 3940 if (auto nullability 3941 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3942 if (*nullability == NullabilityKind::NonNull) 3943 return false; 3944 } 3945 3946 // As a special case, transparent unions initialized with zero are 3947 // considered null for the purposes of the nonnull attribute. 3948 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3949 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3950 if (const CompoundLiteralExpr *CLE = 3951 dyn_cast<CompoundLiteralExpr>(Expr)) 3952 if (const InitListExpr *ILE = 3953 dyn_cast<InitListExpr>(CLE->getInitializer())) 3954 Expr = ILE->getInit(0); 3955 } 3956 3957 bool Result; 3958 return (!Expr->isValueDependent() && 3959 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3960 !Result); 3961 } 3962 3963 static void CheckNonNullArgument(Sema &S, 3964 const Expr *ArgExpr, 3965 SourceLocation CallSiteLoc) { 3966 if (CheckNonNullExpr(S, ArgExpr)) 3967 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3968 S.PDiag(diag::warn_null_arg) 3969 << ArgExpr->getSourceRange()); 3970 } 3971 3972 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3973 FormatStringInfo FSI; 3974 if ((GetFormatStringType(Format) == FST_NSString) && 3975 getFormatStringInfo(Format, false, &FSI)) { 3976 Idx = FSI.FormatIdx; 3977 return true; 3978 } 3979 return false; 3980 } 3981 3982 /// Diagnose use of %s directive in an NSString which is being passed 3983 /// as formatting string to formatting method. 3984 static void 3985 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3986 const NamedDecl *FDecl, 3987 Expr **Args, 3988 unsigned NumArgs) { 3989 unsigned Idx = 0; 3990 bool Format = false; 3991 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3992 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3993 Idx = 2; 3994 Format = true; 3995 } 3996 else 3997 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3998 if (S.GetFormatNSStringIdx(I, Idx)) { 3999 Format = true; 4000 break; 4001 } 4002 } 4003 if (!Format || NumArgs <= Idx) 4004 return; 4005 const Expr *FormatExpr = Args[Idx]; 4006 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4007 FormatExpr = CSCE->getSubExpr(); 4008 const StringLiteral *FormatString; 4009 if (const ObjCStringLiteral *OSL = 4010 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4011 FormatString = OSL->getString(); 4012 else 4013 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4014 if (!FormatString) 4015 return; 4016 if (S.FormatStringHasSArg(FormatString)) { 4017 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4018 << "%s" << 1 << 1; 4019 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4020 << FDecl->getDeclName(); 4021 } 4022 } 4023 4024 /// Determine whether the given type has a non-null nullability annotation. 4025 static bool isNonNullType(ASTContext &ctx, QualType type) { 4026 if (auto nullability = type->getNullability(ctx)) 4027 return *nullability == NullabilityKind::NonNull; 4028 4029 return false; 4030 } 4031 4032 static void CheckNonNullArguments(Sema &S, 4033 const NamedDecl *FDecl, 4034 const FunctionProtoType *Proto, 4035 ArrayRef<const Expr *> Args, 4036 SourceLocation CallSiteLoc) { 4037 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4038 4039 // Already checked by by constant evaluator. 4040 if (S.isConstantEvaluated()) 4041 return; 4042 // Check the attributes attached to the method/function itself. 4043 llvm::SmallBitVector NonNullArgs; 4044 if (FDecl) { 4045 // Handle the nonnull attribute on the function/method declaration itself. 4046 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4047 if (!NonNull->args_size()) { 4048 // Easy case: all pointer arguments are nonnull. 4049 for (const auto *Arg : Args) 4050 if (S.isValidPointerAttrType(Arg->getType())) 4051 CheckNonNullArgument(S, Arg, CallSiteLoc); 4052 return; 4053 } 4054 4055 for (const ParamIdx &Idx : NonNull->args()) { 4056 unsigned IdxAST = Idx.getASTIndex(); 4057 if (IdxAST >= Args.size()) 4058 continue; 4059 if (NonNullArgs.empty()) 4060 NonNullArgs.resize(Args.size()); 4061 NonNullArgs.set(IdxAST); 4062 } 4063 } 4064 } 4065 4066 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4067 // Handle the nonnull attribute on the parameters of the 4068 // function/method. 4069 ArrayRef<ParmVarDecl*> parms; 4070 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4071 parms = FD->parameters(); 4072 else 4073 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4074 4075 unsigned ParamIndex = 0; 4076 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4077 I != E; ++I, ++ParamIndex) { 4078 const ParmVarDecl *PVD = *I; 4079 if (PVD->hasAttr<NonNullAttr>() || 4080 isNonNullType(S.Context, PVD->getType())) { 4081 if (NonNullArgs.empty()) 4082 NonNullArgs.resize(Args.size()); 4083 4084 NonNullArgs.set(ParamIndex); 4085 } 4086 } 4087 } else { 4088 // If we have a non-function, non-method declaration but no 4089 // function prototype, try to dig out the function prototype. 4090 if (!Proto) { 4091 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4092 QualType type = VD->getType().getNonReferenceType(); 4093 if (auto pointerType = type->getAs<PointerType>()) 4094 type = pointerType->getPointeeType(); 4095 else if (auto blockType = type->getAs<BlockPointerType>()) 4096 type = blockType->getPointeeType(); 4097 // FIXME: data member pointers? 4098 4099 // Dig out the function prototype, if there is one. 4100 Proto = type->getAs<FunctionProtoType>(); 4101 } 4102 } 4103 4104 // Fill in non-null argument information from the nullability 4105 // information on the parameter types (if we have them). 4106 if (Proto) { 4107 unsigned Index = 0; 4108 for (auto paramType : Proto->getParamTypes()) { 4109 if (isNonNullType(S.Context, paramType)) { 4110 if (NonNullArgs.empty()) 4111 NonNullArgs.resize(Args.size()); 4112 4113 NonNullArgs.set(Index); 4114 } 4115 4116 ++Index; 4117 } 4118 } 4119 } 4120 4121 // Check for non-null arguments. 4122 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4123 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4124 if (NonNullArgs[ArgIndex]) 4125 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4126 } 4127 } 4128 4129 /// Handles the checks for format strings, non-POD arguments to vararg 4130 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4131 /// attributes. 4132 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4133 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4134 bool IsMemberFunction, SourceLocation Loc, 4135 SourceRange Range, VariadicCallType CallType) { 4136 // FIXME: We should check as much as we can in the template definition. 4137 if (CurContext->isDependentContext()) 4138 return; 4139 4140 // Printf and scanf checking. 4141 llvm::SmallBitVector CheckedVarArgs; 4142 if (FDecl) { 4143 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4144 // Only create vector if there are format attributes. 4145 CheckedVarArgs.resize(Args.size()); 4146 4147 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4148 CheckedVarArgs); 4149 } 4150 } 4151 4152 // Refuse POD arguments that weren't caught by the format string 4153 // checks above. 4154 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4155 if (CallType != VariadicDoesNotApply && 4156 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4157 unsigned NumParams = Proto ? Proto->getNumParams() 4158 : FDecl && isa<FunctionDecl>(FDecl) 4159 ? cast<FunctionDecl>(FDecl)->getNumParams() 4160 : FDecl && isa<ObjCMethodDecl>(FDecl) 4161 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4162 : 0; 4163 4164 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4165 // Args[ArgIdx] can be null in malformed code. 4166 if (const Expr *Arg = Args[ArgIdx]) { 4167 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4168 checkVariadicArgument(Arg, CallType); 4169 } 4170 } 4171 } 4172 4173 if (FDecl || Proto) { 4174 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4175 4176 // Type safety checking. 4177 if (FDecl) { 4178 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4179 CheckArgumentWithTypeTag(I, Args, Loc); 4180 } 4181 } 4182 4183 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4184 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4185 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4186 if (!Arg->isValueDependent()) { 4187 Expr::EvalResult Align; 4188 if (Arg->EvaluateAsInt(Align, Context)) { 4189 const llvm::APSInt &I = Align.Val.getInt(); 4190 if (!I.isPowerOf2()) 4191 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4192 << Arg->getSourceRange(); 4193 4194 if (I > Sema::MaximumAlignment) 4195 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4196 << Arg->getSourceRange() << Sema::MaximumAlignment; 4197 } 4198 } 4199 } 4200 4201 if (FD) 4202 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4203 } 4204 4205 /// CheckConstructorCall - Check a constructor call for correctness and safety 4206 /// properties not enforced by the C type system. 4207 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4208 ArrayRef<const Expr *> Args, 4209 const FunctionProtoType *Proto, 4210 SourceLocation Loc) { 4211 VariadicCallType CallType = 4212 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4213 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4214 Loc, SourceRange(), CallType); 4215 } 4216 4217 /// CheckFunctionCall - Check a direct function call for various correctness 4218 /// and safety properties not strictly enforced by the C type system. 4219 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4220 const FunctionProtoType *Proto) { 4221 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4222 isa<CXXMethodDecl>(FDecl); 4223 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4224 IsMemberOperatorCall; 4225 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4226 TheCall->getCallee()); 4227 Expr** Args = TheCall->getArgs(); 4228 unsigned NumArgs = TheCall->getNumArgs(); 4229 4230 Expr *ImplicitThis = nullptr; 4231 if (IsMemberOperatorCall) { 4232 // If this is a call to a member operator, hide the first argument 4233 // from checkCall. 4234 // FIXME: Our choice of AST representation here is less than ideal. 4235 ImplicitThis = Args[0]; 4236 ++Args; 4237 --NumArgs; 4238 } else if (IsMemberFunction) 4239 ImplicitThis = 4240 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4241 4242 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4243 IsMemberFunction, TheCall->getRParenLoc(), 4244 TheCall->getCallee()->getSourceRange(), CallType); 4245 4246 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4247 // None of the checks below are needed for functions that don't have 4248 // simple names (e.g., C++ conversion functions). 4249 if (!FnInfo) 4250 return false; 4251 4252 CheckAbsoluteValueFunction(TheCall, FDecl); 4253 CheckMaxUnsignedZero(TheCall, FDecl); 4254 4255 if (getLangOpts().ObjC) 4256 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4257 4258 unsigned CMId = FDecl->getMemoryFunctionKind(); 4259 if (CMId == 0) 4260 return false; 4261 4262 // Handle memory setting and copying functions. 4263 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4264 CheckStrlcpycatArguments(TheCall, FnInfo); 4265 else if (CMId == Builtin::BIstrncat) 4266 CheckStrncatArguments(TheCall, FnInfo); 4267 else 4268 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4269 4270 return false; 4271 } 4272 4273 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4274 ArrayRef<const Expr *> Args) { 4275 VariadicCallType CallType = 4276 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4277 4278 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4279 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4280 CallType); 4281 4282 return false; 4283 } 4284 4285 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4286 const FunctionProtoType *Proto) { 4287 QualType Ty; 4288 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4289 Ty = V->getType().getNonReferenceType(); 4290 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4291 Ty = F->getType().getNonReferenceType(); 4292 else 4293 return false; 4294 4295 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4296 !Ty->isFunctionProtoType()) 4297 return false; 4298 4299 VariadicCallType CallType; 4300 if (!Proto || !Proto->isVariadic()) { 4301 CallType = VariadicDoesNotApply; 4302 } else if (Ty->isBlockPointerType()) { 4303 CallType = VariadicBlock; 4304 } else { // Ty->isFunctionPointerType() 4305 CallType = VariadicFunction; 4306 } 4307 4308 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4309 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4310 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4311 TheCall->getCallee()->getSourceRange(), CallType); 4312 4313 return false; 4314 } 4315 4316 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4317 /// such as function pointers returned from functions. 4318 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4319 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4320 TheCall->getCallee()); 4321 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4322 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4323 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4324 TheCall->getCallee()->getSourceRange(), CallType); 4325 4326 return false; 4327 } 4328 4329 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4330 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4331 return false; 4332 4333 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4334 switch (Op) { 4335 case AtomicExpr::AO__c11_atomic_init: 4336 case AtomicExpr::AO__opencl_atomic_init: 4337 llvm_unreachable("There is no ordering argument for an init"); 4338 4339 case AtomicExpr::AO__c11_atomic_load: 4340 case AtomicExpr::AO__opencl_atomic_load: 4341 case AtomicExpr::AO__atomic_load_n: 4342 case AtomicExpr::AO__atomic_load: 4343 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4344 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4345 4346 case AtomicExpr::AO__c11_atomic_store: 4347 case AtomicExpr::AO__opencl_atomic_store: 4348 case AtomicExpr::AO__atomic_store: 4349 case AtomicExpr::AO__atomic_store_n: 4350 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4351 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4352 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4353 4354 default: 4355 return true; 4356 } 4357 } 4358 4359 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4360 AtomicExpr::AtomicOp Op) { 4361 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4362 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4363 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4364 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4365 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4366 Op); 4367 } 4368 4369 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4370 SourceLocation RParenLoc, MultiExprArg Args, 4371 AtomicExpr::AtomicOp Op, 4372 AtomicArgumentOrder ArgOrder) { 4373 // All the non-OpenCL operations take one of the following forms. 4374 // The OpenCL operations take the __c11 forms with one extra argument for 4375 // synchronization scope. 4376 enum { 4377 // C __c11_atomic_init(A *, C) 4378 Init, 4379 4380 // C __c11_atomic_load(A *, int) 4381 Load, 4382 4383 // void __atomic_load(A *, CP, int) 4384 LoadCopy, 4385 4386 // void __atomic_store(A *, CP, int) 4387 Copy, 4388 4389 // C __c11_atomic_add(A *, M, int) 4390 Arithmetic, 4391 4392 // C __atomic_exchange_n(A *, CP, int) 4393 Xchg, 4394 4395 // void __atomic_exchange(A *, C *, CP, int) 4396 GNUXchg, 4397 4398 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4399 C11CmpXchg, 4400 4401 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4402 GNUCmpXchg 4403 } Form = Init; 4404 4405 const unsigned NumForm = GNUCmpXchg + 1; 4406 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4407 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4408 // where: 4409 // C is an appropriate type, 4410 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4411 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4412 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4413 // the int parameters are for orderings. 4414 4415 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4416 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4417 "need to update code for modified forms"); 4418 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4419 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4420 AtomicExpr::AO__atomic_load, 4421 "need to update code for modified C11 atomics"); 4422 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4423 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4424 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4425 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4426 IsOpenCL; 4427 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4428 Op == AtomicExpr::AO__atomic_store_n || 4429 Op == AtomicExpr::AO__atomic_exchange_n || 4430 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4431 bool IsAddSub = false; 4432 4433 switch (Op) { 4434 case AtomicExpr::AO__c11_atomic_init: 4435 case AtomicExpr::AO__opencl_atomic_init: 4436 Form = Init; 4437 break; 4438 4439 case AtomicExpr::AO__c11_atomic_load: 4440 case AtomicExpr::AO__opencl_atomic_load: 4441 case AtomicExpr::AO__atomic_load_n: 4442 Form = Load; 4443 break; 4444 4445 case AtomicExpr::AO__atomic_load: 4446 Form = LoadCopy; 4447 break; 4448 4449 case AtomicExpr::AO__c11_atomic_store: 4450 case AtomicExpr::AO__opencl_atomic_store: 4451 case AtomicExpr::AO__atomic_store: 4452 case AtomicExpr::AO__atomic_store_n: 4453 Form = Copy; 4454 break; 4455 4456 case AtomicExpr::AO__c11_atomic_fetch_add: 4457 case AtomicExpr::AO__c11_atomic_fetch_sub: 4458 case AtomicExpr::AO__opencl_atomic_fetch_add: 4459 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4460 case AtomicExpr::AO__atomic_fetch_add: 4461 case AtomicExpr::AO__atomic_fetch_sub: 4462 case AtomicExpr::AO__atomic_add_fetch: 4463 case AtomicExpr::AO__atomic_sub_fetch: 4464 IsAddSub = true; 4465 LLVM_FALLTHROUGH; 4466 case AtomicExpr::AO__c11_atomic_fetch_and: 4467 case AtomicExpr::AO__c11_atomic_fetch_or: 4468 case AtomicExpr::AO__c11_atomic_fetch_xor: 4469 case AtomicExpr::AO__opencl_atomic_fetch_and: 4470 case AtomicExpr::AO__opencl_atomic_fetch_or: 4471 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4472 case AtomicExpr::AO__atomic_fetch_and: 4473 case AtomicExpr::AO__atomic_fetch_or: 4474 case AtomicExpr::AO__atomic_fetch_xor: 4475 case AtomicExpr::AO__atomic_fetch_nand: 4476 case AtomicExpr::AO__atomic_and_fetch: 4477 case AtomicExpr::AO__atomic_or_fetch: 4478 case AtomicExpr::AO__atomic_xor_fetch: 4479 case AtomicExpr::AO__atomic_nand_fetch: 4480 case AtomicExpr::AO__c11_atomic_fetch_min: 4481 case AtomicExpr::AO__c11_atomic_fetch_max: 4482 case AtomicExpr::AO__opencl_atomic_fetch_min: 4483 case AtomicExpr::AO__opencl_atomic_fetch_max: 4484 case AtomicExpr::AO__atomic_min_fetch: 4485 case AtomicExpr::AO__atomic_max_fetch: 4486 case AtomicExpr::AO__atomic_fetch_min: 4487 case AtomicExpr::AO__atomic_fetch_max: 4488 Form = Arithmetic; 4489 break; 4490 4491 case AtomicExpr::AO__c11_atomic_exchange: 4492 case AtomicExpr::AO__opencl_atomic_exchange: 4493 case AtomicExpr::AO__atomic_exchange_n: 4494 Form = Xchg; 4495 break; 4496 4497 case AtomicExpr::AO__atomic_exchange: 4498 Form = GNUXchg; 4499 break; 4500 4501 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4502 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4503 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4504 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4505 Form = C11CmpXchg; 4506 break; 4507 4508 case AtomicExpr::AO__atomic_compare_exchange: 4509 case AtomicExpr::AO__atomic_compare_exchange_n: 4510 Form = GNUCmpXchg; 4511 break; 4512 } 4513 4514 unsigned AdjustedNumArgs = NumArgs[Form]; 4515 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4516 ++AdjustedNumArgs; 4517 // Check we have the right number of arguments. 4518 if (Args.size() < AdjustedNumArgs) { 4519 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4520 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4521 << ExprRange; 4522 return ExprError(); 4523 } else if (Args.size() > AdjustedNumArgs) { 4524 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4525 diag::err_typecheck_call_too_many_args) 4526 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4527 << ExprRange; 4528 return ExprError(); 4529 } 4530 4531 // Inspect the first argument of the atomic operation. 4532 Expr *Ptr = Args[0]; 4533 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4534 if (ConvertedPtr.isInvalid()) 4535 return ExprError(); 4536 4537 Ptr = ConvertedPtr.get(); 4538 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4539 if (!pointerType) { 4540 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4541 << Ptr->getType() << Ptr->getSourceRange(); 4542 return ExprError(); 4543 } 4544 4545 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4546 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4547 QualType ValType = AtomTy; // 'C' 4548 if (IsC11) { 4549 if (!AtomTy->isAtomicType()) { 4550 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4551 << Ptr->getType() << Ptr->getSourceRange(); 4552 return ExprError(); 4553 } 4554 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4555 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4556 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4557 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4558 << Ptr->getSourceRange(); 4559 return ExprError(); 4560 } 4561 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4562 } else if (Form != Load && Form != LoadCopy) { 4563 if (ValType.isConstQualified()) { 4564 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4565 << Ptr->getType() << Ptr->getSourceRange(); 4566 return ExprError(); 4567 } 4568 } 4569 4570 // For an arithmetic operation, the implied arithmetic must be well-formed. 4571 if (Form == Arithmetic) { 4572 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4573 if (IsAddSub && !ValType->isIntegerType() 4574 && !ValType->isPointerType()) { 4575 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4576 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4577 return ExprError(); 4578 } 4579 if (!IsAddSub && !ValType->isIntegerType()) { 4580 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4581 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4582 return ExprError(); 4583 } 4584 if (IsC11 && ValType->isPointerType() && 4585 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4586 diag::err_incomplete_type)) { 4587 return ExprError(); 4588 } 4589 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4590 // For __atomic_*_n operations, the value type must be a scalar integral or 4591 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4592 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4593 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4594 return ExprError(); 4595 } 4596 4597 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4598 !AtomTy->isScalarType()) { 4599 // For GNU atomics, require a trivially-copyable type. This is not part of 4600 // the GNU atomics specification, but we enforce it for sanity. 4601 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4602 << Ptr->getType() << Ptr->getSourceRange(); 4603 return ExprError(); 4604 } 4605 4606 switch (ValType.getObjCLifetime()) { 4607 case Qualifiers::OCL_None: 4608 case Qualifiers::OCL_ExplicitNone: 4609 // okay 4610 break; 4611 4612 case Qualifiers::OCL_Weak: 4613 case Qualifiers::OCL_Strong: 4614 case Qualifiers::OCL_Autoreleasing: 4615 // FIXME: Can this happen? By this point, ValType should be known 4616 // to be trivially copyable. 4617 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4618 << ValType << Ptr->getSourceRange(); 4619 return ExprError(); 4620 } 4621 4622 // All atomic operations have an overload which takes a pointer to a volatile 4623 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4624 // into the result or the other operands. Similarly atomic_load takes a 4625 // pointer to a const 'A'. 4626 ValType.removeLocalVolatile(); 4627 ValType.removeLocalConst(); 4628 QualType ResultType = ValType; 4629 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4630 Form == Init) 4631 ResultType = Context.VoidTy; 4632 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4633 ResultType = Context.BoolTy; 4634 4635 // The type of a parameter passed 'by value'. In the GNU atomics, such 4636 // arguments are actually passed as pointers. 4637 QualType ByValType = ValType; // 'CP' 4638 bool IsPassedByAddress = false; 4639 if (!IsC11 && !IsN) { 4640 ByValType = Ptr->getType(); 4641 IsPassedByAddress = true; 4642 } 4643 4644 SmallVector<Expr *, 5> APIOrderedArgs; 4645 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4646 APIOrderedArgs.push_back(Args[0]); 4647 switch (Form) { 4648 case Init: 4649 case Load: 4650 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4651 break; 4652 case LoadCopy: 4653 case Copy: 4654 case Arithmetic: 4655 case Xchg: 4656 APIOrderedArgs.push_back(Args[2]); // Val1 4657 APIOrderedArgs.push_back(Args[1]); // Order 4658 break; 4659 case GNUXchg: 4660 APIOrderedArgs.push_back(Args[2]); // Val1 4661 APIOrderedArgs.push_back(Args[3]); // Val2 4662 APIOrderedArgs.push_back(Args[1]); // Order 4663 break; 4664 case C11CmpXchg: 4665 APIOrderedArgs.push_back(Args[2]); // Val1 4666 APIOrderedArgs.push_back(Args[4]); // Val2 4667 APIOrderedArgs.push_back(Args[1]); // Order 4668 APIOrderedArgs.push_back(Args[3]); // OrderFail 4669 break; 4670 case GNUCmpXchg: 4671 APIOrderedArgs.push_back(Args[2]); // Val1 4672 APIOrderedArgs.push_back(Args[4]); // Val2 4673 APIOrderedArgs.push_back(Args[5]); // Weak 4674 APIOrderedArgs.push_back(Args[1]); // Order 4675 APIOrderedArgs.push_back(Args[3]); // OrderFail 4676 break; 4677 } 4678 } else 4679 APIOrderedArgs.append(Args.begin(), Args.end()); 4680 4681 // The first argument's non-CV pointer type is used to deduce the type of 4682 // subsequent arguments, except for: 4683 // - weak flag (always converted to bool) 4684 // - memory order (always converted to int) 4685 // - scope (always converted to int) 4686 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4687 QualType Ty; 4688 if (i < NumVals[Form] + 1) { 4689 switch (i) { 4690 case 0: 4691 // The first argument is always a pointer. It has a fixed type. 4692 // It is always dereferenced, a nullptr is undefined. 4693 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4694 // Nothing else to do: we already know all we want about this pointer. 4695 continue; 4696 case 1: 4697 // The second argument is the non-atomic operand. For arithmetic, this 4698 // is always passed by value, and for a compare_exchange it is always 4699 // passed by address. For the rest, GNU uses by-address and C11 uses 4700 // by-value. 4701 assert(Form != Load); 4702 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4703 Ty = ValType; 4704 else if (Form == Copy || Form == Xchg) { 4705 if (IsPassedByAddress) { 4706 // The value pointer is always dereferenced, a nullptr is undefined. 4707 CheckNonNullArgument(*this, APIOrderedArgs[i], 4708 ExprRange.getBegin()); 4709 } 4710 Ty = ByValType; 4711 } else if (Form == Arithmetic) 4712 Ty = Context.getPointerDiffType(); 4713 else { 4714 Expr *ValArg = APIOrderedArgs[i]; 4715 // The value pointer is always dereferenced, a nullptr is undefined. 4716 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4717 LangAS AS = LangAS::Default; 4718 // Keep address space of non-atomic pointer type. 4719 if (const PointerType *PtrTy = 4720 ValArg->getType()->getAs<PointerType>()) { 4721 AS = PtrTy->getPointeeType().getAddressSpace(); 4722 } 4723 Ty = Context.getPointerType( 4724 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4725 } 4726 break; 4727 case 2: 4728 // The third argument to compare_exchange / GNU exchange is the desired 4729 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4730 if (IsPassedByAddress) 4731 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4732 Ty = ByValType; 4733 break; 4734 case 3: 4735 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4736 Ty = Context.BoolTy; 4737 break; 4738 } 4739 } else { 4740 // The order(s) and scope are always converted to int. 4741 Ty = Context.IntTy; 4742 } 4743 4744 InitializedEntity Entity = 4745 InitializedEntity::InitializeParameter(Context, Ty, false); 4746 ExprResult Arg = APIOrderedArgs[i]; 4747 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4748 if (Arg.isInvalid()) 4749 return true; 4750 APIOrderedArgs[i] = Arg.get(); 4751 } 4752 4753 // Permute the arguments into a 'consistent' order. 4754 SmallVector<Expr*, 5> SubExprs; 4755 SubExprs.push_back(Ptr); 4756 switch (Form) { 4757 case Init: 4758 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4759 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4760 break; 4761 case Load: 4762 SubExprs.push_back(APIOrderedArgs[1]); // Order 4763 break; 4764 case LoadCopy: 4765 case Copy: 4766 case Arithmetic: 4767 case Xchg: 4768 SubExprs.push_back(APIOrderedArgs[2]); // Order 4769 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4770 break; 4771 case GNUXchg: 4772 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4773 SubExprs.push_back(APIOrderedArgs[3]); // Order 4774 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4775 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4776 break; 4777 case C11CmpXchg: 4778 SubExprs.push_back(APIOrderedArgs[3]); // Order 4779 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4780 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4781 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4782 break; 4783 case GNUCmpXchg: 4784 SubExprs.push_back(APIOrderedArgs[4]); // Order 4785 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4786 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4787 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4788 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4789 break; 4790 } 4791 4792 if (SubExprs.size() >= 2 && Form != Init) { 4793 llvm::APSInt Result(32); 4794 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4795 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4796 Diag(SubExprs[1]->getBeginLoc(), 4797 diag::warn_atomic_op_has_invalid_memory_order) 4798 << SubExprs[1]->getSourceRange(); 4799 } 4800 4801 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4802 auto *Scope = Args[Args.size() - 1]; 4803 llvm::APSInt Result(32); 4804 if (Scope->isIntegerConstantExpr(Result, Context) && 4805 !ScopeModel->isValid(Result.getZExtValue())) { 4806 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4807 << Scope->getSourceRange(); 4808 } 4809 SubExprs.push_back(Scope); 4810 } 4811 4812 AtomicExpr *AE = new (Context) 4813 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4814 4815 if ((Op == AtomicExpr::AO__c11_atomic_load || 4816 Op == AtomicExpr::AO__c11_atomic_store || 4817 Op == AtomicExpr::AO__opencl_atomic_load || 4818 Op == AtomicExpr::AO__opencl_atomic_store ) && 4819 Context.AtomicUsesUnsupportedLibcall(AE)) 4820 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4821 << ((Op == AtomicExpr::AO__c11_atomic_load || 4822 Op == AtomicExpr::AO__opencl_atomic_load) 4823 ? 0 4824 : 1); 4825 4826 return AE; 4827 } 4828 4829 /// checkBuiltinArgument - Given a call to a builtin function, perform 4830 /// normal type-checking on the given argument, updating the call in 4831 /// place. This is useful when a builtin function requires custom 4832 /// type-checking for some of its arguments but not necessarily all of 4833 /// them. 4834 /// 4835 /// Returns true on error. 4836 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4837 FunctionDecl *Fn = E->getDirectCallee(); 4838 assert(Fn && "builtin call without direct callee!"); 4839 4840 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4841 InitializedEntity Entity = 4842 InitializedEntity::InitializeParameter(S.Context, Param); 4843 4844 ExprResult Arg = E->getArg(0); 4845 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4846 if (Arg.isInvalid()) 4847 return true; 4848 4849 E->setArg(ArgIndex, Arg.get()); 4850 return false; 4851 } 4852 4853 /// We have a call to a function like __sync_fetch_and_add, which is an 4854 /// overloaded function based on the pointer type of its first argument. 4855 /// The main BuildCallExpr routines have already promoted the types of 4856 /// arguments because all of these calls are prototyped as void(...). 4857 /// 4858 /// This function goes through and does final semantic checking for these 4859 /// builtins, as well as generating any warnings. 4860 ExprResult 4861 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4862 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4863 Expr *Callee = TheCall->getCallee(); 4864 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4865 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4866 4867 // Ensure that we have at least one argument to do type inference from. 4868 if (TheCall->getNumArgs() < 1) { 4869 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4870 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4871 return ExprError(); 4872 } 4873 4874 // Inspect the first argument of the atomic builtin. This should always be 4875 // a pointer type, whose element is an integral scalar or pointer type. 4876 // Because it is a pointer type, we don't have to worry about any implicit 4877 // casts here. 4878 // FIXME: We don't allow floating point scalars as input. 4879 Expr *FirstArg = TheCall->getArg(0); 4880 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4881 if (FirstArgResult.isInvalid()) 4882 return ExprError(); 4883 FirstArg = FirstArgResult.get(); 4884 TheCall->setArg(0, FirstArg); 4885 4886 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4887 if (!pointerType) { 4888 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4889 << FirstArg->getType() << FirstArg->getSourceRange(); 4890 return ExprError(); 4891 } 4892 4893 QualType ValType = pointerType->getPointeeType(); 4894 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4895 !ValType->isBlockPointerType()) { 4896 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4897 << FirstArg->getType() << FirstArg->getSourceRange(); 4898 return ExprError(); 4899 } 4900 4901 if (ValType.isConstQualified()) { 4902 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4903 << FirstArg->getType() << FirstArg->getSourceRange(); 4904 return ExprError(); 4905 } 4906 4907 switch (ValType.getObjCLifetime()) { 4908 case Qualifiers::OCL_None: 4909 case Qualifiers::OCL_ExplicitNone: 4910 // okay 4911 break; 4912 4913 case Qualifiers::OCL_Weak: 4914 case Qualifiers::OCL_Strong: 4915 case Qualifiers::OCL_Autoreleasing: 4916 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4917 << ValType << FirstArg->getSourceRange(); 4918 return ExprError(); 4919 } 4920 4921 // Strip any qualifiers off ValType. 4922 ValType = ValType.getUnqualifiedType(); 4923 4924 // The majority of builtins return a value, but a few have special return 4925 // types, so allow them to override appropriately below. 4926 QualType ResultType = ValType; 4927 4928 // We need to figure out which concrete builtin this maps onto. For example, 4929 // __sync_fetch_and_add with a 2 byte object turns into 4930 // __sync_fetch_and_add_2. 4931 #define BUILTIN_ROW(x) \ 4932 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4933 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4934 4935 static const unsigned BuiltinIndices[][5] = { 4936 BUILTIN_ROW(__sync_fetch_and_add), 4937 BUILTIN_ROW(__sync_fetch_and_sub), 4938 BUILTIN_ROW(__sync_fetch_and_or), 4939 BUILTIN_ROW(__sync_fetch_and_and), 4940 BUILTIN_ROW(__sync_fetch_and_xor), 4941 BUILTIN_ROW(__sync_fetch_and_nand), 4942 4943 BUILTIN_ROW(__sync_add_and_fetch), 4944 BUILTIN_ROW(__sync_sub_and_fetch), 4945 BUILTIN_ROW(__sync_and_and_fetch), 4946 BUILTIN_ROW(__sync_or_and_fetch), 4947 BUILTIN_ROW(__sync_xor_and_fetch), 4948 BUILTIN_ROW(__sync_nand_and_fetch), 4949 4950 BUILTIN_ROW(__sync_val_compare_and_swap), 4951 BUILTIN_ROW(__sync_bool_compare_and_swap), 4952 BUILTIN_ROW(__sync_lock_test_and_set), 4953 BUILTIN_ROW(__sync_lock_release), 4954 BUILTIN_ROW(__sync_swap) 4955 }; 4956 #undef BUILTIN_ROW 4957 4958 // Determine the index of the size. 4959 unsigned SizeIndex; 4960 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4961 case 1: SizeIndex = 0; break; 4962 case 2: SizeIndex = 1; break; 4963 case 4: SizeIndex = 2; break; 4964 case 8: SizeIndex = 3; break; 4965 case 16: SizeIndex = 4; break; 4966 default: 4967 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4968 << FirstArg->getType() << FirstArg->getSourceRange(); 4969 return ExprError(); 4970 } 4971 4972 // Each of these builtins has one pointer argument, followed by some number of 4973 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4974 // that we ignore. Find out which row of BuiltinIndices to read from as well 4975 // as the number of fixed args. 4976 unsigned BuiltinID = FDecl->getBuiltinID(); 4977 unsigned BuiltinIndex, NumFixed = 1; 4978 bool WarnAboutSemanticsChange = false; 4979 switch (BuiltinID) { 4980 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4981 case Builtin::BI__sync_fetch_and_add: 4982 case Builtin::BI__sync_fetch_and_add_1: 4983 case Builtin::BI__sync_fetch_and_add_2: 4984 case Builtin::BI__sync_fetch_and_add_4: 4985 case Builtin::BI__sync_fetch_and_add_8: 4986 case Builtin::BI__sync_fetch_and_add_16: 4987 BuiltinIndex = 0; 4988 break; 4989 4990 case Builtin::BI__sync_fetch_and_sub: 4991 case Builtin::BI__sync_fetch_and_sub_1: 4992 case Builtin::BI__sync_fetch_and_sub_2: 4993 case Builtin::BI__sync_fetch_and_sub_4: 4994 case Builtin::BI__sync_fetch_and_sub_8: 4995 case Builtin::BI__sync_fetch_and_sub_16: 4996 BuiltinIndex = 1; 4997 break; 4998 4999 case Builtin::BI__sync_fetch_and_or: 5000 case Builtin::BI__sync_fetch_and_or_1: 5001 case Builtin::BI__sync_fetch_and_or_2: 5002 case Builtin::BI__sync_fetch_and_or_4: 5003 case Builtin::BI__sync_fetch_and_or_8: 5004 case Builtin::BI__sync_fetch_and_or_16: 5005 BuiltinIndex = 2; 5006 break; 5007 5008 case Builtin::BI__sync_fetch_and_and: 5009 case Builtin::BI__sync_fetch_and_and_1: 5010 case Builtin::BI__sync_fetch_and_and_2: 5011 case Builtin::BI__sync_fetch_and_and_4: 5012 case Builtin::BI__sync_fetch_and_and_8: 5013 case Builtin::BI__sync_fetch_and_and_16: 5014 BuiltinIndex = 3; 5015 break; 5016 5017 case Builtin::BI__sync_fetch_and_xor: 5018 case Builtin::BI__sync_fetch_and_xor_1: 5019 case Builtin::BI__sync_fetch_and_xor_2: 5020 case Builtin::BI__sync_fetch_and_xor_4: 5021 case Builtin::BI__sync_fetch_and_xor_8: 5022 case Builtin::BI__sync_fetch_and_xor_16: 5023 BuiltinIndex = 4; 5024 break; 5025 5026 case Builtin::BI__sync_fetch_and_nand: 5027 case Builtin::BI__sync_fetch_and_nand_1: 5028 case Builtin::BI__sync_fetch_and_nand_2: 5029 case Builtin::BI__sync_fetch_and_nand_4: 5030 case Builtin::BI__sync_fetch_and_nand_8: 5031 case Builtin::BI__sync_fetch_and_nand_16: 5032 BuiltinIndex = 5; 5033 WarnAboutSemanticsChange = true; 5034 break; 5035 5036 case Builtin::BI__sync_add_and_fetch: 5037 case Builtin::BI__sync_add_and_fetch_1: 5038 case Builtin::BI__sync_add_and_fetch_2: 5039 case Builtin::BI__sync_add_and_fetch_4: 5040 case Builtin::BI__sync_add_and_fetch_8: 5041 case Builtin::BI__sync_add_and_fetch_16: 5042 BuiltinIndex = 6; 5043 break; 5044 5045 case Builtin::BI__sync_sub_and_fetch: 5046 case Builtin::BI__sync_sub_and_fetch_1: 5047 case Builtin::BI__sync_sub_and_fetch_2: 5048 case Builtin::BI__sync_sub_and_fetch_4: 5049 case Builtin::BI__sync_sub_and_fetch_8: 5050 case Builtin::BI__sync_sub_and_fetch_16: 5051 BuiltinIndex = 7; 5052 break; 5053 5054 case Builtin::BI__sync_and_and_fetch: 5055 case Builtin::BI__sync_and_and_fetch_1: 5056 case Builtin::BI__sync_and_and_fetch_2: 5057 case Builtin::BI__sync_and_and_fetch_4: 5058 case Builtin::BI__sync_and_and_fetch_8: 5059 case Builtin::BI__sync_and_and_fetch_16: 5060 BuiltinIndex = 8; 5061 break; 5062 5063 case Builtin::BI__sync_or_and_fetch: 5064 case Builtin::BI__sync_or_and_fetch_1: 5065 case Builtin::BI__sync_or_and_fetch_2: 5066 case Builtin::BI__sync_or_and_fetch_4: 5067 case Builtin::BI__sync_or_and_fetch_8: 5068 case Builtin::BI__sync_or_and_fetch_16: 5069 BuiltinIndex = 9; 5070 break; 5071 5072 case Builtin::BI__sync_xor_and_fetch: 5073 case Builtin::BI__sync_xor_and_fetch_1: 5074 case Builtin::BI__sync_xor_and_fetch_2: 5075 case Builtin::BI__sync_xor_and_fetch_4: 5076 case Builtin::BI__sync_xor_and_fetch_8: 5077 case Builtin::BI__sync_xor_and_fetch_16: 5078 BuiltinIndex = 10; 5079 break; 5080 5081 case Builtin::BI__sync_nand_and_fetch: 5082 case Builtin::BI__sync_nand_and_fetch_1: 5083 case Builtin::BI__sync_nand_and_fetch_2: 5084 case Builtin::BI__sync_nand_and_fetch_4: 5085 case Builtin::BI__sync_nand_and_fetch_8: 5086 case Builtin::BI__sync_nand_and_fetch_16: 5087 BuiltinIndex = 11; 5088 WarnAboutSemanticsChange = true; 5089 break; 5090 5091 case Builtin::BI__sync_val_compare_and_swap: 5092 case Builtin::BI__sync_val_compare_and_swap_1: 5093 case Builtin::BI__sync_val_compare_and_swap_2: 5094 case Builtin::BI__sync_val_compare_and_swap_4: 5095 case Builtin::BI__sync_val_compare_and_swap_8: 5096 case Builtin::BI__sync_val_compare_and_swap_16: 5097 BuiltinIndex = 12; 5098 NumFixed = 2; 5099 break; 5100 5101 case Builtin::BI__sync_bool_compare_and_swap: 5102 case Builtin::BI__sync_bool_compare_and_swap_1: 5103 case Builtin::BI__sync_bool_compare_and_swap_2: 5104 case Builtin::BI__sync_bool_compare_and_swap_4: 5105 case Builtin::BI__sync_bool_compare_and_swap_8: 5106 case Builtin::BI__sync_bool_compare_and_swap_16: 5107 BuiltinIndex = 13; 5108 NumFixed = 2; 5109 ResultType = Context.BoolTy; 5110 break; 5111 5112 case Builtin::BI__sync_lock_test_and_set: 5113 case Builtin::BI__sync_lock_test_and_set_1: 5114 case Builtin::BI__sync_lock_test_and_set_2: 5115 case Builtin::BI__sync_lock_test_and_set_4: 5116 case Builtin::BI__sync_lock_test_and_set_8: 5117 case Builtin::BI__sync_lock_test_and_set_16: 5118 BuiltinIndex = 14; 5119 break; 5120 5121 case Builtin::BI__sync_lock_release: 5122 case Builtin::BI__sync_lock_release_1: 5123 case Builtin::BI__sync_lock_release_2: 5124 case Builtin::BI__sync_lock_release_4: 5125 case Builtin::BI__sync_lock_release_8: 5126 case Builtin::BI__sync_lock_release_16: 5127 BuiltinIndex = 15; 5128 NumFixed = 0; 5129 ResultType = Context.VoidTy; 5130 break; 5131 5132 case Builtin::BI__sync_swap: 5133 case Builtin::BI__sync_swap_1: 5134 case Builtin::BI__sync_swap_2: 5135 case Builtin::BI__sync_swap_4: 5136 case Builtin::BI__sync_swap_8: 5137 case Builtin::BI__sync_swap_16: 5138 BuiltinIndex = 16; 5139 break; 5140 } 5141 5142 // Now that we know how many fixed arguments we expect, first check that we 5143 // have at least that many. 5144 if (TheCall->getNumArgs() < 1+NumFixed) { 5145 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5146 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5147 << Callee->getSourceRange(); 5148 return ExprError(); 5149 } 5150 5151 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5152 << Callee->getSourceRange(); 5153 5154 if (WarnAboutSemanticsChange) { 5155 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5156 << Callee->getSourceRange(); 5157 } 5158 5159 // Get the decl for the concrete builtin from this, we can tell what the 5160 // concrete integer type we should convert to is. 5161 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5162 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5163 FunctionDecl *NewBuiltinDecl; 5164 if (NewBuiltinID == BuiltinID) 5165 NewBuiltinDecl = FDecl; 5166 else { 5167 // Perform builtin lookup to avoid redeclaring it. 5168 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5169 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5170 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5171 assert(Res.getFoundDecl()); 5172 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5173 if (!NewBuiltinDecl) 5174 return ExprError(); 5175 } 5176 5177 // The first argument --- the pointer --- has a fixed type; we 5178 // deduce the types of the rest of the arguments accordingly. Walk 5179 // the remaining arguments, converting them to the deduced value type. 5180 for (unsigned i = 0; i != NumFixed; ++i) { 5181 ExprResult Arg = TheCall->getArg(i+1); 5182 5183 // GCC does an implicit conversion to the pointer or integer ValType. This 5184 // can fail in some cases (1i -> int**), check for this error case now. 5185 // Initialize the argument. 5186 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5187 ValType, /*consume*/ false); 5188 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5189 if (Arg.isInvalid()) 5190 return ExprError(); 5191 5192 // Okay, we have something that *can* be converted to the right type. Check 5193 // to see if there is a potentially weird extension going on here. This can 5194 // happen when you do an atomic operation on something like an char* and 5195 // pass in 42. The 42 gets converted to char. This is even more strange 5196 // for things like 45.123 -> char, etc. 5197 // FIXME: Do this check. 5198 TheCall->setArg(i+1, Arg.get()); 5199 } 5200 5201 // Create a new DeclRefExpr to refer to the new decl. 5202 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5203 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5204 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5205 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5206 5207 // Set the callee in the CallExpr. 5208 // FIXME: This loses syntactic information. 5209 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5210 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5211 CK_BuiltinFnToFnPtr); 5212 TheCall->setCallee(PromotedCall.get()); 5213 5214 // Change the result type of the call to match the original value type. This 5215 // is arbitrary, but the codegen for these builtins ins design to handle it 5216 // gracefully. 5217 TheCall->setType(ResultType); 5218 5219 return TheCallResult; 5220 } 5221 5222 /// SemaBuiltinNontemporalOverloaded - We have a call to 5223 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5224 /// overloaded function based on the pointer type of its last argument. 5225 /// 5226 /// This function goes through and does final semantic checking for these 5227 /// builtins. 5228 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5229 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5230 DeclRefExpr *DRE = 5231 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5232 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5233 unsigned BuiltinID = FDecl->getBuiltinID(); 5234 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5235 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5236 "Unexpected nontemporal load/store builtin!"); 5237 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5238 unsigned numArgs = isStore ? 2 : 1; 5239 5240 // Ensure that we have the proper number of arguments. 5241 if (checkArgCount(*this, TheCall, numArgs)) 5242 return ExprError(); 5243 5244 // Inspect the last argument of the nontemporal builtin. This should always 5245 // be a pointer type, from which we imply the type of the memory access. 5246 // Because it is a pointer type, we don't have to worry about any implicit 5247 // casts here. 5248 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5249 ExprResult PointerArgResult = 5250 DefaultFunctionArrayLvalueConversion(PointerArg); 5251 5252 if (PointerArgResult.isInvalid()) 5253 return ExprError(); 5254 PointerArg = PointerArgResult.get(); 5255 TheCall->setArg(numArgs - 1, PointerArg); 5256 5257 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5258 if (!pointerType) { 5259 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5260 << PointerArg->getType() << PointerArg->getSourceRange(); 5261 return ExprError(); 5262 } 5263 5264 QualType ValType = pointerType->getPointeeType(); 5265 5266 // Strip any qualifiers off ValType. 5267 ValType = ValType.getUnqualifiedType(); 5268 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5269 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5270 !ValType->isVectorType()) { 5271 Diag(DRE->getBeginLoc(), 5272 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5273 << PointerArg->getType() << PointerArg->getSourceRange(); 5274 return ExprError(); 5275 } 5276 5277 if (!isStore) { 5278 TheCall->setType(ValType); 5279 return TheCallResult; 5280 } 5281 5282 ExprResult ValArg = TheCall->getArg(0); 5283 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5284 Context, ValType, /*consume*/ false); 5285 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5286 if (ValArg.isInvalid()) 5287 return ExprError(); 5288 5289 TheCall->setArg(0, ValArg.get()); 5290 TheCall->setType(Context.VoidTy); 5291 return TheCallResult; 5292 } 5293 5294 /// CheckObjCString - Checks that the argument to the builtin 5295 /// CFString constructor is correct 5296 /// Note: It might also make sense to do the UTF-16 conversion here (would 5297 /// simplify the backend). 5298 bool Sema::CheckObjCString(Expr *Arg) { 5299 Arg = Arg->IgnoreParenCasts(); 5300 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5301 5302 if (!Literal || !Literal->isAscii()) { 5303 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5304 << Arg->getSourceRange(); 5305 return true; 5306 } 5307 5308 if (Literal->containsNonAsciiOrNull()) { 5309 StringRef String = Literal->getString(); 5310 unsigned NumBytes = String.size(); 5311 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5312 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5313 llvm::UTF16 *ToPtr = &ToBuf[0]; 5314 5315 llvm::ConversionResult Result = 5316 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5317 ToPtr + NumBytes, llvm::strictConversion); 5318 // Check for conversion failure. 5319 if (Result != llvm::conversionOK) 5320 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5321 << Arg->getSourceRange(); 5322 } 5323 return false; 5324 } 5325 5326 /// CheckObjCString - Checks that the format string argument to the os_log() 5327 /// and os_trace() functions is correct, and converts it to const char *. 5328 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5329 Arg = Arg->IgnoreParenCasts(); 5330 auto *Literal = dyn_cast<StringLiteral>(Arg); 5331 if (!Literal) { 5332 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5333 Literal = ObjcLiteral->getString(); 5334 } 5335 } 5336 5337 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5338 return ExprError( 5339 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5340 << Arg->getSourceRange()); 5341 } 5342 5343 ExprResult Result(Literal); 5344 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5345 InitializedEntity Entity = 5346 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5347 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5348 return Result; 5349 } 5350 5351 /// Check that the user is calling the appropriate va_start builtin for the 5352 /// target and calling convention. 5353 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5354 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5355 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5356 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5357 TT.getArch() == llvm::Triple::aarch64_32); 5358 bool IsWindows = TT.isOSWindows(); 5359 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5360 if (IsX64 || IsAArch64) { 5361 CallingConv CC = CC_C; 5362 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5363 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5364 if (IsMSVAStart) { 5365 // Don't allow this in System V ABI functions. 5366 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5367 return S.Diag(Fn->getBeginLoc(), 5368 diag::err_ms_va_start_used_in_sysv_function); 5369 } else { 5370 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5371 // On x64 Windows, don't allow this in System V ABI functions. 5372 // (Yes, that means there's no corresponding way to support variadic 5373 // System V ABI functions on Windows.) 5374 if ((IsWindows && CC == CC_X86_64SysV) || 5375 (!IsWindows && CC == CC_Win64)) 5376 return S.Diag(Fn->getBeginLoc(), 5377 diag::err_va_start_used_in_wrong_abi_function) 5378 << !IsWindows; 5379 } 5380 return false; 5381 } 5382 5383 if (IsMSVAStart) 5384 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5385 return false; 5386 } 5387 5388 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5389 ParmVarDecl **LastParam = nullptr) { 5390 // Determine whether the current function, block, or obj-c method is variadic 5391 // and get its parameter list. 5392 bool IsVariadic = false; 5393 ArrayRef<ParmVarDecl *> Params; 5394 DeclContext *Caller = S.CurContext; 5395 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5396 IsVariadic = Block->isVariadic(); 5397 Params = Block->parameters(); 5398 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5399 IsVariadic = FD->isVariadic(); 5400 Params = FD->parameters(); 5401 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5402 IsVariadic = MD->isVariadic(); 5403 // FIXME: This isn't correct for methods (results in bogus warning). 5404 Params = MD->parameters(); 5405 } else if (isa<CapturedDecl>(Caller)) { 5406 // We don't support va_start in a CapturedDecl. 5407 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5408 return true; 5409 } else { 5410 // This must be some other declcontext that parses exprs. 5411 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5412 return true; 5413 } 5414 5415 if (!IsVariadic) { 5416 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5417 return true; 5418 } 5419 5420 if (LastParam) 5421 *LastParam = Params.empty() ? nullptr : Params.back(); 5422 5423 return false; 5424 } 5425 5426 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5427 /// for validity. Emit an error and return true on failure; return false 5428 /// on success. 5429 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5430 Expr *Fn = TheCall->getCallee(); 5431 5432 if (checkVAStartABI(*this, BuiltinID, Fn)) 5433 return true; 5434 5435 if (TheCall->getNumArgs() > 2) { 5436 Diag(TheCall->getArg(2)->getBeginLoc(), 5437 diag::err_typecheck_call_too_many_args) 5438 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5439 << Fn->getSourceRange() 5440 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5441 (*(TheCall->arg_end() - 1))->getEndLoc()); 5442 return true; 5443 } 5444 5445 if (TheCall->getNumArgs() < 2) { 5446 return Diag(TheCall->getEndLoc(), 5447 diag::err_typecheck_call_too_few_args_at_least) 5448 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5449 } 5450 5451 // Type-check the first argument normally. 5452 if (checkBuiltinArgument(*this, TheCall, 0)) 5453 return true; 5454 5455 // Check that the current function is variadic, and get its last parameter. 5456 ParmVarDecl *LastParam; 5457 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5458 return true; 5459 5460 // Verify that the second argument to the builtin is the last argument of the 5461 // current function or method. 5462 bool SecondArgIsLastNamedArgument = false; 5463 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5464 5465 // These are valid if SecondArgIsLastNamedArgument is false after the next 5466 // block. 5467 QualType Type; 5468 SourceLocation ParamLoc; 5469 bool IsCRegister = false; 5470 5471 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5472 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5473 SecondArgIsLastNamedArgument = PV == LastParam; 5474 5475 Type = PV->getType(); 5476 ParamLoc = PV->getLocation(); 5477 IsCRegister = 5478 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5479 } 5480 } 5481 5482 if (!SecondArgIsLastNamedArgument) 5483 Diag(TheCall->getArg(1)->getBeginLoc(), 5484 diag::warn_second_arg_of_va_start_not_last_named_param); 5485 else if (IsCRegister || Type->isReferenceType() || 5486 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5487 // Promotable integers are UB, but enumerations need a bit of 5488 // extra checking to see what their promotable type actually is. 5489 if (!Type->isPromotableIntegerType()) 5490 return false; 5491 if (!Type->isEnumeralType()) 5492 return true; 5493 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5494 return !(ED && 5495 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5496 }()) { 5497 unsigned Reason = 0; 5498 if (Type->isReferenceType()) Reason = 1; 5499 else if (IsCRegister) Reason = 2; 5500 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5501 Diag(ParamLoc, diag::note_parameter_type) << Type; 5502 } 5503 5504 TheCall->setType(Context.VoidTy); 5505 return false; 5506 } 5507 5508 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5509 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5510 // const char *named_addr); 5511 5512 Expr *Func = Call->getCallee(); 5513 5514 if (Call->getNumArgs() < 3) 5515 return Diag(Call->getEndLoc(), 5516 diag::err_typecheck_call_too_few_args_at_least) 5517 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5518 5519 // Type-check the first argument normally. 5520 if (checkBuiltinArgument(*this, Call, 0)) 5521 return true; 5522 5523 // Check that the current function is variadic. 5524 if (checkVAStartIsInVariadicFunction(*this, Func)) 5525 return true; 5526 5527 // __va_start on Windows does not validate the parameter qualifiers 5528 5529 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5530 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5531 5532 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5533 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5534 5535 const QualType &ConstCharPtrTy = 5536 Context.getPointerType(Context.CharTy.withConst()); 5537 if (!Arg1Ty->isPointerType() || 5538 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5539 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5540 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5541 << 0 /* qualifier difference */ 5542 << 3 /* parameter mismatch */ 5543 << 2 << Arg1->getType() << ConstCharPtrTy; 5544 5545 const QualType SizeTy = Context.getSizeType(); 5546 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5547 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5548 << Arg2->getType() << SizeTy << 1 /* different class */ 5549 << 0 /* qualifier difference */ 5550 << 3 /* parameter mismatch */ 5551 << 3 << Arg2->getType() << SizeTy; 5552 5553 return false; 5554 } 5555 5556 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5557 /// friends. This is declared to take (...), so we have to check everything. 5558 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5559 if (TheCall->getNumArgs() < 2) 5560 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5561 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5562 if (TheCall->getNumArgs() > 2) 5563 return Diag(TheCall->getArg(2)->getBeginLoc(), 5564 diag::err_typecheck_call_too_many_args) 5565 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5566 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5567 (*(TheCall->arg_end() - 1))->getEndLoc()); 5568 5569 ExprResult OrigArg0 = TheCall->getArg(0); 5570 ExprResult OrigArg1 = TheCall->getArg(1); 5571 5572 // Do standard promotions between the two arguments, returning their common 5573 // type. 5574 QualType Res = UsualArithmeticConversions( 5575 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5576 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5577 return true; 5578 5579 // Make sure any conversions are pushed back into the call; this is 5580 // type safe since unordered compare builtins are declared as "_Bool 5581 // foo(...)". 5582 TheCall->setArg(0, OrigArg0.get()); 5583 TheCall->setArg(1, OrigArg1.get()); 5584 5585 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5586 return false; 5587 5588 // If the common type isn't a real floating type, then the arguments were 5589 // invalid for this operation. 5590 if (Res.isNull() || !Res->isRealFloatingType()) 5591 return Diag(OrigArg0.get()->getBeginLoc(), 5592 diag::err_typecheck_call_invalid_ordered_compare) 5593 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5594 << SourceRange(OrigArg0.get()->getBeginLoc(), 5595 OrigArg1.get()->getEndLoc()); 5596 5597 return false; 5598 } 5599 5600 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5601 /// __builtin_isnan and friends. This is declared to take (...), so we have 5602 /// to check everything. We expect the last argument to be a floating point 5603 /// value. 5604 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5605 if (TheCall->getNumArgs() < NumArgs) 5606 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5607 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5608 if (TheCall->getNumArgs() > NumArgs) 5609 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5610 diag::err_typecheck_call_too_many_args) 5611 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5612 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5613 (*(TheCall->arg_end() - 1))->getEndLoc()); 5614 5615 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5616 // on all preceding parameters just being int. Try all of those. 5617 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5618 Expr *Arg = TheCall->getArg(i); 5619 5620 if (Arg->isTypeDependent()) 5621 return false; 5622 5623 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5624 5625 if (Res.isInvalid()) 5626 return true; 5627 TheCall->setArg(i, Res.get()); 5628 } 5629 5630 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5631 5632 if (OrigArg->isTypeDependent()) 5633 return false; 5634 5635 // Usual Unary Conversions will convert half to float, which we want for 5636 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5637 // type how it is, but do normal L->Rvalue conversions. 5638 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5639 OrigArg = UsualUnaryConversions(OrigArg).get(); 5640 else 5641 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5642 TheCall->setArg(NumArgs - 1, OrigArg); 5643 5644 // This operation requires a non-_Complex floating-point number. 5645 if (!OrigArg->getType()->isRealFloatingType()) 5646 return Diag(OrigArg->getBeginLoc(), 5647 diag::err_typecheck_call_invalid_unary_fp) 5648 << OrigArg->getType() << OrigArg->getSourceRange(); 5649 5650 return false; 5651 } 5652 5653 // Customized Sema Checking for VSX builtins that have the following signature: 5654 // vector [...] builtinName(vector [...], vector [...], const int); 5655 // Which takes the same type of vectors (any legal vector type) for the first 5656 // two arguments and takes compile time constant for the third argument. 5657 // Example builtins are : 5658 // vector double vec_xxpermdi(vector double, vector double, int); 5659 // vector short vec_xxsldwi(vector short, vector short, int); 5660 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5661 unsigned ExpectedNumArgs = 3; 5662 if (TheCall->getNumArgs() < ExpectedNumArgs) 5663 return Diag(TheCall->getEndLoc(), 5664 diag::err_typecheck_call_too_few_args_at_least) 5665 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5666 << TheCall->getSourceRange(); 5667 5668 if (TheCall->getNumArgs() > ExpectedNumArgs) 5669 return Diag(TheCall->getEndLoc(), 5670 diag::err_typecheck_call_too_many_args_at_most) 5671 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5672 << TheCall->getSourceRange(); 5673 5674 // Check the third argument is a compile time constant 5675 llvm::APSInt Value; 5676 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5677 return Diag(TheCall->getBeginLoc(), 5678 diag::err_vsx_builtin_nonconstant_argument) 5679 << 3 /* argument index */ << TheCall->getDirectCallee() 5680 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5681 TheCall->getArg(2)->getEndLoc()); 5682 5683 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5684 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5685 5686 // Check the type of argument 1 and argument 2 are vectors. 5687 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5688 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5689 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5690 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5691 << TheCall->getDirectCallee() 5692 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5693 TheCall->getArg(1)->getEndLoc()); 5694 } 5695 5696 // Check the first two arguments are the same type. 5697 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5698 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5699 << TheCall->getDirectCallee() 5700 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5701 TheCall->getArg(1)->getEndLoc()); 5702 } 5703 5704 // When default clang type checking is turned off and the customized type 5705 // checking is used, the returning type of the function must be explicitly 5706 // set. Otherwise it is _Bool by default. 5707 TheCall->setType(Arg1Ty); 5708 5709 return false; 5710 } 5711 5712 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5713 // This is declared to take (...), so we have to check everything. 5714 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5715 if (TheCall->getNumArgs() < 2) 5716 return ExprError(Diag(TheCall->getEndLoc(), 5717 diag::err_typecheck_call_too_few_args_at_least) 5718 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5719 << TheCall->getSourceRange()); 5720 5721 // Determine which of the following types of shufflevector we're checking: 5722 // 1) unary, vector mask: (lhs, mask) 5723 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5724 QualType resType = TheCall->getArg(0)->getType(); 5725 unsigned numElements = 0; 5726 5727 if (!TheCall->getArg(0)->isTypeDependent() && 5728 !TheCall->getArg(1)->isTypeDependent()) { 5729 QualType LHSType = TheCall->getArg(0)->getType(); 5730 QualType RHSType = TheCall->getArg(1)->getType(); 5731 5732 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5733 return ExprError( 5734 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5735 << TheCall->getDirectCallee() 5736 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5737 TheCall->getArg(1)->getEndLoc())); 5738 5739 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5740 unsigned numResElements = TheCall->getNumArgs() - 2; 5741 5742 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5743 // with mask. If so, verify that RHS is an integer vector type with the 5744 // same number of elts as lhs. 5745 if (TheCall->getNumArgs() == 2) { 5746 if (!RHSType->hasIntegerRepresentation() || 5747 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5748 return ExprError(Diag(TheCall->getBeginLoc(), 5749 diag::err_vec_builtin_incompatible_vector) 5750 << TheCall->getDirectCallee() 5751 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5752 TheCall->getArg(1)->getEndLoc())); 5753 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5754 return ExprError(Diag(TheCall->getBeginLoc(), 5755 diag::err_vec_builtin_incompatible_vector) 5756 << TheCall->getDirectCallee() 5757 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5758 TheCall->getArg(1)->getEndLoc())); 5759 } else if (numElements != numResElements) { 5760 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5761 resType = Context.getVectorType(eltType, numResElements, 5762 VectorType::GenericVector); 5763 } 5764 } 5765 5766 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5767 if (TheCall->getArg(i)->isTypeDependent() || 5768 TheCall->getArg(i)->isValueDependent()) 5769 continue; 5770 5771 llvm::APSInt Result(32); 5772 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5773 return ExprError(Diag(TheCall->getBeginLoc(), 5774 diag::err_shufflevector_nonconstant_argument) 5775 << TheCall->getArg(i)->getSourceRange()); 5776 5777 // Allow -1 which will be translated to undef in the IR. 5778 if (Result.isSigned() && Result.isAllOnesValue()) 5779 continue; 5780 5781 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5782 return ExprError(Diag(TheCall->getBeginLoc(), 5783 diag::err_shufflevector_argument_too_large) 5784 << TheCall->getArg(i)->getSourceRange()); 5785 } 5786 5787 SmallVector<Expr*, 32> exprs; 5788 5789 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5790 exprs.push_back(TheCall->getArg(i)); 5791 TheCall->setArg(i, nullptr); 5792 } 5793 5794 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5795 TheCall->getCallee()->getBeginLoc(), 5796 TheCall->getRParenLoc()); 5797 } 5798 5799 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5800 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5801 SourceLocation BuiltinLoc, 5802 SourceLocation RParenLoc) { 5803 ExprValueKind VK = VK_RValue; 5804 ExprObjectKind OK = OK_Ordinary; 5805 QualType DstTy = TInfo->getType(); 5806 QualType SrcTy = E->getType(); 5807 5808 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5809 return ExprError(Diag(BuiltinLoc, 5810 diag::err_convertvector_non_vector) 5811 << E->getSourceRange()); 5812 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5813 return ExprError(Diag(BuiltinLoc, 5814 diag::err_convertvector_non_vector_type)); 5815 5816 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5817 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5818 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5819 if (SrcElts != DstElts) 5820 return ExprError(Diag(BuiltinLoc, 5821 diag::err_convertvector_incompatible_vector) 5822 << E->getSourceRange()); 5823 } 5824 5825 return new (Context) 5826 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5827 } 5828 5829 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5830 // This is declared to take (const void*, ...) and can take two 5831 // optional constant int args. 5832 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5833 unsigned NumArgs = TheCall->getNumArgs(); 5834 5835 if (NumArgs > 3) 5836 return Diag(TheCall->getEndLoc(), 5837 diag::err_typecheck_call_too_many_args_at_most) 5838 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5839 5840 // Argument 0 is checked for us and the remaining arguments must be 5841 // constant integers. 5842 for (unsigned i = 1; i != NumArgs; ++i) 5843 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5844 return true; 5845 5846 return false; 5847 } 5848 5849 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5850 // __assume does not evaluate its arguments, and should warn if its argument 5851 // has side effects. 5852 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5853 Expr *Arg = TheCall->getArg(0); 5854 if (Arg->isInstantiationDependent()) return false; 5855 5856 if (Arg->HasSideEffects(Context)) 5857 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5858 << Arg->getSourceRange() 5859 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5860 5861 return false; 5862 } 5863 5864 /// Handle __builtin_alloca_with_align. This is declared 5865 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5866 /// than 8. 5867 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5868 // The alignment must be a constant integer. 5869 Expr *Arg = TheCall->getArg(1); 5870 5871 // We can't check the value of a dependent argument. 5872 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5873 if (const auto *UE = 5874 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5875 if (UE->getKind() == UETT_AlignOf || 5876 UE->getKind() == UETT_PreferredAlignOf) 5877 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5878 << Arg->getSourceRange(); 5879 5880 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5881 5882 if (!Result.isPowerOf2()) 5883 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5884 << Arg->getSourceRange(); 5885 5886 if (Result < Context.getCharWidth()) 5887 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5888 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5889 5890 if (Result > std::numeric_limits<int32_t>::max()) 5891 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5892 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5893 } 5894 5895 return false; 5896 } 5897 5898 /// Handle __builtin_assume_aligned. This is declared 5899 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5900 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5901 unsigned NumArgs = TheCall->getNumArgs(); 5902 5903 if (NumArgs > 3) 5904 return Diag(TheCall->getEndLoc(), 5905 diag::err_typecheck_call_too_many_args_at_most) 5906 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5907 5908 // The alignment must be a constant integer. 5909 Expr *Arg = TheCall->getArg(1); 5910 5911 // We can't check the value of a dependent argument. 5912 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5913 llvm::APSInt Result; 5914 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5915 return true; 5916 5917 if (!Result.isPowerOf2()) 5918 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5919 << Arg->getSourceRange(); 5920 5921 if (Result > Sema::MaximumAlignment) 5922 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 5923 << Arg->getSourceRange() << Sema::MaximumAlignment; 5924 } 5925 5926 if (NumArgs > 2) { 5927 ExprResult Arg(TheCall->getArg(2)); 5928 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5929 Context.getSizeType(), false); 5930 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5931 if (Arg.isInvalid()) return true; 5932 TheCall->setArg(2, Arg.get()); 5933 } 5934 5935 return false; 5936 } 5937 5938 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5939 unsigned BuiltinID = 5940 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5941 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5942 5943 unsigned NumArgs = TheCall->getNumArgs(); 5944 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5945 if (NumArgs < NumRequiredArgs) { 5946 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5947 << 0 /* function call */ << NumRequiredArgs << NumArgs 5948 << TheCall->getSourceRange(); 5949 } 5950 if (NumArgs >= NumRequiredArgs + 0x100) { 5951 return Diag(TheCall->getEndLoc(), 5952 diag::err_typecheck_call_too_many_args_at_most) 5953 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5954 << TheCall->getSourceRange(); 5955 } 5956 unsigned i = 0; 5957 5958 // For formatting call, check buffer arg. 5959 if (!IsSizeCall) { 5960 ExprResult Arg(TheCall->getArg(i)); 5961 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5962 Context, Context.VoidPtrTy, false); 5963 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5964 if (Arg.isInvalid()) 5965 return true; 5966 TheCall->setArg(i, Arg.get()); 5967 i++; 5968 } 5969 5970 // Check string literal arg. 5971 unsigned FormatIdx = i; 5972 { 5973 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5974 if (Arg.isInvalid()) 5975 return true; 5976 TheCall->setArg(i, Arg.get()); 5977 i++; 5978 } 5979 5980 // Make sure variadic args are scalar. 5981 unsigned FirstDataArg = i; 5982 while (i < NumArgs) { 5983 ExprResult Arg = DefaultVariadicArgumentPromotion( 5984 TheCall->getArg(i), VariadicFunction, nullptr); 5985 if (Arg.isInvalid()) 5986 return true; 5987 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5988 if (ArgSize.getQuantity() >= 0x100) { 5989 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5990 << i << (int)ArgSize.getQuantity() << 0xff 5991 << TheCall->getSourceRange(); 5992 } 5993 TheCall->setArg(i, Arg.get()); 5994 i++; 5995 } 5996 5997 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5998 // call to avoid duplicate diagnostics. 5999 if (!IsSizeCall) { 6000 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6001 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6002 bool Success = CheckFormatArguments( 6003 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6004 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6005 CheckedVarArgs); 6006 if (!Success) 6007 return true; 6008 } 6009 6010 if (IsSizeCall) { 6011 TheCall->setType(Context.getSizeType()); 6012 } else { 6013 TheCall->setType(Context.VoidPtrTy); 6014 } 6015 return false; 6016 } 6017 6018 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6019 /// TheCall is a constant expression. 6020 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6021 llvm::APSInt &Result) { 6022 Expr *Arg = TheCall->getArg(ArgNum); 6023 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6024 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6025 6026 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6027 6028 if (!Arg->isIntegerConstantExpr(Result, Context)) 6029 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6030 << FDecl->getDeclName() << Arg->getSourceRange(); 6031 6032 return false; 6033 } 6034 6035 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6036 /// TheCall is a constant expression in the range [Low, High]. 6037 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6038 int Low, int High, bool RangeIsError) { 6039 if (isConstantEvaluated()) 6040 return false; 6041 llvm::APSInt Result; 6042 6043 // We can't check the value of a dependent argument. 6044 Expr *Arg = TheCall->getArg(ArgNum); 6045 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6046 return false; 6047 6048 // Check constant-ness first. 6049 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6050 return true; 6051 6052 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6053 if (RangeIsError) 6054 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6055 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6056 else 6057 // Defer the warning until we know if the code will be emitted so that 6058 // dead code can ignore this. 6059 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6060 PDiag(diag::warn_argument_invalid_range) 6061 << Result.toString(10) << Low << High 6062 << Arg->getSourceRange()); 6063 } 6064 6065 return false; 6066 } 6067 6068 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6069 /// TheCall is a constant expression is a multiple of Num.. 6070 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6071 unsigned Num) { 6072 llvm::APSInt Result; 6073 6074 // We can't check the value of a dependent argument. 6075 Expr *Arg = TheCall->getArg(ArgNum); 6076 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6077 return false; 6078 6079 // Check constant-ness first. 6080 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6081 return true; 6082 6083 if (Result.getSExtValue() % Num != 0) 6084 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6085 << Num << Arg->getSourceRange(); 6086 6087 return false; 6088 } 6089 6090 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6091 /// constant expression representing a power of 2. 6092 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6093 llvm::APSInt Result; 6094 6095 // We can't check the value of a dependent argument. 6096 Expr *Arg = TheCall->getArg(ArgNum); 6097 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6098 return false; 6099 6100 // Check constant-ness first. 6101 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6102 return true; 6103 6104 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6105 // and only if x is a power of 2. 6106 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6107 return false; 6108 6109 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6110 << Arg->getSourceRange(); 6111 } 6112 6113 static bool IsShiftedByte(llvm::APSInt Value) { 6114 if (Value.isNegative()) 6115 return false; 6116 6117 // Check if it's a shifted byte, by shifting it down 6118 while (true) { 6119 // If the value fits in the bottom byte, the check passes. 6120 if (Value < 0x100) 6121 return true; 6122 6123 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6124 // fails. 6125 if ((Value & 0xFF) != 0) 6126 return false; 6127 6128 // If the bottom 8 bits are all 0, but something above that is nonzero, 6129 // then shifting the value right by 8 bits won't affect whether it's a 6130 // shifted byte or not. So do that, and go round again. 6131 Value >>= 8; 6132 } 6133 } 6134 6135 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6136 /// a constant expression representing an arbitrary byte value shifted left by 6137 /// a multiple of 8 bits. 6138 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6139 unsigned ArgBits) { 6140 llvm::APSInt Result; 6141 6142 // We can't check the value of a dependent argument. 6143 Expr *Arg = TheCall->getArg(ArgNum); 6144 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6145 return false; 6146 6147 // Check constant-ness first. 6148 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6149 return true; 6150 6151 // Truncate to the given size. 6152 Result = Result.getLoBits(ArgBits); 6153 Result.setIsUnsigned(true); 6154 6155 if (IsShiftedByte(Result)) 6156 return false; 6157 6158 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6159 << Arg->getSourceRange(); 6160 } 6161 6162 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6163 /// TheCall is a constant expression representing either a shifted byte value, 6164 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6165 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6166 /// Arm MVE intrinsics. 6167 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6168 int ArgNum, 6169 unsigned ArgBits) { 6170 llvm::APSInt Result; 6171 6172 // We can't check the value of a dependent argument. 6173 Expr *Arg = TheCall->getArg(ArgNum); 6174 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6175 return false; 6176 6177 // Check constant-ness first. 6178 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6179 return true; 6180 6181 // Truncate to the given size. 6182 Result = Result.getLoBits(ArgBits); 6183 Result.setIsUnsigned(true); 6184 6185 // Check to see if it's in either of the required forms. 6186 if (IsShiftedByte(Result) || 6187 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6188 return false; 6189 6190 return Diag(TheCall->getBeginLoc(), 6191 diag::err_argument_not_shifted_byte_or_xxff) 6192 << Arg->getSourceRange(); 6193 } 6194 6195 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6196 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6197 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6198 if (checkArgCount(*this, TheCall, 2)) 6199 return true; 6200 Expr *Arg0 = TheCall->getArg(0); 6201 Expr *Arg1 = TheCall->getArg(1); 6202 6203 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6204 if (FirstArg.isInvalid()) 6205 return true; 6206 QualType FirstArgType = FirstArg.get()->getType(); 6207 if (!FirstArgType->isAnyPointerType()) 6208 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6209 << "first" << FirstArgType << Arg0->getSourceRange(); 6210 TheCall->setArg(0, FirstArg.get()); 6211 6212 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6213 if (SecArg.isInvalid()) 6214 return true; 6215 QualType SecArgType = SecArg.get()->getType(); 6216 if (!SecArgType->isIntegerType()) 6217 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6218 << "second" << SecArgType << Arg1->getSourceRange(); 6219 6220 // Derive the return type from the pointer argument. 6221 TheCall->setType(FirstArgType); 6222 return false; 6223 } 6224 6225 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6226 if (checkArgCount(*this, TheCall, 2)) 6227 return true; 6228 6229 Expr *Arg0 = TheCall->getArg(0); 6230 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6231 if (FirstArg.isInvalid()) 6232 return true; 6233 QualType FirstArgType = FirstArg.get()->getType(); 6234 if (!FirstArgType->isAnyPointerType()) 6235 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6236 << "first" << FirstArgType << Arg0->getSourceRange(); 6237 TheCall->setArg(0, FirstArg.get()); 6238 6239 // Derive the return type from the pointer argument. 6240 TheCall->setType(FirstArgType); 6241 6242 // Second arg must be an constant in range [0,15] 6243 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6244 } 6245 6246 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6247 if (checkArgCount(*this, TheCall, 2)) 6248 return true; 6249 Expr *Arg0 = TheCall->getArg(0); 6250 Expr *Arg1 = TheCall->getArg(1); 6251 6252 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6253 if (FirstArg.isInvalid()) 6254 return true; 6255 QualType FirstArgType = FirstArg.get()->getType(); 6256 if (!FirstArgType->isAnyPointerType()) 6257 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6258 << "first" << FirstArgType << Arg0->getSourceRange(); 6259 6260 QualType SecArgType = Arg1->getType(); 6261 if (!SecArgType->isIntegerType()) 6262 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6263 << "second" << SecArgType << Arg1->getSourceRange(); 6264 TheCall->setType(Context.IntTy); 6265 return false; 6266 } 6267 6268 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6269 BuiltinID == AArch64::BI__builtin_arm_stg) { 6270 if (checkArgCount(*this, TheCall, 1)) 6271 return true; 6272 Expr *Arg0 = TheCall->getArg(0); 6273 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6274 if (FirstArg.isInvalid()) 6275 return true; 6276 6277 QualType FirstArgType = FirstArg.get()->getType(); 6278 if (!FirstArgType->isAnyPointerType()) 6279 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6280 << "first" << FirstArgType << Arg0->getSourceRange(); 6281 TheCall->setArg(0, FirstArg.get()); 6282 6283 // Derive the return type from the pointer argument. 6284 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6285 TheCall->setType(FirstArgType); 6286 return false; 6287 } 6288 6289 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6290 Expr *ArgA = TheCall->getArg(0); 6291 Expr *ArgB = TheCall->getArg(1); 6292 6293 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6294 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6295 6296 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6297 return true; 6298 6299 QualType ArgTypeA = ArgExprA.get()->getType(); 6300 QualType ArgTypeB = ArgExprB.get()->getType(); 6301 6302 auto isNull = [&] (Expr *E) -> bool { 6303 return E->isNullPointerConstant( 6304 Context, Expr::NPC_ValueDependentIsNotNull); }; 6305 6306 // argument should be either a pointer or null 6307 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6308 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6309 << "first" << ArgTypeA << ArgA->getSourceRange(); 6310 6311 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6312 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6313 << "second" << ArgTypeB << ArgB->getSourceRange(); 6314 6315 // Ensure Pointee types are compatible 6316 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6317 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6318 QualType pointeeA = ArgTypeA->getPointeeType(); 6319 QualType pointeeB = ArgTypeB->getPointeeType(); 6320 if (!Context.typesAreCompatible( 6321 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6322 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6323 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6324 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6325 << ArgB->getSourceRange(); 6326 } 6327 } 6328 6329 // at least one argument should be pointer type 6330 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6331 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6332 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6333 6334 if (isNull(ArgA)) // adopt type of the other pointer 6335 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6336 6337 if (isNull(ArgB)) 6338 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6339 6340 TheCall->setArg(0, ArgExprA.get()); 6341 TheCall->setArg(1, ArgExprB.get()); 6342 TheCall->setType(Context.LongLongTy); 6343 return false; 6344 } 6345 assert(false && "Unhandled ARM MTE intrinsic"); 6346 return true; 6347 } 6348 6349 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6350 /// TheCall is an ARM/AArch64 special register string literal. 6351 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6352 int ArgNum, unsigned ExpectedFieldNum, 6353 bool AllowName) { 6354 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6355 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6356 BuiltinID == ARM::BI__builtin_arm_rsr || 6357 BuiltinID == ARM::BI__builtin_arm_rsrp || 6358 BuiltinID == ARM::BI__builtin_arm_wsr || 6359 BuiltinID == ARM::BI__builtin_arm_wsrp; 6360 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6361 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6362 BuiltinID == AArch64::BI__builtin_arm_rsr || 6363 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6364 BuiltinID == AArch64::BI__builtin_arm_wsr || 6365 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6366 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6367 6368 // We can't check the value of a dependent argument. 6369 Expr *Arg = TheCall->getArg(ArgNum); 6370 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6371 return false; 6372 6373 // Check if the argument is a string literal. 6374 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6375 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6376 << Arg->getSourceRange(); 6377 6378 // Check the type of special register given. 6379 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6380 SmallVector<StringRef, 6> Fields; 6381 Reg.split(Fields, ":"); 6382 6383 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6384 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6385 << Arg->getSourceRange(); 6386 6387 // If the string is the name of a register then we cannot check that it is 6388 // valid here but if the string is of one the forms described in ACLE then we 6389 // can check that the supplied fields are integers and within the valid 6390 // ranges. 6391 if (Fields.size() > 1) { 6392 bool FiveFields = Fields.size() == 5; 6393 6394 bool ValidString = true; 6395 if (IsARMBuiltin) { 6396 ValidString &= Fields[0].startswith_lower("cp") || 6397 Fields[0].startswith_lower("p"); 6398 if (ValidString) 6399 Fields[0] = 6400 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6401 6402 ValidString &= Fields[2].startswith_lower("c"); 6403 if (ValidString) 6404 Fields[2] = Fields[2].drop_front(1); 6405 6406 if (FiveFields) { 6407 ValidString &= Fields[3].startswith_lower("c"); 6408 if (ValidString) 6409 Fields[3] = Fields[3].drop_front(1); 6410 } 6411 } 6412 6413 SmallVector<int, 5> Ranges; 6414 if (FiveFields) 6415 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6416 else 6417 Ranges.append({15, 7, 15}); 6418 6419 for (unsigned i=0; i<Fields.size(); ++i) { 6420 int IntField; 6421 ValidString &= !Fields[i].getAsInteger(10, IntField); 6422 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6423 } 6424 6425 if (!ValidString) 6426 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6427 << Arg->getSourceRange(); 6428 } else if (IsAArch64Builtin && Fields.size() == 1) { 6429 // If the register name is one of those that appear in the condition below 6430 // and the special register builtin being used is one of the write builtins, 6431 // then we require that the argument provided for writing to the register 6432 // is an integer constant expression. This is because it will be lowered to 6433 // an MSR (immediate) instruction, so we need to know the immediate at 6434 // compile time. 6435 if (TheCall->getNumArgs() != 2) 6436 return false; 6437 6438 std::string RegLower = Reg.lower(); 6439 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6440 RegLower != "pan" && RegLower != "uao") 6441 return false; 6442 6443 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6444 } 6445 6446 return false; 6447 } 6448 6449 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6450 /// This checks that the target supports __builtin_longjmp and 6451 /// that val is a constant 1. 6452 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6453 if (!Context.getTargetInfo().hasSjLjLowering()) 6454 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6455 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6456 6457 Expr *Arg = TheCall->getArg(1); 6458 llvm::APSInt Result; 6459 6460 // TODO: This is less than ideal. Overload this to take a value. 6461 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6462 return true; 6463 6464 if (Result != 1) 6465 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6466 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6467 6468 return false; 6469 } 6470 6471 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6472 /// This checks that the target supports __builtin_setjmp. 6473 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6474 if (!Context.getTargetInfo().hasSjLjLowering()) 6475 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6476 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6477 return false; 6478 } 6479 6480 namespace { 6481 6482 class UncoveredArgHandler { 6483 enum { Unknown = -1, AllCovered = -2 }; 6484 6485 signed FirstUncoveredArg = Unknown; 6486 SmallVector<const Expr *, 4> DiagnosticExprs; 6487 6488 public: 6489 UncoveredArgHandler() = default; 6490 6491 bool hasUncoveredArg() const { 6492 return (FirstUncoveredArg >= 0); 6493 } 6494 6495 unsigned getUncoveredArg() const { 6496 assert(hasUncoveredArg() && "no uncovered argument"); 6497 return FirstUncoveredArg; 6498 } 6499 6500 void setAllCovered() { 6501 // A string has been found with all arguments covered, so clear out 6502 // the diagnostics. 6503 DiagnosticExprs.clear(); 6504 FirstUncoveredArg = AllCovered; 6505 } 6506 6507 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6508 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6509 6510 // Don't update if a previous string covers all arguments. 6511 if (FirstUncoveredArg == AllCovered) 6512 return; 6513 6514 // UncoveredArgHandler tracks the highest uncovered argument index 6515 // and with it all the strings that match this index. 6516 if (NewFirstUncoveredArg == FirstUncoveredArg) 6517 DiagnosticExprs.push_back(StrExpr); 6518 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6519 DiagnosticExprs.clear(); 6520 DiagnosticExprs.push_back(StrExpr); 6521 FirstUncoveredArg = NewFirstUncoveredArg; 6522 } 6523 } 6524 6525 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6526 }; 6527 6528 enum StringLiteralCheckType { 6529 SLCT_NotALiteral, 6530 SLCT_UncheckedLiteral, 6531 SLCT_CheckedLiteral 6532 }; 6533 6534 } // namespace 6535 6536 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6537 BinaryOperatorKind BinOpKind, 6538 bool AddendIsRight) { 6539 unsigned BitWidth = Offset.getBitWidth(); 6540 unsigned AddendBitWidth = Addend.getBitWidth(); 6541 // There might be negative interim results. 6542 if (Addend.isUnsigned()) { 6543 Addend = Addend.zext(++AddendBitWidth); 6544 Addend.setIsSigned(true); 6545 } 6546 // Adjust the bit width of the APSInts. 6547 if (AddendBitWidth > BitWidth) { 6548 Offset = Offset.sext(AddendBitWidth); 6549 BitWidth = AddendBitWidth; 6550 } else if (BitWidth > AddendBitWidth) { 6551 Addend = Addend.sext(BitWidth); 6552 } 6553 6554 bool Ov = false; 6555 llvm::APSInt ResOffset = Offset; 6556 if (BinOpKind == BO_Add) 6557 ResOffset = Offset.sadd_ov(Addend, Ov); 6558 else { 6559 assert(AddendIsRight && BinOpKind == BO_Sub && 6560 "operator must be add or sub with addend on the right"); 6561 ResOffset = Offset.ssub_ov(Addend, Ov); 6562 } 6563 6564 // We add an offset to a pointer here so we should support an offset as big as 6565 // possible. 6566 if (Ov) { 6567 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6568 "index (intermediate) result too big"); 6569 Offset = Offset.sext(2 * BitWidth); 6570 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6571 return; 6572 } 6573 6574 Offset = ResOffset; 6575 } 6576 6577 namespace { 6578 6579 // This is a wrapper class around StringLiteral to support offsetted string 6580 // literals as format strings. It takes the offset into account when returning 6581 // the string and its length or the source locations to display notes correctly. 6582 class FormatStringLiteral { 6583 const StringLiteral *FExpr; 6584 int64_t Offset; 6585 6586 public: 6587 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6588 : FExpr(fexpr), Offset(Offset) {} 6589 6590 StringRef getString() const { 6591 return FExpr->getString().drop_front(Offset); 6592 } 6593 6594 unsigned getByteLength() const { 6595 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6596 } 6597 6598 unsigned getLength() const { return FExpr->getLength() - Offset; } 6599 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6600 6601 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6602 6603 QualType getType() const { return FExpr->getType(); } 6604 6605 bool isAscii() const { return FExpr->isAscii(); } 6606 bool isWide() const { return FExpr->isWide(); } 6607 bool isUTF8() const { return FExpr->isUTF8(); } 6608 bool isUTF16() const { return FExpr->isUTF16(); } 6609 bool isUTF32() const { return FExpr->isUTF32(); } 6610 bool isPascal() const { return FExpr->isPascal(); } 6611 6612 SourceLocation getLocationOfByte( 6613 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6614 const TargetInfo &Target, unsigned *StartToken = nullptr, 6615 unsigned *StartTokenByteOffset = nullptr) const { 6616 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6617 StartToken, StartTokenByteOffset); 6618 } 6619 6620 SourceLocation getBeginLoc() const LLVM_READONLY { 6621 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6622 } 6623 6624 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6625 }; 6626 6627 } // namespace 6628 6629 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6630 const Expr *OrigFormatExpr, 6631 ArrayRef<const Expr *> Args, 6632 bool HasVAListArg, unsigned format_idx, 6633 unsigned firstDataArg, 6634 Sema::FormatStringType Type, 6635 bool inFunctionCall, 6636 Sema::VariadicCallType CallType, 6637 llvm::SmallBitVector &CheckedVarArgs, 6638 UncoveredArgHandler &UncoveredArg, 6639 bool IgnoreStringsWithoutSpecifiers); 6640 6641 // Determine if an expression is a string literal or constant string. 6642 // If this function returns false on the arguments to a function expecting a 6643 // format string, we will usually need to emit a warning. 6644 // True string literals are then checked by CheckFormatString. 6645 static StringLiteralCheckType 6646 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6647 bool HasVAListArg, unsigned format_idx, 6648 unsigned firstDataArg, Sema::FormatStringType Type, 6649 Sema::VariadicCallType CallType, bool InFunctionCall, 6650 llvm::SmallBitVector &CheckedVarArgs, 6651 UncoveredArgHandler &UncoveredArg, 6652 llvm::APSInt Offset, 6653 bool IgnoreStringsWithoutSpecifiers = false) { 6654 if (S.isConstantEvaluated()) 6655 return SLCT_NotALiteral; 6656 tryAgain: 6657 assert(Offset.isSigned() && "invalid offset"); 6658 6659 if (E->isTypeDependent() || E->isValueDependent()) 6660 return SLCT_NotALiteral; 6661 6662 E = E->IgnoreParenCasts(); 6663 6664 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6665 // Technically -Wformat-nonliteral does not warn about this case. 6666 // The behavior of printf and friends in this case is implementation 6667 // dependent. Ideally if the format string cannot be null then 6668 // it should have a 'nonnull' attribute in the function prototype. 6669 return SLCT_UncheckedLiteral; 6670 6671 switch (E->getStmtClass()) { 6672 case Stmt::BinaryConditionalOperatorClass: 6673 case Stmt::ConditionalOperatorClass: { 6674 // The expression is a literal if both sub-expressions were, and it was 6675 // completely checked only if both sub-expressions were checked. 6676 const AbstractConditionalOperator *C = 6677 cast<AbstractConditionalOperator>(E); 6678 6679 // Determine whether it is necessary to check both sub-expressions, for 6680 // example, because the condition expression is a constant that can be 6681 // evaluated at compile time. 6682 bool CheckLeft = true, CheckRight = true; 6683 6684 bool Cond; 6685 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6686 S.isConstantEvaluated())) { 6687 if (Cond) 6688 CheckRight = false; 6689 else 6690 CheckLeft = false; 6691 } 6692 6693 // We need to maintain the offsets for the right and the left hand side 6694 // separately to check if every possible indexed expression is a valid 6695 // string literal. They might have different offsets for different string 6696 // literals in the end. 6697 StringLiteralCheckType Left; 6698 if (!CheckLeft) 6699 Left = SLCT_UncheckedLiteral; 6700 else { 6701 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6702 HasVAListArg, format_idx, firstDataArg, 6703 Type, CallType, InFunctionCall, 6704 CheckedVarArgs, UncoveredArg, Offset, 6705 IgnoreStringsWithoutSpecifiers); 6706 if (Left == SLCT_NotALiteral || !CheckRight) { 6707 return Left; 6708 } 6709 } 6710 6711 StringLiteralCheckType Right = checkFormatStringExpr( 6712 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6713 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6714 IgnoreStringsWithoutSpecifiers); 6715 6716 return (CheckLeft && Left < Right) ? Left : Right; 6717 } 6718 6719 case Stmt::ImplicitCastExprClass: 6720 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6721 goto tryAgain; 6722 6723 case Stmt::OpaqueValueExprClass: 6724 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6725 E = src; 6726 goto tryAgain; 6727 } 6728 return SLCT_NotALiteral; 6729 6730 case Stmt::PredefinedExprClass: 6731 // While __func__, etc., are technically not string literals, they 6732 // cannot contain format specifiers and thus are not a security 6733 // liability. 6734 return SLCT_UncheckedLiteral; 6735 6736 case Stmt::DeclRefExprClass: { 6737 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6738 6739 // As an exception, do not flag errors for variables binding to 6740 // const string literals. 6741 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6742 bool isConstant = false; 6743 QualType T = DR->getType(); 6744 6745 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6746 isConstant = AT->getElementType().isConstant(S.Context); 6747 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6748 isConstant = T.isConstant(S.Context) && 6749 PT->getPointeeType().isConstant(S.Context); 6750 } else if (T->isObjCObjectPointerType()) { 6751 // In ObjC, there is usually no "const ObjectPointer" type, 6752 // so don't check if the pointee type is constant. 6753 isConstant = T.isConstant(S.Context); 6754 } 6755 6756 if (isConstant) { 6757 if (const Expr *Init = VD->getAnyInitializer()) { 6758 // Look through initializers like const char c[] = { "foo" } 6759 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6760 if (InitList->isStringLiteralInit()) 6761 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6762 } 6763 return checkFormatStringExpr(S, Init, Args, 6764 HasVAListArg, format_idx, 6765 firstDataArg, Type, CallType, 6766 /*InFunctionCall*/ false, CheckedVarArgs, 6767 UncoveredArg, Offset); 6768 } 6769 } 6770 6771 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6772 // special check to see if the format string is a function parameter 6773 // of the function calling the printf function. If the function 6774 // has an attribute indicating it is a printf-like function, then we 6775 // should suppress warnings concerning non-literals being used in a call 6776 // to a vprintf function. For example: 6777 // 6778 // void 6779 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6780 // va_list ap; 6781 // va_start(ap, fmt); 6782 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6783 // ... 6784 // } 6785 if (HasVAListArg) { 6786 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6787 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6788 int PVIndex = PV->getFunctionScopeIndex() + 1; 6789 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6790 // adjust for implicit parameter 6791 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6792 if (MD->isInstance()) 6793 ++PVIndex; 6794 // We also check if the formats are compatible. 6795 // We can't pass a 'scanf' string to a 'printf' function. 6796 if (PVIndex == PVFormat->getFormatIdx() && 6797 Type == S.GetFormatStringType(PVFormat)) 6798 return SLCT_UncheckedLiteral; 6799 } 6800 } 6801 } 6802 } 6803 } 6804 6805 return SLCT_NotALiteral; 6806 } 6807 6808 case Stmt::CallExprClass: 6809 case Stmt::CXXMemberCallExprClass: { 6810 const CallExpr *CE = cast<CallExpr>(E); 6811 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6812 bool IsFirst = true; 6813 StringLiteralCheckType CommonResult; 6814 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6815 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6816 StringLiteralCheckType Result = checkFormatStringExpr( 6817 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6818 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6819 IgnoreStringsWithoutSpecifiers); 6820 if (IsFirst) { 6821 CommonResult = Result; 6822 IsFirst = false; 6823 } 6824 } 6825 if (!IsFirst) 6826 return CommonResult; 6827 6828 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6829 unsigned BuiltinID = FD->getBuiltinID(); 6830 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6831 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6832 const Expr *Arg = CE->getArg(0); 6833 return checkFormatStringExpr(S, Arg, Args, 6834 HasVAListArg, format_idx, 6835 firstDataArg, Type, CallType, 6836 InFunctionCall, CheckedVarArgs, 6837 UncoveredArg, Offset, 6838 IgnoreStringsWithoutSpecifiers); 6839 } 6840 } 6841 } 6842 6843 return SLCT_NotALiteral; 6844 } 6845 case Stmt::ObjCMessageExprClass: { 6846 const auto *ME = cast<ObjCMessageExpr>(E); 6847 if (const auto *MD = ME->getMethodDecl()) { 6848 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 6849 // As a special case heuristic, if we're using the method -[NSBundle 6850 // localizedStringForKey:value:table:], ignore any key strings that lack 6851 // format specifiers. The idea is that if the key doesn't have any 6852 // format specifiers then its probably just a key to map to the 6853 // localized strings. If it does have format specifiers though, then its 6854 // likely that the text of the key is the format string in the 6855 // programmer's language, and should be checked. 6856 const ObjCInterfaceDecl *IFace; 6857 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 6858 IFace->getIdentifier()->isStr("NSBundle") && 6859 MD->getSelector().isKeywordSelector( 6860 {"localizedStringForKey", "value", "table"})) { 6861 IgnoreStringsWithoutSpecifiers = true; 6862 } 6863 6864 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6865 return checkFormatStringExpr( 6866 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6867 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6868 IgnoreStringsWithoutSpecifiers); 6869 } 6870 } 6871 6872 return SLCT_NotALiteral; 6873 } 6874 case Stmt::ObjCStringLiteralClass: 6875 case Stmt::StringLiteralClass: { 6876 const StringLiteral *StrE = nullptr; 6877 6878 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6879 StrE = ObjCFExpr->getString(); 6880 else 6881 StrE = cast<StringLiteral>(E); 6882 6883 if (StrE) { 6884 if (Offset.isNegative() || Offset > StrE->getLength()) { 6885 // TODO: It would be better to have an explicit warning for out of 6886 // bounds literals. 6887 return SLCT_NotALiteral; 6888 } 6889 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6890 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6891 firstDataArg, Type, InFunctionCall, CallType, 6892 CheckedVarArgs, UncoveredArg, 6893 IgnoreStringsWithoutSpecifiers); 6894 return SLCT_CheckedLiteral; 6895 } 6896 6897 return SLCT_NotALiteral; 6898 } 6899 case Stmt::BinaryOperatorClass: { 6900 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6901 6902 // A string literal + an int offset is still a string literal. 6903 if (BinOp->isAdditiveOp()) { 6904 Expr::EvalResult LResult, RResult; 6905 6906 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6907 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6908 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6909 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6910 6911 if (LIsInt != RIsInt) { 6912 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6913 6914 if (LIsInt) { 6915 if (BinOpKind == BO_Add) { 6916 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6917 E = BinOp->getRHS(); 6918 goto tryAgain; 6919 } 6920 } else { 6921 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6922 E = BinOp->getLHS(); 6923 goto tryAgain; 6924 } 6925 } 6926 } 6927 6928 return SLCT_NotALiteral; 6929 } 6930 case Stmt::UnaryOperatorClass: { 6931 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6932 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6933 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6934 Expr::EvalResult IndexResult; 6935 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6936 Expr::SE_NoSideEffects, 6937 S.isConstantEvaluated())) { 6938 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6939 /*RHS is int*/ true); 6940 E = ASE->getBase(); 6941 goto tryAgain; 6942 } 6943 } 6944 6945 return SLCT_NotALiteral; 6946 } 6947 6948 default: 6949 return SLCT_NotALiteral; 6950 } 6951 } 6952 6953 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6954 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6955 .Case("scanf", FST_Scanf) 6956 .Cases("printf", "printf0", FST_Printf) 6957 .Cases("NSString", "CFString", FST_NSString) 6958 .Case("strftime", FST_Strftime) 6959 .Case("strfmon", FST_Strfmon) 6960 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6961 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6962 .Case("os_trace", FST_OSLog) 6963 .Case("os_log", FST_OSLog) 6964 .Default(FST_Unknown); 6965 } 6966 6967 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6968 /// functions) for correct use of format strings. 6969 /// Returns true if a format string has been fully checked. 6970 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6971 ArrayRef<const Expr *> Args, 6972 bool IsCXXMember, 6973 VariadicCallType CallType, 6974 SourceLocation Loc, SourceRange Range, 6975 llvm::SmallBitVector &CheckedVarArgs) { 6976 FormatStringInfo FSI; 6977 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6978 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6979 FSI.FirstDataArg, GetFormatStringType(Format), 6980 CallType, Loc, Range, CheckedVarArgs); 6981 return false; 6982 } 6983 6984 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6985 bool HasVAListArg, unsigned format_idx, 6986 unsigned firstDataArg, FormatStringType Type, 6987 VariadicCallType CallType, 6988 SourceLocation Loc, SourceRange Range, 6989 llvm::SmallBitVector &CheckedVarArgs) { 6990 // CHECK: printf/scanf-like function is called with no format string. 6991 if (format_idx >= Args.size()) { 6992 Diag(Loc, diag::warn_missing_format_string) << Range; 6993 return false; 6994 } 6995 6996 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6997 6998 // CHECK: format string is not a string literal. 6999 // 7000 // Dynamically generated format strings are difficult to 7001 // automatically vet at compile time. Requiring that format strings 7002 // are string literals: (1) permits the checking of format strings by 7003 // the compiler and thereby (2) can practically remove the source of 7004 // many format string exploits. 7005 7006 // Format string can be either ObjC string (e.g. @"%d") or 7007 // C string (e.g. "%d") 7008 // ObjC string uses the same format specifiers as C string, so we can use 7009 // the same format string checking logic for both ObjC and C strings. 7010 UncoveredArgHandler UncoveredArg; 7011 StringLiteralCheckType CT = 7012 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7013 format_idx, firstDataArg, Type, CallType, 7014 /*IsFunctionCall*/ true, CheckedVarArgs, 7015 UncoveredArg, 7016 /*no string offset*/ llvm::APSInt(64, false) = 0); 7017 7018 // Generate a diagnostic where an uncovered argument is detected. 7019 if (UncoveredArg.hasUncoveredArg()) { 7020 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7021 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7022 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7023 } 7024 7025 if (CT != SLCT_NotALiteral) 7026 // Literal format string found, check done! 7027 return CT == SLCT_CheckedLiteral; 7028 7029 // Strftime is particular as it always uses a single 'time' argument, 7030 // so it is safe to pass a non-literal string. 7031 if (Type == FST_Strftime) 7032 return false; 7033 7034 // Do not emit diag when the string param is a macro expansion and the 7035 // format is either NSString or CFString. This is a hack to prevent 7036 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7037 // which are usually used in place of NS and CF string literals. 7038 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7039 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7040 return false; 7041 7042 // If there are no arguments specified, warn with -Wformat-security, otherwise 7043 // warn only with -Wformat-nonliteral. 7044 if (Args.size() == firstDataArg) { 7045 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7046 << OrigFormatExpr->getSourceRange(); 7047 switch (Type) { 7048 default: 7049 break; 7050 case FST_Kprintf: 7051 case FST_FreeBSDKPrintf: 7052 case FST_Printf: 7053 Diag(FormatLoc, diag::note_format_security_fixit) 7054 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7055 break; 7056 case FST_NSString: 7057 Diag(FormatLoc, diag::note_format_security_fixit) 7058 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7059 break; 7060 } 7061 } else { 7062 Diag(FormatLoc, diag::warn_format_nonliteral) 7063 << OrigFormatExpr->getSourceRange(); 7064 } 7065 return false; 7066 } 7067 7068 namespace { 7069 7070 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7071 protected: 7072 Sema &S; 7073 const FormatStringLiteral *FExpr; 7074 const Expr *OrigFormatExpr; 7075 const Sema::FormatStringType FSType; 7076 const unsigned FirstDataArg; 7077 const unsigned NumDataArgs; 7078 const char *Beg; // Start of format string. 7079 const bool HasVAListArg; 7080 ArrayRef<const Expr *> Args; 7081 unsigned FormatIdx; 7082 llvm::SmallBitVector CoveredArgs; 7083 bool usesPositionalArgs = false; 7084 bool atFirstArg = true; 7085 bool inFunctionCall; 7086 Sema::VariadicCallType CallType; 7087 llvm::SmallBitVector &CheckedVarArgs; 7088 UncoveredArgHandler &UncoveredArg; 7089 7090 public: 7091 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7092 const Expr *origFormatExpr, 7093 const Sema::FormatStringType type, unsigned firstDataArg, 7094 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7095 ArrayRef<const Expr *> Args, unsigned formatIdx, 7096 bool inFunctionCall, Sema::VariadicCallType callType, 7097 llvm::SmallBitVector &CheckedVarArgs, 7098 UncoveredArgHandler &UncoveredArg) 7099 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7100 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7101 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7102 inFunctionCall(inFunctionCall), CallType(callType), 7103 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7104 CoveredArgs.resize(numDataArgs); 7105 CoveredArgs.reset(); 7106 } 7107 7108 void DoneProcessing(); 7109 7110 void HandleIncompleteSpecifier(const char *startSpecifier, 7111 unsigned specifierLen) override; 7112 7113 void HandleInvalidLengthModifier( 7114 const analyze_format_string::FormatSpecifier &FS, 7115 const analyze_format_string::ConversionSpecifier &CS, 7116 const char *startSpecifier, unsigned specifierLen, 7117 unsigned DiagID); 7118 7119 void HandleNonStandardLengthModifier( 7120 const analyze_format_string::FormatSpecifier &FS, 7121 const char *startSpecifier, unsigned specifierLen); 7122 7123 void HandleNonStandardConversionSpecifier( 7124 const analyze_format_string::ConversionSpecifier &CS, 7125 const char *startSpecifier, unsigned specifierLen); 7126 7127 void HandlePosition(const char *startPos, unsigned posLen) override; 7128 7129 void HandleInvalidPosition(const char *startSpecifier, 7130 unsigned specifierLen, 7131 analyze_format_string::PositionContext p) override; 7132 7133 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7134 7135 void HandleNullChar(const char *nullCharacter) override; 7136 7137 template <typename Range> 7138 static void 7139 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7140 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7141 bool IsStringLocation, Range StringRange, 7142 ArrayRef<FixItHint> Fixit = None); 7143 7144 protected: 7145 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7146 const char *startSpec, 7147 unsigned specifierLen, 7148 const char *csStart, unsigned csLen); 7149 7150 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7151 const char *startSpec, 7152 unsigned specifierLen); 7153 7154 SourceRange getFormatStringRange(); 7155 CharSourceRange getSpecifierRange(const char *startSpecifier, 7156 unsigned specifierLen); 7157 SourceLocation getLocationOfByte(const char *x); 7158 7159 const Expr *getDataArg(unsigned i) const; 7160 7161 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7162 const analyze_format_string::ConversionSpecifier &CS, 7163 const char *startSpecifier, unsigned specifierLen, 7164 unsigned argIndex); 7165 7166 template <typename Range> 7167 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7168 bool IsStringLocation, Range StringRange, 7169 ArrayRef<FixItHint> Fixit = None); 7170 }; 7171 7172 } // namespace 7173 7174 SourceRange CheckFormatHandler::getFormatStringRange() { 7175 return OrigFormatExpr->getSourceRange(); 7176 } 7177 7178 CharSourceRange CheckFormatHandler:: 7179 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7180 SourceLocation Start = getLocationOfByte(startSpecifier); 7181 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7182 7183 // Advance the end SourceLocation by one due to half-open ranges. 7184 End = End.getLocWithOffset(1); 7185 7186 return CharSourceRange::getCharRange(Start, End); 7187 } 7188 7189 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7190 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7191 S.getLangOpts(), S.Context.getTargetInfo()); 7192 } 7193 7194 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7195 unsigned specifierLen){ 7196 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7197 getLocationOfByte(startSpecifier), 7198 /*IsStringLocation*/true, 7199 getSpecifierRange(startSpecifier, specifierLen)); 7200 } 7201 7202 void CheckFormatHandler::HandleInvalidLengthModifier( 7203 const analyze_format_string::FormatSpecifier &FS, 7204 const analyze_format_string::ConversionSpecifier &CS, 7205 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7206 using namespace analyze_format_string; 7207 7208 const LengthModifier &LM = FS.getLengthModifier(); 7209 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7210 7211 // See if we know how to fix this length modifier. 7212 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7213 if (FixedLM) { 7214 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7215 getLocationOfByte(LM.getStart()), 7216 /*IsStringLocation*/true, 7217 getSpecifierRange(startSpecifier, specifierLen)); 7218 7219 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7220 << FixedLM->toString() 7221 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7222 7223 } else { 7224 FixItHint Hint; 7225 if (DiagID == diag::warn_format_nonsensical_length) 7226 Hint = FixItHint::CreateRemoval(LMRange); 7227 7228 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7229 getLocationOfByte(LM.getStart()), 7230 /*IsStringLocation*/true, 7231 getSpecifierRange(startSpecifier, specifierLen), 7232 Hint); 7233 } 7234 } 7235 7236 void CheckFormatHandler::HandleNonStandardLengthModifier( 7237 const analyze_format_string::FormatSpecifier &FS, 7238 const char *startSpecifier, unsigned specifierLen) { 7239 using namespace analyze_format_string; 7240 7241 const LengthModifier &LM = FS.getLengthModifier(); 7242 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7243 7244 // See if we know how to fix this length modifier. 7245 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7246 if (FixedLM) { 7247 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7248 << LM.toString() << 0, 7249 getLocationOfByte(LM.getStart()), 7250 /*IsStringLocation*/true, 7251 getSpecifierRange(startSpecifier, specifierLen)); 7252 7253 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7254 << FixedLM->toString() 7255 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7256 7257 } else { 7258 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7259 << LM.toString() << 0, 7260 getLocationOfByte(LM.getStart()), 7261 /*IsStringLocation*/true, 7262 getSpecifierRange(startSpecifier, specifierLen)); 7263 } 7264 } 7265 7266 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7267 const analyze_format_string::ConversionSpecifier &CS, 7268 const char *startSpecifier, unsigned specifierLen) { 7269 using namespace analyze_format_string; 7270 7271 // See if we know how to fix this conversion specifier. 7272 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7273 if (FixedCS) { 7274 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7275 << CS.toString() << /*conversion specifier*/1, 7276 getLocationOfByte(CS.getStart()), 7277 /*IsStringLocation*/true, 7278 getSpecifierRange(startSpecifier, specifierLen)); 7279 7280 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7281 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7282 << FixedCS->toString() 7283 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7284 } else { 7285 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7286 << CS.toString() << /*conversion specifier*/1, 7287 getLocationOfByte(CS.getStart()), 7288 /*IsStringLocation*/true, 7289 getSpecifierRange(startSpecifier, specifierLen)); 7290 } 7291 } 7292 7293 void CheckFormatHandler::HandlePosition(const char *startPos, 7294 unsigned posLen) { 7295 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7296 getLocationOfByte(startPos), 7297 /*IsStringLocation*/true, 7298 getSpecifierRange(startPos, posLen)); 7299 } 7300 7301 void 7302 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7303 analyze_format_string::PositionContext p) { 7304 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7305 << (unsigned) p, 7306 getLocationOfByte(startPos), /*IsStringLocation*/true, 7307 getSpecifierRange(startPos, posLen)); 7308 } 7309 7310 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7311 unsigned posLen) { 7312 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7313 getLocationOfByte(startPos), 7314 /*IsStringLocation*/true, 7315 getSpecifierRange(startPos, posLen)); 7316 } 7317 7318 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7319 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7320 // The presence of a null character is likely an error. 7321 EmitFormatDiagnostic( 7322 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7323 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7324 getFormatStringRange()); 7325 } 7326 } 7327 7328 // Note that this may return NULL if there was an error parsing or building 7329 // one of the argument expressions. 7330 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7331 return Args[FirstDataArg + i]; 7332 } 7333 7334 void CheckFormatHandler::DoneProcessing() { 7335 // Does the number of data arguments exceed the number of 7336 // format conversions in the format string? 7337 if (!HasVAListArg) { 7338 // Find any arguments that weren't covered. 7339 CoveredArgs.flip(); 7340 signed notCoveredArg = CoveredArgs.find_first(); 7341 if (notCoveredArg >= 0) { 7342 assert((unsigned)notCoveredArg < NumDataArgs); 7343 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7344 } else { 7345 UncoveredArg.setAllCovered(); 7346 } 7347 } 7348 } 7349 7350 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7351 const Expr *ArgExpr) { 7352 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7353 "Invalid state"); 7354 7355 if (!ArgExpr) 7356 return; 7357 7358 SourceLocation Loc = ArgExpr->getBeginLoc(); 7359 7360 if (S.getSourceManager().isInSystemMacro(Loc)) 7361 return; 7362 7363 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7364 for (auto E : DiagnosticExprs) 7365 PDiag << E->getSourceRange(); 7366 7367 CheckFormatHandler::EmitFormatDiagnostic( 7368 S, IsFunctionCall, DiagnosticExprs[0], 7369 PDiag, Loc, /*IsStringLocation*/false, 7370 DiagnosticExprs[0]->getSourceRange()); 7371 } 7372 7373 bool 7374 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7375 SourceLocation Loc, 7376 const char *startSpec, 7377 unsigned specifierLen, 7378 const char *csStart, 7379 unsigned csLen) { 7380 bool keepGoing = true; 7381 if (argIndex < NumDataArgs) { 7382 // Consider the argument coverered, even though the specifier doesn't 7383 // make sense. 7384 CoveredArgs.set(argIndex); 7385 } 7386 else { 7387 // If argIndex exceeds the number of data arguments we 7388 // don't issue a warning because that is just a cascade of warnings (and 7389 // they may have intended '%%' anyway). We don't want to continue processing 7390 // the format string after this point, however, as we will like just get 7391 // gibberish when trying to match arguments. 7392 keepGoing = false; 7393 } 7394 7395 StringRef Specifier(csStart, csLen); 7396 7397 // If the specifier in non-printable, it could be the first byte of a UTF-8 7398 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7399 // hex value. 7400 std::string CodePointStr; 7401 if (!llvm::sys::locale::isPrint(*csStart)) { 7402 llvm::UTF32 CodePoint; 7403 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7404 const llvm::UTF8 *E = 7405 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7406 llvm::ConversionResult Result = 7407 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7408 7409 if (Result != llvm::conversionOK) { 7410 unsigned char FirstChar = *csStart; 7411 CodePoint = (llvm::UTF32)FirstChar; 7412 } 7413 7414 llvm::raw_string_ostream OS(CodePointStr); 7415 if (CodePoint < 256) 7416 OS << "\\x" << llvm::format("%02x", CodePoint); 7417 else if (CodePoint <= 0xFFFF) 7418 OS << "\\u" << llvm::format("%04x", CodePoint); 7419 else 7420 OS << "\\U" << llvm::format("%08x", CodePoint); 7421 OS.flush(); 7422 Specifier = CodePointStr; 7423 } 7424 7425 EmitFormatDiagnostic( 7426 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7427 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7428 7429 return keepGoing; 7430 } 7431 7432 void 7433 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7434 const char *startSpec, 7435 unsigned specifierLen) { 7436 EmitFormatDiagnostic( 7437 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7438 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7439 } 7440 7441 bool 7442 CheckFormatHandler::CheckNumArgs( 7443 const analyze_format_string::FormatSpecifier &FS, 7444 const analyze_format_string::ConversionSpecifier &CS, 7445 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7446 7447 if (argIndex >= NumDataArgs) { 7448 PartialDiagnostic PDiag = FS.usesPositionalArg() 7449 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7450 << (argIndex+1) << NumDataArgs) 7451 : S.PDiag(diag::warn_printf_insufficient_data_args); 7452 EmitFormatDiagnostic( 7453 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7454 getSpecifierRange(startSpecifier, specifierLen)); 7455 7456 // Since more arguments than conversion tokens are given, by extension 7457 // all arguments are covered, so mark this as so. 7458 UncoveredArg.setAllCovered(); 7459 return false; 7460 } 7461 return true; 7462 } 7463 7464 template<typename Range> 7465 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7466 SourceLocation Loc, 7467 bool IsStringLocation, 7468 Range StringRange, 7469 ArrayRef<FixItHint> FixIt) { 7470 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7471 Loc, IsStringLocation, StringRange, FixIt); 7472 } 7473 7474 /// If the format string is not within the function call, emit a note 7475 /// so that the function call and string are in diagnostic messages. 7476 /// 7477 /// \param InFunctionCall if true, the format string is within the function 7478 /// call and only one diagnostic message will be produced. Otherwise, an 7479 /// extra note will be emitted pointing to location of the format string. 7480 /// 7481 /// \param ArgumentExpr the expression that is passed as the format string 7482 /// argument in the function call. Used for getting locations when two 7483 /// diagnostics are emitted. 7484 /// 7485 /// \param PDiag the callee should already have provided any strings for the 7486 /// diagnostic message. This function only adds locations and fixits 7487 /// to diagnostics. 7488 /// 7489 /// \param Loc primary location for diagnostic. If two diagnostics are 7490 /// required, one will be at Loc and a new SourceLocation will be created for 7491 /// the other one. 7492 /// 7493 /// \param IsStringLocation if true, Loc points to the format string should be 7494 /// used for the note. Otherwise, Loc points to the argument list and will 7495 /// be used with PDiag. 7496 /// 7497 /// \param StringRange some or all of the string to highlight. This is 7498 /// templated so it can accept either a CharSourceRange or a SourceRange. 7499 /// 7500 /// \param FixIt optional fix it hint for the format string. 7501 template <typename Range> 7502 void CheckFormatHandler::EmitFormatDiagnostic( 7503 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7504 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7505 Range StringRange, ArrayRef<FixItHint> FixIt) { 7506 if (InFunctionCall) { 7507 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7508 D << StringRange; 7509 D << FixIt; 7510 } else { 7511 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7512 << ArgumentExpr->getSourceRange(); 7513 7514 const Sema::SemaDiagnosticBuilder &Note = 7515 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7516 diag::note_format_string_defined); 7517 7518 Note << StringRange; 7519 Note << FixIt; 7520 } 7521 } 7522 7523 //===--- CHECK: Printf format string checking ------------------------------===// 7524 7525 namespace { 7526 7527 class CheckPrintfHandler : public CheckFormatHandler { 7528 public: 7529 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7530 const Expr *origFormatExpr, 7531 const Sema::FormatStringType type, unsigned firstDataArg, 7532 unsigned numDataArgs, bool isObjC, const char *beg, 7533 bool hasVAListArg, ArrayRef<const Expr *> Args, 7534 unsigned formatIdx, bool inFunctionCall, 7535 Sema::VariadicCallType CallType, 7536 llvm::SmallBitVector &CheckedVarArgs, 7537 UncoveredArgHandler &UncoveredArg) 7538 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7539 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7540 inFunctionCall, CallType, CheckedVarArgs, 7541 UncoveredArg) {} 7542 7543 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7544 7545 /// Returns true if '%@' specifiers are allowed in the format string. 7546 bool allowsObjCArg() const { 7547 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7548 FSType == Sema::FST_OSTrace; 7549 } 7550 7551 bool HandleInvalidPrintfConversionSpecifier( 7552 const analyze_printf::PrintfSpecifier &FS, 7553 const char *startSpecifier, 7554 unsigned specifierLen) override; 7555 7556 void handleInvalidMaskType(StringRef MaskType) override; 7557 7558 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7559 const char *startSpecifier, 7560 unsigned specifierLen) override; 7561 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7562 const char *StartSpecifier, 7563 unsigned SpecifierLen, 7564 const Expr *E); 7565 7566 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7567 const char *startSpecifier, unsigned specifierLen); 7568 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7569 const analyze_printf::OptionalAmount &Amt, 7570 unsigned type, 7571 const char *startSpecifier, unsigned specifierLen); 7572 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7573 const analyze_printf::OptionalFlag &flag, 7574 const char *startSpecifier, unsigned specifierLen); 7575 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7576 const analyze_printf::OptionalFlag &ignoredFlag, 7577 const analyze_printf::OptionalFlag &flag, 7578 const char *startSpecifier, unsigned specifierLen); 7579 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7580 const Expr *E); 7581 7582 void HandleEmptyObjCModifierFlag(const char *startFlag, 7583 unsigned flagLen) override; 7584 7585 void HandleInvalidObjCModifierFlag(const char *startFlag, 7586 unsigned flagLen) override; 7587 7588 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7589 const char *flagsEnd, 7590 const char *conversionPosition) 7591 override; 7592 }; 7593 7594 } // namespace 7595 7596 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7597 const analyze_printf::PrintfSpecifier &FS, 7598 const char *startSpecifier, 7599 unsigned specifierLen) { 7600 const analyze_printf::PrintfConversionSpecifier &CS = 7601 FS.getConversionSpecifier(); 7602 7603 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7604 getLocationOfByte(CS.getStart()), 7605 startSpecifier, specifierLen, 7606 CS.getStart(), CS.getLength()); 7607 } 7608 7609 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7610 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7611 } 7612 7613 bool CheckPrintfHandler::HandleAmount( 7614 const analyze_format_string::OptionalAmount &Amt, 7615 unsigned k, const char *startSpecifier, 7616 unsigned specifierLen) { 7617 if (Amt.hasDataArgument()) { 7618 if (!HasVAListArg) { 7619 unsigned argIndex = Amt.getArgIndex(); 7620 if (argIndex >= NumDataArgs) { 7621 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7622 << k, 7623 getLocationOfByte(Amt.getStart()), 7624 /*IsStringLocation*/true, 7625 getSpecifierRange(startSpecifier, specifierLen)); 7626 // Don't do any more checking. We will just emit 7627 // spurious errors. 7628 return false; 7629 } 7630 7631 // Type check the data argument. It should be an 'int'. 7632 // Although not in conformance with C99, we also allow the argument to be 7633 // an 'unsigned int' as that is a reasonably safe case. GCC also 7634 // doesn't emit a warning for that case. 7635 CoveredArgs.set(argIndex); 7636 const Expr *Arg = getDataArg(argIndex); 7637 if (!Arg) 7638 return false; 7639 7640 QualType T = Arg->getType(); 7641 7642 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7643 assert(AT.isValid()); 7644 7645 if (!AT.matchesType(S.Context, T)) { 7646 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7647 << k << AT.getRepresentativeTypeName(S.Context) 7648 << T << Arg->getSourceRange(), 7649 getLocationOfByte(Amt.getStart()), 7650 /*IsStringLocation*/true, 7651 getSpecifierRange(startSpecifier, specifierLen)); 7652 // Don't do any more checking. We will just emit 7653 // spurious errors. 7654 return false; 7655 } 7656 } 7657 } 7658 return true; 7659 } 7660 7661 void CheckPrintfHandler::HandleInvalidAmount( 7662 const analyze_printf::PrintfSpecifier &FS, 7663 const analyze_printf::OptionalAmount &Amt, 7664 unsigned type, 7665 const char *startSpecifier, 7666 unsigned specifierLen) { 7667 const analyze_printf::PrintfConversionSpecifier &CS = 7668 FS.getConversionSpecifier(); 7669 7670 FixItHint fixit = 7671 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7672 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7673 Amt.getConstantLength())) 7674 : FixItHint(); 7675 7676 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7677 << type << CS.toString(), 7678 getLocationOfByte(Amt.getStart()), 7679 /*IsStringLocation*/true, 7680 getSpecifierRange(startSpecifier, specifierLen), 7681 fixit); 7682 } 7683 7684 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7685 const analyze_printf::OptionalFlag &flag, 7686 const char *startSpecifier, 7687 unsigned specifierLen) { 7688 // Warn about pointless flag with a fixit removal. 7689 const analyze_printf::PrintfConversionSpecifier &CS = 7690 FS.getConversionSpecifier(); 7691 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7692 << flag.toString() << CS.toString(), 7693 getLocationOfByte(flag.getPosition()), 7694 /*IsStringLocation*/true, 7695 getSpecifierRange(startSpecifier, specifierLen), 7696 FixItHint::CreateRemoval( 7697 getSpecifierRange(flag.getPosition(), 1))); 7698 } 7699 7700 void CheckPrintfHandler::HandleIgnoredFlag( 7701 const analyze_printf::PrintfSpecifier &FS, 7702 const analyze_printf::OptionalFlag &ignoredFlag, 7703 const analyze_printf::OptionalFlag &flag, 7704 const char *startSpecifier, 7705 unsigned specifierLen) { 7706 // Warn about ignored flag with a fixit removal. 7707 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7708 << ignoredFlag.toString() << flag.toString(), 7709 getLocationOfByte(ignoredFlag.getPosition()), 7710 /*IsStringLocation*/true, 7711 getSpecifierRange(startSpecifier, specifierLen), 7712 FixItHint::CreateRemoval( 7713 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7714 } 7715 7716 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7717 unsigned flagLen) { 7718 // Warn about an empty flag. 7719 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7720 getLocationOfByte(startFlag), 7721 /*IsStringLocation*/true, 7722 getSpecifierRange(startFlag, flagLen)); 7723 } 7724 7725 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7726 unsigned flagLen) { 7727 // Warn about an invalid flag. 7728 auto Range = getSpecifierRange(startFlag, flagLen); 7729 StringRef flag(startFlag, flagLen); 7730 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7731 getLocationOfByte(startFlag), 7732 /*IsStringLocation*/true, 7733 Range, FixItHint::CreateRemoval(Range)); 7734 } 7735 7736 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7737 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7738 // Warn about using '[...]' without a '@' conversion. 7739 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7740 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7741 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7742 getLocationOfByte(conversionPosition), 7743 /*IsStringLocation*/true, 7744 Range, FixItHint::CreateRemoval(Range)); 7745 } 7746 7747 // Determines if the specified is a C++ class or struct containing 7748 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7749 // "c_str()"). 7750 template<typename MemberKind> 7751 static llvm::SmallPtrSet<MemberKind*, 1> 7752 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7753 const RecordType *RT = Ty->getAs<RecordType>(); 7754 llvm::SmallPtrSet<MemberKind*, 1> Results; 7755 7756 if (!RT) 7757 return Results; 7758 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7759 if (!RD || !RD->getDefinition()) 7760 return Results; 7761 7762 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7763 Sema::LookupMemberName); 7764 R.suppressDiagnostics(); 7765 7766 // We just need to include all members of the right kind turned up by the 7767 // filter, at this point. 7768 if (S.LookupQualifiedName(R, RT->getDecl())) 7769 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7770 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7771 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7772 Results.insert(FK); 7773 } 7774 return Results; 7775 } 7776 7777 /// Check if we could call '.c_str()' on an object. 7778 /// 7779 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7780 /// allow the call, or if it would be ambiguous). 7781 bool Sema::hasCStrMethod(const Expr *E) { 7782 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7783 7784 MethodSet Results = 7785 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7786 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7787 MI != ME; ++MI) 7788 if ((*MI)->getMinRequiredArguments() == 0) 7789 return true; 7790 return false; 7791 } 7792 7793 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7794 // better diagnostic if so. AT is assumed to be valid. 7795 // Returns true when a c_str() conversion method is found. 7796 bool CheckPrintfHandler::checkForCStrMembers( 7797 const analyze_printf::ArgType &AT, const Expr *E) { 7798 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7799 7800 MethodSet Results = 7801 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7802 7803 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7804 MI != ME; ++MI) { 7805 const CXXMethodDecl *Method = *MI; 7806 if (Method->getMinRequiredArguments() == 0 && 7807 AT.matchesType(S.Context, Method->getReturnType())) { 7808 // FIXME: Suggest parens if the expression needs them. 7809 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7810 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7811 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7812 return true; 7813 } 7814 } 7815 7816 return false; 7817 } 7818 7819 bool 7820 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7821 &FS, 7822 const char *startSpecifier, 7823 unsigned specifierLen) { 7824 using namespace analyze_format_string; 7825 using namespace analyze_printf; 7826 7827 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7828 7829 if (FS.consumesDataArgument()) { 7830 if (atFirstArg) { 7831 atFirstArg = false; 7832 usesPositionalArgs = FS.usesPositionalArg(); 7833 } 7834 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7835 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7836 startSpecifier, specifierLen); 7837 return false; 7838 } 7839 } 7840 7841 // First check if the field width, precision, and conversion specifier 7842 // have matching data arguments. 7843 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7844 startSpecifier, specifierLen)) { 7845 return false; 7846 } 7847 7848 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7849 startSpecifier, specifierLen)) { 7850 return false; 7851 } 7852 7853 if (!CS.consumesDataArgument()) { 7854 // FIXME: Technically specifying a precision or field width here 7855 // makes no sense. Worth issuing a warning at some point. 7856 return true; 7857 } 7858 7859 // Consume the argument. 7860 unsigned argIndex = FS.getArgIndex(); 7861 if (argIndex < NumDataArgs) { 7862 // The check to see if the argIndex is valid will come later. 7863 // We set the bit here because we may exit early from this 7864 // function if we encounter some other error. 7865 CoveredArgs.set(argIndex); 7866 } 7867 7868 // FreeBSD kernel extensions. 7869 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7870 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7871 // We need at least two arguments. 7872 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7873 return false; 7874 7875 // Claim the second argument. 7876 CoveredArgs.set(argIndex + 1); 7877 7878 // Type check the first argument (int for %b, pointer for %D) 7879 const Expr *Ex = getDataArg(argIndex); 7880 const analyze_printf::ArgType &AT = 7881 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7882 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7883 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7884 EmitFormatDiagnostic( 7885 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7886 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7887 << false << Ex->getSourceRange(), 7888 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7889 getSpecifierRange(startSpecifier, specifierLen)); 7890 7891 // Type check the second argument (char * for both %b and %D) 7892 Ex = getDataArg(argIndex + 1); 7893 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7894 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7895 EmitFormatDiagnostic( 7896 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7897 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7898 << false << Ex->getSourceRange(), 7899 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7900 getSpecifierRange(startSpecifier, specifierLen)); 7901 7902 return true; 7903 } 7904 7905 // Check for using an Objective-C specific conversion specifier 7906 // in a non-ObjC literal. 7907 if (!allowsObjCArg() && CS.isObjCArg()) { 7908 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7909 specifierLen); 7910 } 7911 7912 // %P can only be used with os_log. 7913 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7914 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7915 specifierLen); 7916 } 7917 7918 // %n is not allowed with os_log. 7919 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7920 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7921 getLocationOfByte(CS.getStart()), 7922 /*IsStringLocation*/ false, 7923 getSpecifierRange(startSpecifier, specifierLen)); 7924 7925 return true; 7926 } 7927 7928 // Only scalars are allowed for os_trace. 7929 if (FSType == Sema::FST_OSTrace && 7930 (CS.getKind() == ConversionSpecifier::PArg || 7931 CS.getKind() == ConversionSpecifier::sArg || 7932 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7933 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7934 specifierLen); 7935 } 7936 7937 // Check for use of public/private annotation outside of os_log(). 7938 if (FSType != Sema::FST_OSLog) { 7939 if (FS.isPublic().isSet()) { 7940 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7941 << "public", 7942 getLocationOfByte(FS.isPublic().getPosition()), 7943 /*IsStringLocation*/ false, 7944 getSpecifierRange(startSpecifier, specifierLen)); 7945 } 7946 if (FS.isPrivate().isSet()) { 7947 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7948 << "private", 7949 getLocationOfByte(FS.isPrivate().getPosition()), 7950 /*IsStringLocation*/ false, 7951 getSpecifierRange(startSpecifier, specifierLen)); 7952 } 7953 } 7954 7955 // Check for invalid use of field width 7956 if (!FS.hasValidFieldWidth()) { 7957 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7958 startSpecifier, specifierLen); 7959 } 7960 7961 // Check for invalid use of precision 7962 if (!FS.hasValidPrecision()) { 7963 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7964 startSpecifier, specifierLen); 7965 } 7966 7967 // Precision is mandatory for %P specifier. 7968 if (CS.getKind() == ConversionSpecifier::PArg && 7969 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7970 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7971 getLocationOfByte(startSpecifier), 7972 /*IsStringLocation*/ false, 7973 getSpecifierRange(startSpecifier, specifierLen)); 7974 } 7975 7976 // Check each flag does not conflict with any other component. 7977 if (!FS.hasValidThousandsGroupingPrefix()) 7978 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7979 if (!FS.hasValidLeadingZeros()) 7980 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7981 if (!FS.hasValidPlusPrefix()) 7982 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7983 if (!FS.hasValidSpacePrefix()) 7984 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7985 if (!FS.hasValidAlternativeForm()) 7986 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7987 if (!FS.hasValidLeftJustified()) 7988 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7989 7990 // Check that flags are not ignored by another flag 7991 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7992 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7993 startSpecifier, specifierLen); 7994 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7995 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7996 startSpecifier, specifierLen); 7997 7998 // Check the length modifier is valid with the given conversion specifier. 7999 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8000 S.getLangOpts())) 8001 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8002 diag::warn_format_nonsensical_length); 8003 else if (!FS.hasStandardLengthModifier()) 8004 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8005 else if (!FS.hasStandardLengthConversionCombination()) 8006 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8007 diag::warn_format_non_standard_conversion_spec); 8008 8009 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8010 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8011 8012 // The remaining checks depend on the data arguments. 8013 if (HasVAListArg) 8014 return true; 8015 8016 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8017 return false; 8018 8019 const Expr *Arg = getDataArg(argIndex); 8020 if (!Arg) 8021 return true; 8022 8023 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8024 } 8025 8026 static bool requiresParensToAddCast(const Expr *E) { 8027 // FIXME: We should have a general way to reason about operator 8028 // precedence and whether parens are actually needed here. 8029 // Take care of a few common cases where they aren't. 8030 const Expr *Inside = E->IgnoreImpCasts(); 8031 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8032 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8033 8034 switch (Inside->getStmtClass()) { 8035 case Stmt::ArraySubscriptExprClass: 8036 case Stmt::CallExprClass: 8037 case Stmt::CharacterLiteralClass: 8038 case Stmt::CXXBoolLiteralExprClass: 8039 case Stmt::DeclRefExprClass: 8040 case Stmt::FloatingLiteralClass: 8041 case Stmt::IntegerLiteralClass: 8042 case Stmt::MemberExprClass: 8043 case Stmt::ObjCArrayLiteralClass: 8044 case Stmt::ObjCBoolLiteralExprClass: 8045 case Stmt::ObjCBoxedExprClass: 8046 case Stmt::ObjCDictionaryLiteralClass: 8047 case Stmt::ObjCEncodeExprClass: 8048 case Stmt::ObjCIvarRefExprClass: 8049 case Stmt::ObjCMessageExprClass: 8050 case Stmt::ObjCPropertyRefExprClass: 8051 case Stmt::ObjCStringLiteralClass: 8052 case Stmt::ObjCSubscriptRefExprClass: 8053 case Stmt::ParenExprClass: 8054 case Stmt::StringLiteralClass: 8055 case Stmt::UnaryOperatorClass: 8056 return false; 8057 default: 8058 return true; 8059 } 8060 } 8061 8062 static std::pair<QualType, StringRef> 8063 shouldNotPrintDirectly(const ASTContext &Context, 8064 QualType IntendedTy, 8065 const Expr *E) { 8066 // Use a 'while' to peel off layers of typedefs. 8067 QualType TyTy = IntendedTy; 8068 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8069 StringRef Name = UserTy->getDecl()->getName(); 8070 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8071 .Case("CFIndex", Context.getNSIntegerType()) 8072 .Case("NSInteger", Context.getNSIntegerType()) 8073 .Case("NSUInteger", Context.getNSUIntegerType()) 8074 .Case("SInt32", Context.IntTy) 8075 .Case("UInt32", Context.UnsignedIntTy) 8076 .Default(QualType()); 8077 8078 if (!CastTy.isNull()) 8079 return std::make_pair(CastTy, Name); 8080 8081 TyTy = UserTy->desugar(); 8082 } 8083 8084 // Strip parens if necessary. 8085 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8086 return shouldNotPrintDirectly(Context, 8087 PE->getSubExpr()->getType(), 8088 PE->getSubExpr()); 8089 8090 // If this is a conditional expression, then its result type is constructed 8091 // via usual arithmetic conversions and thus there might be no necessary 8092 // typedef sugar there. Recurse to operands to check for NSInteger & 8093 // Co. usage condition. 8094 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8095 QualType TrueTy, FalseTy; 8096 StringRef TrueName, FalseName; 8097 8098 std::tie(TrueTy, TrueName) = 8099 shouldNotPrintDirectly(Context, 8100 CO->getTrueExpr()->getType(), 8101 CO->getTrueExpr()); 8102 std::tie(FalseTy, FalseName) = 8103 shouldNotPrintDirectly(Context, 8104 CO->getFalseExpr()->getType(), 8105 CO->getFalseExpr()); 8106 8107 if (TrueTy == FalseTy) 8108 return std::make_pair(TrueTy, TrueName); 8109 else if (TrueTy.isNull()) 8110 return std::make_pair(FalseTy, FalseName); 8111 else if (FalseTy.isNull()) 8112 return std::make_pair(TrueTy, TrueName); 8113 } 8114 8115 return std::make_pair(QualType(), StringRef()); 8116 } 8117 8118 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8119 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8120 /// type do not count. 8121 static bool 8122 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8123 QualType From = ICE->getSubExpr()->getType(); 8124 QualType To = ICE->getType(); 8125 // It's an integer promotion if the destination type is the promoted 8126 // source type. 8127 if (ICE->getCastKind() == CK_IntegralCast && 8128 From->isPromotableIntegerType() && 8129 S.Context.getPromotedIntegerType(From) == To) 8130 return true; 8131 // Look through vector types, since we do default argument promotion for 8132 // those in OpenCL. 8133 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8134 From = VecTy->getElementType(); 8135 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8136 To = VecTy->getElementType(); 8137 // It's a floating promotion if the source type is a lower rank. 8138 return ICE->getCastKind() == CK_FloatingCast && 8139 S.Context.getFloatingTypeOrder(From, To) < 0; 8140 } 8141 8142 bool 8143 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8144 const char *StartSpecifier, 8145 unsigned SpecifierLen, 8146 const Expr *E) { 8147 using namespace analyze_format_string; 8148 using namespace analyze_printf; 8149 8150 // Now type check the data expression that matches the 8151 // format specifier. 8152 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8153 if (!AT.isValid()) 8154 return true; 8155 8156 QualType ExprTy = E->getType(); 8157 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8158 ExprTy = TET->getUnderlyingExpr()->getType(); 8159 } 8160 8161 // Diagnose attempts to print a boolean value as a character. Unlike other 8162 // -Wformat diagnostics, this is fine from a type perspective, but it still 8163 // doesn't make sense. 8164 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8165 E->isKnownToHaveBooleanValue()) { 8166 const CharSourceRange &CSR = 8167 getSpecifierRange(StartSpecifier, SpecifierLen); 8168 SmallString<4> FSString; 8169 llvm::raw_svector_ostream os(FSString); 8170 FS.toString(os); 8171 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8172 << FSString, 8173 E->getExprLoc(), false, CSR); 8174 return true; 8175 } 8176 8177 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8178 if (Match == analyze_printf::ArgType::Match) 8179 return true; 8180 8181 // Look through argument promotions for our error message's reported type. 8182 // This includes the integral and floating promotions, but excludes array 8183 // and function pointer decay (seeing that an argument intended to be a 8184 // string has type 'char [6]' is probably more confusing than 'char *') and 8185 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8186 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8187 if (isArithmeticArgumentPromotion(S, ICE)) { 8188 E = ICE->getSubExpr(); 8189 ExprTy = E->getType(); 8190 8191 // Check if we didn't match because of an implicit cast from a 'char' 8192 // or 'short' to an 'int'. This is done because printf is a varargs 8193 // function. 8194 if (ICE->getType() == S.Context.IntTy || 8195 ICE->getType() == S.Context.UnsignedIntTy) { 8196 // All further checking is done on the subexpression 8197 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8198 AT.matchesType(S.Context, ExprTy); 8199 if (ImplicitMatch == analyze_printf::ArgType::Match) 8200 return true; 8201 if (ImplicitMatch == ArgType::NoMatchPedantic || 8202 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8203 Match = ImplicitMatch; 8204 } 8205 } 8206 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8207 // Special case for 'a', which has type 'int' in C. 8208 // Note, however, that we do /not/ want to treat multibyte constants like 8209 // 'MooV' as characters! This form is deprecated but still exists. 8210 if (ExprTy == S.Context.IntTy) 8211 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8212 ExprTy = S.Context.CharTy; 8213 } 8214 8215 // Look through enums to their underlying type. 8216 bool IsEnum = false; 8217 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8218 ExprTy = EnumTy->getDecl()->getIntegerType(); 8219 IsEnum = true; 8220 } 8221 8222 // %C in an Objective-C context prints a unichar, not a wchar_t. 8223 // If the argument is an integer of some kind, believe the %C and suggest 8224 // a cast instead of changing the conversion specifier. 8225 QualType IntendedTy = ExprTy; 8226 if (isObjCContext() && 8227 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8228 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8229 !ExprTy->isCharType()) { 8230 // 'unichar' is defined as a typedef of unsigned short, but we should 8231 // prefer using the typedef if it is visible. 8232 IntendedTy = S.Context.UnsignedShortTy; 8233 8234 // While we are here, check if the value is an IntegerLiteral that happens 8235 // to be within the valid range. 8236 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8237 const llvm::APInt &V = IL->getValue(); 8238 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8239 return true; 8240 } 8241 8242 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8243 Sema::LookupOrdinaryName); 8244 if (S.LookupName(Result, S.getCurScope())) { 8245 NamedDecl *ND = Result.getFoundDecl(); 8246 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8247 if (TD->getUnderlyingType() == IntendedTy) 8248 IntendedTy = S.Context.getTypedefType(TD); 8249 } 8250 } 8251 } 8252 8253 // Special-case some of Darwin's platform-independence types by suggesting 8254 // casts to primitive types that are known to be large enough. 8255 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8256 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8257 QualType CastTy; 8258 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8259 if (!CastTy.isNull()) { 8260 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8261 // (long in ASTContext). Only complain to pedants. 8262 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8263 (AT.isSizeT() || AT.isPtrdiffT()) && 8264 AT.matchesType(S.Context, CastTy)) 8265 Match = ArgType::NoMatchPedantic; 8266 IntendedTy = CastTy; 8267 ShouldNotPrintDirectly = true; 8268 } 8269 } 8270 8271 // We may be able to offer a FixItHint if it is a supported type. 8272 PrintfSpecifier fixedFS = FS; 8273 bool Success = 8274 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8275 8276 if (Success) { 8277 // Get the fix string from the fixed format specifier 8278 SmallString<16> buf; 8279 llvm::raw_svector_ostream os(buf); 8280 fixedFS.toString(os); 8281 8282 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8283 8284 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8285 unsigned Diag; 8286 switch (Match) { 8287 case ArgType::Match: llvm_unreachable("expected non-matching"); 8288 case ArgType::NoMatchPedantic: 8289 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8290 break; 8291 case ArgType::NoMatchTypeConfusion: 8292 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8293 break; 8294 case ArgType::NoMatch: 8295 Diag = diag::warn_format_conversion_argument_type_mismatch; 8296 break; 8297 } 8298 8299 // In this case, the specifier is wrong and should be changed to match 8300 // the argument. 8301 EmitFormatDiagnostic(S.PDiag(Diag) 8302 << AT.getRepresentativeTypeName(S.Context) 8303 << IntendedTy << IsEnum << E->getSourceRange(), 8304 E->getBeginLoc(), 8305 /*IsStringLocation*/ false, SpecRange, 8306 FixItHint::CreateReplacement(SpecRange, os.str())); 8307 } else { 8308 // The canonical type for formatting this value is different from the 8309 // actual type of the expression. (This occurs, for example, with Darwin's 8310 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8311 // should be printed as 'long' for 64-bit compatibility.) 8312 // Rather than emitting a normal format/argument mismatch, we want to 8313 // add a cast to the recommended type (and correct the format string 8314 // if necessary). 8315 SmallString<16> CastBuf; 8316 llvm::raw_svector_ostream CastFix(CastBuf); 8317 CastFix << "("; 8318 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8319 CastFix << ")"; 8320 8321 SmallVector<FixItHint,4> Hints; 8322 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8323 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8324 8325 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8326 // If there's already a cast present, just replace it. 8327 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8328 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8329 8330 } else if (!requiresParensToAddCast(E)) { 8331 // If the expression has high enough precedence, 8332 // just write the C-style cast. 8333 Hints.push_back( 8334 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8335 } else { 8336 // Otherwise, add parens around the expression as well as the cast. 8337 CastFix << "("; 8338 Hints.push_back( 8339 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8340 8341 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8342 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8343 } 8344 8345 if (ShouldNotPrintDirectly) { 8346 // The expression has a type that should not be printed directly. 8347 // We extract the name from the typedef because we don't want to show 8348 // the underlying type in the diagnostic. 8349 StringRef Name; 8350 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8351 Name = TypedefTy->getDecl()->getName(); 8352 else 8353 Name = CastTyName; 8354 unsigned Diag = Match == ArgType::NoMatchPedantic 8355 ? diag::warn_format_argument_needs_cast_pedantic 8356 : diag::warn_format_argument_needs_cast; 8357 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8358 << E->getSourceRange(), 8359 E->getBeginLoc(), /*IsStringLocation=*/false, 8360 SpecRange, Hints); 8361 } else { 8362 // In this case, the expression could be printed using a different 8363 // specifier, but we've decided that the specifier is probably correct 8364 // and we should cast instead. Just use the normal warning message. 8365 EmitFormatDiagnostic( 8366 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8367 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8368 << E->getSourceRange(), 8369 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8370 } 8371 } 8372 } else { 8373 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8374 SpecifierLen); 8375 // Since the warning for passing non-POD types to variadic functions 8376 // was deferred until now, we emit a warning for non-POD 8377 // arguments here. 8378 switch (S.isValidVarArgType(ExprTy)) { 8379 case Sema::VAK_Valid: 8380 case Sema::VAK_ValidInCXX11: { 8381 unsigned Diag; 8382 switch (Match) { 8383 case ArgType::Match: llvm_unreachable("expected non-matching"); 8384 case ArgType::NoMatchPedantic: 8385 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8386 break; 8387 case ArgType::NoMatchTypeConfusion: 8388 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8389 break; 8390 case ArgType::NoMatch: 8391 Diag = diag::warn_format_conversion_argument_type_mismatch; 8392 break; 8393 } 8394 8395 EmitFormatDiagnostic( 8396 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8397 << IsEnum << CSR << E->getSourceRange(), 8398 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8399 break; 8400 } 8401 case Sema::VAK_Undefined: 8402 case Sema::VAK_MSVCUndefined: 8403 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8404 << S.getLangOpts().CPlusPlus11 << ExprTy 8405 << CallType 8406 << AT.getRepresentativeTypeName(S.Context) << CSR 8407 << E->getSourceRange(), 8408 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8409 checkForCStrMembers(AT, E); 8410 break; 8411 8412 case Sema::VAK_Invalid: 8413 if (ExprTy->isObjCObjectType()) 8414 EmitFormatDiagnostic( 8415 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8416 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8417 << AT.getRepresentativeTypeName(S.Context) << CSR 8418 << E->getSourceRange(), 8419 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8420 else 8421 // FIXME: If this is an initializer list, suggest removing the braces 8422 // or inserting a cast to the target type. 8423 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8424 << isa<InitListExpr>(E) << ExprTy << CallType 8425 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8426 break; 8427 } 8428 8429 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8430 "format string specifier index out of range"); 8431 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8432 } 8433 8434 return true; 8435 } 8436 8437 //===--- CHECK: Scanf format string checking ------------------------------===// 8438 8439 namespace { 8440 8441 class CheckScanfHandler : public CheckFormatHandler { 8442 public: 8443 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8444 const Expr *origFormatExpr, Sema::FormatStringType type, 8445 unsigned firstDataArg, unsigned numDataArgs, 8446 const char *beg, bool hasVAListArg, 8447 ArrayRef<const Expr *> Args, unsigned formatIdx, 8448 bool inFunctionCall, Sema::VariadicCallType CallType, 8449 llvm::SmallBitVector &CheckedVarArgs, 8450 UncoveredArgHandler &UncoveredArg) 8451 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8452 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8453 inFunctionCall, CallType, CheckedVarArgs, 8454 UncoveredArg) {} 8455 8456 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8457 const char *startSpecifier, 8458 unsigned specifierLen) override; 8459 8460 bool HandleInvalidScanfConversionSpecifier( 8461 const analyze_scanf::ScanfSpecifier &FS, 8462 const char *startSpecifier, 8463 unsigned specifierLen) override; 8464 8465 void HandleIncompleteScanList(const char *start, const char *end) override; 8466 }; 8467 8468 } // namespace 8469 8470 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8471 const char *end) { 8472 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8473 getLocationOfByte(end), /*IsStringLocation*/true, 8474 getSpecifierRange(start, end - start)); 8475 } 8476 8477 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8478 const analyze_scanf::ScanfSpecifier &FS, 8479 const char *startSpecifier, 8480 unsigned specifierLen) { 8481 const analyze_scanf::ScanfConversionSpecifier &CS = 8482 FS.getConversionSpecifier(); 8483 8484 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8485 getLocationOfByte(CS.getStart()), 8486 startSpecifier, specifierLen, 8487 CS.getStart(), CS.getLength()); 8488 } 8489 8490 bool CheckScanfHandler::HandleScanfSpecifier( 8491 const analyze_scanf::ScanfSpecifier &FS, 8492 const char *startSpecifier, 8493 unsigned specifierLen) { 8494 using namespace analyze_scanf; 8495 using namespace analyze_format_string; 8496 8497 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8498 8499 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8500 // be used to decide if we are using positional arguments consistently. 8501 if (FS.consumesDataArgument()) { 8502 if (atFirstArg) { 8503 atFirstArg = false; 8504 usesPositionalArgs = FS.usesPositionalArg(); 8505 } 8506 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8507 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8508 startSpecifier, specifierLen); 8509 return false; 8510 } 8511 } 8512 8513 // Check if the field with is non-zero. 8514 const OptionalAmount &Amt = FS.getFieldWidth(); 8515 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8516 if (Amt.getConstantAmount() == 0) { 8517 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8518 Amt.getConstantLength()); 8519 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8520 getLocationOfByte(Amt.getStart()), 8521 /*IsStringLocation*/true, R, 8522 FixItHint::CreateRemoval(R)); 8523 } 8524 } 8525 8526 if (!FS.consumesDataArgument()) { 8527 // FIXME: Technically specifying a precision or field width here 8528 // makes no sense. Worth issuing a warning at some point. 8529 return true; 8530 } 8531 8532 // Consume the argument. 8533 unsigned argIndex = FS.getArgIndex(); 8534 if (argIndex < NumDataArgs) { 8535 // The check to see if the argIndex is valid will come later. 8536 // We set the bit here because we may exit early from this 8537 // function if we encounter some other error. 8538 CoveredArgs.set(argIndex); 8539 } 8540 8541 // Check the length modifier is valid with the given conversion specifier. 8542 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8543 S.getLangOpts())) 8544 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8545 diag::warn_format_nonsensical_length); 8546 else if (!FS.hasStandardLengthModifier()) 8547 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8548 else if (!FS.hasStandardLengthConversionCombination()) 8549 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8550 diag::warn_format_non_standard_conversion_spec); 8551 8552 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8553 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8554 8555 // The remaining checks depend on the data arguments. 8556 if (HasVAListArg) 8557 return true; 8558 8559 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8560 return false; 8561 8562 // Check that the argument type matches the format specifier. 8563 const Expr *Ex = getDataArg(argIndex); 8564 if (!Ex) 8565 return true; 8566 8567 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8568 8569 if (!AT.isValid()) { 8570 return true; 8571 } 8572 8573 analyze_format_string::ArgType::MatchKind Match = 8574 AT.matchesType(S.Context, Ex->getType()); 8575 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8576 if (Match == analyze_format_string::ArgType::Match) 8577 return true; 8578 8579 ScanfSpecifier fixedFS = FS; 8580 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8581 S.getLangOpts(), S.Context); 8582 8583 unsigned Diag = 8584 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8585 : diag::warn_format_conversion_argument_type_mismatch; 8586 8587 if (Success) { 8588 // Get the fix string from the fixed format specifier. 8589 SmallString<128> buf; 8590 llvm::raw_svector_ostream os(buf); 8591 fixedFS.toString(os); 8592 8593 EmitFormatDiagnostic( 8594 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8595 << Ex->getType() << false << Ex->getSourceRange(), 8596 Ex->getBeginLoc(), 8597 /*IsStringLocation*/ false, 8598 getSpecifierRange(startSpecifier, specifierLen), 8599 FixItHint::CreateReplacement( 8600 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8601 } else { 8602 EmitFormatDiagnostic(S.PDiag(Diag) 8603 << AT.getRepresentativeTypeName(S.Context) 8604 << Ex->getType() << false << Ex->getSourceRange(), 8605 Ex->getBeginLoc(), 8606 /*IsStringLocation*/ false, 8607 getSpecifierRange(startSpecifier, specifierLen)); 8608 } 8609 8610 return true; 8611 } 8612 8613 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8614 const Expr *OrigFormatExpr, 8615 ArrayRef<const Expr *> Args, 8616 bool HasVAListArg, unsigned format_idx, 8617 unsigned firstDataArg, 8618 Sema::FormatStringType Type, 8619 bool inFunctionCall, 8620 Sema::VariadicCallType CallType, 8621 llvm::SmallBitVector &CheckedVarArgs, 8622 UncoveredArgHandler &UncoveredArg, 8623 bool IgnoreStringsWithoutSpecifiers) { 8624 // CHECK: is the format string a wide literal? 8625 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8626 CheckFormatHandler::EmitFormatDiagnostic( 8627 S, inFunctionCall, Args[format_idx], 8628 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8629 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8630 return; 8631 } 8632 8633 // Str - The format string. NOTE: this is NOT null-terminated! 8634 StringRef StrRef = FExpr->getString(); 8635 const char *Str = StrRef.data(); 8636 // Account for cases where the string literal is truncated in a declaration. 8637 const ConstantArrayType *T = 8638 S.Context.getAsConstantArrayType(FExpr->getType()); 8639 assert(T && "String literal not of constant array type!"); 8640 size_t TypeSize = T->getSize().getZExtValue(); 8641 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8642 const unsigned numDataArgs = Args.size() - firstDataArg; 8643 8644 if (IgnoreStringsWithoutSpecifiers && 8645 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8646 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8647 return; 8648 8649 // Emit a warning if the string literal is truncated and does not contain an 8650 // embedded null character. 8651 if (TypeSize <= StrRef.size() && 8652 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8653 CheckFormatHandler::EmitFormatDiagnostic( 8654 S, inFunctionCall, Args[format_idx], 8655 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8656 FExpr->getBeginLoc(), 8657 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8658 return; 8659 } 8660 8661 // CHECK: empty format string? 8662 if (StrLen == 0 && numDataArgs > 0) { 8663 CheckFormatHandler::EmitFormatDiagnostic( 8664 S, inFunctionCall, Args[format_idx], 8665 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8666 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8667 return; 8668 } 8669 8670 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8671 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8672 Type == Sema::FST_OSTrace) { 8673 CheckPrintfHandler H( 8674 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8675 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8676 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8677 CheckedVarArgs, UncoveredArg); 8678 8679 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8680 S.getLangOpts(), 8681 S.Context.getTargetInfo(), 8682 Type == Sema::FST_FreeBSDKPrintf)) 8683 H.DoneProcessing(); 8684 } else if (Type == Sema::FST_Scanf) { 8685 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8686 numDataArgs, Str, HasVAListArg, Args, format_idx, 8687 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8688 8689 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8690 S.getLangOpts(), 8691 S.Context.getTargetInfo())) 8692 H.DoneProcessing(); 8693 } // TODO: handle other formats 8694 } 8695 8696 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8697 // Str - The format string. NOTE: this is NOT null-terminated! 8698 StringRef StrRef = FExpr->getString(); 8699 const char *Str = StrRef.data(); 8700 // Account for cases where the string literal is truncated in a declaration. 8701 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8702 assert(T && "String literal not of constant array type!"); 8703 size_t TypeSize = T->getSize().getZExtValue(); 8704 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8705 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8706 getLangOpts(), 8707 Context.getTargetInfo()); 8708 } 8709 8710 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8711 8712 // Returns the related absolute value function that is larger, of 0 if one 8713 // does not exist. 8714 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8715 switch (AbsFunction) { 8716 default: 8717 return 0; 8718 8719 case Builtin::BI__builtin_abs: 8720 return Builtin::BI__builtin_labs; 8721 case Builtin::BI__builtin_labs: 8722 return Builtin::BI__builtin_llabs; 8723 case Builtin::BI__builtin_llabs: 8724 return 0; 8725 8726 case Builtin::BI__builtin_fabsf: 8727 return Builtin::BI__builtin_fabs; 8728 case Builtin::BI__builtin_fabs: 8729 return Builtin::BI__builtin_fabsl; 8730 case Builtin::BI__builtin_fabsl: 8731 return 0; 8732 8733 case Builtin::BI__builtin_cabsf: 8734 return Builtin::BI__builtin_cabs; 8735 case Builtin::BI__builtin_cabs: 8736 return Builtin::BI__builtin_cabsl; 8737 case Builtin::BI__builtin_cabsl: 8738 return 0; 8739 8740 case Builtin::BIabs: 8741 return Builtin::BIlabs; 8742 case Builtin::BIlabs: 8743 return Builtin::BIllabs; 8744 case Builtin::BIllabs: 8745 return 0; 8746 8747 case Builtin::BIfabsf: 8748 return Builtin::BIfabs; 8749 case Builtin::BIfabs: 8750 return Builtin::BIfabsl; 8751 case Builtin::BIfabsl: 8752 return 0; 8753 8754 case Builtin::BIcabsf: 8755 return Builtin::BIcabs; 8756 case Builtin::BIcabs: 8757 return Builtin::BIcabsl; 8758 case Builtin::BIcabsl: 8759 return 0; 8760 } 8761 } 8762 8763 // Returns the argument type of the absolute value function. 8764 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8765 unsigned AbsType) { 8766 if (AbsType == 0) 8767 return QualType(); 8768 8769 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8770 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8771 if (Error != ASTContext::GE_None) 8772 return QualType(); 8773 8774 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8775 if (!FT) 8776 return QualType(); 8777 8778 if (FT->getNumParams() != 1) 8779 return QualType(); 8780 8781 return FT->getParamType(0); 8782 } 8783 8784 // Returns the best absolute value function, or zero, based on type and 8785 // current absolute value function. 8786 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8787 unsigned AbsFunctionKind) { 8788 unsigned BestKind = 0; 8789 uint64_t ArgSize = Context.getTypeSize(ArgType); 8790 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8791 Kind = getLargerAbsoluteValueFunction(Kind)) { 8792 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8793 if (Context.getTypeSize(ParamType) >= ArgSize) { 8794 if (BestKind == 0) 8795 BestKind = Kind; 8796 else if (Context.hasSameType(ParamType, ArgType)) { 8797 BestKind = Kind; 8798 break; 8799 } 8800 } 8801 } 8802 return BestKind; 8803 } 8804 8805 enum AbsoluteValueKind { 8806 AVK_Integer, 8807 AVK_Floating, 8808 AVK_Complex 8809 }; 8810 8811 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8812 if (T->isIntegralOrEnumerationType()) 8813 return AVK_Integer; 8814 if (T->isRealFloatingType()) 8815 return AVK_Floating; 8816 if (T->isAnyComplexType()) 8817 return AVK_Complex; 8818 8819 llvm_unreachable("Type not integer, floating, or complex"); 8820 } 8821 8822 // Changes the absolute value function to a different type. Preserves whether 8823 // the function is a builtin. 8824 static unsigned changeAbsFunction(unsigned AbsKind, 8825 AbsoluteValueKind ValueKind) { 8826 switch (ValueKind) { 8827 case AVK_Integer: 8828 switch (AbsKind) { 8829 default: 8830 return 0; 8831 case Builtin::BI__builtin_fabsf: 8832 case Builtin::BI__builtin_fabs: 8833 case Builtin::BI__builtin_fabsl: 8834 case Builtin::BI__builtin_cabsf: 8835 case Builtin::BI__builtin_cabs: 8836 case Builtin::BI__builtin_cabsl: 8837 return Builtin::BI__builtin_abs; 8838 case Builtin::BIfabsf: 8839 case Builtin::BIfabs: 8840 case Builtin::BIfabsl: 8841 case Builtin::BIcabsf: 8842 case Builtin::BIcabs: 8843 case Builtin::BIcabsl: 8844 return Builtin::BIabs; 8845 } 8846 case AVK_Floating: 8847 switch (AbsKind) { 8848 default: 8849 return 0; 8850 case Builtin::BI__builtin_abs: 8851 case Builtin::BI__builtin_labs: 8852 case Builtin::BI__builtin_llabs: 8853 case Builtin::BI__builtin_cabsf: 8854 case Builtin::BI__builtin_cabs: 8855 case Builtin::BI__builtin_cabsl: 8856 return Builtin::BI__builtin_fabsf; 8857 case Builtin::BIabs: 8858 case Builtin::BIlabs: 8859 case Builtin::BIllabs: 8860 case Builtin::BIcabsf: 8861 case Builtin::BIcabs: 8862 case Builtin::BIcabsl: 8863 return Builtin::BIfabsf; 8864 } 8865 case AVK_Complex: 8866 switch (AbsKind) { 8867 default: 8868 return 0; 8869 case Builtin::BI__builtin_abs: 8870 case Builtin::BI__builtin_labs: 8871 case Builtin::BI__builtin_llabs: 8872 case Builtin::BI__builtin_fabsf: 8873 case Builtin::BI__builtin_fabs: 8874 case Builtin::BI__builtin_fabsl: 8875 return Builtin::BI__builtin_cabsf; 8876 case Builtin::BIabs: 8877 case Builtin::BIlabs: 8878 case Builtin::BIllabs: 8879 case Builtin::BIfabsf: 8880 case Builtin::BIfabs: 8881 case Builtin::BIfabsl: 8882 return Builtin::BIcabsf; 8883 } 8884 } 8885 llvm_unreachable("Unable to convert function"); 8886 } 8887 8888 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8889 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8890 if (!FnInfo) 8891 return 0; 8892 8893 switch (FDecl->getBuiltinID()) { 8894 default: 8895 return 0; 8896 case Builtin::BI__builtin_abs: 8897 case Builtin::BI__builtin_fabs: 8898 case Builtin::BI__builtin_fabsf: 8899 case Builtin::BI__builtin_fabsl: 8900 case Builtin::BI__builtin_labs: 8901 case Builtin::BI__builtin_llabs: 8902 case Builtin::BI__builtin_cabs: 8903 case Builtin::BI__builtin_cabsf: 8904 case Builtin::BI__builtin_cabsl: 8905 case Builtin::BIabs: 8906 case Builtin::BIlabs: 8907 case Builtin::BIllabs: 8908 case Builtin::BIfabs: 8909 case Builtin::BIfabsf: 8910 case Builtin::BIfabsl: 8911 case Builtin::BIcabs: 8912 case Builtin::BIcabsf: 8913 case Builtin::BIcabsl: 8914 return FDecl->getBuiltinID(); 8915 } 8916 llvm_unreachable("Unknown Builtin type"); 8917 } 8918 8919 // If the replacement is valid, emit a note with replacement function. 8920 // Additionally, suggest including the proper header if not already included. 8921 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8922 unsigned AbsKind, QualType ArgType) { 8923 bool EmitHeaderHint = true; 8924 const char *HeaderName = nullptr; 8925 const char *FunctionName = nullptr; 8926 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8927 FunctionName = "std::abs"; 8928 if (ArgType->isIntegralOrEnumerationType()) { 8929 HeaderName = "cstdlib"; 8930 } else if (ArgType->isRealFloatingType()) { 8931 HeaderName = "cmath"; 8932 } else { 8933 llvm_unreachable("Invalid Type"); 8934 } 8935 8936 // Lookup all std::abs 8937 if (NamespaceDecl *Std = S.getStdNamespace()) { 8938 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8939 R.suppressDiagnostics(); 8940 S.LookupQualifiedName(R, Std); 8941 8942 for (const auto *I : R) { 8943 const FunctionDecl *FDecl = nullptr; 8944 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8945 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8946 } else { 8947 FDecl = dyn_cast<FunctionDecl>(I); 8948 } 8949 if (!FDecl) 8950 continue; 8951 8952 // Found std::abs(), check that they are the right ones. 8953 if (FDecl->getNumParams() != 1) 8954 continue; 8955 8956 // Check that the parameter type can handle the argument. 8957 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8958 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8959 S.Context.getTypeSize(ArgType) <= 8960 S.Context.getTypeSize(ParamType)) { 8961 // Found a function, don't need the header hint. 8962 EmitHeaderHint = false; 8963 break; 8964 } 8965 } 8966 } 8967 } else { 8968 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8969 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8970 8971 if (HeaderName) { 8972 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8973 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8974 R.suppressDiagnostics(); 8975 S.LookupName(R, S.getCurScope()); 8976 8977 if (R.isSingleResult()) { 8978 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8979 if (FD && FD->getBuiltinID() == AbsKind) { 8980 EmitHeaderHint = false; 8981 } else { 8982 return; 8983 } 8984 } else if (!R.empty()) { 8985 return; 8986 } 8987 } 8988 } 8989 8990 S.Diag(Loc, diag::note_replace_abs_function) 8991 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8992 8993 if (!HeaderName) 8994 return; 8995 8996 if (!EmitHeaderHint) 8997 return; 8998 8999 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9000 << FunctionName; 9001 } 9002 9003 template <std::size_t StrLen> 9004 static bool IsStdFunction(const FunctionDecl *FDecl, 9005 const char (&Str)[StrLen]) { 9006 if (!FDecl) 9007 return false; 9008 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9009 return false; 9010 if (!FDecl->isInStdNamespace()) 9011 return false; 9012 9013 return true; 9014 } 9015 9016 // Warn when using the wrong abs() function. 9017 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9018 const FunctionDecl *FDecl) { 9019 if (Call->getNumArgs() != 1) 9020 return; 9021 9022 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9023 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9024 if (AbsKind == 0 && !IsStdAbs) 9025 return; 9026 9027 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9028 QualType ParamType = Call->getArg(0)->getType(); 9029 9030 // Unsigned types cannot be negative. Suggest removing the absolute value 9031 // function call. 9032 if (ArgType->isUnsignedIntegerType()) { 9033 const char *FunctionName = 9034 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9035 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9036 Diag(Call->getExprLoc(), diag::note_remove_abs) 9037 << FunctionName 9038 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9039 return; 9040 } 9041 9042 // Taking the absolute value of a pointer is very suspicious, they probably 9043 // wanted to index into an array, dereference a pointer, call a function, etc. 9044 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9045 unsigned DiagType = 0; 9046 if (ArgType->isFunctionType()) 9047 DiagType = 1; 9048 else if (ArgType->isArrayType()) 9049 DiagType = 2; 9050 9051 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9052 return; 9053 } 9054 9055 // std::abs has overloads which prevent most of the absolute value problems 9056 // from occurring. 9057 if (IsStdAbs) 9058 return; 9059 9060 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9061 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9062 9063 // The argument and parameter are the same kind. Check if they are the right 9064 // size. 9065 if (ArgValueKind == ParamValueKind) { 9066 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9067 return; 9068 9069 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9070 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9071 << FDecl << ArgType << ParamType; 9072 9073 if (NewAbsKind == 0) 9074 return; 9075 9076 emitReplacement(*this, Call->getExprLoc(), 9077 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9078 return; 9079 } 9080 9081 // ArgValueKind != ParamValueKind 9082 // The wrong type of absolute value function was used. Attempt to find the 9083 // proper one. 9084 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9085 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9086 if (NewAbsKind == 0) 9087 return; 9088 9089 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9090 << FDecl << ParamValueKind << ArgValueKind; 9091 9092 emitReplacement(*this, Call->getExprLoc(), 9093 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9094 } 9095 9096 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9097 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9098 const FunctionDecl *FDecl) { 9099 if (!Call || !FDecl) return; 9100 9101 // Ignore template specializations and macros. 9102 if (inTemplateInstantiation()) return; 9103 if (Call->getExprLoc().isMacroID()) return; 9104 9105 // Only care about the one template argument, two function parameter std::max 9106 if (Call->getNumArgs() != 2) return; 9107 if (!IsStdFunction(FDecl, "max")) return; 9108 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9109 if (!ArgList) return; 9110 if (ArgList->size() != 1) return; 9111 9112 // Check that template type argument is unsigned integer. 9113 const auto& TA = ArgList->get(0); 9114 if (TA.getKind() != TemplateArgument::Type) return; 9115 QualType ArgType = TA.getAsType(); 9116 if (!ArgType->isUnsignedIntegerType()) return; 9117 9118 // See if either argument is a literal zero. 9119 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9120 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9121 if (!MTE) return false; 9122 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9123 if (!Num) return false; 9124 if (Num->getValue() != 0) return false; 9125 return true; 9126 }; 9127 9128 const Expr *FirstArg = Call->getArg(0); 9129 const Expr *SecondArg = Call->getArg(1); 9130 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9131 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9132 9133 // Only warn when exactly one argument is zero. 9134 if (IsFirstArgZero == IsSecondArgZero) return; 9135 9136 SourceRange FirstRange = FirstArg->getSourceRange(); 9137 SourceRange SecondRange = SecondArg->getSourceRange(); 9138 9139 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9140 9141 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9142 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9143 9144 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9145 SourceRange RemovalRange; 9146 if (IsFirstArgZero) { 9147 RemovalRange = SourceRange(FirstRange.getBegin(), 9148 SecondRange.getBegin().getLocWithOffset(-1)); 9149 } else { 9150 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9151 SecondRange.getEnd()); 9152 } 9153 9154 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9155 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9156 << FixItHint::CreateRemoval(RemovalRange); 9157 } 9158 9159 //===--- CHECK: Standard memory functions ---------------------------------===// 9160 9161 /// Takes the expression passed to the size_t parameter of functions 9162 /// such as memcmp, strncat, etc and warns if it's a comparison. 9163 /// 9164 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9165 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9166 IdentifierInfo *FnName, 9167 SourceLocation FnLoc, 9168 SourceLocation RParenLoc) { 9169 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9170 if (!Size) 9171 return false; 9172 9173 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9174 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9175 return false; 9176 9177 SourceRange SizeRange = Size->getSourceRange(); 9178 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9179 << SizeRange << FnName; 9180 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9181 << FnName 9182 << FixItHint::CreateInsertion( 9183 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9184 << FixItHint::CreateRemoval(RParenLoc); 9185 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9186 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9187 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9188 ")"); 9189 9190 return true; 9191 } 9192 9193 /// Determine whether the given type is or contains a dynamic class type 9194 /// (e.g., whether it has a vtable). 9195 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9196 bool &IsContained) { 9197 // Look through array types while ignoring qualifiers. 9198 const Type *Ty = T->getBaseElementTypeUnsafe(); 9199 IsContained = false; 9200 9201 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9202 RD = RD ? RD->getDefinition() : nullptr; 9203 if (!RD || RD->isInvalidDecl()) 9204 return nullptr; 9205 9206 if (RD->isDynamicClass()) 9207 return RD; 9208 9209 // Check all the fields. If any bases were dynamic, the class is dynamic. 9210 // It's impossible for a class to transitively contain itself by value, so 9211 // infinite recursion is impossible. 9212 for (auto *FD : RD->fields()) { 9213 bool SubContained; 9214 if (const CXXRecordDecl *ContainedRD = 9215 getContainedDynamicClass(FD->getType(), SubContained)) { 9216 IsContained = true; 9217 return ContainedRD; 9218 } 9219 } 9220 9221 return nullptr; 9222 } 9223 9224 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9225 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9226 if (Unary->getKind() == UETT_SizeOf) 9227 return Unary; 9228 return nullptr; 9229 } 9230 9231 /// If E is a sizeof expression, returns its argument expression, 9232 /// otherwise returns NULL. 9233 static const Expr *getSizeOfExprArg(const Expr *E) { 9234 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9235 if (!SizeOf->isArgumentType()) 9236 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9237 return nullptr; 9238 } 9239 9240 /// If E is a sizeof expression, returns its argument type. 9241 static QualType getSizeOfArgType(const Expr *E) { 9242 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9243 return SizeOf->getTypeOfArgument(); 9244 return QualType(); 9245 } 9246 9247 namespace { 9248 9249 struct SearchNonTrivialToInitializeField 9250 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9251 using Super = 9252 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9253 9254 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9255 9256 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9257 SourceLocation SL) { 9258 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9259 asDerived().visitArray(PDIK, AT, SL); 9260 return; 9261 } 9262 9263 Super::visitWithKind(PDIK, FT, SL); 9264 } 9265 9266 void visitARCStrong(QualType FT, SourceLocation SL) { 9267 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9268 } 9269 void visitARCWeak(QualType FT, SourceLocation SL) { 9270 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9271 } 9272 void visitStruct(QualType FT, SourceLocation SL) { 9273 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9274 visit(FD->getType(), FD->getLocation()); 9275 } 9276 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9277 const ArrayType *AT, SourceLocation SL) { 9278 visit(getContext().getBaseElementType(AT), SL); 9279 } 9280 void visitTrivial(QualType FT, SourceLocation SL) {} 9281 9282 static void diag(QualType RT, const Expr *E, Sema &S) { 9283 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9284 } 9285 9286 ASTContext &getContext() { return S.getASTContext(); } 9287 9288 const Expr *E; 9289 Sema &S; 9290 }; 9291 9292 struct SearchNonTrivialToCopyField 9293 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9294 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9295 9296 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9297 9298 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9299 SourceLocation SL) { 9300 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9301 asDerived().visitArray(PCK, AT, SL); 9302 return; 9303 } 9304 9305 Super::visitWithKind(PCK, FT, SL); 9306 } 9307 9308 void visitARCStrong(QualType FT, SourceLocation SL) { 9309 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9310 } 9311 void visitARCWeak(QualType FT, SourceLocation SL) { 9312 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9313 } 9314 void visitStruct(QualType FT, SourceLocation SL) { 9315 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9316 visit(FD->getType(), FD->getLocation()); 9317 } 9318 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9319 SourceLocation SL) { 9320 visit(getContext().getBaseElementType(AT), SL); 9321 } 9322 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9323 SourceLocation SL) {} 9324 void visitTrivial(QualType FT, SourceLocation SL) {} 9325 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9326 9327 static void diag(QualType RT, const Expr *E, Sema &S) { 9328 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9329 } 9330 9331 ASTContext &getContext() { return S.getASTContext(); } 9332 9333 const Expr *E; 9334 Sema &S; 9335 }; 9336 9337 } 9338 9339 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9340 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9341 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9342 9343 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9344 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9345 return false; 9346 9347 return doesExprLikelyComputeSize(BO->getLHS()) || 9348 doesExprLikelyComputeSize(BO->getRHS()); 9349 } 9350 9351 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9352 } 9353 9354 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9355 /// 9356 /// \code 9357 /// #define MACRO 0 9358 /// foo(MACRO); 9359 /// foo(0); 9360 /// \endcode 9361 /// 9362 /// This should return true for the first call to foo, but not for the second 9363 /// (regardless of whether foo is a macro or function). 9364 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9365 SourceLocation CallLoc, 9366 SourceLocation ArgLoc) { 9367 if (!CallLoc.isMacroID()) 9368 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9369 9370 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9371 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9372 } 9373 9374 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9375 /// last two arguments transposed. 9376 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9377 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9378 return; 9379 9380 const Expr *SizeArg = 9381 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9382 9383 auto isLiteralZero = [](const Expr *E) { 9384 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9385 }; 9386 9387 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9388 SourceLocation CallLoc = Call->getRParenLoc(); 9389 SourceManager &SM = S.getSourceManager(); 9390 if (isLiteralZero(SizeArg) && 9391 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9392 9393 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9394 9395 // Some platforms #define bzero to __builtin_memset. See if this is the 9396 // case, and if so, emit a better diagnostic. 9397 if (BId == Builtin::BIbzero || 9398 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9399 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9400 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9401 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9402 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9403 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9404 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9405 } 9406 return; 9407 } 9408 9409 // If the second argument to a memset is a sizeof expression and the third 9410 // isn't, this is also likely an error. This should catch 9411 // 'memset(buf, sizeof(buf), 0xff)'. 9412 if (BId == Builtin::BImemset && 9413 doesExprLikelyComputeSize(Call->getArg(1)) && 9414 !doesExprLikelyComputeSize(Call->getArg(2))) { 9415 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9416 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9417 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9418 return; 9419 } 9420 } 9421 9422 /// Check for dangerous or invalid arguments to memset(). 9423 /// 9424 /// This issues warnings on known problematic, dangerous or unspecified 9425 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9426 /// function calls. 9427 /// 9428 /// \param Call The call expression to diagnose. 9429 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9430 unsigned BId, 9431 IdentifierInfo *FnName) { 9432 assert(BId != 0); 9433 9434 // It is possible to have a non-standard definition of memset. Validate 9435 // we have enough arguments, and if not, abort further checking. 9436 unsigned ExpectedNumArgs = 9437 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9438 if (Call->getNumArgs() < ExpectedNumArgs) 9439 return; 9440 9441 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9442 BId == Builtin::BIstrndup ? 1 : 2); 9443 unsigned LenArg = 9444 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9445 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9446 9447 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9448 Call->getBeginLoc(), Call->getRParenLoc())) 9449 return; 9450 9451 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9452 CheckMemaccessSize(*this, BId, Call); 9453 9454 // We have special checking when the length is a sizeof expression. 9455 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9456 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9457 llvm::FoldingSetNodeID SizeOfArgID; 9458 9459 // Although widely used, 'bzero' is not a standard function. Be more strict 9460 // with the argument types before allowing diagnostics and only allow the 9461 // form bzero(ptr, sizeof(...)). 9462 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9463 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9464 return; 9465 9466 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9467 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9468 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9469 9470 QualType DestTy = Dest->getType(); 9471 QualType PointeeTy; 9472 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9473 PointeeTy = DestPtrTy->getPointeeType(); 9474 9475 // Never warn about void type pointers. This can be used to suppress 9476 // false positives. 9477 if (PointeeTy->isVoidType()) 9478 continue; 9479 9480 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9481 // actually comparing the expressions for equality. Because computing the 9482 // expression IDs can be expensive, we only do this if the diagnostic is 9483 // enabled. 9484 if (SizeOfArg && 9485 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9486 SizeOfArg->getExprLoc())) { 9487 // We only compute IDs for expressions if the warning is enabled, and 9488 // cache the sizeof arg's ID. 9489 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9490 SizeOfArg->Profile(SizeOfArgID, Context, true); 9491 llvm::FoldingSetNodeID DestID; 9492 Dest->Profile(DestID, Context, true); 9493 if (DestID == SizeOfArgID) { 9494 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9495 // over sizeof(src) as well. 9496 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9497 StringRef ReadableName = FnName->getName(); 9498 9499 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9500 if (UnaryOp->getOpcode() == UO_AddrOf) 9501 ActionIdx = 1; // If its an address-of operator, just remove it. 9502 if (!PointeeTy->isIncompleteType() && 9503 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9504 ActionIdx = 2; // If the pointee's size is sizeof(char), 9505 // suggest an explicit length. 9506 9507 // If the function is defined as a builtin macro, do not show macro 9508 // expansion. 9509 SourceLocation SL = SizeOfArg->getExprLoc(); 9510 SourceRange DSR = Dest->getSourceRange(); 9511 SourceRange SSR = SizeOfArg->getSourceRange(); 9512 SourceManager &SM = getSourceManager(); 9513 9514 if (SM.isMacroArgExpansion(SL)) { 9515 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9516 SL = SM.getSpellingLoc(SL); 9517 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9518 SM.getSpellingLoc(DSR.getEnd())); 9519 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9520 SM.getSpellingLoc(SSR.getEnd())); 9521 } 9522 9523 DiagRuntimeBehavior(SL, SizeOfArg, 9524 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9525 << ReadableName 9526 << PointeeTy 9527 << DestTy 9528 << DSR 9529 << SSR); 9530 DiagRuntimeBehavior(SL, SizeOfArg, 9531 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9532 << ActionIdx 9533 << SSR); 9534 9535 break; 9536 } 9537 } 9538 9539 // Also check for cases where the sizeof argument is the exact same 9540 // type as the memory argument, and where it points to a user-defined 9541 // record type. 9542 if (SizeOfArgTy != QualType()) { 9543 if (PointeeTy->isRecordType() && 9544 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9545 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9546 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9547 << FnName << SizeOfArgTy << ArgIdx 9548 << PointeeTy << Dest->getSourceRange() 9549 << LenExpr->getSourceRange()); 9550 break; 9551 } 9552 } 9553 } else if (DestTy->isArrayType()) { 9554 PointeeTy = DestTy; 9555 } 9556 9557 if (PointeeTy == QualType()) 9558 continue; 9559 9560 // Always complain about dynamic classes. 9561 bool IsContained; 9562 if (const CXXRecordDecl *ContainedRD = 9563 getContainedDynamicClass(PointeeTy, IsContained)) { 9564 9565 unsigned OperationType = 0; 9566 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9567 // "overwritten" if we're warning about the destination for any call 9568 // but memcmp; otherwise a verb appropriate to the call. 9569 if (ArgIdx != 0 || IsCmp) { 9570 if (BId == Builtin::BImemcpy) 9571 OperationType = 1; 9572 else if(BId == Builtin::BImemmove) 9573 OperationType = 2; 9574 else if (IsCmp) 9575 OperationType = 3; 9576 } 9577 9578 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9579 PDiag(diag::warn_dyn_class_memaccess) 9580 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9581 << IsContained << ContainedRD << OperationType 9582 << Call->getCallee()->getSourceRange()); 9583 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9584 BId != Builtin::BImemset) 9585 DiagRuntimeBehavior( 9586 Dest->getExprLoc(), Dest, 9587 PDiag(diag::warn_arc_object_memaccess) 9588 << ArgIdx << FnName << PointeeTy 9589 << Call->getCallee()->getSourceRange()); 9590 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9591 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9592 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9593 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9594 PDiag(diag::warn_cstruct_memaccess) 9595 << ArgIdx << FnName << PointeeTy << 0); 9596 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9597 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9598 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9599 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9600 PDiag(diag::warn_cstruct_memaccess) 9601 << ArgIdx << FnName << PointeeTy << 1); 9602 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9603 } else { 9604 continue; 9605 } 9606 } else 9607 continue; 9608 9609 DiagRuntimeBehavior( 9610 Dest->getExprLoc(), Dest, 9611 PDiag(diag::note_bad_memaccess_silence) 9612 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9613 break; 9614 } 9615 } 9616 9617 // A little helper routine: ignore addition and subtraction of integer literals. 9618 // This intentionally does not ignore all integer constant expressions because 9619 // we don't want to remove sizeof(). 9620 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9621 Ex = Ex->IgnoreParenCasts(); 9622 9623 while (true) { 9624 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9625 if (!BO || !BO->isAdditiveOp()) 9626 break; 9627 9628 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9629 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9630 9631 if (isa<IntegerLiteral>(RHS)) 9632 Ex = LHS; 9633 else if (isa<IntegerLiteral>(LHS)) 9634 Ex = RHS; 9635 else 9636 break; 9637 } 9638 9639 return Ex; 9640 } 9641 9642 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9643 ASTContext &Context) { 9644 // Only handle constant-sized or VLAs, but not flexible members. 9645 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9646 // Only issue the FIXIT for arrays of size > 1. 9647 if (CAT->getSize().getSExtValue() <= 1) 9648 return false; 9649 } else if (!Ty->isVariableArrayType()) { 9650 return false; 9651 } 9652 return true; 9653 } 9654 9655 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9656 // be the size of the source, instead of the destination. 9657 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9658 IdentifierInfo *FnName) { 9659 9660 // Don't crash if the user has the wrong number of arguments 9661 unsigned NumArgs = Call->getNumArgs(); 9662 if ((NumArgs != 3) && (NumArgs != 4)) 9663 return; 9664 9665 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9666 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9667 const Expr *CompareWithSrc = nullptr; 9668 9669 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9670 Call->getBeginLoc(), Call->getRParenLoc())) 9671 return; 9672 9673 // Look for 'strlcpy(dst, x, sizeof(x))' 9674 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9675 CompareWithSrc = Ex; 9676 else { 9677 // Look for 'strlcpy(dst, x, strlen(x))' 9678 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9679 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9680 SizeCall->getNumArgs() == 1) 9681 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9682 } 9683 } 9684 9685 if (!CompareWithSrc) 9686 return; 9687 9688 // Determine if the argument to sizeof/strlen is equal to the source 9689 // argument. In principle there's all kinds of things you could do 9690 // here, for instance creating an == expression and evaluating it with 9691 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9692 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9693 if (!SrcArgDRE) 9694 return; 9695 9696 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9697 if (!CompareWithSrcDRE || 9698 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9699 return; 9700 9701 const Expr *OriginalSizeArg = Call->getArg(2); 9702 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9703 << OriginalSizeArg->getSourceRange() << FnName; 9704 9705 // Output a FIXIT hint if the destination is an array (rather than a 9706 // pointer to an array). This could be enhanced to handle some 9707 // pointers if we know the actual size, like if DstArg is 'array+2' 9708 // we could say 'sizeof(array)-2'. 9709 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9710 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9711 return; 9712 9713 SmallString<128> sizeString; 9714 llvm::raw_svector_ostream OS(sizeString); 9715 OS << "sizeof("; 9716 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9717 OS << ")"; 9718 9719 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9720 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9721 OS.str()); 9722 } 9723 9724 /// Check if two expressions refer to the same declaration. 9725 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9726 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9727 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9728 return D1->getDecl() == D2->getDecl(); 9729 return false; 9730 } 9731 9732 static const Expr *getStrlenExprArg(const Expr *E) { 9733 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9734 const FunctionDecl *FD = CE->getDirectCallee(); 9735 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9736 return nullptr; 9737 return CE->getArg(0)->IgnoreParenCasts(); 9738 } 9739 return nullptr; 9740 } 9741 9742 // Warn on anti-patterns as the 'size' argument to strncat. 9743 // The correct size argument should look like following: 9744 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9745 void Sema::CheckStrncatArguments(const CallExpr *CE, 9746 IdentifierInfo *FnName) { 9747 // Don't crash if the user has the wrong number of arguments. 9748 if (CE->getNumArgs() < 3) 9749 return; 9750 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9751 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9752 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9753 9754 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9755 CE->getRParenLoc())) 9756 return; 9757 9758 // Identify common expressions, which are wrongly used as the size argument 9759 // to strncat and may lead to buffer overflows. 9760 unsigned PatternType = 0; 9761 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9762 // - sizeof(dst) 9763 if (referToTheSameDecl(SizeOfArg, DstArg)) 9764 PatternType = 1; 9765 // - sizeof(src) 9766 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9767 PatternType = 2; 9768 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9769 if (BE->getOpcode() == BO_Sub) { 9770 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9771 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9772 // - sizeof(dst) - strlen(dst) 9773 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9774 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9775 PatternType = 1; 9776 // - sizeof(src) - (anything) 9777 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9778 PatternType = 2; 9779 } 9780 } 9781 9782 if (PatternType == 0) 9783 return; 9784 9785 // Generate the diagnostic. 9786 SourceLocation SL = LenArg->getBeginLoc(); 9787 SourceRange SR = LenArg->getSourceRange(); 9788 SourceManager &SM = getSourceManager(); 9789 9790 // If the function is defined as a builtin macro, do not show macro expansion. 9791 if (SM.isMacroArgExpansion(SL)) { 9792 SL = SM.getSpellingLoc(SL); 9793 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9794 SM.getSpellingLoc(SR.getEnd())); 9795 } 9796 9797 // Check if the destination is an array (rather than a pointer to an array). 9798 QualType DstTy = DstArg->getType(); 9799 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9800 Context); 9801 if (!isKnownSizeArray) { 9802 if (PatternType == 1) 9803 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9804 else 9805 Diag(SL, diag::warn_strncat_src_size) << SR; 9806 return; 9807 } 9808 9809 if (PatternType == 1) 9810 Diag(SL, diag::warn_strncat_large_size) << SR; 9811 else 9812 Diag(SL, diag::warn_strncat_src_size) << SR; 9813 9814 SmallString<128> sizeString; 9815 llvm::raw_svector_ostream OS(sizeString); 9816 OS << "sizeof("; 9817 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9818 OS << ") - "; 9819 OS << "strlen("; 9820 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9821 OS << ") - 1"; 9822 9823 Diag(SL, diag::note_strncat_wrong_size) 9824 << FixItHint::CreateReplacement(SR, OS.str()); 9825 } 9826 9827 void 9828 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9829 SourceLocation ReturnLoc, 9830 bool isObjCMethod, 9831 const AttrVec *Attrs, 9832 const FunctionDecl *FD) { 9833 // Check if the return value is null but should not be. 9834 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9835 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9836 CheckNonNullExpr(*this, RetValExp)) 9837 Diag(ReturnLoc, diag::warn_null_ret) 9838 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9839 9840 // C++11 [basic.stc.dynamic.allocation]p4: 9841 // If an allocation function declared with a non-throwing 9842 // exception-specification fails to allocate storage, it shall return 9843 // a null pointer. Any other allocation function that fails to allocate 9844 // storage shall indicate failure only by throwing an exception [...] 9845 if (FD) { 9846 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9847 if (Op == OO_New || Op == OO_Array_New) { 9848 const FunctionProtoType *Proto 9849 = FD->getType()->castAs<FunctionProtoType>(); 9850 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9851 CheckNonNullExpr(*this, RetValExp)) 9852 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9853 << FD << getLangOpts().CPlusPlus11; 9854 } 9855 } 9856 } 9857 9858 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9859 9860 /// Check for comparisons of floating point operands using != and ==. 9861 /// Issue a warning if these are no self-comparisons, as they are not likely 9862 /// to do what the programmer intended. 9863 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9864 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9865 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9866 9867 // Special case: check for x == x (which is OK). 9868 // Do not emit warnings for such cases. 9869 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9870 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9871 if (DRL->getDecl() == DRR->getDecl()) 9872 return; 9873 9874 // Special case: check for comparisons against literals that can be exactly 9875 // represented by APFloat. In such cases, do not emit a warning. This 9876 // is a heuristic: often comparison against such literals are used to 9877 // detect if a value in a variable has not changed. This clearly can 9878 // lead to false negatives. 9879 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9880 if (FLL->isExact()) 9881 return; 9882 } else 9883 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9884 if (FLR->isExact()) 9885 return; 9886 9887 // Check for comparisons with builtin types. 9888 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9889 if (CL->getBuiltinCallee()) 9890 return; 9891 9892 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9893 if (CR->getBuiltinCallee()) 9894 return; 9895 9896 // Emit the diagnostic. 9897 Diag(Loc, diag::warn_floatingpoint_eq) 9898 << LHS->getSourceRange() << RHS->getSourceRange(); 9899 } 9900 9901 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9902 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9903 9904 namespace { 9905 9906 /// Structure recording the 'active' range of an integer-valued 9907 /// expression. 9908 struct IntRange { 9909 /// The number of bits active in the int. 9910 unsigned Width; 9911 9912 /// True if the int is known not to have negative values. 9913 bool NonNegative; 9914 9915 IntRange(unsigned Width, bool NonNegative) 9916 : Width(Width), NonNegative(NonNegative) {} 9917 9918 /// Returns the range of the bool type. 9919 static IntRange forBoolType() { 9920 return IntRange(1, true); 9921 } 9922 9923 /// Returns the range of an opaque value of the given integral type. 9924 static IntRange forValueOfType(ASTContext &C, QualType T) { 9925 return forValueOfCanonicalType(C, 9926 T->getCanonicalTypeInternal().getTypePtr()); 9927 } 9928 9929 /// Returns the range of an opaque value of a canonical integral type. 9930 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9931 assert(T->isCanonicalUnqualified()); 9932 9933 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9934 T = VT->getElementType().getTypePtr(); 9935 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9936 T = CT->getElementType().getTypePtr(); 9937 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9938 T = AT->getValueType().getTypePtr(); 9939 9940 if (!C.getLangOpts().CPlusPlus) { 9941 // For enum types in C code, use the underlying datatype. 9942 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9943 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9944 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9945 // For enum types in C++, use the known bit width of the enumerators. 9946 EnumDecl *Enum = ET->getDecl(); 9947 // In C++11, enums can have a fixed underlying type. Use this type to 9948 // compute the range. 9949 if (Enum->isFixed()) { 9950 return IntRange(C.getIntWidth(QualType(T, 0)), 9951 !ET->isSignedIntegerOrEnumerationType()); 9952 } 9953 9954 unsigned NumPositive = Enum->getNumPositiveBits(); 9955 unsigned NumNegative = Enum->getNumNegativeBits(); 9956 9957 if (NumNegative == 0) 9958 return IntRange(NumPositive, true/*NonNegative*/); 9959 else 9960 return IntRange(std::max(NumPositive + 1, NumNegative), 9961 false/*NonNegative*/); 9962 } 9963 9964 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 9965 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 9966 9967 const BuiltinType *BT = cast<BuiltinType>(T); 9968 assert(BT->isInteger()); 9969 9970 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9971 } 9972 9973 /// Returns the "target" range of a canonical integral type, i.e. 9974 /// the range of values expressible in the type. 9975 /// 9976 /// This matches forValueOfCanonicalType except that enums have the 9977 /// full range of their type, not the range of their enumerators. 9978 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9979 assert(T->isCanonicalUnqualified()); 9980 9981 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9982 T = VT->getElementType().getTypePtr(); 9983 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9984 T = CT->getElementType().getTypePtr(); 9985 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9986 T = AT->getValueType().getTypePtr(); 9987 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9988 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9989 9990 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 9991 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 9992 9993 const BuiltinType *BT = cast<BuiltinType>(T); 9994 assert(BT->isInteger()); 9995 9996 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9997 } 9998 9999 /// Returns the supremum of two ranges: i.e. their conservative merge. 10000 static IntRange join(IntRange L, IntRange R) { 10001 return IntRange(std::max(L.Width, R.Width), 10002 L.NonNegative && R.NonNegative); 10003 } 10004 10005 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10006 static IntRange meet(IntRange L, IntRange R) { 10007 return IntRange(std::min(L.Width, R.Width), 10008 L.NonNegative || R.NonNegative); 10009 } 10010 }; 10011 10012 } // namespace 10013 10014 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10015 unsigned MaxWidth) { 10016 if (value.isSigned() && value.isNegative()) 10017 return IntRange(value.getMinSignedBits(), false); 10018 10019 if (value.getBitWidth() > MaxWidth) 10020 value = value.trunc(MaxWidth); 10021 10022 // isNonNegative() just checks the sign bit without considering 10023 // signedness. 10024 return IntRange(value.getActiveBits(), true); 10025 } 10026 10027 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10028 unsigned MaxWidth) { 10029 if (result.isInt()) 10030 return GetValueRange(C, result.getInt(), MaxWidth); 10031 10032 if (result.isVector()) { 10033 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10034 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10035 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10036 R = IntRange::join(R, El); 10037 } 10038 return R; 10039 } 10040 10041 if (result.isComplexInt()) { 10042 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10043 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10044 return IntRange::join(R, I); 10045 } 10046 10047 // This can happen with lossless casts to intptr_t of "based" lvalues. 10048 // Assume it might use arbitrary bits. 10049 // FIXME: The only reason we need to pass the type in here is to get 10050 // the sign right on this one case. It would be nice if APValue 10051 // preserved this. 10052 assert(result.isLValue() || result.isAddrLabelDiff()); 10053 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10054 } 10055 10056 static QualType GetExprType(const Expr *E) { 10057 QualType Ty = E->getType(); 10058 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10059 Ty = AtomicRHS->getValueType(); 10060 return Ty; 10061 } 10062 10063 /// Pseudo-evaluate the given integer expression, estimating the 10064 /// range of values it might take. 10065 /// 10066 /// \param MaxWidth - the width to which the value will be truncated 10067 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10068 bool InConstantContext) { 10069 E = E->IgnoreParens(); 10070 10071 // Try a full evaluation first. 10072 Expr::EvalResult result; 10073 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10074 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10075 10076 // I think we only want to look through implicit casts here; if the 10077 // user has an explicit widening cast, we should treat the value as 10078 // being of the new, wider type. 10079 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10080 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10081 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10082 10083 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10084 10085 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10086 CE->getCastKind() == CK_BooleanToSignedIntegral; 10087 10088 // Assume that non-integer casts can span the full range of the type. 10089 if (!isIntegerCast) 10090 return OutputTypeRange; 10091 10092 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10093 std::min(MaxWidth, OutputTypeRange.Width), 10094 InConstantContext); 10095 10096 // Bail out if the subexpr's range is as wide as the cast type. 10097 if (SubRange.Width >= OutputTypeRange.Width) 10098 return OutputTypeRange; 10099 10100 // Otherwise, we take the smaller width, and we're non-negative if 10101 // either the output type or the subexpr is. 10102 return IntRange(SubRange.Width, 10103 SubRange.NonNegative || OutputTypeRange.NonNegative); 10104 } 10105 10106 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10107 // If we can fold the condition, just take that operand. 10108 bool CondResult; 10109 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10110 return GetExprRange(C, 10111 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10112 MaxWidth, InConstantContext); 10113 10114 // Otherwise, conservatively merge. 10115 IntRange L = 10116 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10117 IntRange R = 10118 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10119 return IntRange::join(L, R); 10120 } 10121 10122 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10123 switch (BO->getOpcode()) { 10124 case BO_Cmp: 10125 llvm_unreachable("builtin <=> should have class type"); 10126 10127 // Boolean-valued operations are single-bit and positive. 10128 case BO_LAnd: 10129 case BO_LOr: 10130 case BO_LT: 10131 case BO_GT: 10132 case BO_LE: 10133 case BO_GE: 10134 case BO_EQ: 10135 case BO_NE: 10136 return IntRange::forBoolType(); 10137 10138 // The type of the assignments is the type of the LHS, so the RHS 10139 // is not necessarily the same type. 10140 case BO_MulAssign: 10141 case BO_DivAssign: 10142 case BO_RemAssign: 10143 case BO_AddAssign: 10144 case BO_SubAssign: 10145 case BO_XorAssign: 10146 case BO_OrAssign: 10147 // TODO: bitfields? 10148 return IntRange::forValueOfType(C, GetExprType(E)); 10149 10150 // Simple assignments just pass through the RHS, which will have 10151 // been coerced to the LHS type. 10152 case BO_Assign: 10153 // TODO: bitfields? 10154 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10155 10156 // Operations with opaque sources are black-listed. 10157 case BO_PtrMemD: 10158 case BO_PtrMemI: 10159 return IntRange::forValueOfType(C, GetExprType(E)); 10160 10161 // Bitwise-and uses the *infinum* of the two source ranges. 10162 case BO_And: 10163 case BO_AndAssign: 10164 return IntRange::meet( 10165 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10166 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10167 10168 // Left shift gets black-listed based on a judgement call. 10169 case BO_Shl: 10170 // ...except that we want to treat '1 << (blah)' as logically 10171 // positive. It's an important idiom. 10172 if (IntegerLiteral *I 10173 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10174 if (I->getValue() == 1) { 10175 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10176 return IntRange(R.Width, /*NonNegative*/ true); 10177 } 10178 } 10179 LLVM_FALLTHROUGH; 10180 10181 case BO_ShlAssign: 10182 return IntRange::forValueOfType(C, GetExprType(E)); 10183 10184 // Right shift by a constant can narrow its left argument. 10185 case BO_Shr: 10186 case BO_ShrAssign: { 10187 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10188 10189 // If the shift amount is a positive constant, drop the width by 10190 // that much. 10191 llvm::APSInt shift; 10192 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10193 shift.isNonNegative()) { 10194 unsigned zext = shift.getZExtValue(); 10195 if (zext >= L.Width) 10196 L.Width = (L.NonNegative ? 0 : 1); 10197 else 10198 L.Width -= zext; 10199 } 10200 10201 return L; 10202 } 10203 10204 // Comma acts as its right operand. 10205 case BO_Comma: 10206 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10207 10208 // Black-list pointer subtractions. 10209 case BO_Sub: 10210 if (BO->getLHS()->getType()->isPointerType()) 10211 return IntRange::forValueOfType(C, GetExprType(E)); 10212 break; 10213 10214 // The width of a division result is mostly determined by the size 10215 // of the LHS. 10216 case BO_Div: { 10217 // Don't 'pre-truncate' the operands. 10218 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10219 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10220 10221 // If the divisor is constant, use that. 10222 llvm::APSInt divisor; 10223 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10224 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10225 if (log2 >= L.Width) 10226 L.Width = (L.NonNegative ? 0 : 1); 10227 else 10228 L.Width = std::min(L.Width - log2, MaxWidth); 10229 return L; 10230 } 10231 10232 // Otherwise, just use the LHS's width. 10233 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10234 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10235 } 10236 10237 // The result of a remainder can't be larger than the result of 10238 // either side. 10239 case BO_Rem: { 10240 // Don't 'pre-truncate' the operands. 10241 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10242 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10243 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10244 10245 IntRange meet = IntRange::meet(L, R); 10246 meet.Width = std::min(meet.Width, MaxWidth); 10247 return meet; 10248 } 10249 10250 // The default behavior is okay for these. 10251 case BO_Mul: 10252 case BO_Add: 10253 case BO_Xor: 10254 case BO_Or: 10255 break; 10256 } 10257 10258 // The default case is to treat the operation as if it were closed 10259 // on the narrowest type that encompasses both operands. 10260 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10261 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10262 return IntRange::join(L, R); 10263 } 10264 10265 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10266 switch (UO->getOpcode()) { 10267 // Boolean-valued operations are white-listed. 10268 case UO_LNot: 10269 return IntRange::forBoolType(); 10270 10271 // Operations with opaque sources are black-listed. 10272 case UO_Deref: 10273 case UO_AddrOf: // should be impossible 10274 return IntRange::forValueOfType(C, GetExprType(E)); 10275 10276 default: 10277 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10278 } 10279 } 10280 10281 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10282 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10283 10284 if (const auto *BitField = E->getSourceBitField()) 10285 return IntRange(BitField->getBitWidthValue(C), 10286 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10287 10288 return IntRange::forValueOfType(C, GetExprType(E)); 10289 } 10290 10291 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10292 bool InConstantContext) { 10293 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10294 } 10295 10296 /// Checks whether the given value, which currently has the given 10297 /// source semantics, has the same value when coerced through the 10298 /// target semantics. 10299 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10300 const llvm::fltSemantics &Src, 10301 const llvm::fltSemantics &Tgt) { 10302 llvm::APFloat truncated = value; 10303 10304 bool ignored; 10305 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10306 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10307 10308 return truncated.bitwiseIsEqual(value); 10309 } 10310 10311 /// Checks whether the given value, which currently has the given 10312 /// source semantics, has the same value when coerced through the 10313 /// target semantics. 10314 /// 10315 /// The value might be a vector of floats (or a complex number). 10316 static bool IsSameFloatAfterCast(const APValue &value, 10317 const llvm::fltSemantics &Src, 10318 const llvm::fltSemantics &Tgt) { 10319 if (value.isFloat()) 10320 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10321 10322 if (value.isVector()) { 10323 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10324 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10325 return false; 10326 return true; 10327 } 10328 10329 assert(value.isComplexFloat()); 10330 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10331 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10332 } 10333 10334 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10335 bool IsListInit = false); 10336 10337 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10338 // Suppress cases where we are comparing against an enum constant. 10339 if (const DeclRefExpr *DR = 10340 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10341 if (isa<EnumConstantDecl>(DR->getDecl())) 10342 return true; 10343 10344 // Suppress cases where the value is expanded from a macro, unless that macro 10345 // is how a language represents a boolean literal. This is the case in both C 10346 // and Objective-C. 10347 SourceLocation BeginLoc = E->getBeginLoc(); 10348 if (BeginLoc.isMacroID()) { 10349 StringRef MacroName = Lexer::getImmediateMacroName( 10350 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10351 return MacroName != "YES" && MacroName != "NO" && 10352 MacroName != "true" && MacroName != "false"; 10353 } 10354 10355 return false; 10356 } 10357 10358 static bool isKnownToHaveUnsignedValue(Expr *E) { 10359 return E->getType()->isIntegerType() && 10360 (!E->getType()->isSignedIntegerType() || 10361 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10362 } 10363 10364 namespace { 10365 /// The promoted range of values of a type. In general this has the 10366 /// following structure: 10367 /// 10368 /// |-----------| . . . |-----------| 10369 /// ^ ^ ^ ^ 10370 /// Min HoleMin HoleMax Max 10371 /// 10372 /// ... where there is only a hole if a signed type is promoted to unsigned 10373 /// (in which case Min and Max are the smallest and largest representable 10374 /// values). 10375 struct PromotedRange { 10376 // Min, or HoleMax if there is a hole. 10377 llvm::APSInt PromotedMin; 10378 // Max, or HoleMin if there is a hole. 10379 llvm::APSInt PromotedMax; 10380 10381 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10382 if (R.Width == 0) 10383 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10384 else if (R.Width >= BitWidth && !Unsigned) { 10385 // Promotion made the type *narrower*. This happens when promoting 10386 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10387 // Treat all values of 'signed int' as being in range for now. 10388 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10389 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10390 } else { 10391 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10392 .extOrTrunc(BitWidth); 10393 PromotedMin.setIsUnsigned(Unsigned); 10394 10395 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10396 .extOrTrunc(BitWidth); 10397 PromotedMax.setIsUnsigned(Unsigned); 10398 } 10399 } 10400 10401 // Determine whether this range is contiguous (has no hole). 10402 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10403 10404 // Where a constant value is within the range. 10405 enum ComparisonResult { 10406 LT = 0x1, 10407 LE = 0x2, 10408 GT = 0x4, 10409 GE = 0x8, 10410 EQ = 0x10, 10411 NE = 0x20, 10412 InRangeFlag = 0x40, 10413 10414 Less = LE | LT | NE, 10415 Min = LE | InRangeFlag, 10416 InRange = InRangeFlag, 10417 Max = GE | InRangeFlag, 10418 Greater = GE | GT | NE, 10419 10420 OnlyValue = LE | GE | EQ | InRangeFlag, 10421 InHole = NE 10422 }; 10423 10424 ComparisonResult compare(const llvm::APSInt &Value) const { 10425 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10426 Value.isUnsigned() == PromotedMin.isUnsigned()); 10427 if (!isContiguous()) { 10428 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10429 if (Value.isMinValue()) return Min; 10430 if (Value.isMaxValue()) return Max; 10431 if (Value >= PromotedMin) return InRange; 10432 if (Value <= PromotedMax) return InRange; 10433 return InHole; 10434 } 10435 10436 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10437 case -1: return Less; 10438 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10439 case 1: 10440 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10441 case -1: return InRange; 10442 case 0: return Max; 10443 case 1: return Greater; 10444 } 10445 } 10446 10447 llvm_unreachable("impossible compare result"); 10448 } 10449 10450 static llvm::Optional<StringRef> 10451 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10452 if (Op == BO_Cmp) { 10453 ComparisonResult LTFlag = LT, GTFlag = GT; 10454 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10455 10456 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10457 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10458 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10459 return llvm::None; 10460 } 10461 10462 ComparisonResult TrueFlag, FalseFlag; 10463 if (Op == BO_EQ) { 10464 TrueFlag = EQ; 10465 FalseFlag = NE; 10466 } else if (Op == BO_NE) { 10467 TrueFlag = NE; 10468 FalseFlag = EQ; 10469 } else { 10470 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10471 TrueFlag = LT; 10472 FalseFlag = GE; 10473 } else { 10474 TrueFlag = GT; 10475 FalseFlag = LE; 10476 } 10477 if (Op == BO_GE || Op == BO_LE) 10478 std::swap(TrueFlag, FalseFlag); 10479 } 10480 if (R & TrueFlag) 10481 return StringRef("true"); 10482 if (R & FalseFlag) 10483 return StringRef("false"); 10484 return llvm::None; 10485 } 10486 }; 10487 } 10488 10489 static bool HasEnumType(Expr *E) { 10490 // Strip off implicit integral promotions. 10491 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10492 if (ICE->getCastKind() != CK_IntegralCast && 10493 ICE->getCastKind() != CK_NoOp) 10494 break; 10495 E = ICE->getSubExpr(); 10496 } 10497 10498 return E->getType()->isEnumeralType(); 10499 } 10500 10501 static int classifyConstantValue(Expr *Constant) { 10502 // The values of this enumeration are used in the diagnostics 10503 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10504 enum ConstantValueKind { 10505 Miscellaneous = 0, 10506 LiteralTrue, 10507 LiteralFalse 10508 }; 10509 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10510 return BL->getValue() ? ConstantValueKind::LiteralTrue 10511 : ConstantValueKind::LiteralFalse; 10512 return ConstantValueKind::Miscellaneous; 10513 } 10514 10515 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10516 Expr *Constant, Expr *Other, 10517 const llvm::APSInt &Value, 10518 bool RhsConstant) { 10519 if (S.inTemplateInstantiation()) 10520 return false; 10521 10522 Expr *OriginalOther = Other; 10523 10524 Constant = Constant->IgnoreParenImpCasts(); 10525 Other = Other->IgnoreParenImpCasts(); 10526 10527 // Suppress warnings on tautological comparisons between values of the same 10528 // enumeration type. There are only two ways we could warn on this: 10529 // - If the constant is outside the range of representable values of 10530 // the enumeration. In such a case, we should warn about the cast 10531 // to enumeration type, not about the comparison. 10532 // - If the constant is the maximum / minimum in-range value. For an 10533 // enumeratin type, such comparisons can be meaningful and useful. 10534 if (Constant->getType()->isEnumeralType() && 10535 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10536 return false; 10537 10538 // TODO: Investigate using GetExprRange() to get tighter bounds 10539 // on the bit ranges. 10540 QualType OtherT = Other->getType(); 10541 if (const auto *AT = OtherT->getAs<AtomicType>()) 10542 OtherT = AT->getValueType(); 10543 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10544 10545 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10546 // (Namely, macOS). 10547 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10548 S.NSAPIObj->isObjCBOOLType(OtherT) && 10549 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10550 10551 // Whether we're treating Other as being a bool because of the form of 10552 // expression despite it having another type (typically 'int' in C). 10553 bool OtherIsBooleanDespiteType = 10554 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10555 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10556 OtherRange = IntRange::forBoolType(); 10557 10558 // Determine the promoted range of the other type and see if a comparison of 10559 // the constant against that range is tautological. 10560 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10561 Value.isUnsigned()); 10562 auto Cmp = OtherPromotedRange.compare(Value); 10563 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10564 if (!Result) 10565 return false; 10566 10567 // Suppress the diagnostic for an in-range comparison if the constant comes 10568 // from a macro or enumerator. We don't want to diagnose 10569 // 10570 // some_long_value <= INT_MAX 10571 // 10572 // when sizeof(int) == sizeof(long). 10573 bool InRange = Cmp & PromotedRange::InRangeFlag; 10574 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10575 return false; 10576 10577 // If this is a comparison to an enum constant, include that 10578 // constant in the diagnostic. 10579 const EnumConstantDecl *ED = nullptr; 10580 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10581 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10582 10583 // Should be enough for uint128 (39 decimal digits) 10584 SmallString<64> PrettySourceValue; 10585 llvm::raw_svector_ostream OS(PrettySourceValue); 10586 if (ED) { 10587 OS << '\'' << *ED << "' (" << Value << ")"; 10588 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10589 Constant->IgnoreParenImpCasts())) { 10590 OS << (BL->getValue() ? "YES" : "NO"); 10591 } else { 10592 OS << Value; 10593 } 10594 10595 if (IsObjCSignedCharBool) { 10596 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10597 S.PDiag(diag::warn_tautological_compare_objc_bool) 10598 << OS.str() << *Result); 10599 return true; 10600 } 10601 10602 // FIXME: We use a somewhat different formatting for the in-range cases and 10603 // cases involving boolean values for historical reasons. We should pick a 10604 // consistent way of presenting these diagnostics. 10605 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10606 10607 S.DiagRuntimeBehavior( 10608 E->getOperatorLoc(), E, 10609 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10610 : diag::warn_tautological_bool_compare) 10611 << OS.str() << classifyConstantValue(Constant) << OtherT 10612 << OtherIsBooleanDespiteType << *Result 10613 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10614 } else { 10615 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10616 ? (HasEnumType(OriginalOther) 10617 ? diag::warn_unsigned_enum_always_true_comparison 10618 : diag::warn_unsigned_always_true_comparison) 10619 : diag::warn_tautological_constant_compare; 10620 10621 S.Diag(E->getOperatorLoc(), Diag) 10622 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10623 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10624 } 10625 10626 return true; 10627 } 10628 10629 /// Analyze the operands of the given comparison. Implements the 10630 /// fallback case from AnalyzeComparison. 10631 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10632 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10633 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10634 } 10635 10636 /// Implements -Wsign-compare. 10637 /// 10638 /// \param E the binary operator to check for warnings 10639 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10640 // The type the comparison is being performed in. 10641 QualType T = E->getLHS()->getType(); 10642 10643 // Only analyze comparison operators where both sides have been converted to 10644 // the same type. 10645 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10646 return AnalyzeImpConvsInComparison(S, E); 10647 10648 // Don't analyze value-dependent comparisons directly. 10649 if (E->isValueDependent()) 10650 return AnalyzeImpConvsInComparison(S, E); 10651 10652 Expr *LHS = E->getLHS(); 10653 Expr *RHS = E->getRHS(); 10654 10655 if (T->isIntegralType(S.Context)) { 10656 llvm::APSInt RHSValue; 10657 llvm::APSInt LHSValue; 10658 10659 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10660 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10661 10662 // We don't care about expressions whose result is a constant. 10663 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10664 return AnalyzeImpConvsInComparison(S, E); 10665 10666 // We only care about expressions where just one side is literal 10667 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10668 // Is the constant on the RHS or LHS? 10669 const bool RhsConstant = IsRHSIntegralLiteral; 10670 Expr *Const = RhsConstant ? RHS : LHS; 10671 Expr *Other = RhsConstant ? LHS : RHS; 10672 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10673 10674 // Check whether an integer constant comparison results in a value 10675 // of 'true' or 'false'. 10676 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10677 return AnalyzeImpConvsInComparison(S, E); 10678 } 10679 } 10680 10681 if (!T->hasUnsignedIntegerRepresentation()) { 10682 // We don't do anything special if this isn't an unsigned integral 10683 // comparison: we're only interested in integral comparisons, and 10684 // signed comparisons only happen in cases we don't care to warn about. 10685 return AnalyzeImpConvsInComparison(S, E); 10686 } 10687 10688 LHS = LHS->IgnoreParenImpCasts(); 10689 RHS = RHS->IgnoreParenImpCasts(); 10690 10691 if (!S.getLangOpts().CPlusPlus) { 10692 // Avoid warning about comparison of integers with different signs when 10693 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10694 // the type of `E`. 10695 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10696 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10697 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10698 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10699 } 10700 10701 // Check to see if one of the (unmodified) operands is of different 10702 // signedness. 10703 Expr *signedOperand, *unsignedOperand; 10704 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10705 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10706 "unsigned comparison between two signed integer expressions?"); 10707 signedOperand = LHS; 10708 unsignedOperand = RHS; 10709 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10710 signedOperand = RHS; 10711 unsignedOperand = LHS; 10712 } else { 10713 return AnalyzeImpConvsInComparison(S, E); 10714 } 10715 10716 // Otherwise, calculate the effective range of the signed operand. 10717 IntRange signedRange = 10718 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10719 10720 // Go ahead and analyze implicit conversions in the operands. Note 10721 // that we skip the implicit conversions on both sides. 10722 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10723 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10724 10725 // If the signed range is non-negative, -Wsign-compare won't fire. 10726 if (signedRange.NonNegative) 10727 return; 10728 10729 // For (in)equality comparisons, if the unsigned operand is a 10730 // constant which cannot collide with a overflowed signed operand, 10731 // then reinterpreting the signed operand as unsigned will not 10732 // change the result of the comparison. 10733 if (E->isEqualityOp()) { 10734 unsigned comparisonWidth = S.Context.getIntWidth(T); 10735 IntRange unsignedRange = 10736 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10737 10738 // We should never be unable to prove that the unsigned operand is 10739 // non-negative. 10740 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10741 10742 if (unsignedRange.Width < comparisonWidth) 10743 return; 10744 } 10745 10746 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10747 S.PDiag(diag::warn_mixed_sign_comparison) 10748 << LHS->getType() << RHS->getType() 10749 << LHS->getSourceRange() << RHS->getSourceRange()); 10750 } 10751 10752 /// Analyzes an attempt to assign the given value to a bitfield. 10753 /// 10754 /// Returns true if there was something fishy about the attempt. 10755 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10756 SourceLocation InitLoc) { 10757 assert(Bitfield->isBitField()); 10758 if (Bitfield->isInvalidDecl()) 10759 return false; 10760 10761 // White-list bool bitfields. 10762 QualType BitfieldType = Bitfield->getType(); 10763 if (BitfieldType->isBooleanType()) 10764 return false; 10765 10766 if (BitfieldType->isEnumeralType()) { 10767 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10768 // If the underlying enum type was not explicitly specified as an unsigned 10769 // type and the enum contain only positive values, MSVC++ will cause an 10770 // inconsistency by storing this as a signed type. 10771 if (S.getLangOpts().CPlusPlus11 && 10772 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10773 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10774 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10775 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10776 << BitfieldEnumDecl->getNameAsString(); 10777 } 10778 } 10779 10780 if (Bitfield->getType()->isBooleanType()) 10781 return false; 10782 10783 // Ignore value- or type-dependent expressions. 10784 if (Bitfield->getBitWidth()->isValueDependent() || 10785 Bitfield->getBitWidth()->isTypeDependent() || 10786 Init->isValueDependent() || 10787 Init->isTypeDependent()) 10788 return false; 10789 10790 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10791 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10792 10793 Expr::EvalResult Result; 10794 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10795 Expr::SE_AllowSideEffects)) { 10796 // The RHS is not constant. If the RHS has an enum type, make sure the 10797 // bitfield is wide enough to hold all the values of the enum without 10798 // truncation. 10799 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10800 EnumDecl *ED = EnumTy->getDecl(); 10801 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10802 10803 // Enum types are implicitly signed on Windows, so check if there are any 10804 // negative enumerators to see if the enum was intended to be signed or 10805 // not. 10806 bool SignedEnum = ED->getNumNegativeBits() > 0; 10807 10808 // Check for surprising sign changes when assigning enum values to a 10809 // bitfield of different signedness. If the bitfield is signed and we 10810 // have exactly the right number of bits to store this unsigned enum, 10811 // suggest changing the enum to an unsigned type. This typically happens 10812 // on Windows where unfixed enums always use an underlying type of 'int'. 10813 unsigned DiagID = 0; 10814 if (SignedEnum && !SignedBitfield) { 10815 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10816 } else if (SignedBitfield && !SignedEnum && 10817 ED->getNumPositiveBits() == FieldWidth) { 10818 DiagID = diag::warn_signed_bitfield_enum_conversion; 10819 } 10820 10821 if (DiagID) { 10822 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10823 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10824 SourceRange TypeRange = 10825 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10826 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10827 << SignedEnum << TypeRange; 10828 } 10829 10830 // Compute the required bitwidth. If the enum has negative values, we need 10831 // one more bit than the normal number of positive bits to represent the 10832 // sign bit. 10833 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10834 ED->getNumNegativeBits()) 10835 : ED->getNumPositiveBits(); 10836 10837 // Check the bitwidth. 10838 if (BitsNeeded > FieldWidth) { 10839 Expr *WidthExpr = Bitfield->getBitWidth(); 10840 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10841 << Bitfield << ED; 10842 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10843 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10844 } 10845 } 10846 10847 return false; 10848 } 10849 10850 llvm::APSInt Value = Result.Val.getInt(); 10851 10852 unsigned OriginalWidth = Value.getBitWidth(); 10853 10854 if (!Value.isSigned() || Value.isNegative()) 10855 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10856 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10857 OriginalWidth = Value.getMinSignedBits(); 10858 10859 if (OriginalWidth <= FieldWidth) 10860 return false; 10861 10862 // Compute the value which the bitfield will contain. 10863 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10864 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10865 10866 // Check whether the stored value is equal to the original value. 10867 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10868 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10869 return false; 10870 10871 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10872 // therefore don't strictly fit into a signed bitfield of width 1. 10873 if (FieldWidth == 1 && Value == 1) 10874 return false; 10875 10876 std::string PrettyValue = Value.toString(10); 10877 std::string PrettyTrunc = TruncatedValue.toString(10); 10878 10879 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10880 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10881 << Init->getSourceRange(); 10882 10883 return true; 10884 } 10885 10886 /// Analyze the given simple or compound assignment for warning-worthy 10887 /// operations. 10888 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10889 // Just recurse on the LHS. 10890 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10891 10892 // We want to recurse on the RHS as normal unless we're assigning to 10893 // a bitfield. 10894 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10895 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10896 E->getOperatorLoc())) { 10897 // Recurse, ignoring any implicit conversions on the RHS. 10898 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10899 E->getOperatorLoc()); 10900 } 10901 } 10902 10903 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10904 10905 // Diagnose implicitly sequentially-consistent atomic assignment. 10906 if (E->getLHS()->getType()->isAtomicType()) 10907 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10908 } 10909 10910 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10911 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10912 SourceLocation CContext, unsigned diag, 10913 bool pruneControlFlow = false) { 10914 if (pruneControlFlow) { 10915 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10916 S.PDiag(diag) 10917 << SourceType << T << E->getSourceRange() 10918 << SourceRange(CContext)); 10919 return; 10920 } 10921 S.Diag(E->getExprLoc(), diag) 10922 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10923 } 10924 10925 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10926 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10927 SourceLocation CContext, 10928 unsigned diag, bool pruneControlFlow = false) { 10929 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10930 } 10931 10932 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 10933 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 10934 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 10935 } 10936 10937 static void adornObjCBoolConversionDiagWithTernaryFixit( 10938 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 10939 Expr *Ignored = SourceExpr->IgnoreImplicit(); 10940 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 10941 Ignored = OVE->getSourceExpr(); 10942 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 10943 isa<BinaryOperator>(Ignored) || 10944 isa<CXXOperatorCallExpr>(Ignored); 10945 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 10946 if (NeedsParens) 10947 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 10948 << FixItHint::CreateInsertion(EndLoc, ")"); 10949 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 10950 } 10951 10952 /// Diagnose an implicit cast from a floating point value to an integer value. 10953 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10954 SourceLocation CContext) { 10955 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10956 const bool PruneWarnings = S.inTemplateInstantiation(); 10957 10958 Expr *InnerE = E->IgnoreParenImpCasts(); 10959 // We also want to warn on, e.g., "int i = -1.234" 10960 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10961 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10962 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10963 10964 const bool IsLiteral = 10965 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10966 10967 llvm::APFloat Value(0.0); 10968 bool IsConstant = 10969 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10970 if (!IsConstant) { 10971 if (isObjCSignedCharBool(S, T)) { 10972 return adornObjCBoolConversionDiagWithTernaryFixit( 10973 S, E, 10974 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 10975 << E->getType()); 10976 } 10977 10978 return DiagnoseImpCast(S, E, T, CContext, 10979 diag::warn_impcast_float_integer, PruneWarnings); 10980 } 10981 10982 bool isExact = false; 10983 10984 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10985 T->hasUnsignedIntegerRepresentation()); 10986 llvm::APFloat::opStatus Result = Value.convertToInteger( 10987 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10988 10989 // FIXME: Force the precision of the source value down so we don't print 10990 // digits which are usually useless (we don't really care here if we 10991 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10992 // would automatically print the shortest representation, but it's a bit 10993 // tricky to implement. 10994 SmallString<16> PrettySourceValue; 10995 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10996 precision = (precision * 59 + 195) / 196; 10997 Value.toString(PrettySourceValue, precision); 10998 10999 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11000 return adornObjCBoolConversionDiagWithTernaryFixit( 11001 S, E, 11002 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11003 << PrettySourceValue); 11004 } 11005 11006 if (Result == llvm::APFloat::opOK && isExact) { 11007 if (IsLiteral) return; 11008 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11009 PruneWarnings); 11010 } 11011 11012 // Conversion of a floating-point value to a non-bool integer where the 11013 // integral part cannot be represented by the integer type is undefined. 11014 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11015 return DiagnoseImpCast( 11016 S, E, T, CContext, 11017 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11018 : diag::warn_impcast_float_to_integer_out_of_range, 11019 PruneWarnings); 11020 11021 unsigned DiagID = 0; 11022 if (IsLiteral) { 11023 // Warn on floating point literal to integer. 11024 DiagID = diag::warn_impcast_literal_float_to_integer; 11025 } else if (IntegerValue == 0) { 11026 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11027 return DiagnoseImpCast(S, E, T, CContext, 11028 diag::warn_impcast_float_integer, PruneWarnings); 11029 } 11030 // Warn on non-zero to zero conversion. 11031 DiagID = diag::warn_impcast_float_to_integer_zero; 11032 } else { 11033 if (IntegerValue.isUnsigned()) { 11034 if (!IntegerValue.isMaxValue()) { 11035 return DiagnoseImpCast(S, E, T, CContext, 11036 diag::warn_impcast_float_integer, PruneWarnings); 11037 } 11038 } else { // IntegerValue.isSigned() 11039 if (!IntegerValue.isMaxSignedValue() && 11040 !IntegerValue.isMinSignedValue()) { 11041 return DiagnoseImpCast(S, E, T, CContext, 11042 diag::warn_impcast_float_integer, PruneWarnings); 11043 } 11044 } 11045 // Warn on evaluatable floating point expression to integer conversion. 11046 DiagID = diag::warn_impcast_float_to_integer; 11047 } 11048 11049 SmallString<16> PrettyTargetValue; 11050 if (IsBool) 11051 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11052 else 11053 IntegerValue.toString(PrettyTargetValue); 11054 11055 if (PruneWarnings) { 11056 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11057 S.PDiag(DiagID) 11058 << E->getType() << T.getUnqualifiedType() 11059 << PrettySourceValue << PrettyTargetValue 11060 << E->getSourceRange() << SourceRange(CContext)); 11061 } else { 11062 S.Diag(E->getExprLoc(), DiagID) 11063 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11064 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11065 } 11066 } 11067 11068 /// Analyze the given compound assignment for the possible losing of 11069 /// floating-point precision. 11070 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11071 assert(isa<CompoundAssignOperator>(E) && 11072 "Must be compound assignment operation"); 11073 // Recurse on the LHS and RHS in here 11074 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11075 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11076 11077 if (E->getLHS()->getType()->isAtomicType()) 11078 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11079 11080 // Now check the outermost expression 11081 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11082 const auto *RBT = cast<CompoundAssignOperator>(E) 11083 ->getComputationResultType() 11084 ->getAs<BuiltinType>(); 11085 11086 // The below checks assume source is floating point. 11087 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11088 11089 // If source is floating point but target is an integer. 11090 if (ResultBT->isInteger()) 11091 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11092 E->getExprLoc(), diag::warn_impcast_float_integer); 11093 11094 if (!ResultBT->isFloatingPoint()) 11095 return; 11096 11097 // If both source and target are floating points, warn about losing precision. 11098 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11099 QualType(ResultBT, 0), QualType(RBT, 0)); 11100 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11101 // warn about dropping FP rank. 11102 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11103 diag::warn_impcast_float_result_precision); 11104 } 11105 11106 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11107 IntRange Range) { 11108 if (!Range.Width) return "0"; 11109 11110 llvm::APSInt ValueInRange = Value; 11111 ValueInRange.setIsSigned(!Range.NonNegative); 11112 ValueInRange = ValueInRange.trunc(Range.Width); 11113 return ValueInRange.toString(10); 11114 } 11115 11116 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11117 if (!isa<ImplicitCastExpr>(Ex)) 11118 return false; 11119 11120 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11121 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11122 const Type *Source = 11123 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11124 if (Target->isDependentType()) 11125 return false; 11126 11127 const BuiltinType *FloatCandidateBT = 11128 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11129 const Type *BoolCandidateType = ToBool ? Target : Source; 11130 11131 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11132 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11133 } 11134 11135 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11136 SourceLocation CC) { 11137 unsigned NumArgs = TheCall->getNumArgs(); 11138 for (unsigned i = 0; i < NumArgs; ++i) { 11139 Expr *CurrA = TheCall->getArg(i); 11140 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11141 continue; 11142 11143 bool IsSwapped = ((i > 0) && 11144 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11145 IsSwapped |= ((i < (NumArgs - 1)) && 11146 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11147 if (IsSwapped) { 11148 // Warn on this floating-point to bool conversion. 11149 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11150 CurrA->getType(), CC, 11151 diag::warn_impcast_floating_point_to_bool); 11152 } 11153 } 11154 } 11155 11156 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11157 SourceLocation CC) { 11158 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11159 E->getExprLoc())) 11160 return; 11161 11162 // Don't warn on functions which have return type nullptr_t. 11163 if (isa<CallExpr>(E)) 11164 return; 11165 11166 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11167 const Expr::NullPointerConstantKind NullKind = 11168 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11169 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11170 return; 11171 11172 // Return if target type is a safe conversion. 11173 if (T->isAnyPointerType() || T->isBlockPointerType() || 11174 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11175 return; 11176 11177 SourceLocation Loc = E->getSourceRange().getBegin(); 11178 11179 // Venture through the macro stacks to get to the source of macro arguments. 11180 // The new location is a better location than the complete location that was 11181 // passed in. 11182 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11183 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11184 11185 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11186 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11187 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11188 Loc, S.SourceMgr, S.getLangOpts()); 11189 if (MacroName == "NULL") 11190 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11191 } 11192 11193 // Only warn if the null and context location are in the same macro expansion. 11194 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11195 return; 11196 11197 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11198 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11199 << FixItHint::CreateReplacement(Loc, 11200 S.getFixItZeroLiteralForType(T, Loc)); 11201 } 11202 11203 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11204 ObjCArrayLiteral *ArrayLiteral); 11205 11206 static void 11207 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11208 ObjCDictionaryLiteral *DictionaryLiteral); 11209 11210 /// Check a single element within a collection literal against the 11211 /// target element type. 11212 static void checkObjCCollectionLiteralElement(Sema &S, 11213 QualType TargetElementType, 11214 Expr *Element, 11215 unsigned ElementKind) { 11216 // Skip a bitcast to 'id' or qualified 'id'. 11217 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11218 if (ICE->getCastKind() == CK_BitCast && 11219 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11220 Element = ICE->getSubExpr(); 11221 } 11222 11223 QualType ElementType = Element->getType(); 11224 ExprResult ElementResult(Element); 11225 if (ElementType->getAs<ObjCObjectPointerType>() && 11226 S.CheckSingleAssignmentConstraints(TargetElementType, 11227 ElementResult, 11228 false, false) 11229 != Sema::Compatible) { 11230 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11231 << ElementType << ElementKind << TargetElementType 11232 << Element->getSourceRange(); 11233 } 11234 11235 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11236 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11237 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11238 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11239 } 11240 11241 /// Check an Objective-C array literal being converted to the given 11242 /// target type. 11243 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11244 ObjCArrayLiteral *ArrayLiteral) { 11245 if (!S.NSArrayDecl) 11246 return; 11247 11248 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11249 if (!TargetObjCPtr) 11250 return; 11251 11252 if (TargetObjCPtr->isUnspecialized() || 11253 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11254 != S.NSArrayDecl->getCanonicalDecl()) 11255 return; 11256 11257 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11258 if (TypeArgs.size() != 1) 11259 return; 11260 11261 QualType TargetElementType = TypeArgs[0]; 11262 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11263 checkObjCCollectionLiteralElement(S, TargetElementType, 11264 ArrayLiteral->getElement(I), 11265 0); 11266 } 11267 } 11268 11269 /// Check an Objective-C dictionary literal being converted to the given 11270 /// target type. 11271 static void 11272 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11273 ObjCDictionaryLiteral *DictionaryLiteral) { 11274 if (!S.NSDictionaryDecl) 11275 return; 11276 11277 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11278 if (!TargetObjCPtr) 11279 return; 11280 11281 if (TargetObjCPtr->isUnspecialized() || 11282 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11283 != S.NSDictionaryDecl->getCanonicalDecl()) 11284 return; 11285 11286 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11287 if (TypeArgs.size() != 2) 11288 return; 11289 11290 QualType TargetKeyType = TypeArgs[0]; 11291 QualType TargetObjectType = TypeArgs[1]; 11292 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11293 auto Element = DictionaryLiteral->getKeyValueElement(I); 11294 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11295 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11296 } 11297 } 11298 11299 // Helper function to filter out cases for constant width constant conversion. 11300 // Don't warn on char array initialization or for non-decimal values. 11301 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11302 SourceLocation CC) { 11303 // If initializing from a constant, and the constant starts with '0', 11304 // then it is a binary, octal, or hexadecimal. Allow these constants 11305 // to fill all the bits, even if there is a sign change. 11306 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11307 const char FirstLiteralCharacter = 11308 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11309 if (FirstLiteralCharacter == '0') 11310 return false; 11311 } 11312 11313 // If the CC location points to a '{', and the type is char, then assume 11314 // assume it is an array initialization. 11315 if (CC.isValid() && T->isCharType()) { 11316 const char FirstContextCharacter = 11317 S.getSourceManager().getCharacterData(CC)[0]; 11318 if (FirstContextCharacter == '{') 11319 return false; 11320 } 11321 11322 return true; 11323 } 11324 11325 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11326 const auto *IL = dyn_cast<IntegerLiteral>(E); 11327 if (!IL) { 11328 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11329 if (UO->getOpcode() == UO_Minus) 11330 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11331 } 11332 } 11333 11334 return IL; 11335 } 11336 11337 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11338 E = E->IgnoreParenImpCasts(); 11339 SourceLocation ExprLoc = E->getExprLoc(); 11340 11341 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11342 BinaryOperator::Opcode Opc = BO->getOpcode(); 11343 Expr::EvalResult Result; 11344 // Do not diagnose unsigned shifts. 11345 if (Opc == BO_Shl) { 11346 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11347 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11348 if (LHS && LHS->getValue() == 0) 11349 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11350 else if (!E->isValueDependent() && LHS && RHS && 11351 RHS->getValue().isNonNegative() && 11352 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11353 S.Diag(ExprLoc, diag::warn_left_shift_always) 11354 << (Result.Val.getInt() != 0); 11355 else if (E->getType()->isSignedIntegerType()) 11356 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11357 } 11358 } 11359 11360 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11361 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11362 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11363 if (!LHS || !RHS) 11364 return; 11365 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11366 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11367 // Do not diagnose common idioms. 11368 return; 11369 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11370 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11371 } 11372 } 11373 11374 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11375 SourceLocation CC, 11376 bool *ICContext = nullptr, 11377 bool IsListInit = false) { 11378 if (E->isTypeDependent() || E->isValueDependent()) return; 11379 11380 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11381 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11382 if (Source == Target) return; 11383 if (Target->isDependentType()) return; 11384 11385 // If the conversion context location is invalid don't complain. We also 11386 // don't want to emit a warning if the issue occurs from the expansion of 11387 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11388 // delay this check as long as possible. Once we detect we are in that 11389 // scenario, we just return. 11390 if (CC.isInvalid()) 11391 return; 11392 11393 if (Source->isAtomicType()) 11394 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11395 11396 // Diagnose implicit casts to bool. 11397 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11398 if (isa<StringLiteral>(E)) 11399 // Warn on string literal to bool. Checks for string literals in logical 11400 // and expressions, for instance, assert(0 && "error here"), are 11401 // prevented by a check in AnalyzeImplicitConversions(). 11402 return DiagnoseImpCast(S, E, T, CC, 11403 diag::warn_impcast_string_literal_to_bool); 11404 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11405 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11406 // This covers the literal expressions that evaluate to Objective-C 11407 // objects. 11408 return DiagnoseImpCast(S, E, T, CC, 11409 diag::warn_impcast_objective_c_literal_to_bool); 11410 } 11411 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11412 // Warn on pointer to bool conversion that is always true. 11413 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11414 SourceRange(CC)); 11415 } 11416 } 11417 11418 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11419 // is a typedef for signed char (macOS), then that constant value has to be 1 11420 // or 0. 11421 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11422 Expr::EvalResult Result; 11423 if (E->EvaluateAsInt(Result, S.getASTContext(), 11424 Expr::SE_AllowSideEffects)) { 11425 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11426 adornObjCBoolConversionDiagWithTernaryFixit( 11427 S, E, 11428 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11429 << Result.Val.getInt().toString(10)); 11430 } 11431 return; 11432 } 11433 } 11434 11435 // Check implicit casts from Objective-C collection literals to specialized 11436 // collection types, e.g., NSArray<NSString *> *. 11437 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11438 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11439 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11440 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11441 11442 // Strip vector types. 11443 if (isa<VectorType>(Source)) { 11444 if (!isa<VectorType>(Target)) { 11445 if (S.SourceMgr.isInSystemMacro(CC)) 11446 return; 11447 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11448 } 11449 11450 // If the vector cast is cast between two vectors of the same size, it is 11451 // a bitcast, not a conversion. 11452 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11453 return; 11454 11455 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11456 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11457 } 11458 if (auto VecTy = dyn_cast<VectorType>(Target)) 11459 Target = VecTy->getElementType().getTypePtr(); 11460 11461 // Strip complex types. 11462 if (isa<ComplexType>(Source)) { 11463 if (!isa<ComplexType>(Target)) { 11464 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11465 return; 11466 11467 return DiagnoseImpCast(S, E, T, CC, 11468 S.getLangOpts().CPlusPlus 11469 ? diag::err_impcast_complex_scalar 11470 : diag::warn_impcast_complex_scalar); 11471 } 11472 11473 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11474 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11475 } 11476 11477 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11478 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11479 11480 // If the source is floating point... 11481 if (SourceBT && SourceBT->isFloatingPoint()) { 11482 // ...and the target is floating point... 11483 if (TargetBT && TargetBT->isFloatingPoint()) { 11484 // ...then warn if we're dropping FP rank. 11485 11486 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11487 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11488 if (Order > 0) { 11489 // Don't warn about float constants that are precisely 11490 // representable in the target type. 11491 Expr::EvalResult result; 11492 if (E->EvaluateAsRValue(result, S.Context)) { 11493 // Value might be a float, a float vector, or a float complex. 11494 if (IsSameFloatAfterCast(result.Val, 11495 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11496 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11497 return; 11498 } 11499 11500 if (S.SourceMgr.isInSystemMacro(CC)) 11501 return; 11502 11503 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11504 } 11505 // ... or possibly if we're increasing rank, too 11506 else if (Order < 0) { 11507 if (S.SourceMgr.isInSystemMacro(CC)) 11508 return; 11509 11510 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11511 } 11512 return; 11513 } 11514 11515 // If the target is integral, always warn. 11516 if (TargetBT && TargetBT->isInteger()) { 11517 if (S.SourceMgr.isInSystemMacro(CC)) 11518 return; 11519 11520 DiagnoseFloatingImpCast(S, E, T, CC); 11521 } 11522 11523 // Detect the case where a call result is converted from floating-point to 11524 // to bool, and the final argument to the call is converted from bool, to 11525 // discover this typo: 11526 // 11527 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11528 // 11529 // FIXME: This is an incredibly special case; is there some more general 11530 // way to detect this class of misplaced-parentheses bug? 11531 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11532 // Check last argument of function call to see if it is an 11533 // implicit cast from a type matching the type the result 11534 // is being cast to. 11535 CallExpr *CEx = cast<CallExpr>(E); 11536 if (unsigned NumArgs = CEx->getNumArgs()) { 11537 Expr *LastA = CEx->getArg(NumArgs - 1); 11538 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11539 if (isa<ImplicitCastExpr>(LastA) && 11540 InnerE->getType()->isBooleanType()) { 11541 // Warn on this floating-point to bool conversion 11542 DiagnoseImpCast(S, E, T, CC, 11543 diag::warn_impcast_floating_point_to_bool); 11544 } 11545 } 11546 } 11547 return; 11548 } 11549 11550 // Valid casts involving fixed point types should be accounted for here. 11551 if (Source->isFixedPointType()) { 11552 if (Target->isUnsaturatedFixedPointType()) { 11553 Expr::EvalResult Result; 11554 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11555 S.isConstantEvaluated())) { 11556 APFixedPoint Value = Result.Val.getFixedPoint(); 11557 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11558 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11559 if (Value > MaxVal || Value < MinVal) { 11560 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11561 S.PDiag(diag::warn_impcast_fixed_point_range) 11562 << Value.toString() << T 11563 << E->getSourceRange() 11564 << clang::SourceRange(CC)); 11565 return; 11566 } 11567 } 11568 } else if (Target->isIntegerType()) { 11569 Expr::EvalResult Result; 11570 if (!S.isConstantEvaluated() && 11571 E->EvaluateAsFixedPoint(Result, S.Context, 11572 Expr::SE_AllowSideEffects)) { 11573 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11574 11575 bool Overflowed; 11576 llvm::APSInt IntResult = FXResult.convertToInt( 11577 S.Context.getIntWidth(T), 11578 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11579 11580 if (Overflowed) { 11581 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11582 S.PDiag(diag::warn_impcast_fixed_point_range) 11583 << FXResult.toString() << T 11584 << E->getSourceRange() 11585 << clang::SourceRange(CC)); 11586 return; 11587 } 11588 } 11589 } 11590 } else if (Target->isUnsaturatedFixedPointType()) { 11591 if (Source->isIntegerType()) { 11592 Expr::EvalResult Result; 11593 if (!S.isConstantEvaluated() && 11594 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11595 llvm::APSInt Value = Result.Val.getInt(); 11596 11597 bool Overflowed; 11598 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11599 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11600 11601 if (Overflowed) { 11602 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11603 S.PDiag(diag::warn_impcast_fixed_point_range) 11604 << Value.toString(/*Radix=*/10) << T 11605 << E->getSourceRange() 11606 << clang::SourceRange(CC)); 11607 return; 11608 } 11609 } 11610 } 11611 } 11612 11613 // If we are casting an integer type to a floating point type without 11614 // initialization-list syntax, we might lose accuracy if the floating 11615 // point type has a narrower significand than the integer type. 11616 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11617 TargetBT->isFloatingType() && !IsListInit) { 11618 // Determine the number of precision bits in the source integer type. 11619 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11620 unsigned int SourcePrecision = SourceRange.Width; 11621 11622 // Determine the number of precision bits in the 11623 // target floating point type. 11624 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11625 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11626 11627 if (SourcePrecision > 0 && TargetPrecision > 0 && 11628 SourcePrecision > TargetPrecision) { 11629 11630 llvm::APSInt SourceInt; 11631 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11632 // If the source integer is a constant, convert it to the target 11633 // floating point type. Issue a warning if the value changes 11634 // during the whole conversion. 11635 llvm::APFloat TargetFloatValue( 11636 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11637 llvm::APFloat::opStatus ConversionStatus = 11638 TargetFloatValue.convertFromAPInt( 11639 SourceInt, SourceBT->isSignedInteger(), 11640 llvm::APFloat::rmNearestTiesToEven); 11641 11642 if (ConversionStatus != llvm::APFloat::opOK) { 11643 std::string PrettySourceValue = SourceInt.toString(10); 11644 SmallString<32> PrettyTargetValue; 11645 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11646 11647 S.DiagRuntimeBehavior( 11648 E->getExprLoc(), E, 11649 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11650 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11651 << E->getSourceRange() << clang::SourceRange(CC)); 11652 } 11653 } else { 11654 // Otherwise, the implicit conversion may lose precision. 11655 DiagnoseImpCast(S, E, T, CC, 11656 diag::warn_impcast_integer_float_precision); 11657 } 11658 } 11659 } 11660 11661 DiagnoseNullConversion(S, E, T, CC); 11662 11663 S.DiscardMisalignedMemberAddress(Target, E); 11664 11665 if (Target->isBooleanType()) 11666 DiagnoseIntInBoolContext(S, E); 11667 11668 if (!Source->isIntegerType() || !Target->isIntegerType()) 11669 return; 11670 11671 // TODO: remove this early return once the false positives for constant->bool 11672 // in templates, macros, etc, are reduced or removed. 11673 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11674 return; 11675 11676 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11677 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11678 return adornObjCBoolConversionDiagWithTernaryFixit( 11679 S, E, 11680 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11681 << E->getType()); 11682 } 11683 11684 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11685 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11686 11687 if (SourceRange.Width > TargetRange.Width) { 11688 // If the source is a constant, use a default-on diagnostic. 11689 // TODO: this should happen for bitfield stores, too. 11690 Expr::EvalResult Result; 11691 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11692 S.isConstantEvaluated())) { 11693 llvm::APSInt Value(32); 11694 Value = Result.Val.getInt(); 11695 11696 if (S.SourceMgr.isInSystemMacro(CC)) 11697 return; 11698 11699 std::string PrettySourceValue = Value.toString(10); 11700 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11701 11702 S.DiagRuntimeBehavior( 11703 E->getExprLoc(), E, 11704 S.PDiag(diag::warn_impcast_integer_precision_constant) 11705 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11706 << E->getSourceRange() << clang::SourceRange(CC)); 11707 return; 11708 } 11709 11710 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11711 if (S.SourceMgr.isInSystemMacro(CC)) 11712 return; 11713 11714 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11715 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11716 /* pruneControlFlow */ true); 11717 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11718 } 11719 11720 if (TargetRange.Width > SourceRange.Width) { 11721 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11722 if (UO->getOpcode() == UO_Minus) 11723 if (Source->isUnsignedIntegerType()) { 11724 if (Target->isUnsignedIntegerType()) 11725 return DiagnoseImpCast(S, E, T, CC, 11726 diag::warn_impcast_high_order_zero_bits); 11727 if (Target->isSignedIntegerType()) 11728 return DiagnoseImpCast(S, E, T, CC, 11729 diag::warn_impcast_nonnegative_result); 11730 } 11731 } 11732 11733 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11734 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11735 // Warn when doing a signed to signed conversion, warn if the positive 11736 // source value is exactly the width of the target type, which will 11737 // cause a negative value to be stored. 11738 11739 Expr::EvalResult Result; 11740 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11741 !S.SourceMgr.isInSystemMacro(CC)) { 11742 llvm::APSInt Value = Result.Val.getInt(); 11743 if (isSameWidthConstantConversion(S, E, T, CC)) { 11744 std::string PrettySourceValue = Value.toString(10); 11745 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11746 11747 S.DiagRuntimeBehavior( 11748 E->getExprLoc(), E, 11749 S.PDiag(diag::warn_impcast_integer_precision_constant) 11750 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11751 << E->getSourceRange() << clang::SourceRange(CC)); 11752 return; 11753 } 11754 } 11755 11756 // Fall through for non-constants to give a sign conversion warning. 11757 } 11758 11759 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11760 (!TargetRange.NonNegative && SourceRange.NonNegative && 11761 SourceRange.Width == TargetRange.Width)) { 11762 if (S.SourceMgr.isInSystemMacro(CC)) 11763 return; 11764 11765 unsigned DiagID = diag::warn_impcast_integer_sign; 11766 11767 // Traditionally, gcc has warned about this under -Wsign-compare. 11768 // We also want to warn about it in -Wconversion. 11769 // So if -Wconversion is off, use a completely identical diagnostic 11770 // in the sign-compare group. 11771 // The conditional-checking code will 11772 if (ICContext) { 11773 DiagID = diag::warn_impcast_integer_sign_conditional; 11774 *ICContext = true; 11775 } 11776 11777 return DiagnoseImpCast(S, E, T, CC, DiagID); 11778 } 11779 11780 // Diagnose conversions between different enumeration types. 11781 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11782 // type, to give us better diagnostics. 11783 QualType SourceType = E->getType(); 11784 if (!S.getLangOpts().CPlusPlus) { 11785 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11786 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11787 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11788 SourceType = S.Context.getTypeDeclType(Enum); 11789 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11790 } 11791 } 11792 11793 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11794 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11795 if (SourceEnum->getDecl()->hasNameForLinkage() && 11796 TargetEnum->getDecl()->hasNameForLinkage() && 11797 SourceEnum != TargetEnum) { 11798 if (S.SourceMgr.isInSystemMacro(CC)) 11799 return; 11800 11801 return DiagnoseImpCast(S, E, SourceType, T, CC, 11802 diag::warn_impcast_different_enum_types); 11803 } 11804 } 11805 11806 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11807 SourceLocation CC, QualType T); 11808 11809 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11810 SourceLocation CC, bool &ICContext) { 11811 E = E->IgnoreParenImpCasts(); 11812 11813 if (isa<ConditionalOperator>(E)) 11814 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11815 11816 AnalyzeImplicitConversions(S, E, CC); 11817 if (E->getType() != T) 11818 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11819 } 11820 11821 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11822 SourceLocation CC, QualType T) { 11823 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11824 11825 bool Suspicious = false; 11826 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11827 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11828 11829 if (T->isBooleanType()) 11830 DiagnoseIntInBoolContext(S, E); 11831 11832 // If -Wconversion would have warned about either of the candidates 11833 // for a signedness conversion to the context type... 11834 if (!Suspicious) return; 11835 11836 // ...but it's currently ignored... 11837 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11838 return; 11839 11840 // ...then check whether it would have warned about either of the 11841 // candidates for a signedness conversion to the condition type. 11842 if (E->getType() == T) return; 11843 11844 Suspicious = false; 11845 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11846 E->getType(), CC, &Suspicious); 11847 if (!Suspicious) 11848 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11849 E->getType(), CC, &Suspicious); 11850 } 11851 11852 /// Check conversion of given expression to boolean. 11853 /// Input argument E is a logical expression. 11854 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11855 if (S.getLangOpts().Bool) 11856 return; 11857 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11858 return; 11859 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11860 } 11861 11862 namespace { 11863 struct AnalyzeImplicitConversionsWorkItem { 11864 Expr *E; 11865 SourceLocation CC; 11866 bool IsListInit; 11867 }; 11868 } 11869 11870 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 11871 /// that should be visited are added to WorkList. 11872 static void AnalyzeImplicitConversions( 11873 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 11874 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 11875 Expr *OrigE = Item.E; 11876 SourceLocation CC = Item.CC; 11877 11878 QualType T = OrigE->getType(); 11879 Expr *E = OrigE->IgnoreParenImpCasts(); 11880 11881 // Propagate whether we are in a C++ list initialization expression. 11882 // If so, we do not issue warnings for implicit int-float conversion 11883 // precision loss, because C++11 narrowing already handles it. 11884 bool IsListInit = Item.IsListInit || 11885 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11886 11887 if (E->isTypeDependent() || E->isValueDependent()) 11888 return; 11889 11890 Expr *SourceExpr = E; 11891 // Examine, but don't traverse into the source expression of an 11892 // OpaqueValueExpr, since it may have multiple parents and we don't want to 11893 // emit duplicate diagnostics. Its fine to examine the form or attempt to 11894 // evaluate it in the context of checking the specific conversion to T though. 11895 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11896 if (auto *Src = OVE->getSourceExpr()) 11897 SourceExpr = Src; 11898 11899 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 11900 if (UO->getOpcode() == UO_Not && 11901 UO->getSubExpr()->isKnownToHaveBooleanValue()) 11902 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 11903 << OrigE->getSourceRange() << T->isBooleanType() 11904 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 11905 11906 // For conditional operators, we analyze the arguments as if they 11907 // were being fed directly into the output. 11908 if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) { 11909 CheckConditionalOperator(S, CO, CC, T); 11910 return; 11911 } 11912 11913 // Check implicit argument conversions for function calls. 11914 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 11915 CheckImplicitArgumentConversions(S, Call, CC); 11916 11917 // Go ahead and check any implicit conversions we might have skipped. 11918 // The non-canonical typecheck is just an optimization; 11919 // CheckImplicitConversion will filter out dead implicit conversions. 11920 if (SourceExpr->getType() != T) 11921 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 11922 11923 // Now continue drilling into this expression. 11924 11925 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11926 // The bound subexpressions in a PseudoObjectExpr are not reachable 11927 // as transitive children. 11928 // FIXME: Use a more uniform representation for this. 11929 for (auto *SE : POE->semantics()) 11930 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11931 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 11932 } 11933 11934 // Skip past explicit casts. 11935 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11936 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11937 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11938 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11939 WorkList.push_back({E, CC, IsListInit}); 11940 return; 11941 } 11942 11943 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11944 // Do a somewhat different check with comparison operators. 11945 if (BO->isComparisonOp()) 11946 return AnalyzeComparison(S, BO); 11947 11948 // And with simple assignments. 11949 if (BO->getOpcode() == BO_Assign) 11950 return AnalyzeAssignment(S, BO); 11951 // And with compound assignments. 11952 if (BO->isAssignmentOp()) 11953 return AnalyzeCompoundAssignment(S, BO); 11954 } 11955 11956 // These break the otherwise-useful invariant below. Fortunately, 11957 // we don't really need to recurse into them, because any internal 11958 // expressions should have been analyzed already when they were 11959 // built into statements. 11960 if (isa<StmtExpr>(E)) return; 11961 11962 // Don't descend into unevaluated contexts. 11963 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11964 11965 // Now just recurse over the expression's children. 11966 CC = E->getExprLoc(); 11967 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11968 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11969 for (Stmt *SubStmt : E->children()) { 11970 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11971 if (!ChildExpr) 11972 continue; 11973 11974 if (IsLogicalAndOperator && 11975 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11976 // Ignore checking string literals that are in logical and operators. 11977 // This is a common pattern for asserts. 11978 continue; 11979 WorkList.push_back({ChildExpr, CC, IsListInit}); 11980 } 11981 11982 if (BO && BO->isLogicalOp()) { 11983 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11984 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11985 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11986 11987 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11988 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11989 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11990 } 11991 11992 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11993 if (U->getOpcode() == UO_LNot) { 11994 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11995 } else if (U->getOpcode() != UO_AddrOf) { 11996 if (U->getSubExpr()->getType()->isAtomicType()) 11997 S.Diag(U->getSubExpr()->getBeginLoc(), 11998 diag::warn_atomic_implicit_seq_cst); 11999 } 12000 } 12001 } 12002 12003 /// AnalyzeImplicitConversions - Find and report any interesting 12004 /// implicit conversions in the given expression. There are a couple 12005 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12006 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12007 bool IsListInit/*= false*/) { 12008 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12009 WorkList.push_back({OrigE, CC, IsListInit}); 12010 while (!WorkList.empty()) 12011 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12012 } 12013 12014 /// Diagnose integer type and any valid implicit conversion to it. 12015 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12016 // Taking into account implicit conversions, 12017 // allow any integer. 12018 if (!E->getType()->isIntegerType()) { 12019 S.Diag(E->getBeginLoc(), 12020 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12021 return true; 12022 } 12023 // Potentially emit standard warnings for implicit conversions if enabled 12024 // using -Wconversion. 12025 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12026 return false; 12027 } 12028 12029 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12030 // Returns true when emitting a warning about taking the address of a reference. 12031 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12032 const PartialDiagnostic &PD) { 12033 E = E->IgnoreParenImpCasts(); 12034 12035 const FunctionDecl *FD = nullptr; 12036 12037 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12038 if (!DRE->getDecl()->getType()->isReferenceType()) 12039 return false; 12040 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12041 if (!M->getMemberDecl()->getType()->isReferenceType()) 12042 return false; 12043 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12044 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12045 return false; 12046 FD = Call->getDirectCallee(); 12047 } else { 12048 return false; 12049 } 12050 12051 SemaRef.Diag(E->getExprLoc(), PD); 12052 12053 // If possible, point to location of function. 12054 if (FD) { 12055 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12056 } 12057 12058 return true; 12059 } 12060 12061 // Returns true if the SourceLocation is expanded from any macro body. 12062 // Returns false if the SourceLocation is invalid, is from not in a macro 12063 // expansion, or is from expanded from a top-level macro argument. 12064 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12065 if (Loc.isInvalid()) 12066 return false; 12067 12068 while (Loc.isMacroID()) { 12069 if (SM.isMacroBodyExpansion(Loc)) 12070 return true; 12071 Loc = SM.getImmediateMacroCallerLoc(Loc); 12072 } 12073 12074 return false; 12075 } 12076 12077 /// Diagnose pointers that are always non-null. 12078 /// \param E the expression containing the pointer 12079 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12080 /// compared to a null pointer 12081 /// \param IsEqual True when the comparison is equal to a null pointer 12082 /// \param Range Extra SourceRange to highlight in the diagnostic 12083 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12084 Expr::NullPointerConstantKind NullKind, 12085 bool IsEqual, SourceRange Range) { 12086 if (!E) 12087 return; 12088 12089 // Don't warn inside macros. 12090 if (E->getExprLoc().isMacroID()) { 12091 const SourceManager &SM = getSourceManager(); 12092 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12093 IsInAnyMacroBody(SM, Range.getBegin())) 12094 return; 12095 } 12096 E = E->IgnoreImpCasts(); 12097 12098 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12099 12100 if (isa<CXXThisExpr>(E)) { 12101 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12102 : diag::warn_this_bool_conversion; 12103 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12104 return; 12105 } 12106 12107 bool IsAddressOf = false; 12108 12109 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12110 if (UO->getOpcode() != UO_AddrOf) 12111 return; 12112 IsAddressOf = true; 12113 E = UO->getSubExpr(); 12114 } 12115 12116 if (IsAddressOf) { 12117 unsigned DiagID = IsCompare 12118 ? diag::warn_address_of_reference_null_compare 12119 : diag::warn_address_of_reference_bool_conversion; 12120 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12121 << IsEqual; 12122 if (CheckForReference(*this, E, PD)) { 12123 return; 12124 } 12125 } 12126 12127 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12128 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12129 std::string Str; 12130 llvm::raw_string_ostream S(Str); 12131 E->printPretty(S, nullptr, getPrintingPolicy()); 12132 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12133 : diag::warn_cast_nonnull_to_bool; 12134 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12135 << E->getSourceRange() << Range << IsEqual; 12136 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12137 }; 12138 12139 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12140 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12141 if (auto *Callee = Call->getDirectCallee()) { 12142 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12143 ComplainAboutNonnullParamOrCall(A); 12144 return; 12145 } 12146 } 12147 } 12148 12149 // Expect to find a single Decl. Skip anything more complicated. 12150 ValueDecl *D = nullptr; 12151 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12152 D = R->getDecl(); 12153 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12154 D = M->getMemberDecl(); 12155 } 12156 12157 // Weak Decls can be null. 12158 if (!D || D->isWeak()) 12159 return; 12160 12161 // Check for parameter decl with nonnull attribute 12162 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12163 if (getCurFunction() && 12164 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12165 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12166 ComplainAboutNonnullParamOrCall(A); 12167 return; 12168 } 12169 12170 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12171 // Skip function template not specialized yet. 12172 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12173 return; 12174 auto ParamIter = llvm::find(FD->parameters(), PV); 12175 assert(ParamIter != FD->param_end()); 12176 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12177 12178 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12179 if (!NonNull->args_size()) { 12180 ComplainAboutNonnullParamOrCall(NonNull); 12181 return; 12182 } 12183 12184 for (const ParamIdx &ArgNo : NonNull->args()) { 12185 if (ArgNo.getASTIndex() == ParamNo) { 12186 ComplainAboutNonnullParamOrCall(NonNull); 12187 return; 12188 } 12189 } 12190 } 12191 } 12192 } 12193 } 12194 12195 QualType T = D->getType(); 12196 const bool IsArray = T->isArrayType(); 12197 const bool IsFunction = T->isFunctionType(); 12198 12199 // Address of function is used to silence the function warning. 12200 if (IsAddressOf && IsFunction) { 12201 return; 12202 } 12203 12204 // Found nothing. 12205 if (!IsAddressOf && !IsFunction && !IsArray) 12206 return; 12207 12208 // Pretty print the expression for the diagnostic. 12209 std::string Str; 12210 llvm::raw_string_ostream S(Str); 12211 E->printPretty(S, nullptr, getPrintingPolicy()); 12212 12213 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12214 : diag::warn_impcast_pointer_to_bool; 12215 enum { 12216 AddressOf, 12217 FunctionPointer, 12218 ArrayPointer 12219 } DiagType; 12220 if (IsAddressOf) 12221 DiagType = AddressOf; 12222 else if (IsFunction) 12223 DiagType = FunctionPointer; 12224 else if (IsArray) 12225 DiagType = ArrayPointer; 12226 else 12227 llvm_unreachable("Could not determine diagnostic."); 12228 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12229 << Range << IsEqual; 12230 12231 if (!IsFunction) 12232 return; 12233 12234 // Suggest '&' to silence the function warning. 12235 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12236 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12237 12238 // Check to see if '()' fixit should be emitted. 12239 QualType ReturnType; 12240 UnresolvedSet<4> NonTemplateOverloads; 12241 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12242 if (ReturnType.isNull()) 12243 return; 12244 12245 if (IsCompare) { 12246 // There are two cases here. If there is null constant, the only suggest 12247 // for a pointer return type. If the null is 0, then suggest if the return 12248 // type is a pointer or an integer type. 12249 if (!ReturnType->isPointerType()) { 12250 if (NullKind == Expr::NPCK_ZeroExpression || 12251 NullKind == Expr::NPCK_ZeroLiteral) { 12252 if (!ReturnType->isIntegerType()) 12253 return; 12254 } else { 12255 return; 12256 } 12257 } 12258 } else { // !IsCompare 12259 // For function to bool, only suggest if the function pointer has bool 12260 // return type. 12261 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12262 return; 12263 } 12264 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12265 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12266 } 12267 12268 /// Diagnoses "dangerous" implicit conversions within the given 12269 /// expression (which is a full expression). Implements -Wconversion 12270 /// and -Wsign-compare. 12271 /// 12272 /// \param CC the "context" location of the implicit conversion, i.e. 12273 /// the most location of the syntactic entity requiring the implicit 12274 /// conversion 12275 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12276 // Don't diagnose in unevaluated contexts. 12277 if (isUnevaluatedContext()) 12278 return; 12279 12280 // Don't diagnose for value- or type-dependent expressions. 12281 if (E->isTypeDependent() || E->isValueDependent()) 12282 return; 12283 12284 // Check for array bounds violations in cases where the check isn't triggered 12285 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12286 // ArraySubscriptExpr is on the RHS of a variable initialization. 12287 CheckArrayAccess(E); 12288 12289 // This is not the right CC for (e.g.) a variable initialization. 12290 AnalyzeImplicitConversions(*this, E, CC); 12291 } 12292 12293 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12294 /// Input argument E is a logical expression. 12295 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12296 ::CheckBoolLikeConversion(*this, E, CC); 12297 } 12298 12299 /// Diagnose when expression is an integer constant expression and its evaluation 12300 /// results in integer overflow 12301 void Sema::CheckForIntOverflow (Expr *E) { 12302 // Use a work list to deal with nested struct initializers. 12303 SmallVector<Expr *, 2> Exprs(1, E); 12304 12305 do { 12306 Expr *OriginalE = Exprs.pop_back_val(); 12307 Expr *E = OriginalE->IgnoreParenCasts(); 12308 12309 if (isa<BinaryOperator>(E)) { 12310 E->EvaluateForOverflow(Context); 12311 continue; 12312 } 12313 12314 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12315 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12316 else if (isa<ObjCBoxedExpr>(OriginalE)) 12317 E->EvaluateForOverflow(Context); 12318 else if (auto Call = dyn_cast<CallExpr>(E)) 12319 Exprs.append(Call->arg_begin(), Call->arg_end()); 12320 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12321 Exprs.append(Message->arg_begin(), Message->arg_end()); 12322 } while (!Exprs.empty()); 12323 } 12324 12325 namespace { 12326 12327 /// Visitor for expressions which looks for unsequenced operations on the 12328 /// same object. 12329 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12330 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12331 12332 /// A tree of sequenced regions within an expression. Two regions are 12333 /// unsequenced if one is an ancestor or a descendent of the other. When we 12334 /// finish processing an expression with sequencing, such as a comma 12335 /// expression, we fold its tree nodes into its parent, since they are 12336 /// unsequenced with respect to nodes we will visit later. 12337 class SequenceTree { 12338 struct Value { 12339 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12340 unsigned Parent : 31; 12341 unsigned Merged : 1; 12342 }; 12343 SmallVector<Value, 8> Values; 12344 12345 public: 12346 /// A region within an expression which may be sequenced with respect 12347 /// to some other region. 12348 class Seq { 12349 friend class SequenceTree; 12350 12351 unsigned Index; 12352 12353 explicit Seq(unsigned N) : Index(N) {} 12354 12355 public: 12356 Seq() : Index(0) {} 12357 }; 12358 12359 SequenceTree() { Values.push_back(Value(0)); } 12360 Seq root() const { return Seq(0); } 12361 12362 /// Create a new sequence of operations, which is an unsequenced 12363 /// subset of \p Parent. This sequence of operations is sequenced with 12364 /// respect to other children of \p Parent. 12365 Seq allocate(Seq Parent) { 12366 Values.push_back(Value(Parent.Index)); 12367 return Seq(Values.size() - 1); 12368 } 12369 12370 /// Merge a sequence of operations into its parent. 12371 void merge(Seq S) { 12372 Values[S.Index].Merged = true; 12373 } 12374 12375 /// Determine whether two operations are unsequenced. This operation 12376 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12377 /// should have been merged into its parent as appropriate. 12378 bool isUnsequenced(Seq Cur, Seq Old) { 12379 unsigned C = representative(Cur.Index); 12380 unsigned Target = representative(Old.Index); 12381 while (C >= Target) { 12382 if (C == Target) 12383 return true; 12384 C = Values[C].Parent; 12385 } 12386 return false; 12387 } 12388 12389 private: 12390 /// Pick a representative for a sequence. 12391 unsigned representative(unsigned K) { 12392 if (Values[K].Merged) 12393 // Perform path compression as we go. 12394 return Values[K].Parent = representative(Values[K].Parent); 12395 return K; 12396 } 12397 }; 12398 12399 /// An object for which we can track unsequenced uses. 12400 using Object = const NamedDecl *; 12401 12402 /// Different flavors of object usage which we track. We only track the 12403 /// least-sequenced usage of each kind. 12404 enum UsageKind { 12405 /// A read of an object. Multiple unsequenced reads are OK. 12406 UK_Use, 12407 12408 /// A modification of an object which is sequenced before the value 12409 /// computation of the expression, such as ++n in C++. 12410 UK_ModAsValue, 12411 12412 /// A modification of an object which is not sequenced before the value 12413 /// computation of the expression, such as n++. 12414 UK_ModAsSideEffect, 12415 12416 UK_Count = UK_ModAsSideEffect + 1 12417 }; 12418 12419 /// Bundle together a sequencing region and the expression corresponding 12420 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12421 struct Usage { 12422 const Expr *UsageExpr; 12423 SequenceTree::Seq Seq; 12424 12425 Usage() : UsageExpr(nullptr), Seq() {} 12426 }; 12427 12428 struct UsageInfo { 12429 Usage Uses[UK_Count]; 12430 12431 /// Have we issued a diagnostic for this object already? 12432 bool Diagnosed; 12433 12434 UsageInfo() : Uses(), Diagnosed(false) {} 12435 }; 12436 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12437 12438 Sema &SemaRef; 12439 12440 /// Sequenced regions within the expression. 12441 SequenceTree Tree; 12442 12443 /// Declaration modifications and references which we have seen. 12444 UsageInfoMap UsageMap; 12445 12446 /// The region we are currently within. 12447 SequenceTree::Seq Region; 12448 12449 /// Filled in with declarations which were modified as a side-effect 12450 /// (that is, post-increment operations). 12451 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12452 12453 /// Expressions to check later. We defer checking these to reduce 12454 /// stack usage. 12455 SmallVectorImpl<const Expr *> &WorkList; 12456 12457 /// RAII object wrapping the visitation of a sequenced subexpression of an 12458 /// expression. At the end of this process, the side-effects of the evaluation 12459 /// become sequenced with respect to the value computation of the result, so 12460 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12461 /// UK_ModAsValue. 12462 struct SequencedSubexpression { 12463 SequencedSubexpression(SequenceChecker &Self) 12464 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12465 Self.ModAsSideEffect = &ModAsSideEffect; 12466 } 12467 12468 ~SequencedSubexpression() { 12469 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12470 // Add a new usage with usage kind UK_ModAsValue, and then restore 12471 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12472 // the previous one was empty). 12473 UsageInfo &UI = Self.UsageMap[M.first]; 12474 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12475 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12476 SideEffectUsage = M.second; 12477 } 12478 Self.ModAsSideEffect = OldModAsSideEffect; 12479 } 12480 12481 SequenceChecker &Self; 12482 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12483 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12484 }; 12485 12486 /// RAII object wrapping the visitation of a subexpression which we might 12487 /// choose to evaluate as a constant. If any subexpression is evaluated and 12488 /// found to be non-constant, this allows us to suppress the evaluation of 12489 /// the outer expression. 12490 class EvaluationTracker { 12491 public: 12492 EvaluationTracker(SequenceChecker &Self) 12493 : Self(Self), Prev(Self.EvalTracker) { 12494 Self.EvalTracker = this; 12495 } 12496 12497 ~EvaluationTracker() { 12498 Self.EvalTracker = Prev; 12499 if (Prev) 12500 Prev->EvalOK &= EvalOK; 12501 } 12502 12503 bool evaluate(const Expr *E, bool &Result) { 12504 if (!EvalOK || E->isValueDependent()) 12505 return false; 12506 EvalOK = E->EvaluateAsBooleanCondition( 12507 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12508 return EvalOK; 12509 } 12510 12511 private: 12512 SequenceChecker &Self; 12513 EvaluationTracker *Prev; 12514 bool EvalOK = true; 12515 } *EvalTracker = nullptr; 12516 12517 /// Find the object which is produced by the specified expression, 12518 /// if any. 12519 Object getObject(const Expr *E, bool Mod) const { 12520 E = E->IgnoreParenCasts(); 12521 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12522 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12523 return getObject(UO->getSubExpr(), Mod); 12524 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12525 if (BO->getOpcode() == BO_Comma) 12526 return getObject(BO->getRHS(), Mod); 12527 if (Mod && BO->isAssignmentOp()) 12528 return getObject(BO->getLHS(), Mod); 12529 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12530 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12531 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12532 return ME->getMemberDecl(); 12533 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12534 // FIXME: If this is a reference, map through to its value. 12535 return DRE->getDecl(); 12536 return nullptr; 12537 } 12538 12539 /// Note that an object \p O was modified or used by an expression 12540 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12541 /// the object \p O as obtained via the \p UsageMap. 12542 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12543 // Get the old usage for the given object and usage kind. 12544 Usage &U = UI.Uses[UK]; 12545 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12546 // If we have a modification as side effect and are in a sequenced 12547 // subexpression, save the old Usage so that we can restore it later 12548 // in SequencedSubexpression::~SequencedSubexpression. 12549 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12550 ModAsSideEffect->push_back(std::make_pair(O, U)); 12551 // Then record the new usage with the current sequencing region. 12552 U.UsageExpr = UsageExpr; 12553 U.Seq = Region; 12554 } 12555 } 12556 12557 /// Check whether a modification or use of an object \p O in an expression 12558 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12559 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12560 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12561 /// usage and false we are checking for a mod-use unsequenced usage. 12562 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12563 UsageKind OtherKind, bool IsModMod) { 12564 if (UI.Diagnosed) 12565 return; 12566 12567 const Usage &U = UI.Uses[OtherKind]; 12568 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12569 return; 12570 12571 const Expr *Mod = U.UsageExpr; 12572 const Expr *ModOrUse = UsageExpr; 12573 if (OtherKind == UK_Use) 12574 std::swap(Mod, ModOrUse); 12575 12576 SemaRef.DiagRuntimeBehavior( 12577 Mod->getExprLoc(), {Mod, ModOrUse}, 12578 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12579 : diag::warn_unsequenced_mod_use) 12580 << O << SourceRange(ModOrUse->getExprLoc())); 12581 UI.Diagnosed = true; 12582 } 12583 12584 // A note on note{Pre, Post}{Use, Mod}: 12585 // 12586 // (It helps to follow the algorithm with an expression such as 12587 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12588 // operations before C++17 and both are well-defined in C++17). 12589 // 12590 // When visiting a node which uses/modify an object we first call notePreUse 12591 // or notePreMod before visiting its sub-expression(s). At this point the 12592 // children of the current node have not yet been visited and so the eventual 12593 // uses/modifications resulting from the children of the current node have not 12594 // been recorded yet. 12595 // 12596 // We then visit the children of the current node. After that notePostUse or 12597 // notePostMod is called. These will 1) detect an unsequenced modification 12598 // as side effect (as in "k++ + k") and 2) add a new usage with the 12599 // appropriate usage kind. 12600 // 12601 // We also have to be careful that some operation sequences modification as 12602 // side effect as well (for example: || or ,). To account for this we wrap 12603 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12604 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12605 // which record usages which are modifications as side effect, and then 12606 // downgrade them (or more accurately restore the previous usage which was a 12607 // modification as side effect) when exiting the scope of the sequenced 12608 // subexpression. 12609 12610 void notePreUse(Object O, const Expr *UseExpr) { 12611 UsageInfo &UI = UsageMap[O]; 12612 // Uses conflict with other modifications. 12613 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12614 } 12615 12616 void notePostUse(Object O, const Expr *UseExpr) { 12617 UsageInfo &UI = UsageMap[O]; 12618 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12619 /*IsModMod=*/false); 12620 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12621 } 12622 12623 void notePreMod(Object O, const Expr *ModExpr) { 12624 UsageInfo &UI = UsageMap[O]; 12625 // Modifications conflict with other modifications and with uses. 12626 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12627 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12628 } 12629 12630 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12631 UsageInfo &UI = UsageMap[O]; 12632 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12633 /*IsModMod=*/true); 12634 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12635 } 12636 12637 public: 12638 SequenceChecker(Sema &S, const Expr *E, 12639 SmallVectorImpl<const Expr *> &WorkList) 12640 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12641 Visit(E); 12642 // Silence a -Wunused-private-field since WorkList is now unused. 12643 // TODO: Evaluate if it can be used, and if not remove it. 12644 (void)this->WorkList; 12645 } 12646 12647 void VisitStmt(const Stmt *S) { 12648 // Skip all statements which aren't expressions for now. 12649 } 12650 12651 void VisitExpr(const Expr *E) { 12652 // By default, just recurse to evaluated subexpressions. 12653 Base::VisitStmt(E); 12654 } 12655 12656 void VisitCastExpr(const CastExpr *E) { 12657 Object O = Object(); 12658 if (E->getCastKind() == CK_LValueToRValue) 12659 O = getObject(E->getSubExpr(), false); 12660 12661 if (O) 12662 notePreUse(O, E); 12663 VisitExpr(E); 12664 if (O) 12665 notePostUse(O, E); 12666 } 12667 12668 void VisitSequencedExpressions(const Expr *SequencedBefore, 12669 const Expr *SequencedAfter) { 12670 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12671 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12672 SequenceTree::Seq OldRegion = Region; 12673 12674 { 12675 SequencedSubexpression SeqBefore(*this); 12676 Region = BeforeRegion; 12677 Visit(SequencedBefore); 12678 } 12679 12680 Region = AfterRegion; 12681 Visit(SequencedAfter); 12682 12683 Region = OldRegion; 12684 12685 Tree.merge(BeforeRegion); 12686 Tree.merge(AfterRegion); 12687 } 12688 12689 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12690 // C++17 [expr.sub]p1: 12691 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12692 // expression E1 is sequenced before the expression E2. 12693 if (SemaRef.getLangOpts().CPlusPlus17) 12694 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12695 else { 12696 Visit(ASE->getLHS()); 12697 Visit(ASE->getRHS()); 12698 } 12699 } 12700 12701 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12702 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12703 void VisitBinPtrMem(const BinaryOperator *BO) { 12704 // C++17 [expr.mptr.oper]p4: 12705 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12706 // the expression E1 is sequenced before the expression E2. 12707 if (SemaRef.getLangOpts().CPlusPlus17) 12708 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12709 else { 12710 Visit(BO->getLHS()); 12711 Visit(BO->getRHS()); 12712 } 12713 } 12714 12715 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12716 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12717 void VisitBinShlShr(const BinaryOperator *BO) { 12718 // C++17 [expr.shift]p4: 12719 // The expression E1 is sequenced before the expression E2. 12720 if (SemaRef.getLangOpts().CPlusPlus17) 12721 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12722 else { 12723 Visit(BO->getLHS()); 12724 Visit(BO->getRHS()); 12725 } 12726 } 12727 12728 void VisitBinComma(const BinaryOperator *BO) { 12729 // C++11 [expr.comma]p1: 12730 // Every value computation and side effect associated with the left 12731 // expression is sequenced before every value computation and side 12732 // effect associated with the right expression. 12733 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12734 } 12735 12736 void VisitBinAssign(const BinaryOperator *BO) { 12737 SequenceTree::Seq RHSRegion; 12738 SequenceTree::Seq LHSRegion; 12739 if (SemaRef.getLangOpts().CPlusPlus17) { 12740 RHSRegion = Tree.allocate(Region); 12741 LHSRegion = Tree.allocate(Region); 12742 } else { 12743 RHSRegion = Region; 12744 LHSRegion = Region; 12745 } 12746 SequenceTree::Seq OldRegion = Region; 12747 12748 // C++11 [expr.ass]p1: 12749 // [...] the assignment is sequenced after the value computation 12750 // of the right and left operands, [...] 12751 // 12752 // so check it before inspecting the operands and update the 12753 // map afterwards. 12754 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12755 if (O) 12756 notePreMod(O, BO); 12757 12758 if (SemaRef.getLangOpts().CPlusPlus17) { 12759 // C++17 [expr.ass]p1: 12760 // [...] The right operand is sequenced before the left operand. [...] 12761 { 12762 SequencedSubexpression SeqBefore(*this); 12763 Region = RHSRegion; 12764 Visit(BO->getRHS()); 12765 } 12766 12767 Region = LHSRegion; 12768 Visit(BO->getLHS()); 12769 12770 if (O && isa<CompoundAssignOperator>(BO)) 12771 notePostUse(O, BO); 12772 12773 } else { 12774 // C++11 does not specify any sequencing between the LHS and RHS. 12775 Region = LHSRegion; 12776 Visit(BO->getLHS()); 12777 12778 if (O && isa<CompoundAssignOperator>(BO)) 12779 notePostUse(O, BO); 12780 12781 Region = RHSRegion; 12782 Visit(BO->getRHS()); 12783 } 12784 12785 // C++11 [expr.ass]p1: 12786 // the assignment is sequenced [...] before the value computation of the 12787 // assignment expression. 12788 // C11 6.5.16/3 has no such rule. 12789 Region = OldRegion; 12790 if (O) 12791 notePostMod(O, BO, 12792 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12793 : UK_ModAsSideEffect); 12794 if (SemaRef.getLangOpts().CPlusPlus17) { 12795 Tree.merge(RHSRegion); 12796 Tree.merge(LHSRegion); 12797 } 12798 } 12799 12800 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12801 VisitBinAssign(CAO); 12802 } 12803 12804 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12805 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12806 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12807 Object O = getObject(UO->getSubExpr(), true); 12808 if (!O) 12809 return VisitExpr(UO); 12810 12811 notePreMod(O, UO); 12812 Visit(UO->getSubExpr()); 12813 // C++11 [expr.pre.incr]p1: 12814 // the expression ++x is equivalent to x+=1 12815 notePostMod(O, UO, 12816 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12817 : UK_ModAsSideEffect); 12818 } 12819 12820 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12821 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12822 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12823 Object O = getObject(UO->getSubExpr(), true); 12824 if (!O) 12825 return VisitExpr(UO); 12826 12827 notePreMod(O, UO); 12828 Visit(UO->getSubExpr()); 12829 notePostMod(O, UO, UK_ModAsSideEffect); 12830 } 12831 12832 void VisitBinLOr(const BinaryOperator *BO) { 12833 // C++11 [expr.log.or]p2: 12834 // If the second expression is evaluated, every value computation and 12835 // side effect associated with the first expression is sequenced before 12836 // every value computation and side effect associated with the 12837 // second expression. 12838 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12839 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12840 SequenceTree::Seq OldRegion = Region; 12841 12842 EvaluationTracker Eval(*this); 12843 { 12844 SequencedSubexpression Sequenced(*this); 12845 Region = LHSRegion; 12846 Visit(BO->getLHS()); 12847 } 12848 12849 // C++11 [expr.log.or]p1: 12850 // [...] the second operand is not evaluated if the first operand 12851 // evaluates to true. 12852 bool EvalResult = false; 12853 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12854 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 12855 if (ShouldVisitRHS) { 12856 Region = RHSRegion; 12857 Visit(BO->getRHS()); 12858 } 12859 12860 Region = OldRegion; 12861 Tree.merge(LHSRegion); 12862 Tree.merge(RHSRegion); 12863 } 12864 12865 void VisitBinLAnd(const BinaryOperator *BO) { 12866 // C++11 [expr.log.and]p2: 12867 // If the second expression is evaluated, every value computation and 12868 // side effect associated with the first expression is sequenced before 12869 // every value computation and side effect associated with the 12870 // second expression. 12871 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12872 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12873 SequenceTree::Seq OldRegion = Region; 12874 12875 EvaluationTracker Eval(*this); 12876 { 12877 SequencedSubexpression Sequenced(*this); 12878 Region = LHSRegion; 12879 Visit(BO->getLHS()); 12880 } 12881 12882 // C++11 [expr.log.and]p1: 12883 // [...] the second operand is not evaluated if the first operand is false. 12884 bool EvalResult = false; 12885 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12886 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 12887 if (ShouldVisitRHS) { 12888 Region = RHSRegion; 12889 Visit(BO->getRHS()); 12890 } 12891 12892 Region = OldRegion; 12893 Tree.merge(LHSRegion); 12894 Tree.merge(RHSRegion); 12895 } 12896 12897 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 12898 // C++11 [expr.cond]p1: 12899 // [...] Every value computation and side effect associated with the first 12900 // expression is sequenced before every value computation and side effect 12901 // associated with the second or third expression. 12902 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 12903 12904 // No sequencing is specified between the true and false expression. 12905 // However since exactly one of both is going to be evaluated we can 12906 // consider them to be sequenced. This is needed to avoid warning on 12907 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 12908 // both the true and false expressions because we can't evaluate x. 12909 // This will still allow us to detect an expression like (pre C++17) 12910 // "(x ? y += 1 : y += 2) = y". 12911 // 12912 // We don't wrap the visitation of the true and false expression with 12913 // SequencedSubexpression because we don't want to downgrade modifications 12914 // as side effect in the true and false expressions after the visition 12915 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 12916 // not warn between the two "y++", but we should warn between the "y++" 12917 // and the "y". 12918 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 12919 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 12920 SequenceTree::Seq OldRegion = Region; 12921 12922 EvaluationTracker Eval(*this); 12923 { 12924 SequencedSubexpression Sequenced(*this); 12925 Region = ConditionRegion; 12926 Visit(CO->getCond()); 12927 } 12928 12929 // C++11 [expr.cond]p1: 12930 // [...] The first expression is contextually converted to bool (Clause 4). 12931 // It is evaluated and if it is true, the result of the conditional 12932 // expression is the value of the second expression, otherwise that of the 12933 // third expression. Only one of the second and third expressions is 12934 // evaluated. [...] 12935 bool EvalResult = false; 12936 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 12937 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 12938 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 12939 if (ShouldVisitTrueExpr) { 12940 Region = TrueRegion; 12941 Visit(CO->getTrueExpr()); 12942 } 12943 if (ShouldVisitFalseExpr) { 12944 Region = FalseRegion; 12945 Visit(CO->getFalseExpr()); 12946 } 12947 12948 Region = OldRegion; 12949 Tree.merge(ConditionRegion); 12950 Tree.merge(TrueRegion); 12951 Tree.merge(FalseRegion); 12952 } 12953 12954 void VisitCallExpr(const CallExpr *CE) { 12955 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12956 12957 if (CE->isUnevaluatedBuiltinCall(Context)) 12958 return; 12959 12960 // C++11 [intro.execution]p15: 12961 // When calling a function [...], every value computation and side effect 12962 // associated with any argument expression, or with the postfix expression 12963 // designating the called function, is sequenced before execution of every 12964 // expression or statement in the body of the function [and thus before 12965 // the value computation of its result]. 12966 SequencedSubexpression Sequenced(*this); 12967 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 12968 // C++17 [expr.call]p5 12969 // The postfix-expression is sequenced before each expression in the 12970 // expression-list and any default argument. [...] 12971 SequenceTree::Seq CalleeRegion; 12972 SequenceTree::Seq OtherRegion; 12973 if (SemaRef.getLangOpts().CPlusPlus17) { 12974 CalleeRegion = Tree.allocate(Region); 12975 OtherRegion = Tree.allocate(Region); 12976 } else { 12977 CalleeRegion = Region; 12978 OtherRegion = Region; 12979 } 12980 SequenceTree::Seq OldRegion = Region; 12981 12982 // Visit the callee expression first. 12983 Region = CalleeRegion; 12984 if (SemaRef.getLangOpts().CPlusPlus17) { 12985 SequencedSubexpression Sequenced(*this); 12986 Visit(CE->getCallee()); 12987 } else { 12988 Visit(CE->getCallee()); 12989 } 12990 12991 // Then visit the argument expressions. 12992 Region = OtherRegion; 12993 for (const Expr *Argument : CE->arguments()) 12994 Visit(Argument); 12995 12996 Region = OldRegion; 12997 if (SemaRef.getLangOpts().CPlusPlus17) { 12998 Tree.merge(CalleeRegion); 12999 Tree.merge(OtherRegion); 13000 } 13001 }); 13002 } 13003 13004 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13005 // This is a call, so all subexpressions are sequenced before the result. 13006 SequencedSubexpression Sequenced(*this); 13007 13008 if (!CCE->isListInitialization()) 13009 return VisitExpr(CCE); 13010 13011 // In C++11, list initializations are sequenced. 13012 SmallVector<SequenceTree::Seq, 32> Elts; 13013 SequenceTree::Seq Parent = Region; 13014 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13015 E = CCE->arg_end(); 13016 I != E; ++I) { 13017 Region = Tree.allocate(Parent); 13018 Elts.push_back(Region); 13019 Visit(*I); 13020 } 13021 13022 // Forget that the initializers are sequenced. 13023 Region = Parent; 13024 for (unsigned I = 0; I < Elts.size(); ++I) 13025 Tree.merge(Elts[I]); 13026 } 13027 13028 void VisitInitListExpr(const InitListExpr *ILE) { 13029 if (!SemaRef.getLangOpts().CPlusPlus11) 13030 return VisitExpr(ILE); 13031 13032 // In C++11, list initializations are sequenced. 13033 SmallVector<SequenceTree::Seq, 32> Elts; 13034 SequenceTree::Seq Parent = Region; 13035 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13036 const Expr *E = ILE->getInit(I); 13037 if (!E) 13038 continue; 13039 Region = Tree.allocate(Parent); 13040 Elts.push_back(Region); 13041 Visit(E); 13042 } 13043 13044 // Forget that the initializers are sequenced. 13045 Region = Parent; 13046 for (unsigned I = 0; I < Elts.size(); ++I) 13047 Tree.merge(Elts[I]); 13048 } 13049 }; 13050 13051 } // namespace 13052 13053 void Sema::CheckUnsequencedOperations(const Expr *E) { 13054 SmallVector<const Expr *, 8> WorkList; 13055 WorkList.push_back(E); 13056 while (!WorkList.empty()) { 13057 const Expr *Item = WorkList.pop_back_val(); 13058 SequenceChecker(*this, Item, WorkList); 13059 } 13060 } 13061 13062 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13063 bool IsConstexpr) { 13064 llvm::SaveAndRestore<bool> ConstantContext( 13065 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13066 CheckImplicitConversions(E, CheckLoc); 13067 if (!E->isInstantiationDependent()) 13068 CheckUnsequencedOperations(E); 13069 if (!IsConstexpr && !E->isValueDependent()) 13070 CheckForIntOverflow(E); 13071 DiagnoseMisalignedMembers(); 13072 } 13073 13074 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13075 FieldDecl *BitField, 13076 Expr *Init) { 13077 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13078 } 13079 13080 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13081 SourceLocation Loc) { 13082 if (!PType->isVariablyModifiedType()) 13083 return; 13084 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13085 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13086 return; 13087 } 13088 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13089 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13090 return; 13091 } 13092 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13093 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13094 return; 13095 } 13096 13097 const ArrayType *AT = S.Context.getAsArrayType(PType); 13098 if (!AT) 13099 return; 13100 13101 if (AT->getSizeModifier() != ArrayType::Star) { 13102 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13103 return; 13104 } 13105 13106 S.Diag(Loc, diag::err_array_star_in_function_definition); 13107 } 13108 13109 /// CheckParmsForFunctionDef - Check that the parameters of the given 13110 /// function are appropriate for the definition of a function. This 13111 /// takes care of any checks that cannot be performed on the 13112 /// declaration itself, e.g., that the types of each of the function 13113 /// parameters are complete. 13114 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13115 bool CheckParameterNames) { 13116 bool HasInvalidParm = false; 13117 for (ParmVarDecl *Param : Parameters) { 13118 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13119 // function declarator that is part of a function definition of 13120 // that function shall not have incomplete type. 13121 // 13122 // This is also C++ [dcl.fct]p6. 13123 if (!Param->isInvalidDecl() && 13124 RequireCompleteType(Param->getLocation(), Param->getType(), 13125 diag::err_typecheck_decl_incomplete_type)) { 13126 Param->setInvalidDecl(); 13127 HasInvalidParm = true; 13128 } 13129 13130 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13131 // declaration of each parameter shall include an identifier. 13132 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13133 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13134 // Diagnose this as an extension in C17 and earlier. 13135 if (!getLangOpts().C2x) 13136 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13137 } 13138 13139 // C99 6.7.5.3p12: 13140 // If the function declarator is not part of a definition of that 13141 // function, parameters may have incomplete type and may use the [*] 13142 // notation in their sequences of declarator specifiers to specify 13143 // variable length array types. 13144 QualType PType = Param->getOriginalType(); 13145 // FIXME: This diagnostic should point the '[*]' if source-location 13146 // information is added for it. 13147 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13148 13149 // If the parameter is a c++ class type and it has to be destructed in the 13150 // callee function, declare the destructor so that it can be called by the 13151 // callee function. Do not perform any direct access check on the dtor here. 13152 if (!Param->isInvalidDecl()) { 13153 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13154 if (!ClassDecl->isInvalidDecl() && 13155 !ClassDecl->hasIrrelevantDestructor() && 13156 !ClassDecl->isDependentContext() && 13157 ClassDecl->isParamDestroyedInCallee()) { 13158 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13159 MarkFunctionReferenced(Param->getLocation(), Destructor); 13160 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13161 } 13162 } 13163 } 13164 13165 // Parameters with the pass_object_size attribute only need to be marked 13166 // constant at function definitions. Because we lack information about 13167 // whether we're on a declaration or definition when we're instantiating the 13168 // attribute, we need to check for constness here. 13169 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13170 if (!Param->getType().isConstQualified()) 13171 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13172 << Attr->getSpelling() << 1; 13173 13174 // Check for parameter names shadowing fields from the class. 13175 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13176 // The owning context for the parameter should be the function, but we 13177 // want to see if this function's declaration context is a record. 13178 DeclContext *DC = Param->getDeclContext(); 13179 if (DC && DC->isFunctionOrMethod()) { 13180 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13181 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13182 RD, /*DeclIsField*/ false); 13183 } 13184 } 13185 } 13186 13187 return HasInvalidParm; 13188 } 13189 13190 Optional<std::pair<CharUnits, CharUnits>> 13191 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13192 13193 /// Compute the alignment and offset of the base class object given the 13194 /// derived-to-base cast expression and the alignment and offset of the derived 13195 /// class object. 13196 static std::pair<CharUnits, CharUnits> 13197 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13198 CharUnits BaseAlignment, CharUnits Offset, 13199 ASTContext &Ctx) { 13200 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13201 ++PathI) { 13202 const CXXBaseSpecifier *Base = *PathI; 13203 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13204 if (Base->isVirtual()) { 13205 // The complete object may have a lower alignment than the non-virtual 13206 // alignment of the base, in which case the base may be misaligned. Choose 13207 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13208 // conservative lower bound of the complete object alignment. 13209 CharUnits NonVirtualAlignment = 13210 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13211 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13212 Offset = CharUnits::Zero(); 13213 } else { 13214 const ASTRecordLayout &RL = 13215 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13216 Offset += RL.getBaseClassOffset(BaseDecl); 13217 } 13218 DerivedType = Base->getType(); 13219 } 13220 13221 return std::make_pair(BaseAlignment, Offset); 13222 } 13223 13224 /// Compute the alignment and offset of a binary additive operator. 13225 static Optional<std::pair<CharUnits, CharUnits>> 13226 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13227 bool IsSub, ASTContext &Ctx) { 13228 QualType PointeeType = PtrE->getType()->getPointeeType(); 13229 13230 if (!PointeeType->isConstantSizeType()) 13231 return llvm::None; 13232 13233 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13234 13235 if (!P) 13236 return llvm::None; 13237 13238 llvm::APSInt IdxRes; 13239 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13240 if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) { 13241 CharUnits Offset = EltSize * IdxRes.getExtValue(); 13242 if (IsSub) 13243 Offset = -Offset; 13244 return std::make_pair(P->first, P->second + Offset); 13245 } 13246 13247 // If the integer expression isn't a constant expression, compute the lower 13248 // bound of the alignment using the alignment and offset of the pointer 13249 // expression and the element size. 13250 return std::make_pair( 13251 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13252 CharUnits::Zero()); 13253 } 13254 13255 /// This helper function takes an lvalue expression and returns the alignment of 13256 /// a VarDecl and a constant offset from the VarDecl. 13257 Optional<std::pair<CharUnits, CharUnits>> 13258 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13259 E = E->IgnoreParens(); 13260 switch (E->getStmtClass()) { 13261 default: 13262 break; 13263 case Stmt::CStyleCastExprClass: 13264 case Stmt::CXXStaticCastExprClass: 13265 case Stmt::ImplicitCastExprClass: { 13266 auto *CE = cast<CastExpr>(E); 13267 const Expr *From = CE->getSubExpr(); 13268 switch (CE->getCastKind()) { 13269 default: 13270 break; 13271 case CK_NoOp: 13272 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13273 case CK_UncheckedDerivedToBase: 13274 case CK_DerivedToBase: { 13275 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13276 if (!P) 13277 break; 13278 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13279 P->second, Ctx); 13280 } 13281 } 13282 break; 13283 } 13284 case Stmt::ArraySubscriptExprClass: { 13285 auto *ASE = cast<ArraySubscriptExpr>(E); 13286 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13287 false, Ctx); 13288 } 13289 case Stmt::DeclRefExprClass: { 13290 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13291 // FIXME: If VD is captured by copy or is an escaping __block variable, 13292 // use the alignment of VD's type. 13293 if (!VD->getType()->isReferenceType()) 13294 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13295 if (VD->hasInit()) 13296 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13297 } 13298 break; 13299 } 13300 case Stmt::MemberExprClass: { 13301 auto *ME = cast<MemberExpr>(E); 13302 if (ME->isArrow()) 13303 break; 13304 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13305 if (!FD || FD->getType()->isReferenceType()) 13306 break; 13307 auto P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13308 if (!P) 13309 break; 13310 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13311 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13312 return std::make_pair(P->first, 13313 P->second + CharUnits::fromQuantity(Offset)); 13314 } 13315 case Stmt::UnaryOperatorClass: { 13316 auto *UO = cast<UnaryOperator>(E); 13317 switch (UO->getOpcode()) { 13318 default: 13319 break; 13320 case UO_Deref: 13321 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13322 } 13323 break; 13324 } 13325 case Stmt::BinaryOperatorClass: { 13326 auto *BO = cast<BinaryOperator>(E); 13327 auto Opcode = BO->getOpcode(); 13328 switch (Opcode) { 13329 default: 13330 break; 13331 case BO_Comma: 13332 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13333 } 13334 break; 13335 } 13336 } 13337 return llvm::None; 13338 } 13339 13340 /// This helper function takes a pointer expression and returns the alignment of 13341 /// a VarDecl and a constant offset from the VarDecl. 13342 Optional<std::pair<CharUnits, CharUnits>> 13343 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 13344 E = E->IgnoreParens(); 13345 switch (E->getStmtClass()) { 13346 default: 13347 break; 13348 case Stmt::CStyleCastExprClass: 13349 case Stmt::CXXStaticCastExprClass: 13350 case Stmt::ImplicitCastExprClass: { 13351 auto *CE = cast<CastExpr>(E); 13352 const Expr *From = CE->getSubExpr(); 13353 switch (CE->getCastKind()) { 13354 default: 13355 break; 13356 case CK_NoOp: 13357 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13358 case CK_ArrayToPointerDecay: 13359 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13360 case CK_UncheckedDerivedToBase: 13361 case CK_DerivedToBase: { 13362 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13363 if (!P) 13364 break; 13365 return getDerivedToBaseAlignmentAndOffset( 13366 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13367 } 13368 } 13369 break; 13370 } 13371 case Stmt::UnaryOperatorClass: { 13372 auto *UO = cast<UnaryOperator>(E); 13373 if (UO->getOpcode() == UO_AddrOf) 13374 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13375 break; 13376 } 13377 case Stmt::BinaryOperatorClass: { 13378 auto *BO = cast<BinaryOperator>(E); 13379 auto Opcode = BO->getOpcode(); 13380 switch (Opcode) { 13381 default: 13382 break; 13383 case BO_Add: 13384 case BO_Sub: { 13385 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13386 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13387 std::swap(LHS, RHS); 13388 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13389 Ctx); 13390 } 13391 case BO_Comma: 13392 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13393 } 13394 break; 13395 } 13396 } 13397 return llvm::None; 13398 } 13399 13400 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13401 // See if we can compute the alignment of a VarDecl and an offset from it. 13402 Optional<std::pair<CharUnits, CharUnits>> P = 13403 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13404 13405 if (P) 13406 return P->first.alignmentAtOffset(P->second); 13407 13408 // If that failed, return the type's alignment. 13409 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13410 } 13411 13412 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13413 /// pointer cast increases the alignment requirements. 13414 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13415 // This is actually a lot of work to potentially be doing on every 13416 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13417 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13418 return; 13419 13420 // Ignore dependent types. 13421 if (T->isDependentType() || Op->getType()->isDependentType()) 13422 return; 13423 13424 // Require that the destination be a pointer type. 13425 const PointerType *DestPtr = T->getAs<PointerType>(); 13426 if (!DestPtr) return; 13427 13428 // If the destination has alignment 1, we're done. 13429 QualType DestPointee = DestPtr->getPointeeType(); 13430 if (DestPointee->isIncompleteType()) return; 13431 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13432 if (DestAlign.isOne()) return; 13433 13434 // Require that the source be a pointer type. 13435 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13436 if (!SrcPtr) return; 13437 QualType SrcPointee = SrcPtr->getPointeeType(); 13438 13439 // Whitelist casts from cv void*. We already implicitly 13440 // whitelisted casts to cv void*, since they have alignment 1. 13441 // Also whitelist casts involving incomplete types, which implicitly 13442 // includes 'void'. 13443 if (SrcPointee->isIncompleteType()) return; 13444 13445 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13446 13447 if (SrcAlign >= DestAlign) return; 13448 13449 Diag(TRange.getBegin(), diag::warn_cast_align) 13450 << Op->getType() << T 13451 << static_cast<unsigned>(SrcAlign.getQuantity()) 13452 << static_cast<unsigned>(DestAlign.getQuantity()) 13453 << TRange << Op->getSourceRange(); 13454 } 13455 13456 /// Check whether this array fits the idiom of a size-one tail padded 13457 /// array member of a struct. 13458 /// 13459 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13460 /// commonly used to emulate flexible arrays in C89 code. 13461 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13462 const NamedDecl *ND) { 13463 if (Size != 1 || !ND) return false; 13464 13465 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13466 if (!FD) return false; 13467 13468 // Don't consider sizes resulting from macro expansions or template argument 13469 // substitution to form C89 tail-padded arrays. 13470 13471 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13472 while (TInfo) { 13473 TypeLoc TL = TInfo->getTypeLoc(); 13474 // Look through typedefs. 13475 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13476 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13477 TInfo = TDL->getTypeSourceInfo(); 13478 continue; 13479 } 13480 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13481 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13482 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13483 return false; 13484 } 13485 break; 13486 } 13487 13488 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13489 if (!RD) return false; 13490 if (RD->isUnion()) return false; 13491 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13492 if (!CRD->isStandardLayout()) return false; 13493 } 13494 13495 // See if this is the last field decl in the record. 13496 const Decl *D = FD; 13497 while ((D = D->getNextDeclInContext())) 13498 if (isa<FieldDecl>(D)) 13499 return false; 13500 return true; 13501 } 13502 13503 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13504 const ArraySubscriptExpr *ASE, 13505 bool AllowOnePastEnd, bool IndexNegated) { 13506 // Already diagnosed by the constant evaluator. 13507 if (isConstantEvaluated()) 13508 return; 13509 13510 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13511 if (IndexExpr->isValueDependent()) 13512 return; 13513 13514 const Type *EffectiveType = 13515 BaseExpr->getType()->getPointeeOrArrayElementType(); 13516 BaseExpr = BaseExpr->IgnoreParenCasts(); 13517 const ConstantArrayType *ArrayTy = 13518 Context.getAsConstantArrayType(BaseExpr->getType()); 13519 13520 if (!ArrayTy) 13521 return; 13522 13523 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13524 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13525 return; 13526 13527 Expr::EvalResult Result; 13528 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13529 return; 13530 13531 llvm::APSInt index = Result.Val.getInt(); 13532 if (IndexNegated) 13533 index = -index; 13534 13535 const NamedDecl *ND = nullptr; 13536 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13537 ND = DRE->getDecl(); 13538 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13539 ND = ME->getMemberDecl(); 13540 13541 if (index.isUnsigned() || !index.isNegative()) { 13542 // It is possible that the type of the base expression after 13543 // IgnoreParenCasts is incomplete, even though the type of the base 13544 // expression before IgnoreParenCasts is complete (see PR39746 for an 13545 // example). In this case we have no information about whether the array 13546 // access exceeds the array bounds. However we can still diagnose an array 13547 // access which precedes the array bounds. 13548 if (BaseType->isIncompleteType()) 13549 return; 13550 13551 llvm::APInt size = ArrayTy->getSize(); 13552 if (!size.isStrictlyPositive()) 13553 return; 13554 13555 if (BaseType != EffectiveType) { 13556 // Make sure we're comparing apples to apples when comparing index to size 13557 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13558 uint64_t array_typesize = Context.getTypeSize(BaseType); 13559 // Handle ptrarith_typesize being zero, such as when casting to void* 13560 if (!ptrarith_typesize) ptrarith_typesize = 1; 13561 if (ptrarith_typesize != array_typesize) { 13562 // There's a cast to a different size type involved 13563 uint64_t ratio = array_typesize / ptrarith_typesize; 13564 // TODO: Be smarter about handling cases where array_typesize is not a 13565 // multiple of ptrarith_typesize 13566 if (ptrarith_typesize * ratio == array_typesize) 13567 size *= llvm::APInt(size.getBitWidth(), ratio); 13568 } 13569 } 13570 13571 if (size.getBitWidth() > index.getBitWidth()) 13572 index = index.zext(size.getBitWidth()); 13573 else if (size.getBitWidth() < index.getBitWidth()) 13574 size = size.zext(index.getBitWidth()); 13575 13576 // For array subscripting the index must be less than size, but for pointer 13577 // arithmetic also allow the index (offset) to be equal to size since 13578 // computing the next address after the end of the array is legal and 13579 // commonly done e.g. in C++ iterators and range-based for loops. 13580 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13581 return; 13582 13583 // Also don't warn for arrays of size 1 which are members of some 13584 // structure. These are often used to approximate flexible arrays in C89 13585 // code. 13586 if (IsTailPaddedMemberArray(*this, size, ND)) 13587 return; 13588 13589 // Suppress the warning if the subscript expression (as identified by the 13590 // ']' location) and the index expression are both from macro expansions 13591 // within a system header. 13592 if (ASE) { 13593 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13594 ASE->getRBracketLoc()); 13595 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13596 SourceLocation IndexLoc = 13597 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13598 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13599 return; 13600 } 13601 } 13602 13603 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13604 if (ASE) 13605 DiagID = diag::warn_array_index_exceeds_bounds; 13606 13607 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13608 PDiag(DiagID) << index.toString(10, true) 13609 << size.toString(10, true) 13610 << (unsigned)size.getLimitedValue(~0U) 13611 << IndexExpr->getSourceRange()); 13612 } else { 13613 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13614 if (!ASE) { 13615 DiagID = diag::warn_ptr_arith_precedes_bounds; 13616 if (index.isNegative()) index = -index; 13617 } 13618 13619 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13620 PDiag(DiagID) << index.toString(10, true) 13621 << IndexExpr->getSourceRange()); 13622 } 13623 13624 if (!ND) { 13625 // Try harder to find a NamedDecl to point at in the note. 13626 while (const ArraySubscriptExpr *ASE = 13627 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13628 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13629 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13630 ND = DRE->getDecl(); 13631 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13632 ND = ME->getMemberDecl(); 13633 } 13634 13635 if (ND) 13636 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13637 PDiag(diag::note_array_declared_here) 13638 << ND->getDeclName()); 13639 } 13640 13641 void Sema::CheckArrayAccess(const Expr *expr) { 13642 int AllowOnePastEnd = 0; 13643 while (expr) { 13644 expr = expr->IgnoreParenImpCasts(); 13645 switch (expr->getStmtClass()) { 13646 case Stmt::ArraySubscriptExprClass: { 13647 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13648 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13649 AllowOnePastEnd > 0); 13650 expr = ASE->getBase(); 13651 break; 13652 } 13653 case Stmt::MemberExprClass: { 13654 expr = cast<MemberExpr>(expr)->getBase(); 13655 break; 13656 } 13657 case Stmt::OMPArraySectionExprClass: { 13658 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13659 if (ASE->getLowerBound()) 13660 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13661 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13662 return; 13663 } 13664 case Stmt::UnaryOperatorClass: { 13665 // Only unwrap the * and & unary operators 13666 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13667 expr = UO->getSubExpr(); 13668 switch (UO->getOpcode()) { 13669 case UO_AddrOf: 13670 AllowOnePastEnd++; 13671 break; 13672 case UO_Deref: 13673 AllowOnePastEnd--; 13674 break; 13675 default: 13676 return; 13677 } 13678 break; 13679 } 13680 case Stmt::ConditionalOperatorClass: { 13681 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13682 if (const Expr *lhs = cond->getLHS()) 13683 CheckArrayAccess(lhs); 13684 if (const Expr *rhs = cond->getRHS()) 13685 CheckArrayAccess(rhs); 13686 return; 13687 } 13688 case Stmt::CXXOperatorCallExprClass: { 13689 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13690 for (const auto *Arg : OCE->arguments()) 13691 CheckArrayAccess(Arg); 13692 return; 13693 } 13694 default: 13695 return; 13696 } 13697 } 13698 } 13699 13700 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13701 13702 namespace { 13703 13704 struct RetainCycleOwner { 13705 VarDecl *Variable = nullptr; 13706 SourceRange Range; 13707 SourceLocation Loc; 13708 bool Indirect = false; 13709 13710 RetainCycleOwner() = default; 13711 13712 void setLocsFrom(Expr *e) { 13713 Loc = e->getExprLoc(); 13714 Range = e->getSourceRange(); 13715 } 13716 }; 13717 13718 } // namespace 13719 13720 /// Consider whether capturing the given variable can possibly lead to 13721 /// a retain cycle. 13722 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13723 // In ARC, it's captured strongly iff the variable has __strong 13724 // lifetime. In MRR, it's captured strongly if the variable is 13725 // __block and has an appropriate type. 13726 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13727 return false; 13728 13729 owner.Variable = var; 13730 if (ref) 13731 owner.setLocsFrom(ref); 13732 return true; 13733 } 13734 13735 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13736 while (true) { 13737 e = e->IgnoreParens(); 13738 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13739 switch (cast->getCastKind()) { 13740 case CK_BitCast: 13741 case CK_LValueBitCast: 13742 case CK_LValueToRValue: 13743 case CK_ARCReclaimReturnedObject: 13744 e = cast->getSubExpr(); 13745 continue; 13746 13747 default: 13748 return false; 13749 } 13750 } 13751 13752 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13753 ObjCIvarDecl *ivar = ref->getDecl(); 13754 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13755 return false; 13756 13757 // Try to find a retain cycle in the base. 13758 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13759 return false; 13760 13761 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13762 owner.Indirect = true; 13763 return true; 13764 } 13765 13766 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13767 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13768 if (!var) return false; 13769 return considerVariable(var, ref, owner); 13770 } 13771 13772 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13773 if (member->isArrow()) return false; 13774 13775 // Don't count this as an indirect ownership. 13776 e = member->getBase(); 13777 continue; 13778 } 13779 13780 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13781 // Only pay attention to pseudo-objects on property references. 13782 ObjCPropertyRefExpr *pre 13783 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13784 ->IgnoreParens()); 13785 if (!pre) return false; 13786 if (pre->isImplicitProperty()) return false; 13787 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13788 if (!property->isRetaining() && 13789 !(property->getPropertyIvarDecl() && 13790 property->getPropertyIvarDecl()->getType() 13791 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13792 return false; 13793 13794 owner.Indirect = true; 13795 if (pre->isSuperReceiver()) { 13796 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13797 if (!owner.Variable) 13798 return false; 13799 owner.Loc = pre->getLocation(); 13800 owner.Range = pre->getSourceRange(); 13801 return true; 13802 } 13803 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13804 ->getSourceExpr()); 13805 continue; 13806 } 13807 13808 // Array ivars? 13809 13810 return false; 13811 } 13812 } 13813 13814 namespace { 13815 13816 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13817 ASTContext &Context; 13818 VarDecl *Variable; 13819 Expr *Capturer = nullptr; 13820 bool VarWillBeReased = false; 13821 13822 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13823 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13824 Context(Context), Variable(variable) {} 13825 13826 void VisitDeclRefExpr(DeclRefExpr *ref) { 13827 if (ref->getDecl() == Variable && !Capturer) 13828 Capturer = ref; 13829 } 13830 13831 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13832 if (Capturer) return; 13833 Visit(ref->getBase()); 13834 if (Capturer && ref->isFreeIvar()) 13835 Capturer = ref; 13836 } 13837 13838 void VisitBlockExpr(BlockExpr *block) { 13839 // Look inside nested blocks 13840 if (block->getBlockDecl()->capturesVariable(Variable)) 13841 Visit(block->getBlockDecl()->getBody()); 13842 } 13843 13844 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13845 if (Capturer) return; 13846 if (OVE->getSourceExpr()) 13847 Visit(OVE->getSourceExpr()); 13848 } 13849 13850 void VisitBinaryOperator(BinaryOperator *BinOp) { 13851 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13852 return; 13853 Expr *LHS = BinOp->getLHS(); 13854 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13855 if (DRE->getDecl() != Variable) 13856 return; 13857 if (Expr *RHS = BinOp->getRHS()) { 13858 RHS = RHS->IgnoreParenCasts(); 13859 llvm::APSInt Value; 13860 VarWillBeReased = 13861 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13862 } 13863 } 13864 } 13865 }; 13866 13867 } // namespace 13868 13869 /// Check whether the given argument is a block which captures a 13870 /// variable. 13871 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13872 assert(owner.Variable && owner.Loc.isValid()); 13873 13874 e = e->IgnoreParenCasts(); 13875 13876 // Look through [^{...} copy] and Block_copy(^{...}). 13877 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13878 Selector Cmd = ME->getSelector(); 13879 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13880 e = ME->getInstanceReceiver(); 13881 if (!e) 13882 return nullptr; 13883 e = e->IgnoreParenCasts(); 13884 } 13885 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13886 if (CE->getNumArgs() == 1) { 13887 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13888 if (Fn) { 13889 const IdentifierInfo *FnI = Fn->getIdentifier(); 13890 if (FnI && FnI->isStr("_Block_copy")) { 13891 e = CE->getArg(0)->IgnoreParenCasts(); 13892 } 13893 } 13894 } 13895 } 13896 13897 BlockExpr *block = dyn_cast<BlockExpr>(e); 13898 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13899 return nullptr; 13900 13901 FindCaptureVisitor visitor(S.Context, owner.Variable); 13902 visitor.Visit(block->getBlockDecl()->getBody()); 13903 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13904 } 13905 13906 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13907 RetainCycleOwner &owner) { 13908 assert(capturer); 13909 assert(owner.Variable && owner.Loc.isValid()); 13910 13911 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13912 << owner.Variable << capturer->getSourceRange(); 13913 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13914 << owner.Indirect << owner.Range; 13915 } 13916 13917 /// Check for a keyword selector that starts with the word 'add' or 13918 /// 'set'. 13919 static bool isSetterLikeSelector(Selector sel) { 13920 if (sel.isUnarySelector()) return false; 13921 13922 StringRef str = sel.getNameForSlot(0); 13923 while (!str.empty() && str.front() == '_') str = str.substr(1); 13924 if (str.startswith("set")) 13925 str = str.substr(3); 13926 else if (str.startswith("add")) { 13927 // Specially whitelist 'addOperationWithBlock:'. 13928 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13929 return false; 13930 str = str.substr(3); 13931 } 13932 else 13933 return false; 13934 13935 if (str.empty()) return true; 13936 return !isLowercase(str.front()); 13937 } 13938 13939 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13940 ObjCMessageExpr *Message) { 13941 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13942 Message->getReceiverInterface(), 13943 NSAPI::ClassId_NSMutableArray); 13944 if (!IsMutableArray) { 13945 return None; 13946 } 13947 13948 Selector Sel = Message->getSelector(); 13949 13950 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13951 S.NSAPIObj->getNSArrayMethodKind(Sel); 13952 if (!MKOpt) { 13953 return None; 13954 } 13955 13956 NSAPI::NSArrayMethodKind MK = *MKOpt; 13957 13958 switch (MK) { 13959 case NSAPI::NSMutableArr_addObject: 13960 case NSAPI::NSMutableArr_insertObjectAtIndex: 13961 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13962 return 0; 13963 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13964 return 1; 13965 13966 default: 13967 return None; 13968 } 13969 13970 return None; 13971 } 13972 13973 static 13974 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13975 ObjCMessageExpr *Message) { 13976 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13977 Message->getReceiverInterface(), 13978 NSAPI::ClassId_NSMutableDictionary); 13979 if (!IsMutableDictionary) { 13980 return None; 13981 } 13982 13983 Selector Sel = Message->getSelector(); 13984 13985 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13986 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13987 if (!MKOpt) { 13988 return None; 13989 } 13990 13991 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13992 13993 switch (MK) { 13994 case NSAPI::NSMutableDict_setObjectForKey: 13995 case NSAPI::NSMutableDict_setValueForKey: 13996 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13997 return 0; 13998 13999 default: 14000 return None; 14001 } 14002 14003 return None; 14004 } 14005 14006 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14007 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14008 Message->getReceiverInterface(), 14009 NSAPI::ClassId_NSMutableSet); 14010 14011 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14012 Message->getReceiverInterface(), 14013 NSAPI::ClassId_NSMutableOrderedSet); 14014 if (!IsMutableSet && !IsMutableOrderedSet) { 14015 return None; 14016 } 14017 14018 Selector Sel = Message->getSelector(); 14019 14020 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14021 if (!MKOpt) { 14022 return None; 14023 } 14024 14025 NSAPI::NSSetMethodKind MK = *MKOpt; 14026 14027 switch (MK) { 14028 case NSAPI::NSMutableSet_addObject: 14029 case NSAPI::NSOrderedSet_setObjectAtIndex: 14030 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14031 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14032 return 0; 14033 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14034 return 1; 14035 } 14036 14037 return None; 14038 } 14039 14040 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14041 if (!Message->isInstanceMessage()) { 14042 return; 14043 } 14044 14045 Optional<int> ArgOpt; 14046 14047 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14048 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14049 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14050 return; 14051 } 14052 14053 int ArgIndex = *ArgOpt; 14054 14055 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14056 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14057 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14058 } 14059 14060 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14061 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14062 if (ArgRE->isObjCSelfExpr()) { 14063 Diag(Message->getSourceRange().getBegin(), 14064 diag::warn_objc_circular_container) 14065 << ArgRE->getDecl() << StringRef("'super'"); 14066 } 14067 } 14068 } else { 14069 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14070 14071 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14072 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14073 } 14074 14075 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14076 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14077 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14078 ValueDecl *Decl = ReceiverRE->getDecl(); 14079 Diag(Message->getSourceRange().getBegin(), 14080 diag::warn_objc_circular_container) 14081 << Decl << Decl; 14082 if (!ArgRE->isObjCSelfExpr()) { 14083 Diag(Decl->getLocation(), 14084 diag::note_objc_circular_container_declared_here) 14085 << Decl; 14086 } 14087 } 14088 } 14089 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14090 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14091 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14092 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14093 Diag(Message->getSourceRange().getBegin(), 14094 diag::warn_objc_circular_container) 14095 << Decl << Decl; 14096 Diag(Decl->getLocation(), 14097 diag::note_objc_circular_container_declared_here) 14098 << Decl; 14099 } 14100 } 14101 } 14102 } 14103 } 14104 14105 /// Check a message send to see if it's likely to cause a retain cycle. 14106 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14107 // Only check instance methods whose selector looks like a setter. 14108 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14109 return; 14110 14111 // Try to find a variable that the receiver is strongly owned by. 14112 RetainCycleOwner owner; 14113 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14114 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14115 return; 14116 } else { 14117 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14118 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14119 owner.Loc = msg->getSuperLoc(); 14120 owner.Range = msg->getSuperLoc(); 14121 } 14122 14123 // Check whether the receiver is captured by any of the arguments. 14124 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14125 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14126 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14127 // noescape blocks should not be retained by the method. 14128 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14129 continue; 14130 return diagnoseRetainCycle(*this, capturer, owner); 14131 } 14132 } 14133 } 14134 14135 /// Check a property assign to see if it's likely to cause a retain cycle. 14136 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14137 RetainCycleOwner owner; 14138 if (!findRetainCycleOwner(*this, receiver, owner)) 14139 return; 14140 14141 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14142 diagnoseRetainCycle(*this, capturer, owner); 14143 } 14144 14145 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14146 RetainCycleOwner Owner; 14147 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14148 return; 14149 14150 // Because we don't have an expression for the variable, we have to set the 14151 // location explicitly here. 14152 Owner.Loc = Var->getLocation(); 14153 Owner.Range = Var->getSourceRange(); 14154 14155 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14156 diagnoseRetainCycle(*this, Capturer, Owner); 14157 } 14158 14159 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14160 Expr *RHS, bool isProperty) { 14161 // Check if RHS is an Objective-C object literal, which also can get 14162 // immediately zapped in a weak reference. Note that we explicitly 14163 // allow ObjCStringLiterals, since those are designed to never really die. 14164 RHS = RHS->IgnoreParenImpCasts(); 14165 14166 // This enum needs to match with the 'select' in 14167 // warn_objc_arc_literal_assign (off-by-1). 14168 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14169 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14170 return false; 14171 14172 S.Diag(Loc, diag::warn_arc_literal_assign) 14173 << (unsigned) Kind 14174 << (isProperty ? 0 : 1) 14175 << RHS->getSourceRange(); 14176 14177 return true; 14178 } 14179 14180 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14181 Qualifiers::ObjCLifetime LT, 14182 Expr *RHS, bool isProperty) { 14183 // Strip off any implicit cast added to get to the one ARC-specific. 14184 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14185 if (cast->getCastKind() == CK_ARCConsumeObject) { 14186 S.Diag(Loc, diag::warn_arc_retained_assign) 14187 << (LT == Qualifiers::OCL_ExplicitNone) 14188 << (isProperty ? 0 : 1) 14189 << RHS->getSourceRange(); 14190 return true; 14191 } 14192 RHS = cast->getSubExpr(); 14193 } 14194 14195 if (LT == Qualifiers::OCL_Weak && 14196 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14197 return true; 14198 14199 return false; 14200 } 14201 14202 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14203 QualType LHS, Expr *RHS) { 14204 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14205 14206 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14207 return false; 14208 14209 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14210 return true; 14211 14212 return false; 14213 } 14214 14215 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14216 Expr *LHS, Expr *RHS) { 14217 QualType LHSType; 14218 // PropertyRef on LHS type need be directly obtained from 14219 // its declaration as it has a PseudoType. 14220 ObjCPropertyRefExpr *PRE 14221 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14222 if (PRE && !PRE->isImplicitProperty()) { 14223 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14224 if (PD) 14225 LHSType = PD->getType(); 14226 } 14227 14228 if (LHSType.isNull()) 14229 LHSType = LHS->getType(); 14230 14231 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14232 14233 if (LT == Qualifiers::OCL_Weak) { 14234 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14235 getCurFunction()->markSafeWeakUse(LHS); 14236 } 14237 14238 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14239 return; 14240 14241 // FIXME. Check for other life times. 14242 if (LT != Qualifiers::OCL_None) 14243 return; 14244 14245 if (PRE) { 14246 if (PRE->isImplicitProperty()) 14247 return; 14248 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14249 if (!PD) 14250 return; 14251 14252 unsigned Attributes = PD->getPropertyAttributes(); 14253 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14254 // when 'assign' attribute was not explicitly specified 14255 // by user, ignore it and rely on property type itself 14256 // for lifetime info. 14257 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14258 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 14259 LHSType->isObjCRetainableType()) 14260 return; 14261 14262 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14263 if (cast->getCastKind() == CK_ARCConsumeObject) { 14264 Diag(Loc, diag::warn_arc_retained_property_assign) 14265 << RHS->getSourceRange(); 14266 return; 14267 } 14268 RHS = cast->getSubExpr(); 14269 } 14270 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 14271 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14272 return; 14273 } 14274 } 14275 } 14276 14277 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14278 14279 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14280 SourceLocation StmtLoc, 14281 const NullStmt *Body) { 14282 // Do not warn if the body is a macro that expands to nothing, e.g: 14283 // 14284 // #define CALL(x) 14285 // if (condition) 14286 // CALL(0); 14287 if (Body->hasLeadingEmptyMacro()) 14288 return false; 14289 14290 // Get line numbers of statement and body. 14291 bool StmtLineInvalid; 14292 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14293 &StmtLineInvalid); 14294 if (StmtLineInvalid) 14295 return false; 14296 14297 bool BodyLineInvalid; 14298 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14299 &BodyLineInvalid); 14300 if (BodyLineInvalid) 14301 return false; 14302 14303 // Warn if null statement and body are on the same line. 14304 if (StmtLine != BodyLine) 14305 return false; 14306 14307 return true; 14308 } 14309 14310 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14311 const Stmt *Body, 14312 unsigned DiagID) { 14313 // Since this is a syntactic check, don't emit diagnostic for template 14314 // instantiations, this just adds noise. 14315 if (CurrentInstantiationScope) 14316 return; 14317 14318 // The body should be a null statement. 14319 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14320 if (!NBody) 14321 return; 14322 14323 // Do the usual checks. 14324 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14325 return; 14326 14327 Diag(NBody->getSemiLoc(), DiagID); 14328 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14329 } 14330 14331 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14332 const Stmt *PossibleBody) { 14333 assert(!CurrentInstantiationScope); // Ensured by caller 14334 14335 SourceLocation StmtLoc; 14336 const Stmt *Body; 14337 unsigned DiagID; 14338 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14339 StmtLoc = FS->getRParenLoc(); 14340 Body = FS->getBody(); 14341 DiagID = diag::warn_empty_for_body; 14342 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14343 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14344 Body = WS->getBody(); 14345 DiagID = diag::warn_empty_while_body; 14346 } else 14347 return; // Neither `for' nor `while'. 14348 14349 // The body should be a null statement. 14350 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14351 if (!NBody) 14352 return; 14353 14354 // Skip expensive checks if diagnostic is disabled. 14355 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14356 return; 14357 14358 // Do the usual checks. 14359 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14360 return; 14361 14362 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14363 // noise level low, emit diagnostics only if for/while is followed by a 14364 // CompoundStmt, e.g.: 14365 // for (int i = 0; i < n; i++); 14366 // { 14367 // a(i); 14368 // } 14369 // or if for/while is followed by a statement with more indentation 14370 // than for/while itself: 14371 // for (int i = 0; i < n; i++); 14372 // a(i); 14373 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14374 if (!ProbableTypo) { 14375 bool BodyColInvalid; 14376 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14377 PossibleBody->getBeginLoc(), &BodyColInvalid); 14378 if (BodyColInvalid) 14379 return; 14380 14381 bool StmtColInvalid; 14382 unsigned StmtCol = 14383 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14384 if (StmtColInvalid) 14385 return; 14386 14387 if (BodyCol > StmtCol) 14388 ProbableTypo = true; 14389 } 14390 14391 if (ProbableTypo) { 14392 Diag(NBody->getSemiLoc(), DiagID); 14393 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14394 } 14395 } 14396 14397 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14398 14399 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14400 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14401 SourceLocation OpLoc) { 14402 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14403 return; 14404 14405 if (inTemplateInstantiation()) 14406 return; 14407 14408 // Strip parens and casts away. 14409 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14410 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14411 14412 // Check for a call expression 14413 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14414 if (!CE || CE->getNumArgs() != 1) 14415 return; 14416 14417 // Check for a call to std::move 14418 if (!CE->isCallToStdMove()) 14419 return; 14420 14421 // Get argument from std::move 14422 RHSExpr = CE->getArg(0); 14423 14424 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14425 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14426 14427 // Two DeclRefExpr's, check that the decls are the same. 14428 if (LHSDeclRef && RHSDeclRef) { 14429 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14430 return; 14431 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14432 RHSDeclRef->getDecl()->getCanonicalDecl()) 14433 return; 14434 14435 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14436 << LHSExpr->getSourceRange() 14437 << RHSExpr->getSourceRange(); 14438 return; 14439 } 14440 14441 // Member variables require a different approach to check for self moves. 14442 // MemberExpr's are the same if every nested MemberExpr refers to the same 14443 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14444 // the base Expr's are CXXThisExpr's. 14445 const Expr *LHSBase = LHSExpr; 14446 const Expr *RHSBase = RHSExpr; 14447 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14448 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14449 if (!LHSME || !RHSME) 14450 return; 14451 14452 while (LHSME && RHSME) { 14453 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14454 RHSME->getMemberDecl()->getCanonicalDecl()) 14455 return; 14456 14457 LHSBase = LHSME->getBase(); 14458 RHSBase = RHSME->getBase(); 14459 LHSME = dyn_cast<MemberExpr>(LHSBase); 14460 RHSME = dyn_cast<MemberExpr>(RHSBase); 14461 } 14462 14463 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14464 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14465 if (LHSDeclRef && RHSDeclRef) { 14466 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14467 return; 14468 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14469 RHSDeclRef->getDecl()->getCanonicalDecl()) 14470 return; 14471 14472 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14473 << LHSExpr->getSourceRange() 14474 << RHSExpr->getSourceRange(); 14475 return; 14476 } 14477 14478 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14479 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14480 << LHSExpr->getSourceRange() 14481 << RHSExpr->getSourceRange(); 14482 } 14483 14484 //===--- Layout compatibility ----------------------------------------------// 14485 14486 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14487 14488 /// Check if two enumeration types are layout-compatible. 14489 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14490 // C++11 [dcl.enum] p8: 14491 // Two enumeration types are layout-compatible if they have the same 14492 // underlying type. 14493 return ED1->isComplete() && ED2->isComplete() && 14494 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14495 } 14496 14497 /// Check if two fields are layout-compatible. 14498 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14499 FieldDecl *Field2) { 14500 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14501 return false; 14502 14503 if (Field1->isBitField() != Field2->isBitField()) 14504 return false; 14505 14506 if (Field1->isBitField()) { 14507 // Make sure that the bit-fields are the same length. 14508 unsigned Bits1 = Field1->getBitWidthValue(C); 14509 unsigned Bits2 = Field2->getBitWidthValue(C); 14510 14511 if (Bits1 != Bits2) 14512 return false; 14513 } 14514 14515 return true; 14516 } 14517 14518 /// Check if two standard-layout structs are layout-compatible. 14519 /// (C++11 [class.mem] p17) 14520 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14521 RecordDecl *RD2) { 14522 // If both records are C++ classes, check that base classes match. 14523 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14524 // If one of records is a CXXRecordDecl we are in C++ mode, 14525 // thus the other one is a CXXRecordDecl, too. 14526 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14527 // Check number of base classes. 14528 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14529 return false; 14530 14531 // Check the base classes. 14532 for (CXXRecordDecl::base_class_const_iterator 14533 Base1 = D1CXX->bases_begin(), 14534 BaseEnd1 = D1CXX->bases_end(), 14535 Base2 = D2CXX->bases_begin(); 14536 Base1 != BaseEnd1; 14537 ++Base1, ++Base2) { 14538 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14539 return false; 14540 } 14541 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14542 // If only RD2 is a C++ class, it should have zero base classes. 14543 if (D2CXX->getNumBases() > 0) 14544 return false; 14545 } 14546 14547 // Check the fields. 14548 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14549 Field2End = RD2->field_end(), 14550 Field1 = RD1->field_begin(), 14551 Field1End = RD1->field_end(); 14552 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14553 if (!isLayoutCompatible(C, *Field1, *Field2)) 14554 return false; 14555 } 14556 if (Field1 != Field1End || Field2 != Field2End) 14557 return false; 14558 14559 return true; 14560 } 14561 14562 /// Check if two standard-layout unions are layout-compatible. 14563 /// (C++11 [class.mem] p18) 14564 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14565 RecordDecl *RD2) { 14566 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14567 for (auto *Field2 : RD2->fields()) 14568 UnmatchedFields.insert(Field2); 14569 14570 for (auto *Field1 : RD1->fields()) { 14571 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14572 I = UnmatchedFields.begin(), 14573 E = UnmatchedFields.end(); 14574 14575 for ( ; I != E; ++I) { 14576 if (isLayoutCompatible(C, Field1, *I)) { 14577 bool Result = UnmatchedFields.erase(*I); 14578 (void) Result; 14579 assert(Result); 14580 break; 14581 } 14582 } 14583 if (I == E) 14584 return false; 14585 } 14586 14587 return UnmatchedFields.empty(); 14588 } 14589 14590 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14591 RecordDecl *RD2) { 14592 if (RD1->isUnion() != RD2->isUnion()) 14593 return false; 14594 14595 if (RD1->isUnion()) 14596 return isLayoutCompatibleUnion(C, RD1, RD2); 14597 else 14598 return isLayoutCompatibleStruct(C, RD1, RD2); 14599 } 14600 14601 /// Check if two types are layout-compatible in C++11 sense. 14602 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14603 if (T1.isNull() || T2.isNull()) 14604 return false; 14605 14606 // C++11 [basic.types] p11: 14607 // If two types T1 and T2 are the same type, then T1 and T2 are 14608 // layout-compatible types. 14609 if (C.hasSameType(T1, T2)) 14610 return true; 14611 14612 T1 = T1.getCanonicalType().getUnqualifiedType(); 14613 T2 = T2.getCanonicalType().getUnqualifiedType(); 14614 14615 const Type::TypeClass TC1 = T1->getTypeClass(); 14616 const Type::TypeClass TC2 = T2->getTypeClass(); 14617 14618 if (TC1 != TC2) 14619 return false; 14620 14621 if (TC1 == Type::Enum) { 14622 return isLayoutCompatible(C, 14623 cast<EnumType>(T1)->getDecl(), 14624 cast<EnumType>(T2)->getDecl()); 14625 } else if (TC1 == Type::Record) { 14626 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14627 return false; 14628 14629 return isLayoutCompatible(C, 14630 cast<RecordType>(T1)->getDecl(), 14631 cast<RecordType>(T2)->getDecl()); 14632 } 14633 14634 return false; 14635 } 14636 14637 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14638 14639 /// Given a type tag expression find the type tag itself. 14640 /// 14641 /// \param TypeExpr Type tag expression, as it appears in user's code. 14642 /// 14643 /// \param VD Declaration of an identifier that appears in a type tag. 14644 /// 14645 /// \param MagicValue Type tag magic value. 14646 /// 14647 /// \param isConstantEvaluated wether the evalaution should be performed in 14648 14649 /// constant context. 14650 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14651 const ValueDecl **VD, uint64_t *MagicValue, 14652 bool isConstantEvaluated) { 14653 while(true) { 14654 if (!TypeExpr) 14655 return false; 14656 14657 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14658 14659 switch (TypeExpr->getStmtClass()) { 14660 case Stmt::UnaryOperatorClass: { 14661 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14662 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14663 TypeExpr = UO->getSubExpr(); 14664 continue; 14665 } 14666 return false; 14667 } 14668 14669 case Stmt::DeclRefExprClass: { 14670 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14671 *VD = DRE->getDecl(); 14672 return true; 14673 } 14674 14675 case Stmt::IntegerLiteralClass: { 14676 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14677 llvm::APInt MagicValueAPInt = IL->getValue(); 14678 if (MagicValueAPInt.getActiveBits() <= 64) { 14679 *MagicValue = MagicValueAPInt.getZExtValue(); 14680 return true; 14681 } else 14682 return false; 14683 } 14684 14685 case Stmt::BinaryConditionalOperatorClass: 14686 case Stmt::ConditionalOperatorClass: { 14687 const AbstractConditionalOperator *ACO = 14688 cast<AbstractConditionalOperator>(TypeExpr); 14689 bool Result; 14690 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14691 isConstantEvaluated)) { 14692 if (Result) 14693 TypeExpr = ACO->getTrueExpr(); 14694 else 14695 TypeExpr = ACO->getFalseExpr(); 14696 continue; 14697 } 14698 return false; 14699 } 14700 14701 case Stmt::BinaryOperatorClass: { 14702 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14703 if (BO->getOpcode() == BO_Comma) { 14704 TypeExpr = BO->getRHS(); 14705 continue; 14706 } 14707 return false; 14708 } 14709 14710 default: 14711 return false; 14712 } 14713 } 14714 } 14715 14716 /// Retrieve the C type corresponding to type tag TypeExpr. 14717 /// 14718 /// \param TypeExpr Expression that specifies a type tag. 14719 /// 14720 /// \param MagicValues Registered magic values. 14721 /// 14722 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14723 /// kind. 14724 /// 14725 /// \param TypeInfo Information about the corresponding C type. 14726 /// 14727 /// \param isConstantEvaluated wether the evalaution should be performed in 14728 /// constant context. 14729 /// 14730 /// \returns true if the corresponding C type was found. 14731 static bool GetMatchingCType( 14732 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14733 const ASTContext &Ctx, 14734 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14735 *MagicValues, 14736 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14737 bool isConstantEvaluated) { 14738 FoundWrongKind = false; 14739 14740 // Variable declaration that has type_tag_for_datatype attribute. 14741 const ValueDecl *VD = nullptr; 14742 14743 uint64_t MagicValue; 14744 14745 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14746 return false; 14747 14748 if (VD) { 14749 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14750 if (I->getArgumentKind() != ArgumentKind) { 14751 FoundWrongKind = true; 14752 return false; 14753 } 14754 TypeInfo.Type = I->getMatchingCType(); 14755 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14756 TypeInfo.MustBeNull = I->getMustBeNull(); 14757 return true; 14758 } 14759 return false; 14760 } 14761 14762 if (!MagicValues) 14763 return false; 14764 14765 llvm::DenseMap<Sema::TypeTagMagicValue, 14766 Sema::TypeTagData>::const_iterator I = 14767 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14768 if (I == MagicValues->end()) 14769 return false; 14770 14771 TypeInfo = I->second; 14772 return true; 14773 } 14774 14775 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14776 uint64_t MagicValue, QualType Type, 14777 bool LayoutCompatible, 14778 bool MustBeNull) { 14779 if (!TypeTagForDatatypeMagicValues) 14780 TypeTagForDatatypeMagicValues.reset( 14781 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14782 14783 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14784 (*TypeTagForDatatypeMagicValues)[Magic] = 14785 TypeTagData(Type, LayoutCompatible, MustBeNull); 14786 } 14787 14788 static bool IsSameCharType(QualType T1, QualType T2) { 14789 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14790 if (!BT1) 14791 return false; 14792 14793 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14794 if (!BT2) 14795 return false; 14796 14797 BuiltinType::Kind T1Kind = BT1->getKind(); 14798 BuiltinType::Kind T2Kind = BT2->getKind(); 14799 14800 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14801 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14802 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14803 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14804 } 14805 14806 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14807 const ArrayRef<const Expr *> ExprArgs, 14808 SourceLocation CallSiteLoc) { 14809 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14810 bool IsPointerAttr = Attr->getIsPointer(); 14811 14812 // Retrieve the argument representing the 'type_tag'. 14813 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14814 if (TypeTagIdxAST >= ExprArgs.size()) { 14815 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14816 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14817 return; 14818 } 14819 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14820 bool FoundWrongKind; 14821 TypeTagData TypeInfo; 14822 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14823 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14824 TypeInfo, isConstantEvaluated())) { 14825 if (FoundWrongKind) 14826 Diag(TypeTagExpr->getExprLoc(), 14827 diag::warn_type_tag_for_datatype_wrong_kind) 14828 << TypeTagExpr->getSourceRange(); 14829 return; 14830 } 14831 14832 // Retrieve the argument representing the 'arg_idx'. 14833 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14834 if (ArgumentIdxAST >= ExprArgs.size()) { 14835 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14836 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14837 return; 14838 } 14839 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14840 if (IsPointerAttr) { 14841 // Skip implicit cast of pointer to `void *' (as a function argument). 14842 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14843 if (ICE->getType()->isVoidPointerType() && 14844 ICE->getCastKind() == CK_BitCast) 14845 ArgumentExpr = ICE->getSubExpr(); 14846 } 14847 QualType ArgumentType = ArgumentExpr->getType(); 14848 14849 // Passing a `void*' pointer shouldn't trigger a warning. 14850 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14851 return; 14852 14853 if (TypeInfo.MustBeNull) { 14854 // Type tag with matching void type requires a null pointer. 14855 if (!ArgumentExpr->isNullPointerConstant(Context, 14856 Expr::NPC_ValueDependentIsNotNull)) { 14857 Diag(ArgumentExpr->getExprLoc(), 14858 diag::warn_type_safety_null_pointer_required) 14859 << ArgumentKind->getName() 14860 << ArgumentExpr->getSourceRange() 14861 << TypeTagExpr->getSourceRange(); 14862 } 14863 return; 14864 } 14865 14866 QualType RequiredType = TypeInfo.Type; 14867 if (IsPointerAttr) 14868 RequiredType = Context.getPointerType(RequiredType); 14869 14870 bool mismatch = false; 14871 if (!TypeInfo.LayoutCompatible) { 14872 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14873 14874 // C++11 [basic.fundamental] p1: 14875 // Plain char, signed char, and unsigned char are three distinct types. 14876 // 14877 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14878 // char' depending on the current char signedness mode. 14879 if (mismatch) 14880 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14881 RequiredType->getPointeeType())) || 14882 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14883 mismatch = false; 14884 } else 14885 if (IsPointerAttr) 14886 mismatch = !isLayoutCompatible(Context, 14887 ArgumentType->getPointeeType(), 14888 RequiredType->getPointeeType()); 14889 else 14890 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14891 14892 if (mismatch) 14893 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14894 << ArgumentType << ArgumentKind 14895 << TypeInfo.LayoutCompatible << RequiredType 14896 << ArgumentExpr->getSourceRange() 14897 << TypeTagExpr->getSourceRange(); 14898 } 14899 14900 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14901 CharUnits Alignment) { 14902 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14903 } 14904 14905 void Sema::DiagnoseMisalignedMembers() { 14906 for (MisalignedMember &m : MisalignedMembers) { 14907 const NamedDecl *ND = m.RD; 14908 if (ND->getName().empty()) { 14909 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14910 ND = TD; 14911 } 14912 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14913 << m.MD << ND << m.E->getSourceRange(); 14914 } 14915 MisalignedMembers.clear(); 14916 } 14917 14918 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14919 E = E->IgnoreParens(); 14920 if (!T->isPointerType() && !T->isIntegerType()) 14921 return; 14922 if (isa<UnaryOperator>(E) && 14923 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14924 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14925 if (isa<MemberExpr>(Op)) { 14926 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14927 if (MA != MisalignedMembers.end() && 14928 (T->isIntegerType() || 14929 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14930 Context.getTypeAlignInChars( 14931 T->getPointeeType()) <= MA->Alignment)))) 14932 MisalignedMembers.erase(MA); 14933 } 14934 } 14935 } 14936 14937 void Sema::RefersToMemberWithReducedAlignment( 14938 Expr *E, 14939 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14940 Action) { 14941 const auto *ME = dyn_cast<MemberExpr>(E); 14942 if (!ME) 14943 return; 14944 14945 // No need to check expressions with an __unaligned-qualified type. 14946 if (E->getType().getQualifiers().hasUnaligned()) 14947 return; 14948 14949 // For a chain of MemberExpr like "a.b.c.d" this list 14950 // will keep FieldDecl's like [d, c, b]. 14951 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14952 const MemberExpr *TopME = nullptr; 14953 bool AnyIsPacked = false; 14954 do { 14955 QualType BaseType = ME->getBase()->getType(); 14956 if (BaseType->isDependentType()) 14957 return; 14958 if (ME->isArrow()) 14959 BaseType = BaseType->getPointeeType(); 14960 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14961 if (RD->isInvalidDecl()) 14962 return; 14963 14964 ValueDecl *MD = ME->getMemberDecl(); 14965 auto *FD = dyn_cast<FieldDecl>(MD); 14966 // We do not care about non-data members. 14967 if (!FD || FD->isInvalidDecl()) 14968 return; 14969 14970 AnyIsPacked = 14971 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14972 ReverseMemberChain.push_back(FD); 14973 14974 TopME = ME; 14975 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14976 } while (ME); 14977 assert(TopME && "We did not compute a topmost MemberExpr!"); 14978 14979 // Not the scope of this diagnostic. 14980 if (!AnyIsPacked) 14981 return; 14982 14983 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14984 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14985 // TODO: The innermost base of the member expression may be too complicated. 14986 // For now, just disregard these cases. This is left for future 14987 // improvement. 14988 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14989 return; 14990 14991 // Alignment expected by the whole expression. 14992 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14993 14994 // No need to do anything else with this case. 14995 if (ExpectedAlignment.isOne()) 14996 return; 14997 14998 // Synthesize offset of the whole access. 14999 CharUnits Offset; 15000 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15001 I++) { 15002 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15003 } 15004 15005 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15006 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15007 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15008 15009 // The base expression of the innermost MemberExpr may give 15010 // stronger guarantees than the class containing the member. 15011 if (DRE && !TopME->isArrow()) { 15012 const ValueDecl *VD = DRE->getDecl(); 15013 if (!VD->getType()->isReferenceType()) 15014 CompleteObjectAlignment = 15015 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15016 } 15017 15018 // Check if the synthesized offset fulfills the alignment. 15019 if (Offset % ExpectedAlignment != 0 || 15020 // It may fulfill the offset it but the effective alignment may still be 15021 // lower than the expected expression alignment. 15022 CompleteObjectAlignment < ExpectedAlignment) { 15023 // If this happens, we want to determine a sensible culprit of this. 15024 // Intuitively, watching the chain of member expressions from right to 15025 // left, we start with the required alignment (as required by the field 15026 // type) but some packed attribute in that chain has reduced the alignment. 15027 // It may happen that another packed structure increases it again. But if 15028 // we are here such increase has not been enough. So pointing the first 15029 // FieldDecl that either is packed or else its RecordDecl is, 15030 // seems reasonable. 15031 FieldDecl *FD = nullptr; 15032 CharUnits Alignment; 15033 for (FieldDecl *FDI : ReverseMemberChain) { 15034 if (FDI->hasAttr<PackedAttr>() || 15035 FDI->getParent()->hasAttr<PackedAttr>()) { 15036 FD = FDI; 15037 Alignment = std::min( 15038 Context.getTypeAlignInChars(FD->getType()), 15039 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15040 break; 15041 } 15042 } 15043 assert(FD && "We did not find a packed FieldDecl!"); 15044 Action(E, FD->getParent(), FD, Alignment); 15045 } 15046 } 15047 15048 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15049 using namespace std::placeholders; 15050 15051 RefersToMemberWithReducedAlignment( 15052 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15053 _2, _3, _4)); 15054 } 15055 15056 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15057 ExprResult CallResult) { 15058 if (checkArgCount(*this, TheCall, 1)) 15059 return ExprError(); 15060 15061 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15062 if (MatrixArg.isInvalid()) 15063 return MatrixArg; 15064 Expr *Matrix = MatrixArg.get(); 15065 15066 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15067 if (!MType) { 15068 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15069 return ExprError(); 15070 } 15071 15072 // Create returned matrix type by swapping rows and columns of the argument 15073 // matrix type. 15074 QualType ResultType = Context.getConstantMatrixType( 15075 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15076 15077 // Change the return type to the type of the returned matrix. 15078 TheCall->setType(ResultType); 15079 15080 // Update call argument to use the possibly converted matrix argument. 15081 TheCall->setArg(0, Matrix); 15082 return CallResult; 15083 } 15084