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/Stmt.h" 34 #include "clang/AST/TemplateBase.h" 35 #include "clang/AST/Type.h" 36 #include "clang/AST/TypeLoc.h" 37 #include "clang/AST/UnresolvedSet.h" 38 #include "clang/Basic/AddressSpaces.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/Diagnostic.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/OpenCLOptions.h" 45 #include "clang/Basic/OperatorKinds.h" 46 #include "clang/Basic/PartialDiagnostic.h" 47 #include "clang/Basic/SourceLocation.h" 48 #include "clang/Basic/SourceManager.h" 49 #include "clang/Basic/Specifiers.h" 50 #include "clang/Basic/SyncScope.h" 51 #include "clang/Basic/TargetBuiltins.h" 52 #include "clang/Basic/TargetCXXABI.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "clang/Basic/TypeTraits.h" 55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 56 #include "clang/Sema/Initialization.h" 57 #include "clang/Sema/Lookup.h" 58 #include "clang/Sema/Ownership.h" 59 #include "clang/Sema/Scope.h" 60 #include "clang/Sema/ScopeInfo.h" 61 #include "clang/Sema/Sema.h" 62 #include "clang/Sema/SemaInternal.h" 63 #include "llvm/ADT/APFloat.h" 64 #include "llvm/ADT/APInt.h" 65 #include "llvm/ADT/APSInt.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/FoldingSet.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/SmallBitVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallString.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSwitch.h" 78 #include "llvm/ADT/Triple.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/ConvertUTF.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/Locale.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/SaveAndRestore.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <functional> 94 #include <limits> 95 #include <string> 96 #include <tuple> 97 #include <utility> 98 99 using namespace clang; 100 using namespace sema; 101 102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 103 unsigned ByteNo) const { 104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 105 Context.getTargetInfo()); 106 } 107 108 /// Checks that a call expression's argument count is the desired number. 109 /// This is useful when doing custom type-checking. Returns true on error. 110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 111 unsigned argCount = call->getNumArgs(); 112 if (argCount == desiredArgCount) return false; 113 114 if (argCount < desiredArgCount) 115 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 116 << 0 /*function call*/ << desiredArgCount << argCount 117 << call->getSourceRange(); 118 119 // Highlight all the excess arguments. 120 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 121 call->getArg(argCount - 1)->getEndLoc()); 122 123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 124 << 0 /*function call*/ << desiredArgCount << argCount 125 << call->getArg(1)->getSourceRange(); 126 } 127 128 /// Check that the first argument to __builtin_annotation is an integer 129 /// and the second argument is a non-wide string literal. 130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 131 if (checkArgCount(S, TheCall, 2)) 132 return true; 133 134 // First argument should be an integer. 135 Expr *ValArg = TheCall->getArg(0); 136 QualType Ty = ValArg->getType(); 137 if (!Ty->isIntegerType()) { 138 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 139 << ValArg->getSourceRange(); 140 return true; 141 } 142 143 // Second argument should be a constant string. 144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 146 if (!Literal || !Literal->isAscii()) { 147 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 148 << StrArg->getSourceRange(); 149 return true; 150 } 151 152 TheCall->setType(Ty); 153 return false; 154 } 155 156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 157 // We need at least one argument. 158 if (TheCall->getNumArgs() < 1) { 159 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 160 << 0 << 1 << TheCall->getNumArgs() 161 << TheCall->getCallee()->getSourceRange(); 162 return true; 163 } 164 165 // All arguments should be wide string literals. 166 for (Expr *Arg : TheCall->arguments()) { 167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 168 if (!Literal || !Literal->isWide()) { 169 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 170 << Arg->getSourceRange(); 171 return true; 172 } 173 } 174 175 return false; 176 } 177 178 /// Check that the argument to __builtin_addressof is a glvalue, and set the 179 /// result type to the corresponding pointer type. 180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 181 if (checkArgCount(S, TheCall, 1)) 182 return true; 183 184 ExprResult Arg(TheCall->getArg(0)); 185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 186 if (ResultType.isNull()) 187 return true; 188 189 TheCall->setArg(0, Arg.get()); 190 TheCall->setType(ResultType); 191 return false; 192 } 193 194 /// Check the number of arguments and set the result type to 195 /// the argument type. 196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 197 if (checkArgCount(S, TheCall, 1)) 198 return true; 199 200 TheCall->setType(TheCall->getArg(0)->getType()); 201 return false; 202 } 203 204 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 205 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 206 /// type (but not a function pointer) and that the alignment is a power-of-two. 207 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 208 if (checkArgCount(S, TheCall, 2)) 209 return true; 210 211 clang::Expr *Source = TheCall->getArg(0); 212 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 213 214 auto IsValidIntegerType = [](QualType Ty) { 215 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 216 }; 217 QualType SrcTy = Source->getType(); 218 // We should also be able to use it with arrays (but not functions!). 219 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 220 SrcTy = S.Context.getDecayedType(SrcTy); 221 } 222 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 223 SrcTy->isFunctionPointerType()) { 224 // FIXME: this is not quite the right error message since we don't allow 225 // floating point types, or member pointers. 226 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 227 << SrcTy; 228 return true; 229 } 230 231 clang::Expr *AlignOp = TheCall->getArg(1); 232 if (!IsValidIntegerType(AlignOp->getType())) { 233 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 234 << AlignOp->getType(); 235 return true; 236 } 237 Expr::EvalResult AlignResult; 238 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 239 // We can't check validity of alignment if it is type dependent. 240 if (!AlignOp->isInstantiationDependent() && 241 AlignOp->EvaluateAsInt(AlignResult, S.Context, 242 Expr::SE_AllowSideEffects)) { 243 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 244 llvm::APSInt MaxValue( 245 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 246 if (AlignValue < 1) { 247 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 248 return true; 249 } 250 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 252 << MaxValue.toString(10); 253 return true; 254 } 255 if (!AlignValue.isPowerOf2()) { 256 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 257 return true; 258 } 259 if (AlignValue == 1) { 260 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 261 << IsBooleanAlignBuiltin; 262 } 263 } 264 265 ExprResult SrcArg = S.PerformCopyInitialization( 266 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 267 SourceLocation(), Source); 268 if (SrcArg.isInvalid()) 269 return true; 270 TheCall->setArg(0, SrcArg.get()); 271 ExprResult AlignArg = 272 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 273 S.Context, AlignOp->getType(), false), 274 SourceLocation(), AlignOp); 275 if (AlignArg.isInvalid()) 276 return true; 277 TheCall->setArg(1, AlignArg.get()); 278 // For align_up/align_down, the return type is the same as the (potentially 279 // decayed) argument type including qualifiers. For is_aligned(), the result 280 // is always bool. 281 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 282 return false; 283 } 284 285 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 286 if (checkArgCount(S, TheCall, 3)) 287 return true; 288 289 // First two arguments should be integers. 290 for (unsigned I = 0; I < 2; ++I) { 291 ExprResult Arg = TheCall->getArg(I); 292 QualType Ty = Arg.get()->getType(); 293 if (!Ty->isIntegerType()) { 294 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 295 << Ty << Arg.get()->getSourceRange(); 296 return true; 297 } 298 InitializedEntity Entity = InitializedEntity::InitializeParameter( 299 S.getASTContext(), Ty, /*consume*/ false); 300 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 301 if (Arg.isInvalid()) 302 return true; 303 TheCall->setArg(I, Arg.get()); 304 } 305 306 // Third argument should be a pointer to a non-const integer. 307 // IRGen correctly handles volatile, restrict, and address spaces, and 308 // the other qualifiers aren't possible. 309 { 310 ExprResult Arg = TheCall->getArg(2); 311 QualType Ty = Arg.get()->getType(); 312 const auto *PtrTy = Ty->getAs<PointerType>(); 313 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 314 !PtrTy->getPointeeType().isConstQualified())) { 315 S.Diag(Arg.get()->getBeginLoc(), 316 diag::err_overflow_builtin_must_be_ptr_int) 317 << Ty << Arg.get()->getSourceRange(); 318 return true; 319 } 320 InitializedEntity Entity = InitializedEntity::InitializeParameter( 321 S.getASTContext(), Ty, /*consume*/ false); 322 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 323 if (Arg.isInvalid()) 324 return true; 325 TheCall->setArg(2, Arg.get()); 326 } 327 return false; 328 } 329 330 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 331 if (checkArgCount(S, BuiltinCall, 2)) 332 return true; 333 334 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 335 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 336 Expr *Call = BuiltinCall->getArg(0); 337 Expr *Chain = BuiltinCall->getArg(1); 338 339 if (Call->getStmtClass() != Stmt::CallExprClass) { 340 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 341 << Call->getSourceRange(); 342 return true; 343 } 344 345 auto CE = cast<CallExpr>(Call); 346 if (CE->getCallee()->getType()->isBlockPointerType()) { 347 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 348 << Call->getSourceRange(); 349 return true; 350 } 351 352 const Decl *TargetDecl = CE->getCalleeDecl(); 353 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 354 if (FD->getBuiltinID()) { 355 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 356 << Call->getSourceRange(); 357 return true; 358 } 359 360 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 361 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 362 << Call->getSourceRange(); 363 return true; 364 } 365 366 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 367 if (ChainResult.isInvalid()) 368 return true; 369 if (!ChainResult.get()->getType()->isPointerType()) { 370 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 371 << Chain->getSourceRange(); 372 return true; 373 } 374 375 QualType ReturnTy = CE->getCallReturnType(S.Context); 376 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 377 QualType BuiltinTy = S.Context.getFunctionType( 378 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 379 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 380 381 Builtin = 382 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 383 384 BuiltinCall->setType(CE->getType()); 385 BuiltinCall->setValueKind(CE->getValueKind()); 386 BuiltinCall->setObjectKind(CE->getObjectKind()); 387 BuiltinCall->setCallee(Builtin); 388 BuiltinCall->setArg(1, ChainResult.get()); 389 390 return false; 391 } 392 393 namespace { 394 395 class EstimateSizeFormatHandler 396 : public analyze_format_string::FormatStringHandler { 397 size_t Size; 398 399 public: 400 EstimateSizeFormatHandler(StringRef Format) 401 : Size(std::min(Format.find(0), Format.size()) + 402 1 /* null byte always written by sprintf */) {} 403 404 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 405 const char *, unsigned SpecifierLen) override { 406 407 const size_t FieldWidth = computeFieldWidth(FS); 408 const size_t Precision = computePrecision(FS); 409 410 // The actual format. 411 switch (FS.getConversionSpecifier().getKind()) { 412 // Just a char. 413 case analyze_format_string::ConversionSpecifier::cArg: 414 case analyze_format_string::ConversionSpecifier::CArg: 415 Size += std::max(FieldWidth, (size_t)1); 416 break; 417 // Just an integer. 418 case analyze_format_string::ConversionSpecifier::dArg: 419 case analyze_format_string::ConversionSpecifier::DArg: 420 case analyze_format_string::ConversionSpecifier::iArg: 421 case analyze_format_string::ConversionSpecifier::oArg: 422 case analyze_format_string::ConversionSpecifier::OArg: 423 case analyze_format_string::ConversionSpecifier::uArg: 424 case analyze_format_string::ConversionSpecifier::UArg: 425 case analyze_format_string::ConversionSpecifier::xArg: 426 case analyze_format_string::ConversionSpecifier::XArg: 427 Size += std::max(FieldWidth, Precision); 428 break; 429 430 // %g style conversion switches between %f or %e style dynamically. 431 // %f always takes less space, so default to it. 432 case analyze_format_string::ConversionSpecifier::gArg: 433 case analyze_format_string::ConversionSpecifier::GArg: 434 435 // Floating point number in the form '[+]ddd.ddd'. 436 case analyze_format_string::ConversionSpecifier::fArg: 437 case analyze_format_string::ConversionSpecifier::FArg: 438 Size += std::max(FieldWidth, 1 /* integer part */ + 439 (Precision ? 1 + Precision 440 : 0) /* period + decimal */); 441 break; 442 443 // Floating point number in the form '[-]d.ddde[+-]dd'. 444 case analyze_format_string::ConversionSpecifier::eArg: 445 case analyze_format_string::ConversionSpecifier::EArg: 446 Size += 447 std::max(FieldWidth, 448 1 /* integer part */ + 449 (Precision ? 1 + Precision : 0) /* period + decimal */ + 450 1 /* e or E letter */ + 2 /* exponent */); 451 break; 452 453 // Floating point number in the form '[-]0xh.hhhhp±dd'. 454 case analyze_format_string::ConversionSpecifier::aArg: 455 case analyze_format_string::ConversionSpecifier::AArg: 456 Size += 457 std::max(FieldWidth, 458 2 /* 0x */ + 1 /* integer part */ + 459 (Precision ? 1 + Precision : 0) /* period + decimal */ + 460 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 461 break; 462 463 // Just a string. 464 case analyze_format_string::ConversionSpecifier::sArg: 465 case analyze_format_string::ConversionSpecifier::SArg: 466 Size += FieldWidth; 467 break; 468 469 // Just a pointer in the form '0xddd'. 470 case analyze_format_string::ConversionSpecifier::pArg: 471 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 472 break; 473 474 // A plain percent. 475 case analyze_format_string::ConversionSpecifier::PercentArg: 476 Size += 1; 477 break; 478 479 default: 480 break; 481 } 482 483 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 484 485 if (FS.hasAlternativeForm()) { 486 switch (FS.getConversionSpecifier().getKind()) { 487 default: 488 break; 489 // Force a leading '0'. 490 case analyze_format_string::ConversionSpecifier::oArg: 491 Size += 1; 492 break; 493 // Force a leading '0x'. 494 case analyze_format_string::ConversionSpecifier::xArg: 495 case analyze_format_string::ConversionSpecifier::XArg: 496 Size += 2; 497 break; 498 // Force a period '.' before decimal, even if precision is 0. 499 case analyze_format_string::ConversionSpecifier::aArg: 500 case analyze_format_string::ConversionSpecifier::AArg: 501 case analyze_format_string::ConversionSpecifier::eArg: 502 case analyze_format_string::ConversionSpecifier::EArg: 503 case analyze_format_string::ConversionSpecifier::fArg: 504 case analyze_format_string::ConversionSpecifier::FArg: 505 case analyze_format_string::ConversionSpecifier::gArg: 506 case analyze_format_string::ConversionSpecifier::GArg: 507 Size += (Precision ? 0 : 1); 508 break; 509 } 510 } 511 assert(SpecifierLen <= Size && "no underflow"); 512 Size -= SpecifierLen; 513 return true; 514 } 515 516 size_t getSizeLowerBound() const { return Size; } 517 518 private: 519 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 520 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 521 size_t FieldWidth = 0; 522 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 523 FieldWidth = FW.getConstantAmount(); 524 return FieldWidth; 525 } 526 527 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 528 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 529 size_t Precision = 0; 530 531 // See man 3 printf for default precision value based on the specifier. 532 switch (FW.getHowSpecified()) { 533 case analyze_format_string::OptionalAmount::NotSpecified: 534 switch (FS.getConversionSpecifier().getKind()) { 535 default: 536 break; 537 case analyze_format_string::ConversionSpecifier::dArg: // %d 538 case analyze_format_string::ConversionSpecifier::DArg: // %D 539 case analyze_format_string::ConversionSpecifier::iArg: // %i 540 Precision = 1; 541 break; 542 case analyze_format_string::ConversionSpecifier::oArg: // %d 543 case analyze_format_string::ConversionSpecifier::OArg: // %D 544 case analyze_format_string::ConversionSpecifier::uArg: // %d 545 case analyze_format_string::ConversionSpecifier::UArg: // %D 546 case analyze_format_string::ConversionSpecifier::xArg: // %d 547 case analyze_format_string::ConversionSpecifier::XArg: // %D 548 Precision = 1; 549 break; 550 case analyze_format_string::ConversionSpecifier::fArg: // %f 551 case analyze_format_string::ConversionSpecifier::FArg: // %F 552 case analyze_format_string::ConversionSpecifier::eArg: // %e 553 case analyze_format_string::ConversionSpecifier::EArg: // %E 554 case analyze_format_string::ConversionSpecifier::gArg: // %g 555 case analyze_format_string::ConversionSpecifier::GArg: // %G 556 Precision = 6; 557 break; 558 case analyze_format_string::ConversionSpecifier::pArg: // %d 559 Precision = 1; 560 break; 561 } 562 break; 563 case analyze_format_string::OptionalAmount::Constant: 564 Precision = FW.getConstantAmount(); 565 break; 566 default: 567 break; 568 } 569 return Precision; 570 } 571 }; 572 573 } // namespace 574 575 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 576 /// __builtin_*_chk function, then use the object size argument specified in the 577 /// source. Otherwise, infer the object size using __builtin_object_size. 578 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 579 CallExpr *TheCall) { 580 // FIXME: There are some more useful checks we could be doing here: 581 // - Evaluate strlen of strcpy arguments, use as object size. 582 583 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 584 isConstantEvaluated()) 585 return; 586 587 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 588 if (!BuiltinID) 589 return; 590 591 const TargetInfo &TI = getASTContext().getTargetInfo(); 592 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 593 594 unsigned DiagID = 0; 595 bool IsChkVariant = false; 596 Optional<llvm::APSInt> UsedSize; 597 unsigned SizeIndex, ObjectIndex; 598 switch (BuiltinID) { 599 default: 600 return; 601 case Builtin::BIsprintf: 602 case Builtin::BI__builtin___sprintf_chk: { 603 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 604 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 605 606 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 607 608 if (!Format->isAscii() && !Format->isUTF8()) 609 return; 610 611 StringRef FormatStrRef = Format->getString(); 612 EstimateSizeFormatHandler H(FormatStrRef); 613 const char *FormatBytes = FormatStrRef.data(); 614 const ConstantArrayType *T = 615 Context.getAsConstantArrayType(Format->getType()); 616 assert(T && "String literal not of constant array type!"); 617 size_t TypeSize = T->getSize().getZExtValue(); 618 619 // In case there's a null byte somewhere. 620 size_t StrLen = 621 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 622 if (!analyze_format_string::ParsePrintfString( 623 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 624 Context.getTargetInfo(), false)) { 625 DiagID = diag::warn_fortify_source_format_overflow; 626 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 627 .extOrTrunc(SizeTypeWidth); 628 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 629 IsChkVariant = true; 630 ObjectIndex = 2; 631 } else { 632 IsChkVariant = false; 633 ObjectIndex = 0; 634 } 635 break; 636 } 637 } 638 return; 639 } 640 case Builtin::BI__builtin___memcpy_chk: 641 case Builtin::BI__builtin___memmove_chk: 642 case Builtin::BI__builtin___memset_chk: 643 case Builtin::BI__builtin___strlcat_chk: 644 case Builtin::BI__builtin___strlcpy_chk: 645 case Builtin::BI__builtin___strncat_chk: 646 case Builtin::BI__builtin___strncpy_chk: 647 case Builtin::BI__builtin___stpncpy_chk: 648 case Builtin::BI__builtin___memccpy_chk: 649 case Builtin::BI__builtin___mempcpy_chk: { 650 DiagID = diag::warn_builtin_chk_overflow; 651 IsChkVariant = true; 652 SizeIndex = TheCall->getNumArgs() - 2; 653 ObjectIndex = TheCall->getNumArgs() - 1; 654 break; 655 } 656 657 case Builtin::BI__builtin___snprintf_chk: 658 case Builtin::BI__builtin___vsnprintf_chk: { 659 DiagID = diag::warn_builtin_chk_overflow; 660 IsChkVariant = true; 661 SizeIndex = 1; 662 ObjectIndex = 3; 663 break; 664 } 665 666 case Builtin::BIstrncat: 667 case Builtin::BI__builtin_strncat: 668 case Builtin::BIstrncpy: 669 case Builtin::BI__builtin_strncpy: 670 case Builtin::BIstpncpy: 671 case Builtin::BI__builtin_stpncpy: { 672 // Whether these functions overflow depends on the runtime strlen of the 673 // string, not just the buffer size, so emitting the "always overflow" 674 // diagnostic isn't quite right. We should still diagnose passing a buffer 675 // size larger than the destination buffer though; this is a runtime abort 676 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 677 DiagID = diag::warn_fortify_source_size_mismatch; 678 SizeIndex = TheCall->getNumArgs() - 1; 679 ObjectIndex = 0; 680 break; 681 } 682 683 case Builtin::BImemcpy: 684 case Builtin::BI__builtin_memcpy: 685 case Builtin::BImemmove: 686 case Builtin::BI__builtin_memmove: 687 case Builtin::BImemset: 688 case Builtin::BI__builtin_memset: 689 case Builtin::BImempcpy: 690 case Builtin::BI__builtin_mempcpy: { 691 DiagID = diag::warn_fortify_source_overflow; 692 SizeIndex = TheCall->getNumArgs() - 1; 693 ObjectIndex = 0; 694 break; 695 } 696 case Builtin::BIsnprintf: 697 case Builtin::BI__builtin_snprintf: 698 case Builtin::BIvsnprintf: 699 case Builtin::BI__builtin_vsnprintf: { 700 DiagID = diag::warn_fortify_source_size_mismatch; 701 SizeIndex = 1; 702 ObjectIndex = 0; 703 break; 704 } 705 } 706 707 llvm::APSInt ObjectSize; 708 // For __builtin___*_chk, the object size is explicitly provided by the caller 709 // (usually using __builtin_object_size). Use that value to check this call. 710 if (IsChkVariant) { 711 Expr::EvalResult Result; 712 Expr *SizeArg = TheCall->getArg(ObjectIndex); 713 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 714 return; 715 ObjectSize = Result.Val.getInt(); 716 717 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 718 } else { 719 // If the parameter has a pass_object_size attribute, then we should use its 720 // (potentially) more strict checking mode. Otherwise, conservatively assume 721 // type 0. 722 int BOSType = 0; 723 if (const auto *POS = 724 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 725 BOSType = POS->getType(); 726 727 Expr *ObjArg = TheCall->getArg(ObjectIndex); 728 uint64_t Result; 729 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 730 return; 731 // Get the object size in the target's size_t width. 732 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 733 } 734 735 // Evaluate the number of bytes of the object that this call will use. 736 if (!UsedSize) { 737 Expr::EvalResult Result; 738 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 739 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 740 return; 741 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 742 } 743 744 if (UsedSize.getValue().ule(ObjectSize)) 745 return; 746 747 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 748 // Skim off the details of whichever builtin was called to produce a better 749 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 750 if (IsChkVariant) { 751 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 752 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 753 } else if (FunctionName.startswith("__builtin_")) { 754 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 755 } 756 757 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 758 PDiag(DiagID) 759 << FunctionName << ObjectSize.toString(/*Radix=*/10) 760 << UsedSize.getValue().toString(/*Radix=*/10)); 761 } 762 763 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 764 Scope::ScopeFlags NeededScopeFlags, 765 unsigned DiagID) { 766 // Scopes aren't available during instantiation. Fortunately, builtin 767 // functions cannot be template args so they cannot be formed through template 768 // instantiation. Therefore checking once during the parse is sufficient. 769 if (SemaRef.inTemplateInstantiation()) 770 return false; 771 772 Scope *S = SemaRef.getCurScope(); 773 while (S && !S->isSEHExceptScope()) 774 S = S->getParent(); 775 if (!S || !(S->getFlags() & NeededScopeFlags)) { 776 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 777 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 778 << DRE->getDecl()->getIdentifier(); 779 return true; 780 } 781 782 return false; 783 } 784 785 static inline bool isBlockPointer(Expr *Arg) { 786 return Arg->getType()->isBlockPointerType(); 787 } 788 789 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 790 /// void*, which is a requirement of device side enqueue. 791 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 792 const BlockPointerType *BPT = 793 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 794 ArrayRef<QualType> Params = 795 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 796 unsigned ArgCounter = 0; 797 bool IllegalParams = false; 798 // Iterate through the block parameters until either one is found that is not 799 // a local void*, or the block is valid. 800 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 801 I != E; ++I, ++ArgCounter) { 802 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 803 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 804 LangAS::opencl_local) { 805 // Get the location of the error. If a block literal has been passed 806 // (BlockExpr) then we can point straight to the offending argument, 807 // else we just point to the variable reference. 808 SourceLocation ErrorLoc; 809 if (isa<BlockExpr>(BlockArg)) { 810 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 811 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 812 } else if (isa<DeclRefExpr>(BlockArg)) { 813 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 814 } 815 S.Diag(ErrorLoc, 816 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 817 IllegalParams = true; 818 } 819 } 820 821 return IllegalParams; 822 } 823 824 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 825 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 826 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 827 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 828 return true; 829 } 830 return false; 831 } 832 833 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 834 if (checkArgCount(S, TheCall, 2)) 835 return true; 836 837 if (checkOpenCLSubgroupExt(S, TheCall)) 838 return true; 839 840 // First argument is an ndrange_t type. 841 Expr *NDRangeArg = TheCall->getArg(0); 842 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 843 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 844 << TheCall->getDirectCallee() << "'ndrange_t'"; 845 return true; 846 } 847 848 Expr *BlockArg = TheCall->getArg(1); 849 if (!isBlockPointer(BlockArg)) { 850 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 851 << TheCall->getDirectCallee() << "block"; 852 return true; 853 } 854 return checkOpenCLBlockArgs(S, BlockArg); 855 } 856 857 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 858 /// get_kernel_work_group_size 859 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 860 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 861 if (checkArgCount(S, TheCall, 1)) 862 return true; 863 864 Expr *BlockArg = TheCall->getArg(0); 865 if (!isBlockPointer(BlockArg)) { 866 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 867 << TheCall->getDirectCallee() << "block"; 868 return true; 869 } 870 return checkOpenCLBlockArgs(S, BlockArg); 871 } 872 873 /// Diagnose integer type and any valid implicit conversion to it. 874 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 875 const QualType &IntType); 876 877 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 878 unsigned Start, unsigned End) { 879 bool IllegalParams = false; 880 for (unsigned I = Start; I <= End; ++I) 881 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 882 S.Context.getSizeType()); 883 return IllegalParams; 884 } 885 886 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 887 /// 'local void*' parameter of passed block. 888 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 889 Expr *BlockArg, 890 unsigned NumNonVarArgs) { 891 const BlockPointerType *BPT = 892 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 893 unsigned NumBlockParams = 894 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 895 unsigned TotalNumArgs = TheCall->getNumArgs(); 896 897 // For each argument passed to the block, a corresponding uint needs to 898 // be passed to describe the size of the local memory. 899 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 900 S.Diag(TheCall->getBeginLoc(), 901 diag::err_opencl_enqueue_kernel_local_size_args); 902 return true; 903 } 904 905 // Check that the sizes of the local memory are specified by integers. 906 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 907 TotalNumArgs - 1); 908 } 909 910 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 911 /// overload formats specified in Table 6.13.17.1. 912 /// int enqueue_kernel(queue_t queue, 913 /// kernel_enqueue_flags_t flags, 914 /// const ndrange_t ndrange, 915 /// void (^block)(void)) 916 /// int enqueue_kernel(queue_t queue, 917 /// kernel_enqueue_flags_t flags, 918 /// const ndrange_t ndrange, 919 /// uint num_events_in_wait_list, 920 /// clk_event_t *event_wait_list, 921 /// clk_event_t *event_ret, 922 /// void (^block)(void)) 923 /// int enqueue_kernel(queue_t queue, 924 /// kernel_enqueue_flags_t flags, 925 /// const ndrange_t ndrange, 926 /// void (^block)(local void*, ...), 927 /// uint size0, ...) 928 /// int enqueue_kernel(queue_t queue, 929 /// kernel_enqueue_flags_t flags, 930 /// const ndrange_t ndrange, 931 /// uint num_events_in_wait_list, 932 /// clk_event_t *event_wait_list, 933 /// clk_event_t *event_ret, 934 /// void (^block)(local void*, ...), 935 /// uint size0, ...) 936 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 937 unsigned NumArgs = TheCall->getNumArgs(); 938 939 if (NumArgs < 4) { 940 S.Diag(TheCall->getBeginLoc(), 941 diag::err_typecheck_call_too_few_args_at_least) 942 << 0 << 4 << NumArgs; 943 return true; 944 } 945 946 Expr *Arg0 = TheCall->getArg(0); 947 Expr *Arg1 = TheCall->getArg(1); 948 Expr *Arg2 = TheCall->getArg(2); 949 Expr *Arg3 = TheCall->getArg(3); 950 951 // First argument always needs to be a queue_t type. 952 if (!Arg0->getType()->isQueueT()) { 953 S.Diag(TheCall->getArg(0)->getBeginLoc(), 954 diag::err_opencl_builtin_expected_type) 955 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 956 return true; 957 } 958 959 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 960 if (!Arg1->getType()->isIntegerType()) { 961 S.Diag(TheCall->getArg(1)->getBeginLoc(), 962 diag::err_opencl_builtin_expected_type) 963 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 964 return true; 965 } 966 967 // Third argument is always an ndrange_t type. 968 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 969 S.Diag(TheCall->getArg(2)->getBeginLoc(), 970 diag::err_opencl_builtin_expected_type) 971 << TheCall->getDirectCallee() << "'ndrange_t'"; 972 return true; 973 } 974 975 // With four arguments, there is only one form that the function could be 976 // called in: no events and no variable arguments. 977 if (NumArgs == 4) { 978 // check that the last argument is the right block type. 979 if (!isBlockPointer(Arg3)) { 980 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 981 << TheCall->getDirectCallee() << "block"; 982 return true; 983 } 984 // we have a block type, check the prototype 985 const BlockPointerType *BPT = 986 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 987 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 988 S.Diag(Arg3->getBeginLoc(), 989 diag::err_opencl_enqueue_kernel_blocks_no_args); 990 return true; 991 } 992 return false; 993 } 994 // we can have block + varargs. 995 if (isBlockPointer(Arg3)) 996 return (checkOpenCLBlockArgs(S, Arg3) || 997 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 998 // last two cases with either exactly 7 args or 7 args and varargs. 999 if (NumArgs >= 7) { 1000 // check common block argument. 1001 Expr *Arg6 = TheCall->getArg(6); 1002 if (!isBlockPointer(Arg6)) { 1003 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1004 << TheCall->getDirectCallee() << "block"; 1005 return true; 1006 } 1007 if (checkOpenCLBlockArgs(S, Arg6)) 1008 return true; 1009 1010 // Forth argument has to be any integer type. 1011 if (!Arg3->getType()->isIntegerType()) { 1012 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1013 diag::err_opencl_builtin_expected_type) 1014 << TheCall->getDirectCallee() << "integer"; 1015 return true; 1016 } 1017 // check remaining common arguments. 1018 Expr *Arg4 = TheCall->getArg(4); 1019 Expr *Arg5 = TheCall->getArg(5); 1020 1021 // Fifth argument is always passed as a pointer to clk_event_t. 1022 if (!Arg4->isNullPointerConstant(S.Context, 1023 Expr::NPC_ValueDependentIsNotNull) && 1024 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1025 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1026 diag::err_opencl_builtin_expected_type) 1027 << TheCall->getDirectCallee() 1028 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1029 return true; 1030 } 1031 1032 // Sixth argument is always passed as a pointer to clk_event_t. 1033 if (!Arg5->isNullPointerConstant(S.Context, 1034 Expr::NPC_ValueDependentIsNotNull) && 1035 !(Arg5->getType()->isPointerType() && 1036 Arg5->getType()->getPointeeType()->isClkEventT())) { 1037 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1038 diag::err_opencl_builtin_expected_type) 1039 << TheCall->getDirectCallee() 1040 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1041 return true; 1042 } 1043 1044 if (NumArgs == 7) 1045 return false; 1046 1047 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1048 } 1049 1050 // None of the specific case has been detected, give generic error 1051 S.Diag(TheCall->getBeginLoc(), 1052 diag::err_opencl_enqueue_kernel_incorrect_args); 1053 return true; 1054 } 1055 1056 /// Returns OpenCL access qual. 1057 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1058 return D->getAttr<OpenCLAccessAttr>(); 1059 } 1060 1061 /// Returns true if pipe element type is different from the pointer. 1062 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1063 const Expr *Arg0 = Call->getArg(0); 1064 // First argument type should always be pipe. 1065 if (!Arg0->getType()->isPipeType()) { 1066 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1067 << Call->getDirectCallee() << Arg0->getSourceRange(); 1068 return true; 1069 } 1070 OpenCLAccessAttr *AccessQual = 1071 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1072 // Validates the access qualifier is compatible with the call. 1073 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1074 // read_only and write_only, and assumed to be read_only if no qualifier is 1075 // specified. 1076 switch (Call->getDirectCallee()->getBuiltinID()) { 1077 case Builtin::BIread_pipe: 1078 case Builtin::BIreserve_read_pipe: 1079 case Builtin::BIcommit_read_pipe: 1080 case Builtin::BIwork_group_reserve_read_pipe: 1081 case Builtin::BIsub_group_reserve_read_pipe: 1082 case Builtin::BIwork_group_commit_read_pipe: 1083 case Builtin::BIsub_group_commit_read_pipe: 1084 if (!(!AccessQual || AccessQual->isReadOnly())) { 1085 S.Diag(Arg0->getBeginLoc(), 1086 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1087 << "read_only" << Arg0->getSourceRange(); 1088 return true; 1089 } 1090 break; 1091 case Builtin::BIwrite_pipe: 1092 case Builtin::BIreserve_write_pipe: 1093 case Builtin::BIcommit_write_pipe: 1094 case Builtin::BIwork_group_reserve_write_pipe: 1095 case Builtin::BIsub_group_reserve_write_pipe: 1096 case Builtin::BIwork_group_commit_write_pipe: 1097 case Builtin::BIsub_group_commit_write_pipe: 1098 if (!(AccessQual && AccessQual->isWriteOnly())) { 1099 S.Diag(Arg0->getBeginLoc(), 1100 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1101 << "write_only" << Arg0->getSourceRange(); 1102 return true; 1103 } 1104 break; 1105 default: 1106 break; 1107 } 1108 return false; 1109 } 1110 1111 /// Returns true if pipe element type is different from the pointer. 1112 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1113 const Expr *Arg0 = Call->getArg(0); 1114 const Expr *ArgIdx = Call->getArg(Idx); 1115 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1116 const QualType EltTy = PipeTy->getElementType(); 1117 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1118 // The Idx argument should be a pointer and the type of the pointer and 1119 // the type of pipe element should also be the same. 1120 if (!ArgTy || 1121 !S.Context.hasSameType( 1122 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1123 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1124 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1125 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1126 return true; 1127 } 1128 return false; 1129 } 1130 1131 // Performs semantic analysis for the read/write_pipe call. 1132 // \param S Reference to the semantic analyzer. 1133 // \param Call A pointer to the builtin call. 1134 // \return True if a semantic error has been found, false otherwise. 1135 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1136 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1137 // functions have two forms. 1138 switch (Call->getNumArgs()) { 1139 case 2: 1140 if (checkOpenCLPipeArg(S, Call)) 1141 return true; 1142 // The call with 2 arguments should be 1143 // read/write_pipe(pipe T, T*). 1144 // Check packet type T. 1145 if (checkOpenCLPipePacketType(S, Call, 1)) 1146 return true; 1147 break; 1148 1149 case 4: { 1150 if (checkOpenCLPipeArg(S, Call)) 1151 return true; 1152 // The call with 4 arguments should be 1153 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1154 // Check reserve_id_t. 1155 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1156 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1157 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1158 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1159 return true; 1160 } 1161 1162 // Check the index. 1163 const Expr *Arg2 = Call->getArg(2); 1164 if (!Arg2->getType()->isIntegerType() && 1165 !Arg2->getType()->isUnsignedIntegerType()) { 1166 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1167 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1168 << Arg2->getType() << Arg2->getSourceRange(); 1169 return true; 1170 } 1171 1172 // Check packet type T. 1173 if (checkOpenCLPipePacketType(S, Call, 3)) 1174 return true; 1175 } break; 1176 default: 1177 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1178 << Call->getDirectCallee() << Call->getSourceRange(); 1179 return true; 1180 } 1181 1182 return false; 1183 } 1184 1185 // Performs a semantic analysis on the {work_group_/sub_group_ 1186 // /_}reserve_{read/write}_pipe 1187 // \param S Reference to the semantic analyzer. 1188 // \param Call The call to the builtin function to be analyzed. 1189 // \return True if a semantic error was found, false otherwise. 1190 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1191 if (checkArgCount(S, Call, 2)) 1192 return true; 1193 1194 if (checkOpenCLPipeArg(S, Call)) 1195 return true; 1196 1197 // Check the reserve size. 1198 if (!Call->getArg(1)->getType()->isIntegerType() && 1199 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1200 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1201 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1202 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1203 return true; 1204 } 1205 1206 // Since return type of reserve_read/write_pipe built-in function is 1207 // reserve_id_t, which is not defined in the builtin def file , we used int 1208 // as return type and need to override the return type of these functions. 1209 Call->setType(S.Context.OCLReserveIDTy); 1210 1211 return false; 1212 } 1213 1214 // Performs a semantic analysis on {work_group_/sub_group_ 1215 // /_}commit_{read/write}_pipe 1216 // \param S Reference to the semantic analyzer. 1217 // \param Call The call to the builtin function to be analyzed. 1218 // \return True if a semantic error was found, false otherwise. 1219 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1220 if (checkArgCount(S, Call, 2)) 1221 return true; 1222 1223 if (checkOpenCLPipeArg(S, Call)) 1224 return true; 1225 1226 // Check reserve_id_t. 1227 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1228 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1229 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1230 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1231 return true; 1232 } 1233 1234 return false; 1235 } 1236 1237 // Performs a semantic analysis on the call to built-in Pipe 1238 // Query Functions. 1239 // \param S Reference to the semantic analyzer. 1240 // \param Call The call to the builtin function to be analyzed. 1241 // \return True if a semantic error was found, false otherwise. 1242 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1243 if (checkArgCount(S, Call, 1)) 1244 return true; 1245 1246 if (!Call->getArg(0)->getType()->isPipeType()) { 1247 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1248 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1249 return true; 1250 } 1251 1252 return false; 1253 } 1254 1255 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1256 // Performs semantic analysis for the to_global/local/private call. 1257 // \param S Reference to the semantic analyzer. 1258 // \param BuiltinID ID of the builtin function. 1259 // \param Call A pointer to the builtin call. 1260 // \return True if a semantic error has been found, false otherwise. 1261 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1262 CallExpr *Call) { 1263 if (Call->getNumArgs() != 1) { 1264 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 1265 << Call->getDirectCallee() << Call->getSourceRange(); 1266 return true; 1267 } 1268 1269 auto RT = Call->getArg(0)->getType(); 1270 if (!RT->isPointerType() || RT->getPointeeType() 1271 .getAddressSpace() == LangAS::opencl_constant) { 1272 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1273 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1274 return true; 1275 } 1276 1277 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1278 S.Diag(Call->getArg(0)->getBeginLoc(), 1279 diag::warn_opencl_generic_address_space_arg) 1280 << Call->getDirectCallee()->getNameInfo().getAsString() 1281 << Call->getArg(0)->getSourceRange(); 1282 } 1283 1284 RT = RT->getPointeeType(); 1285 auto Qual = RT.getQualifiers(); 1286 switch (BuiltinID) { 1287 case Builtin::BIto_global: 1288 Qual.setAddressSpace(LangAS::opencl_global); 1289 break; 1290 case Builtin::BIto_local: 1291 Qual.setAddressSpace(LangAS::opencl_local); 1292 break; 1293 case Builtin::BIto_private: 1294 Qual.setAddressSpace(LangAS::opencl_private); 1295 break; 1296 default: 1297 llvm_unreachable("Invalid builtin function"); 1298 } 1299 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1300 RT.getUnqualifiedType(), Qual))); 1301 1302 return false; 1303 } 1304 1305 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1306 if (checkArgCount(S, TheCall, 1)) 1307 return ExprError(); 1308 1309 // Compute __builtin_launder's parameter type from the argument. 1310 // The parameter type is: 1311 // * The type of the argument if it's not an array or function type, 1312 // Otherwise, 1313 // * The decayed argument type. 1314 QualType ParamTy = [&]() { 1315 QualType ArgTy = TheCall->getArg(0)->getType(); 1316 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1317 return S.Context.getPointerType(Ty->getElementType()); 1318 if (ArgTy->isFunctionType()) { 1319 return S.Context.getPointerType(ArgTy); 1320 } 1321 return ArgTy; 1322 }(); 1323 1324 TheCall->setType(ParamTy); 1325 1326 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1327 if (!ParamTy->isPointerType()) 1328 return 0; 1329 if (ParamTy->isFunctionPointerType()) 1330 return 1; 1331 if (ParamTy->isVoidPointerType()) 1332 return 2; 1333 return llvm::Optional<unsigned>{}; 1334 }(); 1335 if (DiagSelect.hasValue()) { 1336 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1337 << DiagSelect.getValue() << TheCall->getSourceRange(); 1338 return ExprError(); 1339 } 1340 1341 // We either have an incomplete class type, or we have a class template 1342 // whose instantiation has not been forced. Example: 1343 // 1344 // template <class T> struct Foo { T value; }; 1345 // Foo<int> *p = nullptr; 1346 // auto *d = __builtin_launder(p); 1347 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1348 diag::err_incomplete_type)) 1349 return ExprError(); 1350 1351 assert(ParamTy->getPointeeType()->isObjectType() && 1352 "Unhandled non-object pointer case"); 1353 1354 InitializedEntity Entity = 1355 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1356 ExprResult Arg = 1357 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1358 if (Arg.isInvalid()) 1359 return ExprError(); 1360 TheCall->setArg(0, Arg.get()); 1361 1362 return TheCall; 1363 } 1364 1365 // Emit an error and return true if the current architecture is not in the list 1366 // of supported architectures. 1367 static bool 1368 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1369 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1370 llvm::Triple::ArchType CurArch = 1371 S.getASTContext().getTargetInfo().getTriple().getArch(); 1372 if (llvm::is_contained(SupportedArchs, CurArch)) 1373 return false; 1374 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1375 << TheCall->getSourceRange(); 1376 return true; 1377 } 1378 1379 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1380 SourceLocation CallSiteLoc); 1381 1382 ExprResult 1383 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1384 CallExpr *TheCall) { 1385 ExprResult TheCallResult(TheCall); 1386 1387 // Find out if any arguments are required to be integer constant expressions. 1388 unsigned ICEArguments = 0; 1389 ASTContext::GetBuiltinTypeError Error; 1390 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1391 if (Error != ASTContext::GE_None) 1392 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1393 1394 // If any arguments are required to be ICE's, check and diagnose. 1395 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1396 // Skip arguments not required to be ICE's. 1397 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1398 1399 llvm::APSInt Result; 1400 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1401 return true; 1402 ICEArguments &= ~(1 << ArgNo); 1403 } 1404 1405 switch (BuiltinID) { 1406 case Builtin::BI__builtin___CFStringMakeConstantString: 1407 assert(TheCall->getNumArgs() == 1 && 1408 "Wrong # arguments to builtin CFStringMakeConstantString"); 1409 if (CheckObjCString(TheCall->getArg(0))) 1410 return ExprError(); 1411 break; 1412 case Builtin::BI__builtin_ms_va_start: 1413 case Builtin::BI__builtin_stdarg_start: 1414 case Builtin::BI__builtin_va_start: 1415 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1416 return ExprError(); 1417 break; 1418 case Builtin::BI__va_start: { 1419 switch (Context.getTargetInfo().getTriple().getArch()) { 1420 case llvm::Triple::aarch64: 1421 case llvm::Triple::arm: 1422 case llvm::Triple::thumb: 1423 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1424 return ExprError(); 1425 break; 1426 default: 1427 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1428 return ExprError(); 1429 break; 1430 } 1431 break; 1432 } 1433 1434 // The acquire, release, and no fence variants are ARM and AArch64 only. 1435 case Builtin::BI_interlockedbittestandset_acq: 1436 case Builtin::BI_interlockedbittestandset_rel: 1437 case Builtin::BI_interlockedbittestandset_nf: 1438 case Builtin::BI_interlockedbittestandreset_acq: 1439 case Builtin::BI_interlockedbittestandreset_rel: 1440 case Builtin::BI_interlockedbittestandreset_nf: 1441 if (CheckBuiltinTargetSupport( 1442 *this, BuiltinID, TheCall, 1443 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1444 return ExprError(); 1445 break; 1446 1447 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1448 case Builtin::BI_bittest64: 1449 case Builtin::BI_bittestandcomplement64: 1450 case Builtin::BI_bittestandreset64: 1451 case Builtin::BI_bittestandset64: 1452 case Builtin::BI_interlockedbittestandreset64: 1453 case Builtin::BI_interlockedbittestandset64: 1454 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1455 {llvm::Triple::x86_64, llvm::Triple::arm, 1456 llvm::Triple::thumb, llvm::Triple::aarch64})) 1457 return ExprError(); 1458 break; 1459 1460 case Builtin::BI__builtin_isgreater: 1461 case Builtin::BI__builtin_isgreaterequal: 1462 case Builtin::BI__builtin_isless: 1463 case Builtin::BI__builtin_islessequal: 1464 case Builtin::BI__builtin_islessgreater: 1465 case Builtin::BI__builtin_isunordered: 1466 if (SemaBuiltinUnorderedCompare(TheCall)) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__builtin_fpclassify: 1470 if (SemaBuiltinFPClassification(TheCall, 6)) 1471 return ExprError(); 1472 break; 1473 case Builtin::BI__builtin_isfinite: 1474 case Builtin::BI__builtin_isinf: 1475 case Builtin::BI__builtin_isinf_sign: 1476 case Builtin::BI__builtin_isnan: 1477 case Builtin::BI__builtin_isnormal: 1478 case Builtin::BI__builtin_signbit: 1479 case Builtin::BI__builtin_signbitf: 1480 case Builtin::BI__builtin_signbitl: 1481 if (SemaBuiltinFPClassification(TheCall, 1)) 1482 return ExprError(); 1483 break; 1484 case Builtin::BI__builtin_shufflevector: 1485 return SemaBuiltinShuffleVector(TheCall); 1486 // TheCall will be freed by the smart pointer here, but that's fine, since 1487 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1488 case Builtin::BI__builtin_prefetch: 1489 if (SemaBuiltinPrefetch(TheCall)) 1490 return ExprError(); 1491 break; 1492 case Builtin::BI__builtin_alloca_with_align: 1493 if (SemaBuiltinAllocaWithAlign(TheCall)) 1494 return ExprError(); 1495 LLVM_FALLTHROUGH; 1496 case Builtin::BI__builtin_alloca: 1497 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1498 << TheCall->getDirectCallee(); 1499 break; 1500 case Builtin::BI__assume: 1501 case Builtin::BI__builtin_assume: 1502 if (SemaBuiltinAssume(TheCall)) 1503 return ExprError(); 1504 break; 1505 case Builtin::BI__builtin_assume_aligned: 1506 if (SemaBuiltinAssumeAligned(TheCall)) 1507 return ExprError(); 1508 break; 1509 case Builtin::BI__builtin_dynamic_object_size: 1510 case Builtin::BI__builtin_object_size: 1511 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1512 return ExprError(); 1513 break; 1514 case Builtin::BI__builtin_longjmp: 1515 if (SemaBuiltinLongjmp(TheCall)) 1516 return ExprError(); 1517 break; 1518 case Builtin::BI__builtin_setjmp: 1519 if (SemaBuiltinSetjmp(TheCall)) 1520 return ExprError(); 1521 break; 1522 case Builtin::BI_setjmp: 1523 case Builtin::BI_setjmpex: 1524 if (checkArgCount(*this, TheCall, 1)) 1525 return true; 1526 break; 1527 case Builtin::BI__builtin_classify_type: 1528 if (checkArgCount(*this, TheCall, 1)) return true; 1529 TheCall->setType(Context.IntTy); 1530 break; 1531 case Builtin::BI__builtin_constant_p: { 1532 if (checkArgCount(*this, TheCall, 1)) return true; 1533 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1534 if (Arg.isInvalid()) return true; 1535 TheCall->setArg(0, Arg.get()); 1536 TheCall->setType(Context.IntTy); 1537 break; 1538 } 1539 case Builtin::BI__builtin_launder: 1540 return SemaBuiltinLaunder(*this, TheCall); 1541 case Builtin::BI__sync_fetch_and_add: 1542 case Builtin::BI__sync_fetch_and_add_1: 1543 case Builtin::BI__sync_fetch_and_add_2: 1544 case Builtin::BI__sync_fetch_and_add_4: 1545 case Builtin::BI__sync_fetch_and_add_8: 1546 case Builtin::BI__sync_fetch_and_add_16: 1547 case Builtin::BI__sync_fetch_and_sub: 1548 case Builtin::BI__sync_fetch_and_sub_1: 1549 case Builtin::BI__sync_fetch_and_sub_2: 1550 case Builtin::BI__sync_fetch_and_sub_4: 1551 case Builtin::BI__sync_fetch_and_sub_8: 1552 case Builtin::BI__sync_fetch_and_sub_16: 1553 case Builtin::BI__sync_fetch_and_or: 1554 case Builtin::BI__sync_fetch_and_or_1: 1555 case Builtin::BI__sync_fetch_and_or_2: 1556 case Builtin::BI__sync_fetch_and_or_4: 1557 case Builtin::BI__sync_fetch_and_or_8: 1558 case Builtin::BI__sync_fetch_and_or_16: 1559 case Builtin::BI__sync_fetch_and_and: 1560 case Builtin::BI__sync_fetch_and_and_1: 1561 case Builtin::BI__sync_fetch_and_and_2: 1562 case Builtin::BI__sync_fetch_and_and_4: 1563 case Builtin::BI__sync_fetch_and_and_8: 1564 case Builtin::BI__sync_fetch_and_and_16: 1565 case Builtin::BI__sync_fetch_and_xor: 1566 case Builtin::BI__sync_fetch_and_xor_1: 1567 case Builtin::BI__sync_fetch_and_xor_2: 1568 case Builtin::BI__sync_fetch_and_xor_4: 1569 case Builtin::BI__sync_fetch_and_xor_8: 1570 case Builtin::BI__sync_fetch_and_xor_16: 1571 case Builtin::BI__sync_fetch_and_nand: 1572 case Builtin::BI__sync_fetch_and_nand_1: 1573 case Builtin::BI__sync_fetch_and_nand_2: 1574 case Builtin::BI__sync_fetch_and_nand_4: 1575 case Builtin::BI__sync_fetch_and_nand_8: 1576 case Builtin::BI__sync_fetch_and_nand_16: 1577 case Builtin::BI__sync_add_and_fetch: 1578 case Builtin::BI__sync_add_and_fetch_1: 1579 case Builtin::BI__sync_add_and_fetch_2: 1580 case Builtin::BI__sync_add_and_fetch_4: 1581 case Builtin::BI__sync_add_and_fetch_8: 1582 case Builtin::BI__sync_add_and_fetch_16: 1583 case Builtin::BI__sync_sub_and_fetch: 1584 case Builtin::BI__sync_sub_and_fetch_1: 1585 case Builtin::BI__sync_sub_and_fetch_2: 1586 case Builtin::BI__sync_sub_and_fetch_4: 1587 case Builtin::BI__sync_sub_and_fetch_8: 1588 case Builtin::BI__sync_sub_and_fetch_16: 1589 case Builtin::BI__sync_and_and_fetch: 1590 case Builtin::BI__sync_and_and_fetch_1: 1591 case Builtin::BI__sync_and_and_fetch_2: 1592 case Builtin::BI__sync_and_and_fetch_4: 1593 case Builtin::BI__sync_and_and_fetch_8: 1594 case Builtin::BI__sync_and_and_fetch_16: 1595 case Builtin::BI__sync_or_and_fetch: 1596 case Builtin::BI__sync_or_and_fetch_1: 1597 case Builtin::BI__sync_or_and_fetch_2: 1598 case Builtin::BI__sync_or_and_fetch_4: 1599 case Builtin::BI__sync_or_and_fetch_8: 1600 case Builtin::BI__sync_or_and_fetch_16: 1601 case Builtin::BI__sync_xor_and_fetch: 1602 case Builtin::BI__sync_xor_and_fetch_1: 1603 case Builtin::BI__sync_xor_and_fetch_2: 1604 case Builtin::BI__sync_xor_and_fetch_4: 1605 case Builtin::BI__sync_xor_and_fetch_8: 1606 case Builtin::BI__sync_xor_and_fetch_16: 1607 case Builtin::BI__sync_nand_and_fetch: 1608 case Builtin::BI__sync_nand_and_fetch_1: 1609 case Builtin::BI__sync_nand_and_fetch_2: 1610 case Builtin::BI__sync_nand_and_fetch_4: 1611 case Builtin::BI__sync_nand_and_fetch_8: 1612 case Builtin::BI__sync_nand_and_fetch_16: 1613 case Builtin::BI__sync_val_compare_and_swap: 1614 case Builtin::BI__sync_val_compare_and_swap_1: 1615 case Builtin::BI__sync_val_compare_and_swap_2: 1616 case Builtin::BI__sync_val_compare_and_swap_4: 1617 case Builtin::BI__sync_val_compare_and_swap_8: 1618 case Builtin::BI__sync_val_compare_and_swap_16: 1619 case Builtin::BI__sync_bool_compare_and_swap: 1620 case Builtin::BI__sync_bool_compare_and_swap_1: 1621 case Builtin::BI__sync_bool_compare_and_swap_2: 1622 case Builtin::BI__sync_bool_compare_and_swap_4: 1623 case Builtin::BI__sync_bool_compare_and_swap_8: 1624 case Builtin::BI__sync_bool_compare_and_swap_16: 1625 case Builtin::BI__sync_lock_test_and_set: 1626 case Builtin::BI__sync_lock_test_and_set_1: 1627 case Builtin::BI__sync_lock_test_and_set_2: 1628 case Builtin::BI__sync_lock_test_and_set_4: 1629 case Builtin::BI__sync_lock_test_and_set_8: 1630 case Builtin::BI__sync_lock_test_and_set_16: 1631 case Builtin::BI__sync_lock_release: 1632 case Builtin::BI__sync_lock_release_1: 1633 case Builtin::BI__sync_lock_release_2: 1634 case Builtin::BI__sync_lock_release_4: 1635 case Builtin::BI__sync_lock_release_8: 1636 case Builtin::BI__sync_lock_release_16: 1637 case Builtin::BI__sync_swap: 1638 case Builtin::BI__sync_swap_1: 1639 case Builtin::BI__sync_swap_2: 1640 case Builtin::BI__sync_swap_4: 1641 case Builtin::BI__sync_swap_8: 1642 case Builtin::BI__sync_swap_16: 1643 return SemaBuiltinAtomicOverloaded(TheCallResult); 1644 case Builtin::BI__sync_synchronize: 1645 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1646 << TheCall->getCallee()->getSourceRange(); 1647 break; 1648 case Builtin::BI__builtin_nontemporal_load: 1649 case Builtin::BI__builtin_nontemporal_store: 1650 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1651 case Builtin::BI__builtin_memcpy_inline: { 1652 // __builtin_memcpy_inline size argument is a constant by definition. 1653 if (TheCall->getArg(2)->EvaluateKnownConstInt(Context).isNullValue()) 1654 break; 1655 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1656 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1657 break; 1658 } 1659 #define BUILTIN(ID, TYPE, ATTRS) 1660 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1661 case Builtin::BI##ID: \ 1662 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1663 #include "clang/Basic/Builtins.def" 1664 case Builtin::BI__annotation: 1665 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1666 return ExprError(); 1667 break; 1668 case Builtin::BI__builtin_annotation: 1669 if (SemaBuiltinAnnotation(*this, TheCall)) 1670 return ExprError(); 1671 break; 1672 case Builtin::BI__builtin_addressof: 1673 if (SemaBuiltinAddressof(*this, TheCall)) 1674 return ExprError(); 1675 break; 1676 case Builtin::BI__builtin_is_aligned: 1677 case Builtin::BI__builtin_align_up: 1678 case Builtin::BI__builtin_align_down: 1679 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1680 return ExprError(); 1681 break; 1682 case Builtin::BI__builtin_add_overflow: 1683 case Builtin::BI__builtin_sub_overflow: 1684 case Builtin::BI__builtin_mul_overflow: 1685 if (SemaBuiltinOverflow(*this, TheCall)) 1686 return ExprError(); 1687 break; 1688 case Builtin::BI__builtin_operator_new: 1689 case Builtin::BI__builtin_operator_delete: { 1690 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1691 ExprResult Res = 1692 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1693 if (Res.isInvalid()) 1694 CorrectDelayedTyposInExpr(TheCallResult.get()); 1695 return Res; 1696 } 1697 case Builtin::BI__builtin_dump_struct: { 1698 // We first want to ensure we are called with 2 arguments 1699 if (checkArgCount(*this, TheCall, 2)) 1700 return ExprError(); 1701 // Ensure that the first argument is of type 'struct XX *' 1702 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1703 const QualType PtrArgType = PtrArg->getType(); 1704 if (!PtrArgType->isPointerType() || 1705 !PtrArgType->getPointeeType()->isRecordType()) { 1706 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1707 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1708 << "structure pointer"; 1709 return ExprError(); 1710 } 1711 1712 // Ensure that the second argument is of type 'FunctionType' 1713 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1714 const QualType FnPtrArgType = FnPtrArg->getType(); 1715 if (!FnPtrArgType->isPointerType()) { 1716 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1717 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1718 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1719 return ExprError(); 1720 } 1721 1722 const auto *FuncType = 1723 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1724 1725 if (!FuncType) { 1726 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1727 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1728 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1729 return ExprError(); 1730 } 1731 1732 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1733 if (!FT->getNumParams()) { 1734 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1735 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1736 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1737 return ExprError(); 1738 } 1739 QualType PT = FT->getParamType(0); 1740 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1741 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1742 !PT->getPointeeType().isConstQualified()) { 1743 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1744 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1745 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1746 return ExprError(); 1747 } 1748 } 1749 1750 TheCall->setType(Context.IntTy); 1751 break; 1752 } 1753 case Builtin::BI__builtin_preserve_access_index: 1754 if (SemaBuiltinPreserveAI(*this, TheCall)) 1755 return ExprError(); 1756 break; 1757 case Builtin::BI__builtin_call_with_static_chain: 1758 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__exception_code: 1762 case Builtin::BI_exception_code: 1763 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1764 diag::err_seh___except_block)) 1765 return ExprError(); 1766 break; 1767 case Builtin::BI__exception_info: 1768 case Builtin::BI_exception_info: 1769 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1770 diag::err_seh___except_filter)) 1771 return ExprError(); 1772 break; 1773 case Builtin::BI__GetExceptionInfo: 1774 if (checkArgCount(*this, TheCall, 1)) 1775 return ExprError(); 1776 1777 if (CheckCXXThrowOperand( 1778 TheCall->getBeginLoc(), 1779 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1780 TheCall)) 1781 return ExprError(); 1782 1783 TheCall->setType(Context.VoidPtrTy); 1784 break; 1785 // OpenCL v2.0, s6.13.16 - Pipe functions 1786 case Builtin::BIread_pipe: 1787 case Builtin::BIwrite_pipe: 1788 // Since those two functions are declared with var args, we need a semantic 1789 // check for the argument. 1790 if (SemaBuiltinRWPipe(*this, TheCall)) 1791 return ExprError(); 1792 break; 1793 case Builtin::BIreserve_read_pipe: 1794 case Builtin::BIreserve_write_pipe: 1795 case Builtin::BIwork_group_reserve_read_pipe: 1796 case Builtin::BIwork_group_reserve_write_pipe: 1797 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1798 return ExprError(); 1799 break; 1800 case Builtin::BIsub_group_reserve_read_pipe: 1801 case Builtin::BIsub_group_reserve_write_pipe: 1802 if (checkOpenCLSubgroupExt(*this, TheCall) || 1803 SemaBuiltinReserveRWPipe(*this, TheCall)) 1804 return ExprError(); 1805 break; 1806 case Builtin::BIcommit_read_pipe: 1807 case Builtin::BIcommit_write_pipe: 1808 case Builtin::BIwork_group_commit_read_pipe: 1809 case Builtin::BIwork_group_commit_write_pipe: 1810 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1811 return ExprError(); 1812 break; 1813 case Builtin::BIsub_group_commit_read_pipe: 1814 case Builtin::BIsub_group_commit_write_pipe: 1815 if (checkOpenCLSubgroupExt(*this, TheCall) || 1816 SemaBuiltinCommitRWPipe(*this, TheCall)) 1817 return ExprError(); 1818 break; 1819 case Builtin::BIget_pipe_num_packets: 1820 case Builtin::BIget_pipe_max_packets: 1821 if (SemaBuiltinPipePackets(*this, TheCall)) 1822 return ExprError(); 1823 break; 1824 case Builtin::BIto_global: 1825 case Builtin::BIto_local: 1826 case Builtin::BIto_private: 1827 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1828 return ExprError(); 1829 break; 1830 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1831 case Builtin::BIenqueue_kernel: 1832 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1833 return ExprError(); 1834 break; 1835 case Builtin::BIget_kernel_work_group_size: 1836 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1837 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1838 return ExprError(); 1839 break; 1840 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1841 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1842 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1843 return ExprError(); 1844 break; 1845 case Builtin::BI__builtin_os_log_format: 1846 Cleanup.setExprNeedsCleanups(true); 1847 LLVM_FALLTHROUGH; 1848 case Builtin::BI__builtin_os_log_format_buffer_size: 1849 if (SemaBuiltinOSLogFormat(TheCall)) 1850 return ExprError(); 1851 break; 1852 case Builtin::BI__builtin_frame_address: 1853 case Builtin::BI__builtin_return_address: 1854 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1855 return ExprError(); 1856 break; 1857 } 1858 1859 // Since the target specific builtins for each arch overlap, only check those 1860 // of the arch we are compiling for. 1861 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1862 switch (Context.getTargetInfo().getTriple().getArch()) { 1863 case llvm::Triple::arm: 1864 case llvm::Triple::armeb: 1865 case llvm::Triple::thumb: 1866 case llvm::Triple::thumbeb: 1867 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1868 return ExprError(); 1869 break; 1870 case llvm::Triple::aarch64: 1871 case llvm::Triple::aarch64_32: 1872 case llvm::Triple::aarch64_be: 1873 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1874 return ExprError(); 1875 break; 1876 case llvm::Triple::bpfeb: 1877 case llvm::Triple::bpfel: 1878 if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall)) 1879 return ExprError(); 1880 break; 1881 case llvm::Triple::hexagon: 1882 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1883 return ExprError(); 1884 break; 1885 case llvm::Triple::mips: 1886 case llvm::Triple::mipsel: 1887 case llvm::Triple::mips64: 1888 case llvm::Triple::mips64el: 1889 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1890 return ExprError(); 1891 break; 1892 case llvm::Triple::systemz: 1893 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1894 return ExprError(); 1895 break; 1896 case llvm::Triple::x86: 1897 case llvm::Triple::x86_64: 1898 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1899 return ExprError(); 1900 break; 1901 case llvm::Triple::ppc: 1902 case llvm::Triple::ppc64: 1903 case llvm::Triple::ppc64le: 1904 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1905 return ExprError(); 1906 break; 1907 default: 1908 break; 1909 } 1910 } 1911 1912 return TheCallResult; 1913 } 1914 1915 // Get the valid immediate range for the specified NEON type code. 1916 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1917 NeonTypeFlags Type(t); 1918 int IsQuad = ForceQuad ? true : Type.isQuad(); 1919 switch (Type.getEltType()) { 1920 case NeonTypeFlags::Int8: 1921 case NeonTypeFlags::Poly8: 1922 return shift ? 7 : (8 << IsQuad) - 1; 1923 case NeonTypeFlags::Int16: 1924 case NeonTypeFlags::Poly16: 1925 return shift ? 15 : (4 << IsQuad) - 1; 1926 case NeonTypeFlags::Int32: 1927 return shift ? 31 : (2 << IsQuad) - 1; 1928 case NeonTypeFlags::Int64: 1929 case NeonTypeFlags::Poly64: 1930 return shift ? 63 : (1 << IsQuad) - 1; 1931 case NeonTypeFlags::Poly128: 1932 return shift ? 127 : (1 << IsQuad) - 1; 1933 case NeonTypeFlags::Float16: 1934 assert(!shift && "cannot shift float types!"); 1935 return (4 << IsQuad) - 1; 1936 case NeonTypeFlags::Float32: 1937 assert(!shift && "cannot shift float types!"); 1938 return (2 << IsQuad) - 1; 1939 case NeonTypeFlags::Float64: 1940 assert(!shift && "cannot shift float types!"); 1941 return (1 << IsQuad) - 1; 1942 } 1943 llvm_unreachable("Invalid NeonTypeFlag!"); 1944 } 1945 1946 /// getNeonEltType - Return the QualType corresponding to the elements of 1947 /// the vector type specified by the NeonTypeFlags. This is used to check 1948 /// the pointer arguments for Neon load/store intrinsics. 1949 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1950 bool IsPolyUnsigned, bool IsInt64Long) { 1951 switch (Flags.getEltType()) { 1952 case NeonTypeFlags::Int8: 1953 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1954 case NeonTypeFlags::Int16: 1955 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1956 case NeonTypeFlags::Int32: 1957 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1958 case NeonTypeFlags::Int64: 1959 if (IsInt64Long) 1960 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1961 else 1962 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1963 : Context.LongLongTy; 1964 case NeonTypeFlags::Poly8: 1965 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1966 case NeonTypeFlags::Poly16: 1967 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1968 case NeonTypeFlags::Poly64: 1969 if (IsInt64Long) 1970 return Context.UnsignedLongTy; 1971 else 1972 return Context.UnsignedLongLongTy; 1973 case NeonTypeFlags::Poly128: 1974 break; 1975 case NeonTypeFlags::Float16: 1976 return Context.HalfTy; 1977 case NeonTypeFlags::Float32: 1978 return Context.FloatTy; 1979 case NeonTypeFlags::Float64: 1980 return Context.DoubleTy; 1981 } 1982 llvm_unreachable("Invalid NeonTypeFlag!"); 1983 } 1984 1985 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1986 llvm::APSInt Result; 1987 uint64_t mask = 0; 1988 unsigned TV = 0; 1989 int PtrArgNum = -1; 1990 bool HasConstPtr = false; 1991 switch (BuiltinID) { 1992 #define GET_NEON_OVERLOAD_CHECK 1993 #include "clang/Basic/arm_neon.inc" 1994 #include "clang/Basic/arm_fp16.inc" 1995 #undef GET_NEON_OVERLOAD_CHECK 1996 } 1997 1998 // For NEON intrinsics which are overloaded on vector element type, validate 1999 // the immediate which specifies which variant to emit. 2000 unsigned ImmArg = TheCall->getNumArgs()-1; 2001 if (mask) { 2002 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2003 return true; 2004 2005 TV = Result.getLimitedValue(64); 2006 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2007 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2008 << TheCall->getArg(ImmArg)->getSourceRange(); 2009 } 2010 2011 if (PtrArgNum >= 0) { 2012 // Check that pointer arguments have the specified type. 2013 Expr *Arg = TheCall->getArg(PtrArgNum); 2014 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2015 Arg = ICE->getSubExpr(); 2016 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2017 QualType RHSTy = RHS.get()->getType(); 2018 2019 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 2020 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2021 Arch == llvm::Triple::aarch64_32 || 2022 Arch == llvm::Triple::aarch64_be; 2023 bool IsInt64Long = 2024 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 2025 QualType EltTy = 2026 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2027 if (HasConstPtr) 2028 EltTy = EltTy.withConst(); 2029 QualType LHSTy = Context.getPointerType(EltTy); 2030 AssignConvertType ConvTy; 2031 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2032 if (RHS.isInvalid()) 2033 return true; 2034 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2035 RHS.get(), AA_Assigning)) 2036 return true; 2037 } 2038 2039 // For NEON intrinsics which take an immediate value as part of the 2040 // instruction, range check them here. 2041 unsigned i = 0, l = 0, u = 0; 2042 switch (BuiltinID) { 2043 default: 2044 return false; 2045 #define GET_NEON_IMMEDIATE_CHECK 2046 #include "clang/Basic/arm_neon.inc" 2047 #include "clang/Basic/arm_fp16.inc" 2048 #undef GET_NEON_IMMEDIATE_CHECK 2049 } 2050 2051 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2052 } 2053 2054 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2055 switch (BuiltinID) { 2056 default: 2057 return false; 2058 #include "clang/Basic/arm_mve_builtin_sema.inc" 2059 } 2060 } 2061 2062 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2063 unsigned MaxWidth) { 2064 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2065 BuiltinID == ARM::BI__builtin_arm_ldaex || 2066 BuiltinID == ARM::BI__builtin_arm_strex || 2067 BuiltinID == ARM::BI__builtin_arm_stlex || 2068 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2069 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2070 BuiltinID == AArch64::BI__builtin_arm_strex || 2071 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2072 "unexpected ARM builtin"); 2073 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2074 BuiltinID == ARM::BI__builtin_arm_ldaex || 2075 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2076 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2077 2078 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2079 2080 // Ensure that we have the proper number of arguments. 2081 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2082 return true; 2083 2084 // Inspect the pointer argument of the atomic builtin. This should always be 2085 // a pointer type, whose element is an integral scalar or pointer type. 2086 // Because it is a pointer type, we don't have to worry about any implicit 2087 // casts here. 2088 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2089 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2090 if (PointerArgRes.isInvalid()) 2091 return true; 2092 PointerArg = PointerArgRes.get(); 2093 2094 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2095 if (!pointerType) { 2096 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2097 << PointerArg->getType() << PointerArg->getSourceRange(); 2098 return true; 2099 } 2100 2101 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2102 // task is to insert the appropriate casts into the AST. First work out just 2103 // what the appropriate type is. 2104 QualType ValType = pointerType->getPointeeType(); 2105 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2106 if (IsLdrex) 2107 AddrType.addConst(); 2108 2109 // Issue a warning if the cast is dodgy. 2110 CastKind CastNeeded = CK_NoOp; 2111 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2112 CastNeeded = CK_BitCast; 2113 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2114 << PointerArg->getType() << Context.getPointerType(AddrType) 2115 << AA_Passing << PointerArg->getSourceRange(); 2116 } 2117 2118 // Finally, do the cast and replace the argument with the corrected version. 2119 AddrType = Context.getPointerType(AddrType); 2120 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2121 if (PointerArgRes.isInvalid()) 2122 return true; 2123 PointerArg = PointerArgRes.get(); 2124 2125 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2126 2127 // In general, we allow ints, floats and pointers to be loaded and stored. 2128 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2129 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2130 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2131 << PointerArg->getType() << PointerArg->getSourceRange(); 2132 return true; 2133 } 2134 2135 // But ARM doesn't have instructions to deal with 128-bit versions. 2136 if (Context.getTypeSize(ValType) > MaxWidth) { 2137 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2138 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2139 << PointerArg->getType() << PointerArg->getSourceRange(); 2140 return true; 2141 } 2142 2143 switch (ValType.getObjCLifetime()) { 2144 case Qualifiers::OCL_None: 2145 case Qualifiers::OCL_ExplicitNone: 2146 // okay 2147 break; 2148 2149 case Qualifiers::OCL_Weak: 2150 case Qualifiers::OCL_Strong: 2151 case Qualifiers::OCL_Autoreleasing: 2152 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2153 << ValType << PointerArg->getSourceRange(); 2154 return true; 2155 } 2156 2157 if (IsLdrex) { 2158 TheCall->setType(ValType); 2159 return false; 2160 } 2161 2162 // Initialize the argument to be stored. 2163 ExprResult ValArg = TheCall->getArg(0); 2164 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2165 Context, ValType, /*consume*/ false); 2166 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2167 if (ValArg.isInvalid()) 2168 return true; 2169 TheCall->setArg(0, ValArg.get()); 2170 2171 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2172 // but the custom checker bypasses all default analysis. 2173 TheCall->setType(Context.IntTy); 2174 return false; 2175 } 2176 2177 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2178 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2179 BuiltinID == ARM::BI__builtin_arm_ldaex || 2180 BuiltinID == ARM::BI__builtin_arm_strex || 2181 BuiltinID == ARM::BI__builtin_arm_stlex) { 2182 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2183 } 2184 2185 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2186 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2187 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2188 } 2189 2190 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2191 BuiltinID == ARM::BI__builtin_arm_wsr64) 2192 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2193 2194 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2195 BuiltinID == ARM::BI__builtin_arm_rsrp || 2196 BuiltinID == ARM::BI__builtin_arm_wsr || 2197 BuiltinID == ARM::BI__builtin_arm_wsrp) 2198 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2199 2200 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2201 return true; 2202 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2203 return true; 2204 2205 // For intrinsics which take an immediate value as part of the instruction, 2206 // range check them here. 2207 // FIXME: VFP Intrinsics should error if VFP not present. 2208 switch (BuiltinID) { 2209 default: return false; 2210 case ARM::BI__builtin_arm_ssat: 2211 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2212 case ARM::BI__builtin_arm_usat: 2213 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2214 case ARM::BI__builtin_arm_ssat16: 2215 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2216 case ARM::BI__builtin_arm_usat16: 2217 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2218 case ARM::BI__builtin_arm_vcvtr_f: 2219 case ARM::BI__builtin_arm_vcvtr_d: 2220 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2221 case ARM::BI__builtin_arm_dmb: 2222 case ARM::BI__builtin_arm_dsb: 2223 case ARM::BI__builtin_arm_isb: 2224 case ARM::BI__builtin_arm_dbg: 2225 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2226 } 2227 } 2228 2229 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 2230 CallExpr *TheCall) { 2231 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2232 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2233 BuiltinID == AArch64::BI__builtin_arm_strex || 2234 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2235 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2236 } 2237 2238 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2239 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2240 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2241 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2242 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2243 } 2244 2245 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2246 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2247 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2248 2249 // Memory Tagging Extensions (MTE) Intrinsics 2250 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2251 BuiltinID == AArch64::BI__builtin_arm_addg || 2252 BuiltinID == AArch64::BI__builtin_arm_gmi || 2253 BuiltinID == AArch64::BI__builtin_arm_ldg || 2254 BuiltinID == AArch64::BI__builtin_arm_stg || 2255 BuiltinID == AArch64::BI__builtin_arm_subp) { 2256 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2257 } 2258 2259 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2260 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2261 BuiltinID == AArch64::BI__builtin_arm_wsr || 2262 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2263 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2264 2265 // Only check the valid encoding range. Any constant in this range would be 2266 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2267 // an exception for incorrect registers. This matches MSVC behavior. 2268 if (BuiltinID == AArch64::BI_ReadStatusReg || 2269 BuiltinID == AArch64::BI_WriteStatusReg) 2270 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2271 2272 if (BuiltinID == AArch64::BI__getReg) 2273 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2274 2275 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2276 return true; 2277 2278 // For intrinsics which take an immediate value as part of the instruction, 2279 // range check them here. 2280 unsigned i = 0, l = 0, u = 0; 2281 switch (BuiltinID) { 2282 default: return false; 2283 case AArch64::BI__builtin_arm_dmb: 2284 case AArch64::BI__builtin_arm_dsb: 2285 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2286 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2287 } 2288 2289 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2290 } 2291 2292 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2293 CallExpr *TheCall) { 2294 assert(BuiltinID == BPF::BI__builtin_preserve_field_info && 2295 "unexpected ARM builtin"); 2296 2297 if (checkArgCount(*this, TheCall, 2)) 2298 return true; 2299 2300 // The first argument needs to be a record field access. 2301 // If it is an array element access, we delay decision 2302 // to BPF backend to check whether the access is a 2303 // field access or not. 2304 Expr *Arg = TheCall->getArg(0); 2305 if (Arg->getType()->getAsPlaceholderType() || 2306 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2307 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2308 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2309 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2310 << 1 << Arg->getSourceRange(); 2311 return true; 2312 } 2313 2314 // The second argument needs to be a constant int 2315 llvm::APSInt Value; 2316 if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) { 2317 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2318 << 2 << Arg->getSourceRange(); 2319 return true; 2320 } 2321 2322 TheCall->setType(Context.UnsignedIntTy); 2323 return false; 2324 } 2325 2326 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2327 struct ArgInfo { 2328 uint8_t OpNum; 2329 bool IsSigned; 2330 uint8_t BitWidth; 2331 uint8_t Align; 2332 }; 2333 struct BuiltinInfo { 2334 unsigned BuiltinID; 2335 ArgInfo Infos[2]; 2336 }; 2337 2338 static BuiltinInfo Infos[] = { 2339 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2340 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2341 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2342 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2343 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2344 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2345 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2346 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2347 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2348 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2349 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2350 2351 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2352 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2353 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2354 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2355 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2356 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2357 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2358 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2359 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2360 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2361 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2362 2363 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2364 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2365 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2366 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2367 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2368 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2369 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2370 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2371 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2372 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2373 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2374 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2375 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2376 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2377 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2378 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2379 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2380 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2381 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2382 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2383 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2384 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2385 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2386 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2387 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2388 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2389 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2390 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2391 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2392 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2393 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2394 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2395 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2396 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2397 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2398 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2399 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2400 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2401 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2402 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2403 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2404 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2405 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2406 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2407 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2408 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2409 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2410 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2411 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2412 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2413 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2414 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2415 {{ 1, false, 6, 0 }} }, 2416 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2417 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2418 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2419 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2420 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2421 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2422 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2423 {{ 1, false, 5, 0 }} }, 2424 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2425 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2426 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2427 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2428 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2429 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2430 { 2, false, 5, 0 }} }, 2431 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2432 { 2, false, 6, 0 }} }, 2433 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2434 { 3, false, 5, 0 }} }, 2435 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2436 { 3, false, 6, 0 }} }, 2437 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2438 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2439 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2440 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2441 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2442 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2443 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2444 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2445 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2446 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2447 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2448 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2449 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2450 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2451 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2452 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2453 {{ 2, false, 4, 0 }, 2454 { 3, false, 5, 0 }} }, 2455 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2456 {{ 2, false, 4, 0 }, 2457 { 3, false, 5, 0 }} }, 2458 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2459 {{ 2, false, 4, 0 }, 2460 { 3, false, 5, 0 }} }, 2461 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2462 {{ 2, false, 4, 0 }, 2463 { 3, false, 5, 0 }} }, 2464 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2465 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2466 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2467 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2468 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2469 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2470 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2471 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2472 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2473 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2474 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2475 { 2, false, 5, 0 }} }, 2476 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2477 { 2, false, 6, 0 }} }, 2478 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2479 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2480 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2481 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2482 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2483 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2484 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2485 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2486 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2487 {{ 1, false, 4, 0 }} }, 2488 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2489 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2490 {{ 1, false, 4, 0 }} }, 2491 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2492 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2493 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2494 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2495 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2496 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2497 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2498 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2499 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2500 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2501 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2502 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2511 {{ 3, false, 1, 0 }} }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2516 {{ 3, false, 1, 0 }} }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2521 {{ 3, false, 1, 0 }} }, 2522 }; 2523 2524 // Use a dynamically initialized static to sort the table exactly once on 2525 // first run. 2526 static const bool SortOnce = 2527 (llvm::sort(Infos, 2528 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2529 return LHS.BuiltinID < RHS.BuiltinID; 2530 }), 2531 true); 2532 (void)SortOnce; 2533 2534 const BuiltinInfo *F = llvm::partition_point( 2535 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2536 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2537 return false; 2538 2539 bool Error = false; 2540 2541 for (const ArgInfo &A : F->Infos) { 2542 // Ignore empty ArgInfo elements. 2543 if (A.BitWidth == 0) 2544 continue; 2545 2546 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2547 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2548 if (!A.Align) { 2549 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2550 } else { 2551 unsigned M = 1 << A.Align; 2552 Min *= M; 2553 Max *= M; 2554 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2555 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2556 } 2557 } 2558 return Error; 2559 } 2560 2561 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2562 CallExpr *TheCall) { 2563 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2564 } 2565 2566 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2567 return CheckMipsBuiltinCpu(BuiltinID, TheCall) || 2568 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2569 } 2570 2571 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 2572 const TargetInfo &TI = Context.getTargetInfo(); 2573 2574 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2575 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2576 if (!TI.hasFeature("dsp")) 2577 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2578 } 2579 2580 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2581 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2582 if (!TI.hasFeature("dspr2")) 2583 return Diag(TheCall->getBeginLoc(), 2584 diag::err_mips_builtin_requires_dspr2); 2585 } 2586 2587 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2588 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2589 if (!TI.hasFeature("msa")) 2590 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2591 } 2592 2593 return false; 2594 } 2595 2596 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2597 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2598 // ordering for DSP is unspecified. MSA is ordered by the data format used 2599 // by the underlying instruction i.e., df/m, df/n and then by size. 2600 // 2601 // FIXME: The size tests here should instead be tablegen'd along with the 2602 // definitions from include/clang/Basic/BuiltinsMips.def. 2603 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2604 // be too. 2605 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2606 unsigned i = 0, l = 0, u = 0, m = 0; 2607 switch (BuiltinID) { 2608 default: return false; 2609 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2610 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2611 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2612 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2613 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2614 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2615 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2616 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2617 // df/m field. 2618 // These intrinsics take an unsigned 3 bit immediate. 2619 case Mips::BI__builtin_msa_bclri_b: 2620 case Mips::BI__builtin_msa_bnegi_b: 2621 case Mips::BI__builtin_msa_bseti_b: 2622 case Mips::BI__builtin_msa_sat_s_b: 2623 case Mips::BI__builtin_msa_sat_u_b: 2624 case Mips::BI__builtin_msa_slli_b: 2625 case Mips::BI__builtin_msa_srai_b: 2626 case Mips::BI__builtin_msa_srari_b: 2627 case Mips::BI__builtin_msa_srli_b: 2628 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2629 case Mips::BI__builtin_msa_binsli_b: 2630 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2631 // These intrinsics take an unsigned 4 bit immediate. 2632 case Mips::BI__builtin_msa_bclri_h: 2633 case Mips::BI__builtin_msa_bnegi_h: 2634 case Mips::BI__builtin_msa_bseti_h: 2635 case Mips::BI__builtin_msa_sat_s_h: 2636 case Mips::BI__builtin_msa_sat_u_h: 2637 case Mips::BI__builtin_msa_slli_h: 2638 case Mips::BI__builtin_msa_srai_h: 2639 case Mips::BI__builtin_msa_srari_h: 2640 case Mips::BI__builtin_msa_srli_h: 2641 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2642 case Mips::BI__builtin_msa_binsli_h: 2643 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2644 // These intrinsics take an unsigned 5 bit immediate. 2645 // The first block of intrinsics actually have an unsigned 5 bit field, 2646 // not a df/n field. 2647 case Mips::BI__builtin_msa_cfcmsa: 2648 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 2649 case Mips::BI__builtin_msa_clei_u_b: 2650 case Mips::BI__builtin_msa_clei_u_h: 2651 case Mips::BI__builtin_msa_clei_u_w: 2652 case Mips::BI__builtin_msa_clei_u_d: 2653 case Mips::BI__builtin_msa_clti_u_b: 2654 case Mips::BI__builtin_msa_clti_u_h: 2655 case Mips::BI__builtin_msa_clti_u_w: 2656 case Mips::BI__builtin_msa_clti_u_d: 2657 case Mips::BI__builtin_msa_maxi_u_b: 2658 case Mips::BI__builtin_msa_maxi_u_h: 2659 case Mips::BI__builtin_msa_maxi_u_w: 2660 case Mips::BI__builtin_msa_maxi_u_d: 2661 case Mips::BI__builtin_msa_mini_u_b: 2662 case Mips::BI__builtin_msa_mini_u_h: 2663 case Mips::BI__builtin_msa_mini_u_w: 2664 case Mips::BI__builtin_msa_mini_u_d: 2665 case Mips::BI__builtin_msa_addvi_b: 2666 case Mips::BI__builtin_msa_addvi_h: 2667 case Mips::BI__builtin_msa_addvi_w: 2668 case Mips::BI__builtin_msa_addvi_d: 2669 case Mips::BI__builtin_msa_bclri_w: 2670 case Mips::BI__builtin_msa_bnegi_w: 2671 case Mips::BI__builtin_msa_bseti_w: 2672 case Mips::BI__builtin_msa_sat_s_w: 2673 case Mips::BI__builtin_msa_sat_u_w: 2674 case Mips::BI__builtin_msa_slli_w: 2675 case Mips::BI__builtin_msa_srai_w: 2676 case Mips::BI__builtin_msa_srari_w: 2677 case Mips::BI__builtin_msa_srli_w: 2678 case Mips::BI__builtin_msa_srlri_w: 2679 case Mips::BI__builtin_msa_subvi_b: 2680 case Mips::BI__builtin_msa_subvi_h: 2681 case Mips::BI__builtin_msa_subvi_w: 2682 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2683 case Mips::BI__builtin_msa_binsli_w: 2684 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2685 // These intrinsics take an unsigned 6 bit immediate. 2686 case Mips::BI__builtin_msa_bclri_d: 2687 case Mips::BI__builtin_msa_bnegi_d: 2688 case Mips::BI__builtin_msa_bseti_d: 2689 case Mips::BI__builtin_msa_sat_s_d: 2690 case Mips::BI__builtin_msa_sat_u_d: 2691 case Mips::BI__builtin_msa_slli_d: 2692 case Mips::BI__builtin_msa_srai_d: 2693 case Mips::BI__builtin_msa_srari_d: 2694 case Mips::BI__builtin_msa_srli_d: 2695 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2696 case Mips::BI__builtin_msa_binsli_d: 2697 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2698 // These intrinsics take a signed 5 bit immediate. 2699 case Mips::BI__builtin_msa_ceqi_b: 2700 case Mips::BI__builtin_msa_ceqi_h: 2701 case Mips::BI__builtin_msa_ceqi_w: 2702 case Mips::BI__builtin_msa_ceqi_d: 2703 case Mips::BI__builtin_msa_clti_s_b: 2704 case Mips::BI__builtin_msa_clti_s_h: 2705 case Mips::BI__builtin_msa_clti_s_w: 2706 case Mips::BI__builtin_msa_clti_s_d: 2707 case Mips::BI__builtin_msa_clei_s_b: 2708 case Mips::BI__builtin_msa_clei_s_h: 2709 case Mips::BI__builtin_msa_clei_s_w: 2710 case Mips::BI__builtin_msa_clei_s_d: 2711 case Mips::BI__builtin_msa_maxi_s_b: 2712 case Mips::BI__builtin_msa_maxi_s_h: 2713 case Mips::BI__builtin_msa_maxi_s_w: 2714 case Mips::BI__builtin_msa_maxi_s_d: 2715 case Mips::BI__builtin_msa_mini_s_b: 2716 case Mips::BI__builtin_msa_mini_s_h: 2717 case Mips::BI__builtin_msa_mini_s_w: 2718 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2719 // These intrinsics take an unsigned 8 bit immediate. 2720 case Mips::BI__builtin_msa_andi_b: 2721 case Mips::BI__builtin_msa_nori_b: 2722 case Mips::BI__builtin_msa_ori_b: 2723 case Mips::BI__builtin_msa_shf_b: 2724 case Mips::BI__builtin_msa_shf_h: 2725 case Mips::BI__builtin_msa_shf_w: 2726 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2727 case Mips::BI__builtin_msa_bseli_b: 2728 case Mips::BI__builtin_msa_bmnzi_b: 2729 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2730 // df/n format 2731 // These intrinsics take an unsigned 4 bit immediate. 2732 case Mips::BI__builtin_msa_copy_s_b: 2733 case Mips::BI__builtin_msa_copy_u_b: 2734 case Mips::BI__builtin_msa_insve_b: 2735 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2736 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2737 // These intrinsics take an unsigned 3 bit immediate. 2738 case Mips::BI__builtin_msa_copy_s_h: 2739 case Mips::BI__builtin_msa_copy_u_h: 2740 case Mips::BI__builtin_msa_insve_h: 2741 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2742 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2743 // These intrinsics take an unsigned 2 bit immediate. 2744 case Mips::BI__builtin_msa_copy_s_w: 2745 case Mips::BI__builtin_msa_copy_u_w: 2746 case Mips::BI__builtin_msa_insve_w: 2747 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2748 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2749 // These intrinsics take an unsigned 1 bit immediate. 2750 case Mips::BI__builtin_msa_copy_s_d: 2751 case Mips::BI__builtin_msa_copy_u_d: 2752 case Mips::BI__builtin_msa_insve_d: 2753 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2754 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2755 // Memory offsets and immediate loads. 2756 // These intrinsics take a signed 10 bit immediate. 2757 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2758 case Mips::BI__builtin_msa_ldi_h: 2759 case Mips::BI__builtin_msa_ldi_w: 2760 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2761 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 2762 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 2763 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 2764 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 2765 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 2766 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 2767 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 2768 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 2769 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 2770 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 2771 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 2772 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 2773 } 2774 2775 if (!m) 2776 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2777 2778 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2779 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2780 } 2781 2782 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2783 unsigned i = 0, l = 0, u = 0; 2784 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2785 BuiltinID == PPC::BI__builtin_divdeu || 2786 BuiltinID == PPC::BI__builtin_bpermd; 2787 bool IsTarget64Bit = Context.getTargetInfo() 2788 .getTypeWidth(Context 2789 .getTargetInfo() 2790 .getIntPtrType()) == 64; 2791 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2792 BuiltinID == PPC::BI__builtin_divweu || 2793 BuiltinID == PPC::BI__builtin_divde || 2794 BuiltinID == PPC::BI__builtin_divdeu; 2795 2796 if (Is64BitBltin && !IsTarget64Bit) 2797 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 2798 << TheCall->getSourceRange(); 2799 2800 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2801 (BuiltinID == PPC::BI__builtin_bpermd && 2802 !Context.getTargetInfo().hasFeature("bpermd"))) 2803 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2804 << TheCall->getSourceRange(); 2805 2806 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 2807 if (!Context.getTargetInfo().hasFeature("vsx")) 2808 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2809 << TheCall->getSourceRange(); 2810 return false; 2811 }; 2812 2813 switch (BuiltinID) { 2814 default: return false; 2815 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 2816 case PPC::BI__builtin_altivec_crypto_vshasigmad: 2817 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2818 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2819 case PPC::BI__builtin_altivec_dss: 2820 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 2821 case PPC::BI__builtin_tbegin: 2822 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 2823 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 2824 case PPC::BI__builtin_tabortwc: 2825 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 2826 case PPC::BI__builtin_tabortwci: 2827 case PPC::BI__builtin_tabortdci: 2828 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 2829 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 2830 case PPC::BI__builtin_altivec_dst: 2831 case PPC::BI__builtin_altivec_dstt: 2832 case PPC::BI__builtin_altivec_dstst: 2833 case PPC::BI__builtin_altivec_dststt: 2834 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 2835 case PPC::BI__builtin_vsx_xxpermdi: 2836 case PPC::BI__builtin_vsx_xxsldwi: 2837 return SemaBuiltinVSX(TheCall); 2838 case PPC::BI__builtin_unpack_vector_int128: 2839 return SemaVSXCheck(TheCall) || 2840 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2841 case PPC::BI__builtin_pack_vector_int128: 2842 return SemaVSXCheck(TheCall); 2843 } 2844 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2845 } 2846 2847 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 2848 CallExpr *TheCall) { 2849 if (BuiltinID == SystemZ::BI__builtin_tabort) { 2850 Expr *Arg = TheCall->getArg(0); 2851 llvm::APSInt AbortCode(32); 2852 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 2853 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 2854 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 2855 << Arg->getSourceRange(); 2856 } 2857 2858 // For intrinsics which take an immediate value as part of the instruction, 2859 // range check them here. 2860 unsigned i = 0, l = 0, u = 0; 2861 switch (BuiltinID) { 2862 default: return false; 2863 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 2864 case SystemZ::BI__builtin_s390_verimb: 2865 case SystemZ::BI__builtin_s390_verimh: 2866 case SystemZ::BI__builtin_s390_verimf: 2867 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 2868 case SystemZ::BI__builtin_s390_vfaeb: 2869 case SystemZ::BI__builtin_s390_vfaeh: 2870 case SystemZ::BI__builtin_s390_vfaef: 2871 case SystemZ::BI__builtin_s390_vfaebs: 2872 case SystemZ::BI__builtin_s390_vfaehs: 2873 case SystemZ::BI__builtin_s390_vfaefs: 2874 case SystemZ::BI__builtin_s390_vfaezb: 2875 case SystemZ::BI__builtin_s390_vfaezh: 2876 case SystemZ::BI__builtin_s390_vfaezf: 2877 case SystemZ::BI__builtin_s390_vfaezbs: 2878 case SystemZ::BI__builtin_s390_vfaezhs: 2879 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 2880 case SystemZ::BI__builtin_s390_vfisb: 2881 case SystemZ::BI__builtin_s390_vfidb: 2882 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 2883 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2884 case SystemZ::BI__builtin_s390_vftcisb: 2885 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 2886 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 2887 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 2888 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 2889 case SystemZ::BI__builtin_s390_vstrcb: 2890 case SystemZ::BI__builtin_s390_vstrch: 2891 case SystemZ::BI__builtin_s390_vstrcf: 2892 case SystemZ::BI__builtin_s390_vstrczb: 2893 case SystemZ::BI__builtin_s390_vstrczh: 2894 case SystemZ::BI__builtin_s390_vstrczf: 2895 case SystemZ::BI__builtin_s390_vstrcbs: 2896 case SystemZ::BI__builtin_s390_vstrchs: 2897 case SystemZ::BI__builtin_s390_vstrcfs: 2898 case SystemZ::BI__builtin_s390_vstrczbs: 2899 case SystemZ::BI__builtin_s390_vstrczhs: 2900 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 2901 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 2902 case SystemZ::BI__builtin_s390_vfminsb: 2903 case SystemZ::BI__builtin_s390_vfmaxsb: 2904 case SystemZ::BI__builtin_s390_vfmindb: 2905 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 2906 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 2907 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 2908 } 2909 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2910 } 2911 2912 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 2913 /// This checks that the target supports __builtin_cpu_supports and 2914 /// that the string argument is constant and valid. 2915 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 2916 Expr *Arg = TheCall->getArg(0); 2917 2918 // Check if the argument is a string literal. 2919 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2920 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 2921 << Arg->getSourceRange(); 2922 2923 // Check the contents of the string. 2924 StringRef Feature = 2925 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2926 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 2927 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 2928 << Arg->getSourceRange(); 2929 return false; 2930 } 2931 2932 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 2933 /// This checks that the target supports __builtin_cpu_is and 2934 /// that the string argument is constant and valid. 2935 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 2936 Expr *Arg = TheCall->getArg(0); 2937 2938 // Check if the argument is a string literal. 2939 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2940 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 2941 << Arg->getSourceRange(); 2942 2943 // Check the contents of the string. 2944 StringRef Feature = 2945 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2946 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 2947 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 2948 << Arg->getSourceRange(); 2949 return false; 2950 } 2951 2952 // Check if the rounding mode is legal. 2953 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 2954 // Indicates if this instruction has rounding control or just SAE. 2955 bool HasRC = false; 2956 2957 unsigned ArgNum = 0; 2958 switch (BuiltinID) { 2959 default: 2960 return false; 2961 case X86::BI__builtin_ia32_vcvttsd2si32: 2962 case X86::BI__builtin_ia32_vcvttsd2si64: 2963 case X86::BI__builtin_ia32_vcvttsd2usi32: 2964 case X86::BI__builtin_ia32_vcvttsd2usi64: 2965 case X86::BI__builtin_ia32_vcvttss2si32: 2966 case X86::BI__builtin_ia32_vcvttss2si64: 2967 case X86::BI__builtin_ia32_vcvttss2usi32: 2968 case X86::BI__builtin_ia32_vcvttss2usi64: 2969 ArgNum = 1; 2970 break; 2971 case X86::BI__builtin_ia32_maxpd512: 2972 case X86::BI__builtin_ia32_maxps512: 2973 case X86::BI__builtin_ia32_minpd512: 2974 case X86::BI__builtin_ia32_minps512: 2975 ArgNum = 2; 2976 break; 2977 case X86::BI__builtin_ia32_cvtps2pd512_mask: 2978 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 2979 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 2980 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 2981 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 2982 case X86::BI__builtin_ia32_cvttps2dq512_mask: 2983 case X86::BI__builtin_ia32_cvttps2qq512_mask: 2984 case X86::BI__builtin_ia32_cvttps2udq512_mask: 2985 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 2986 case X86::BI__builtin_ia32_exp2pd_mask: 2987 case X86::BI__builtin_ia32_exp2ps_mask: 2988 case X86::BI__builtin_ia32_getexppd512_mask: 2989 case X86::BI__builtin_ia32_getexpps512_mask: 2990 case X86::BI__builtin_ia32_rcp28pd_mask: 2991 case X86::BI__builtin_ia32_rcp28ps_mask: 2992 case X86::BI__builtin_ia32_rsqrt28pd_mask: 2993 case X86::BI__builtin_ia32_rsqrt28ps_mask: 2994 case X86::BI__builtin_ia32_vcomisd: 2995 case X86::BI__builtin_ia32_vcomiss: 2996 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 2997 ArgNum = 3; 2998 break; 2999 case X86::BI__builtin_ia32_cmppd512_mask: 3000 case X86::BI__builtin_ia32_cmpps512_mask: 3001 case X86::BI__builtin_ia32_cmpsd_mask: 3002 case X86::BI__builtin_ia32_cmpss_mask: 3003 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3004 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3005 case X86::BI__builtin_ia32_getexpss128_round_mask: 3006 case X86::BI__builtin_ia32_getmantpd512_mask: 3007 case X86::BI__builtin_ia32_getmantps512_mask: 3008 case X86::BI__builtin_ia32_maxsd_round_mask: 3009 case X86::BI__builtin_ia32_maxss_round_mask: 3010 case X86::BI__builtin_ia32_minsd_round_mask: 3011 case X86::BI__builtin_ia32_minss_round_mask: 3012 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3013 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3014 case X86::BI__builtin_ia32_reducepd512_mask: 3015 case X86::BI__builtin_ia32_reduceps512_mask: 3016 case X86::BI__builtin_ia32_rndscalepd_mask: 3017 case X86::BI__builtin_ia32_rndscaleps_mask: 3018 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3019 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3020 ArgNum = 4; 3021 break; 3022 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3023 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3024 case X86::BI__builtin_ia32_fixupimmps512_mask: 3025 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3026 case X86::BI__builtin_ia32_fixupimmsd_mask: 3027 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3028 case X86::BI__builtin_ia32_fixupimmss_mask: 3029 case X86::BI__builtin_ia32_fixupimmss_maskz: 3030 case X86::BI__builtin_ia32_getmantsd_round_mask: 3031 case X86::BI__builtin_ia32_getmantss_round_mask: 3032 case X86::BI__builtin_ia32_rangepd512_mask: 3033 case X86::BI__builtin_ia32_rangeps512_mask: 3034 case X86::BI__builtin_ia32_rangesd128_round_mask: 3035 case X86::BI__builtin_ia32_rangess128_round_mask: 3036 case X86::BI__builtin_ia32_reducesd_mask: 3037 case X86::BI__builtin_ia32_reducess_mask: 3038 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3039 case X86::BI__builtin_ia32_rndscaless_round_mask: 3040 ArgNum = 5; 3041 break; 3042 case X86::BI__builtin_ia32_vcvtsd2si64: 3043 case X86::BI__builtin_ia32_vcvtsd2si32: 3044 case X86::BI__builtin_ia32_vcvtsd2usi32: 3045 case X86::BI__builtin_ia32_vcvtsd2usi64: 3046 case X86::BI__builtin_ia32_vcvtss2si32: 3047 case X86::BI__builtin_ia32_vcvtss2si64: 3048 case X86::BI__builtin_ia32_vcvtss2usi32: 3049 case X86::BI__builtin_ia32_vcvtss2usi64: 3050 case X86::BI__builtin_ia32_sqrtpd512: 3051 case X86::BI__builtin_ia32_sqrtps512: 3052 ArgNum = 1; 3053 HasRC = true; 3054 break; 3055 case X86::BI__builtin_ia32_addpd512: 3056 case X86::BI__builtin_ia32_addps512: 3057 case X86::BI__builtin_ia32_divpd512: 3058 case X86::BI__builtin_ia32_divps512: 3059 case X86::BI__builtin_ia32_mulpd512: 3060 case X86::BI__builtin_ia32_mulps512: 3061 case X86::BI__builtin_ia32_subpd512: 3062 case X86::BI__builtin_ia32_subps512: 3063 case X86::BI__builtin_ia32_cvtsi2sd64: 3064 case X86::BI__builtin_ia32_cvtsi2ss32: 3065 case X86::BI__builtin_ia32_cvtsi2ss64: 3066 case X86::BI__builtin_ia32_cvtusi2sd64: 3067 case X86::BI__builtin_ia32_cvtusi2ss32: 3068 case X86::BI__builtin_ia32_cvtusi2ss64: 3069 ArgNum = 2; 3070 HasRC = true; 3071 break; 3072 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3073 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3074 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3075 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3076 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3077 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3078 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3079 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3080 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3081 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3082 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3083 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3084 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3085 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3086 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3087 ArgNum = 3; 3088 HasRC = true; 3089 break; 3090 case X86::BI__builtin_ia32_addss_round_mask: 3091 case X86::BI__builtin_ia32_addsd_round_mask: 3092 case X86::BI__builtin_ia32_divss_round_mask: 3093 case X86::BI__builtin_ia32_divsd_round_mask: 3094 case X86::BI__builtin_ia32_mulss_round_mask: 3095 case X86::BI__builtin_ia32_mulsd_round_mask: 3096 case X86::BI__builtin_ia32_subss_round_mask: 3097 case X86::BI__builtin_ia32_subsd_round_mask: 3098 case X86::BI__builtin_ia32_scalefpd512_mask: 3099 case X86::BI__builtin_ia32_scalefps512_mask: 3100 case X86::BI__builtin_ia32_scalefsd_round_mask: 3101 case X86::BI__builtin_ia32_scalefss_round_mask: 3102 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3103 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3104 case X86::BI__builtin_ia32_sqrtss_round_mask: 3105 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3106 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3107 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3108 case X86::BI__builtin_ia32_vfmaddss3_mask: 3109 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3110 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3111 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3112 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3113 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3114 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3115 case X86::BI__builtin_ia32_vfmaddps512_mask: 3116 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3117 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3118 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3119 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3120 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3121 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3122 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3123 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3124 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3125 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3126 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3127 ArgNum = 4; 3128 HasRC = true; 3129 break; 3130 } 3131 3132 llvm::APSInt Result; 3133 3134 // We can't check the value of a dependent argument. 3135 Expr *Arg = TheCall->getArg(ArgNum); 3136 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3137 return false; 3138 3139 // Check constant-ness first. 3140 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3141 return true; 3142 3143 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3144 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3145 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3146 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3147 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3148 Result == 8/*ROUND_NO_EXC*/ || 3149 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3150 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3151 return false; 3152 3153 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3154 << Arg->getSourceRange(); 3155 } 3156 3157 // Check if the gather/scatter scale is legal. 3158 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3159 CallExpr *TheCall) { 3160 unsigned ArgNum = 0; 3161 switch (BuiltinID) { 3162 default: 3163 return false; 3164 case X86::BI__builtin_ia32_gatherpfdpd: 3165 case X86::BI__builtin_ia32_gatherpfdps: 3166 case X86::BI__builtin_ia32_gatherpfqpd: 3167 case X86::BI__builtin_ia32_gatherpfqps: 3168 case X86::BI__builtin_ia32_scatterpfdpd: 3169 case X86::BI__builtin_ia32_scatterpfdps: 3170 case X86::BI__builtin_ia32_scatterpfqpd: 3171 case X86::BI__builtin_ia32_scatterpfqps: 3172 ArgNum = 3; 3173 break; 3174 case X86::BI__builtin_ia32_gatherd_pd: 3175 case X86::BI__builtin_ia32_gatherd_pd256: 3176 case X86::BI__builtin_ia32_gatherq_pd: 3177 case X86::BI__builtin_ia32_gatherq_pd256: 3178 case X86::BI__builtin_ia32_gatherd_ps: 3179 case X86::BI__builtin_ia32_gatherd_ps256: 3180 case X86::BI__builtin_ia32_gatherq_ps: 3181 case X86::BI__builtin_ia32_gatherq_ps256: 3182 case X86::BI__builtin_ia32_gatherd_q: 3183 case X86::BI__builtin_ia32_gatherd_q256: 3184 case X86::BI__builtin_ia32_gatherq_q: 3185 case X86::BI__builtin_ia32_gatherq_q256: 3186 case X86::BI__builtin_ia32_gatherd_d: 3187 case X86::BI__builtin_ia32_gatherd_d256: 3188 case X86::BI__builtin_ia32_gatherq_d: 3189 case X86::BI__builtin_ia32_gatherq_d256: 3190 case X86::BI__builtin_ia32_gather3div2df: 3191 case X86::BI__builtin_ia32_gather3div2di: 3192 case X86::BI__builtin_ia32_gather3div4df: 3193 case X86::BI__builtin_ia32_gather3div4di: 3194 case X86::BI__builtin_ia32_gather3div4sf: 3195 case X86::BI__builtin_ia32_gather3div4si: 3196 case X86::BI__builtin_ia32_gather3div8sf: 3197 case X86::BI__builtin_ia32_gather3div8si: 3198 case X86::BI__builtin_ia32_gather3siv2df: 3199 case X86::BI__builtin_ia32_gather3siv2di: 3200 case X86::BI__builtin_ia32_gather3siv4df: 3201 case X86::BI__builtin_ia32_gather3siv4di: 3202 case X86::BI__builtin_ia32_gather3siv4sf: 3203 case X86::BI__builtin_ia32_gather3siv4si: 3204 case X86::BI__builtin_ia32_gather3siv8sf: 3205 case X86::BI__builtin_ia32_gather3siv8si: 3206 case X86::BI__builtin_ia32_gathersiv8df: 3207 case X86::BI__builtin_ia32_gathersiv16sf: 3208 case X86::BI__builtin_ia32_gatherdiv8df: 3209 case X86::BI__builtin_ia32_gatherdiv16sf: 3210 case X86::BI__builtin_ia32_gathersiv8di: 3211 case X86::BI__builtin_ia32_gathersiv16si: 3212 case X86::BI__builtin_ia32_gatherdiv8di: 3213 case X86::BI__builtin_ia32_gatherdiv16si: 3214 case X86::BI__builtin_ia32_scatterdiv2df: 3215 case X86::BI__builtin_ia32_scatterdiv2di: 3216 case X86::BI__builtin_ia32_scatterdiv4df: 3217 case X86::BI__builtin_ia32_scatterdiv4di: 3218 case X86::BI__builtin_ia32_scatterdiv4sf: 3219 case X86::BI__builtin_ia32_scatterdiv4si: 3220 case X86::BI__builtin_ia32_scatterdiv8sf: 3221 case X86::BI__builtin_ia32_scatterdiv8si: 3222 case X86::BI__builtin_ia32_scattersiv2df: 3223 case X86::BI__builtin_ia32_scattersiv2di: 3224 case X86::BI__builtin_ia32_scattersiv4df: 3225 case X86::BI__builtin_ia32_scattersiv4di: 3226 case X86::BI__builtin_ia32_scattersiv4sf: 3227 case X86::BI__builtin_ia32_scattersiv4si: 3228 case X86::BI__builtin_ia32_scattersiv8sf: 3229 case X86::BI__builtin_ia32_scattersiv8si: 3230 case X86::BI__builtin_ia32_scattersiv8df: 3231 case X86::BI__builtin_ia32_scattersiv16sf: 3232 case X86::BI__builtin_ia32_scatterdiv8df: 3233 case X86::BI__builtin_ia32_scatterdiv16sf: 3234 case X86::BI__builtin_ia32_scattersiv8di: 3235 case X86::BI__builtin_ia32_scattersiv16si: 3236 case X86::BI__builtin_ia32_scatterdiv8di: 3237 case X86::BI__builtin_ia32_scatterdiv16si: 3238 ArgNum = 4; 3239 break; 3240 } 3241 3242 llvm::APSInt Result; 3243 3244 // We can't check the value of a dependent argument. 3245 Expr *Arg = TheCall->getArg(ArgNum); 3246 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3247 return false; 3248 3249 // Check constant-ness first. 3250 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3251 return true; 3252 3253 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3254 return false; 3255 3256 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3257 << Arg->getSourceRange(); 3258 } 3259 3260 static bool isX86_32Builtin(unsigned BuiltinID) { 3261 // These builtins only work on x86-32 targets. 3262 switch (BuiltinID) { 3263 case X86::BI__builtin_ia32_readeflags_u32: 3264 case X86::BI__builtin_ia32_writeeflags_u32: 3265 return true; 3266 } 3267 3268 return false; 3269 } 3270 3271 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3272 if (BuiltinID == X86::BI__builtin_cpu_supports) 3273 return SemaBuiltinCpuSupports(*this, TheCall); 3274 3275 if (BuiltinID == X86::BI__builtin_cpu_is) 3276 return SemaBuiltinCpuIs(*this, TheCall); 3277 3278 // Check for 32-bit only builtins on a 64-bit target. 3279 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3280 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3281 return Diag(TheCall->getCallee()->getBeginLoc(), 3282 diag::err_32_bit_builtin_64_bit_tgt); 3283 3284 // If the intrinsic has rounding or SAE make sure its valid. 3285 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3286 return true; 3287 3288 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3289 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3290 return true; 3291 3292 // For intrinsics which take an immediate value as part of the instruction, 3293 // range check them here. 3294 int i = 0, l = 0, u = 0; 3295 switch (BuiltinID) { 3296 default: 3297 return false; 3298 case X86::BI__builtin_ia32_vec_ext_v2si: 3299 case X86::BI__builtin_ia32_vec_ext_v2di: 3300 case X86::BI__builtin_ia32_vextractf128_pd256: 3301 case X86::BI__builtin_ia32_vextractf128_ps256: 3302 case X86::BI__builtin_ia32_vextractf128_si256: 3303 case X86::BI__builtin_ia32_extract128i256: 3304 case X86::BI__builtin_ia32_extractf64x4_mask: 3305 case X86::BI__builtin_ia32_extracti64x4_mask: 3306 case X86::BI__builtin_ia32_extractf32x8_mask: 3307 case X86::BI__builtin_ia32_extracti32x8_mask: 3308 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3309 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3310 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3311 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3312 i = 1; l = 0; u = 1; 3313 break; 3314 case X86::BI__builtin_ia32_vec_set_v2di: 3315 case X86::BI__builtin_ia32_vinsertf128_pd256: 3316 case X86::BI__builtin_ia32_vinsertf128_ps256: 3317 case X86::BI__builtin_ia32_vinsertf128_si256: 3318 case X86::BI__builtin_ia32_insert128i256: 3319 case X86::BI__builtin_ia32_insertf32x8: 3320 case X86::BI__builtin_ia32_inserti32x8: 3321 case X86::BI__builtin_ia32_insertf64x4: 3322 case X86::BI__builtin_ia32_inserti64x4: 3323 case X86::BI__builtin_ia32_insertf64x2_256: 3324 case X86::BI__builtin_ia32_inserti64x2_256: 3325 case X86::BI__builtin_ia32_insertf32x4_256: 3326 case X86::BI__builtin_ia32_inserti32x4_256: 3327 i = 2; l = 0; u = 1; 3328 break; 3329 case X86::BI__builtin_ia32_vpermilpd: 3330 case X86::BI__builtin_ia32_vec_ext_v4hi: 3331 case X86::BI__builtin_ia32_vec_ext_v4si: 3332 case X86::BI__builtin_ia32_vec_ext_v4sf: 3333 case X86::BI__builtin_ia32_vec_ext_v4di: 3334 case X86::BI__builtin_ia32_extractf32x4_mask: 3335 case X86::BI__builtin_ia32_extracti32x4_mask: 3336 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3337 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3338 i = 1; l = 0; u = 3; 3339 break; 3340 case X86::BI_mm_prefetch: 3341 case X86::BI__builtin_ia32_vec_ext_v8hi: 3342 case X86::BI__builtin_ia32_vec_ext_v8si: 3343 i = 1; l = 0; u = 7; 3344 break; 3345 case X86::BI__builtin_ia32_sha1rnds4: 3346 case X86::BI__builtin_ia32_blendpd: 3347 case X86::BI__builtin_ia32_shufpd: 3348 case X86::BI__builtin_ia32_vec_set_v4hi: 3349 case X86::BI__builtin_ia32_vec_set_v4si: 3350 case X86::BI__builtin_ia32_vec_set_v4di: 3351 case X86::BI__builtin_ia32_shuf_f32x4_256: 3352 case X86::BI__builtin_ia32_shuf_f64x2_256: 3353 case X86::BI__builtin_ia32_shuf_i32x4_256: 3354 case X86::BI__builtin_ia32_shuf_i64x2_256: 3355 case X86::BI__builtin_ia32_insertf64x2_512: 3356 case X86::BI__builtin_ia32_inserti64x2_512: 3357 case X86::BI__builtin_ia32_insertf32x4: 3358 case X86::BI__builtin_ia32_inserti32x4: 3359 i = 2; l = 0; u = 3; 3360 break; 3361 case X86::BI__builtin_ia32_vpermil2pd: 3362 case X86::BI__builtin_ia32_vpermil2pd256: 3363 case X86::BI__builtin_ia32_vpermil2ps: 3364 case X86::BI__builtin_ia32_vpermil2ps256: 3365 i = 3; l = 0; u = 3; 3366 break; 3367 case X86::BI__builtin_ia32_cmpb128_mask: 3368 case X86::BI__builtin_ia32_cmpw128_mask: 3369 case X86::BI__builtin_ia32_cmpd128_mask: 3370 case X86::BI__builtin_ia32_cmpq128_mask: 3371 case X86::BI__builtin_ia32_cmpb256_mask: 3372 case X86::BI__builtin_ia32_cmpw256_mask: 3373 case X86::BI__builtin_ia32_cmpd256_mask: 3374 case X86::BI__builtin_ia32_cmpq256_mask: 3375 case X86::BI__builtin_ia32_cmpb512_mask: 3376 case X86::BI__builtin_ia32_cmpw512_mask: 3377 case X86::BI__builtin_ia32_cmpd512_mask: 3378 case X86::BI__builtin_ia32_cmpq512_mask: 3379 case X86::BI__builtin_ia32_ucmpb128_mask: 3380 case X86::BI__builtin_ia32_ucmpw128_mask: 3381 case X86::BI__builtin_ia32_ucmpd128_mask: 3382 case X86::BI__builtin_ia32_ucmpq128_mask: 3383 case X86::BI__builtin_ia32_ucmpb256_mask: 3384 case X86::BI__builtin_ia32_ucmpw256_mask: 3385 case X86::BI__builtin_ia32_ucmpd256_mask: 3386 case X86::BI__builtin_ia32_ucmpq256_mask: 3387 case X86::BI__builtin_ia32_ucmpb512_mask: 3388 case X86::BI__builtin_ia32_ucmpw512_mask: 3389 case X86::BI__builtin_ia32_ucmpd512_mask: 3390 case X86::BI__builtin_ia32_ucmpq512_mask: 3391 case X86::BI__builtin_ia32_vpcomub: 3392 case X86::BI__builtin_ia32_vpcomuw: 3393 case X86::BI__builtin_ia32_vpcomud: 3394 case X86::BI__builtin_ia32_vpcomuq: 3395 case X86::BI__builtin_ia32_vpcomb: 3396 case X86::BI__builtin_ia32_vpcomw: 3397 case X86::BI__builtin_ia32_vpcomd: 3398 case X86::BI__builtin_ia32_vpcomq: 3399 case X86::BI__builtin_ia32_vec_set_v8hi: 3400 case X86::BI__builtin_ia32_vec_set_v8si: 3401 i = 2; l = 0; u = 7; 3402 break; 3403 case X86::BI__builtin_ia32_vpermilpd256: 3404 case X86::BI__builtin_ia32_roundps: 3405 case X86::BI__builtin_ia32_roundpd: 3406 case X86::BI__builtin_ia32_roundps256: 3407 case X86::BI__builtin_ia32_roundpd256: 3408 case X86::BI__builtin_ia32_getmantpd128_mask: 3409 case X86::BI__builtin_ia32_getmantpd256_mask: 3410 case X86::BI__builtin_ia32_getmantps128_mask: 3411 case X86::BI__builtin_ia32_getmantps256_mask: 3412 case X86::BI__builtin_ia32_getmantpd512_mask: 3413 case X86::BI__builtin_ia32_getmantps512_mask: 3414 case X86::BI__builtin_ia32_vec_ext_v16qi: 3415 case X86::BI__builtin_ia32_vec_ext_v16hi: 3416 i = 1; l = 0; u = 15; 3417 break; 3418 case X86::BI__builtin_ia32_pblendd128: 3419 case X86::BI__builtin_ia32_blendps: 3420 case X86::BI__builtin_ia32_blendpd256: 3421 case X86::BI__builtin_ia32_shufpd256: 3422 case X86::BI__builtin_ia32_roundss: 3423 case X86::BI__builtin_ia32_roundsd: 3424 case X86::BI__builtin_ia32_rangepd128_mask: 3425 case X86::BI__builtin_ia32_rangepd256_mask: 3426 case X86::BI__builtin_ia32_rangepd512_mask: 3427 case X86::BI__builtin_ia32_rangeps128_mask: 3428 case X86::BI__builtin_ia32_rangeps256_mask: 3429 case X86::BI__builtin_ia32_rangeps512_mask: 3430 case X86::BI__builtin_ia32_getmantsd_round_mask: 3431 case X86::BI__builtin_ia32_getmantss_round_mask: 3432 case X86::BI__builtin_ia32_vec_set_v16qi: 3433 case X86::BI__builtin_ia32_vec_set_v16hi: 3434 i = 2; l = 0; u = 15; 3435 break; 3436 case X86::BI__builtin_ia32_vec_ext_v32qi: 3437 i = 1; l = 0; u = 31; 3438 break; 3439 case X86::BI__builtin_ia32_cmpps: 3440 case X86::BI__builtin_ia32_cmpss: 3441 case X86::BI__builtin_ia32_cmppd: 3442 case X86::BI__builtin_ia32_cmpsd: 3443 case X86::BI__builtin_ia32_cmpps256: 3444 case X86::BI__builtin_ia32_cmppd256: 3445 case X86::BI__builtin_ia32_cmpps128_mask: 3446 case X86::BI__builtin_ia32_cmppd128_mask: 3447 case X86::BI__builtin_ia32_cmpps256_mask: 3448 case X86::BI__builtin_ia32_cmppd256_mask: 3449 case X86::BI__builtin_ia32_cmpps512_mask: 3450 case X86::BI__builtin_ia32_cmppd512_mask: 3451 case X86::BI__builtin_ia32_cmpsd_mask: 3452 case X86::BI__builtin_ia32_cmpss_mask: 3453 case X86::BI__builtin_ia32_vec_set_v32qi: 3454 i = 2; l = 0; u = 31; 3455 break; 3456 case X86::BI__builtin_ia32_permdf256: 3457 case X86::BI__builtin_ia32_permdi256: 3458 case X86::BI__builtin_ia32_permdf512: 3459 case X86::BI__builtin_ia32_permdi512: 3460 case X86::BI__builtin_ia32_vpermilps: 3461 case X86::BI__builtin_ia32_vpermilps256: 3462 case X86::BI__builtin_ia32_vpermilpd512: 3463 case X86::BI__builtin_ia32_vpermilps512: 3464 case X86::BI__builtin_ia32_pshufd: 3465 case X86::BI__builtin_ia32_pshufd256: 3466 case X86::BI__builtin_ia32_pshufd512: 3467 case X86::BI__builtin_ia32_pshufhw: 3468 case X86::BI__builtin_ia32_pshufhw256: 3469 case X86::BI__builtin_ia32_pshufhw512: 3470 case X86::BI__builtin_ia32_pshuflw: 3471 case X86::BI__builtin_ia32_pshuflw256: 3472 case X86::BI__builtin_ia32_pshuflw512: 3473 case X86::BI__builtin_ia32_vcvtps2ph: 3474 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3475 case X86::BI__builtin_ia32_vcvtps2ph256: 3476 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3477 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3478 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3479 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3480 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3481 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3482 case X86::BI__builtin_ia32_rndscaleps_mask: 3483 case X86::BI__builtin_ia32_rndscalepd_mask: 3484 case X86::BI__builtin_ia32_reducepd128_mask: 3485 case X86::BI__builtin_ia32_reducepd256_mask: 3486 case X86::BI__builtin_ia32_reducepd512_mask: 3487 case X86::BI__builtin_ia32_reduceps128_mask: 3488 case X86::BI__builtin_ia32_reduceps256_mask: 3489 case X86::BI__builtin_ia32_reduceps512_mask: 3490 case X86::BI__builtin_ia32_prold512: 3491 case X86::BI__builtin_ia32_prolq512: 3492 case X86::BI__builtin_ia32_prold128: 3493 case X86::BI__builtin_ia32_prold256: 3494 case X86::BI__builtin_ia32_prolq128: 3495 case X86::BI__builtin_ia32_prolq256: 3496 case X86::BI__builtin_ia32_prord512: 3497 case X86::BI__builtin_ia32_prorq512: 3498 case X86::BI__builtin_ia32_prord128: 3499 case X86::BI__builtin_ia32_prord256: 3500 case X86::BI__builtin_ia32_prorq128: 3501 case X86::BI__builtin_ia32_prorq256: 3502 case X86::BI__builtin_ia32_fpclasspd128_mask: 3503 case X86::BI__builtin_ia32_fpclasspd256_mask: 3504 case X86::BI__builtin_ia32_fpclassps128_mask: 3505 case X86::BI__builtin_ia32_fpclassps256_mask: 3506 case X86::BI__builtin_ia32_fpclassps512_mask: 3507 case X86::BI__builtin_ia32_fpclasspd512_mask: 3508 case X86::BI__builtin_ia32_fpclasssd_mask: 3509 case X86::BI__builtin_ia32_fpclassss_mask: 3510 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3511 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3512 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3513 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3514 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3515 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3516 case X86::BI__builtin_ia32_kshiftliqi: 3517 case X86::BI__builtin_ia32_kshiftlihi: 3518 case X86::BI__builtin_ia32_kshiftlisi: 3519 case X86::BI__builtin_ia32_kshiftlidi: 3520 case X86::BI__builtin_ia32_kshiftriqi: 3521 case X86::BI__builtin_ia32_kshiftrihi: 3522 case X86::BI__builtin_ia32_kshiftrisi: 3523 case X86::BI__builtin_ia32_kshiftridi: 3524 i = 1; l = 0; u = 255; 3525 break; 3526 case X86::BI__builtin_ia32_vperm2f128_pd256: 3527 case X86::BI__builtin_ia32_vperm2f128_ps256: 3528 case X86::BI__builtin_ia32_vperm2f128_si256: 3529 case X86::BI__builtin_ia32_permti256: 3530 case X86::BI__builtin_ia32_pblendw128: 3531 case X86::BI__builtin_ia32_pblendw256: 3532 case X86::BI__builtin_ia32_blendps256: 3533 case X86::BI__builtin_ia32_pblendd256: 3534 case X86::BI__builtin_ia32_palignr128: 3535 case X86::BI__builtin_ia32_palignr256: 3536 case X86::BI__builtin_ia32_palignr512: 3537 case X86::BI__builtin_ia32_alignq512: 3538 case X86::BI__builtin_ia32_alignd512: 3539 case X86::BI__builtin_ia32_alignd128: 3540 case X86::BI__builtin_ia32_alignd256: 3541 case X86::BI__builtin_ia32_alignq128: 3542 case X86::BI__builtin_ia32_alignq256: 3543 case X86::BI__builtin_ia32_vcomisd: 3544 case X86::BI__builtin_ia32_vcomiss: 3545 case X86::BI__builtin_ia32_shuf_f32x4: 3546 case X86::BI__builtin_ia32_shuf_f64x2: 3547 case X86::BI__builtin_ia32_shuf_i32x4: 3548 case X86::BI__builtin_ia32_shuf_i64x2: 3549 case X86::BI__builtin_ia32_shufpd512: 3550 case X86::BI__builtin_ia32_shufps: 3551 case X86::BI__builtin_ia32_shufps256: 3552 case X86::BI__builtin_ia32_shufps512: 3553 case X86::BI__builtin_ia32_dbpsadbw128: 3554 case X86::BI__builtin_ia32_dbpsadbw256: 3555 case X86::BI__builtin_ia32_dbpsadbw512: 3556 case X86::BI__builtin_ia32_vpshldd128: 3557 case X86::BI__builtin_ia32_vpshldd256: 3558 case X86::BI__builtin_ia32_vpshldd512: 3559 case X86::BI__builtin_ia32_vpshldq128: 3560 case X86::BI__builtin_ia32_vpshldq256: 3561 case X86::BI__builtin_ia32_vpshldq512: 3562 case X86::BI__builtin_ia32_vpshldw128: 3563 case X86::BI__builtin_ia32_vpshldw256: 3564 case X86::BI__builtin_ia32_vpshldw512: 3565 case X86::BI__builtin_ia32_vpshrdd128: 3566 case X86::BI__builtin_ia32_vpshrdd256: 3567 case X86::BI__builtin_ia32_vpshrdd512: 3568 case X86::BI__builtin_ia32_vpshrdq128: 3569 case X86::BI__builtin_ia32_vpshrdq256: 3570 case X86::BI__builtin_ia32_vpshrdq512: 3571 case X86::BI__builtin_ia32_vpshrdw128: 3572 case X86::BI__builtin_ia32_vpshrdw256: 3573 case X86::BI__builtin_ia32_vpshrdw512: 3574 i = 2; l = 0; u = 255; 3575 break; 3576 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3577 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3578 case X86::BI__builtin_ia32_fixupimmps512_mask: 3579 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3580 case X86::BI__builtin_ia32_fixupimmsd_mask: 3581 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3582 case X86::BI__builtin_ia32_fixupimmss_mask: 3583 case X86::BI__builtin_ia32_fixupimmss_maskz: 3584 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3585 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3586 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3587 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3588 case X86::BI__builtin_ia32_fixupimmps128_mask: 3589 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3590 case X86::BI__builtin_ia32_fixupimmps256_mask: 3591 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3592 case X86::BI__builtin_ia32_pternlogd512_mask: 3593 case X86::BI__builtin_ia32_pternlogd512_maskz: 3594 case X86::BI__builtin_ia32_pternlogq512_mask: 3595 case X86::BI__builtin_ia32_pternlogq512_maskz: 3596 case X86::BI__builtin_ia32_pternlogd128_mask: 3597 case X86::BI__builtin_ia32_pternlogd128_maskz: 3598 case X86::BI__builtin_ia32_pternlogd256_mask: 3599 case X86::BI__builtin_ia32_pternlogd256_maskz: 3600 case X86::BI__builtin_ia32_pternlogq128_mask: 3601 case X86::BI__builtin_ia32_pternlogq128_maskz: 3602 case X86::BI__builtin_ia32_pternlogq256_mask: 3603 case X86::BI__builtin_ia32_pternlogq256_maskz: 3604 i = 3; l = 0; u = 255; 3605 break; 3606 case X86::BI__builtin_ia32_gatherpfdpd: 3607 case X86::BI__builtin_ia32_gatherpfdps: 3608 case X86::BI__builtin_ia32_gatherpfqpd: 3609 case X86::BI__builtin_ia32_gatherpfqps: 3610 case X86::BI__builtin_ia32_scatterpfdpd: 3611 case X86::BI__builtin_ia32_scatterpfdps: 3612 case X86::BI__builtin_ia32_scatterpfqpd: 3613 case X86::BI__builtin_ia32_scatterpfqps: 3614 i = 4; l = 2; u = 3; 3615 break; 3616 case X86::BI__builtin_ia32_reducesd_mask: 3617 case X86::BI__builtin_ia32_reducess_mask: 3618 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3619 case X86::BI__builtin_ia32_rndscaless_round_mask: 3620 i = 4; l = 0; u = 255; 3621 break; 3622 } 3623 3624 // Note that we don't force a hard error on the range check here, allowing 3625 // template-generated or macro-generated dead code to potentially have out-of- 3626 // range values. These need to code generate, but don't need to necessarily 3627 // make any sense. We use a warning that defaults to an error. 3628 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3629 } 3630 3631 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3632 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3633 /// Returns true when the format fits the function and the FormatStringInfo has 3634 /// been populated. 3635 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3636 FormatStringInfo *FSI) { 3637 FSI->HasVAListArg = Format->getFirstArg() == 0; 3638 FSI->FormatIdx = Format->getFormatIdx() - 1; 3639 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3640 3641 // The way the format attribute works in GCC, the implicit this argument 3642 // of member functions is counted. However, it doesn't appear in our own 3643 // lists, so decrement format_idx in that case. 3644 if (IsCXXMember) { 3645 if(FSI->FormatIdx == 0) 3646 return false; 3647 --FSI->FormatIdx; 3648 if (FSI->FirstDataArg != 0) 3649 --FSI->FirstDataArg; 3650 } 3651 return true; 3652 } 3653 3654 /// Checks if a the given expression evaluates to null. 3655 /// 3656 /// Returns true if the value evaluates to null. 3657 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3658 // If the expression has non-null type, it doesn't evaluate to null. 3659 if (auto nullability 3660 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3661 if (*nullability == NullabilityKind::NonNull) 3662 return false; 3663 } 3664 3665 // As a special case, transparent unions initialized with zero are 3666 // considered null for the purposes of the nonnull attribute. 3667 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3668 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3669 if (const CompoundLiteralExpr *CLE = 3670 dyn_cast<CompoundLiteralExpr>(Expr)) 3671 if (const InitListExpr *ILE = 3672 dyn_cast<InitListExpr>(CLE->getInitializer())) 3673 Expr = ILE->getInit(0); 3674 } 3675 3676 bool Result; 3677 return (!Expr->isValueDependent() && 3678 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3679 !Result); 3680 } 3681 3682 static void CheckNonNullArgument(Sema &S, 3683 const Expr *ArgExpr, 3684 SourceLocation CallSiteLoc) { 3685 if (CheckNonNullExpr(S, ArgExpr)) 3686 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3687 S.PDiag(diag::warn_null_arg) 3688 << ArgExpr->getSourceRange()); 3689 } 3690 3691 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3692 FormatStringInfo FSI; 3693 if ((GetFormatStringType(Format) == FST_NSString) && 3694 getFormatStringInfo(Format, false, &FSI)) { 3695 Idx = FSI.FormatIdx; 3696 return true; 3697 } 3698 return false; 3699 } 3700 3701 /// Diagnose use of %s directive in an NSString which is being passed 3702 /// as formatting string to formatting method. 3703 static void 3704 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3705 const NamedDecl *FDecl, 3706 Expr **Args, 3707 unsigned NumArgs) { 3708 unsigned Idx = 0; 3709 bool Format = false; 3710 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3711 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3712 Idx = 2; 3713 Format = true; 3714 } 3715 else 3716 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3717 if (S.GetFormatNSStringIdx(I, Idx)) { 3718 Format = true; 3719 break; 3720 } 3721 } 3722 if (!Format || NumArgs <= Idx) 3723 return; 3724 const Expr *FormatExpr = Args[Idx]; 3725 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3726 FormatExpr = CSCE->getSubExpr(); 3727 const StringLiteral *FormatString; 3728 if (const ObjCStringLiteral *OSL = 3729 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3730 FormatString = OSL->getString(); 3731 else 3732 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3733 if (!FormatString) 3734 return; 3735 if (S.FormatStringHasSArg(FormatString)) { 3736 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3737 << "%s" << 1 << 1; 3738 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3739 << FDecl->getDeclName(); 3740 } 3741 } 3742 3743 /// Determine whether the given type has a non-null nullability annotation. 3744 static bool isNonNullType(ASTContext &ctx, QualType type) { 3745 if (auto nullability = type->getNullability(ctx)) 3746 return *nullability == NullabilityKind::NonNull; 3747 3748 return false; 3749 } 3750 3751 static void CheckNonNullArguments(Sema &S, 3752 const NamedDecl *FDecl, 3753 const FunctionProtoType *Proto, 3754 ArrayRef<const Expr *> Args, 3755 SourceLocation CallSiteLoc) { 3756 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3757 3758 // Already checked by by constant evaluator. 3759 if (S.isConstantEvaluated()) 3760 return; 3761 // Check the attributes attached to the method/function itself. 3762 llvm::SmallBitVector NonNullArgs; 3763 if (FDecl) { 3764 // Handle the nonnull attribute on the function/method declaration itself. 3765 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3766 if (!NonNull->args_size()) { 3767 // Easy case: all pointer arguments are nonnull. 3768 for (const auto *Arg : Args) 3769 if (S.isValidPointerAttrType(Arg->getType())) 3770 CheckNonNullArgument(S, Arg, CallSiteLoc); 3771 return; 3772 } 3773 3774 for (const ParamIdx &Idx : NonNull->args()) { 3775 unsigned IdxAST = Idx.getASTIndex(); 3776 if (IdxAST >= Args.size()) 3777 continue; 3778 if (NonNullArgs.empty()) 3779 NonNullArgs.resize(Args.size()); 3780 NonNullArgs.set(IdxAST); 3781 } 3782 } 3783 } 3784 3785 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3786 // Handle the nonnull attribute on the parameters of the 3787 // function/method. 3788 ArrayRef<ParmVarDecl*> parms; 3789 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3790 parms = FD->parameters(); 3791 else 3792 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3793 3794 unsigned ParamIndex = 0; 3795 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3796 I != E; ++I, ++ParamIndex) { 3797 const ParmVarDecl *PVD = *I; 3798 if (PVD->hasAttr<NonNullAttr>() || 3799 isNonNullType(S.Context, PVD->getType())) { 3800 if (NonNullArgs.empty()) 3801 NonNullArgs.resize(Args.size()); 3802 3803 NonNullArgs.set(ParamIndex); 3804 } 3805 } 3806 } else { 3807 // If we have a non-function, non-method declaration but no 3808 // function prototype, try to dig out the function prototype. 3809 if (!Proto) { 3810 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3811 QualType type = VD->getType().getNonReferenceType(); 3812 if (auto pointerType = type->getAs<PointerType>()) 3813 type = pointerType->getPointeeType(); 3814 else if (auto blockType = type->getAs<BlockPointerType>()) 3815 type = blockType->getPointeeType(); 3816 // FIXME: data member pointers? 3817 3818 // Dig out the function prototype, if there is one. 3819 Proto = type->getAs<FunctionProtoType>(); 3820 } 3821 } 3822 3823 // Fill in non-null argument information from the nullability 3824 // information on the parameter types (if we have them). 3825 if (Proto) { 3826 unsigned Index = 0; 3827 for (auto paramType : Proto->getParamTypes()) { 3828 if (isNonNullType(S.Context, paramType)) { 3829 if (NonNullArgs.empty()) 3830 NonNullArgs.resize(Args.size()); 3831 3832 NonNullArgs.set(Index); 3833 } 3834 3835 ++Index; 3836 } 3837 } 3838 } 3839 3840 // Check for non-null arguments. 3841 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 3842 ArgIndex != ArgIndexEnd; ++ArgIndex) { 3843 if (NonNullArgs[ArgIndex]) 3844 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 3845 } 3846 } 3847 3848 /// Handles the checks for format strings, non-POD arguments to vararg 3849 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 3850 /// attributes. 3851 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 3852 const Expr *ThisArg, ArrayRef<const Expr *> Args, 3853 bool IsMemberFunction, SourceLocation Loc, 3854 SourceRange Range, VariadicCallType CallType) { 3855 // FIXME: We should check as much as we can in the template definition. 3856 if (CurContext->isDependentContext()) 3857 return; 3858 3859 // Printf and scanf checking. 3860 llvm::SmallBitVector CheckedVarArgs; 3861 if (FDecl) { 3862 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3863 // Only create vector if there are format attributes. 3864 CheckedVarArgs.resize(Args.size()); 3865 3866 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 3867 CheckedVarArgs); 3868 } 3869 } 3870 3871 // Refuse POD arguments that weren't caught by the format string 3872 // checks above. 3873 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 3874 if (CallType != VariadicDoesNotApply && 3875 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 3876 unsigned NumParams = Proto ? Proto->getNumParams() 3877 : FDecl && isa<FunctionDecl>(FDecl) 3878 ? cast<FunctionDecl>(FDecl)->getNumParams() 3879 : FDecl && isa<ObjCMethodDecl>(FDecl) 3880 ? cast<ObjCMethodDecl>(FDecl)->param_size() 3881 : 0; 3882 3883 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 3884 // Args[ArgIdx] can be null in malformed code. 3885 if (const Expr *Arg = Args[ArgIdx]) { 3886 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 3887 checkVariadicArgument(Arg, CallType); 3888 } 3889 } 3890 } 3891 3892 if (FDecl || Proto) { 3893 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 3894 3895 // Type safety checking. 3896 if (FDecl) { 3897 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 3898 CheckArgumentWithTypeTag(I, Args, Loc); 3899 } 3900 } 3901 3902 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 3903 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 3904 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 3905 if (!Arg->isValueDependent()) { 3906 Expr::EvalResult Align; 3907 if (Arg->EvaluateAsInt(Align, Context)) { 3908 const llvm::APSInt &I = Align.Val.getInt(); 3909 if (!I.isPowerOf2()) 3910 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 3911 << Arg->getSourceRange(); 3912 3913 if (I > Sema::MaximumAlignment) 3914 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 3915 << Arg->getSourceRange() << Sema::MaximumAlignment; 3916 } 3917 } 3918 } 3919 3920 if (FD) 3921 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 3922 } 3923 3924 /// CheckConstructorCall - Check a constructor call for correctness and safety 3925 /// properties not enforced by the C type system. 3926 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 3927 ArrayRef<const Expr *> Args, 3928 const FunctionProtoType *Proto, 3929 SourceLocation Loc) { 3930 VariadicCallType CallType = 3931 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 3932 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 3933 Loc, SourceRange(), CallType); 3934 } 3935 3936 /// CheckFunctionCall - Check a direct function call for various correctness 3937 /// and safety properties not strictly enforced by the C type system. 3938 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 3939 const FunctionProtoType *Proto) { 3940 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 3941 isa<CXXMethodDecl>(FDecl); 3942 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 3943 IsMemberOperatorCall; 3944 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 3945 TheCall->getCallee()); 3946 Expr** Args = TheCall->getArgs(); 3947 unsigned NumArgs = TheCall->getNumArgs(); 3948 3949 Expr *ImplicitThis = nullptr; 3950 if (IsMemberOperatorCall) { 3951 // If this is a call to a member operator, hide the first argument 3952 // from checkCall. 3953 // FIXME: Our choice of AST representation here is less than ideal. 3954 ImplicitThis = Args[0]; 3955 ++Args; 3956 --NumArgs; 3957 } else if (IsMemberFunction) 3958 ImplicitThis = 3959 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 3960 3961 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 3962 IsMemberFunction, TheCall->getRParenLoc(), 3963 TheCall->getCallee()->getSourceRange(), CallType); 3964 3965 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 3966 // None of the checks below are needed for functions that don't have 3967 // simple names (e.g., C++ conversion functions). 3968 if (!FnInfo) 3969 return false; 3970 3971 CheckAbsoluteValueFunction(TheCall, FDecl); 3972 CheckMaxUnsignedZero(TheCall, FDecl); 3973 3974 if (getLangOpts().ObjC) 3975 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 3976 3977 unsigned CMId = FDecl->getMemoryFunctionKind(); 3978 if (CMId == 0) 3979 return false; 3980 3981 // Handle memory setting and copying functions. 3982 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 3983 CheckStrlcpycatArguments(TheCall, FnInfo); 3984 else if (CMId == Builtin::BIstrncat) 3985 CheckStrncatArguments(TheCall, FnInfo); 3986 else 3987 CheckMemaccessArguments(TheCall, CMId, FnInfo); 3988 3989 return false; 3990 } 3991 3992 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 3993 ArrayRef<const Expr *> Args) { 3994 VariadicCallType CallType = 3995 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 3996 3997 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 3998 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 3999 CallType); 4000 4001 return false; 4002 } 4003 4004 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4005 const FunctionProtoType *Proto) { 4006 QualType Ty; 4007 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4008 Ty = V->getType().getNonReferenceType(); 4009 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4010 Ty = F->getType().getNonReferenceType(); 4011 else 4012 return false; 4013 4014 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4015 !Ty->isFunctionProtoType()) 4016 return false; 4017 4018 VariadicCallType CallType; 4019 if (!Proto || !Proto->isVariadic()) { 4020 CallType = VariadicDoesNotApply; 4021 } else if (Ty->isBlockPointerType()) { 4022 CallType = VariadicBlock; 4023 } else { // Ty->isFunctionPointerType() 4024 CallType = VariadicFunction; 4025 } 4026 4027 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4028 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4029 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4030 TheCall->getCallee()->getSourceRange(), CallType); 4031 4032 return false; 4033 } 4034 4035 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4036 /// such as function pointers returned from functions. 4037 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4038 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4039 TheCall->getCallee()); 4040 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4041 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4042 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4043 TheCall->getCallee()->getSourceRange(), CallType); 4044 4045 return false; 4046 } 4047 4048 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4049 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4050 return false; 4051 4052 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4053 switch (Op) { 4054 case AtomicExpr::AO__c11_atomic_init: 4055 case AtomicExpr::AO__opencl_atomic_init: 4056 llvm_unreachable("There is no ordering argument for an init"); 4057 4058 case AtomicExpr::AO__c11_atomic_load: 4059 case AtomicExpr::AO__opencl_atomic_load: 4060 case AtomicExpr::AO__atomic_load_n: 4061 case AtomicExpr::AO__atomic_load: 4062 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4063 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4064 4065 case AtomicExpr::AO__c11_atomic_store: 4066 case AtomicExpr::AO__opencl_atomic_store: 4067 case AtomicExpr::AO__atomic_store: 4068 case AtomicExpr::AO__atomic_store_n: 4069 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4070 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4071 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4072 4073 default: 4074 return true; 4075 } 4076 } 4077 4078 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4079 AtomicExpr::AtomicOp Op) { 4080 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4081 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4082 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4083 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4084 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4085 Op); 4086 } 4087 4088 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4089 SourceLocation RParenLoc, MultiExprArg Args, 4090 AtomicExpr::AtomicOp Op, 4091 AtomicArgumentOrder ArgOrder) { 4092 // All the non-OpenCL operations take one of the following forms. 4093 // The OpenCL operations take the __c11 forms with one extra argument for 4094 // synchronization scope. 4095 enum { 4096 // C __c11_atomic_init(A *, C) 4097 Init, 4098 4099 // C __c11_atomic_load(A *, int) 4100 Load, 4101 4102 // void __atomic_load(A *, CP, int) 4103 LoadCopy, 4104 4105 // void __atomic_store(A *, CP, int) 4106 Copy, 4107 4108 // C __c11_atomic_add(A *, M, int) 4109 Arithmetic, 4110 4111 // C __atomic_exchange_n(A *, CP, int) 4112 Xchg, 4113 4114 // void __atomic_exchange(A *, C *, CP, int) 4115 GNUXchg, 4116 4117 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4118 C11CmpXchg, 4119 4120 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4121 GNUCmpXchg 4122 } Form = Init; 4123 4124 const unsigned NumForm = GNUCmpXchg + 1; 4125 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4126 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4127 // where: 4128 // C is an appropriate type, 4129 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4130 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4131 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4132 // the int parameters are for orderings. 4133 4134 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4135 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4136 "need to update code for modified forms"); 4137 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4138 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4139 AtomicExpr::AO__atomic_load, 4140 "need to update code for modified C11 atomics"); 4141 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4142 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4143 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4144 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4145 IsOpenCL; 4146 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4147 Op == AtomicExpr::AO__atomic_store_n || 4148 Op == AtomicExpr::AO__atomic_exchange_n || 4149 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4150 bool IsAddSub = false; 4151 4152 switch (Op) { 4153 case AtomicExpr::AO__c11_atomic_init: 4154 case AtomicExpr::AO__opencl_atomic_init: 4155 Form = Init; 4156 break; 4157 4158 case AtomicExpr::AO__c11_atomic_load: 4159 case AtomicExpr::AO__opencl_atomic_load: 4160 case AtomicExpr::AO__atomic_load_n: 4161 Form = Load; 4162 break; 4163 4164 case AtomicExpr::AO__atomic_load: 4165 Form = LoadCopy; 4166 break; 4167 4168 case AtomicExpr::AO__c11_atomic_store: 4169 case AtomicExpr::AO__opencl_atomic_store: 4170 case AtomicExpr::AO__atomic_store: 4171 case AtomicExpr::AO__atomic_store_n: 4172 Form = Copy; 4173 break; 4174 4175 case AtomicExpr::AO__c11_atomic_fetch_add: 4176 case AtomicExpr::AO__c11_atomic_fetch_sub: 4177 case AtomicExpr::AO__opencl_atomic_fetch_add: 4178 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4179 case AtomicExpr::AO__atomic_fetch_add: 4180 case AtomicExpr::AO__atomic_fetch_sub: 4181 case AtomicExpr::AO__atomic_add_fetch: 4182 case AtomicExpr::AO__atomic_sub_fetch: 4183 IsAddSub = true; 4184 LLVM_FALLTHROUGH; 4185 case AtomicExpr::AO__c11_atomic_fetch_and: 4186 case AtomicExpr::AO__c11_atomic_fetch_or: 4187 case AtomicExpr::AO__c11_atomic_fetch_xor: 4188 case AtomicExpr::AO__opencl_atomic_fetch_and: 4189 case AtomicExpr::AO__opencl_atomic_fetch_or: 4190 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4191 case AtomicExpr::AO__atomic_fetch_and: 4192 case AtomicExpr::AO__atomic_fetch_or: 4193 case AtomicExpr::AO__atomic_fetch_xor: 4194 case AtomicExpr::AO__atomic_fetch_nand: 4195 case AtomicExpr::AO__atomic_and_fetch: 4196 case AtomicExpr::AO__atomic_or_fetch: 4197 case AtomicExpr::AO__atomic_xor_fetch: 4198 case AtomicExpr::AO__atomic_nand_fetch: 4199 case AtomicExpr::AO__c11_atomic_fetch_min: 4200 case AtomicExpr::AO__c11_atomic_fetch_max: 4201 case AtomicExpr::AO__opencl_atomic_fetch_min: 4202 case AtomicExpr::AO__opencl_atomic_fetch_max: 4203 case AtomicExpr::AO__atomic_min_fetch: 4204 case AtomicExpr::AO__atomic_max_fetch: 4205 case AtomicExpr::AO__atomic_fetch_min: 4206 case AtomicExpr::AO__atomic_fetch_max: 4207 Form = Arithmetic; 4208 break; 4209 4210 case AtomicExpr::AO__c11_atomic_exchange: 4211 case AtomicExpr::AO__opencl_atomic_exchange: 4212 case AtomicExpr::AO__atomic_exchange_n: 4213 Form = Xchg; 4214 break; 4215 4216 case AtomicExpr::AO__atomic_exchange: 4217 Form = GNUXchg; 4218 break; 4219 4220 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4221 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4222 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4223 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4224 Form = C11CmpXchg; 4225 break; 4226 4227 case AtomicExpr::AO__atomic_compare_exchange: 4228 case AtomicExpr::AO__atomic_compare_exchange_n: 4229 Form = GNUCmpXchg; 4230 break; 4231 } 4232 4233 unsigned AdjustedNumArgs = NumArgs[Form]; 4234 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4235 ++AdjustedNumArgs; 4236 // Check we have the right number of arguments. 4237 if (Args.size() < AdjustedNumArgs) { 4238 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4239 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4240 << ExprRange; 4241 return ExprError(); 4242 } else if (Args.size() > AdjustedNumArgs) { 4243 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4244 diag::err_typecheck_call_too_many_args) 4245 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4246 << ExprRange; 4247 return ExprError(); 4248 } 4249 4250 // Inspect the first argument of the atomic operation. 4251 Expr *Ptr = Args[0]; 4252 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4253 if (ConvertedPtr.isInvalid()) 4254 return ExprError(); 4255 4256 Ptr = ConvertedPtr.get(); 4257 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4258 if (!pointerType) { 4259 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4260 << Ptr->getType() << Ptr->getSourceRange(); 4261 return ExprError(); 4262 } 4263 4264 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4265 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4266 QualType ValType = AtomTy; // 'C' 4267 if (IsC11) { 4268 if (!AtomTy->isAtomicType()) { 4269 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4270 << Ptr->getType() << Ptr->getSourceRange(); 4271 return ExprError(); 4272 } 4273 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4274 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4275 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4276 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4277 << Ptr->getSourceRange(); 4278 return ExprError(); 4279 } 4280 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4281 } else if (Form != Load && Form != LoadCopy) { 4282 if (ValType.isConstQualified()) { 4283 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4284 << Ptr->getType() << Ptr->getSourceRange(); 4285 return ExprError(); 4286 } 4287 } 4288 4289 // For an arithmetic operation, the implied arithmetic must be well-formed. 4290 if (Form == Arithmetic) { 4291 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4292 if (IsAddSub && !ValType->isIntegerType() 4293 && !ValType->isPointerType()) { 4294 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4295 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4296 return ExprError(); 4297 } 4298 if (!IsAddSub && !ValType->isIntegerType()) { 4299 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4300 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4301 return ExprError(); 4302 } 4303 if (IsC11 && ValType->isPointerType() && 4304 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4305 diag::err_incomplete_type)) { 4306 return ExprError(); 4307 } 4308 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4309 // For __atomic_*_n operations, the value type must be a scalar integral or 4310 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4311 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4312 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4313 return ExprError(); 4314 } 4315 4316 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4317 !AtomTy->isScalarType()) { 4318 // For GNU atomics, require a trivially-copyable type. This is not part of 4319 // the GNU atomics specification, but we enforce it for sanity. 4320 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4321 << Ptr->getType() << Ptr->getSourceRange(); 4322 return ExprError(); 4323 } 4324 4325 switch (ValType.getObjCLifetime()) { 4326 case Qualifiers::OCL_None: 4327 case Qualifiers::OCL_ExplicitNone: 4328 // okay 4329 break; 4330 4331 case Qualifiers::OCL_Weak: 4332 case Qualifiers::OCL_Strong: 4333 case Qualifiers::OCL_Autoreleasing: 4334 // FIXME: Can this happen? By this point, ValType should be known 4335 // to be trivially copyable. 4336 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4337 << ValType << Ptr->getSourceRange(); 4338 return ExprError(); 4339 } 4340 4341 // All atomic operations have an overload which takes a pointer to a volatile 4342 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4343 // into the result or the other operands. Similarly atomic_load takes a 4344 // pointer to a const 'A'. 4345 ValType.removeLocalVolatile(); 4346 ValType.removeLocalConst(); 4347 QualType ResultType = ValType; 4348 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4349 Form == Init) 4350 ResultType = Context.VoidTy; 4351 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4352 ResultType = Context.BoolTy; 4353 4354 // The type of a parameter passed 'by value'. In the GNU atomics, such 4355 // arguments are actually passed as pointers. 4356 QualType ByValType = ValType; // 'CP' 4357 bool IsPassedByAddress = false; 4358 if (!IsC11 && !IsN) { 4359 ByValType = Ptr->getType(); 4360 IsPassedByAddress = true; 4361 } 4362 4363 SmallVector<Expr *, 5> APIOrderedArgs; 4364 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4365 APIOrderedArgs.push_back(Args[0]); 4366 switch (Form) { 4367 case Init: 4368 case Load: 4369 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4370 break; 4371 case LoadCopy: 4372 case Copy: 4373 case Arithmetic: 4374 case Xchg: 4375 APIOrderedArgs.push_back(Args[2]); // Val1 4376 APIOrderedArgs.push_back(Args[1]); // Order 4377 break; 4378 case GNUXchg: 4379 APIOrderedArgs.push_back(Args[2]); // Val1 4380 APIOrderedArgs.push_back(Args[3]); // Val2 4381 APIOrderedArgs.push_back(Args[1]); // Order 4382 break; 4383 case C11CmpXchg: 4384 APIOrderedArgs.push_back(Args[2]); // Val1 4385 APIOrderedArgs.push_back(Args[4]); // Val2 4386 APIOrderedArgs.push_back(Args[1]); // Order 4387 APIOrderedArgs.push_back(Args[3]); // OrderFail 4388 break; 4389 case GNUCmpXchg: 4390 APIOrderedArgs.push_back(Args[2]); // Val1 4391 APIOrderedArgs.push_back(Args[4]); // Val2 4392 APIOrderedArgs.push_back(Args[5]); // Weak 4393 APIOrderedArgs.push_back(Args[1]); // Order 4394 APIOrderedArgs.push_back(Args[3]); // OrderFail 4395 break; 4396 } 4397 } else 4398 APIOrderedArgs.append(Args.begin(), Args.end()); 4399 4400 // The first argument's non-CV pointer type is used to deduce the type of 4401 // subsequent arguments, except for: 4402 // - weak flag (always converted to bool) 4403 // - memory order (always converted to int) 4404 // - scope (always converted to int) 4405 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4406 QualType Ty; 4407 if (i < NumVals[Form] + 1) { 4408 switch (i) { 4409 case 0: 4410 // The first argument is always a pointer. It has a fixed type. 4411 // It is always dereferenced, a nullptr is undefined. 4412 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4413 // Nothing else to do: we already know all we want about this pointer. 4414 continue; 4415 case 1: 4416 // The second argument is the non-atomic operand. For arithmetic, this 4417 // is always passed by value, and for a compare_exchange it is always 4418 // passed by address. For the rest, GNU uses by-address and C11 uses 4419 // by-value. 4420 assert(Form != Load); 4421 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4422 Ty = ValType; 4423 else if (Form == Copy || Form == Xchg) { 4424 if (IsPassedByAddress) { 4425 // The value pointer is always dereferenced, a nullptr is undefined. 4426 CheckNonNullArgument(*this, APIOrderedArgs[i], 4427 ExprRange.getBegin()); 4428 } 4429 Ty = ByValType; 4430 } else if (Form == Arithmetic) 4431 Ty = Context.getPointerDiffType(); 4432 else { 4433 Expr *ValArg = APIOrderedArgs[i]; 4434 // The value pointer is always dereferenced, a nullptr is undefined. 4435 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4436 LangAS AS = LangAS::Default; 4437 // Keep address space of non-atomic pointer type. 4438 if (const PointerType *PtrTy = 4439 ValArg->getType()->getAs<PointerType>()) { 4440 AS = PtrTy->getPointeeType().getAddressSpace(); 4441 } 4442 Ty = Context.getPointerType( 4443 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4444 } 4445 break; 4446 case 2: 4447 // The third argument to compare_exchange / GNU exchange is the desired 4448 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4449 if (IsPassedByAddress) 4450 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4451 Ty = ByValType; 4452 break; 4453 case 3: 4454 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4455 Ty = Context.BoolTy; 4456 break; 4457 } 4458 } else { 4459 // The order(s) and scope are always converted to int. 4460 Ty = Context.IntTy; 4461 } 4462 4463 InitializedEntity Entity = 4464 InitializedEntity::InitializeParameter(Context, Ty, false); 4465 ExprResult Arg = APIOrderedArgs[i]; 4466 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4467 if (Arg.isInvalid()) 4468 return true; 4469 APIOrderedArgs[i] = Arg.get(); 4470 } 4471 4472 // Permute the arguments into a 'consistent' order. 4473 SmallVector<Expr*, 5> SubExprs; 4474 SubExprs.push_back(Ptr); 4475 switch (Form) { 4476 case Init: 4477 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4478 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4479 break; 4480 case Load: 4481 SubExprs.push_back(APIOrderedArgs[1]); // Order 4482 break; 4483 case LoadCopy: 4484 case Copy: 4485 case Arithmetic: 4486 case Xchg: 4487 SubExprs.push_back(APIOrderedArgs[2]); // Order 4488 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4489 break; 4490 case GNUXchg: 4491 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4492 SubExprs.push_back(APIOrderedArgs[3]); // Order 4493 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4494 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4495 break; 4496 case C11CmpXchg: 4497 SubExprs.push_back(APIOrderedArgs[3]); // Order 4498 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4499 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4500 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4501 break; 4502 case GNUCmpXchg: 4503 SubExprs.push_back(APIOrderedArgs[4]); // Order 4504 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4505 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4506 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4507 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4508 break; 4509 } 4510 4511 if (SubExprs.size() >= 2 && Form != Init) { 4512 llvm::APSInt Result(32); 4513 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4514 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4515 Diag(SubExprs[1]->getBeginLoc(), 4516 diag::warn_atomic_op_has_invalid_memory_order) 4517 << SubExprs[1]->getSourceRange(); 4518 } 4519 4520 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4521 auto *Scope = Args[Args.size() - 1]; 4522 llvm::APSInt Result(32); 4523 if (Scope->isIntegerConstantExpr(Result, Context) && 4524 !ScopeModel->isValid(Result.getZExtValue())) { 4525 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4526 << Scope->getSourceRange(); 4527 } 4528 SubExprs.push_back(Scope); 4529 } 4530 4531 AtomicExpr *AE = new (Context) 4532 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4533 4534 if ((Op == AtomicExpr::AO__c11_atomic_load || 4535 Op == AtomicExpr::AO__c11_atomic_store || 4536 Op == AtomicExpr::AO__opencl_atomic_load || 4537 Op == AtomicExpr::AO__opencl_atomic_store ) && 4538 Context.AtomicUsesUnsupportedLibcall(AE)) 4539 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4540 << ((Op == AtomicExpr::AO__c11_atomic_load || 4541 Op == AtomicExpr::AO__opencl_atomic_load) 4542 ? 0 4543 : 1); 4544 4545 return AE; 4546 } 4547 4548 /// checkBuiltinArgument - Given a call to a builtin function, perform 4549 /// normal type-checking on the given argument, updating the call in 4550 /// place. This is useful when a builtin function requires custom 4551 /// type-checking for some of its arguments but not necessarily all of 4552 /// them. 4553 /// 4554 /// Returns true on error. 4555 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4556 FunctionDecl *Fn = E->getDirectCallee(); 4557 assert(Fn && "builtin call without direct callee!"); 4558 4559 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4560 InitializedEntity Entity = 4561 InitializedEntity::InitializeParameter(S.Context, Param); 4562 4563 ExprResult Arg = E->getArg(0); 4564 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4565 if (Arg.isInvalid()) 4566 return true; 4567 4568 E->setArg(ArgIndex, Arg.get()); 4569 return false; 4570 } 4571 4572 /// We have a call to a function like __sync_fetch_and_add, which is an 4573 /// overloaded function based on the pointer type of its first argument. 4574 /// The main BuildCallExpr routines have already promoted the types of 4575 /// arguments because all of these calls are prototyped as void(...). 4576 /// 4577 /// This function goes through and does final semantic checking for these 4578 /// builtins, as well as generating any warnings. 4579 ExprResult 4580 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4581 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4582 Expr *Callee = TheCall->getCallee(); 4583 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4584 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4585 4586 // Ensure that we have at least one argument to do type inference from. 4587 if (TheCall->getNumArgs() < 1) { 4588 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4589 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4590 return ExprError(); 4591 } 4592 4593 // Inspect the first argument of the atomic builtin. This should always be 4594 // a pointer type, whose element is an integral scalar or pointer type. 4595 // Because it is a pointer type, we don't have to worry about any implicit 4596 // casts here. 4597 // FIXME: We don't allow floating point scalars as input. 4598 Expr *FirstArg = TheCall->getArg(0); 4599 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4600 if (FirstArgResult.isInvalid()) 4601 return ExprError(); 4602 FirstArg = FirstArgResult.get(); 4603 TheCall->setArg(0, FirstArg); 4604 4605 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4606 if (!pointerType) { 4607 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4608 << FirstArg->getType() << FirstArg->getSourceRange(); 4609 return ExprError(); 4610 } 4611 4612 QualType ValType = pointerType->getPointeeType(); 4613 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4614 !ValType->isBlockPointerType()) { 4615 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4616 << FirstArg->getType() << FirstArg->getSourceRange(); 4617 return ExprError(); 4618 } 4619 4620 if (ValType.isConstQualified()) { 4621 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4622 << FirstArg->getType() << FirstArg->getSourceRange(); 4623 return ExprError(); 4624 } 4625 4626 switch (ValType.getObjCLifetime()) { 4627 case Qualifiers::OCL_None: 4628 case Qualifiers::OCL_ExplicitNone: 4629 // okay 4630 break; 4631 4632 case Qualifiers::OCL_Weak: 4633 case Qualifiers::OCL_Strong: 4634 case Qualifiers::OCL_Autoreleasing: 4635 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4636 << ValType << FirstArg->getSourceRange(); 4637 return ExprError(); 4638 } 4639 4640 // Strip any qualifiers off ValType. 4641 ValType = ValType.getUnqualifiedType(); 4642 4643 // The majority of builtins return a value, but a few have special return 4644 // types, so allow them to override appropriately below. 4645 QualType ResultType = ValType; 4646 4647 // We need to figure out which concrete builtin this maps onto. For example, 4648 // __sync_fetch_and_add with a 2 byte object turns into 4649 // __sync_fetch_and_add_2. 4650 #define BUILTIN_ROW(x) \ 4651 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4652 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4653 4654 static const unsigned BuiltinIndices[][5] = { 4655 BUILTIN_ROW(__sync_fetch_and_add), 4656 BUILTIN_ROW(__sync_fetch_and_sub), 4657 BUILTIN_ROW(__sync_fetch_and_or), 4658 BUILTIN_ROW(__sync_fetch_and_and), 4659 BUILTIN_ROW(__sync_fetch_and_xor), 4660 BUILTIN_ROW(__sync_fetch_and_nand), 4661 4662 BUILTIN_ROW(__sync_add_and_fetch), 4663 BUILTIN_ROW(__sync_sub_and_fetch), 4664 BUILTIN_ROW(__sync_and_and_fetch), 4665 BUILTIN_ROW(__sync_or_and_fetch), 4666 BUILTIN_ROW(__sync_xor_and_fetch), 4667 BUILTIN_ROW(__sync_nand_and_fetch), 4668 4669 BUILTIN_ROW(__sync_val_compare_and_swap), 4670 BUILTIN_ROW(__sync_bool_compare_and_swap), 4671 BUILTIN_ROW(__sync_lock_test_and_set), 4672 BUILTIN_ROW(__sync_lock_release), 4673 BUILTIN_ROW(__sync_swap) 4674 }; 4675 #undef BUILTIN_ROW 4676 4677 // Determine the index of the size. 4678 unsigned SizeIndex; 4679 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4680 case 1: SizeIndex = 0; break; 4681 case 2: SizeIndex = 1; break; 4682 case 4: SizeIndex = 2; break; 4683 case 8: SizeIndex = 3; break; 4684 case 16: SizeIndex = 4; break; 4685 default: 4686 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4687 << FirstArg->getType() << FirstArg->getSourceRange(); 4688 return ExprError(); 4689 } 4690 4691 // Each of these builtins has one pointer argument, followed by some number of 4692 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4693 // that we ignore. Find out which row of BuiltinIndices to read from as well 4694 // as the number of fixed args. 4695 unsigned BuiltinID = FDecl->getBuiltinID(); 4696 unsigned BuiltinIndex, NumFixed = 1; 4697 bool WarnAboutSemanticsChange = false; 4698 switch (BuiltinID) { 4699 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4700 case Builtin::BI__sync_fetch_and_add: 4701 case Builtin::BI__sync_fetch_and_add_1: 4702 case Builtin::BI__sync_fetch_and_add_2: 4703 case Builtin::BI__sync_fetch_and_add_4: 4704 case Builtin::BI__sync_fetch_and_add_8: 4705 case Builtin::BI__sync_fetch_and_add_16: 4706 BuiltinIndex = 0; 4707 break; 4708 4709 case Builtin::BI__sync_fetch_and_sub: 4710 case Builtin::BI__sync_fetch_and_sub_1: 4711 case Builtin::BI__sync_fetch_and_sub_2: 4712 case Builtin::BI__sync_fetch_and_sub_4: 4713 case Builtin::BI__sync_fetch_and_sub_8: 4714 case Builtin::BI__sync_fetch_and_sub_16: 4715 BuiltinIndex = 1; 4716 break; 4717 4718 case Builtin::BI__sync_fetch_and_or: 4719 case Builtin::BI__sync_fetch_and_or_1: 4720 case Builtin::BI__sync_fetch_and_or_2: 4721 case Builtin::BI__sync_fetch_and_or_4: 4722 case Builtin::BI__sync_fetch_and_or_8: 4723 case Builtin::BI__sync_fetch_and_or_16: 4724 BuiltinIndex = 2; 4725 break; 4726 4727 case Builtin::BI__sync_fetch_and_and: 4728 case Builtin::BI__sync_fetch_and_and_1: 4729 case Builtin::BI__sync_fetch_and_and_2: 4730 case Builtin::BI__sync_fetch_and_and_4: 4731 case Builtin::BI__sync_fetch_and_and_8: 4732 case Builtin::BI__sync_fetch_and_and_16: 4733 BuiltinIndex = 3; 4734 break; 4735 4736 case Builtin::BI__sync_fetch_and_xor: 4737 case Builtin::BI__sync_fetch_and_xor_1: 4738 case Builtin::BI__sync_fetch_and_xor_2: 4739 case Builtin::BI__sync_fetch_and_xor_4: 4740 case Builtin::BI__sync_fetch_and_xor_8: 4741 case Builtin::BI__sync_fetch_and_xor_16: 4742 BuiltinIndex = 4; 4743 break; 4744 4745 case Builtin::BI__sync_fetch_and_nand: 4746 case Builtin::BI__sync_fetch_and_nand_1: 4747 case Builtin::BI__sync_fetch_and_nand_2: 4748 case Builtin::BI__sync_fetch_and_nand_4: 4749 case Builtin::BI__sync_fetch_and_nand_8: 4750 case Builtin::BI__sync_fetch_and_nand_16: 4751 BuiltinIndex = 5; 4752 WarnAboutSemanticsChange = true; 4753 break; 4754 4755 case Builtin::BI__sync_add_and_fetch: 4756 case Builtin::BI__sync_add_and_fetch_1: 4757 case Builtin::BI__sync_add_and_fetch_2: 4758 case Builtin::BI__sync_add_and_fetch_4: 4759 case Builtin::BI__sync_add_and_fetch_8: 4760 case Builtin::BI__sync_add_and_fetch_16: 4761 BuiltinIndex = 6; 4762 break; 4763 4764 case Builtin::BI__sync_sub_and_fetch: 4765 case Builtin::BI__sync_sub_and_fetch_1: 4766 case Builtin::BI__sync_sub_and_fetch_2: 4767 case Builtin::BI__sync_sub_and_fetch_4: 4768 case Builtin::BI__sync_sub_and_fetch_8: 4769 case Builtin::BI__sync_sub_and_fetch_16: 4770 BuiltinIndex = 7; 4771 break; 4772 4773 case Builtin::BI__sync_and_and_fetch: 4774 case Builtin::BI__sync_and_and_fetch_1: 4775 case Builtin::BI__sync_and_and_fetch_2: 4776 case Builtin::BI__sync_and_and_fetch_4: 4777 case Builtin::BI__sync_and_and_fetch_8: 4778 case Builtin::BI__sync_and_and_fetch_16: 4779 BuiltinIndex = 8; 4780 break; 4781 4782 case Builtin::BI__sync_or_and_fetch: 4783 case Builtin::BI__sync_or_and_fetch_1: 4784 case Builtin::BI__sync_or_and_fetch_2: 4785 case Builtin::BI__sync_or_and_fetch_4: 4786 case Builtin::BI__sync_or_and_fetch_8: 4787 case Builtin::BI__sync_or_and_fetch_16: 4788 BuiltinIndex = 9; 4789 break; 4790 4791 case Builtin::BI__sync_xor_and_fetch: 4792 case Builtin::BI__sync_xor_and_fetch_1: 4793 case Builtin::BI__sync_xor_and_fetch_2: 4794 case Builtin::BI__sync_xor_and_fetch_4: 4795 case Builtin::BI__sync_xor_and_fetch_8: 4796 case Builtin::BI__sync_xor_and_fetch_16: 4797 BuiltinIndex = 10; 4798 break; 4799 4800 case Builtin::BI__sync_nand_and_fetch: 4801 case Builtin::BI__sync_nand_and_fetch_1: 4802 case Builtin::BI__sync_nand_and_fetch_2: 4803 case Builtin::BI__sync_nand_and_fetch_4: 4804 case Builtin::BI__sync_nand_and_fetch_8: 4805 case Builtin::BI__sync_nand_and_fetch_16: 4806 BuiltinIndex = 11; 4807 WarnAboutSemanticsChange = true; 4808 break; 4809 4810 case Builtin::BI__sync_val_compare_and_swap: 4811 case Builtin::BI__sync_val_compare_and_swap_1: 4812 case Builtin::BI__sync_val_compare_and_swap_2: 4813 case Builtin::BI__sync_val_compare_and_swap_4: 4814 case Builtin::BI__sync_val_compare_and_swap_8: 4815 case Builtin::BI__sync_val_compare_and_swap_16: 4816 BuiltinIndex = 12; 4817 NumFixed = 2; 4818 break; 4819 4820 case Builtin::BI__sync_bool_compare_and_swap: 4821 case Builtin::BI__sync_bool_compare_and_swap_1: 4822 case Builtin::BI__sync_bool_compare_and_swap_2: 4823 case Builtin::BI__sync_bool_compare_and_swap_4: 4824 case Builtin::BI__sync_bool_compare_and_swap_8: 4825 case Builtin::BI__sync_bool_compare_and_swap_16: 4826 BuiltinIndex = 13; 4827 NumFixed = 2; 4828 ResultType = Context.BoolTy; 4829 break; 4830 4831 case Builtin::BI__sync_lock_test_and_set: 4832 case Builtin::BI__sync_lock_test_and_set_1: 4833 case Builtin::BI__sync_lock_test_and_set_2: 4834 case Builtin::BI__sync_lock_test_and_set_4: 4835 case Builtin::BI__sync_lock_test_and_set_8: 4836 case Builtin::BI__sync_lock_test_and_set_16: 4837 BuiltinIndex = 14; 4838 break; 4839 4840 case Builtin::BI__sync_lock_release: 4841 case Builtin::BI__sync_lock_release_1: 4842 case Builtin::BI__sync_lock_release_2: 4843 case Builtin::BI__sync_lock_release_4: 4844 case Builtin::BI__sync_lock_release_8: 4845 case Builtin::BI__sync_lock_release_16: 4846 BuiltinIndex = 15; 4847 NumFixed = 0; 4848 ResultType = Context.VoidTy; 4849 break; 4850 4851 case Builtin::BI__sync_swap: 4852 case Builtin::BI__sync_swap_1: 4853 case Builtin::BI__sync_swap_2: 4854 case Builtin::BI__sync_swap_4: 4855 case Builtin::BI__sync_swap_8: 4856 case Builtin::BI__sync_swap_16: 4857 BuiltinIndex = 16; 4858 break; 4859 } 4860 4861 // Now that we know how many fixed arguments we expect, first check that we 4862 // have at least that many. 4863 if (TheCall->getNumArgs() < 1+NumFixed) { 4864 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4865 << 0 << 1 + NumFixed << TheCall->getNumArgs() 4866 << Callee->getSourceRange(); 4867 return ExprError(); 4868 } 4869 4870 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 4871 << Callee->getSourceRange(); 4872 4873 if (WarnAboutSemanticsChange) { 4874 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 4875 << Callee->getSourceRange(); 4876 } 4877 4878 // Get the decl for the concrete builtin from this, we can tell what the 4879 // concrete integer type we should convert to is. 4880 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4881 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4882 FunctionDecl *NewBuiltinDecl; 4883 if (NewBuiltinID == BuiltinID) 4884 NewBuiltinDecl = FDecl; 4885 else { 4886 // Perform builtin lookup to avoid redeclaring it. 4887 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4888 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 4889 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 4890 assert(Res.getFoundDecl()); 4891 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 4892 if (!NewBuiltinDecl) 4893 return ExprError(); 4894 } 4895 4896 // The first argument --- the pointer --- has a fixed type; we 4897 // deduce the types of the rest of the arguments accordingly. Walk 4898 // the remaining arguments, converting them to the deduced value type. 4899 for (unsigned i = 0; i != NumFixed; ++i) { 4900 ExprResult Arg = TheCall->getArg(i+1); 4901 4902 // GCC does an implicit conversion to the pointer or integer ValType. This 4903 // can fail in some cases (1i -> int**), check for this error case now. 4904 // Initialize the argument. 4905 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4906 ValType, /*consume*/ false); 4907 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4908 if (Arg.isInvalid()) 4909 return ExprError(); 4910 4911 // Okay, we have something that *can* be converted to the right type. Check 4912 // to see if there is a potentially weird extension going on here. This can 4913 // happen when you do an atomic operation on something like an char* and 4914 // pass in 42. The 42 gets converted to char. This is even more strange 4915 // for things like 45.123 -> char, etc. 4916 // FIXME: Do this check. 4917 TheCall->setArg(i+1, Arg.get()); 4918 } 4919 4920 // Create a new DeclRefExpr to refer to the new decl. 4921 DeclRefExpr *NewDRE = DeclRefExpr::Create( 4922 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 4923 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 4924 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 4925 4926 // Set the callee in the CallExpr. 4927 // FIXME: This loses syntactic information. 4928 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 4929 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 4930 CK_BuiltinFnToFnPtr); 4931 TheCall->setCallee(PromotedCall.get()); 4932 4933 // Change the result type of the call to match the original value type. This 4934 // is arbitrary, but the codegen for these builtins ins design to handle it 4935 // gracefully. 4936 TheCall->setType(ResultType); 4937 4938 return TheCallResult; 4939 } 4940 4941 /// SemaBuiltinNontemporalOverloaded - We have a call to 4942 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 4943 /// overloaded function based on the pointer type of its last argument. 4944 /// 4945 /// This function goes through and does final semantic checking for these 4946 /// builtins. 4947 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 4948 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 4949 DeclRefExpr *DRE = 4950 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4951 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4952 unsigned BuiltinID = FDecl->getBuiltinID(); 4953 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 4954 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 4955 "Unexpected nontemporal load/store builtin!"); 4956 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 4957 unsigned numArgs = isStore ? 2 : 1; 4958 4959 // Ensure that we have the proper number of arguments. 4960 if (checkArgCount(*this, TheCall, numArgs)) 4961 return ExprError(); 4962 4963 // Inspect the last argument of the nontemporal builtin. This should always 4964 // be a pointer type, from which we imply the type of the memory access. 4965 // Because it is a pointer type, we don't have to worry about any implicit 4966 // casts here. 4967 Expr *PointerArg = TheCall->getArg(numArgs - 1); 4968 ExprResult PointerArgResult = 4969 DefaultFunctionArrayLvalueConversion(PointerArg); 4970 4971 if (PointerArgResult.isInvalid()) 4972 return ExprError(); 4973 PointerArg = PointerArgResult.get(); 4974 TheCall->setArg(numArgs - 1, PointerArg); 4975 4976 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 4977 if (!pointerType) { 4978 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 4979 << PointerArg->getType() << PointerArg->getSourceRange(); 4980 return ExprError(); 4981 } 4982 4983 QualType ValType = pointerType->getPointeeType(); 4984 4985 // Strip any qualifiers off ValType. 4986 ValType = ValType.getUnqualifiedType(); 4987 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4988 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 4989 !ValType->isVectorType()) { 4990 Diag(DRE->getBeginLoc(), 4991 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 4992 << PointerArg->getType() << PointerArg->getSourceRange(); 4993 return ExprError(); 4994 } 4995 4996 if (!isStore) { 4997 TheCall->setType(ValType); 4998 return TheCallResult; 4999 } 5000 5001 ExprResult ValArg = TheCall->getArg(0); 5002 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5003 Context, ValType, /*consume*/ false); 5004 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5005 if (ValArg.isInvalid()) 5006 return ExprError(); 5007 5008 TheCall->setArg(0, ValArg.get()); 5009 TheCall->setType(Context.VoidTy); 5010 return TheCallResult; 5011 } 5012 5013 /// CheckObjCString - Checks that the argument to the builtin 5014 /// CFString constructor is correct 5015 /// Note: It might also make sense to do the UTF-16 conversion here (would 5016 /// simplify the backend). 5017 bool Sema::CheckObjCString(Expr *Arg) { 5018 Arg = Arg->IgnoreParenCasts(); 5019 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5020 5021 if (!Literal || !Literal->isAscii()) { 5022 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5023 << Arg->getSourceRange(); 5024 return true; 5025 } 5026 5027 if (Literal->containsNonAsciiOrNull()) { 5028 StringRef String = Literal->getString(); 5029 unsigned NumBytes = String.size(); 5030 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5031 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5032 llvm::UTF16 *ToPtr = &ToBuf[0]; 5033 5034 llvm::ConversionResult Result = 5035 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5036 ToPtr + NumBytes, llvm::strictConversion); 5037 // Check for conversion failure. 5038 if (Result != llvm::conversionOK) 5039 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5040 << Arg->getSourceRange(); 5041 } 5042 return false; 5043 } 5044 5045 /// CheckObjCString - Checks that the format string argument to the os_log() 5046 /// and os_trace() functions is correct, and converts it to const char *. 5047 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5048 Arg = Arg->IgnoreParenCasts(); 5049 auto *Literal = dyn_cast<StringLiteral>(Arg); 5050 if (!Literal) { 5051 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5052 Literal = ObjcLiteral->getString(); 5053 } 5054 } 5055 5056 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5057 return ExprError( 5058 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5059 << Arg->getSourceRange()); 5060 } 5061 5062 ExprResult Result(Literal); 5063 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5064 InitializedEntity Entity = 5065 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5066 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5067 return Result; 5068 } 5069 5070 /// Check that the user is calling the appropriate va_start builtin for the 5071 /// target and calling convention. 5072 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5073 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5074 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5075 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5076 TT.getArch() == llvm::Triple::aarch64_32); 5077 bool IsWindows = TT.isOSWindows(); 5078 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5079 if (IsX64 || IsAArch64) { 5080 CallingConv CC = CC_C; 5081 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5082 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5083 if (IsMSVAStart) { 5084 // Don't allow this in System V ABI functions. 5085 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5086 return S.Diag(Fn->getBeginLoc(), 5087 diag::err_ms_va_start_used_in_sysv_function); 5088 } else { 5089 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5090 // On x64 Windows, don't allow this in System V ABI functions. 5091 // (Yes, that means there's no corresponding way to support variadic 5092 // System V ABI functions on Windows.) 5093 if ((IsWindows && CC == CC_X86_64SysV) || 5094 (!IsWindows && CC == CC_Win64)) 5095 return S.Diag(Fn->getBeginLoc(), 5096 diag::err_va_start_used_in_wrong_abi_function) 5097 << !IsWindows; 5098 } 5099 return false; 5100 } 5101 5102 if (IsMSVAStart) 5103 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5104 return false; 5105 } 5106 5107 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5108 ParmVarDecl **LastParam = nullptr) { 5109 // Determine whether the current function, block, or obj-c method is variadic 5110 // and get its parameter list. 5111 bool IsVariadic = false; 5112 ArrayRef<ParmVarDecl *> Params; 5113 DeclContext *Caller = S.CurContext; 5114 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5115 IsVariadic = Block->isVariadic(); 5116 Params = Block->parameters(); 5117 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5118 IsVariadic = FD->isVariadic(); 5119 Params = FD->parameters(); 5120 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5121 IsVariadic = MD->isVariadic(); 5122 // FIXME: This isn't correct for methods (results in bogus warning). 5123 Params = MD->parameters(); 5124 } else if (isa<CapturedDecl>(Caller)) { 5125 // We don't support va_start in a CapturedDecl. 5126 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5127 return true; 5128 } else { 5129 // This must be some other declcontext that parses exprs. 5130 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5131 return true; 5132 } 5133 5134 if (!IsVariadic) { 5135 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5136 return true; 5137 } 5138 5139 if (LastParam) 5140 *LastParam = Params.empty() ? nullptr : Params.back(); 5141 5142 return false; 5143 } 5144 5145 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5146 /// for validity. Emit an error and return true on failure; return false 5147 /// on success. 5148 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5149 Expr *Fn = TheCall->getCallee(); 5150 5151 if (checkVAStartABI(*this, BuiltinID, Fn)) 5152 return true; 5153 5154 if (TheCall->getNumArgs() > 2) { 5155 Diag(TheCall->getArg(2)->getBeginLoc(), 5156 diag::err_typecheck_call_too_many_args) 5157 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5158 << Fn->getSourceRange() 5159 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5160 (*(TheCall->arg_end() - 1))->getEndLoc()); 5161 return true; 5162 } 5163 5164 if (TheCall->getNumArgs() < 2) { 5165 return Diag(TheCall->getEndLoc(), 5166 diag::err_typecheck_call_too_few_args_at_least) 5167 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5168 } 5169 5170 // Type-check the first argument normally. 5171 if (checkBuiltinArgument(*this, TheCall, 0)) 5172 return true; 5173 5174 // Check that the current function is variadic, and get its last parameter. 5175 ParmVarDecl *LastParam; 5176 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5177 return true; 5178 5179 // Verify that the second argument to the builtin is the last argument of the 5180 // current function or method. 5181 bool SecondArgIsLastNamedArgument = false; 5182 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5183 5184 // These are valid if SecondArgIsLastNamedArgument is false after the next 5185 // block. 5186 QualType Type; 5187 SourceLocation ParamLoc; 5188 bool IsCRegister = false; 5189 5190 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5191 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5192 SecondArgIsLastNamedArgument = PV == LastParam; 5193 5194 Type = PV->getType(); 5195 ParamLoc = PV->getLocation(); 5196 IsCRegister = 5197 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5198 } 5199 } 5200 5201 if (!SecondArgIsLastNamedArgument) 5202 Diag(TheCall->getArg(1)->getBeginLoc(), 5203 diag::warn_second_arg_of_va_start_not_last_named_param); 5204 else if (IsCRegister || Type->isReferenceType() || 5205 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5206 // Promotable integers are UB, but enumerations need a bit of 5207 // extra checking to see what their promotable type actually is. 5208 if (!Type->isPromotableIntegerType()) 5209 return false; 5210 if (!Type->isEnumeralType()) 5211 return true; 5212 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5213 return !(ED && 5214 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5215 }()) { 5216 unsigned Reason = 0; 5217 if (Type->isReferenceType()) Reason = 1; 5218 else if (IsCRegister) Reason = 2; 5219 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5220 Diag(ParamLoc, diag::note_parameter_type) << Type; 5221 } 5222 5223 TheCall->setType(Context.VoidTy); 5224 return false; 5225 } 5226 5227 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5228 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5229 // const char *named_addr); 5230 5231 Expr *Func = Call->getCallee(); 5232 5233 if (Call->getNumArgs() < 3) 5234 return Diag(Call->getEndLoc(), 5235 diag::err_typecheck_call_too_few_args_at_least) 5236 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5237 5238 // Type-check the first argument normally. 5239 if (checkBuiltinArgument(*this, Call, 0)) 5240 return true; 5241 5242 // Check that the current function is variadic. 5243 if (checkVAStartIsInVariadicFunction(*this, Func)) 5244 return true; 5245 5246 // __va_start on Windows does not validate the parameter qualifiers 5247 5248 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5249 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5250 5251 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5252 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5253 5254 const QualType &ConstCharPtrTy = 5255 Context.getPointerType(Context.CharTy.withConst()); 5256 if (!Arg1Ty->isPointerType() || 5257 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5258 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5259 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5260 << 0 /* qualifier difference */ 5261 << 3 /* parameter mismatch */ 5262 << 2 << Arg1->getType() << ConstCharPtrTy; 5263 5264 const QualType SizeTy = Context.getSizeType(); 5265 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5266 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5267 << Arg2->getType() << SizeTy << 1 /* different class */ 5268 << 0 /* qualifier difference */ 5269 << 3 /* parameter mismatch */ 5270 << 3 << Arg2->getType() << SizeTy; 5271 5272 return false; 5273 } 5274 5275 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5276 /// friends. This is declared to take (...), so we have to check everything. 5277 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5278 if (TheCall->getNumArgs() < 2) 5279 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5280 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5281 if (TheCall->getNumArgs() > 2) 5282 return Diag(TheCall->getArg(2)->getBeginLoc(), 5283 diag::err_typecheck_call_too_many_args) 5284 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5285 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5286 (*(TheCall->arg_end() - 1))->getEndLoc()); 5287 5288 ExprResult OrigArg0 = TheCall->getArg(0); 5289 ExprResult OrigArg1 = TheCall->getArg(1); 5290 5291 // Do standard promotions between the two arguments, returning their common 5292 // type. 5293 QualType Res = UsualArithmeticConversions( 5294 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5295 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5296 return true; 5297 5298 // Make sure any conversions are pushed back into the call; this is 5299 // type safe since unordered compare builtins are declared as "_Bool 5300 // foo(...)". 5301 TheCall->setArg(0, OrigArg0.get()); 5302 TheCall->setArg(1, OrigArg1.get()); 5303 5304 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5305 return false; 5306 5307 // If the common type isn't a real floating type, then the arguments were 5308 // invalid for this operation. 5309 if (Res.isNull() || !Res->isRealFloatingType()) 5310 return Diag(OrigArg0.get()->getBeginLoc(), 5311 diag::err_typecheck_call_invalid_ordered_compare) 5312 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5313 << SourceRange(OrigArg0.get()->getBeginLoc(), 5314 OrigArg1.get()->getEndLoc()); 5315 5316 return false; 5317 } 5318 5319 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5320 /// __builtin_isnan and friends. This is declared to take (...), so we have 5321 /// to check everything. We expect the last argument to be a floating point 5322 /// value. 5323 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5324 if (TheCall->getNumArgs() < NumArgs) 5325 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5326 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5327 if (TheCall->getNumArgs() > NumArgs) 5328 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5329 diag::err_typecheck_call_too_many_args) 5330 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5331 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5332 (*(TheCall->arg_end() - 1))->getEndLoc()); 5333 5334 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5335 // on all preceding parameters just being int. Try all of those. 5336 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5337 Expr *Arg = TheCall->getArg(i); 5338 5339 if (Arg->isTypeDependent()) 5340 return false; 5341 5342 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5343 5344 if (Res.isInvalid()) 5345 return true; 5346 TheCall->setArg(i, Res.get()); 5347 } 5348 5349 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5350 5351 if (OrigArg->isTypeDependent()) 5352 return false; 5353 5354 // Usual Unary Conversions will convert half to float, which we want for 5355 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5356 // type how it is, but do normal L->Rvalue conversions. 5357 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5358 OrigArg = UsualUnaryConversions(OrigArg).get(); 5359 else 5360 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5361 TheCall->setArg(NumArgs - 1, OrigArg); 5362 5363 // This operation requires a non-_Complex floating-point number. 5364 if (!OrigArg->getType()->isRealFloatingType()) 5365 return Diag(OrigArg->getBeginLoc(), 5366 diag::err_typecheck_call_invalid_unary_fp) 5367 << OrigArg->getType() << OrigArg->getSourceRange(); 5368 5369 return false; 5370 } 5371 5372 // Customized Sema Checking for VSX builtins that have the following signature: 5373 // vector [...] builtinName(vector [...], vector [...], const int); 5374 // Which takes the same type of vectors (any legal vector type) for the first 5375 // two arguments and takes compile time constant for the third argument. 5376 // Example builtins are : 5377 // vector double vec_xxpermdi(vector double, vector double, int); 5378 // vector short vec_xxsldwi(vector short, vector short, int); 5379 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5380 unsigned ExpectedNumArgs = 3; 5381 if (TheCall->getNumArgs() < ExpectedNumArgs) 5382 return Diag(TheCall->getEndLoc(), 5383 diag::err_typecheck_call_too_few_args_at_least) 5384 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5385 << TheCall->getSourceRange(); 5386 5387 if (TheCall->getNumArgs() > ExpectedNumArgs) 5388 return Diag(TheCall->getEndLoc(), 5389 diag::err_typecheck_call_too_many_args_at_most) 5390 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5391 << TheCall->getSourceRange(); 5392 5393 // Check the third argument is a compile time constant 5394 llvm::APSInt Value; 5395 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5396 return Diag(TheCall->getBeginLoc(), 5397 diag::err_vsx_builtin_nonconstant_argument) 5398 << 3 /* argument index */ << TheCall->getDirectCallee() 5399 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5400 TheCall->getArg(2)->getEndLoc()); 5401 5402 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5403 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5404 5405 // Check the type of argument 1 and argument 2 are vectors. 5406 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5407 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5408 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5409 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5410 << TheCall->getDirectCallee() 5411 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5412 TheCall->getArg(1)->getEndLoc()); 5413 } 5414 5415 // Check the first two arguments are the same type. 5416 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5417 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5418 << TheCall->getDirectCallee() 5419 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5420 TheCall->getArg(1)->getEndLoc()); 5421 } 5422 5423 // When default clang type checking is turned off and the customized type 5424 // checking is used, the returning type of the function must be explicitly 5425 // set. Otherwise it is _Bool by default. 5426 TheCall->setType(Arg1Ty); 5427 5428 return false; 5429 } 5430 5431 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5432 // This is declared to take (...), so we have to check everything. 5433 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5434 if (TheCall->getNumArgs() < 2) 5435 return ExprError(Diag(TheCall->getEndLoc(), 5436 diag::err_typecheck_call_too_few_args_at_least) 5437 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5438 << TheCall->getSourceRange()); 5439 5440 // Determine which of the following types of shufflevector we're checking: 5441 // 1) unary, vector mask: (lhs, mask) 5442 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5443 QualType resType = TheCall->getArg(0)->getType(); 5444 unsigned numElements = 0; 5445 5446 if (!TheCall->getArg(0)->isTypeDependent() && 5447 !TheCall->getArg(1)->isTypeDependent()) { 5448 QualType LHSType = TheCall->getArg(0)->getType(); 5449 QualType RHSType = TheCall->getArg(1)->getType(); 5450 5451 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5452 return ExprError( 5453 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5454 << TheCall->getDirectCallee() 5455 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5456 TheCall->getArg(1)->getEndLoc())); 5457 5458 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5459 unsigned numResElements = TheCall->getNumArgs() - 2; 5460 5461 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5462 // with mask. If so, verify that RHS is an integer vector type with the 5463 // same number of elts as lhs. 5464 if (TheCall->getNumArgs() == 2) { 5465 if (!RHSType->hasIntegerRepresentation() || 5466 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5467 return ExprError(Diag(TheCall->getBeginLoc(), 5468 diag::err_vec_builtin_incompatible_vector) 5469 << TheCall->getDirectCallee() 5470 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5471 TheCall->getArg(1)->getEndLoc())); 5472 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5473 return ExprError(Diag(TheCall->getBeginLoc(), 5474 diag::err_vec_builtin_incompatible_vector) 5475 << TheCall->getDirectCallee() 5476 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5477 TheCall->getArg(1)->getEndLoc())); 5478 } else if (numElements != numResElements) { 5479 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5480 resType = Context.getVectorType(eltType, numResElements, 5481 VectorType::GenericVector); 5482 } 5483 } 5484 5485 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5486 if (TheCall->getArg(i)->isTypeDependent() || 5487 TheCall->getArg(i)->isValueDependent()) 5488 continue; 5489 5490 llvm::APSInt Result(32); 5491 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5492 return ExprError(Diag(TheCall->getBeginLoc(), 5493 diag::err_shufflevector_nonconstant_argument) 5494 << TheCall->getArg(i)->getSourceRange()); 5495 5496 // Allow -1 which will be translated to undef in the IR. 5497 if (Result.isSigned() && Result.isAllOnesValue()) 5498 continue; 5499 5500 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5501 return ExprError(Diag(TheCall->getBeginLoc(), 5502 diag::err_shufflevector_argument_too_large) 5503 << TheCall->getArg(i)->getSourceRange()); 5504 } 5505 5506 SmallVector<Expr*, 32> exprs; 5507 5508 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5509 exprs.push_back(TheCall->getArg(i)); 5510 TheCall->setArg(i, nullptr); 5511 } 5512 5513 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5514 TheCall->getCallee()->getBeginLoc(), 5515 TheCall->getRParenLoc()); 5516 } 5517 5518 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5519 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5520 SourceLocation BuiltinLoc, 5521 SourceLocation RParenLoc) { 5522 ExprValueKind VK = VK_RValue; 5523 ExprObjectKind OK = OK_Ordinary; 5524 QualType DstTy = TInfo->getType(); 5525 QualType SrcTy = E->getType(); 5526 5527 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5528 return ExprError(Diag(BuiltinLoc, 5529 diag::err_convertvector_non_vector) 5530 << E->getSourceRange()); 5531 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5532 return ExprError(Diag(BuiltinLoc, 5533 diag::err_convertvector_non_vector_type)); 5534 5535 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5536 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5537 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5538 if (SrcElts != DstElts) 5539 return ExprError(Diag(BuiltinLoc, 5540 diag::err_convertvector_incompatible_vector) 5541 << E->getSourceRange()); 5542 } 5543 5544 return new (Context) 5545 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5546 } 5547 5548 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5549 // This is declared to take (const void*, ...) and can take two 5550 // optional constant int args. 5551 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5552 unsigned NumArgs = TheCall->getNumArgs(); 5553 5554 if (NumArgs > 3) 5555 return Diag(TheCall->getEndLoc(), 5556 diag::err_typecheck_call_too_many_args_at_most) 5557 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5558 5559 // Argument 0 is checked for us and the remaining arguments must be 5560 // constant integers. 5561 for (unsigned i = 1; i != NumArgs; ++i) 5562 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5563 return true; 5564 5565 return false; 5566 } 5567 5568 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5569 // __assume does not evaluate its arguments, and should warn if its argument 5570 // has side effects. 5571 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5572 Expr *Arg = TheCall->getArg(0); 5573 if (Arg->isInstantiationDependent()) return false; 5574 5575 if (Arg->HasSideEffects(Context)) 5576 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5577 << Arg->getSourceRange() 5578 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5579 5580 return false; 5581 } 5582 5583 /// Handle __builtin_alloca_with_align. This is declared 5584 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5585 /// than 8. 5586 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5587 // The alignment must be a constant integer. 5588 Expr *Arg = TheCall->getArg(1); 5589 5590 // We can't check the value of a dependent argument. 5591 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5592 if (const auto *UE = 5593 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5594 if (UE->getKind() == UETT_AlignOf || 5595 UE->getKind() == UETT_PreferredAlignOf) 5596 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5597 << Arg->getSourceRange(); 5598 5599 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5600 5601 if (!Result.isPowerOf2()) 5602 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5603 << Arg->getSourceRange(); 5604 5605 if (Result < Context.getCharWidth()) 5606 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5607 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5608 5609 if (Result > std::numeric_limits<int32_t>::max()) 5610 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5611 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5612 } 5613 5614 return false; 5615 } 5616 5617 /// Handle __builtin_assume_aligned. This is declared 5618 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5619 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5620 unsigned NumArgs = TheCall->getNumArgs(); 5621 5622 if (NumArgs > 3) 5623 return Diag(TheCall->getEndLoc(), 5624 diag::err_typecheck_call_too_many_args_at_most) 5625 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5626 5627 // The alignment must be a constant integer. 5628 Expr *Arg = TheCall->getArg(1); 5629 5630 // We can't check the value of a dependent argument. 5631 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5632 llvm::APSInt Result; 5633 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5634 return true; 5635 5636 if (!Result.isPowerOf2()) 5637 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5638 << Arg->getSourceRange(); 5639 5640 if (Result > Sema::MaximumAlignment) 5641 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 5642 << Arg->getSourceRange() << Sema::MaximumAlignment; 5643 } 5644 5645 if (NumArgs > 2) { 5646 ExprResult Arg(TheCall->getArg(2)); 5647 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5648 Context.getSizeType(), false); 5649 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5650 if (Arg.isInvalid()) return true; 5651 TheCall->setArg(2, Arg.get()); 5652 } 5653 5654 return false; 5655 } 5656 5657 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5658 unsigned BuiltinID = 5659 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5660 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5661 5662 unsigned NumArgs = TheCall->getNumArgs(); 5663 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5664 if (NumArgs < NumRequiredArgs) { 5665 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5666 << 0 /* function call */ << NumRequiredArgs << NumArgs 5667 << TheCall->getSourceRange(); 5668 } 5669 if (NumArgs >= NumRequiredArgs + 0x100) { 5670 return Diag(TheCall->getEndLoc(), 5671 diag::err_typecheck_call_too_many_args_at_most) 5672 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5673 << TheCall->getSourceRange(); 5674 } 5675 unsigned i = 0; 5676 5677 // For formatting call, check buffer arg. 5678 if (!IsSizeCall) { 5679 ExprResult Arg(TheCall->getArg(i)); 5680 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5681 Context, Context.VoidPtrTy, false); 5682 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5683 if (Arg.isInvalid()) 5684 return true; 5685 TheCall->setArg(i, Arg.get()); 5686 i++; 5687 } 5688 5689 // Check string literal arg. 5690 unsigned FormatIdx = i; 5691 { 5692 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5693 if (Arg.isInvalid()) 5694 return true; 5695 TheCall->setArg(i, Arg.get()); 5696 i++; 5697 } 5698 5699 // Make sure variadic args are scalar. 5700 unsigned FirstDataArg = i; 5701 while (i < NumArgs) { 5702 ExprResult Arg = DefaultVariadicArgumentPromotion( 5703 TheCall->getArg(i), VariadicFunction, nullptr); 5704 if (Arg.isInvalid()) 5705 return true; 5706 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5707 if (ArgSize.getQuantity() >= 0x100) { 5708 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5709 << i << (int)ArgSize.getQuantity() << 0xff 5710 << TheCall->getSourceRange(); 5711 } 5712 TheCall->setArg(i, Arg.get()); 5713 i++; 5714 } 5715 5716 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5717 // call to avoid duplicate diagnostics. 5718 if (!IsSizeCall) { 5719 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5720 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5721 bool Success = CheckFormatArguments( 5722 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5723 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5724 CheckedVarArgs); 5725 if (!Success) 5726 return true; 5727 } 5728 5729 if (IsSizeCall) { 5730 TheCall->setType(Context.getSizeType()); 5731 } else { 5732 TheCall->setType(Context.VoidPtrTy); 5733 } 5734 return false; 5735 } 5736 5737 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5738 /// TheCall is a constant expression. 5739 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5740 llvm::APSInt &Result) { 5741 Expr *Arg = TheCall->getArg(ArgNum); 5742 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5743 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5744 5745 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5746 5747 if (!Arg->isIntegerConstantExpr(Result, Context)) 5748 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5749 << FDecl->getDeclName() << Arg->getSourceRange(); 5750 5751 return false; 5752 } 5753 5754 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5755 /// TheCall is a constant expression in the range [Low, High]. 5756 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5757 int Low, int High, bool RangeIsError) { 5758 if (isConstantEvaluated()) 5759 return false; 5760 llvm::APSInt Result; 5761 5762 // We can't check the value of a dependent argument. 5763 Expr *Arg = TheCall->getArg(ArgNum); 5764 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5765 return false; 5766 5767 // Check constant-ness first. 5768 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5769 return true; 5770 5771 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5772 if (RangeIsError) 5773 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5774 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5775 else 5776 // Defer the warning until we know if the code will be emitted so that 5777 // dead code can ignore this. 5778 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5779 PDiag(diag::warn_argument_invalid_range) 5780 << Result.toString(10) << Low << High 5781 << Arg->getSourceRange()); 5782 } 5783 5784 return false; 5785 } 5786 5787 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5788 /// TheCall is a constant expression is a multiple of Num.. 5789 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5790 unsigned Num) { 5791 llvm::APSInt Result; 5792 5793 // We can't check the value of a dependent argument. 5794 Expr *Arg = TheCall->getArg(ArgNum); 5795 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5796 return false; 5797 5798 // Check constant-ness first. 5799 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5800 return true; 5801 5802 if (Result.getSExtValue() % Num != 0) 5803 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5804 << Num << Arg->getSourceRange(); 5805 5806 return false; 5807 } 5808 5809 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 5810 /// constant expression representing a power of 2. 5811 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 5812 llvm::APSInt Result; 5813 5814 // We can't check the value of a dependent argument. 5815 Expr *Arg = TheCall->getArg(ArgNum); 5816 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5817 return false; 5818 5819 // Check constant-ness first. 5820 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5821 return true; 5822 5823 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 5824 // and only if x is a power of 2. 5825 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 5826 return false; 5827 5828 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 5829 << Arg->getSourceRange(); 5830 } 5831 5832 static bool IsShiftedByte(llvm::APSInt Value) { 5833 if (Value.isNegative()) 5834 return false; 5835 5836 // Check if it's a shifted byte, by shifting it down 5837 while (true) { 5838 // If the value fits in the bottom byte, the check passes. 5839 if (Value < 0x100) 5840 return true; 5841 5842 // Otherwise, if the value has _any_ bits in the bottom byte, the check 5843 // fails. 5844 if ((Value & 0xFF) != 0) 5845 return false; 5846 5847 // If the bottom 8 bits are all 0, but something above that is nonzero, 5848 // then shifting the value right by 8 bits won't affect whether it's a 5849 // shifted byte or not. So do that, and go round again. 5850 Value >>= 8; 5851 } 5852 } 5853 5854 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 5855 /// a constant expression representing an arbitrary byte value shifted left by 5856 /// a multiple of 8 bits. 5857 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 5858 unsigned ArgBits) { 5859 llvm::APSInt Result; 5860 5861 // We can't check the value of a dependent argument. 5862 Expr *Arg = TheCall->getArg(ArgNum); 5863 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5864 return false; 5865 5866 // Check constant-ness first. 5867 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5868 return true; 5869 5870 // Truncate to the given size. 5871 Result = Result.getLoBits(ArgBits); 5872 Result.setIsUnsigned(true); 5873 5874 if (IsShiftedByte(Result)) 5875 return false; 5876 5877 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 5878 << Arg->getSourceRange(); 5879 } 5880 5881 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 5882 /// TheCall is a constant expression representing either a shifted byte value, 5883 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 5884 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 5885 /// Arm MVE intrinsics. 5886 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 5887 int ArgNum, 5888 unsigned ArgBits) { 5889 llvm::APSInt Result; 5890 5891 // We can't check the value of a dependent argument. 5892 Expr *Arg = TheCall->getArg(ArgNum); 5893 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5894 return false; 5895 5896 // Check constant-ness first. 5897 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5898 return true; 5899 5900 // Truncate to the given size. 5901 Result = Result.getLoBits(ArgBits); 5902 Result.setIsUnsigned(true); 5903 5904 // Check to see if it's in either of the required forms. 5905 if (IsShiftedByte(Result) || 5906 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 5907 return false; 5908 5909 return Diag(TheCall->getBeginLoc(), 5910 diag::err_argument_not_shifted_byte_or_xxff) 5911 << Arg->getSourceRange(); 5912 } 5913 5914 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 5915 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 5916 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 5917 if (checkArgCount(*this, TheCall, 2)) 5918 return true; 5919 Expr *Arg0 = TheCall->getArg(0); 5920 Expr *Arg1 = TheCall->getArg(1); 5921 5922 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 5923 if (FirstArg.isInvalid()) 5924 return true; 5925 QualType FirstArgType = FirstArg.get()->getType(); 5926 if (!FirstArgType->isAnyPointerType()) 5927 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 5928 << "first" << FirstArgType << Arg0->getSourceRange(); 5929 TheCall->setArg(0, FirstArg.get()); 5930 5931 ExprResult SecArg = DefaultLvalueConversion(Arg1); 5932 if (SecArg.isInvalid()) 5933 return true; 5934 QualType SecArgType = SecArg.get()->getType(); 5935 if (!SecArgType->isIntegerType()) 5936 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 5937 << "second" << SecArgType << Arg1->getSourceRange(); 5938 5939 // Derive the return type from the pointer argument. 5940 TheCall->setType(FirstArgType); 5941 return false; 5942 } 5943 5944 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 5945 if (checkArgCount(*this, TheCall, 2)) 5946 return true; 5947 5948 Expr *Arg0 = TheCall->getArg(0); 5949 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 5950 if (FirstArg.isInvalid()) 5951 return true; 5952 QualType FirstArgType = FirstArg.get()->getType(); 5953 if (!FirstArgType->isAnyPointerType()) 5954 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 5955 << "first" << FirstArgType << Arg0->getSourceRange(); 5956 TheCall->setArg(0, FirstArg.get()); 5957 5958 // Derive the return type from the pointer argument. 5959 TheCall->setType(FirstArgType); 5960 5961 // Second arg must be an constant in range [0,15] 5962 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 5963 } 5964 5965 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 5966 if (checkArgCount(*this, TheCall, 2)) 5967 return true; 5968 Expr *Arg0 = TheCall->getArg(0); 5969 Expr *Arg1 = TheCall->getArg(1); 5970 5971 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 5972 if (FirstArg.isInvalid()) 5973 return true; 5974 QualType FirstArgType = FirstArg.get()->getType(); 5975 if (!FirstArgType->isAnyPointerType()) 5976 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 5977 << "first" << FirstArgType << Arg0->getSourceRange(); 5978 5979 QualType SecArgType = Arg1->getType(); 5980 if (!SecArgType->isIntegerType()) 5981 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 5982 << "second" << SecArgType << Arg1->getSourceRange(); 5983 TheCall->setType(Context.IntTy); 5984 return false; 5985 } 5986 5987 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 5988 BuiltinID == AArch64::BI__builtin_arm_stg) { 5989 if (checkArgCount(*this, TheCall, 1)) 5990 return true; 5991 Expr *Arg0 = TheCall->getArg(0); 5992 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 5993 if (FirstArg.isInvalid()) 5994 return true; 5995 5996 QualType FirstArgType = FirstArg.get()->getType(); 5997 if (!FirstArgType->isAnyPointerType()) 5998 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 5999 << "first" << FirstArgType << Arg0->getSourceRange(); 6000 TheCall->setArg(0, FirstArg.get()); 6001 6002 // Derive the return type from the pointer argument. 6003 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6004 TheCall->setType(FirstArgType); 6005 return false; 6006 } 6007 6008 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6009 Expr *ArgA = TheCall->getArg(0); 6010 Expr *ArgB = TheCall->getArg(1); 6011 6012 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6013 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6014 6015 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6016 return true; 6017 6018 QualType ArgTypeA = ArgExprA.get()->getType(); 6019 QualType ArgTypeB = ArgExprB.get()->getType(); 6020 6021 auto isNull = [&] (Expr *E) -> bool { 6022 return E->isNullPointerConstant( 6023 Context, Expr::NPC_ValueDependentIsNotNull); }; 6024 6025 // argument should be either a pointer or null 6026 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6027 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6028 << "first" << ArgTypeA << ArgA->getSourceRange(); 6029 6030 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6031 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6032 << "second" << ArgTypeB << ArgB->getSourceRange(); 6033 6034 // Ensure Pointee types are compatible 6035 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6036 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6037 QualType pointeeA = ArgTypeA->getPointeeType(); 6038 QualType pointeeB = ArgTypeB->getPointeeType(); 6039 if (!Context.typesAreCompatible( 6040 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6041 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6042 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6043 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6044 << ArgB->getSourceRange(); 6045 } 6046 } 6047 6048 // at least one argument should be pointer type 6049 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6050 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6051 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6052 6053 if (isNull(ArgA)) // adopt type of the other pointer 6054 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6055 6056 if (isNull(ArgB)) 6057 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6058 6059 TheCall->setArg(0, ArgExprA.get()); 6060 TheCall->setArg(1, ArgExprB.get()); 6061 TheCall->setType(Context.LongLongTy); 6062 return false; 6063 } 6064 assert(false && "Unhandled ARM MTE intrinsic"); 6065 return true; 6066 } 6067 6068 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6069 /// TheCall is an ARM/AArch64 special register string literal. 6070 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6071 int ArgNum, unsigned ExpectedFieldNum, 6072 bool AllowName) { 6073 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6074 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6075 BuiltinID == ARM::BI__builtin_arm_rsr || 6076 BuiltinID == ARM::BI__builtin_arm_rsrp || 6077 BuiltinID == ARM::BI__builtin_arm_wsr || 6078 BuiltinID == ARM::BI__builtin_arm_wsrp; 6079 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6080 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6081 BuiltinID == AArch64::BI__builtin_arm_rsr || 6082 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6083 BuiltinID == AArch64::BI__builtin_arm_wsr || 6084 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6085 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6086 6087 // We can't check the value of a dependent argument. 6088 Expr *Arg = TheCall->getArg(ArgNum); 6089 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6090 return false; 6091 6092 // Check if the argument is a string literal. 6093 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6094 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6095 << Arg->getSourceRange(); 6096 6097 // Check the type of special register given. 6098 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6099 SmallVector<StringRef, 6> Fields; 6100 Reg.split(Fields, ":"); 6101 6102 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6103 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6104 << Arg->getSourceRange(); 6105 6106 // If the string is the name of a register then we cannot check that it is 6107 // valid here but if the string is of one the forms described in ACLE then we 6108 // can check that the supplied fields are integers and within the valid 6109 // ranges. 6110 if (Fields.size() > 1) { 6111 bool FiveFields = Fields.size() == 5; 6112 6113 bool ValidString = true; 6114 if (IsARMBuiltin) { 6115 ValidString &= Fields[0].startswith_lower("cp") || 6116 Fields[0].startswith_lower("p"); 6117 if (ValidString) 6118 Fields[0] = 6119 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6120 6121 ValidString &= Fields[2].startswith_lower("c"); 6122 if (ValidString) 6123 Fields[2] = Fields[2].drop_front(1); 6124 6125 if (FiveFields) { 6126 ValidString &= Fields[3].startswith_lower("c"); 6127 if (ValidString) 6128 Fields[3] = Fields[3].drop_front(1); 6129 } 6130 } 6131 6132 SmallVector<int, 5> Ranges; 6133 if (FiveFields) 6134 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6135 else 6136 Ranges.append({15, 7, 15}); 6137 6138 for (unsigned i=0; i<Fields.size(); ++i) { 6139 int IntField; 6140 ValidString &= !Fields[i].getAsInteger(10, IntField); 6141 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6142 } 6143 6144 if (!ValidString) 6145 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6146 << Arg->getSourceRange(); 6147 } else if (IsAArch64Builtin && Fields.size() == 1) { 6148 // If the register name is one of those that appear in the condition below 6149 // and the special register builtin being used is one of the write builtins, 6150 // then we require that the argument provided for writing to the register 6151 // is an integer constant expression. This is because it will be lowered to 6152 // an MSR (immediate) instruction, so we need to know the immediate at 6153 // compile time. 6154 if (TheCall->getNumArgs() != 2) 6155 return false; 6156 6157 std::string RegLower = Reg.lower(); 6158 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6159 RegLower != "pan" && RegLower != "uao") 6160 return false; 6161 6162 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6163 } 6164 6165 return false; 6166 } 6167 6168 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6169 /// This checks that the target supports __builtin_longjmp and 6170 /// that val is a constant 1. 6171 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6172 if (!Context.getTargetInfo().hasSjLjLowering()) 6173 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6174 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6175 6176 Expr *Arg = TheCall->getArg(1); 6177 llvm::APSInt Result; 6178 6179 // TODO: This is less than ideal. Overload this to take a value. 6180 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6181 return true; 6182 6183 if (Result != 1) 6184 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6185 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6186 6187 return false; 6188 } 6189 6190 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6191 /// This checks that the target supports __builtin_setjmp. 6192 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6193 if (!Context.getTargetInfo().hasSjLjLowering()) 6194 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6195 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6196 return false; 6197 } 6198 6199 namespace { 6200 6201 class UncoveredArgHandler { 6202 enum { Unknown = -1, AllCovered = -2 }; 6203 6204 signed FirstUncoveredArg = Unknown; 6205 SmallVector<const Expr *, 4> DiagnosticExprs; 6206 6207 public: 6208 UncoveredArgHandler() = default; 6209 6210 bool hasUncoveredArg() const { 6211 return (FirstUncoveredArg >= 0); 6212 } 6213 6214 unsigned getUncoveredArg() const { 6215 assert(hasUncoveredArg() && "no uncovered argument"); 6216 return FirstUncoveredArg; 6217 } 6218 6219 void setAllCovered() { 6220 // A string has been found with all arguments covered, so clear out 6221 // the diagnostics. 6222 DiagnosticExprs.clear(); 6223 FirstUncoveredArg = AllCovered; 6224 } 6225 6226 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6227 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6228 6229 // Don't update if a previous string covers all arguments. 6230 if (FirstUncoveredArg == AllCovered) 6231 return; 6232 6233 // UncoveredArgHandler tracks the highest uncovered argument index 6234 // and with it all the strings that match this index. 6235 if (NewFirstUncoveredArg == FirstUncoveredArg) 6236 DiagnosticExprs.push_back(StrExpr); 6237 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6238 DiagnosticExprs.clear(); 6239 DiagnosticExprs.push_back(StrExpr); 6240 FirstUncoveredArg = NewFirstUncoveredArg; 6241 } 6242 } 6243 6244 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6245 }; 6246 6247 enum StringLiteralCheckType { 6248 SLCT_NotALiteral, 6249 SLCT_UncheckedLiteral, 6250 SLCT_CheckedLiteral 6251 }; 6252 6253 } // namespace 6254 6255 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6256 BinaryOperatorKind BinOpKind, 6257 bool AddendIsRight) { 6258 unsigned BitWidth = Offset.getBitWidth(); 6259 unsigned AddendBitWidth = Addend.getBitWidth(); 6260 // There might be negative interim results. 6261 if (Addend.isUnsigned()) { 6262 Addend = Addend.zext(++AddendBitWidth); 6263 Addend.setIsSigned(true); 6264 } 6265 // Adjust the bit width of the APSInts. 6266 if (AddendBitWidth > BitWidth) { 6267 Offset = Offset.sext(AddendBitWidth); 6268 BitWidth = AddendBitWidth; 6269 } else if (BitWidth > AddendBitWidth) { 6270 Addend = Addend.sext(BitWidth); 6271 } 6272 6273 bool Ov = false; 6274 llvm::APSInt ResOffset = Offset; 6275 if (BinOpKind == BO_Add) 6276 ResOffset = Offset.sadd_ov(Addend, Ov); 6277 else { 6278 assert(AddendIsRight && BinOpKind == BO_Sub && 6279 "operator must be add or sub with addend on the right"); 6280 ResOffset = Offset.ssub_ov(Addend, Ov); 6281 } 6282 6283 // We add an offset to a pointer here so we should support an offset as big as 6284 // possible. 6285 if (Ov) { 6286 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6287 "index (intermediate) result too big"); 6288 Offset = Offset.sext(2 * BitWidth); 6289 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6290 return; 6291 } 6292 6293 Offset = ResOffset; 6294 } 6295 6296 namespace { 6297 6298 // This is a wrapper class around StringLiteral to support offsetted string 6299 // literals as format strings. It takes the offset into account when returning 6300 // the string and its length or the source locations to display notes correctly. 6301 class FormatStringLiteral { 6302 const StringLiteral *FExpr; 6303 int64_t Offset; 6304 6305 public: 6306 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6307 : FExpr(fexpr), Offset(Offset) {} 6308 6309 StringRef getString() const { 6310 return FExpr->getString().drop_front(Offset); 6311 } 6312 6313 unsigned getByteLength() const { 6314 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6315 } 6316 6317 unsigned getLength() const { return FExpr->getLength() - Offset; } 6318 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6319 6320 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6321 6322 QualType getType() const { return FExpr->getType(); } 6323 6324 bool isAscii() const { return FExpr->isAscii(); } 6325 bool isWide() const { return FExpr->isWide(); } 6326 bool isUTF8() const { return FExpr->isUTF8(); } 6327 bool isUTF16() const { return FExpr->isUTF16(); } 6328 bool isUTF32() const { return FExpr->isUTF32(); } 6329 bool isPascal() const { return FExpr->isPascal(); } 6330 6331 SourceLocation getLocationOfByte( 6332 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6333 const TargetInfo &Target, unsigned *StartToken = nullptr, 6334 unsigned *StartTokenByteOffset = nullptr) const { 6335 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6336 StartToken, StartTokenByteOffset); 6337 } 6338 6339 SourceLocation getBeginLoc() const LLVM_READONLY { 6340 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6341 } 6342 6343 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6344 }; 6345 6346 } // namespace 6347 6348 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6349 const Expr *OrigFormatExpr, 6350 ArrayRef<const Expr *> Args, 6351 bool HasVAListArg, unsigned format_idx, 6352 unsigned firstDataArg, 6353 Sema::FormatStringType Type, 6354 bool inFunctionCall, 6355 Sema::VariadicCallType CallType, 6356 llvm::SmallBitVector &CheckedVarArgs, 6357 UncoveredArgHandler &UncoveredArg, 6358 bool IgnoreStringsWithoutSpecifiers); 6359 6360 // Determine if an expression is a string literal or constant string. 6361 // If this function returns false on the arguments to a function expecting a 6362 // format string, we will usually need to emit a warning. 6363 // True string literals are then checked by CheckFormatString. 6364 static StringLiteralCheckType 6365 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6366 bool HasVAListArg, unsigned format_idx, 6367 unsigned firstDataArg, Sema::FormatStringType Type, 6368 Sema::VariadicCallType CallType, bool InFunctionCall, 6369 llvm::SmallBitVector &CheckedVarArgs, 6370 UncoveredArgHandler &UncoveredArg, 6371 llvm::APSInt Offset, 6372 bool IgnoreStringsWithoutSpecifiers = false) { 6373 if (S.isConstantEvaluated()) 6374 return SLCT_NotALiteral; 6375 tryAgain: 6376 assert(Offset.isSigned() && "invalid offset"); 6377 6378 if (E->isTypeDependent() || E->isValueDependent()) 6379 return SLCT_NotALiteral; 6380 6381 E = E->IgnoreParenCasts(); 6382 6383 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6384 // Technically -Wformat-nonliteral does not warn about this case. 6385 // The behavior of printf and friends in this case is implementation 6386 // dependent. Ideally if the format string cannot be null then 6387 // it should have a 'nonnull' attribute in the function prototype. 6388 return SLCT_UncheckedLiteral; 6389 6390 switch (E->getStmtClass()) { 6391 case Stmt::BinaryConditionalOperatorClass: 6392 case Stmt::ConditionalOperatorClass: { 6393 // The expression is a literal if both sub-expressions were, and it was 6394 // completely checked only if both sub-expressions were checked. 6395 const AbstractConditionalOperator *C = 6396 cast<AbstractConditionalOperator>(E); 6397 6398 // Determine whether it is necessary to check both sub-expressions, for 6399 // example, because the condition expression is a constant that can be 6400 // evaluated at compile time. 6401 bool CheckLeft = true, CheckRight = true; 6402 6403 bool Cond; 6404 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6405 S.isConstantEvaluated())) { 6406 if (Cond) 6407 CheckRight = false; 6408 else 6409 CheckLeft = false; 6410 } 6411 6412 // We need to maintain the offsets for the right and the left hand side 6413 // separately to check if every possible indexed expression is a valid 6414 // string literal. They might have different offsets for different string 6415 // literals in the end. 6416 StringLiteralCheckType Left; 6417 if (!CheckLeft) 6418 Left = SLCT_UncheckedLiteral; 6419 else { 6420 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6421 HasVAListArg, format_idx, firstDataArg, 6422 Type, CallType, InFunctionCall, 6423 CheckedVarArgs, UncoveredArg, Offset, 6424 IgnoreStringsWithoutSpecifiers); 6425 if (Left == SLCT_NotALiteral || !CheckRight) { 6426 return Left; 6427 } 6428 } 6429 6430 StringLiteralCheckType Right = checkFormatStringExpr( 6431 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6432 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6433 IgnoreStringsWithoutSpecifiers); 6434 6435 return (CheckLeft && Left < Right) ? Left : Right; 6436 } 6437 6438 case Stmt::ImplicitCastExprClass: 6439 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6440 goto tryAgain; 6441 6442 case Stmt::OpaqueValueExprClass: 6443 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6444 E = src; 6445 goto tryAgain; 6446 } 6447 return SLCT_NotALiteral; 6448 6449 case Stmt::PredefinedExprClass: 6450 // While __func__, etc., are technically not string literals, they 6451 // cannot contain format specifiers and thus are not a security 6452 // liability. 6453 return SLCT_UncheckedLiteral; 6454 6455 case Stmt::DeclRefExprClass: { 6456 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6457 6458 // As an exception, do not flag errors for variables binding to 6459 // const string literals. 6460 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6461 bool isConstant = false; 6462 QualType T = DR->getType(); 6463 6464 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6465 isConstant = AT->getElementType().isConstant(S.Context); 6466 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6467 isConstant = T.isConstant(S.Context) && 6468 PT->getPointeeType().isConstant(S.Context); 6469 } else if (T->isObjCObjectPointerType()) { 6470 // In ObjC, there is usually no "const ObjectPointer" type, 6471 // so don't check if the pointee type is constant. 6472 isConstant = T.isConstant(S.Context); 6473 } 6474 6475 if (isConstant) { 6476 if (const Expr *Init = VD->getAnyInitializer()) { 6477 // Look through initializers like const char c[] = { "foo" } 6478 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6479 if (InitList->isStringLiteralInit()) 6480 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6481 } 6482 return checkFormatStringExpr(S, Init, Args, 6483 HasVAListArg, format_idx, 6484 firstDataArg, Type, CallType, 6485 /*InFunctionCall*/ false, CheckedVarArgs, 6486 UncoveredArg, Offset); 6487 } 6488 } 6489 6490 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6491 // special check to see if the format string is a function parameter 6492 // of the function calling the printf function. If the function 6493 // has an attribute indicating it is a printf-like function, then we 6494 // should suppress warnings concerning non-literals being used in a call 6495 // to a vprintf function. For example: 6496 // 6497 // void 6498 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6499 // va_list ap; 6500 // va_start(ap, fmt); 6501 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6502 // ... 6503 // } 6504 if (HasVAListArg) { 6505 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6506 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6507 int PVIndex = PV->getFunctionScopeIndex() + 1; 6508 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6509 // adjust for implicit parameter 6510 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6511 if (MD->isInstance()) 6512 ++PVIndex; 6513 // We also check if the formats are compatible. 6514 // We can't pass a 'scanf' string to a 'printf' function. 6515 if (PVIndex == PVFormat->getFormatIdx() && 6516 Type == S.GetFormatStringType(PVFormat)) 6517 return SLCT_UncheckedLiteral; 6518 } 6519 } 6520 } 6521 } 6522 } 6523 6524 return SLCT_NotALiteral; 6525 } 6526 6527 case Stmt::CallExprClass: 6528 case Stmt::CXXMemberCallExprClass: { 6529 const CallExpr *CE = cast<CallExpr>(E); 6530 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6531 bool IsFirst = true; 6532 StringLiteralCheckType CommonResult; 6533 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6534 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6535 StringLiteralCheckType Result = checkFormatStringExpr( 6536 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6537 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6538 IgnoreStringsWithoutSpecifiers); 6539 if (IsFirst) { 6540 CommonResult = Result; 6541 IsFirst = false; 6542 } 6543 } 6544 if (!IsFirst) 6545 return CommonResult; 6546 6547 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6548 unsigned BuiltinID = FD->getBuiltinID(); 6549 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6550 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6551 const Expr *Arg = CE->getArg(0); 6552 return checkFormatStringExpr(S, Arg, Args, 6553 HasVAListArg, format_idx, 6554 firstDataArg, Type, CallType, 6555 InFunctionCall, CheckedVarArgs, 6556 UncoveredArg, Offset, 6557 IgnoreStringsWithoutSpecifiers); 6558 } 6559 } 6560 } 6561 6562 return SLCT_NotALiteral; 6563 } 6564 case Stmt::ObjCMessageExprClass: { 6565 const auto *ME = cast<ObjCMessageExpr>(E); 6566 if (const auto *MD = ME->getMethodDecl()) { 6567 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 6568 // As a special case heuristic, if we're using the method -[NSBundle 6569 // localizedStringForKey:value:table:], ignore any key strings that lack 6570 // format specifiers. The idea is that if the key doesn't have any 6571 // format specifiers then its probably just a key to map to the 6572 // localized strings. If it does have format specifiers though, then its 6573 // likely that the text of the key is the format string in the 6574 // programmer's language, and should be checked. 6575 const ObjCInterfaceDecl *IFace; 6576 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 6577 IFace->getIdentifier()->isStr("NSBundle") && 6578 MD->getSelector().isKeywordSelector( 6579 {"localizedStringForKey", "value", "table"})) { 6580 IgnoreStringsWithoutSpecifiers = true; 6581 } 6582 6583 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6584 return checkFormatStringExpr( 6585 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6586 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6587 IgnoreStringsWithoutSpecifiers); 6588 } 6589 } 6590 6591 return SLCT_NotALiteral; 6592 } 6593 case Stmt::ObjCStringLiteralClass: 6594 case Stmt::StringLiteralClass: { 6595 const StringLiteral *StrE = nullptr; 6596 6597 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6598 StrE = ObjCFExpr->getString(); 6599 else 6600 StrE = cast<StringLiteral>(E); 6601 6602 if (StrE) { 6603 if (Offset.isNegative() || Offset > StrE->getLength()) { 6604 // TODO: It would be better to have an explicit warning for out of 6605 // bounds literals. 6606 return SLCT_NotALiteral; 6607 } 6608 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6609 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6610 firstDataArg, Type, InFunctionCall, CallType, 6611 CheckedVarArgs, UncoveredArg, 6612 IgnoreStringsWithoutSpecifiers); 6613 return SLCT_CheckedLiteral; 6614 } 6615 6616 return SLCT_NotALiteral; 6617 } 6618 case Stmt::BinaryOperatorClass: { 6619 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6620 6621 // A string literal + an int offset is still a string literal. 6622 if (BinOp->isAdditiveOp()) { 6623 Expr::EvalResult LResult, RResult; 6624 6625 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6626 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6627 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6628 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6629 6630 if (LIsInt != RIsInt) { 6631 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6632 6633 if (LIsInt) { 6634 if (BinOpKind == BO_Add) { 6635 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6636 E = BinOp->getRHS(); 6637 goto tryAgain; 6638 } 6639 } else { 6640 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6641 E = BinOp->getLHS(); 6642 goto tryAgain; 6643 } 6644 } 6645 } 6646 6647 return SLCT_NotALiteral; 6648 } 6649 case Stmt::UnaryOperatorClass: { 6650 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6651 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6652 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6653 Expr::EvalResult IndexResult; 6654 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6655 Expr::SE_NoSideEffects, 6656 S.isConstantEvaluated())) { 6657 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6658 /*RHS is int*/ true); 6659 E = ASE->getBase(); 6660 goto tryAgain; 6661 } 6662 } 6663 6664 return SLCT_NotALiteral; 6665 } 6666 6667 default: 6668 return SLCT_NotALiteral; 6669 } 6670 } 6671 6672 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6673 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6674 .Case("scanf", FST_Scanf) 6675 .Cases("printf", "printf0", FST_Printf) 6676 .Cases("NSString", "CFString", FST_NSString) 6677 .Case("strftime", FST_Strftime) 6678 .Case("strfmon", FST_Strfmon) 6679 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6680 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6681 .Case("os_trace", FST_OSLog) 6682 .Case("os_log", FST_OSLog) 6683 .Default(FST_Unknown); 6684 } 6685 6686 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6687 /// functions) for correct use of format strings. 6688 /// Returns true if a format string has been fully checked. 6689 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6690 ArrayRef<const Expr *> Args, 6691 bool IsCXXMember, 6692 VariadicCallType CallType, 6693 SourceLocation Loc, SourceRange Range, 6694 llvm::SmallBitVector &CheckedVarArgs) { 6695 FormatStringInfo FSI; 6696 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6697 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6698 FSI.FirstDataArg, GetFormatStringType(Format), 6699 CallType, Loc, Range, CheckedVarArgs); 6700 return false; 6701 } 6702 6703 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6704 bool HasVAListArg, unsigned format_idx, 6705 unsigned firstDataArg, FormatStringType Type, 6706 VariadicCallType CallType, 6707 SourceLocation Loc, SourceRange Range, 6708 llvm::SmallBitVector &CheckedVarArgs) { 6709 // CHECK: printf/scanf-like function is called with no format string. 6710 if (format_idx >= Args.size()) { 6711 Diag(Loc, diag::warn_missing_format_string) << Range; 6712 return false; 6713 } 6714 6715 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6716 6717 // CHECK: format string is not a string literal. 6718 // 6719 // Dynamically generated format strings are difficult to 6720 // automatically vet at compile time. Requiring that format strings 6721 // are string literals: (1) permits the checking of format strings by 6722 // the compiler and thereby (2) can practically remove the source of 6723 // many format string exploits. 6724 6725 // Format string can be either ObjC string (e.g. @"%d") or 6726 // C string (e.g. "%d") 6727 // ObjC string uses the same format specifiers as C string, so we can use 6728 // the same format string checking logic for both ObjC and C strings. 6729 UncoveredArgHandler UncoveredArg; 6730 StringLiteralCheckType CT = 6731 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6732 format_idx, firstDataArg, Type, CallType, 6733 /*IsFunctionCall*/ true, CheckedVarArgs, 6734 UncoveredArg, 6735 /*no string offset*/ llvm::APSInt(64, false) = 0); 6736 6737 // Generate a diagnostic where an uncovered argument is detected. 6738 if (UncoveredArg.hasUncoveredArg()) { 6739 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6740 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6741 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6742 } 6743 6744 if (CT != SLCT_NotALiteral) 6745 // Literal format string found, check done! 6746 return CT == SLCT_CheckedLiteral; 6747 6748 // Strftime is particular as it always uses a single 'time' argument, 6749 // so it is safe to pass a non-literal string. 6750 if (Type == FST_Strftime) 6751 return false; 6752 6753 // Do not emit diag when the string param is a macro expansion and the 6754 // format is either NSString or CFString. This is a hack to prevent 6755 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6756 // which are usually used in place of NS and CF string literals. 6757 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6758 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6759 return false; 6760 6761 // If there are no arguments specified, warn with -Wformat-security, otherwise 6762 // warn only with -Wformat-nonliteral. 6763 if (Args.size() == firstDataArg) { 6764 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6765 << OrigFormatExpr->getSourceRange(); 6766 switch (Type) { 6767 default: 6768 break; 6769 case FST_Kprintf: 6770 case FST_FreeBSDKPrintf: 6771 case FST_Printf: 6772 Diag(FormatLoc, diag::note_format_security_fixit) 6773 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6774 break; 6775 case FST_NSString: 6776 Diag(FormatLoc, diag::note_format_security_fixit) 6777 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6778 break; 6779 } 6780 } else { 6781 Diag(FormatLoc, diag::warn_format_nonliteral) 6782 << OrigFormatExpr->getSourceRange(); 6783 } 6784 return false; 6785 } 6786 6787 namespace { 6788 6789 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6790 protected: 6791 Sema &S; 6792 const FormatStringLiteral *FExpr; 6793 const Expr *OrigFormatExpr; 6794 const Sema::FormatStringType FSType; 6795 const unsigned FirstDataArg; 6796 const unsigned NumDataArgs; 6797 const char *Beg; // Start of format string. 6798 const bool HasVAListArg; 6799 ArrayRef<const Expr *> Args; 6800 unsigned FormatIdx; 6801 llvm::SmallBitVector CoveredArgs; 6802 bool usesPositionalArgs = false; 6803 bool atFirstArg = true; 6804 bool inFunctionCall; 6805 Sema::VariadicCallType CallType; 6806 llvm::SmallBitVector &CheckedVarArgs; 6807 UncoveredArgHandler &UncoveredArg; 6808 6809 public: 6810 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6811 const Expr *origFormatExpr, 6812 const Sema::FormatStringType type, unsigned firstDataArg, 6813 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6814 ArrayRef<const Expr *> Args, unsigned formatIdx, 6815 bool inFunctionCall, Sema::VariadicCallType callType, 6816 llvm::SmallBitVector &CheckedVarArgs, 6817 UncoveredArgHandler &UncoveredArg) 6818 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6819 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6820 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6821 inFunctionCall(inFunctionCall), CallType(callType), 6822 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6823 CoveredArgs.resize(numDataArgs); 6824 CoveredArgs.reset(); 6825 } 6826 6827 void DoneProcessing(); 6828 6829 void HandleIncompleteSpecifier(const char *startSpecifier, 6830 unsigned specifierLen) override; 6831 6832 void HandleInvalidLengthModifier( 6833 const analyze_format_string::FormatSpecifier &FS, 6834 const analyze_format_string::ConversionSpecifier &CS, 6835 const char *startSpecifier, unsigned specifierLen, 6836 unsigned DiagID); 6837 6838 void HandleNonStandardLengthModifier( 6839 const analyze_format_string::FormatSpecifier &FS, 6840 const char *startSpecifier, unsigned specifierLen); 6841 6842 void HandleNonStandardConversionSpecifier( 6843 const analyze_format_string::ConversionSpecifier &CS, 6844 const char *startSpecifier, unsigned specifierLen); 6845 6846 void HandlePosition(const char *startPos, unsigned posLen) override; 6847 6848 void HandleInvalidPosition(const char *startSpecifier, 6849 unsigned specifierLen, 6850 analyze_format_string::PositionContext p) override; 6851 6852 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6853 6854 void HandleNullChar(const char *nullCharacter) override; 6855 6856 template <typename Range> 6857 static void 6858 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6859 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6860 bool IsStringLocation, Range StringRange, 6861 ArrayRef<FixItHint> Fixit = None); 6862 6863 protected: 6864 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6865 const char *startSpec, 6866 unsigned specifierLen, 6867 const char *csStart, unsigned csLen); 6868 6869 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6870 const char *startSpec, 6871 unsigned specifierLen); 6872 6873 SourceRange getFormatStringRange(); 6874 CharSourceRange getSpecifierRange(const char *startSpecifier, 6875 unsigned specifierLen); 6876 SourceLocation getLocationOfByte(const char *x); 6877 6878 const Expr *getDataArg(unsigned i) const; 6879 6880 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6881 const analyze_format_string::ConversionSpecifier &CS, 6882 const char *startSpecifier, unsigned specifierLen, 6883 unsigned argIndex); 6884 6885 template <typename Range> 6886 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6887 bool IsStringLocation, Range StringRange, 6888 ArrayRef<FixItHint> Fixit = None); 6889 }; 6890 6891 } // namespace 6892 6893 SourceRange CheckFormatHandler::getFormatStringRange() { 6894 return OrigFormatExpr->getSourceRange(); 6895 } 6896 6897 CharSourceRange CheckFormatHandler:: 6898 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6899 SourceLocation Start = getLocationOfByte(startSpecifier); 6900 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6901 6902 // Advance the end SourceLocation by one due to half-open ranges. 6903 End = End.getLocWithOffset(1); 6904 6905 return CharSourceRange::getCharRange(Start, End); 6906 } 6907 6908 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6909 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6910 S.getLangOpts(), S.Context.getTargetInfo()); 6911 } 6912 6913 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6914 unsigned specifierLen){ 6915 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6916 getLocationOfByte(startSpecifier), 6917 /*IsStringLocation*/true, 6918 getSpecifierRange(startSpecifier, specifierLen)); 6919 } 6920 6921 void CheckFormatHandler::HandleInvalidLengthModifier( 6922 const analyze_format_string::FormatSpecifier &FS, 6923 const analyze_format_string::ConversionSpecifier &CS, 6924 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6925 using namespace analyze_format_string; 6926 6927 const LengthModifier &LM = FS.getLengthModifier(); 6928 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6929 6930 // See if we know how to fix this length modifier. 6931 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6932 if (FixedLM) { 6933 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6934 getLocationOfByte(LM.getStart()), 6935 /*IsStringLocation*/true, 6936 getSpecifierRange(startSpecifier, specifierLen)); 6937 6938 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6939 << FixedLM->toString() 6940 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6941 6942 } else { 6943 FixItHint Hint; 6944 if (DiagID == diag::warn_format_nonsensical_length) 6945 Hint = FixItHint::CreateRemoval(LMRange); 6946 6947 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6948 getLocationOfByte(LM.getStart()), 6949 /*IsStringLocation*/true, 6950 getSpecifierRange(startSpecifier, specifierLen), 6951 Hint); 6952 } 6953 } 6954 6955 void CheckFormatHandler::HandleNonStandardLengthModifier( 6956 const analyze_format_string::FormatSpecifier &FS, 6957 const char *startSpecifier, unsigned specifierLen) { 6958 using namespace analyze_format_string; 6959 6960 const LengthModifier &LM = FS.getLengthModifier(); 6961 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6962 6963 // See if we know how to fix this length modifier. 6964 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6965 if (FixedLM) { 6966 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6967 << LM.toString() << 0, 6968 getLocationOfByte(LM.getStart()), 6969 /*IsStringLocation*/true, 6970 getSpecifierRange(startSpecifier, specifierLen)); 6971 6972 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6973 << FixedLM->toString() 6974 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6975 6976 } else { 6977 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6978 << LM.toString() << 0, 6979 getLocationOfByte(LM.getStart()), 6980 /*IsStringLocation*/true, 6981 getSpecifierRange(startSpecifier, specifierLen)); 6982 } 6983 } 6984 6985 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6986 const analyze_format_string::ConversionSpecifier &CS, 6987 const char *startSpecifier, unsigned specifierLen) { 6988 using namespace analyze_format_string; 6989 6990 // See if we know how to fix this conversion specifier. 6991 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 6992 if (FixedCS) { 6993 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6994 << CS.toString() << /*conversion specifier*/1, 6995 getLocationOfByte(CS.getStart()), 6996 /*IsStringLocation*/true, 6997 getSpecifierRange(startSpecifier, specifierLen)); 6998 6999 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7000 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7001 << FixedCS->toString() 7002 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7003 } else { 7004 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7005 << CS.toString() << /*conversion specifier*/1, 7006 getLocationOfByte(CS.getStart()), 7007 /*IsStringLocation*/true, 7008 getSpecifierRange(startSpecifier, specifierLen)); 7009 } 7010 } 7011 7012 void CheckFormatHandler::HandlePosition(const char *startPos, 7013 unsigned posLen) { 7014 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7015 getLocationOfByte(startPos), 7016 /*IsStringLocation*/true, 7017 getSpecifierRange(startPos, posLen)); 7018 } 7019 7020 void 7021 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7022 analyze_format_string::PositionContext p) { 7023 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7024 << (unsigned) p, 7025 getLocationOfByte(startPos), /*IsStringLocation*/true, 7026 getSpecifierRange(startPos, posLen)); 7027 } 7028 7029 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7030 unsigned posLen) { 7031 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7032 getLocationOfByte(startPos), 7033 /*IsStringLocation*/true, 7034 getSpecifierRange(startPos, posLen)); 7035 } 7036 7037 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7038 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7039 // The presence of a null character is likely an error. 7040 EmitFormatDiagnostic( 7041 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7042 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7043 getFormatStringRange()); 7044 } 7045 } 7046 7047 // Note that this may return NULL if there was an error parsing or building 7048 // one of the argument expressions. 7049 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7050 return Args[FirstDataArg + i]; 7051 } 7052 7053 void CheckFormatHandler::DoneProcessing() { 7054 // Does the number of data arguments exceed the number of 7055 // format conversions in the format string? 7056 if (!HasVAListArg) { 7057 // Find any arguments that weren't covered. 7058 CoveredArgs.flip(); 7059 signed notCoveredArg = CoveredArgs.find_first(); 7060 if (notCoveredArg >= 0) { 7061 assert((unsigned)notCoveredArg < NumDataArgs); 7062 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7063 } else { 7064 UncoveredArg.setAllCovered(); 7065 } 7066 } 7067 } 7068 7069 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7070 const Expr *ArgExpr) { 7071 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7072 "Invalid state"); 7073 7074 if (!ArgExpr) 7075 return; 7076 7077 SourceLocation Loc = ArgExpr->getBeginLoc(); 7078 7079 if (S.getSourceManager().isInSystemMacro(Loc)) 7080 return; 7081 7082 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7083 for (auto E : DiagnosticExprs) 7084 PDiag << E->getSourceRange(); 7085 7086 CheckFormatHandler::EmitFormatDiagnostic( 7087 S, IsFunctionCall, DiagnosticExprs[0], 7088 PDiag, Loc, /*IsStringLocation*/false, 7089 DiagnosticExprs[0]->getSourceRange()); 7090 } 7091 7092 bool 7093 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7094 SourceLocation Loc, 7095 const char *startSpec, 7096 unsigned specifierLen, 7097 const char *csStart, 7098 unsigned csLen) { 7099 bool keepGoing = true; 7100 if (argIndex < NumDataArgs) { 7101 // Consider the argument coverered, even though the specifier doesn't 7102 // make sense. 7103 CoveredArgs.set(argIndex); 7104 } 7105 else { 7106 // If argIndex exceeds the number of data arguments we 7107 // don't issue a warning because that is just a cascade of warnings (and 7108 // they may have intended '%%' anyway). We don't want to continue processing 7109 // the format string after this point, however, as we will like just get 7110 // gibberish when trying to match arguments. 7111 keepGoing = false; 7112 } 7113 7114 StringRef Specifier(csStart, csLen); 7115 7116 // If the specifier in non-printable, it could be the first byte of a UTF-8 7117 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7118 // hex value. 7119 std::string CodePointStr; 7120 if (!llvm::sys::locale::isPrint(*csStart)) { 7121 llvm::UTF32 CodePoint; 7122 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7123 const llvm::UTF8 *E = 7124 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7125 llvm::ConversionResult Result = 7126 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7127 7128 if (Result != llvm::conversionOK) { 7129 unsigned char FirstChar = *csStart; 7130 CodePoint = (llvm::UTF32)FirstChar; 7131 } 7132 7133 llvm::raw_string_ostream OS(CodePointStr); 7134 if (CodePoint < 256) 7135 OS << "\\x" << llvm::format("%02x", CodePoint); 7136 else if (CodePoint <= 0xFFFF) 7137 OS << "\\u" << llvm::format("%04x", CodePoint); 7138 else 7139 OS << "\\U" << llvm::format("%08x", CodePoint); 7140 OS.flush(); 7141 Specifier = CodePointStr; 7142 } 7143 7144 EmitFormatDiagnostic( 7145 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7146 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7147 7148 return keepGoing; 7149 } 7150 7151 void 7152 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7153 const char *startSpec, 7154 unsigned specifierLen) { 7155 EmitFormatDiagnostic( 7156 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7157 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7158 } 7159 7160 bool 7161 CheckFormatHandler::CheckNumArgs( 7162 const analyze_format_string::FormatSpecifier &FS, 7163 const analyze_format_string::ConversionSpecifier &CS, 7164 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7165 7166 if (argIndex >= NumDataArgs) { 7167 PartialDiagnostic PDiag = FS.usesPositionalArg() 7168 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7169 << (argIndex+1) << NumDataArgs) 7170 : S.PDiag(diag::warn_printf_insufficient_data_args); 7171 EmitFormatDiagnostic( 7172 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7173 getSpecifierRange(startSpecifier, specifierLen)); 7174 7175 // Since more arguments than conversion tokens are given, by extension 7176 // all arguments are covered, so mark this as so. 7177 UncoveredArg.setAllCovered(); 7178 return false; 7179 } 7180 return true; 7181 } 7182 7183 template<typename Range> 7184 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7185 SourceLocation Loc, 7186 bool IsStringLocation, 7187 Range StringRange, 7188 ArrayRef<FixItHint> FixIt) { 7189 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7190 Loc, IsStringLocation, StringRange, FixIt); 7191 } 7192 7193 /// If the format string is not within the function call, emit a note 7194 /// so that the function call and string are in diagnostic messages. 7195 /// 7196 /// \param InFunctionCall if true, the format string is within the function 7197 /// call and only one diagnostic message will be produced. Otherwise, an 7198 /// extra note will be emitted pointing to location of the format string. 7199 /// 7200 /// \param ArgumentExpr the expression that is passed as the format string 7201 /// argument in the function call. Used for getting locations when two 7202 /// diagnostics are emitted. 7203 /// 7204 /// \param PDiag the callee should already have provided any strings for the 7205 /// diagnostic message. This function only adds locations and fixits 7206 /// to diagnostics. 7207 /// 7208 /// \param Loc primary location for diagnostic. If two diagnostics are 7209 /// required, one will be at Loc and a new SourceLocation will be created for 7210 /// the other one. 7211 /// 7212 /// \param IsStringLocation if true, Loc points to the format string should be 7213 /// used for the note. Otherwise, Loc points to the argument list and will 7214 /// be used with PDiag. 7215 /// 7216 /// \param StringRange some or all of the string to highlight. This is 7217 /// templated so it can accept either a CharSourceRange or a SourceRange. 7218 /// 7219 /// \param FixIt optional fix it hint for the format string. 7220 template <typename Range> 7221 void CheckFormatHandler::EmitFormatDiagnostic( 7222 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7223 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7224 Range StringRange, ArrayRef<FixItHint> FixIt) { 7225 if (InFunctionCall) { 7226 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7227 D << StringRange; 7228 D << FixIt; 7229 } else { 7230 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7231 << ArgumentExpr->getSourceRange(); 7232 7233 const Sema::SemaDiagnosticBuilder &Note = 7234 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7235 diag::note_format_string_defined); 7236 7237 Note << StringRange; 7238 Note << FixIt; 7239 } 7240 } 7241 7242 //===--- CHECK: Printf format string checking ------------------------------===// 7243 7244 namespace { 7245 7246 class CheckPrintfHandler : public CheckFormatHandler { 7247 public: 7248 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7249 const Expr *origFormatExpr, 7250 const Sema::FormatStringType type, unsigned firstDataArg, 7251 unsigned numDataArgs, bool isObjC, const char *beg, 7252 bool hasVAListArg, ArrayRef<const Expr *> Args, 7253 unsigned formatIdx, bool inFunctionCall, 7254 Sema::VariadicCallType CallType, 7255 llvm::SmallBitVector &CheckedVarArgs, 7256 UncoveredArgHandler &UncoveredArg) 7257 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7258 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7259 inFunctionCall, CallType, CheckedVarArgs, 7260 UncoveredArg) {} 7261 7262 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7263 7264 /// Returns true if '%@' specifiers are allowed in the format string. 7265 bool allowsObjCArg() const { 7266 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7267 FSType == Sema::FST_OSTrace; 7268 } 7269 7270 bool HandleInvalidPrintfConversionSpecifier( 7271 const analyze_printf::PrintfSpecifier &FS, 7272 const char *startSpecifier, 7273 unsigned specifierLen) override; 7274 7275 void handleInvalidMaskType(StringRef MaskType) override; 7276 7277 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7278 const char *startSpecifier, 7279 unsigned specifierLen) override; 7280 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7281 const char *StartSpecifier, 7282 unsigned SpecifierLen, 7283 const Expr *E); 7284 7285 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7286 const char *startSpecifier, unsigned specifierLen); 7287 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7288 const analyze_printf::OptionalAmount &Amt, 7289 unsigned type, 7290 const char *startSpecifier, unsigned specifierLen); 7291 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7292 const analyze_printf::OptionalFlag &flag, 7293 const char *startSpecifier, unsigned specifierLen); 7294 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7295 const analyze_printf::OptionalFlag &ignoredFlag, 7296 const analyze_printf::OptionalFlag &flag, 7297 const char *startSpecifier, unsigned specifierLen); 7298 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7299 const Expr *E); 7300 7301 void HandleEmptyObjCModifierFlag(const char *startFlag, 7302 unsigned flagLen) override; 7303 7304 void HandleInvalidObjCModifierFlag(const char *startFlag, 7305 unsigned flagLen) override; 7306 7307 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7308 const char *flagsEnd, 7309 const char *conversionPosition) 7310 override; 7311 }; 7312 7313 } // namespace 7314 7315 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7316 const analyze_printf::PrintfSpecifier &FS, 7317 const char *startSpecifier, 7318 unsigned specifierLen) { 7319 const analyze_printf::PrintfConversionSpecifier &CS = 7320 FS.getConversionSpecifier(); 7321 7322 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7323 getLocationOfByte(CS.getStart()), 7324 startSpecifier, specifierLen, 7325 CS.getStart(), CS.getLength()); 7326 } 7327 7328 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7329 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7330 } 7331 7332 bool CheckPrintfHandler::HandleAmount( 7333 const analyze_format_string::OptionalAmount &Amt, 7334 unsigned k, const char *startSpecifier, 7335 unsigned specifierLen) { 7336 if (Amt.hasDataArgument()) { 7337 if (!HasVAListArg) { 7338 unsigned argIndex = Amt.getArgIndex(); 7339 if (argIndex >= NumDataArgs) { 7340 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7341 << k, 7342 getLocationOfByte(Amt.getStart()), 7343 /*IsStringLocation*/true, 7344 getSpecifierRange(startSpecifier, specifierLen)); 7345 // Don't do any more checking. We will just emit 7346 // spurious errors. 7347 return false; 7348 } 7349 7350 // Type check the data argument. It should be an 'int'. 7351 // Although not in conformance with C99, we also allow the argument to be 7352 // an 'unsigned int' as that is a reasonably safe case. GCC also 7353 // doesn't emit a warning for that case. 7354 CoveredArgs.set(argIndex); 7355 const Expr *Arg = getDataArg(argIndex); 7356 if (!Arg) 7357 return false; 7358 7359 QualType T = Arg->getType(); 7360 7361 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7362 assert(AT.isValid()); 7363 7364 if (!AT.matchesType(S.Context, T)) { 7365 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7366 << k << AT.getRepresentativeTypeName(S.Context) 7367 << T << Arg->getSourceRange(), 7368 getLocationOfByte(Amt.getStart()), 7369 /*IsStringLocation*/true, 7370 getSpecifierRange(startSpecifier, specifierLen)); 7371 // Don't do any more checking. We will just emit 7372 // spurious errors. 7373 return false; 7374 } 7375 } 7376 } 7377 return true; 7378 } 7379 7380 void CheckPrintfHandler::HandleInvalidAmount( 7381 const analyze_printf::PrintfSpecifier &FS, 7382 const analyze_printf::OptionalAmount &Amt, 7383 unsigned type, 7384 const char *startSpecifier, 7385 unsigned specifierLen) { 7386 const analyze_printf::PrintfConversionSpecifier &CS = 7387 FS.getConversionSpecifier(); 7388 7389 FixItHint fixit = 7390 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7391 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7392 Amt.getConstantLength())) 7393 : FixItHint(); 7394 7395 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7396 << type << CS.toString(), 7397 getLocationOfByte(Amt.getStart()), 7398 /*IsStringLocation*/true, 7399 getSpecifierRange(startSpecifier, specifierLen), 7400 fixit); 7401 } 7402 7403 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7404 const analyze_printf::OptionalFlag &flag, 7405 const char *startSpecifier, 7406 unsigned specifierLen) { 7407 // Warn about pointless flag with a fixit removal. 7408 const analyze_printf::PrintfConversionSpecifier &CS = 7409 FS.getConversionSpecifier(); 7410 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7411 << flag.toString() << CS.toString(), 7412 getLocationOfByte(flag.getPosition()), 7413 /*IsStringLocation*/true, 7414 getSpecifierRange(startSpecifier, specifierLen), 7415 FixItHint::CreateRemoval( 7416 getSpecifierRange(flag.getPosition(), 1))); 7417 } 7418 7419 void CheckPrintfHandler::HandleIgnoredFlag( 7420 const analyze_printf::PrintfSpecifier &FS, 7421 const analyze_printf::OptionalFlag &ignoredFlag, 7422 const analyze_printf::OptionalFlag &flag, 7423 const char *startSpecifier, 7424 unsigned specifierLen) { 7425 // Warn about ignored flag with a fixit removal. 7426 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7427 << ignoredFlag.toString() << flag.toString(), 7428 getLocationOfByte(ignoredFlag.getPosition()), 7429 /*IsStringLocation*/true, 7430 getSpecifierRange(startSpecifier, specifierLen), 7431 FixItHint::CreateRemoval( 7432 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7433 } 7434 7435 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7436 unsigned flagLen) { 7437 // Warn about an empty flag. 7438 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7439 getLocationOfByte(startFlag), 7440 /*IsStringLocation*/true, 7441 getSpecifierRange(startFlag, flagLen)); 7442 } 7443 7444 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7445 unsigned flagLen) { 7446 // Warn about an invalid flag. 7447 auto Range = getSpecifierRange(startFlag, flagLen); 7448 StringRef flag(startFlag, flagLen); 7449 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7450 getLocationOfByte(startFlag), 7451 /*IsStringLocation*/true, 7452 Range, FixItHint::CreateRemoval(Range)); 7453 } 7454 7455 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7456 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7457 // Warn about using '[...]' without a '@' conversion. 7458 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7459 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7460 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7461 getLocationOfByte(conversionPosition), 7462 /*IsStringLocation*/true, 7463 Range, FixItHint::CreateRemoval(Range)); 7464 } 7465 7466 // Determines if the specified is a C++ class or struct containing 7467 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7468 // "c_str()"). 7469 template<typename MemberKind> 7470 static llvm::SmallPtrSet<MemberKind*, 1> 7471 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7472 const RecordType *RT = Ty->getAs<RecordType>(); 7473 llvm::SmallPtrSet<MemberKind*, 1> Results; 7474 7475 if (!RT) 7476 return Results; 7477 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7478 if (!RD || !RD->getDefinition()) 7479 return Results; 7480 7481 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7482 Sema::LookupMemberName); 7483 R.suppressDiagnostics(); 7484 7485 // We just need to include all members of the right kind turned up by the 7486 // filter, at this point. 7487 if (S.LookupQualifiedName(R, RT->getDecl())) 7488 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7489 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7490 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7491 Results.insert(FK); 7492 } 7493 return Results; 7494 } 7495 7496 /// Check if we could call '.c_str()' on an object. 7497 /// 7498 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7499 /// allow the call, or if it would be ambiguous). 7500 bool Sema::hasCStrMethod(const Expr *E) { 7501 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7502 7503 MethodSet Results = 7504 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7505 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7506 MI != ME; ++MI) 7507 if ((*MI)->getMinRequiredArguments() == 0) 7508 return true; 7509 return false; 7510 } 7511 7512 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7513 // better diagnostic if so. AT is assumed to be valid. 7514 // Returns true when a c_str() conversion method is found. 7515 bool CheckPrintfHandler::checkForCStrMembers( 7516 const analyze_printf::ArgType &AT, const Expr *E) { 7517 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7518 7519 MethodSet Results = 7520 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7521 7522 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7523 MI != ME; ++MI) { 7524 const CXXMethodDecl *Method = *MI; 7525 if (Method->getMinRequiredArguments() == 0 && 7526 AT.matchesType(S.Context, Method->getReturnType())) { 7527 // FIXME: Suggest parens if the expression needs them. 7528 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7529 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7530 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7531 return true; 7532 } 7533 } 7534 7535 return false; 7536 } 7537 7538 bool 7539 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7540 &FS, 7541 const char *startSpecifier, 7542 unsigned specifierLen) { 7543 using namespace analyze_format_string; 7544 using namespace analyze_printf; 7545 7546 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7547 7548 if (FS.consumesDataArgument()) { 7549 if (atFirstArg) { 7550 atFirstArg = false; 7551 usesPositionalArgs = FS.usesPositionalArg(); 7552 } 7553 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7554 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7555 startSpecifier, specifierLen); 7556 return false; 7557 } 7558 } 7559 7560 // First check if the field width, precision, and conversion specifier 7561 // have matching data arguments. 7562 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7563 startSpecifier, specifierLen)) { 7564 return false; 7565 } 7566 7567 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7568 startSpecifier, specifierLen)) { 7569 return false; 7570 } 7571 7572 if (!CS.consumesDataArgument()) { 7573 // FIXME: Technically specifying a precision or field width here 7574 // makes no sense. Worth issuing a warning at some point. 7575 return true; 7576 } 7577 7578 // Consume the argument. 7579 unsigned argIndex = FS.getArgIndex(); 7580 if (argIndex < NumDataArgs) { 7581 // The check to see if the argIndex is valid will come later. 7582 // We set the bit here because we may exit early from this 7583 // function if we encounter some other error. 7584 CoveredArgs.set(argIndex); 7585 } 7586 7587 // FreeBSD kernel extensions. 7588 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7589 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7590 // We need at least two arguments. 7591 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7592 return false; 7593 7594 // Claim the second argument. 7595 CoveredArgs.set(argIndex + 1); 7596 7597 // Type check the first argument (int for %b, pointer for %D) 7598 const Expr *Ex = getDataArg(argIndex); 7599 const analyze_printf::ArgType &AT = 7600 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7601 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7602 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7603 EmitFormatDiagnostic( 7604 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7605 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7606 << false << Ex->getSourceRange(), 7607 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7608 getSpecifierRange(startSpecifier, specifierLen)); 7609 7610 // Type check the second argument (char * for both %b and %D) 7611 Ex = getDataArg(argIndex + 1); 7612 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7613 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7614 EmitFormatDiagnostic( 7615 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7616 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7617 << false << Ex->getSourceRange(), 7618 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7619 getSpecifierRange(startSpecifier, specifierLen)); 7620 7621 return true; 7622 } 7623 7624 // Check for using an Objective-C specific conversion specifier 7625 // in a non-ObjC literal. 7626 if (!allowsObjCArg() && CS.isObjCArg()) { 7627 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7628 specifierLen); 7629 } 7630 7631 // %P can only be used with os_log. 7632 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7633 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7634 specifierLen); 7635 } 7636 7637 // %n is not allowed with os_log. 7638 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7639 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7640 getLocationOfByte(CS.getStart()), 7641 /*IsStringLocation*/ false, 7642 getSpecifierRange(startSpecifier, specifierLen)); 7643 7644 return true; 7645 } 7646 7647 // Only scalars are allowed for os_trace. 7648 if (FSType == Sema::FST_OSTrace && 7649 (CS.getKind() == ConversionSpecifier::PArg || 7650 CS.getKind() == ConversionSpecifier::sArg || 7651 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7652 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7653 specifierLen); 7654 } 7655 7656 // Check for use of public/private annotation outside of os_log(). 7657 if (FSType != Sema::FST_OSLog) { 7658 if (FS.isPublic().isSet()) { 7659 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7660 << "public", 7661 getLocationOfByte(FS.isPublic().getPosition()), 7662 /*IsStringLocation*/ false, 7663 getSpecifierRange(startSpecifier, specifierLen)); 7664 } 7665 if (FS.isPrivate().isSet()) { 7666 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7667 << "private", 7668 getLocationOfByte(FS.isPrivate().getPosition()), 7669 /*IsStringLocation*/ false, 7670 getSpecifierRange(startSpecifier, specifierLen)); 7671 } 7672 } 7673 7674 // Check for invalid use of field width 7675 if (!FS.hasValidFieldWidth()) { 7676 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7677 startSpecifier, specifierLen); 7678 } 7679 7680 // Check for invalid use of precision 7681 if (!FS.hasValidPrecision()) { 7682 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7683 startSpecifier, specifierLen); 7684 } 7685 7686 // Precision is mandatory for %P specifier. 7687 if (CS.getKind() == ConversionSpecifier::PArg && 7688 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7689 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7690 getLocationOfByte(startSpecifier), 7691 /*IsStringLocation*/ false, 7692 getSpecifierRange(startSpecifier, specifierLen)); 7693 } 7694 7695 // Check each flag does not conflict with any other component. 7696 if (!FS.hasValidThousandsGroupingPrefix()) 7697 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7698 if (!FS.hasValidLeadingZeros()) 7699 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7700 if (!FS.hasValidPlusPrefix()) 7701 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7702 if (!FS.hasValidSpacePrefix()) 7703 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7704 if (!FS.hasValidAlternativeForm()) 7705 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7706 if (!FS.hasValidLeftJustified()) 7707 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7708 7709 // Check that flags are not ignored by another flag 7710 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7711 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7712 startSpecifier, specifierLen); 7713 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7714 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7715 startSpecifier, specifierLen); 7716 7717 // Check the length modifier is valid with the given conversion specifier. 7718 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 7719 S.getLangOpts())) 7720 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7721 diag::warn_format_nonsensical_length); 7722 else if (!FS.hasStandardLengthModifier()) 7723 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7724 else if (!FS.hasStandardLengthConversionCombination()) 7725 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7726 diag::warn_format_non_standard_conversion_spec); 7727 7728 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7729 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7730 7731 // The remaining checks depend on the data arguments. 7732 if (HasVAListArg) 7733 return true; 7734 7735 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7736 return false; 7737 7738 const Expr *Arg = getDataArg(argIndex); 7739 if (!Arg) 7740 return true; 7741 7742 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7743 } 7744 7745 static bool requiresParensToAddCast(const Expr *E) { 7746 // FIXME: We should have a general way to reason about operator 7747 // precedence and whether parens are actually needed here. 7748 // Take care of a few common cases where they aren't. 7749 const Expr *Inside = E->IgnoreImpCasts(); 7750 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7751 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7752 7753 switch (Inside->getStmtClass()) { 7754 case Stmt::ArraySubscriptExprClass: 7755 case Stmt::CallExprClass: 7756 case Stmt::CharacterLiteralClass: 7757 case Stmt::CXXBoolLiteralExprClass: 7758 case Stmt::DeclRefExprClass: 7759 case Stmt::FloatingLiteralClass: 7760 case Stmt::IntegerLiteralClass: 7761 case Stmt::MemberExprClass: 7762 case Stmt::ObjCArrayLiteralClass: 7763 case Stmt::ObjCBoolLiteralExprClass: 7764 case Stmt::ObjCBoxedExprClass: 7765 case Stmt::ObjCDictionaryLiteralClass: 7766 case Stmt::ObjCEncodeExprClass: 7767 case Stmt::ObjCIvarRefExprClass: 7768 case Stmt::ObjCMessageExprClass: 7769 case Stmt::ObjCPropertyRefExprClass: 7770 case Stmt::ObjCStringLiteralClass: 7771 case Stmt::ObjCSubscriptRefExprClass: 7772 case Stmt::ParenExprClass: 7773 case Stmt::StringLiteralClass: 7774 case Stmt::UnaryOperatorClass: 7775 return false; 7776 default: 7777 return true; 7778 } 7779 } 7780 7781 static std::pair<QualType, StringRef> 7782 shouldNotPrintDirectly(const ASTContext &Context, 7783 QualType IntendedTy, 7784 const Expr *E) { 7785 // Use a 'while' to peel off layers of typedefs. 7786 QualType TyTy = IntendedTy; 7787 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7788 StringRef Name = UserTy->getDecl()->getName(); 7789 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7790 .Case("CFIndex", Context.getNSIntegerType()) 7791 .Case("NSInteger", Context.getNSIntegerType()) 7792 .Case("NSUInteger", Context.getNSUIntegerType()) 7793 .Case("SInt32", Context.IntTy) 7794 .Case("UInt32", Context.UnsignedIntTy) 7795 .Default(QualType()); 7796 7797 if (!CastTy.isNull()) 7798 return std::make_pair(CastTy, Name); 7799 7800 TyTy = UserTy->desugar(); 7801 } 7802 7803 // Strip parens if necessary. 7804 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7805 return shouldNotPrintDirectly(Context, 7806 PE->getSubExpr()->getType(), 7807 PE->getSubExpr()); 7808 7809 // If this is a conditional expression, then its result type is constructed 7810 // via usual arithmetic conversions and thus there might be no necessary 7811 // typedef sugar there. Recurse to operands to check for NSInteger & 7812 // Co. usage condition. 7813 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7814 QualType TrueTy, FalseTy; 7815 StringRef TrueName, FalseName; 7816 7817 std::tie(TrueTy, TrueName) = 7818 shouldNotPrintDirectly(Context, 7819 CO->getTrueExpr()->getType(), 7820 CO->getTrueExpr()); 7821 std::tie(FalseTy, FalseName) = 7822 shouldNotPrintDirectly(Context, 7823 CO->getFalseExpr()->getType(), 7824 CO->getFalseExpr()); 7825 7826 if (TrueTy == FalseTy) 7827 return std::make_pair(TrueTy, TrueName); 7828 else if (TrueTy.isNull()) 7829 return std::make_pair(FalseTy, FalseName); 7830 else if (FalseTy.isNull()) 7831 return std::make_pair(TrueTy, TrueName); 7832 } 7833 7834 return std::make_pair(QualType(), StringRef()); 7835 } 7836 7837 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 7838 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 7839 /// type do not count. 7840 static bool 7841 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 7842 QualType From = ICE->getSubExpr()->getType(); 7843 QualType To = ICE->getType(); 7844 // It's an integer promotion if the destination type is the promoted 7845 // source type. 7846 if (ICE->getCastKind() == CK_IntegralCast && 7847 From->isPromotableIntegerType() && 7848 S.Context.getPromotedIntegerType(From) == To) 7849 return true; 7850 // Look through vector types, since we do default argument promotion for 7851 // those in OpenCL. 7852 if (const auto *VecTy = From->getAs<ExtVectorType>()) 7853 From = VecTy->getElementType(); 7854 if (const auto *VecTy = To->getAs<ExtVectorType>()) 7855 To = VecTy->getElementType(); 7856 // It's a floating promotion if the source type is a lower rank. 7857 return ICE->getCastKind() == CK_FloatingCast && 7858 S.Context.getFloatingTypeOrder(From, To) < 0; 7859 } 7860 7861 bool 7862 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7863 const char *StartSpecifier, 7864 unsigned SpecifierLen, 7865 const Expr *E) { 7866 using namespace analyze_format_string; 7867 using namespace analyze_printf; 7868 7869 // Now type check the data expression that matches the 7870 // format specifier. 7871 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7872 if (!AT.isValid()) 7873 return true; 7874 7875 QualType ExprTy = E->getType(); 7876 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7877 ExprTy = TET->getUnderlyingExpr()->getType(); 7878 } 7879 7880 // Diagnose attempts to print a boolean value as a character. Unlike other 7881 // -Wformat diagnostics, this is fine from a type perspective, but it still 7882 // doesn't make sense. 7883 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 7884 E->isKnownToHaveBooleanValue()) { 7885 const CharSourceRange &CSR = 7886 getSpecifierRange(StartSpecifier, SpecifierLen); 7887 SmallString<4> FSString; 7888 llvm::raw_svector_ostream os(FSString); 7889 FS.toString(os); 7890 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 7891 << FSString, 7892 E->getExprLoc(), false, CSR); 7893 return true; 7894 } 7895 7896 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 7897 if (Match == analyze_printf::ArgType::Match) 7898 return true; 7899 7900 // Look through argument promotions for our error message's reported type. 7901 // This includes the integral and floating promotions, but excludes array 7902 // and function pointer decay (seeing that an argument intended to be a 7903 // string has type 'char [6]' is probably more confusing than 'char *') and 7904 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 7905 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7906 if (isArithmeticArgumentPromotion(S, ICE)) { 7907 E = ICE->getSubExpr(); 7908 ExprTy = E->getType(); 7909 7910 // Check if we didn't match because of an implicit cast from a 'char' 7911 // or 'short' to an 'int'. This is done because printf is a varargs 7912 // function. 7913 if (ICE->getType() == S.Context.IntTy || 7914 ICE->getType() == S.Context.UnsignedIntTy) { 7915 // All further checking is done on the subexpression 7916 const analyze_printf::ArgType::MatchKind ImplicitMatch = 7917 AT.matchesType(S.Context, ExprTy); 7918 if (ImplicitMatch == analyze_printf::ArgType::Match) 7919 return true; 7920 if (ImplicitMatch == ArgType::NoMatchPedantic || 7921 ImplicitMatch == ArgType::NoMatchTypeConfusion) 7922 Match = ImplicitMatch; 7923 } 7924 } 7925 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7926 // Special case for 'a', which has type 'int' in C. 7927 // Note, however, that we do /not/ want to treat multibyte constants like 7928 // 'MooV' as characters! This form is deprecated but still exists. 7929 if (ExprTy == S.Context.IntTy) 7930 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 7931 ExprTy = S.Context.CharTy; 7932 } 7933 7934 // Look through enums to their underlying type. 7935 bool IsEnum = false; 7936 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7937 ExprTy = EnumTy->getDecl()->getIntegerType(); 7938 IsEnum = true; 7939 } 7940 7941 // %C in an Objective-C context prints a unichar, not a wchar_t. 7942 // If the argument is an integer of some kind, believe the %C and suggest 7943 // a cast instead of changing the conversion specifier. 7944 QualType IntendedTy = ExprTy; 7945 if (isObjCContext() && 7946 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7947 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7948 !ExprTy->isCharType()) { 7949 // 'unichar' is defined as a typedef of unsigned short, but we should 7950 // prefer using the typedef if it is visible. 7951 IntendedTy = S.Context.UnsignedShortTy; 7952 7953 // While we are here, check if the value is an IntegerLiteral that happens 7954 // to be within the valid range. 7955 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7956 const llvm::APInt &V = IL->getValue(); 7957 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7958 return true; 7959 } 7960 7961 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7962 Sema::LookupOrdinaryName); 7963 if (S.LookupName(Result, S.getCurScope())) { 7964 NamedDecl *ND = Result.getFoundDecl(); 7965 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7966 if (TD->getUnderlyingType() == IntendedTy) 7967 IntendedTy = S.Context.getTypedefType(TD); 7968 } 7969 } 7970 } 7971 7972 // Special-case some of Darwin's platform-independence types by suggesting 7973 // casts to primitive types that are known to be large enough. 7974 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7975 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7976 QualType CastTy; 7977 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7978 if (!CastTy.isNull()) { 7979 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7980 // (long in ASTContext). Only complain to pedants. 7981 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7982 (AT.isSizeT() || AT.isPtrdiffT()) && 7983 AT.matchesType(S.Context, CastTy)) 7984 Match = ArgType::NoMatchPedantic; 7985 IntendedTy = CastTy; 7986 ShouldNotPrintDirectly = true; 7987 } 7988 } 7989 7990 // We may be able to offer a FixItHint if it is a supported type. 7991 PrintfSpecifier fixedFS = FS; 7992 bool Success = 7993 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7994 7995 if (Success) { 7996 // Get the fix string from the fixed format specifier 7997 SmallString<16> buf; 7998 llvm::raw_svector_ostream os(buf); 7999 fixedFS.toString(os); 8000 8001 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8002 8003 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8004 unsigned Diag; 8005 switch (Match) { 8006 case ArgType::Match: llvm_unreachable("expected non-matching"); 8007 case ArgType::NoMatchPedantic: 8008 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8009 break; 8010 case ArgType::NoMatchTypeConfusion: 8011 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8012 break; 8013 case ArgType::NoMatch: 8014 Diag = diag::warn_format_conversion_argument_type_mismatch; 8015 break; 8016 } 8017 8018 // In this case, the specifier is wrong and should be changed to match 8019 // the argument. 8020 EmitFormatDiagnostic(S.PDiag(Diag) 8021 << AT.getRepresentativeTypeName(S.Context) 8022 << IntendedTy << IsEnum << E->getSourceRange(), 8023 E->getBeginLoc(), 8024 /*IsStringLocation*/ false, SpecRange, 8025 FixItHint::CreateReplacement(SpecRange, os.str())); 8026 } else { 8027 // The canonical type for formatting this value is different from the 8028 // actual type of the expression. (This occurs, for example, with Darwin's 8029 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8030 // should be printed as 'long' for 64-bit compatibility.) 8031 // Rather than emitting a normal format/argument mismatch, we want to 8032 // add a cast to the recommended type (and correct the format string 8033 // if necessary). 8034 SmallString<16> CastBuf; 8035 llvm::raw_svector_ostream CastFix(CastBuf); 8036 CastFix << "("; 8037 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8038 CastFix << ")"; 8039 8040 SmallVector<FixItHint,4> Hints; 8041 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8042 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8043 8044 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8045 // If there's already a cast present, just replace it. 8046 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8047 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8048 8049 } else if (!requiresParensToAddCast(E)) { 8050 // If the expression has high enough precedence, 8051 // just write the C-style cast. 8052 Hints.push_back( 8053 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8054 } else { 8055 // Otherwise, add parens around the expression as well as the cast. 8056 CastFix << "("; 8057 Hints.push_back( 8058 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8059 8060 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8061 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8062 } 8063 8064 if (ShouldNotPrintDirectly) { 8065 // The expression has a type that should not be printed directly. 8066 // We extract the name from the typedef because we don't want to show 8067 // the underlying type in the diagnostic. 8068 StringRef Name; 8069 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8070 Name = TypedefTy->getDecl()->getName(); 8071 else 8072 Name = CastTyName; 8073 unsigned Diag = Match == ArgType::NoMatchPedantic 8074 ? diag::warn_format_argument_needs_cast_pedantic 8075 : diag::warn_format_argument_needs_cast; 8076 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8077 << E->getSourceRange(), 8078 E->getBeginLoc(), /*IsStringLocation=*/false, 8079 SpecRange, Hints); 8080 } else { 8081 // In this case, the expression could be printed using a different 8082 // specifier, but we've decided that the specifier is probably correct 8083 // and we should cast instead. Just use the normal warning message. 8084 EmitFormatDiagnostic( 8085 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8086 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8087 << E->getSourceRange(), 8088 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8089 } 8090 } 8091 } else { 8092 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8093 SpecifierLen); 8094 // Since the warning for passing non-POD types to variadic functions 8095 // was deferred until now, we emit a warning for non-POD 8096 // arguments here. 8097 switch (S.isValidVarArgType(ExprTy)) { 8098 case Sema::VAK_Valid: 8099 case Sema::VAK_ValidInCXX11: { 8100 unsigned Diag; 8101 switch (Match) { 8102 case ArgType::Match: llvm_unreachable("expected non-matching"); 8103 case ArgType::NoMatchPedantic: 8104 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8105 break; 8106 case ArgType::NoMatchTypeConfusion: 8107 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8108 break; 8109 case ArgType::NoMatch: 8110 Diag = diag::warn_format_conversion_argument_type_mismatch; 8111 break; 8112 } 8113 8114 EmitFormatDiagnostic( 8115 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8116 << IsEnum << CSR << E->getSourceRange(), 8117 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8118 break; 8119 } 8120 case Sema::VAK_Undefined: 8121 case Sema::VAK_MSVCUndefined: 8122 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8123 << S.getLangOpts().CPlusPlus11 << ExprTy 8124 << CallType 8125 << AT.getRepresentativeTypeName(S.Context) << CSR 8126 << E->getSourceRange(), 8127 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8128 checkForCStrMembers(AT, E); 8129 break; 8130 8131 case Sema::VAK_Invalid: 8132 if (ExprTy->isObjCObjectType()) 8133 EmitFormatDiagnostic( 8134 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8135 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8136 << AT.getRepresentativeTypeName(S.Context) << CSR 8137 << E->getSourceRange(), 8138 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8139 else 8140 // FIXME: If this is an initializer list, suggest removing the braces 8141 // or inserting a cast to the target type. 8142 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8143 << isa<InitListExpr>(E) << ExprTy << CallType 8144 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8145 break; 8146 } 8147 8148 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8149 "format string specifier index out of range"); 8150 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8151 } 8152 8153 return true; 8154 } 8155 8156 //===--- CHECK: Scanf format string checking ------------------------------===// 8157 8158 namespace { 8159 8160 class CheckScanfHandler : public CheckFormatHandler { 8161 public: 8162 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8163 const Expr *origFormatExpr, Sema::FormatStringType type, 8164 unsigned firstDataArg, unsigned numDataArgs, 8165 const char *beg, bool hasVAListArg, 8166 ArrayRef<const Expr *> Args, unsigned formatIdx, 8167 bool inFunctionCall, Sema::VariadicCallType CallType, 8168 llvm::SmallBitVector &CheckedVarArgs, 8169 UncoveredArgHandler &UncoveredArg) 8170 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8171 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8172 inFunctionCall, CallType, CheckedVarArgs, 8173 UncoveredArg) {} 8174 8175 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8176 const char *startSpecifier, 8177 unsigned specifierLen) override; 8178 8179 bool HandleInvalidScanfConversionSpecifier( 8180 const analyze_scanf::ScanfSpecifier &FS, 8181 const char *startSpecifier, 8182 unsigned specifierLen) override; 8183 8184 void HandleIncompleteScanList(const char *start, const char *end) override; 8185 }; 8186 8187 } // namespace 8188 8189 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8190 const char *end) { 8191 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8192 getLocationOfByte(end), /*IsStringLocation*/true, 8193 getSpecifierRange(start, end - start)); 8194 } 8195 8196 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8197 const analyze_scanf::ScanfSpecifier &FS, 8198 const char *startSpecifier, 8199 unsigned specifierLen) { 8200 const analyze_scanf::ScanfConversionSpecifier &CS = 8201 FS.getConversionSpecifier(); 8202 8203 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8204 getLocationOfByte(CS.getStart()), 8205 startSpecifier, specifierLen, 8206 CS.getStart(), CS.getLength()); 8207 } 8208 8209 bool CheckScanfHandler::HandleScanfSpecifier( 8210 const analyze_scanf::ScanfSpecifier &FS, 8211 const char *startSpecifier, 8212 unsigned specifierLen) { 8213 using namespace analyze_scanf; 8214 using namespace analyze_format_string; 8215 8216 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8217 8218 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8219 // be used to decide if we are using positional arguments consistently. 8220 if (FS.consumesDataArgument()) { 8221 if (atFirstArg) { 8222 atFirstArg = false; 8223 usesPositionalArgs = FS.usesPositionalArg(); 8224 } 8225 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8226 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8227 startSpecifier, specifierLen); 8228 return false; 8229 } 8230 } 8231 8232 // Check if the field with is non-zero. 8233 const OptionalAmount &Amt = FS.getFieldWidth(); 8234 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8235 if (Amt.getConstantAmount() == 0) { 8236 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8237 Amt.getConstantLength()); 8238 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8239 getLocationOfByte(Amt.getStart()), 8240 /*IsStringLocation*/true, R, 8241 FixItHint::CreateRemoval(R)); 8242 } 8243 } 8244 8245 if (!FS.consumesDataArgument()) { 8246 // FIXME: Technically specifying a precision or field width here 8247 // makes no sense. Worth issuing a warning at some point. 8248 return true; 8249 } 8250 8251 // Consume the argument. 8252 unsigned argIndex = FS.getArgIndex(); 8253 if (argIndex < NumDataArgs) { 8254 // The check to see if the argIndex is valid will come later. 8255 // We set the bit here because we may exit early from this 8256 // function if we encounter some other error. 8257 CoveredArgs.set(argIndex); 8258 } 8259 8260 // Check the length modifier is valid with the given conversion specifier. 8261 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8262 S.getLangOpts())) 8263 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8264 diag::warn_format_nonsensical_length); 8265 else if (!FS.hasStandardLengthModifier()) 8266 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8267 else if (!FS.hasStandardLengthConversionCombination()) 8268 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8269 diag::warn_format_non_standard_conversion_spec); 8270 8271 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8272 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8273 8274 // The remaining checks depend on the data arguments. 8275 if (HasVAListArg) 8276 return true; 8277 8278 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8279 return false; 8280 8281 // Check that the argument type matches the format specifier. 8282 const Expr *Ex = getDataArg(argIndex); 8283 if (!Ex) 8284 return true; 8285 8286 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8287 8288 if (!AT.isValid()) { 8289 return true; 8290 } 8291 8292 analyze_format_string::ArgType::MatchKind Match = 8293 AT.matchesType(S.Context, Ex->getType()); 8294 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8295 if (Match == analyze_format_string::ArgType::Match) 8296 return true; 8297 8298 ScanfSpecifier fixedFS = FS; 8299 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8300 S.getLangOpts(), S.Context); 8301 8302 unsigned Diag = 8303 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8304 : diag::warn_format_conversion_argument_type_mismatch; 8305 8306 if (Success) { 8307 // Get the fix string from the fixed format specifier. 8308 SmallString<128> buf; 8309 llvm::raw_svector_ostream os(buf); 8310 fixedFS.toString(os); 8311 8312 EmitFormatDiagnostic( 8313 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8314 << Ex->getType() << false << Ex->getSourceRange(), 8315 Ex->getBeginLoc(), 8316 /*IsStringLocation*/ false, 8317 getSpecifierRange(startSpecifier, specifierLen), 8318 FixItHint::CreateReplacement( 8319 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8320 } else { 8321 EmitFormatDiagnostic(S.PDiag(Diag) 8322 << AT.getRepresentativeTypeName(S.Context) 8323 << Ex->getType() << false << Ex->getSourceRange(), 8324 Ex->getBeginLoc(), 8325 /*IsStringLocation*/ false, 8326 getSpecifierRange(startSpecifier, specifierLen)); 8327 } 8328 8329 return true; 8330 } 8331 8332 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8333 const Expr *OrigFormatExpr, 8334 ArrayRef<const Expr *> Args, 8335 bool HasVAListArg, unsigned format_idx, 8336 unsigned firstDataArg, 8337 Sema::FormatStringType Type, 8338 bool inFunctionCall, 8339 Sema::VariadicCallType CallType, 8340 llvm::SmallBitVector &CheckedVarArgs, 8341 UncoveredArgHandler &UncoveredArg, 8342 bool IgnoreStringsWithoutSpecifiers) { 8343 // CHECK: is the format string a wide literal? 8344 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8345 CheckFormatHandler::EmitFormatDiagnostic( 8346 S, inFunctionCall, Args[format_idx], 8347 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8348 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8349 return; 8350 } 8351 8352 // Str - The format string. NOTE: this is NOT null-terminated! 8353 StringRef StrRef = FExpr->getString(); 8354 const char *Str = StrRef.data(); 8355 // Account for cases where the string literal is truncated in a declaration. 8356 const ConstantArrayType *T = 8357 S.Context.getAsConstantArrayType(FExpr->getType()); 8358 assert(T && "String literal not of constant array type!"); 8359 size_t TypeSize = T->getSize().getZExtValue(); 8360 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8361 const unsigned numDataArgs = Args.size() - firstDataArg; 8362 8363 if (IgnoreStringsWithoutSpecifiers && 8364 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8365 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8366 return; 8367 8368 // Emit a warning if the string literal is truncated and does not contain an 8369 // embedded null character. 8370 if (TypeSize <= StrRef.size() && 8371 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8372 CheckFormatHandler::EmitFormatDiagnostic( 8373 S, inFunctionCall, Args[format_idx], 8374 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8375 FExpr->getBeginLoc(), 8376 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8377 return; 8378 } 8379 8380 // CHECK: empty format string? 8381 if (StrLen == 0 && numDataArgs > 0) { 8382 CheckFormatHandler::EmitFormatDiagnostic( 8383 S, inFunctionCall, Args[format_idx], 8384 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8385 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8386 return; 8387 } 8388 8389 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8390 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8391 Type == Sema::FST_OSTrace) { 8392 CheckPrintfHandler H( 8393 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8394 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8395 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8396 CheckedVarArgs, UncoveredArg); 8397 8398 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8399 S.getLangOpts(), 8400 S.Context.getTargetInfo(), 8401 Type == Sema::FST_FreeBSDKPrintf)) 8402 H.DoneProcessing(); 8403 } else if (Type == Sema::FST_Scanf) { 8404 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8405 numDataArgs, Str, HasVAListArg, Args, format_idx, 8406 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8407 8408 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8409 S.getLangOpts(), 8410 S.Context.getTargetInfo())) 8411 H.DoneProcessing(); 8412 } // TODO: handle other formats 8413 } 8414 8415 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8416 // Str - The format string. NOTE: this is NOT null-terminated! 8417 StringRef StrRef = FExpr->getString(); 8418 const char *Str = StrRef.data(); 8419 // Account for cases where the string literal is truncated in a declaration. 8420 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8421 assert(T && "String literal not of constant array type!"); 8422 size_t TypeSize = T->getSize().getZExtValue(); 8423 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8424 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8425 getLangOpts(), 8426 Context.getTargetInfo()); 8427 } 8428 8429 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8430 8431 // Returns the related absolute value function that is larger, of 0 if one 8432 // does not exist. 8433 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8434 switch (AbsFunction) { 8435 default: 8436 return 0; 8437 8438 case Builtin::BI__builtin_abs: 8439 return Builtin::BI__builtin_labs; 8440 case Builtin::BI__builtin_labs: 8441 return Builtin::BI__builtin_llabs; 8442 case Builtin::BI__builtin_llabs: 8443 return 0; 8444 8445 case Builtin::BI__builtin_fabsf: 8446 return Builtin::BI__builtin_fabs; 8447 case Builtin::BI__builtin_fabs: 8448 return Builtin::BI__builtin_fabsl; 8449 case Builtin::BI__builtin_fabsl: 8450 return 0; 8451 8452 case Builtin::BI__builtin_cabsf: 8453 return Builtin::BI__builtin_cabs; 8454 case Builtin::BI__builtin_cabs: 8455 return Builtin::BI__builtin_cabsl; 8456 case Builtin::BI__builtin_cabsl: 8457 return 0; 8458 8459 case Builtin::BIabs: 8460 return Builtin::BIlabs; 8461 case Builtin::BIlabs: 8462 return Builtin::BIllabs; 8463 case Builtin::BIllabs: 8464 return 0; 8465 8466 case Builtin::BIfabsf: 8467 return Builtin::BIfabs; 8468 case Builtin::BIfabs: 8469 return Builtin::BIfabsl; 8470 case Builtin::BIfabsl: 8471 return 0; 8472 8473 case Builtin::BIcabsf: 8474 return Builtin::BIcabs; 8475 case Builtin::BIcabs: 8476 return Builtin::BIcabsl; 8477 case Builtin::BIcabsl: 8478 return 0; 8479 } 8480 } 8481 8482 // Returns the argument type of the absolute value function. 8483 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8484 unsigned AbsType) { 8485 if (AbsType == 0) 8486 return QualType(); 8487 8488 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8489 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8490 if (Error != ASTContext::GE_None) 8491 return QualType(); 8492 8493 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8494 if (!FT) 8495 return QualType(); 8496 8497 if (FT->getNumParams() != 1) 8498 return QualType(); 8499 8500 return FT->getParamType(0); 8501 } 8502 8503 // Returns the best absolute value function, or zero, based on type and 8504 // current absolute value function. 8505 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8506 unsigned AbsFunctionKind) { 8507 unsigned BestKind = 0; 8508 uint64_t ArgSize = Context.getTypeSize(ArgType); 8509 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8510 Kind = getLargerAbsoluteValueFunction(Kind)) { 8511 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8512 if (Context.getTypeSize(ParamType) >= ArgSize) { 8513 if (BestKind == 0) 8514 BestKind = Kind; 8515 else if (Context.hasSameType(ParamType, ArgType)) { 8516 BestKind = Kind; 8517 break; 8518 } 8519 } 8520 } 8521 return BestKind; 8522 } 8523 8524 enum AbsoluteValueKind { 8525 AVK_Integer, 8526 AVK_Floating, 8527 AVK_Complex 8528 }; 8529 8530 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8531 if (T->isIntegralOrEnumerationType()) 8532 return AVK_Integer; 8533 if (T->isRealFloatingType()) 8534 return AVK_Floating; 8535 if (T->isAnyComplexType()) 8536 return AVK_Complex; 8537 8538 llvm_unreachable("Type not integer, floating, or complex"); 8539 } 8540 8541 // Changes the absolute value function to a different type. Preserves whether 8542 // the function is a builtin. 8543 static unsigned changeAbsFunction(unsigned AbsKind, 8544 AbsoluteValueKind ValueKind) { 8545 switch (ValueKind) { 8546 case AVK_Integer: 8547 switch (AbsKind) { 8548 default: 8549 return 0; 8550 case Builtin::BI__builtin_fabsf: 8551 case Builtin::BI__builtin_fabs: 8552 case Builtin::BI__builtin_fabsl: 8553 case Builtin::BI__builtin_cabsf: 8554 case Builtin::BI__builtin_cabs: 8555 case Builtin::BI__builtin_cabsl: 8556 return Builtin::BI__builtin_abs; 8557 case Builtin::BIfabsf: 8558 case Builtin::BIfabs: 8559 case Builtin::BIfabsl: 8560 case Builtin::BIcabsf: 8561 case Builtin::BIcabs: 8562 case Builtin::BIcabsl: 8563 return Builtin::BIabs; 8564 } 8565 case AVK_Floating: 8566 switch (AbsKind) { 8567 default: 8568 return 0; 8569 case Builtin::BI__builtin_abs: 8570 case Builtin::BI__builtin_labs: 8571 case Builtin::BI__builtin_llabs: 8572 case Builtin::BI__builtin_cabsf: 8573 case Builtin::BI__builtin_cabs: 8574 case Builtin::BI__builtin_cabsl: 8575 return Builtin::BI__builtin_fabsf; 8576 case Builtin::BIabs: 8577 case Builtin::BIlabs: 8578 case Builtin::BIllabs: 8579 case Builtin::BIcabsf: 8580 case Builtin::BIcabs: 8581 case Builtin::BIcabsl: 8582 return Builtin::BIfabsf; 8583 } 8584 case AVK_Complex: 8585 switch (AbsKind) { 8586 default: 8587 return 0; 8588 case Builtin::BI__builtin_abs: 8589 case Builtin::BI__builtin_labs: 8590 case Builtin::BI__builtin_llabs: 8591 case Builtin::BI__builtin_fabsf: 8592 case Builtin::BI__builtin_fabs: 8593 case Builtin::BI__builtin_fabsl: 8594 return Builtin::BI__builtin_cabsf; 8595 case Builtin::BIabs: 8596 case Builtin::BIlabs: 8597 case Builtin::BIllabs: 8598 case Builtin::BIfabsf: 8599 case Builtin::BIfabs: 8600 case Builtin::BIfabsl: 8601 return Builtin::BIcabsf; 8602 } 8603 } 8604 llvm_unreachable("Unable to convert function"); 8605 } 8606 8607 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8608 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8609 if (!FnInfo) 8610 return 0; 8611 8612 switch (FDecl->getBuiltinID()) { 8613 default: 8614 return 0; 8615 case Builtin::BI__builtin_abs: 8616 case Builtin::BI__builtin_fabs: 8617 case Builtin::BI__builtin_fabsf: 8618 case Builtin::BI__builtin_fabsl: 8619 case Builtin::BI__builtin_labs: 8620 case Builtin::BI__builtin_llabs: 8621 case Builtin::BI__builtin_cabs: 8622 case Builtin::BI__builtin_cabsf: 8623 case Builtin::BI__builtin_cabsl: 8624 case Builtin::BIabs: 8625 case Builtin::BIlabs: 8626 case Builtin::BIllabs: 8627 case Builtin::BIfabs: 8628 case Builtin::BIfabsf: 8629 case Builtin::BIfabsl: 8630 case Builtin::BIcabs: 8631 case Builtin::BIcabsf: 8632 case Builtin::BIcabsl: 8633 return FDecl->getBuiltinID(); 8634 } 8635 llvm_unreachable("Unknown Builtin type"); 8636 } 8637 8638 // If the replacement is valid, emit a note with replacement function. 8639 // Additionally, suggest including the proper header if not already included. 8640 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8641 unsigned AbsKind, QualType ArgType) { 8642 bool EmitHeaderHint = true; 8643 const char *HeaderName = nullptr; 8644 const char *FunctionName = nullptr; 8645 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8646 FunctionName = "std::abs"; 8647 if (ArgType->isIntegralOrEnumerationType()) { 8648 HeaderName = "cstdlib"; 8649 } else if (ArgType->isRealFloatingType()) { 8650 HeaderName = "cmath"; 8651 } else { 8652 llvm_unreachable("Invalid Type"); 8653 } 8654 8655 // Lookup all std::abs 8656 if (NamespaceDecl *Std = S.getStdNamespace()) { 8657 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8658 R.suppressDiagnostics(); 8659 S.LookupQualifiedName(R, Std); 8660 8661 for (const auto *I : R) { 8662 const FunctionDecl *FDecl = nullptr; 8663 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8664 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8665 } else { 8666 FDecl = dyn_cast<FunctionDecl>(I); 8667 } 8668 if (!FDecl) 8669 continue; 8670 8671 // Found std::abs(), check that they are the right ones. 8672 if (FDecl->getNumParams() != 1) 8673 continue; 8674 8675 // Check that the parameter type can handle the argument. 8676 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8677 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8678 S.Context.getTypeSize(ArgType) <= 8679 S.Context.getTypeSize(ParamType)) { 8680 // Found a function, don't need the header hint. 8681 EmitHeaderHint = false; 8682 break; 8683 } 8684 } 8685 } 8686 } else { 8687 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8688 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8689 8690 if (HeaderName) { 8691 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8692 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8693 R.suppressDiagnostics(); 8694 S.LookupName(R, S.getCurScope()); 8695 8696 if (R.isSingleResult()) { 8697 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8698 if (FD && FD->getBuiltinID() == AbsKind) { 8699 EmitHeaderHint = false; 8700 } else { 8701 return; 8702 } 8703 } else if (!R.empty()) { 8704 return; 8705 } 8706 } 8707 } 8708 8709 S.Diag(Loc, diag::note_replace_abs_function) 8710 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8711 8712 if (!HeaderName) 8713 return; 8714 8715 if (!EmitHeaderHint) 8716 return; 8717 8718 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8719 << FunctionName; 8720 } 8721 8722 template <std::size_t StrLen> 8723 static bool IsStdFunction(const FunctionDecl *FDecl, 8724 const char (&Str)[StrLen]) { 8725 if (!FDecl) 8726 return false; 8727 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8728 return false; 8729 if (!FDecl->isInStdNamespace()) 8730 return false; 8731 8732 return true; 8733 } 8734 8735 // Warn when using the wrong abs() function. 8736 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8737 const FunctionDecl *FDecl) { 8738 if (Call->getNumArgs() != 1) 8739 return; 8740 8741 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8742 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8743 if (AbsKind == 0 && !IsStdAbs) 8744 return; 8745 8746 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8747 QualType ParamType = Call->getArg(0)->getType(); 8748 8749 // Unsigned types cannot be negative. Suggest removing the absolute value 8750 // function call. 8751 if (ArgType->isUnsignedIntegerType()) { 8752 const char *FunctionName = 8753 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8754 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8755 Diag(Call->getExprLoc(), diag::note_remove_abs) 8756 << FunctionName 8757 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8758 return; 8759 } 8760 8761 // Taking the absolute value of a pointer is very suspicious, they probably 8762 // wanted to index into an array, dereference a pointer, call a function, etc. 8763 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8764 unsigned DiagType = 0; 8765 if (ArgType->isFunctionType()) 8766 DiagType = 1; 8767 else if (ArgType->isArrayType()) 8768 DiagType = 2; 8769 8770 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8771 return; 8772 } 8773 8774 // std::abs has overloads which prevent most of the absolute value problems 8775 // from occurring. 8776 if (IsStdAbs) 8777 return; 8778 8779 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8780 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8781 8782 // The argument and parameter are the same kind. Check if they are the right 8783 // size. 8784 if (ArgValueKind == ParamValueKind) { 8785 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8786 return; 8787 8788 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8789 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8790 << FDecl << ArgType << ParamType; 8791 8792 if (NewAbsKind == 0) 8793 return; 8794 8795 emitReplacement(*this, Call->getExprLoc(), 8796 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8797 return; 8798 } 8799 8800 // ArgValueKind != ParamValueKind 8801 // The wrong type of absolute value function was used. Attempt to find the 8802 // proper one. 8803 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8804 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8805 if (NewAbsKind == 0) 8806 return; 8807 8808 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8809 << FDecl << ParamValueKind << ArgValueKind; 8810 8811 emitReplacement(*this, Call->getExprLoc(), 8812 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8813 } 8814 8815 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8816 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8817 const FunctionDecl *FDecl) { 8818 if (!Call || !FDecl) return; 8819 8820 // Ignore template specializations and macros. 8821 if (inTemplateInstantiation()) return; 8822 if (Call->getExprLoc().isMacroID()) return; 8823 8824 // Only care about the one template argument, two function parameter std::max 8825 if (Call->getNumArgs() != 2) return; 8826 if (!IsStdFunction(FDecl, "max")) return; 8827 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8828 if (!ArgList) return; 8829 if (ArgList->size() != 1) return; 8830 8831 // Check that template type argument is unsigned integer. 8832 const auto& TA = ArgList->get(0); 8833 if (TA.getKind() != TemplateArgument::Type) return; 8834 QualType ArgType = TA.getAsType(); 8835 if (!ArgType->isUnsignedIntegerType()) return; 8836 8837 // See if either argument is a literal zero. 8838 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8839 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8840 if (!MTE) return false; 8841 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 8842 if (!Num) return false; 8843 if (Num->getValue() != 0) return false; 8844 return true; 8845 }; 8846 8847 const Expr *FirstArg = Call->getArg(0); 8848 const Expr *SecondArg = Call->getArg(1); 8849 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8850 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8851 8852 // Only warn when exactly one argument is zero. 8853 if (IsFirstArgZero == IsSecondArgZero) return; 8854 8855 SourceRange FirstRange = FirstArg->getSourceRange(); 8856 SourceRange SecondRange = SecondArg->getSourceRange(); 8857 8858 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8859 8860 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8861 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8862 8863 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8864 SourceRange RemovalRange; 8865 if (IsFirstArgZero) { 8866 RemovalRange = SourceRange(FirstRange.getBegin(), 8867 SecondRange.getBegin().getLocWithOffset(-1)); 8868 } else { 8869 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8870 SecondRange.getEnd()); 8871 } 8872 8873 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8874 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8875 << FixItHint::CreateRemoval(RemovalRange); 8876 } 8877 8878 //===--- CHECK: Standard memory functions ---------------------------------===// 8879 8880 /// Takes the expression passed to the size_t parameter of functions 8881 /// such as memcmp, strncat, etc and warns if it's a comparison. 8882 /// 8883 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8884 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8885 IdentifierInfo *FnName, 8886 SourceLocation FnLoc, 8887 SourceLocation RParenLoc) { 8888 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8889 if (!Size) 8890 return false; 8891 8892 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8893 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8894 return false; 8895 8896 SourceRange SizeRange = Size->getSourceRange(); 8897 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8898 << SizeRange << FnName; 8899 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8900 << FnName 8901 << FixItHint::CreateInsertion( 8902 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8903 << FixItHint::CreateRemoval(RParenLoc); 8904 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8905 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8906 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8907 ")"); 8908 8909 return true; 8910 } 8911 8912 /// Determine whether the given type is or contains a dynamic class type 8913 /// (e.g., whether it has a vtable). 8914 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8915 bool &IsContained) { 8916 // Look through array types while ignoring qualifiers. 8917 const Type *Ty = T->getBaseElementTypeUnsafe(); 8918 IsContained = false; 8919 8920 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8921 RD = RD ? RD->getDefinition() : nullptr; 8922 if (!RD || RD->isInvalidDecl()) 8923 return nullptr; 8924 8925 if (RD->isDynamicClass()) 8926 return RD; 8927 8928 // Check all the fields. If any bases were dynamic, the class is dynamic. 8929 // It's impossible for a class to transitively contain itself by value, so 8930 // infinite recursion is impossible. 8931 for (auto *FD : RD->fields()) { 8932 bool SubContained; 8933 if (const CXXRecordDecl *ContainedRD = 8934 getContainedDynamicClass(FD->getType(), SubContained)) { 8935 IsContained = true; 8936 return ContainedRD; 8937 } 8938 } 8939 8940 return nullptr; 8941 } 8942 8943 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8944 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8945 if (Unary->getKind() == UETT_SizeOf) 8946 return Unary; 8947 return nullptr; 8948 } 8949 8950 /// If E is a sizeof expression, returns its argument expression, 8951 /// otherwise returns NULL. 8952 static const Expr *getSizeOfExprArg(const Expr *E) { 8953 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8954 if (!SizeOf->isArgumentType()) 8955 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8956 return nullptr; 8957 } 8958 8959 /// If E is a sizeof expression, returns its argument type. 8960 static QualType getSizeOfArgType(const Expr *E) { 8961 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8962 return SizeOf->getTypeOfArgument(); 8963 return QualType(); 8964 } 8965 8966 namespace { 8967 8968 struct SearchNonTrivialToInitializeField 8969 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8970 using Super = 8971 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8972 8973 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8974 8975 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8976 SourceLocation SL) { 8977 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8978 asDerived().visitArray(PDIK, AT, SL); 8979 return; 8980 } 8981 8982 Super::visitWithKind(PDIK, FT, SL); 8983 } 8984 8985 void visitARCStrong(QualType FT, SourceLocation SL) { 8986 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8987 } 8988 void visitARCWeak(QualType FT, SourceLocation SL) { 8989 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8990 } 8991 void visitStruct(QualType FT, SourceLocation SL) { 8992 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8993 visit(FD->getType(), FD->getLocation()); 8994 } 8995 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8996 const ArrayType *AT, SourceLocation SL) { 8997 visit(getContext().getBaseElementType(AT), SL); 8998 } 8999 void visitTrivial(QualType FT, SourceLocation SL) {} 9000 9001 static void diag(QualType RT, const Expr *E, Sema &S) { 9002 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9003 } 9004 9005 ASTContext &getContext() { return S.getASTContext(); } 9006 9007 const Expr *E; 9008 Sema &S; 9009 }; 9010 9011 struct SearchNonTrivialToCopyField 9012 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9013 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9014 9015 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9016 9017 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9018 SourceLocation SL) { 9019 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9020 asDerived().visitArray(PCK, AT, SL); 9021 return; 9022 } 9023 9024 Super::visitWithKind(PCK, FT, SL); 9025 } 9026 9027 void visitARCStrong(QualType FT, SourceLocation SL) { 9028 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9029 } 9030 void visitARCWeak(QualType FT, SourceLocation SL) { 9031 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9032 } 9033 void visitStruct(QualType FT, SourceLocation SL) { 9034 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9035 visit(FD->getType(), FD->getLocation()); 9036 } 9037 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9038 SourceLocation SL) { 9039 visit(getContext().getBaseElementType(AT), SL); 9040 } 9041 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9042 SourceLocation SL) {} 9043 void visitTrivial(QualType FT, SourceLocation SL) {} 9044 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9045 9046 static void diag(QualType RT, const Expr *E, Sema &S) { 9047 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9048 } 9049 9050 ASTContext &getContext() { return S.getASTContext(); } 9051 9052 const Expr *E; 9053 Sema &S; 9054 }; 9055 9056 } 9057 9058 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9059 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9060 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9061 9062 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9063 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9064 return false; 9065 9066 return doesExprLikelyComputeSize(BO->getLHS()) || 9067 doesExprLikelyComputeSize(BO->getRHS()); 9068 } 9069 9070 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9071 } 9072 9073 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9074 /// 9075 /// \code 9076 /// #define MACRO 0 9077 /// foo(MACRO); 9078 /// foo(0); 9079 /// \endcode 9080 /// 9081 /// This should return true for the first call to foo, but not for the second 9082 /// (regardless of whether foo is a macro or function). 9083 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9084 SourceLocation CallLoc, 9085 SourceLocation ArgLoc) { 9086 if (!CallLoc.isMacroID()) 9087 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9088 9089 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9090 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9091 } 9092 9093 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9094 /// last two arguments transposed. 9095 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9096 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9097 return; 9098 9099 const Expr *SizeArg = 9100 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9101 9102 auto isLiteralZero = [](const Expr *E) { 9103 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9104 }; 9105 9106 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9107 SourceLocation CallLoc = Call->getRParenLoc(); 9108 SourceManager &SM = S.getSourceManager(); 9109 if (isLiteralZero(SizeArg) && 9110 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9111 9112 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9113 9114 // Some platforms #define bzero to __builtin_memset. See if this is the 9115 // case, and if so, emit a better diagnostic. 9116 if (BId == Builtin::BIbzero || 9117 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9118 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9119 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9120 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9121 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9122 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9123 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9124 } 9125 return; 9126 } 9127 9128 // If the second argument to a memset is a sizeof expression and the third 9129 // isn't, this is also likely an error. This should catch 9130 // 'memset(buf, sizeof(buf), 0xff)'. 9131 if (BId == Builtin::BImemset && 9132 doesExprLikelyComputeSize(Call->getArg(1)) && 9133 !doesExprLikelyComputeSize(Call->getArg(2))) { 9134 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9135 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9136 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9137 return; 9138 } 9139 } 9140 9141 /// Check for dangerous or invalid arguments to memset(). 9142 /// 9143 /// This issues warnings on known problematic, dangerous or unspecified 9144 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9145 /// function calls. 9146 /// 9147 /// \param Call The call expression to diagnose. 9148 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9149 unsigned BId, 9150 IdentifierInfo *FnName) { 9151 assert(BId != 0); 9152 9153 // It is possible to have a non-standard definition of memset. Validate 9154 // we have enough arguments, and if not, abort further checking. 9155 unsigned ExpectedNumArgs = 9156 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9157 if (Call->getNumArgs() < ExpectedNumArgs) 9158 return; 9159 9160 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9161 BId == Builtin::BIstrndup ? 1 : 2); 9162 unsigned LenArg = 9163 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9164 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9165 9166 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9167 Call->getBeginLoc(), Call->getRParenLoc())) 9168 return; 9169 9170 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9171 CheckMemaccessSize(*this, BId, Call); 9172 9173 // We have special checking when the length is a sizeof expression. 9174 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9175 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9176 llvm::FoldingSetNodeID SizeOfArgID; 9177 9178 // Although widely used, 'bzero' is not a standard function. Be more strict 9179 // with the argument types before allowing diagnostics and only allow the 9180 // form bzero(ptr, sizeof(...)). 9181 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9182 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9183 return; 9184 9185 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9186 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9187 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9188 9189 QualType DestTy = Dest->getType(); 9190 QualType PointeeTy; 9191 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9192 PointeeTy = DestPtrTy->getPointeeType(); 9193 9194 // Never warn about void type pointers. This can be used to suppress 9195 // false positives. 9196 if (PointeeTy->isVoidType()) 9197 continue; 9198 9199 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9200 // actually comparing the expressions for equality. Because computing the 9201 // expression IDs can be expensive, we only do this if the diagnostic is 9202 // enabled. 9203 if (SizeOfArg && 9204 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9205 SizeOfArg->getExprLoc())) { 9206 // We only compute IDs for expressions if the warning is enabled, and 9207 // cache the sizeof arg's ID. 9208 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9209 SizeOfArg->Profile(SizeOfArgID, Context, true); 9210 llvm::FoldingSetNodeID DestID; 9211 Dest->Profile(DestID, Context, true); 9212 if (DestID == SizeOfArgID) { 9213 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9214 // over sizeof(src) as well. 9215 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9216 StringRef ReadableName = FnName->getName(); 9217 9218 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9219 if (UnaryOp->getOpcode() == UO_AddrOf) 9220 ActionIdx = 1; // If its an address-of operator, just remove it. 9221 if (!PointeeTy->isIncompleteType() && 9222 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9223 ActionIdx = 2; // If the pointee's size is sizeof(char), 9224 // suggest an explicit length. 9225 9226 // If the function is defined as a builtin macro, do not show macro 9227 // expansion. 9228 SourceLocation SL = SizeOfArg->getExprLoc(); 9229 SourceRange DSR = Dest->getSourceRange(); 9230 SourceRange SSR = SizeOfArg->getSourceRange(); 9231 SourceManager &SM = getSourceManager(); 9232 9233 if (SM.isMacroArgExpansion(SL)) { 9234 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9235 SL = SM.getSpellingLoc(SL); 9236 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9237 SM.getSpellingLoc(DSR.getEnd())); 9238 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9239 SM.getSpellingLoc(SSR.getEnd())); 9240 } 9241 9242 DiagRuntimeBehavior(SL, SizeOfArg, 9243 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9244 << ReadableName 9245 << PointeeTy 9246 << DestTy 9247 << DSR 9248 << SSR); 9249 DiagRuntimeBehavior(SL, SizeOfArg, 9250 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9251 << ActionIdx 9252 << SSR); 9253 9254 break; 9255 } 9256 } 9257 9258 // Also check for cases where the sizeof argument is the exact same 9259 // type as the memory argument, and where it points to a user-defined 9260 // record type. 9261 if (SizeOfArgTy != QualType()) { 9262 if (PointeeTy->isRecordType() && 9263 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9264 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9265 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9266 << FnName << SizeOfArgTy << ArgIdx 9267 << PointeeTy << Dest->getSourceRange() 9268 << LenExpr->getSourceRange()); 9269 break; 9270 } 9271 } 9272 } else if (DestTy->isArrayType()) { 9273 PointeeTy = DestTy; 9274 } 9275 9276 if (PointeeTy == QualType()) 9277 continue; 9278 9279 // Always complain about dynamic classes. 9280 bool IsContained; 9281 if (const CXXRecordDecl *ContainedRD = 9282 getContainedDynamicClass(PointeeTy, IsContained)) { 9283 9284 unsigned OperationType = 0; 9285 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9286 // "overwritten" if we're warning about the destination for any call 9287 // but memcmp; otherwise a verb appropriate to the call. 9288 if (ArgIdx != 0 || IsCmp) { 9289 if (BId == Builtin::BImemcpy) 9290 OperationType = 1; 9291 else if(BId == Builtin::BImemmove) 9292 OperationType = 2; 9293 else if (IsCmp) 9294 OperationType = 3; 9295 } 9296 9297 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9298 PDiag(diag::warn_dyn_class_memaccess) 9299 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9300 << IsContained << ContainedRD << OperationType 9301 << Call->getCallee()->getSourceRange()); 9302 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9303 BId != Builtin::BImemset) 9304 DiagRuntimeBehavior( 9305 Dest->getExprLoc(), Dest, 9306 PDiag(diag::warn_arc_object_memaccess) 9307 << ArgIdx << FnName << PointeeTy 9308 << Call->getCallee()->getSourceRange()); 9309 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9310 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9311 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9312 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9313 PDiag(diag::warn_cstruct_memaccess) 9314 << ArgIdx << FnName << PointeeTy << 0); 9315 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9316 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9317 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9318 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9319 PDiag(diag::warn_cstruct_memaccess) 9320 << ArgIdx << FnName << PointeeTy << 1); 9321 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9322 } else { 9323 continue; 9324 } 9325 } else 9326 continue; 9327 9328 DiagRuntimeBehavior( 9329 Dest->getExprLoc(), Dest, 9330 PDiag(diag::note_bad_memaccess_silence) 9331 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9332 break; 9333 } 9334 } 9335 9336 // A little helper routine: ignore addition and subtraction of integer literals. 9337 // This intentionally does not ignore all integer constant expressions because 9338 // we don't want to remove sizeof(). 9339 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9340 Ex = Ex->IgnoreParenCasts(); 9341 9342 while (true) { 9343 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9344 if (!BO || !BO->isAdditiveOp()) 9345 break; 9346 9347 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9348 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9349 9350 if (isa<IntegerLiteral>(RHS)) 9351 Ex = LHS; 9352 else if (isa<IntegerLiteral>(LHS)) 9353 Ex = RHS; 9354 else 9355 break; 9356 } 9357 9358 return Ex; 9359 } 9360 9361 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9362 ASTContext &Context) { 9363 // Only handle constant-sized or VLAs, but not flexible members. 9364 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9365 // Only issue the FIXIT for arrays of size > 1. 9366 if (CAT->getSize().getSExtValue() <= 1) 9367 return false; 9368 } else if (!Ty->isVariableArrayType()) { 9369 return false; 9370 } 9371 return true; 9372 } 9373 9374 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9375 // be the size of the source, instead of the destination. 9376 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9377 IdentifierInfo *FnName) { 9378 9379 // Don't crash if the user has the wrong number of arguments 9380 unsigned NumArgs = Call->getNumArgs(); 9381 if ((NumArgs != 3) && (NumArgs != 4)) 9382 return; 9383 9384 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9385 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9386 const Expr *CompareWithSrc = nullptr; 9387 9388 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9389 Call->getBeginLoc(), Call->getRParenLoc())) 9390 return; 9391 9392 // Look for 'strlcpy(dst, x, sizeof(x))' 9393 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9394 CompareWithSrc = Ex; 9395 else { 9396 // Look for 'strlcpy(dst, x, strlen(x))' 9397 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9398 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9399 SizeCall->getNumArgs() == 1) 9400 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9401 } 9402 } 9403 9404 if (!CompareWithSrc) 9405 return; 9406 9407 // Determine if the argument to sizeof/strlen is equal to the source 9408 // argument. In principle there's all kinds of things you could do 9409 // here, for instance creating an == expression and evaluating it with 9410 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9411 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9412 if (!SrcArgDRE) 9413 return; 9414 9415 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9416 if (!CompareWithSrcDRE || 9417 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9418 return; 9419 9420 const Expr *OriginalSizeArg = Call->getArg(2); 9421 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9422 << OriginalSizeArg->getSourceRange() << FnName; 9423 9424 // Output a FIXIT hint if the destination is an array (rather than a 9425 // pointer to an array). This could be enhanced to handle some 9426 // pointers if we know the actual size, like if DstArg is 'array+2' 9427 // we could say 'sizeof(array)-2'. 9428 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9429 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9430 return; 9431 9432 SmallString<128> sizeString; 9433 llvm::raw_svector_ostream OS(sizeString); 9434 OS << "sizeof("; 9435 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9436 OS << ")"; 9437 9438 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9439 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9440 OS.str()); 9441 } 9442 9443 /// Check if two expressions refer to the same declaration. 9444 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9445 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9446 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9447 return D1->getDecl() == D2->getDecl(); 9448 return false; 9449 } 9450 9451 static const Expr *getStrlenExprArg(const Expr *E) { 9452 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9453 const FunctionDecl *FD = CE->getDirectCallee(); 9454 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9455 return nullptr; 9456 return CE->getArg(0)->IgnoreParenCasts(); 9457 } 9458 return nullptr; 9459 } 9460 9461 // Warn on anti-patterns as the 'size' argument to strncat. 9462 // The correct size argument should look like following: 9463 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9464 void Sema::CheckStrncatArguments(const CallExpr *CE, 9465 IdentifierInfo *FnName) { 9466 // Don't crash if the user has the wrong number of arguments. 9467 if (CE->getNumArgs() < 3) 9468 return; 9469 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9470 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9471 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9472 9473 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9474 CE->getRParenLoc())) 9475 return; 9476 9477 // Identify common expressions, which are wrongly used as the size argument 9478 // to strncat and may lead to buffer overflows. 9479 unsigned PatternType = 0; 9480 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9481 // - sizeof(dst) 9482 if (referToTheSameDecl(SizeOfArg, DstArg)) 9483 PatternType = 1; 9484 // - sizeof(src) 9485 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9486 PatternType = 2; 9487 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9488 if (BE->getOpcode() == BO_Sub) { 9489 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9490 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9491 // - sizeof(dst) - strlen(dst) 9492 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9493 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9494 PatternType = 1; 9495 // - sizeof(src) - (anything) 9496 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9497 PatternType = 2; 9498 } 9499 } 9500 9501 if (PatternType == 0) 9502 return; 9503 9504 // Generate the diagnostic. 9505 SourceLocation SL = LenArg->getBeginLoc(); 9506 SourceRange SR = LenArg->getSourceRange(); 9507 SourceManager &SM = getSourceManager(); 9508 9509 // If the function is defined as a builtin macro, do not show macro expansion. 9510 if (SM.isMacroArgExpansion(SL)) { 9511 SL = SM.getSpellingLoc(SL); 9512 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9513 SM.getSpellingLoc(SR.getEnd())); 9514 } 9515 9516 // Check if the destination is an array (rather than a pointer to an array). 9517 QualType DstTy = DstArg->getType(); 9518 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9519 Context); 9520 if (!isKnownSizeArray) { 9521 if (PatternType == 1) 9522 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9523 else 9524 Diag(SL, diag::warn_strncat_src_size) << SR; 9525 return; 9526 } 9527 9528 if (PatternType == 1) 9529 Diag(SL, diag::warn_strncat_large_size) << SR; 9530 else 9531 Diag(SL, diag::warn_strncat_src_size) << SR; 9532 9533 SmallString<128> sizeString; 9534 llvm::raw_svector_ostream OS(sizeString); 9535 OS << "sizeof("; 9536 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9537 OS << ") - "; 9538 OS << "strlen("; 9539 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9540 OS << ") - 1"; 9541 9542 Diag(SL, diag::note_strncat_wrong_size) 9543 << FixItHint::CreateReplacement(SR, OS.str()); 9544 } 9545 9546 void 9547 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9548 SourceLocation ReturnLoc, 9549 bool isObjCMethod, 9550 const AttrVec *Attrs, 9551 const FunctionDecl *FD) { 9552 // Check if the return value is null but should not be. 9553 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9554 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9555 CheckNonNullExpr(*this, RetValExp)) 9556 Diag(ReturnLoc, diag::warn_null_ret) 9557 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9558 9559 // C++11 [basic.stc.dynamic.allocation]p4: 9560 // If an allocation function declared with a non-throwing 9561 // exception-specification fails to allocate storage, it shall return 9562 // a null pointer. Any other allocation function that fails to allocate 9563 // storage shall indicate failure only by throwing an exception [...] 9564 if (FD) { 9565 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9566 if (Op == OO_New || Op == OO_Array_New) { 9567 const FunctionProtoType *Proto 9568 = FD->getType()->castAs<FunctionProtoType>(); 9569 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9570 CheckNonNullExpr(*this, RetValExp)) 9571 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9572 << FD << getLangOpts().CPlusPlus11; 9573 } 9574 } 9575 } 9576 9577 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9578 9579 /// Check for comparisons of floating point operands using != and ==. 9580 /// Issue a warning if these are no self-comparisons, as they are not likely 9581 /// to do what the programmer intended. 9582 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9583 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9584 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9585 9586 // Special case: check for x == x (which is OK). 9587 // Do not emit warnings for such cases. 9588 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9589 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9590 if (DRL->getDecl() == DRR->getDecl()) 9591 return; 9592 9593 // Special case: check for comparisons against literals that can be exactly 9594 // represented by APFloat. In such cases, do not emit a warning. This 9595 // is a heuristic: often comparison against such literals are used to 9596 // detect if a value in a variable has not changed. This clearly can 9597 // lead to false negatives. 9598 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9599 if (FLL->isExact()) 9600 return; 9601 } else 9602 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9603 if (FLR->isExact()) 9604 return; 9605 9606 // Check for comparisons with builtin types. 9607 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9608 if (CL->getBuiltinCallee()) 9609 return; 9610 9611 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9612 if (CR->getBuiltinCallee()) 9613 return; 9614 9615 // Emit the diagnostic. 9616 Diag(Loc, diag::warn_floatingpoint_eq) 9617 << LHS->getSourceRange() << RHS->getSourceRange(); 9618 } 9619 9620 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9621 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9622 9623 namespace { 9624 9625 /// Structure recording the 'active' range of an integer-valued 9626 /// expression. 9627 struct IntRange { 9628 /// The number of bits active in the int. 9629 unsigned Width; 9630 9631 /// True if the int is known not to have negative values. 9632 bool NonNegative; 9633 9634 IntRange(unsigned Width, bool NonNegative) 9635 : Width(Width), NonNegative(NonNegative) {} 9636 9637 /// Returns the range of the bool type. 9638 static IntRange forBoolType() { 9639 return IntRange(1, true); 9640 } 9641 9642 /// Returns the range of an opaque value of the given integral type. 9643 static IntRange forValueOfType(ASTContext &C, QualType T) { 9644 return forValueOfCanonicalType(C, 9645 T->getCanonicalTypeInternal().getTypePtr()); 9646 } 9647 9648 /// Returns the range of an opaque value of a canonical integral type. 9649 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9650 assert(T->isCanonicalUnqualified()); 9651 9652 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9653 T = VT->getElementType().getTypePtr(); 9654 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9655 T = CT->getElementType().getTypePtr(); 9656 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9657 T = AT->getValueType().getTypePtr(); 9658 9659 if (!C.getLangOpts().CPlusPlus) { 9660 // For enum types in C code, use the underlying datatype. 9661 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9662 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9663 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9664 // For enum types in C++, use the known bit width of the enumerators. 9665 EnumDecl *Enum = ET->getDecl(); 9666 // In C++11, enums can have a fixed underlying type. Use this type to 9667 // compute the range. 9668 if (Enum->isFixed()) { 9669 return IntRange(C.getIntWidth(QualType(T, 0)), 9670 !ET->isSignedIntegerOrEnumerationType()); 9671 } 9672 9673 unsigned NumPositive = Enum->getNumPositiveBits(); 9674 unsigned NumNegative = Enum->getNumNegativeBits(); 9675 9676 if (NumNegative == 0) 9677 return IntRange(NumPositive, true/*NonNegative*/); 9678 else 9679 return IntRange(std::max(NumPositive + 1, NumNegative), 9680 false/*NonNegative*/); 9681 } 9682 9683 const BuiltinType *BT = cast<BuiltinType>(T); 9684 assert(BT->isInteger()); 9685 9686 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9687 } 9688 9689 /// Returns the "target" range of a canonical integral type, i.e. 9690 /// the range of values expressible in the type. 9691 /// 9692 /// This matches forValueOfCanonicalType except that enums have the 9693 /// full range of their type, not the range of their enumerators. 9694 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9695 assert(T->isCanonicalUnqualified()); 9696 9697 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9698 T = VT->getElementType().getTypePtr(); 9699 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9700 T = CT->getElementType().getTypePtr(); 9701 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9702 T = AT->getValueType().getTypePtr(); 9703 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9704 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9705 9706 const BuiltinType *BT = cast<BuiltinType>(T); 9707 assert(BT->isInteger()); 9708 9709 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9710 } 9711 9712 /// Returns the supremum of two ranges: i.e. their conservative merge. 9713 static IntRange join(IntRange L, IntRange R) { 9714 return IntRange(std::max(L.Width, R.Width), 9715 L.NonNegative && R.NonNegative); 9716 } 9717 9718 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9719 static IntRange meet(IntRange L, IntRange R) { 9720 return IntRange(std::min(L.Width, R.Width), 9721 L.NonNegative || R.NonNegative); 9722 } 9723 }; 9724 9725 } // namespace 9726 9727 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9728 unsigned MaxWidth) { 9729 if (value.isSigned() && value.isNegative()) 9730 return IntRange(value.getMinSignedBits(), false); 9731 9732 if (value.getBitWidth() > MaxWidth) 9733 value = value.trunc(MaxWidth); 9734 9735 // isNonNegative() just checks the sign bit without considering 9736 // signedness. 9737 return IntRange(value.getActiveBits(), true); 9738 } 9739 9740 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9741 unsigned MaxWidth) { 9742 if (result.isInt()) 9743 return GetValueRange(C, result.getInt(), MaxWidth); 9744 9745 if (result.isVector()) { 9746 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9747 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9748 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9749 R = IntRange::join(R, El); 9750 } 9751 return R; 9752 } 9753 9754 if (result.isComplexInt()) { 9755 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9756 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9757 return IntRange::join(R, I); 9758 } 9759 9760 // This can happen with lossless casts to intptr_t of "based" lvalues. 9761 // Assume it might use arbitrary bits. 9762 // FIXME: The only reason we need to pass the type in here is to get 9763 // the sign right on this one case. It would be nice if APValue 9764 // preserved this. 9765 assert(result.isLValue() || result.isAddrLabelDiff()); 9766 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9767 } 9768 9769 static QualType GetExprType(const Expr *E) { 9770 QualType Ty = E->getType(); 9771 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9772 Ty = AtomicRHS->getValueType(); 9773 return Ty; 9774 } 9775 9776 /// Pseudo-evaluate the given integer expression, estimating the 9777 /// range of values it might take. 9778 /// 9779 /// \param MaxWidth - the width to which the value will be truncated 9780 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 9781 bool InConstantContext) { 9782 E = E->IgnoreParens(); 9783 9784 // Try a full evaluation first. 9785 Expr::EvalResult result; 9786 if (E->EvaluateAsRValue(result, C, InConstantContext)) 9787 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9788 9789 // I think we only want to look through implicit casts here; if the 9790 // user has an explicit widening cast, we should treat the value as 9791 // being of the new, wider type. 9792 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9793 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9794 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 9795 9796 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9797 9798 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9799 CE->getCastKind() == CK_BooleanToSignedIntegral; 9800 9801 // Assume that non-integer casts can span the full range of the type. 9802 if (!isIntegerCast) 9803 return OutputTypeRange; 9804 9805 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 9806 std::min(MaxWidth, OutputTypeRange.Width), 9807 InConstantContext); 9808 9809 // Bail out if the subexpr's range is as wide as the cast type. 9810 if (SubRange.Width >= OutputTypeRange.Width) 9811 return OutputTypeRange; 9812 9813 // Otherwise, we take the smaller width, and we're non-negative if 9814 // either the output type or the subexpr is. 9815 return IntRange(SubRange.Width, 9816 SubRange.NonNegative || OutputTypeRange.NonNegative); 9817 } 9818 9819 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9820 // If we can fold the condition, just take that operand. 9821 bool CondResult; 9822 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9823 return GetExprRange(C, 9824 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 9825 MaxWidth, InConstantContext); 9826 9827 // Otherwise, conservatively merge. 9828 IntRange L = 9829 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 9830 IntRange R = 9831 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 9832 return IntRange::join(L, R); 9833 } 9834 9835 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9836 switch (BO->getOpcode()) { 9837 case BO_Cmp: 9838 llvm_unreachable("builtin <=> should have class type"); 9839 9840 // Boolean-valued operations are single-bit and positive. 9841 case BO_LAnd: 9842 case BO_LOr: 9843 case BO_LT: 9844 case BO_GT: 9845 case BO_LE: 9846 case BO_GE: 9847 case BO_EQ: 9848 case BO_NE: 9849 return IntRange::forBoolType(); 9850 9851 // The type of the assignments is the type of the LHS, so the RHS 9852 // is not necessarily the same type. 9853 case BO_MulAssign: 9854 case BO_DivAssign: 9855 case BO_RemAssign: 9856 case BO_AddAssign: 9857 case BO_SubAssign: 9858 case BO_XorAssign: 9859 case BO_OrAssign: 9860 // TODO: bitfields? 9861 return IntRange::forValueOfType(C, GetExprType(E)); 9862 9863 // Simple assignments just pass through the RHS, which will have 9864 // been coerced to the LHS type. 9865 case BO_Assign: 9866 // TODO: bitfields? 9867 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 9868 9869 // Operations with opaque sources are black-listed. 9870 case BO_PtrMemD: 9871 case BO_PtrMemI: 9872 return IntRange::forValueOfType(C, GetExprType(E)); 9873 9874 // Bitwise-and uses the *infinum* of the two source ranges. 9875 case BO_And: 9876 case BO_AndAssign: 9877 return IntRange::meet( 9878 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 9879 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 9880 9881 // Left shift gets black-listed based on a judgement call. 9882 case BO_Shl: 9883 // ...except that we want to treat '1 << (blah)' as logically 9884 // positive. It's an important idiom. 9885 if (IntegerLiteral *I 9886 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9887 if (I->getValue() == 1) { 9888 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9889 return IntRange(R.Width, /*NonNegative*/ true); 9890 } 9891 } 9892 LLVM_FALLTHROUGH; 9893 9894 case BO_ShlAssign: 9895 return IntRange::forValueOfType(C, GetExprType(E)); 9896 9897 // Right shift by a constant can narrow its left argument. 9898 case BO_Shr: 9899 case BO_ShrAssign: { 9900 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 9901 9902 // If the shift amount is a positive constant, drop the width by 9903 // that much. 9904 llvm::APSInt shift; 9905 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9906 shift.isNonNegative()) { 9907 unsigned zext = shift.getZExtValue(); 9908 if (zext >= L.Width) 9909 L.Width = (L.NonNegative ? 0 : 1); 9910 else 9911 L.Width -= zext; 9912 } 9913 9914 return L; 9915 } 9916 9917 // Comma acts as its right operand. 9918 case BO_Comma: 9919 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 9920 9921 // Black-list pointer subtractions. 9922 case BO_Sub: 9923 if (BO->getLHS()->getType()->isPointerType()) 9924 return IntRange::forValueOfType(C, GetExprType(E)); 9925 break; 9926 9927 // The width of a division result is mostly determined by the size 9928 // of the LHS. 9929 case BO_Div: { 9930 // Don't 'pre-truncate' the operands. 9931 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9932 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 9933 9934 // If the divisor is constant, use that. 9935 llvm::APSInt divisor; 9936 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9937 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9938 if (log2 >= L.Width) 9939 L.Width = (L.NonNegative ? 0 : 1); 9940 else 9941 L.Width = std::min(L.Width - log2, MaxWidth); 9942 return L; 9943 } 9944 9945 // Otherwise, just use the LHS's width. 9946 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 9947 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9948 } 9949 9950 // The result of a remainder can't be larger than the result of 9951 // either side. 9952 case BO_Rem: { 9953 // Don't 'pre-truncate' the operands. 9954 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9955 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 9956 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 9957 9958 IntRange meet = IntRange::meet(L, R); 9959 meet.Width = std::min(meet.Width, MaxWidth); 9960 return meet; 9961 } 9962 9963 // The default behavior is okay for these. 9964 case BO_Mul: 9965 case BO_Add: 9966 case BO_Xor: 9967 case BO_Or: 9968 break; 9969 } 9970 9971 // The default case is to treat the operation as if it were closed 9972 // on the narrowest type that encompasses both operands. 9973 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 9974 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 9975 return IntRange::join(L, R); 9976 } 9977 9978 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9979 switch (UO->getOpcode()) { 9980 // Boolean-valued operations are white-listed. 9981 case UO_LNot: 9982 return IntRange::forBoolType(); 9983 9984 // Operations with opaque sources are black-listed. 9985 case UO_Deref: 9986 case UO_AddrOf: // should be impossible 9987 return IntRange::forValueOfType(C, GetExprType(E)); 9988 9989 default: 9990 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 9991 } 9992 } 9993 9994 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9995 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 9996 9997 if (const auto *BitField = E->getSourceBitField()) 9998 return IntRange(BitField->getBitWidthValue(C), 9999 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10000 10001 return IntRange::forValueOfType(C, GetExprType(E)); 10002 } 10003 10004 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10005 bool InConstantContext) { 10006 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10007 } 10008 10009 /// Checks whether the given value, which currently has the given 10010 /// source semantics, has the same value when coerced through the 10011 /// target semantics. 10012 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10013 const llvm::fltSemantics &Src, 10014 const llvm::fltSemantics &Tgt) { 10015 llvm::APFloat truncated = value; 10016 10017 bool ignored; 10018 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10019 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10020 10021 return truncated.bitwiseIsEqual(value); 10022 } 10023 10024 /// Checks whether the given value, which currently has the given 10025 /// source semantics, has the same value when coerced through the 10026 /// target semantics. 10027 /// 10028 /// The value might be a vector of floats (or a complex number). 10029 static bool IsSameFloatAfterCast(const APValue &value, 10030 const llvm::fltSemantics &Src, 10031 const llvm::fltSemantics &Tgt) { 10032 if (value.isFloat()) 10033 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10034 10035 if (value.isVector()) { 10036 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10037 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10038 return false; 10039 return true; 10040 } 10041 10042 assert(value.isComplexFloat()); 10043 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10044 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10045 } 10046 10047 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10048 bool IsListInit = false); 10049 10050 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10051 // Suppress cases where we are comparing against an enum constant. 10052 if (const DeclRefExpr *DR = 10053 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10054 if (isa<EnumConstantDecl>(DR->getDecl())) 10055 return true; 10056 10057 // Suppress cases where the value is expanded from a macro, unless that macro 10058 // is how a language represents a boolean literal. This is the case in both C 10059 // and Objective-C. 10060 SourceLocation BeginLoc = E->getBeginLoc(); 10061 if (BeginLoc.isMacroID()) { 10062 StringRef MacroName = Lexer::getImmediateMacroName( 10063 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10064 return MacroName != "YES" && MacroName != "NO" && 10065 MacroName != "true" && MacroName != "false"; 10066 } 10067 10068 return false; 10069 } 10070 10071 static bool isKnownToHaveUnsignedValue(Expr *E) { 10072 return E->getType()->isIntegerType() && 10073 (!E->getType()->isSignedIntegerType() || 10074 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10075 } 10076 10077 namespace { 10078 /// The promoted range of values of a type. In general this has the 10079 /// following structure: 10080 /// 10081 /// |-----------| . . . |-----------| 10082 /// ^ ^ ^ ^ 10083 /// Min HoleMin HoleMax Max 10084 /// 10085 /// ... where there is only a hole if a signed type is promoted to unsigned 10086 /// (in which case Min and Max are the smallest and largest representable 10087 /// values). 10088 struct PromotedRange { 10089 // Min, or HoleMax if there is a hole. 10090 llvm::APSInt PromotedMin; 10091 // Max, or HoleMin if there is a hole. 10092 llvm::APSInt PromotedMax; 10093 10094 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10095 if (R.Width == 0) 10096 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10097 else if (R.Width >= BitWidth && !Unsigned) { 10098 // Promotion made the type *narrower*. This happens when promoting 10099 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10100 // Treat all values of 'signed int' as being in range for now. 10101 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10102 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10103 } else { 10104 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10105 .extOrTrunc(BitWidth); 10106 PromotedMin.setIsUnsigned(Unsigned); 10107 10108 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10109 .extOrTrunc(BitWidth); 10110 PromotedMax.setIsUnsigned(Unsigned); 10111 } 10112 } 10113 10114 // Determine whether this range is contiguous (has no hole). 10115 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10116 10117 // Where a constant value is within the range. 10118 enum ComparisonResult { 10119 LT = 0x1, 10120 LE = 0x2, 10121 GT = 0x4, 10122 GE = 0x8, 10123 EQ = 0x10, 10124 NE = 0x20, 10125 InRangeFlag = 0x40, 10126 10127 Less = LE | LT | NE, 10128 Min = LE | InRangeFlag, 10129 InRange = InRangeFlag, 10130 Max = GE | InRangeFlag, 10131 Greater = GE | GT | NE, 10132 10133 OnlyValue = LE | GE | EQ | InRangeFlag, 10134 InHole = NE 10135 }; 10136 10137 ComparisonResult compare(const llvm::APSInt &Value) const { 10138 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10139 Value.isUnsigned() == PromotedMin.isUnsigned()); 10140 if (!isContiguous()) { 10141 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10142 if (Value.isMinValue()) return Min; 10143 if (Value.isMaxValue()) return Max; 10144 if (Value >= PromotedMin) return InRange; 10145 if (Value <= PromotedMax) return InRange; 10146 return InHole; 10147 } 10148 10149 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10150 case -1: return Less; 10151 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10152 case 1: 10153 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10154 case -1: return InRange; 10155 case 0: return Max; 10156 case 1: return Greater; 10157 } 10158 } 10159 10160 llvm_unreachable("impossible compare result"); 10161 } 10162 10163 static llvm::Optional<StringRef> 10164 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10165 if (Op == BO_Cmp) { 10166 ComparisonResult LTFlag = LT, GTFlag = GT; 10167 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10168 10169 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10170 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10171 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10172 return llvm::None; 10173 } 10174 10175 ComparisonResult TrueFlag, FalseFlag; 10176 if (Op == BO_EQ) { 10177 TrueFlag = EQ; 10178 FalseFlag = NE; 10179 } else if (Op == BO_NE) { 10180 TrueFlag = NE; 10181 FalseFlag = EQ; 10182 } else { 10183 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10184 TrueFlag = LT; 10185 FalseFlag = GE; 10186 } else { 10187 TrueFlag = GT; 10188 FalseFlag = LE; 10189 } 10190 if (Op == BO_GE || Op == BO_LE) 10191 std::swap(TrueFlag, FalseFlag); 10192 } 10193 if (R & TrueFlag) 10194 return StringRef("true"); 10195 if (R & FalseFlag) 10196 return StringRef("false"); 10197 return llvm::None; 10198 } 10199 }; 10200 } 10201 10202 static bool HasEnumType(Expr *E) { 10203 // Strip off implicit integral promotions. 10204 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10205 if (ICE->getCastKind() != CK_IntegralCast && 10206 ICE->getCastKind() != CK_NoOp) 10207 break; 10208 E = ICE->getSubExpr(); 10209 } 10210 10211 return E->getType()->isEnumeralType(); 10212 } 10213 10214 static int classifyConstantValue(Expr *Constant) { 10215 // The values of this enumeration are used in the diagnostics 10216 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10217 enum ConstantValueKind { 10218 Miscellaneous = 0, 10219 LiteralTrue, 10220 LiteralFalse 10221 }; 10222 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10223 return BL->getValue() ? ConstantValueKind::LiteralTrue 10224 : ConstantValueKind::LiteralFalse; 10225 return ConstantValueKind::Miscellaneous; 10226 } 10227 10228 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10229 Expr *Constant, Expr *Other, 10230 const llvm::APSInt &Value, 10231 bool RhsConstant) { 10232 if (S.inTemplateInstantiation()) 10233 return false; 10234 10235 Expr *OriginalOther = Other; 10236 10237 Constant = Constant->IgnoreParenImpCasts(); 10238 Other = Other->IgnoreParenImpCasts(); 10239 10240 // Suppress warnings on tautological comparisons between values of the same 10241 // enumeration type. There are only two ways we could warn on this: 10242 // - If the constant is outside the range of representable values of 10243 // the enumeration. In such a case, we should warn about the cast 10244 // to enumeration type, not about the comparison. 10245 // - If the constant is the maximum / minimum in-range value. For an 10246 // enumeratin type, such comparisons can be meaningful and useful. 10247 if (Constant->getType()->isEnumeralType() && 10248 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10249 return false; 10250 10251 // TODO: Investigate using GetExprRange() to get tighter bounds 10252 // on the bit ranges. 10253 QualType OtherT = Other->getType(); 10254 if (const auto *AT = OtherT->getAs<AtomicType>()) 10255 OtherT = AT->getValueType(); 10256 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10257 10258 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10259 // (Namely, macOS). 10260 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10261 S.NSAPIObj->isObjCBOOLType(OtherT) && 10262 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10263 10264 // Whether we're treating Other as being a bool because of the form of 10265 // expression despite it having another type (typically 'int' in C). 10266 bool OtherIsBooleanDespiteType = 10267 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10268 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10269 OtherRange = IntRange::forBoolType(); 10270 10271 // Determine the promoted range of the other type and see if a comparison of 10272 // the constant against that range is tautological. 10273 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10274 Value.isUnsigned()); 10275 auto Cmp = OtherPromotedRange.compare(Value); 10276 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10277 if (!Result) 10278 return false; 10279 10280 // Suppress the diagnostic for an in-range comparison if the constant comes 10281 // from a macro or enumerator. We don't want to diagnose 10282 // 10283 // some_long_value <= INT_MAX 10284 // 10285 // when sizeof(int) == sizeof(long). 10286 bool InRange = Cmp & PromotedRange::InRangeFlag; 10287 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10288 return false; 10289 10290 // If this is a comparison to an enum constant, include that 10291 // constant in the diagnostic. 10292 const EnumConstantDecl *ED = nullptr; 10293 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10294 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10295 10296 // Should be enough for uint128 (39 decimal digits) 10297 SmallString<64> PrettySourceValue; 10298 llvm::raw_svector_ostream OS(PrettySourceValue); 10299 if (ED) { 10300 OS << '\'' << *ED << "' (" << Value << ")"; 10301 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10302 Constant->IgnoreParenImpCasts())) { 10303 OS << (BL->getValue() ? "YES" : "NO"); 10304 } else { 10305 OS << Value; 10306 } 10307 10308 if (IsObjCSignedCharBool) { 10309 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10310 S.PDiag(diag::warn_tautological_compare_objc_bool) 10311 << OS.str() << *Result); 10312 return true; 10313 } 10314 10315 // FIXME: We use a somewhat different formatting for the in-range cases and 10316 // cases involving boolean values for historical reasons. We should pick a 10317 // consistent way of presenting these diagnostics. 10318 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10319 10320 S.DiagRuntimeBehavior( 10321 E->getOperatorLoc(), E, 10322 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10323 : diag::warn_tautological_bool_compare) 10324 << OS.str() << classifyConstantValue(Constant) << OtherT 10325 << OtherIsBooleanDespiteType << *Result 10326 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10327 } else { 10328 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10329 ? (HasEnumType(OriginalOther) 10330 ? diag::warn_unsigned_enum_always_true_comparison 10331 : diag::warn_unsigned_always_true_comparison) 10332 : diag::warn_tautological_constant_compare; 10333 10334 S.Diag(E->getOperatorLoc(), Diag) 10335 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10336 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10337 } 10338 10339 return true; 10340 } 10341 10342 /// Analyze the operands of the given comparison. Implements the 10343 /// fallback case from AnalyzeComparison. 10344 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10345 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10346 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10347 } 10348 10349 /// Implements -Wsign-compare. 10350 /// 10351 /// \param E the binary operator to check for warnings 10352 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10353 // The type the comparison is being performed in. 10354 QualType T = E->getLHS()->getType(); 10355 10356 // Only analyze comparison operators where both sides have been converted to 10357 // the same type. 10358 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10359 return AnalyzeImpConvsInComparison(S, E); 10360 10361 // Don't analyze value-dependent comparisons directly. 10362 if (E->isValueDependent()) 10363 return AnalyzeImpConvsInComparison(S, E); 10364 10365 Expr *LHS = E->getLHS(); 10366 Expr *RHS = E->getRHS(); 10367 10368 if (T->isIntegralType(S.Context)) { 10369 llvm::APSInt RHSValue; 10370 llvm::APSInt LHSValue; 10371 10372 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10373 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10374 10375 // We don't care about expressions whose result is a constant. 10376 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10377 return AnalyzeImpConvsInComparison(S, E); 10378 10379 // We only care about expressions where just one side is literal 10380 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10381 // Is the constant on the RHS or LHS? 10382 const bool RhsConstant = IsRHSIntegralLiteral; 10383 Expr *Const = RhsConstant ? RHS : LHS; 10384 Expr *Other = RhsConstant ? LHS : RHS; 10385 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10386 10387 // Check whether an integer constant comparison results in a value 10388 // of 'true' or 'false'. 10389 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10390 return AnalyzeImpConvsInComparison(S, E); 10391 } 10392 } 10393 10394 if (!T->hasUnsignedIntegerRepresentation()) { 10395 // We don't do anything special if this isn't an unsigned integral 10396 // comparison: we're only interested in integral comparisons, and 10397 // signed comparisons only happen in cases we don't care to warn about. 10398 return AnalyzeImpConvsInComparison(S, E); 10399 } 10400 10401 LHS = LHS->IgnoreParenImpCasts(); 10402 RHS = RHS->IgnoreParenImpCasts(); 10403 10404 if (!S.getLangOpts().CPlusPlus) { 10405 // Avoid warning about comparison of integers with different signs when 10406 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10407 // the type of `E`. 10408 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10409 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10410 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10411 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10412 } 10413 10414 // Check to see if one of the (unmodified) operands is of different 10415 // signedness. 10416 Expr *signedOperand, *unsignedOperand; 10417 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10418 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10419 "unsigned comparison between two signed integer expressions?"); 10420 signedOperand = LHS; 10421 unsignedOperand = RHS; 10422 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10423 signedOperand = RHS; 10424 unsignedOperand = LHS; 10425 } else { 10426 return AnalyzeImpConvsInComparison(S, E); 10427 } 10428 10429 // Otherwise, calculate the effective range of the signed operand. 10430 IntRange signedRange = 10431 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10432 10433 // Go ahead and analyze implicit conversions in the operands. Note 10434 // that we skip the implicit conversions on both sides. 10435 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10436 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10437 10438 // If the signed range is non-negative, -Wsign-compare won't fire. 10439 if (signedRange.NonNegative) 10440 return; 10441 10442 // For (in)equality comparisons, if the unsigned operand is a 10443 // constant which cannot collide with a overflowed signed operand, 10444 // then reinterpreting the signed operand as unsigned will not 10445 // change the result of the comparison. 10446 if (E->isEqualityOp()) { 10447 unsigned comparisonWidth = S.Context.getIntWidth(T); 10448 IntRange unsignedRange = 10449 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10450 10451 // We should never be unable to prove that the unsigned operand is 10452 // non-negative. 10453 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10454 10455 if (unsignedRange.Width < comparisonWidth) 10456 return; 10457 } 10458 10459 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10460 S.PDiag(diag::warn_mixed_sign_comparison) 10461 << LHS->getType() << RHS->getType() 10462 << LHS->getSourceRange() << RHS->getSourceRange()); 10463 } 10464 10465 /// Analyzes an attempt to assign the given value to a bitfield. 10466 /// 10467 /// Returns true if there was something fishy about the attempt. 10468 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10469 SourceLocation InitLoc) { 10470 assert(Bitfield->isBitField()); 10471 if (Bitfield->isInvalidDecl()) 10472 return false; 10473 10474 // White-list bool bitfields. 10475 QualType BitfieldType = Bitfield->getType(); 10476 if (BitfieldType->isBooleanType()) 10477 return false; 10478 10479 if (BitfieldType->isEnumeralType()) { 10480 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10481 // If the underlying enum type was not explicitly specified as an unsigned 10482 // type and the enum contain only positive values, MSVC++ will cause an 10483 // inconsistency by storing this as a signed type. 10484 if (S.getLangOpts().CPlusPlus11 && 10485 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10486 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10487 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10488 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10489 << BitfieldEnumDecl->getNameAsString(); 10490 } 10491 } 10492 10493 if (Bitfield->getType()->isBooleanType()) 10494 return false; 10495 10496 // Ignore value- or type-dependent expressions. 10497 if (Bitfield->getBitWidth()->isValueDependent() || 10498 Bitfield->getBitWidth()->isTypeDependent() || 10499 Init->isValueDependent() || 10500 Init->isTypeDependent()) 10501 return false; 10502 10503 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10504 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10505 10506 Expr::EvalResult Result; 10507 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10508 Expr::SE_AllowSideEffects)) { 10509 // The RHS is not constant. If the RHS has an enum type, make sure the 10510 // bitfield is wide enough to hold all the values of the enum without 10511 // truncation. 10512 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10513 EnumDecl *ED = EnumTy->getDecl(); 10514 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10515 10516 // Enum types are implicitly signed on Windows, so check if there are any 10517 // negative enumerators to see if the enum was intended to be signed or 10518 // not. 10519 bool SignedEnum = ED->getNumNegativeBits() > 0; 10520 10521 // Check for surprising sign changes when assigning enum values to a 10522 // bitfield of different signedness. If the bitfield is signed and we 10523 // have exactly the right number of bits to store this unsigned enum, 10524 // suggest changing the enum to an unsigned type. This typically happens 10525 // on Windows where unfixed enums always use an underlying type of 'int'. 10526 unsigned DiagID = 0; 10527 if (SignedEnum && !SignedBitfield) { 10528 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10529 } else if (SignedBitfield && !SignedEnum && 10530 ED->getNumPositiveBits() == FieldWidth) { 10531 DiagID = diag::warn_signed_bitfield_enum_conversion; 10532 } 10533 10534 if (DiagID) { 10535 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10536 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10537 SourceRange TypeRange = 10538 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10539 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10540 << SignedEnum << TypeRange; 10541 } 10542 10543 // Compute the required bitwidth. If the enum has negative values, we need 10544 // one more bit than the normal number of positive bits to represent the 10545 // sign bit. 10546 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10547 ED->getNumNegativeBits()) 10548 : ED->getNumPositiveBits(); 10549 10550 // Check the bitwidth. 10551 if (BitsNeeded > FieldWidth) { 10552 Expr *WidthExpr = Bitfield->getBitWidth(); 10553 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10554 << Bitfield << ED; 10555 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10556 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10557 } 10558 } 10559 10560 return false; 10561 } 10562 10563 llvm::APSInt Value = Result.Val.getInt(); 10564 10565 unsigned OriginalWidth = Value.getBitWidth(); 10566 10567 if (!Value.isSigned() || Value.isNegative()) 10568 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10569 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10570 OriginalWidth = Value.getMinSignedBits(); 10571 10572 if (OriginalWidth <= FieldWidth) 10573 return false; 10574 10575 // Compute the value which the bitfield will contain. 10576 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10577 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10578 10579 // Check whether the stored value is equal to the original value. 10580 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10581 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10582 return false; 10583 10584 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10585 // therefore don't strictly fit into a signed bitfield of width 1. 10586 if (FieldWidth == 1 && Value == 1) 10587 return false; 10588 10589 std::string PrettyValue = Value.toString(10); 10590 std::string PrettyTrunc = TruncatedValue.toString(10); 10591 10592 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10593 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10594 << Init->getSourceRange(); 10595 10596 return true; 10597 } 10598 10599 /// Analyze the given simple or compound assignment for warning-worthy 10600 /// operations. 10601 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10602 // Just recurse on the LHS. 10603 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10604 10605 // We want to recurse on the RHS as normal unless we're assigning to 10606 // a bitfield. 10607 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10608 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10609 E->getOperatorLoc())) { 10610 // Recurse, ignoring any implicit conversions on the RHS. 10611 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10612 E->getOperatorLoc()); 10613 } 10614 } 10615 10616 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10617 10618 // Diagnose implicitly sequentially-consistent atomic assignment. 10619 if (E->getLHS()->getType()->isAtomicType()) 10620 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10621 } 10622 10623 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10624 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10625 SourceLocation CContext, unsigned diag, 10626 bool pruneControlFlow = false) { 10627 if (pruneControlFlow) { 10628 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10629 S.PDiag(diag) 10630 << SourceType << T << E->getSourceRange() 10631 << SourceRange(CContext)); 10632 return; 10633 } 10634 S.Diag(E->getExprLoc(), diag) 10635 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10636 } 10637 10638 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10639 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10640 SourceLocation CContext, 10641 unsigned diag, bool pruneControlFlow = false) { 10642 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10643 } 10644 10645 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 10646 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 10647 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 10648 } 10649 10650 static void adornObjCBoolConversionDiagWithTernaryFixit( 10651 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 10652 Expr *Ignored = SourceExpr->IgnoreImplicit(); 10653 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 10654 Ignored = OVE->getSourceExpr(); 10655 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 10656 isa<BinaryOperator>(Ignored) || 10657 isa<CXXOperatorCallExpr>(Ignored); 10658 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 10659 if (NeedsParens) 10660 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 10661 << FixItHint::CreateInsertion(EndLoc, ")"); 10662 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 10663 } 10664 10665 /// Diagnose an implicit cast from a floating point value to an integer value. 10666 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10667 SourceLocation CContext) { 10668 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10669 const bool PruneWarnings = S.inTemplateInstantiation(); 10670 10671 Expr *InnerE = E->IgnoreParenImpCasts(); 10672 // We also want to warn on, e.g., "int i = -1.234" 10673 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10674 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10675 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10676 10677 const bool IsLiteral = 10678 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10679 10680 llvm::APFloat Value(0.0); 10681 bool IsConstant = 10682 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10683 if (!IsConstant) { 10684 if (isObjCSignedCharBool(S, T)) { 10685 return adornObjCBoolConversionDiagWithTernaryFixit( 10686 S, E, 10687 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 10688 << E->getType()); 10689 } 10690 10691 return DiagnoseImpCast(S, E, T, CContext, 10692 diag::warn_impcast_float_integer, PruneWarnings); 10693 } 10694 10695 bool isExact = false; 10696 10697 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10698 T->hasUnsignedIntegerRepresentation()); 10699 llvm::APFloat::opStatus Result = Value.convertToInteger( 10700 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10701 10702 // FIXME: Force the precision of the source value down so we don't print 10703 // digits which are usually useless (we don't really care here if we 10704 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10705 // would automatically print the shortest representation, but it's a bit 10706 // tricky to implement. 10707 SmallString<16> PrettySourceValue; 10708 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10709 precision = (precision * 59 + 195) / 196; 10710 Value.toString(PrettySourceValue, precision); 10711 10712 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 10713 return adornObjCBoolConversionDiagWithTernaryFixit( 10714 S, E, 10715 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 10716 << PrettySourceValue); 10717 } 10718 10719 if (Result == llvm::APFloat::opOK && isExact) { 10720 if (IsLiteral) return; 10721 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10722 PruneWarnings); 10723 } 10724 10725 // Conversion of a floating-point value to a non-bool integer where the 10726 // integral part cannot be represented by the integer type is undefined. 10727 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10728 return DiagnoseImpCast( 10729 S, E, T, CContext, 10730 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10731 : diag::warn_impcast_float_to_integer_out_of_range, 10732 PruneWarnings); 10733 10734 unsigned DiagID = 0; 10735 if (IsLiteral) { 10736 // Warn on floating point literal to integer. 10737 DiagID = diag::warn_impcast_literal_float_to_integer; 10738 } else if (IntegerValue == 0) { 10739 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10740 return DiagnoseImpCast(S, E, T, CContext, 10741 diag::warn_impcast_float_integer, PruneWarnings); 10742 } 10743 // Warn on non-zero to zero conversion. 10744 DiagID = diag::warn_impcast_float_to_integer_zero; 10745 } else { 10746 if (IntegerValue.isUnsigned()) { 10747 if (!IntegerValue.isMaxValue()) { 10748 return DiagnoseImpCast(S, E, T, CContext, 10749 diag::warn_impcast_float_integer, PruneWarnings); 10750 } 10751 } else { // IntegerValue.isSigned() 10752 if (!IntegerValue.isMaxSignedValue() && 10753 !IntegerValue.isMinSignedValue()) { 10754 return DiagnoseImpCast(S, E, T, CContext, 10755 diag::warn_impcast_float_integer, PruneWarnings); 10756 } 10757 } 10758 // Warn on evaluatable floating point expression to integer conversion. 10759 DiagID = diag::warn_impcast_float_to_integer; 10760 } 10761 10762 SmallString<16> PrettyTargetValue; 10763 if (IsBool) 10764 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10765 else 10766 IntegerValue.toString(PrettyTargetValue); 10767 10768 if (PruneWarnings) { 10769 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10770 S.PDiag(DiagID) 10771 << E->getType() << T.getUnqualifiedType() 10772 << PrettySourceValue << PrettyTargetValue 10773 << E->getSourceRange() << SourceRange(CContext)); 10774 } else { 10775 S.Diag(E->getExprLoc(), DiagID) 10776 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10777 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10778 } 10779 } 10780 10781 /// Analyze the given compound assignment for the possible losing of 10782 /// floating-point precision. 10783 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10784 assert(isa<CompoundAssignOperator>(E) && 10785 "Must be compound assignment operation"); 10786 // Recurse on the LHS and RHS in here 10787 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10788 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10789 10790 if (E->getLHS()->getType()->isAtomicType()) 10791 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10792 10793 // Now check the outermost expression 10794 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10795 const auto *RBT = cast<CompoundAssignOperator>(E) 10796 ->getComputationResultType() 10797 ->getAs<BuiltinType>(); 10798 10799 // The below checks assume source is floating point. 10800 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10801 10802 // If source is floating point but target is an integer. 10803 if (ResultBT->isInteger()) 10804 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 10805 E->getExprLoc(), diag::warn_impcast_float_integer); 10806 10807 if (!ResultBT->isFloatingPoint()) 10808 return; 10809 10810 // If both source and target are floating points, warn about losing precision. 10811 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 10812 QualType(ResultBT, 0), QualType(RBT, 0)); 10813 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10814 // warn about dropping FP rank. 10815 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10816 diag::warn_impcast_float_result_precision); 10817 } 10818 10819 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10820 IntRange Range) { 10821 if (!Range.Width) return "0"; 10822 10823 llvm::APSInt ValueInRange = Value; 10824 ValueInRange.setIsSigned(!Range.NonNegative); 10825 ValueInRange = ValueInRange.trunc(Range.Width); 10826 return ValueInRange.toString(10); 10827 } 10828 10829 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10830 if (!isa<ImplicitCastExpr>(Ex)) 10831 return false; 10832 10833 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10834 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10835 const Type *Source = 10836 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10837 if (Target->isDependentType()) 10838 return false; 10839 10840 const BuiltinType *FloatCandidateBT = 10841 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10842 const Type *BoolCandidateType = ToBool ? Target : Source; 10843 10844 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10845 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10846 } 10847 10848 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10849 SourceLocation CC) { 10850 unsigned NumArgs = TheCall->getNumArgs(); 10851 for (unsigned i = 0; i < NumArgs; ++i) { 10852 Expr *CurrA = TheCall->getArg(i); 10853 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10854 continue; 10855 10856 bool IsSwapped = ((i > 0) && 10857 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10858 IsSwapped |= ((i < (NumArgs - 1)) && 10859 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10860 if (IsSwapped) { 10861 // Warn on this floating-point to bool conversion. 10862 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10863 CurrA->getType(), CC, 10864 diag::warn_impcast_floating_point_to_bool); 10865 } 10866 } 10867 } 10868 10869 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10870 SourceLocation CC) { 10871 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10872 E->getExprLoc())) 10873 return; 10874 10875 // Don't warn on functions which have return type nullptr_t. 10876 if (isa<CallExpr>(E)) 10877 return; 10878 10879 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10880 const Expr::NullPointerConstantKind NullKind = 10881 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10882 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10883 return; 10884 10885 // Return if target type is a safe conversion. 10886 if (T->isAnyPointerType() || T->isBlockPointerType() || 10887 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10888 return; 10889 10890 SourceLocation Loc = E->getSourceRange().getBegin(); 10891 10892 // Venture through the macro stacks to get to the source of macro arguments. 10893 // The new location is a better location than the complete location that was 10894 // passed in. 10895 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10896 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10897 10898 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10899 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10900 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10901 Loc, S.SourceMgr, S.getLangOpts()); 10902 if (MacroName == "NULL") 10903 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10904 } 10905 10906 // Only warn if the null and context location are in the same macro expansion. 10907 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10908 return; 10909 10910 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10911 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10912 << FixItHint::CreateReplacement(Loc, 10913 S.getFixItZeroLiteralForType(T, Loc)); 10914 } 10915 10916 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10917 ObjCArrayLiteral *ArrayLiteral); 10918 10919 static void 10920 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10921 ObjCDictionaryLiteral *DictionaryLiteral); 10922 10923 /// Check a single element within a collection literal against the 10924 /// target element type. 10925 static void checkObjCCollectionLiteralElement(Sema &S, 10926 QualType TargetElementType, 10927 Expr *Element, 10928 unsigned ElementKind) { 10929 // Skip a bitcast to 'id' or qualified 'id'. 10930 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10931 if (ICE->getCastKind() == CK_BitCast && 10932 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10933 Element = ICE->getSubExpr(); 10934 } 10935 10936 QualType ElementType = Element->getType(); 10937 ExprResult ElementResult(Element); 10938 if (ElementType->getAs<ObjCObjectPointerType>() && 10939 S.CheckSingleAssignmentConstraints(TargetElementType, 10940 ElementResult, 10941 false, false) 10942 != Sema::Compatible) { 10943 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 10944 << ElementType << ElementKind << TargetElementType 10945 << Element->getSourceRange(); 10946 } 10947 10948 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10949 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10950 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10951 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10952 } 10953 10954 /// Check an Objective-C array literal being converted to the given 10955 /// target type. 10956 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10957 ObjCArrayLiteral *ArrayLiteral) { 10958 if (!S.NSArrayDecl) 10959 return; 10960 10961 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10962 if (!TargetObjCPtr) 10963 return; 10964 10965 if (TargetObjCPtr->isUnspecialized() || 10966 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10967 != S.NSArrayDecl->getCanonicalDecl()) 10968 return; 10969 10970 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10971 if (TypeArgs.size() != 1) 10972 return; 10973 10974 QualType TargetElementType = TypeArgs[0]; 10975 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10976 checkObjCCollectionLiteralElement(S, TargetElementType, 10977 ArrayLiteral->getElement(I), 10978 0); 10979 } 10980 } 10981 10982 /// Check an Objective-C dictionary literal being converted to the given 10983 /// target type. 10984 static void 10985 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10986 ObjCDictionaryLiteral *DictionaryLiteral) { 10987 if (!S.NSDictionaryDecl) 10988 return; 10989 10990 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10991 if (!TargetObjCPtr) 10992 return; 10993 10994 if (TargetObjCPtr->isUnspecialized() || 10995 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10996 != S.NSDictionaryDecl->getCanonicalDecl()) 10997 return; 10998 10999 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11000 if (TypeArgs.size() != 2) 11001 return; 11002 11003 QualType TargetKeyType = TypeArgs[0]; 11004 QualType TargetObjectType = TypeArgs[1]; 11005 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11006 auto Element = DictionaryLiteral->getKeyValueElement(I); 11007 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11008 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11009 } 11010 } 11011 11012 // Helper function to filter out cases for constant width constant conversion. 11013 // Don't warn on char array initialization or for non-decimal values. 11014 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11015 SourceLocation CC) { 11016 // If initializing from a constant, and the constant starts with '0', 11017 // then it is a binary, octal, or hexadecimal. Allow these constants 11018 // to fill all the bits, even if there is a sign change. 11019 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11020 const char FirstLiteralCharacter = 11021 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11022 if (FirstLiteralCharacter == '0') 11023 return false; 11024 } 11025 11026 // If the CC location points to a '{', and the type is char, then assume 11027 // assume it is an array initialization. 11028 if (CC.isValid() && T->isCharType()) { 11029 const char FirstContextCharacter = 11030 S.getSourceManager().getCharacterData(CC)[0]; 11031 if (FirstContextCharacter == '{') 11032 return false; 11033 } 11034 11035 return true; 11036 } 11037 11038 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11039 const auto *IL = dyn_cast<IntegerLiteral>(E); 11040 if (!IL) { 11041 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11042 if (UO->getOpcode() == UO_Minus) 11043 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11044 } 11045 } 11046 11047 return IL; 11048 } 11049 11050 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11051 E = E->IgnoreParenImpCasts(); 11052 SourceLocation ExprLoc = E->getExprLoc(); 11053 11054 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11055 BinaryOperator::Opcode Opc = BO->getOpcode(); 11056 Expr::EvalResult Result; 11057 // Do not diagnose unsigned shifts. 11058 if (Opc == BO_Shl) { 11059 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11060 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11061 if (LHS && LHS->getValue() == 0) 11062 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11063 else if (!E->isValueDependent() && LHS && RHS && 11064 RHS->getValue().isNonNegative() && 11065 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11066 S.Diag(ExprLoc, diag::warn_left_shift_always) 11067 << (Result.Val.getInt() != 0); 11068 else if (E->getType()->isSignedIntegerType()) 11069 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11070 } 11071 } 11072 11073 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11074 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11075 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11076 if (!LHS || !RHS) 11077 return; 11078 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11079 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11080 // Do not diagnose common idioms. 11081 return; 11082 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11083 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11084 } 11085 } 11086 11087 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11088 SourceLocation CC, 11089 bool *ICContext = nullptr, 11090 bool IsListInit = false) { 11091 if (E->isTypeDependent() || E->isValueDependent()) return; 11092 11093 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11094 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11095 if (Source == Target) return; 11096 if (Target->isDependentType()) return; 11097 11098 // If the conversion context location is invalid don't complain. We also 11099 // don't want to emit a warning if the issue occurs from the expansion of 11100 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11101 // delay this check as long as possible. Once we detect we are in that 11102 // scenario, we just return. 11103 if (CC.isInvalid()) 11104 return; 11105 11106 if (Source->isAtomicType()) 11107 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11108 11109 // Diagnose implicit casts to bool. 11110 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11111 if (isa<StringLiteral>(E)) 11112 // Warn on string literal to bool. Checks for string literals in logical 11113 // and expressions, for instance, assert(0 && "error here"), are 11114 // prevented by a check in AnalyzeImplicitConversions(). 11115 return DiagnoseImpCast(S, E, T, CC, 11116 diag::warn_impcast_string_literal_to_bool); 11117 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11118 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11119 // This covers the literal expressions that evaluate to Objective-C 11120 // objects. 11121 return DiagnoseImpCast(S, E, T, CC, 11122 diag::warn_impcast_objective_c_literal_to_bool); 11123 } 11124 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11125 // Warn on pointer to bool conversion that is always true. 11126 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11127 SourceRange(CC)); 11128 } 11129 } 11130 11131 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11132 // is a typedef for signed char (macOS), then that constant value has to be 1 11133 // or 0. 11134 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11135 Expr::EvalResult Result; 11136 if (E->EvaluateAsInt(Result, S.getASTContext(), 11137 Expr::SE_AllowSideEffects)) { 11138 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11139 adornObjCBoolConversionDiagWithTernaryFixit( 11140 S, E, 11141 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11142 << Result.Val.getInt().toString(10)); 11143 } 11144 return; 11145 } 11146 } 11147 11148 // Check implicit casts from Objective-C collection literals to specialized 11149 // collection types, e.g., NSArray<NSString *> *. 11150 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11151 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11152 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11153 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11154 11155 // Strip vector types. 11156 if (isa<VectorType>(Source)) { 11157 if (!isa<VectorType>(Target)) { 11158 if (S.SourceMgr.isInSystemMacro(CC)) 11159 return; 11160 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11161 } 11162 11163 // If the vector cast is cast between two vectors of the same size, it is 11164 // a bitcast, not a conversion. 11165 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11166 return; 11167 11168 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11169 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11170 } 11171 if (auto VecTy = dyn_cast<VectorType>(Target)) 11172 Target = VecTy->getElementType().getTypePtr(); 11173 11174 // Strip complex types. 11175 if (isa<ComplexType>(Source)) { 11176 if (!isa<ComplexType>(Target)) { 11177 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11178 return; 11179 11180 return DiagnoseImpCast(S, E, T, CC, 11181 S.getLangOpts().CPlusPlus 11182 ? diag::err_impcast_complex_scalar 11183 : diag::warn_impcast_complex_scalar); 11184 } 11185 11186 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11187 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11188 } 11189 11190 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11191 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11192 11193 // If the source is floating point... 11194 if (SourceBT && SourceBT->isFloatingPoint()) { 11195 // ...and the target is floating point... 11196 if (TargetBT && TargetBT->isFloatingPoint()) { 11197 // ...then warn if we're dropping FP rank. 11198 11199 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11200 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11201 if (Order > 0) { 11202 // Don't warn about float constants that are precisely 11203 // representable in the target type. 11204 Expr::EvalResult result; 11205 if (E->EvaluateAsRValue(result, S.Context)) { 11206 // Value might be a float, a float vector, or a float complex. 11207 if (IsSameFloatAfterCast(result.Val, 11208 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11209 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11210 return; 11211 } 11212 11213 if (S.SourceMgr.isInSystemMacro(CC)) 11214 return; 11215 11216 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11217 } 11218 // ... or possibly if we're increasing rank, too 11219 else if (Order < 0) { 11220 if (S.SourceMgr.isInSystemMacro(CC)) 11221 return; 11222 11223 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11224 } 11225 return; 11226 } 11227 11228 // If the target is integral, always warn. 11229 if (TargetBT && TargetBT->isInteger()) { 11230 if (S.SourceMgr.isInSystemMacro(CC)) 11231 return; 11232 11233 DiagnoseFloatingImpCast(S, E, T, CC); 11234 } 11235 11236 // Detect the case where a call result is converted from floating-point to 11237 // to bool, and the final argument to the call is converted from bool, to 11238 // discover this typo: 11239 // 11240 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11241 // 11242 // FIXME: This is an incredibly special case; is there some more general 11243 // way to detect this class of misplaced-parentheses bug? 11244 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11245 // Check last argument of function call to see if it is an 11246 // implicit cast from a type matching the type the result 11247 // is being cast to. 11248 CallExpr *CEx = cast<CallExpr>(E); 11249 if (unsigned NumArgs = CEx->getNumArgs()) { 11250 Expr *LastA = CEx->getArg(NumArgs - 1); 11251 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11252 if (isa<ImplicitCastExpr>(LastA) && 11253 InnerE->getType()->isBooleanType()) { 11254 // Warn on this floating-point to bool conversion 11255 DiagnoseImpCast(S, E, T, CC, 11256 diag::warn_impcast_floating_point_to_bool); 11257 } 11258 } 11259 } 11260 return; 11261 } 11262 11263 // Valid casts involving fixed point types should be accounted for here. 11264 if (Source->isFixedPointType()) { 11265 if (Target->isUnsaturatedFixedPointType()) { 11266 Expr::EvalResult Result; 11267 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11268 S.isConstantEvaluated())) { 11269 APFixedPoint Value = Result.Val.getFixedPoint(); 11270 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11271 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11272 if (Value > MaxVal || Value < MinVal) { 11273 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11274 S.PDiag(diag::warn_impcast_fixed_point_range) 11275 << Value.toString() << T 11276 << E->getSourceRange() 11277 << clang::SourceRange(CC)); 11278 return; 11279 } 11280 } 11281 } else if (Target->isIntegerType()) { 11282 Expr::EvalResult Result; 11283 if (!S.isConstantEvaluated() && 11284 E->EvaluateAsFixedPoint(Result, S.Context, 11285 Expr::SE_AllowSideEffects)) { 11286 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11287 11288 bool Overflowed; 11289 llvm::APSInt IntResult = FXResult.convertToInt( 11290 S.Context.getIntWidth(T), 11291 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11292 11293 if (Overflowed) { 11294 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11295 S.PDiag(diag::warn_impcast_fixed_point_range) 11296 << FXResult.toString() << T 11297 << E->getSourceRange() 11298 << clang::SourceRange(CC)); 11299 return; 11300 } 11301 } 11302 } 11303 } else if (Target->isUnsaturatedFixedPointType()) { 11304 if (Source->isIntegerType()) { 11305 Expr::EvalResult Result; 11306 if (!S.isConstantEvaluated() && 11307 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11308 llvm::APSInt Value = Result.Val.getInt(); 11309 11310 bool Overflowed; 11311 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11312 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11313 11314 if (Overflowed) { 11315 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11316 S.PDiag(diag::warn_impcast_fixed_point_range) 11317 << Value.toString(/*Radix=*/10) << T 11318 << E->getSourceRange() 11319 << clang::SourceRange(CC)); 11320 return; 11321 } 11322 } 11323 } 11324 } 11325 11326 // If we are casting an integer type to a floating point type without 11327 // initialization-list syntax, we might lose accuracy if the floating 11328 // point type has a narrower significand than the integer type. 11329 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11330 TargetBT->isFloatingType() && !IsListInit) { 11331 // Determine the number of precision bits in the source integer type. 11332 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11333 unsigned int SourcePrecision = SourceRange.Width; 11334 11335 // Determine the number of precision bits in the 11336 // target floating point type. 11337 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11338 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11339 11340 if (SourcePrecision > 0 && TargetPrecision > 0 && 11341 SourcePrecision > TargetPrecision) { 11342 11343 llvm::APSInt SourceInt; 11344 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11345 // If the source integer is a constant, convert it to the target 11346 // floating point type. Issue a warning if the value changes 11347 // during the whole conversion. 11348 llvm::APFloat TargetFloatValue( 11349 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11350 llvm::APFloat::opStatus ConversionStatus = 11351 TargetFloatValue.convertFromAPInt( 11352 SourceInt, SourceBT->isSignedInteger(), 11353 llvm::APFloat::rmNearestTiesToEven); 11354 11355 if (ConversionStatus != llvm::APFloat::opOK) { 11356 std::string PrettySourceValue = SourceInt.toString(10); 11357 SmallString<32> PrettyTargetValue; 11358 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11359 11360 S.DiagRuntimeBehavior( 11361 E->getExprLoc(), E, 11362 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11363 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11364 << E->getSourceRange() << clang::SourceRange(CC)); 11365 } 11366 } else { 11367 // Otherwise, the implicit conversion may lose precision. 11368 DiagnoseImpCast(S, E, T, CC, 11369 diag::warn_impcast_integer_float_precision); 11370 } 11371 } 11372 } 11373 11374 DiagnoseNullConversion(S, E, T, CC); 11375 11376 S.DiscardMisalignedMemberAddress(Target, E); 11377 11378 if (Target->isBooleanType()) 11379 DiagnoseIntInBoolContext(S, E); 11380 11381 if (!Source->isIntegerType() || !Target->isIntegerType()) 11382 return; 11383 11384 // TODO: remove this early return once the false positives for constant->bool 11385 // in templates, macros, etc, are reduced or removed. 11386 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11387 return; 11388 11389 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11390 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11391 return adornObjCBoolConversionDiagWithTernaryFixit( 11392 S, E, 11393 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11394 << E->getType()); 11395 } 11396 11397 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11398 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11399 11400 if (SourceRange.Width > TargetRange.Width) { 11401 // If the source is a constant, use a default-on diagnostic. 11402 // TODO: this should happen for bitfield stores, too. 11403 Expr::EvalResult Result; 11404 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11405 S.isConstantEvaluated())) { 11406 llvm::APSInt Value(32); 11407 Value = Result.Val.getInt(); 11408 11409 if (S.SourceMgr.isInSystemMacro(CC)) 11410 return; 11411 11412 std::string PrettySourceValue = Value.toString(10); 11413 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11414 11415 S.DiagRuntimeBehavior( 11416 E->getExprLoc(), E, 11417 S.PDiag(diag::warn_impcast_integer_precision_constant) 11418 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11419 << E->getSourceRange() << clang::SourceRange(CC)); 11420 return; 11421 } 11422 11423 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11424 if (S.SourceMgr.isInSystemMacro(CC)) 11425 return; 11426 11427 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11428 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11429 /* pruneControlFlow */ true); 11430 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11431 } 11432 11433 if (TargetRange.Width > SourceRange.Width) { 11434 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11435 if (UO->getOpcode() == UO_Minus) 11436 if (Source->isUnsignedIntegerType()) { 11437 if (Target->isUnsignedIntegerType()) 11438 return DiagnoseImpCast(S, E, T, CC, 11439 diag::warn_impcast_high_order_zero_bits); 11440 if (Target->isSignedIntegerType()) 11441 return DiagnoseImpCast(S, E, T, CC, 11442 diag::warn_impcast_nonnegative_result); 11443 } 11444 } 11445 11446 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11447 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11448 // Warn when doing a signed to signed conversion, warn if the positive 11449 // source value is exactly the width of the target type, which will 11450 // cause a negative value to be stored. 11451 11452 Expr::EvalResult Result; 11453 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11454 !S.SourceMgr.isInSystemMacro(CC)) { 11455 llvm::APSInt Value = Result.Val.getInt(); 11456 if (isSameWidthConstantConversion(S, E, T, CC)) { 11457 std::string PrettySourceValue = Value.toString(10); 11458 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11459 11460 S.DiagRuntimeBehavior( 11461 E->getExprLoc(), E, 11462 S.PDiag(diag::warn_impcast_integer_precision_constant) 11463 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11464 << E->getSourceRange() << clang::SourceRange(CC)); 11465 return; 11466 } 11467 } 11468 11469 // Fall through for non-constants to give a sign conversion warning. 11470 } 11471 11472 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11473 (!TargetRange.NonNegative && SourceRange.NonNegative && 11474 SourceRange.Width == TargetRange.Width)) { 11475 if (S.SourceMgr.isInSystemMacro(CC)) 11476 return; 11477 11478 unsigned DiagID = diag::warn_impcast_integer_sign; 11479 11480 // Traditionally, gcc has warned about this under -Wsign-compare. 11481 // We also want to warn about it in -Wconversion. 11482 // So if -Wconversion is off, use a completely identical diagnostic 11483 // in the sign-compare group. 11484 // The conditional-checking code will 11485 if (ICContext) { 11486 DiagID = diag::warn_impcast_integer_sign_conditional; 11487 *ICContext = true; 11488 } 11489 11490 return DiagnoseImpCast(S, E, T, CC, DiagID); 11491 } 11492 11493 // Diagnose conversions between different enumeration types. 11494 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11495 // type, to give us better diagnostics. 11496 QualType SourceType = E->getType(); 11497 if (!S.getLangOpts().CPlusPlus) { 11498 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11499 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11500 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11501 SourceType = S.Context.getTypeDeclType(Enum); 11502 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11503 } 11504 } 11505 11506 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11507 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11508 if (SourceEnum->getDecl()->hasNameForLinkage() && 11509 TargetEnum->getDecl()->hasNameForLinkage() && 11510 SourceEnum != TargetEnum) { 11511 if (S.SourceMgr.isInSystemMacro(CC)) 11512 return; 11513 11514 return DiagnoseImpCast(S, E, SourceType, T, CC, 11515 diag::warn_impcast_different_enum_types); 11516 } 11517 } 11518 11519 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11520 SourceLocation CC, QualType T); 11521 11522 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11523 SourceLocation CC, bool &ICContext) { 11524 E = E->IgnoreParenImpCasts(); 11525 11526 if (isa<ConditionalOperator>(E)) 11527 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11528 11529 AnalyzeImplicitConversions(S, E, CC); 11530 if (E->getType() != T) 11531 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11532 } 11533 11534 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11535 SourceLocation CC, QualType T) { 11536 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11537 11538 bool Suspicious = false; 11539 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11540 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11541 11542 if (T->isBooleanType()) 11543 DiagnoseIntInBoolContext(S, E); 11544 11545 // If -Wconversion would have warned about either of the candidates 11546 // for a signedness conversion to the context type... 11547 if (!Suspicious) return; 11548 11549 // ...but it's currently ignored... 11550 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11551 return; 11552 11553 // ...then check whether it would have warned about either of the 11554 // candidates for a signedness conversion to the condition type. 11555 if (E->getType() == T) return; 11556 11557 Suspicious = false; 11558 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11559 E->getType(), CC, &Suspicious); 11560 if (!Suspicious) 11561 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11562 E->getType(), CC, &Suspicious); 11563 } 11564 11565 /// Check conversion of given expression to boolean. 11566 /// Input argument E is a logical expression. 11567 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11568 if (S.getLangOpts().Bool) 11569 return; 11570 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11571 return; 11572 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11573 } 11574 11575 /// AnalyzeImplicitConversions - Find and report any interesting 11576 /// implicit conversions in the given expression. There are a couple 11577 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11578 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 11579 bool IsListInit/*= false*/) { 11580 QualType T = OrigE->getType(); 11581 Expr *E = OrigE->IgnoreParenImpCasts(); 11582 11583 // Propagate whether we are in a C++ list initialization expression. 11584 // If so, we do not issue warnings for implicit int-float conversion 11585 // precision loss, because C++11 narrowing already handles it. 11586 IsListInit = 11587 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11588 11589 if (E->isTypeDependent() || E->isValueDependent()) 11590 return; 11591 11592 Expr *SourceExpr = E; 11593 // Examine, but don't traverse into the source expression of an 11594 // OpaqueValueExpr, since it may have multiple parents and we don't want to 11595 // emit duplicate diagnostics. Its fine to examine the form or attempt to 11596 // evaluate it in the context of checking the specific conversion to T though. 11597 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11598 if (auto *Src = OVE->getSourceExpr()) 11599 SourceExpr = Src; 11600 11601 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 11602 if (UO->getOpcode() == UO_Not && 11603 UO->getSubExpr()->isKnownToHaveBooleanValue()) 11604 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 11605 << OrigE->getSourceRange() << T->isBooleanType() 11606 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 11607 11608 // For conditional operators, we analyze the arguments as if they 11609 // were being fed directly into the output. 11610 if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) { 11611 CheckConditionalOperator(S, CO, CC, T); 11612 return; 11613 } 11614 11615 // Check implicit argument conversions for function calls. 11616 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 11617 CheckImplicitArgumentConversions(S, Call, CC); 11618 11619 // Go ahead and check any implicit conversions we might have skipped. 11620 // The non-canonical typecheck is just an optimization; 11621 // CheckImplicitConversion will filter out dead implicit conversions. 11622 if (SourceExpr->getType() != T) 11623 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 11624 11625 // Now continue drilling into this expression. 11626 11627 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11628 // The bound subexpressions in a PseudoObjectExpr are not reachable 11629 // as transitive children. 11630 // FIXME: Use a more uniform representation for this. 11631 for (auto *SE : POE->semantics()) 11632 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11633 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit); 11634 } 11635 11636 // Skip past explicit casts. 11637 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11638 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11639 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11640 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11641 return AnalyzeImplicitConversions(S, E, CC, IsListInit); 11642 } 11643 11644 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11645 // Do a somewhat different check with comparison operators. 11646 if (BO->isComparisonOp()) 11647 return AnalyzeComparison(S, BO); 11648 11649 // And with simple assignments. 11650 if (BO->getOpcode() == BO_Assign) 11651 return AnalyzeAssignment(S, BO); 11652 // And with compound assignments. 11653 if (BO->isAssignmentOp()) 11654 return AnalyzeCompoundAssignment(S, BO); 11655 } 11656 11657 // These break the otherwise-useful invariant below. Fortunately, 11658 // we don't really need to recurse into them, because any internal 11659 // expressions should have been analyzed already when they were 11660 // built into statements. 11661 if (isa<StmtExpr>(E)) return; 11662 11663 // Don't descend into unevaluated contexts. 11664 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11665 11666 // Now just recurse over the expression's children. 11667 CC = E->getExprLoc(); 11668 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11669 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11670 for (Stmt *SubStmt : E->children()) { 11671 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11672 if (!ChildExpr) 11673 continue; 11674 11675 if (IsLogicalAndOperator && 11676 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11677 // Ignore checking string literals that are in logical and operators. 11678 // This is a common pattern for asserts. 11679 continue; 11680 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit); 11681 } 11682 11683 if (BO && BO->isLogicalOp()) { 11684 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11685 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11686 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11687 11688 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11689 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11690 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11691 } 11692 11693 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11694 if (U->getOpcode() == UO_LNot) { 11695 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11696 } else if (U->getOpcode() != UO_AddrOf) { 11697 if (U->getSubExpr()->getType()->isAtomicType()) 11698 S.Diag(U->getSubExpr()->getBeginLoc(), 11699 diag::warn_atomic_implicit_seq_cst); 11700 } 11701 } 11702 } 11703 11704 /// Diagnose integer type and any valid implicit conversion to it. 11705 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11706 // Taking into account implicit conversions, 11707 // allow any integer. 11708 if (!E->getType()->isIntegerType()) { 11709 S.Diag(E->getBeginLoc(), 11710 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11711 return true; 11712 } 11713 // Potentially emit standard warnings for implicit conversions if enabled 11714 // using -Wconversion. 11715 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11716 return false; 11717 } 11718 11719 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11720 // Returns true when emitting a warning about taking the address of a reference. 11721 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11722 const PartialDiagnostic &PD) { 11723 E = E->IgnoreParenImpCasts(); 11724 11725 const FunctionDecl *FD = nullptr; 11726 11727 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11728 if (!DRE->getDecl()->getType()->isReferenceType()) 11729 return false; 11730 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11731 if (!M->getMemberDecl()->getType()->isReferenceType()) 11732 return false; 11733 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11734 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11735 return false; 11736 FD = Call->getDirectCallee(); 11737 } else { 11738 return false; 11739 } 11740 11741 SemaRef.Diag(E->getExprLoc(), PD); 11742 11743 // If possible, point to location of function. 11744 if (FD) { 11745 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11746 } 11747 11748 return true; 11749 } 11750 11751 // Returns true if the SourceLocation is expanded from any macro body. 11752 // Returns false if the SourceLocation is invalid, is from not in a macro 11753 // expansion, or is from expanded from a top-level macro argument. 11754 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11755 if (Loc.isInvalid()) 11756 return false; 11757 11758 while (Loc.isMacroID()) { 11759 if (SM.isMacroBodyExpansion(Loc)) 11760 return true; 11761 Loc = SM.getImmediateMacroCallerLoc(Loc); 11762 } 11763 11764 return false; 11765 } 11766 11767 /// Diagnose pointers that are always non-null. 11768 /// \param E the expression containing the pointer 11769 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11770 /// compared to a null pointer 11771 /// \param IsEqual True when the comparison is equal to a null pointer 11772 /// \param Range Extra SourceRange to highlight in the diagnostic 11773 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11774 Expr::NullPointerConstantKind NullKind, 11775 bool IsEqual, SourceRange Range) { 11776 if (!E) 11777 return; 11778 11779 // Don't warn inside macros. 11780 if (E->getExprLoc().isMacroID()) { 11781 const SourceManager &SM = getSourceManager(); 11782 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11783 IsInAnyMacroBody(SM, Range.getBegin())) 11784 return; 11785 } 11786 E = E->IgnoreImpCasts(); 11787 11788 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11789 11790 if (isa<CXXThisExpr>(E)) { 11791 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11792 : diag::warn_this_bool_conversion; 11793 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11794 return; 11795 } 11796 11797 bool IsAddressOf = false; 11798 11799 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11800 if (UO->getOpcode() != UO_AddrOf) 11801 return; 11802 IsAddressOf = true; 11803 E = UO->getSubExpr(); 11804 } 11805 11806 if (IsAddressOf) { 11807 unsigned DiagID = IsCompare 11808 ? diag::warn_address_of_reference_null_compare 11809 : diag::warn_address_of_reference_bool_conversion; 11810 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11811 << IsEqual; 11812 if (CheckForReference(*this, E, PD)) { 11813 return; 11814 } 11815 } 11816 11817 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11818 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11819 std::string Str; 11820 llvm::raw_string_ostream S(Str); 11821 E->printPretty(S, nullptr, getPrintingPolicy()); 11822 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11823 : diag::warn_cast_nonnull_to_bool; 11824 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11825 << E->getSourceRange() << Range << IsEqual; 11826 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11827 }; 11828 11829 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11830 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11831 if (auto *Callee = Call->getDirectCallee()) { 11832 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11833 ComplainAboutNonnullParamOrCall(A); 11834 return; 11835 } 11836 } 11837 } 11838 11839 // Expect to find a single Decl. Skip anything more complicated. 11840 ValueDecl *D = nullptr; 11841 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11842 D = R->getDecl(); 11843 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11844 D = M->getMemberDecl(); 11845 } 11846 11847 // Weak Decls can be null. 11848 if (!D || D->isWeak()) 11849 return; 11850 11851 // Check for parameter decl with nonnull attribute 11852 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11853 if (getCurFunction() && 11854 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11855 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11856 ComplainAboutNonnullParamOrCall(A); 11857 return; 11858 } 11859 11860 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11861 // Skip function template not specialized yet. 11862 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11863 return; 11864 auto ParamIter = llvm::find(FD->parameters(), PV); 11865 assert(ParamIter != FD->param_end()); 11866 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11867 11868 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11869 if (!NonNull->args_size()) { 11870 ComplainAboutNonnullParamOrCall(NonNull); 11871 return; 11872 } 11873 11874 for (const ParamIdx &ArgNo : NonNull->args()) { 11875 if (ArgNo.getASTIndex() == ParamNo) { 11876 ComplainAboutNonnullParamOrCall(NonNull); 11877 return; 11878 } 11879 } 11880 } 11881 } 11882 } 11883 } 11884 11885 QualType T = D->getType(); 11886 const bool IsArray = T->isArrayType(); 11887 const bool IsFunction = T->isFunctionType(); 11888 11889 // Address of function is used to silence the function warning. 11890 if (IsAddressOf && IsFunction) { 11891 return; 11892 } 11893 11894 // Found nothing. 11895 if (!IsAddressOf && !IsFunction && !IsArray) 11896 return; 11897 11898 // Pretty print the expression for the diagnostic. 11899 std::string Str; 11900 llvm::raw_string_ostream S(Str); 11901 E->printPretty(S, nullptr, getPrintingPolicy()); 11902 11903 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11904 : diag::warn_impcast_pointer_to_bool; 11905 enum { 11906 AddressOf, 11907 FunctionPointer, 11908 ArrayPointer 11909 } DiagType; 11910 if (IsAddressOf) 11911 DiagType = AddressOf; 11912 else if (IsFunction) 11913 DiagType = FunctionPointer; 11914 else if (IsArray) 11915 DiagType = ArrayPointer; 11916 else 11917 llvm_unreachable("Could not determine diagnostic."); 11918 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11919 << Range << IsEqual; 11920 11921 if (!IsFunction) 11922 return; 11923 11924 // Suggest '&' to silence the function warning. 11925 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11926 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11927 11928 // Check to see if '()' fixit should be emitted. 11929 QualType ReturnType; 11930 UnresolvedSet<4> NonTemplateOverloads; 11931 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11932 if (ReturnType.isNull()) 11933 return; 11934 11935 if (IsCompare) { 11936 // There are two cases here. If there is null constant, the only suggest 11937 // for a pointer return type. If the null is 0, then suggest if the return 11938 // type is a pointer or an integer type. 11939 if (!ReturnType->isPointerType()) { 11940 if (NullKind == Expr::NPCK_ZeroExpression || 11941 NullKind == Expr::NPCK_ZeroLiteral) { 11942 if (!ReturnType->isIntegerType()) 11943 return; 11944 } else { 11945 return; 11946 } 11947 } 11948 } else { // !IsCompare 11949 // For function to bool, only suggest if the function pointer has bool 11950 // return type. 11951 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11952 return; 11953 } 11954 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11955 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11956 } 11957 11958 /// Diagnoses "dangerous" implicit conversions within the given 11959 /// expression (which is a full expression). Implements -Wconversion 11960 /// and -Wsign-compare. 11961 /// 11962 /// \param CC the "context" location of the implicit conversion, i.e. 11963 /// the most location of the syntactic entity requiring the implicit 11964 /// conversion 11965 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11966 // Don't diagnose in unevaluated contexts. 11967 if (isUnevaluatedContext()) 11968 return; 11969 11970 // Don't diagnose for value- or type-dependent expressions. 11971 if (E->isTypeDependent() || E->isValueDependent()) 11972 return; 11973 11974 // Check for array bounds violations in cases where the check isn't triggered 11975 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11976 // ArraySubscriptExpr is on the RHS of a variable initialization. 11977 CheckArrayAccess(E); 11978 11979 // This is not the right CC for (e.g.) a variable initialization. 11980 AnalyzeImplicitConversions(*this, E, CC); 11981 } 11982 11983 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11984 /// Input argument E is a logical expression. 11985 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11986 ::CheckBoolLikeConversion(*this, E, CC); 11987 } 11988 11989 /// Diagnose when expression is an integer constant expression and its evaluation 11990 /// results in integer overflow 11991 void Sema::CheckForIntOverflow (Expr *E) { 11992 // Use a work list to deal with nested struct initializers. 11993 SmallVector<Expr *, 2> Exprs(1, E); 11994 11995 do { 11996 Expr *OriginalE = Exprs.pop_back_val(); 11997 Expr *E = OriginalE->IgnoreParenCasts(); 11998 11999 if (isa<BinaryOperator>(E)) { 12000 E->EvaluateForOverflow(Context); 12001 continue; 12002 } 12003 12004 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12005 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12006 else if (isa<ObjCBoxedExpr>(OriginalE)) 12007 E->EvaluateForOverflow(Context); 12008 else if (auto Call = dyn_cast<CallExpr>(E)) 12009 Exprs.append(Call->arg_begin(), Call->arg_end()); 12010 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12011 Exprs.append(Message->arg_begin(), Message->arg_end()); 12012 } while (!Exprs.empty()); 12013 } 12014 12015 namespace { 12016 12017 /// Visitor for expressions which looks for unsequenced operations on the 12018 /// same object. 12019 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12020 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12021 12022 /// A tree of sequenced regions within an expression. Two regions are 12023 /// unsequenced if one is an ancestor or a descendent of the other. When we 12024 /// finish processing an expression with sequencing, such as a comma 12025 /// expression, we fold its tree nodes into its parent, since they are 12026 /// unsequenced with respect to nodes we will visit later. 12027 class SequenceTree { 12028 struct Value { 12029 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12030 unsigned Parent : 31; 12031 unsigned Merged : 1; 12032 }; 12033 SmallVector<Value, 8> Values; 12034 12035 public: 12036 /// A region within an expression which may be sequenced with respect 12037 /// to some other region. 12038 class Seq { 12039 friend class SequenceTree; 12040 12041 unsigned Index; 12042 12043 explicit Seq(unsigned N) : Index(N) {} 12044 12045 public: 12046 Seq() : Index(0) {} 12047 }; 12048 12049 SequenceTree() { Values.push_back(Value(0)); } 12050 Seq root() const { return Seq(0); } 12051 12052 /// Create a new sequence of operations, which is an unsequenced 12053 /// subset of \p Parent. This sequence of operations is sequenced with 12054 /// respect to other children of \p Parent. 12055 Seq allocate(Seq Parent) { 12056 Values.push_back(Value(Parent.Index)); 12057 return Seq(Values.size() - 1); 12058 } 12059 12060 /// Merge a sequence of operations into its parent. 12061 void merge(Seq S) { 12062 Values[S.Index].Merged = true; 12063 } 12064 12065 /// Determine whether two operations are unsequenced. This operation 12066 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12067 /// should have been merged into its parent as appropriate. 12068 bool isUnsequenced(Seq Cur, Seq Old) { 12069 unsigned C = representative(Cur.Index); 12070 unsigned Target = representative(Old.Index); 12071 while (C >= Target) { 12072 if (C == Target) 12073 return true; 12074 C = Values[C].Parent; 12075 } 12076 return false; 12077 } 12078 12079 private: 12080 /// Pick a representative for a sequence. 12081 unsigned representative(unsigned K) { 12082 if (Values[K].Merged) 12083 // Perform path compression as we go. 12084 return Values[K].Parent = representative(Values[K].Parent); 12085 return K; 12086 } 12087 }; 12088 12089 /// An object for which we can track unsequenced uses. 12090 using Object = const NamedDecl *; 12091 12092 /// Different flavors of object usage which we track. We only track the 12093 /// least-sequenced usage of each kind. 12094 enum UsageKind { 12095 /// A read of an object. Multiple unsequenced reads are OK. 12096 UK_Use, 12097 12098 /// A modification of an object which is sequenced before the value 12099 /// computation of the expression, such as ++n in C++. 12100 UK_ModAsValue, 12101 12102 /// A modification of an object which is not sequenced before the value 12103 /// computation of the expression, such as n++. 12104 UK_ModAsSideEffect, 12105 12106 UK_Count = UK_ModAsSideEffect + 1 12107 }; 12108 12109 /// Bundle together a sequencing region and the expression corresponding 12110 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12111 struct Usage { 12112 const Expr *UsageExpr; 12113 SequenceTree::Seq Seq; 12114 12115 Usage() : UsageExpr(nullptr), Seq() {} 12116 }; 12117 12118 struct UsageInfo { 12119 Usage Uses[UK_Count]; 12120 12121 /// Have we issued a diagnostic for this object already? 12122 bool Diagnosed; 12123 12124 UsageInfo() : Uses(), Diagnosed(false) {} 12125 }; 12126 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12127 12128 Sema &SemaRef; 12129 12130 /// Sequenced regions within the expression. 12131 SequenceTree Tree; 12132 12133 /// Declaration modifications and references which we have seen. 12134 UsageInfoMap UsageMap; 12135 12136 /// The region we are currently within. 12137 SequenceTree::Seq Region; 12138 12139 /// Filled in with declarations which were modified as a side-effect 12140 /// (that is, post-increment operations). 12141 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12142 12143 /// Expressions to check later. We defer checking these to reduce 12144 /// stack usage. 12145 SmallVectorImpl<const Expr *> &WorkList; 12146 12147 /// RAII object wrapping the visitation of a sequenced subexpression of an 12148 /// expression. At the end of this process, the side-effects of the evaluation 12149 /// become sequenced with respect to the value computation of the result, so 12150 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12151 /// UK_ModAsValue. 12152 struct SequencedSubexpression { 12153 SequencedSubexpression(SequenceChecker &Self) 12154 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12155 Self.ModAsSideEffect = &ModAsSideEffect; 12156 } 12157 12158 ~SequencedSubexpression() { 12159 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12160 // Add a new usage with usage kind UK_ModAsValue, and then restore 12161 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12162 // the previous one was empty). 12163 UsageInfo &UI = Self.UsageMap[M.first]; 12164 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12165 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12166 SideEffectUsage = M.second; 12167 } 12168 Self.ModAsSideEffect = OldModAsSideEffect; 12169 } 12170 12171 SequenceChecker &Self; 12172 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12173 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12174 }; 12175 12176 /// RAII object wrapping the visitation of a subexpression which we might 12177 /// choose to evaluate as a constant. If any subexpression is evaluated and 12178 /// found to be non-constant, this allows us to suppress the evaluation of 12179 /// the outer expression. 12180 class EvaluationTracker { 12181 public: 12182 EvaluationTracker(SequenceChecker &Self) 12183 : Self(Self), Prev(Self.EvalTracker) { 12184 Self.EvalTracker = this; 12185 } 12186 12187 ~EvaluationTracker() { 12188 Self.EvalTracker = Prev; 12189 if (Prev) 12190 Prev->EvalOK &= EvalOK; 12191 } 12192 12193 bool evaluate(const Expr *E, bool &Result) { 12194 if (!EvalOK || E->isValueDependent()) 12195 return false; 12196 EvalOK = E->EvaluateAsBooleanCondition( 12197 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12198 return EvalOK; 12199 } 12200 12201 private: 12202 SequenceChecker &Self; 12203 EvaluationTracker *Prev; 12204 bool EvalOK = true; 12205 } *EvalTracker = nullptr; 12206 12207 /// Find the object which is produced by the specified expression, 12208 /// if any. 12209 Object getObject(const Expr *E, bool Mod) const { 12210 E = E->IgnoreParenCasts(); 12211 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12212 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12213 return getObject(UO->getSubExpr(), Mod); 12214 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12215 if (BO->getOpcode() == BO_Comma) 12216 return getObject(BO->getRHS(), Mod); 12217 if (Mod && BO->isAssignmentOp()) 12218 return getObject(BO->getLHS(), Mod); 12219 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12220 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12221 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12222 return ME->getMemberDecl(); 12223 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12224 // FIXME: If this is a reference, map through to its value. 12225 return DRE->getDecl(); 12226 return nullptr; 12227 } 12228 12229 /// Note that an object \p O was modified or used by an expression 12230 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12231 /// the object \p O as obtained via the \p UsageMap. 12232 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12233 // Get the old usage for the given object and usage kind. 12234 Usage &U = UI.Uses[UK]; 12235 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12236 // If we have a modification as side effect and are in a sequenced 12237 // subexpression, save the old Usage so that we can restore it later 12238 // in SequencedSubexpression::~SequencedSubexpression. 12239 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12240 ModAsSideEffect->push_back(std::make_pair(O, U)); 12241 // Then record the new usage with the current sequencing region. 12242 U.UsageExpr = UsageExpr; 12243 U.Seq = Region; 12244 } 12245 } 12246 12247 /// Check whether a modification or use of an object \p O in an expression 12248 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12249 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12250 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12251 /// usage and false we are checking for a mod-use unsequenced usage. 12252 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12253 UsageKind OtherKind, bool IsModMod) { 12254 if (UI.Diagnosed) 12255 return; 12256 12257 const Usage &U = UI.Uses[OtherKind]; 12258 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12259 return; 12260 12261 const Expr *Mod = U.UsageExpr; 12262 const Expr *ModOrUse = UsageExpr; 12263 if (OtherKind == UK_Use) 12264 std::swap(Mod, ModOrUse); 12265 12266 SemaRef.DiagRuntimeBehavior( 12267 Mod->getExprLoc(), {Mod, ModOrUse}, 12268 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12269 : diag::warn_unsequenced_mod_use) 12270 << O << SourceRange(ModOrUse->getExprLoc())); 12271 UI.Diagnosed = true; 12272 } 12273 12274 // A note on note{Pre, Post}{Use, Mod}: 12275 // 12276 // (It helps to follow the algorithm with an expression such as 12277 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12278 // operations before C++17 and both are well-defined in C++17). 12279 // 12280 // When visiting a node which uses/modify an object we first call notePreUse 12281 // or notePreMod before visiting its sub-expression(s). At this point the 12282 // children of the current node have not yet been visited and so the eventual 12283 // uses/modifications resulting from the children of the current node have not 12284 // been recorded yet. 12285 // 12286 // We then visit the children of the current node. After that notePostUse or 12287 // notePostMod is called. These will 1) detect an unsequenced modification 12288 // as side effect (as in "k++ + k") and 2) add a new usage with the 12289 // appropriate usage kind. 12290 // 12291 // We also have to be careful that some operation sequences modification as 12292 // side effect as well (for example: || or ,). To account for this we wrap 12293 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12294 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12295 // which record usages which are modifications as side effect, and then 12296 // downgrade them (or more accurately restore the previous usage which was a 12297 // modification as side effect) when exiting the scope of the sequenced 12298 // subexpression. 12299 12300 void notePreUse(Object O, const Expr *UseExpr) { 12301 UsageInfo &UI = UsageMap[O]; 12302 // Uses conflict with other modifications. 12303 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12304 } 12305 12306 void notePostUse(Object O, const Expr *UseExpr) { 12307 UsageInfo &UI = UsageMap[O]; 12308 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12309 /*IsModMod=*/false); 12310 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12311 } 12312 12313 void notePreMod(Object O, const Expr *ModExpr) { 12314 UsageInfo &UI = UsageMap[O]; 12315 // Modifications conflict with other modifications and with uses. 12316 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12317 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12318 } 12319 12320 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12321 UsageInfo &UI = UsageMap[O]; 12322 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12323 /*IsModMod=*/true); 12324 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12325 } 12326 12327 public: 12328 SequenceChecker(Sema &S, const Expr *E, 12329 SmallVectorImpl<const Expr *> &WorkList) 12330 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12331 Visit(E); 12332 // Silence a -Wunused-private-field since WorkList is now unused. 12333 // TODO: Evaluate if it can be used, and if not remove it. 12334 (void)this->WorkList; 12335 } 12336 12337 void VisitStmt(const Stmt *S) { 12338 // Skip all statements which aren't expressions for now. 12339 } 12340 12341 void VisitExpr(const Expr *E) { 12342 // By default, just recurse to evaluated subexpressions. 12343 Base::VisitStmt(E); 12344 } 12345 12346 void VisitCastExpr(const CastExpr *E) { 12347 Object O = Object(); 12348 if (E->getCastKind() == CK_LValueToRValue) 12349 O = getObject(E->getSubExpr(), false); 12350 12351 if (O) 12352 notePreUse(O, E); 12353 VisitExpr(E); 12354 if (O) 12355 notePostUse(O, E); 12356 } 12357 12358 void VisitSequencedExpressions(const Expr *SequencedBefore, 12359 const Expr *SequencedAfter) { 12360 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12361 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12362 SequenceTree::Seq OldRegion = Region; 12363 12364 { 12365 SequencedSubexpression SeqBefore(*this); 12366 Region = BeforeRegion; 12367 Visit(SequencedBefore); 12368 } 12369 12370 Region = AfterRegion; 12371 Visit(SequencedAfter); 12372 12373 Region = OldRegion; 12374 12375 Tree.merge(BeforeRegion); 12376 Tree.merge(AfterRegion); 12377 } 12378 12379 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12380 // C++17 [expr.sub]p1: 12381 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12382 // expression E1 is sequenced before the expression E2. 12383 if (SemaRef.getLangOpts().CPlusPlus17) 12384 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12385 else { 12386 Visit(ASE->getLHS()); 12387 Visit(ASE->getRHS()); 12388 } 12389 } 12390 12391 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12392 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12393 void VisitBinPtrMem(const BinaryOperator *BO) { 12394 // C++17 [expr.mptr.oper]p4: 12395 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12396 // the expression E1 is sequenced before the expression E2. 12397 if (SemaRef.getLangOpts().CPlusPlus17) 12398 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12399 else { 12400 Visit(BO->getLHS()); 12401 Visit(BO->getRHS()); 12402 } 12403 } 12404 12405 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12406 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12407 void VisitBinShlShr(const BinaryOperator *BO) { 12408 // C++17 [expr.shift]p4: 12409 // The expression E1 is sequenced before the expression E2. 12410 if (SemaRef.getLangOpts().CPlusPlus17) 12411 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12412 else { 12413 Visit(BO->getLHS()); 12414 Visit(BO->getRHS()); 12415 } 12416 } 12417 12418 void VisitBinComma(const BinaryOperator *BO) { 12419 // C++11 [expr.comma]p1: 12420 // Every value computation and side effect associated with the left 12421 // expression is sequenced before every value computation and side 12422 // effect associated with the right expression. 12423 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12424 } 12425 12426 void VisitBinAssign(const BinaryOperator *BO) { 12427 SequenceTree::Seq RHSRegion; 12428 SequenceTree::Seq LHSRegion; 12429 if (SemaRef.getLangOpts().CPlusPlus17) { 12430 RHSRegion = Tree.allocate(Region); 12431 LHSRegion = Tree.allocate(Region); 12432 } else { 12433 RHSRegion = Region; 12434 LHSRegion = Region; 12435 } 12436 SequenceTree::Seq OldRegion = Region; 12437 12438 // C++11 [expr.ass]p1: 12439 // [...] the assignment is sequenced after the value computation 12440 // of the right and left operands, [...] 12441 // 12442 // so check it before inspecting the operands and update the 12443 // map afterwards. 12444 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12445 if (O) 12446 notePreMod(O, BO); 12447 12448 if (SemaRef.getLangOpts().CPlusPlus17) { 12449 // C++17 [expr.ass]p1: 12450 // [...] The right operand is sequenced before the left operand. [...] 12451 { 12452 SequencedSubexpression SeqBefore(*this); 12453 Region = RHSRegion; 12454 Visit(BO->getRHS()); 12455 } 12456 12457 Region = LHSRegion; 12458 Visit(BO->getLHS()); 12459 12460 if (O && isa<CompoundAssignOperator>(BO)) 12461 notePostUse(O, BO); 12462 12463 } else { 12464 // C++11 does not specify any sequencing between the LHS and RHS. 12465 Region = LHSRegion; 12466 Visit(BO->getLHS()); 12467 12468 if (O && isa<CompoundAssignOperator>(BO)) 12469 notePostUse(O, BO); 12470 12471 Region = RHSRegion; 12472 Visit(BO->getRHS()); 12473 } 12474 12475 // C++11 [expr.ass]p1: 12476 // the assignment is sequenced [...] before the value computation of the 12477 // assignment expression. 12478 // C11 6.5.16/3 has no such rule. 12479 Region = OldRegion; 12480 if (O) 12481 notePostMod(O, BO, 12482 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12483 : UK_ModAsSideEffect); 12484 if (SemaRef.getLangOpts().CPlusPlus17) { 12485 Tree.merge(RHSRegion); 12486 Tree.merge(LHSRegion); 12487 } 12488 } 12489 12490 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12491 VisitBinAssign(CAO); 12492 } 12493 12494 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12495 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12496 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12497 Object O = getObject(UO->getSubExpr(), true); 12498 if (!O) 12499 return VisitExpr(UO); 12500 12501 notePreMod(O, UO); 12502 Visit(UO->getSubExpr()); 12503 // C++11 [expr.pre.incr]p1: 12504 // the expression ++x is equivalent to x+=1 12505 notePostMod(O, UO, 12506 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12507 : UK_ModAsSideEffect); 12508 } 12509 12510 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12511 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12512 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12513 Object O = getObject(UO->getSubExpr(), true); 12514 if (!O) 12515 return VisitExpr(UO); 12516 12517 notePreMod(O, UO); 12518 Visit(UO->getSubExpr()); 12519 notePostMod(O, UO, UK_ModAsSideEffect); 12520 } 12521 12522 void VisitBinLOr(const BinaryOperator *BO) { 12523 // C++11 [expr.log.or]p2: 12524 // If the second expression is evaluated, every value computation and 12525 // side effect associated with the first expression is sequenced before 12526 // every value computation and side effect associated with the 12527 // second expression. 12528 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12529 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12530 SequenceTree::Seq OldRegion = Region; 12531 12532 EvaluationTracker Eval(*this); 12533 { 12534 SequencedSubexpression Sequenced(*this); 12535 Region = LHSRegion; 12536 Visit(BO->getLHS()); 12537 } 12538 12539 // C++11 [expr.log.or]p1: 12540 // [...] the second operand is not evaluated if the first operand 12541 // evaluates to true. 12542 bool EvalResult = false; 12543 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12544 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 12545 if (ShouldVisitRHS) { 12546 Region = RHSRegion; 12547 Visit(BO->getRHS()); 12548 } 12549 12550 Region = OldRegion; 12551 Tree.merge(LHSRegion); 12552 Tree.merge(RHSRegion); 12553 } 12554 12555 void VisitBinLAnd(const BinaryOperator *BO) { 12556 // C++11 [expr.log.and]p2: 12557 // If the second expression is evaluated, every value computation and 12558 // side effect associated with the first expression is sequenced before 12559 // every value computation and side effect associated with the 12560 // second expression. 12561 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12562 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12563 SequenceTree::Seq OldRegion = Region; 12564 12565 EvaluationTracker Eval(*this); 12566 { 12567 SequencedSubexpression Sequenced(*this); 12568 Region = LHSRegion; 12569 Visit(BO->getLHS()); 12570 } 12571 12572 // C++11 [expr.log.and]p1: 12573 // [...] the second operand is not evaluated if the first operand is false. 12574 bool EvalResult = false; 12575 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12576 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 12577 if (ShouldVisitRHS) { 12578 Region = RHSRegion; 12579 Visit(BO->getRHS()); 12580 } 12581 12582 Region = OldRegion; 12583 Tree.merge(LHSRegion); 12584 Tree.merge(RHSRegion); 12585 } 12586 12587 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 12588 // C++11 [expr.cond]p1: 12589 // [...] Every value computation and side effect associated with the first 12590 // expression is sequenced before every value computation and side effect 12591 // associated with the second or third expression. 12592 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 12593 12594 // No sequencing is specified between the true and false expression. 12595 // However since exactly one of both is going to be evaluated we can 12596 // consider them to be sequenced. This is needed to avoid warning on 12597 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 12598 // both the true and false expressions because we can't evaluate x. 12599 // This will still allow us to detect an expression like (pre C++17) 12600 // "(x ? y += 1 : y += 2) = y". 12601 // 12602 // We don't wrap the visitation of the true and false expression with 12603 // SequencedSubexpression because we don't want to downgrade modifications 12604 // as side effect in the true and false expressions after the visition 12605 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 12606 // not warn between the two "y++", but we should warn between the "y++" 12607 // and the "y". 12608 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 12609 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 12610 SequenceTree::Seq OldRegion = Region; 12611 12612 EvaluationTracker Eval(*this); 12613 { 12614 SequencedSubexpression Sequenced(*this); 12615 Region = ConditionRegion; 12616 Visit(CO->getCond()); 12617 } 12618 12619 // C++11 [expr.cond]p1: 12620 // [...] The first expression is contextually converted to bool (Clause 4). 12621 // It is evaluated and if it is true, the result of the conditional 12622 // expression is the value of the second expression, otherwise that of the 12623 // third expression. Only one of the second and third expressions is 12624 // evaluated. [...] 12625 bool EvalResult = false; 12626 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 12627 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 12628 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 12629 if (ShouldVisitTrueExpr) { 12630 Region = TrueRegion; 12631 Visit(CO->getTrueExpr()); 12632 } 12633 if (ShouldVisitFalseExpr) { 12634 Region = FalseRegion; 12635 Visit(CO->getFalseExpr()); 12636 } 12637 12638 Region = OldRegion; 12639 Tree.merge(ConditionRegion); 12640 Tree.merge(TrueRegion); 12641 Tree.merge(FalseRegion); 12642 } 12643 12644 void VisitCallExpr(const CallExpr *CE) { 12645 // C++11 [intro.execution]p15: 12646 // When calling a function [...], every value computation and side effect 12647 // associated with any argument expression, or with the postfix expression 12648 // designating the called function, is sequenced before execution of every 12649 // expression or statement in the body of the function [and thus before 12650 // the value computation of its result]. 12651 SequencedSubexpression Sequenced(*this); 12652 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), 12653 [&] { Base::VisitCallExpr(CE); }); 12654 12655 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12656 } 12657 12658 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 12659 // This is a call, so all subexpressions are sequenced before the result. 12660 SequencedSubexpression Sequenced(*this); 12661 12662 if (!CCE->isListInitialization()) 12663 return VisitExpr(CCE); 12664 12665 // In C++11, list initializations are sequenced. 12666 SmallVector<SequenceTree::Seq, 32> Elts; 12667 SequenceTree::Seq Parent = Region; 12668 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 12669 E = CCE->arg_end(); 12670 I != E; ++I) { 12671 Region = Tree.allocate(Parent); 12672 Elts.push_back(Region); 12673 Visit(*I); 12674 } 12675 12676 // Forget that the initializers are sequenced. 12677 Region = Parent; 12678 for (unsigned I = 0; I < Elts.size(); ++I) 12679 Tree.merge(Elts[I]); 12680 } 12681 12682 void VisitInitListExpr(const InitListExpr *ILE) { 12683 if (!SemaRef.getLangOpts().CPlusPlus11) 12684 return VisitExpr(ILE); 12685 12686 // In C++11, list initializations are sequenced. 12687 SmallVector<SequenceTree::Seq, 32> Elts; 12688 SequenceTree::Seq Parent = Region; 12689 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12690 const Expr *E = ILE->getInit(I); 12691 if (!E) 12692 continue; 12693 Region = Tree.allocate(Parent); 12694 Elts.push_back(Region); 12695 Visit(E); 12696 } 12697 12698 // Forget that the initializers are sequenced. 12699 Region = Parent; 12700 for (unsigned I = 0; I < Elts.size(); ++I) 12701 Tree.merge(Elts[I]); 12702 } 12703 }; 12704 12705 } // namespace 12706 12707 void Sema::CheckUnsequencedOperations(const Expr *E) { 12708 SmallVector<const Expr *, 8> WorkList; 12709 WorkList.push_back(E); 12710 while (!WorkList.empty()) { 12711 const Expr *Item = WorkList.pop_back_val(); 12712 SequenceChecker(*this, Item, WorkList); 12713 } 12714 } 12715 12716 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12717 bool IsConstexpr) { 12718 llvm::SaveAndRestore<bool> ConstantContext( 12719 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 12720 CheckImplicitConversions(E, CheckLoc); 12721 if (!E->isInstantiationDependent()) 12722 CheckUnsequencedOperations(E); 12723 if (!IsConstexpr && !E->isValueDependent()) 12724 CheckForIntOverflow(E); 12725 DiagnoseMisalignedMembers(); 12726 } 12727 12728 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12729 FieldDecl *BitField, 12730 Expr *Init) { 12731 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12732 } 12733 12734 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12735 SourceLocation Loc) { 12736 if (!PType->isVariablyModifiedType()) 12737 return; 12738 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12739 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12740 return; 12741 } 12742 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12743 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12744 return; 12745 } 12746 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12747 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12748 return; 12749 } 12750 12751 const ArrayType *AT = S.Context.getAsArrayType(PType); 12752 if (!AT) 12753 return; 12754 12755 if (AT->getSizeModifier() != ArrayType::Star) { 12756 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12757 return; 12758 } 12759 12760 S.Diag(Loc, diag::err_array_star_in_function_definition); 12761 } 12762 12763 /// CheckParmsForFunctionDef - Check that the parameters of the given 12764 /// function are appropriate for the definition of a function. This 12765 /// takes care of any checks that cannot be performed on the 12766 /// declaration itself, e.g., that the types of each of the function 12767 /// parameters are complete. 12768 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12769 bool CheckParameterNames) { 12770 bool HasInvalidParm = false; 12771 for (ParmVarDecl *Param : Parameters) { 12772 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12773 // function declarator that is part of a function definition of 12774 // that function shall not have incomplete type. 12775 // 12776 // This is also C++ [dcl.fct]p6. 12777 if (!Param->isInvalidDecl() && 12778 RequireCompleteType(Param->getLocation(), Param->getType(), 12779 diag::err_typecheck_decl_incomplete_type)) { 12780 Param->setInvalidDecl(); 12781 HasInvalidParm = true; 12782 } 12783 12784 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12785 // declaration of each parameter shall include an identifier. 12786 if (CheckParameterNames && 12787 Param->getIdentifier() == nullptr && 12788 !Param->isImplicit() && 12789 !getLangOpts().CPlusPlus) 12790 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12791 12792 // C99 6.7.5.3p12: 12793 // If the function declarator is not part of a definition of that 12794 // function, parameters may have incomplete type and may use the [*] 12795 // notation in their sequences of declarator specifiers to specify 12796 // variable length array types. 12797 QualType PType = Param->getOriginalType(); 12798 // FIXME: This diagnostic should point the '[*]' if source-location 12799 // information is added for it. 12800 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12801 12802 // If the parameter is a c++ class type and it has to be destructed in the 12803 // callee function, declare the destructor so that it can be called by the 12804 // callee function. Do not perform any direct access check on the dtor here. 12805 if (!Param->isInvalidDecl()) { 12806 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12807 if (!ClassDecl->isInvalidDecl() && 12808 !ClassDecl->hasIrrelevantDestructor() && 12809 !ClassDecl->isDependentContext() && 12810 ClassDecl->isParamDestroyedInCallee()) { 12811 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12812 MarkFunctionReferenced(Param->getLocation(), Destructor); 12813 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12814 } 12815 } 12816 } 12817 12818 // Parameters with the pass_object_size attribute only need to be marked 12819 // constant at function definitions. Because we lack information about 12820 // whether we're on a declaration or definition when we're instantiating the 12821 // attribute, we need to check for constness here. 12822 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12823 if (!Param->getType().isConstQualified()) 12824 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12825 << Attr->getSpelling() << 1; 12826 12827 // Check for parameter names shadowing fields from the class. 12828 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 12829 // The owning context for the parameter should be the function, but we 12830 // want to see if this function's declaration context is a record. 12831 DeclContext *DC = Param->getDeclContext(); 12832 if (DC && DC->isFunctionOrMethod()) { 12833 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 12834 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 12835 RD, /*DeclIsField*/ false); 12836 } 12837 } 12838 } 12839 12840 return HasInvalidParm; 12841 } 12842 12843 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12844 /// or MemberExpr. 12845 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12846 ASTContext &Context) { 12847 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12848 return Context.getDeclAlign(DRE->getDecl()); 12849 12850 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12851 return Context.getDeclAlign(ME->getMemberDecl()); 12852 12853 return TypeAlign; 12854 } 12855 12856 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12857 /// pointer cast increases the alignment requirements. 12858 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12859 // This is actually a lot of work to potentially be doing on every 12860 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12861 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12862 return; 12863 12864 // Ignore dependent types. 12865 if (T->isDependentType() || Op->getType()->isDependentType()) 12866 return; 12867 12868 // Require that the destination be a pointer type. 12869 const PointerType *DestPtr = T->getAs<PointerType>(); 12870 if (!DestPtr) return; 12871 12872 // If the destination has alignment 1, we're done. 12873 QualType DestPointee = DestPtr->getPointeeType(); 12874 if (DestPointee->isIncompleteType()) return; 12875 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12876 if (DestAlign.isOne()) return; 12877 12878 // Require that the source be a pointer type. 12879 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12880 if (!SrcPtr) return; 12881 QualType SrcPointee = SrcPtr->getPointeeType(); 12882 12883 // Whitelist casts from cv void*. We already implicitly 12884 // whitelisted casts to cv void*, since they have alignment 1. 12885 // Also whitelist casts involving incomplete types, which implicitly 12886 // includes 'void'. 12887 if (SrcPointee->isIncompleteType()) return; 12888 12889 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12890 12891 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12892 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12893 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12894 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12895 if (UO->getOpcode() == UO_AddrOf) 12896 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12897 } 12898 12899 if (SrcAlign >= DestAlign) return; 12900 12901 Diag(TRange.getBegin(), diag::warn_cast_align) 12902 << Op->getType() << T 12903 << static_cast<unsigned>(SrcAlign.getQuantity()) 12904 << static_cast<unsigned>(DestAlign.getQuantity()) 12905 << TRange << Op->getSourceRange(); 12906 } 12907 12908 /// Check whether this array fits the idiom of a size-one tail padded 12909 /// array member of a struct. 12910 /// 12911 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12912 /// commonly used to emulate flexible arrays in C89 code. 12913 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12914 const NamedDecl *ND) { 12915 if (Size != 1 || !ND) return false; 12916 12917 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12918 if (!FD) return false; 12919 12920 // Don't consider sizes resulting from macro expansions or template argument 12921 // substitution to form C89 tail-padded arrays. 12922 12923 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12924 while (TInfo) { 12925 TypeLoc TL = TInfo->getTypeLoc(); 12926 // Look through typedefs. 12927 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12928 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12929 TInfo = TDL->getTypeSourceInfo(); 12930 continue; 12931 } 12932 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12933 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12934 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12935 return false; 12936 } 12937 break; 12938 } 12939 12940 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12941 if (!RD) return false; 12942 if (RD->isUnion()) return false; 12943 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12944 if (!CRD->isStandardLayout()) return false; 12945 } 12946 12947 // See if this is the last field decl in the record. 12948 const Decl *D = FD; 12949 while ((D = D->getNextDeclInContext())) 12950 if (isa<FieldDecl>(D)) 12951 return false; 12952 return true; 12953 } 12954 12955 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12956 const ArraySubscriptExpr *ASE, 12957 bool AllowOnePastEnd, bool IndexNegated) { 12958 // Already diagnosed by the constant evaluator. 12959 if (isConstantEvaluated()) 12960 return; 12961 12962 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12963 if (IndexExpr->isValueDependent()) 12964 return; 12965 12966 const Type *EffectiveType = 12967 BaseExpr->getType()->getPointeeOrArrayElementType(); 12968 BaseExpr = BaseExpr->IgnoreParenCasts(); 12969 const ConstantArrayType *ArrayTy = 12970 Context.getAsConstantArrayType(BaseExpr->getType()); 12971 12972 if (!ArrayTy) 12973 return; 12974 12975 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 12976 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 12977 return; 12978 12979 Expr::EvalResult Result; 12980 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 12981 return; 12982 12983 llvm::APSInt index = Result.Val.getInt(); 12984 if (IndexNegated) 12985 index = -index; 12986 12987 const NamedDecl *ND = nullptr; 12988 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12989 ND = DRE->getDecl(); 12990 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12991 ND = ME->getMemberDecl(); 12992 12993 if (index.isUnsigned() || !index.isNegative()) { 12994 // It is possible that the type of the base expression after 12995 // IgnoreParenCasts is incomplete, even though the type of the base 12996 // expression before IgnoreParenCasts is complete (see PR39746 for an 12997 // example). In this case we have no information about whether the array 12998 // access exceeds the array bounds. However we can still diagnose an array 12999 // access which precedes the array bounds. 13000 if (BaseType->isIncompleteType()) 13001 return; 13002 13003 llvm::APInt size = ArrayTy->getSize(); 13004 if (!size.isStrictlyPositive()) 13005 return; 13006 13007 if (BaseType != EffectiveType) { 13008 // Make sure we're comparing apples to apples when comparing index to size 13009 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13010 uint64_t array_typesize = Context.getTypeSize(BaseType); 13011 // Handle ptrarith_typesize being zero, such as when casting to void* 13012 if (!ptrarith_typesize) ptrarith_typesize = 1; 13013 if (ptrarith_typesize != array_typesize) { 13014 // There's a cast to a different size type involved 13015 uint64_t ratio = array_typesize / ptrarith_typesize; 13016 // TODO: Be smarter about handling cases where array_typesize is not a 13017 // multiple of ptrarith_typesize 13018 if (ptrarith_typesize * ratio == array_typesize) 13019 size *= llvm::APInt(size.getBitWidth(), ratio); 13020 } 13021 } 13022 13023 if (size.getBitWidth() > index.getBitWidth()) 13024 index = index.zext(size.getBitWidth()); 13025 else if (size.getBitWidth() < index.getBitWidth()) 13026 size = size.zext(index.getBitWidth()); 13027 13028 // For array subscripting the index must be less than size, but for pointer 13029 // arithmetic also allow the index (offset) to be equal to size since 13030 // computing the next address after the end of the array is legal and 13031 // commonly done e.g. in C++ iterators and range-based for loops. 13032 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13033 return; 13034 13035 // Also don't warn for arrays of size 1 which are members of some 13036 // structure. These are often used to approximate flexible arrays in C89 13037 // code. 13038 if (IsTailPaddedMemberArray(*this, size, ND)) 13039 return; 13040 13041 // Suppress the warning if the subscript expression (as identified by the 13042 // ']' location) and the index expression are both from macro expansions 13043 // within a system header. 13044 if (ASE) { 13045 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13046 ASE->getRBracketLoc()); 13047 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13048 SourceLocation IndexLoc = 13049 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13050 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13051 return; 13052 } 13053 } 13054 13055 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13056 if (ASE) 13057 DiagID = diag::warn_array_index_exceeds_bounds; 13058 13059 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13060 PDiag(DiagID) << index.toString(10, true) 13061 << size.toString(10, true) 13062 << (unsigned)size.getLimitedValue(~0U) 13063 << IndexExpr->getSourceRange()); 13064 } else { 13065 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13066 if (!ASE) { 13067 DiagID = diag::warn_ptr_arith_precedes_bounds; 13068 if (index.isNegative()) index = -index; 13069 } 13070 13071 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13072 PDiag(DiagID) << index.toString(10, true) 13073 << IndexExpr->getSourceRange()); 13074 } 13075 13076 if (!ND) { 13077 // Try harder to find a NamedDecl to point at in the note. 13078 while (const ArraySubscriptExpr *ASE = 13079 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13080 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13081 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13082 ND = DRE->getDecl(); 13083 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13084 ND = ME->getMemberDecl(); 13085 } 13086 13087 if (ND) 13088 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13089 PDiag(diag::note_array_declared_here) 13090 << ND->getDeclName()); 13091 } 13092 13093 void Sema::CheckArrayAccess(const Expr *expr) { 13094 int AllowOnePastEnd = 0; 13095 while (expr) { 13096 expr = expr->IgnoreParenImpCasts(); 13097 switch (expr->getStmtClass()) { 13098 case Stmt::ArraySubscriptExprClass: { 13099 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13100 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13101 AllowOnePastEnd > 0); 13102 expr = ASE->getBase(); 13103 break; 13104 } 13105 case Stmt::MemberExprClass: { 13106 expr = cast<MemberExpr>(expr)->getBase(); 13107 break; 13108 } 13109 case Stmt::OMPArraySectionExprClass: { 13110 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13111 if (ASE->getLowerBound()) 13112 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13113 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13114 return; 13115 } 13116 case Stmt::UnaryOperatorClass: { 13117 // Only unwrap the * and & unary operators 13118 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13119 expr = UO->getSubExpr(); 13120 switch (UO->getOpcode()) { 13121 case UO_AddrOf: 13122 AllowOnePastEnd++; 13123 break; 13124 case UO_Deref: 13125 AllowOnePastEnd--; 13126 break; 13127 default: 13128 return; 13129 } 13130 break; 13131 } 13132 case Stmt::ConditionalOperatorClass: { 13133 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13134 if (const Expr *lhs = cond->getLHS()) 13135 CheckArrayAccess(lhs); 13136 if (const Expr *rhs = cond->getRHS()) 13137 CheckArrayAccess(rhs); 13138 return; 13139 } 13140 case Stmt::CXXOperatorCallExprClass: { 13141 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13142 for (const auto *Arg : OCE->arguments()) 13143 CheckArrayAccess(Arg); 13144 return; 13145 } 13146 default: 13147 return; 13148 } 13149 } 13150 } 13151 13152 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13153 13154 namespace { 13155 13156 struct RetainCycleOwner { 13157 VarDecl *Variable = nullptr; 13158 SourceRange Range; 13159 SourceLocation Loc; 13160 bool Indirect = false; 13161 13162 RetainCycleOwner() = default; 13163 13164 void setLocsFrom(Expr *e) { 13165 Loc = e->getExprLoc(); 13166 Range = e->getSourceRange(); 13167 } 13168 }; 13169 13170 } // namespace 13171 13172 /// Consider whether capturing the given variable can possibly lead to 13173 /// a retain cycle. 13174 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13175 // In ARC, it's captured strongly iff the variable has __strong 13176 // lifetime. In MRR, it's captured strongly if the variable is 13177 // __block and has an appropriate type. 13178 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13179 return false; 13180 13181 owner.Variable = var; 13182 if (ref) 13183 owner.setLocsFrom(ref); 13184 return true; 13185 } 13186 13187 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13188 while (true) { 13189 e = e->IgnoreParens(); 13190 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13191 switch (cast->getCastKind()) { 13192 case CK_BitCast: 13193 case CK_LValueBitCast: 13194 case CK_LValueToRValue: 13195 case CK_ARCReclaimReturnedObject: 13196 e = cast->getSubExpr(); 13197 continue; 13198 13199 default: 13200 return false; 13201 } 13202 } 13203 13204 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13205 ObjCIvarDecl *ivar = ref->getDecl(); 13206 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13207 return false; 13208 13209 // Try to find a retain cycle in the base. 13210 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13211 return false; 13212 13213 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13214 owner.Indirect = true; 13215 return true; 13216 } 13217 13218 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13219 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13220 if (!var) return false; 13221 return considerVariable(var, ref, owner); 13222 } 13223 13224 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13225 if (member->isArrow()) return false; 13226 13227 // Don't count this as an indirect ownership. 13228 e = member->getBase(); 13229 continue; 13230 } 13231 13232 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13233 // Only pay attention to pseudo-objects on property references. 13234 ObjCPropertyRefExpr *pre 13235 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13236 ->IgnoreParens()); 13237 if (!pre) return false; 13238 if (pre->isImplicitProperty()) return false; 13239 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13240 if (!property->isRetaining() && 13241 !(property->getPropertyIvarDecl() && 13242 property->getPropertyIvarDecl()->getType() 13243 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13244 return false; 13245 13246 owner.Indirect = true; 13247 if (pre->isSuperReceiver()) { 13248 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13249 if (!owner.Variable) 13250 return false; 13251 owner.Loc = pre->getLocation(); 13252 owner.Range = pre->getSourceRange(); 13253 return true; 13254 } 13255 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13256 ->getSourceExpr()); 13257 continue; 13258 } 13259 13260 // Array ivars? 13261 13262 return false; 13263 } 13264 } 13265 13266 namespace { 13267 13268 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13269 ASTContext &Context; 13270 VarDecl *Variable; 13271 Expr *Capturer = nullptr; 13272 bool VarWillBeReased = false; 13273 13274 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13275 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13276 Context(Context), Variable(variable) {} 13277 13278 void VisitDeclRefExpr(DeclRefExpr *ref) { 13279 if (ref->getDecl() == Variable && !Capturer) 13280 Capturer = ref; 13281 } 13282 13283 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13284 if (Capturer) return; 13285 Visit(ref->getBase()); 13286 if (Capturer && ref->isFreeIvar()) 13287 Capturer = ref; 13288 } 13289 13290 void VisitBlockExpr(BlockExpr *block) { 13291 // Look inside nested blocks 13292 if (block->getBlockDecl()->capturesVariable(Variable)) 13293 Visit(block->getBlockDecl()->getBody()); 13294 } 13295 13296 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13297 if (Capturer) return; 13298 if (OVE->getSourceExpr()) 13299 Visit(OVE->getSourceExpr()); 13300 } 13301 13302 void VisitBinaryOperator(BinaryOperator *BinOp) { 13303 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13304 return; 13305 Expr *LHS = BinOp->getLHS(); 13306 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13307 if (DRE->getDecl() != Variable) 13308 return; 13309 if (Expr *RHS = BinOp->getRHS()) { 13310 RHS = RHS->IgnoreParenCasts(); 13311 llvm::APSInt Value; 13312 VarWillBeReased = 13313 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13314 } 13315 } 13316 } 13317 }; 13318 13319 } // namespace 13320 13321 /// Check whether the given argument is a block which captures a 13322 /// variable. 13323 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13324 assert(owner.Variable && owner.Loc.isValid()); 13325 13326 e = e->IgnoreParenCasts(); 13327 13328 // Look through [^{...} copy] and Block_copy(^{...}). 13329 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13330 Selector Cmd = ME->getSelector(); 13331 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13332 e = ME->getInstanceReceiver(); 13333 if (!e) 13334 return nullptr; 13335 e = e->IgnoreParenCasts(); 13336 } 13337 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13338 if (CE->getNumArgs() == 1) { 13339 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13340 if (Fn) { 13341 const IdentifierInfo *FnI = Fn->getIdentifier(); 13342 if (FnI && FnI->isStr("_Block_copy")) { 13343 e = CE->getArg(0)->IgnoreParenCasts(); 13344 } 13345 } 13346 } 13347 } 13348 13349 BlockExpr *block = dyn_cast<BlockExpr>(e); 13350 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13351 return nullptr; 13352 13353 FindCaptureVisitor visitor(S.Context, owner.Variable); 13354 visitor.Visit(block->getBlockDecl()->getBody()); 13355 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13356 } 13357 13358 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13359 RetainCycleOwner &owner) { 13360 assert(capturer); 13361 assert(owner.Variable && owner.Loc.isValid()); 13362 13363 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13364 << owner.Variable << capturer->getSourceRange(); 13365 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13366 << owner.Indirect << owner.Range; 13367 } 13368 13369 /// Check for a keyword selector that starts with the word 'add' or 13370 /// 'set'. 13371 static bool isSetterLikeSelector(Selector sel) { 13372 if (sel.isUnarySelector()) return false; 13373 13374 StringRef str = sel.getNameForSlot(0); 13375 while (!str.empty() && str.front() == '_') str = str.substr(1); 13376 if (str.startswith("set")) 13377 str = str.substr(3); 13378 else if (str.startswith("add")) { 13379 // Specially whitelist 'addOperationWithBlock:'. 13380 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13381 return false; 13382 str = str.substr(3); 13383 } 13384 else 13385 return false; 13386 13387 if (str.empty()) return true; 13388 return !isLowercase(str.front()); 13389 } 13390 13391 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13392 ObjCMessageExpr *Message) { 13393 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13394 Message->getReceiverInterface(), 13395 NSAPI::ClassId_NSMutableArray); 13396 if (!IsMutableArray) { 13397 return None; 13398 } 13399 13400 Selector Sel = Message->getSelector(); 13401 13402 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13403 S.NSAPIObj->getNSArrayMethodKind(Sel); 13404 if (!MKOpt) { 13405 return None; 13406 } 13407 13408 NSAPI::NSArrayMethodKind MK = *MKOpt; 13409 13410 switch (MK) { 13411 case NSAPI::NSMutableArr_addObject: 13412 case NSAPI::NSMutableArr_insertObjectAtIndex: 13413 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13414 return 0; 13415 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13416 return 1; 13417 13418 default: 13419 return None; 13420 } 13421 13422 return None; 13423 } 13424 13425 static 13426 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13427 ObjCMessageExpr *Message) { 13428 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13429 Message->getReceiverInterface(), 13430 NSAPI::ClassId_NSMutableDictionary); 13431 if (!IsMutableDictionary) { 13432 return None; 13433 } 13434 13435 Selector Sel = Message->getSelector(); 13436 13437 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13438 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13439 if (!MKOpt) { 13440 return None; 13441 } 13442 13443 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13444 13445 switch (MK) { 13446 case NSAPI::NSMutableDict_setObjectForKey: 13447 case NSAPI::NSMutableDict_setValueForKey: 13448 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13449 return 0; 13450 13451 default: 13452 return None; 13453 } 13454 13455 return None; 13456 } 13457 13458 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13459 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13460 Message->getReceiverInterface(), 13461 NSAPI::ClassId_NSMutableSet); 13462 13463 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13464 Message->getReceiverInterface(), 13465 NSAPI::ClassId_NSMutableOrderedSet); 13466 if (!IsMutableSet && !IsMutableOrderedSet) { 13467 return None; 13468 } 13469 13470 Selector Sel = Message->getSelector(); 13471 13472 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13473 if (!MKOpt) { 13474 return None; 13475 } 13476 13477 NSAPI::NSSetMethodKind MK = *MKOpt; 13478 13479 switch (MK) { 13480 case NSAPI::NSMutableSet_addObject: 13481 case NSAPI::NSOrderedSet_setObjectAtIndex: 13482 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13483 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13484 return 0; 13485 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13486 return 1; 13487 } 13488 13489 return None; 13490 } 13491 13492 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13493 if (!Message->isInstanceMessage()) { 13494 return; 13495 } 13496 13497 Optional<int> ArgOpt; 13498 13499 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13500 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13501 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13502 return; 13503 } 13504 13505 int ArgIndex = *ArgOpt; 13506 13507 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13508 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13509 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13510 } 13511 13512 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13513 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13514 if (ArgRE->isObjCSelfExpr()) { 13515 Diag(Message->getSourceRange().getBegin(), 13516 diag::warn_objc_circular_container) 13517 << ArgRE->getDecl() << StringRef("'super'"); 13518 } 13519 } 13520 } else { 13521 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13522 13523 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13524 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13525 } 13526 13527 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13528 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13529 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13530 ValueDecl *Decl = ReceiverRE->getDecl(); 13531 Diag(Message->getSourceRange().getBegin(), 13532 diag::warn_objc_circular_container) 13533 << Decl << Decl; 13534 if (!ArgRE->isObjCSelfExpr()) { 13535 Diag(Decl->getLocation(), 13536 diag::note_objc_circular_container_declared_here) 13537 << Decl; 13538 } 13539 } 13540 } 13541 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13542 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13543 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13544 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13545 Diag(Message->getSourceRange().getBegin(), 13546 diag::warn_objc_circular_container) 13547 << Decl << Decl; 13548 Diag(Decl->getLocation(), 13549 diag::note_objc_circular_container_declared_here) 13550 << Decl; 13551 } 13552 } 13553 } 13554 } 13555 } 13556 13557 /// Check a message send to see if it's likely to cause a retain cycle. 13558 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13559 // Only check instance methods whose selector looks like a setter. 13560 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13561 return; 13562 13563 // Try to find a variable that the receiver is strongly owned by. 13564 RetainCycleOwner owner; 13565 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13566 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13567 return; 13568 } else { 13569 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13570 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13571 owner.Loc = msg->getSuperLoc(); 13572 owner.Range = msg->getSuperLoc(); 13573 } 13574 13575 // Check whether the receiver is captured by any of the arguments. 13576 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13577 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13578 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13579 // noescape blocks should not be retained by the method. 13580 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13581 continue; 13582 return diagnoseRetainCycle(*this, capturer, owner); 13583 } 13584 } 13585 } 13586 13587 /// Check a property assign to see if it's likely to cause a retain cycle. 13588 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13589 RetainCycleOwner owner; 13590 if (!findRetainCycleOwner(*this, receiver, owner)) 13591 return; 13592 13593 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13594 diagnoseRetainCycle(*this, capturer, owner); 13595 } 13596 13597 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13598 RetainCycleOwner Owner; 13599 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13600 return; 13601 13602 // Because we don't have an expression for the variable, we have to set the 13603 // location explicitly here. 13604 Owner.Loc = Var->getLocation(); 13605 Owner.Range = Var->getSourceRange(); 13606 13607 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13608 diagnoseRetainCycle(*this, Capturer, Owner); 13609 } 13610 13611 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13612 Expr *RHS, bool isProperty) { 13613 // Check if RHS is an Objective-C object literal, which also can get 13614 // immediately zapped in a weak reference. Note that we explicitly 13615 // allow ObjCStringLiterals, since those are designed to never really die. 13616 RHS = RHS->IgnoreParenImpCasts(); 13617 13618 // This enum needs to match with the 'select' in 13619 // warn_objc_arc_literal_assign (off-by-1). 13620 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13621 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13622 return false; 13623 13624 S.Diag(Loc, diag::warn_arc_literal_assign) 13625 << (unsigned) Kind 13626 << (isProperty ? 0 : 1) 13627 << RHS->getSourceRange(); 13628 13629 return true; 13630 } 13631 13632 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13633 Qualifiers::ObjCLifetime LT, 13634 Expr *RHS, bool isProperty) { 13635 // Strip off any implicit cast added to get to the one ARC-specific. 13636 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13637 if (cast->getCastKind() == CK_ARCConsumeObject) { 13638 S.Diag(Loc, diag::warn_arc_retained_assign) 13639 << (LT == Qualifiers::OCL_ExplicitNone) 13640 << (isProperty ? 0 : 1) 13641 << RHS->getSourceRange(); 13642 return true; 13643 } 13644 RHS = cast->getSubExpr(); 13645 } 13646 13647 if (LT == Qualifiers::OCL_Weak && 13648 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13649 return true; 13650 13651 return false; 13652 } 13653 13654 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13655 QualType LHS, Expr *RHS) { 13656 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13657 13658 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13659 return false; 13660 13661 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13662 return true; 13663 13664 return false; 13665 } 13666 13667 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13668 Expr *LHS, Expr *RHS) { 13669 QualType LHSType; 13670 // PropertyRef on LHS type need be directly obtained from 13671 // its declaration as it has a PseudoType. 13672 ObjCPropertyRefExpr *PRE 13673 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13674 if (PRE && !PRE->isImplicitProperty()) { 13675 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13676 if (PD) 13677 LHSType = PD->getType(); 13678 } 13679 13680 if (LHSType.isNull()) 13681 LHSType = LHS->getType(); 13682 13683 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13684 13685 if (LT == Qualifiers::OCL_Weak) { 13686 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13687 getCurFunction()->markSafeWeakUse(LHS); 13688 } 13689 13690 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13691 return; 13692 13693 // FIXME. Check for other life times. 13694 if (LT != Qualifiers::OCL_None) 13695 return; 13696 13697 if (PRE) { 13698 if (PRE->isImplicitProperty()) 13699 return; 13700 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13701 if (!PD) 13702 return; 13703 13704 unsigned Attributes = PD->getPropertyAttributes(); 13705 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13706 // when 'assign' attribute was not explicitly specified 13707 // by user, ignore it and rely on property type itself 13708 // for lifetime info. 13709 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13710 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13711 LHSType->isObjCRetainableType()) 13712 return; 13713 13714 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13715 if (cast->getCastKind() == CK_ARCConsumeObject) { 13716 Diag(Loc, diag::warn_arc_retained_property_assign) 13717 << RHS->getSourceRange(); 13718 return; 13719 } 13720 RHS = cast->getSubExpr(); 13721 } 13722 } 13723 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13724 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13725 return; 13726 } 13727 } 13728 } 13729 13730 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13731 13732 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13733 SourceLocation StmtLoc, 13734 const NullStmt *Body) { 13735 // Do not warn if the body is a macro that expands to nothing, e.g: 13736 // 13737 // #define CALL(x) 13738 // if (condition) 13739 // CALL(0); 13740 if (Body->hasLeadingEmptyMacro()) 13741 return false; 13742 13743 // Get line numbers of statement and body. 13744 bool StmtLineInvalid; 13745 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13746 &StmtLineInvalid); 13747 if (StmtLineInvalid) 13748 return false; 13749 13750 bool BodyLineInvalid; 13751 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13752 &BodyLineInvalid); 13753 if (BodyLineInvalid) 13754 return false; 13755 13756 // Warn if null statement and body are on the same line. 13757 if (StmtLine != BodyLine) 13758 return false; 13759 13760 return true; 13761 } 13762 13763 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13764 const Stmt *Body, 13765 unsigned DiagID) { 13766 // Since this is a syntactic check, don't emit diagnostic for template 13767 // instantiations, this just adds noise. 13768 if (CurrentInstantiationScope) 13769 return; 13770 13771 // The body should be a null statement. 13772 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13773 if (!NBody) 13774 return; 13775 13776 // Do the usual checks. 13777 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13778 return; 13779 13780 Diag(NBody->getSemiLoc(), DiagID); 13781 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13782 } 13783 13784 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13785 const Stmt *PossibleBody) { 13786 assert(!CurrentInstantiationScope); // Ensured by caller 13787 13788 SourceLocation StmtLoc; 13789 const Stmt *Body; 13790 unsigned DiagID; 13791 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13792 StmtLoc = FS->getRParenLoc(); 13793 Body = FS->getBody(); 13794 DiagID = diag::warn_empty_for_body; 13795 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13796 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13797 Body = WS->getBody(); 13798 DiagID = diag::warn_empty_while_body; 13799 } else 13800 return; // Neither `for' nor `while'. 13801 13802 // The body should be a null statement. 13803 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13804 if (!NBody) 13805 return; 13806 13807 // Skip expensive checks if diagnostic is disabled. 13808 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13809 return; 13810 13811 // Do the usual checks. 13812 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13813 return; 13814 13815 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13816 // noise level low, emit diagnostics only if for/while is followed by a 13817 // CompoundStmt, e.g.: 13818 // for (int i = 0; i < n; i++); 13819 // { 13820 // a(i); 13821 // } 13822 // or if for/while is followed by a statement with more indentation 13823 // than for/while itself: 13824 // for (int i = 0; i < n; i++); 13825 // a(i); 13826 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13827 if (!ProbableTypo) { 13828 bool BodyColInvalid; 13829 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13830 PossibleBody->getBeginLoc(), &BodyColInvalid); 13831 if (BodyColInvalid) 13832 return; 13833 13834 bool StmtColInvalid; 13835 unsigned StmtCol = 13836 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13837 if (StmtColInvalid) 13838 return; 13839 13840 if (BodyCol > StmtCol) 13841 ProbableTypo = true; 13842 } 13843 13844 if (ProbableTypo) { 13845 Diag(NBody->getSemiLoc(), DiagID); 13846 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13847 } 13848 } 13849 13850 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13851 13852 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13853 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13854 SourceLocation OpLoc) { 13855 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13856 return; 13857 13858 if (inTemplateInstantiation()) 13859 return; 13860 13861 // Strip parens and casts away. 13862 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13863 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13864 13865 // Check for a call expression 13866 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13867 if (!CE || CE->getNumArgs() != 1) 13868 return; 13869 13870 // Check for a call to std::move 13871 if (!CE->isCallToStdMove()) 13872 return; 13873 13874 // Get argument from std::move 13875 RHSExpr = CE->getArg(0); 13876 13877 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13878 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13879 13880 // Two DeclRefExpr's, check that the decls are the same. 13881 if (LHSDeclRef && RHSDeclRef) { 13882 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13883 return; 13884 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13885 RHSDeclRef->getDecl()->getCanonicalDecl()) 13886 return; 13887 13888 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13889 << LHSExpr->getSourceRange() 13890 << RHSExpr->getSourceRange(); 13891 return; 13892 } 13893 13894 // Member variables require a different approach to check for self moves. 13895 // MemberExpr's are the same if every nested MemberExpr refers to the same 13896 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13897 // the base Expr's are CXXThisExpr's. 13898 const Expr *LHSBase = LHSExpr; 13899 const Expr *RHSBase = RHSExpr; 13900 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13901 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13902 if (!LHSME || !RHSME) 13903 return; 13904 13905 while (LHSME && RHSME) { 13906 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13907 RHSME->getMemberDecl()->getCanonicalDecl()) 13908 return; 13909 13910 LHSBase = LHSME->getBase(); 13911 RHSBase = RHSME->getBase(); 13912 LHSME = dyn_cast<MemberExpr>(LHSBase); 13913 RHSME = dyn_cast<MemberExpr>(RHSBase); 13914 } 13915 13916 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13917 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13918 if (LHSDeclRef && RHSDeclRef) { 13919 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13920 return; 13921 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13922 RHSDeclRef->getDecl()->getCanonicalDecl()) 13923 return; 13924 13925 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13926 << LHSExpr->getSourceRange() 13927 << RHSExpr->getSourceRange(); 13928 return; 13929 } 13930 13931 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13932 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13933 << LHSExpr->getSourceRange() 13934 << RHSExpr->getSourceRange(); 13935 } 13936 13937 //===--- Layout compatibility ----------------------------------------------// 13938 13939 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13940 13941 /// Check if two enumeration types are layout-compatible. 13942 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13943 // C++11 [dcl.enum] p8: 13944 // Two enumeration types are layout-compatible if they have the same 13945 // underlying type. 13946 return ED1->isComplete() && ED2->isComplete() && 13947 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13948 } 13949 13950 /// Check if two fields are layout-compatible. 13951 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13952 FieldDecl *Field2) { 13953 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13954 return false; 13955 13956 if (Field1->isBitField() != Field2->isBitField()) 13957 return false; 13958 13959 if (Field1->isBitField()) { 13960 // Make sure that the bit-fields are the same length. 13961 unsigned Bits1 = Field1->getBitWidthValue(C); 13962 unsigned Bits2 = Field2->getBitWidthValue(C); 13963 13964 if (Bits1 != Bits2) 13965 return false; 13966 } 13967 13968 return true; 13969 } 13970 13971 /// Check if two standard-layout structs are layout-compatible. 13972 /// (C++11 [class.mem] p17) 13973 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13974 RecordDecl *RD2) { 13975 // If both records are C++ classes, check that base classes match. 13976 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13977 // If one of records is a CXXRecordDecl we are in C++ mode, 13978 // thus the other one is a CXXRecordDecl, too. 13979 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13980 // Check number of base classes. 13981 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13982 return false; 13983 13984 // Check the base classes. 13985 for (CXXRecordDecl::base_class_const_iterator 13986 Base1 = D1CXX->bases_begin(), 13987 BaseEnd1 = D1CXX->bases_end(), 13988 Base2 = D2CXX->bases_begin(); 13989 Base1 != BaseEnd1; 13990 ++Base1, ++Base2) { 13991 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13992 return false; 13993 } 13994 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13995 // If only RD2 is a C++ class, it should have zero base classes. 13996 if (D2CXX->getNumBases() > 0) 13997 return false; 13998 } 13999 14000 // Check the fields. 14001 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14002 Field2End = RD2->field_end(), 14003 Field1 = RD1->field_begin(), 14004 Field1End = RD1->field_end(); 14005 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14006 if (!isLayoutCompatible(C, *Field1, *Field2)) 14007 return false; 14008 } 14009 if (Field1 != Field1End || Field2 != Field2End) 14010 return false; 14011 14012 return true; 14013 } 14014 14015 /// Check if two standard-layout unions are layout-compatible. 14016 /// (C++11 [class.mem] p18) 14017 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14018 RecordDecl *RD2) { 14019 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14020 for (auto *Field2 : RD2->fields()) 14021 UnmatchedFields.insert(Field2); 14022 14023 for (auto *Field1 : RD1->fields()) { 14024 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14025 I = UnmatchedFields.begin(), 14026 E = UnmatchedFields.end(); 14027 14028 for ( ; I != E; ++I) { 14029 if (isLayoutCompatible(C, Field1, *I)) { 14030 bool Result = UnmatchedFields.erase(*I); 14031 (void) Result; 14032 assert(Result); 14033 break; 14034 } 14035 } 14036 if (I == E) 14037 return false; 14038 } 14039 14040 return UnmatchedFields.empty(); 14041 } 14042 14043 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14044 RecordDecl *RD2) { 14045 if (RD1->isUnion() != RD2->isUnion()) 14046 return false; 14047 14048 if (RD1->isUnion()) 14049 return isLayoutCompatibleUnion(C, RD1, RD2); 14050 else 14051 return isLayoutCompatibleStruct(C, RD1, RD2); 14052 } 14053 14054 /// Check if two types are layout-compatible in C++11 sense. 14055 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14056 if (T1.isNull() || T2.isNull()) 14057 return false; 14058 14059 // C++11 [basic.types] p11: 14060 // If two types T1 and T2 are the same type, then T1 and T2 are 14061 // layout-compatible types. 14062 if (C.hasSameType(T1, T2)) 14063 return true; 14064 14065 T1 = T1.getCanonicalType().getUnqualifiedType(); 14066 T2 = T2.getCanonicalType().getUnqualifiedType(); 14067 14068 const Type::TypeClass TC1 = T1->getTypeClass(); 14069 const Type::TypeClass TC2 = T2->getTypeClass(); 14070 14071 if (TC1 != TC2) 14072 return false; 14073 14074 if (TC1 == Type::Enum) { 14075 return isLayoutCompatible(C, 14076 cast<EnumType>(T1)->getDecl(), 14077 cast<EnumType>(T2)->getDecl()); 14078 } else if (TC1 == Type::Record) { 14079 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14080 return false; 14081 14082 return isLayoutCompatible(C, 14083 cast<RecordType>(T1)->getDecl(), 14084 cast<RecordType>(T2)->getDecl()); 14085 } 14086 14087 return false; 14088 } 14089 14090 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14091 14092 /// Given a type tag expression find the type tag itself. 14093 /// 14094 /// \param TypeExpr Type tag expression, as it appears in user's code. 14095 /// 14096 /// \param VD Declaration of an identifier that appears in a type tag. 14097 /// 14098 /// \param MagicValue Type tag magic value. 14099 /// 14100 /// \param isConstantEvaluated wether the evalaution should be performed in 14101 14102 /// constant context. 14103 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14104 const ValueDecl **VD, uint64_t *MagicValue, 14105 bool isConstantEvaluated) { 14106 while(true) { 14107 if (!TypeExpr) 14108 return false; 14109 14110 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14111 14112 switch (TypeExpr->getStmtClass()) { 14113 case Stmt::UnaryOperatorClass: { 14114 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14115 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14116 TypeExpr = UO->getSubExpr(); 14117 continue; 14118 } 14119 return false; 14120 } 14121 14122 case Stmt::DeclRefExprClass: { 14123 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14124 *VD = DRE->getDecl(); 14125 return true; 14126 } 14127 14128 case Stmt::IntegerLiteralClass: { 14129 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14130 llvm::APInt MagicValueAPInt = IL->getValue(); 14131 if (MagicValueAPInt.getActiveBits() <= 64) { 14132 *MagicValue = MagicValueAPInt.getZExtValue(); 14133 return true; 14134 } else 14135 return false; 14136 } 14137 14138 case Stmt::BinaryConditionalOperatorClass: 14139 case Stmt::ConditionalOperatorClass: { 14140 const AbstractConditionalOperator *ACO = 14141 cast<AbstractConditionalOperator>(TypeExpr); 14142 bool Result; 14143 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14144 isConstantEvaluated)) { 14145 if (Result) 14146 TypeExpr = ACO->getTrueExpr(); 14147 else 14148 TypeExpr = ACO->getFalseExpr(); 14149 continue; 14150 } 14151 return false; 14152 } 14153 14154 case Stmt::BinaryOperatorClass: { 14155 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14156 if (BO->getOpcode() == BO_Comma) { 14157 TypeExpr = BO->getRHS(); 14158 continue; 14159 } 14160 return false; 14161 } 14162 14163 default: 14164 return false; 14165 } 14166 } 14167 } 14168 14169 /// Retrieve the C type corresponding to type tag TypeExpr. 14170 /// 14171 /// \param TypeExpr Expression that specifies a type tag. 14172 /// 14173 /// \param MagicValues Registered magic values. 14174 /// 14175 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14176 /// kind. 14177 /// 14178 /// \param TypeInfo Information about the corresponding C type. 14179 /// 14180 /// \param isConstantEvaluated wether the evalaution should be performed in 14181 /// constant context. 14182 /// 14183 /// \returns true if the corresponding C type was found. 14184 static bool GetMatchingCType( 14185 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14186 const ASTContext &Ctx, 14187 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14188 *MagicValues, 14189 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14190 bool isConstantEvaluated) { 14191 FoundWrongKind = false; 14192 14193 // Variable declaration that has type_tag_for_datatype attribute. 14194 const ValueDecl *VD = nullptr; 14195 14196 uint64_t MagicValue; 14197 14198 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14199 return false; 14200 14201 if (VD) { 14202 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14203 if (I->getArgumentKind() != ArgumentKind) { 14204 FoundWrongKind = true; 14205 return false; 14206 } 14207 TypeInfo.Type = I->getMatchingCType(); 14208 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14209 TypeInfo.MustBeNull = I->getMustBeNull(); 14210 return true; 14211 } 14212 return false; 14213 } 14214 14215 if (!MagicValues) 14216 return false; 14217 14218 llvm::DenseMap<Sema::TypeTagMagicValue, 14219 Sema::TypeTagData>::const_iterator I = 14220 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14221 if (I == MagicValues->end()) 14222 return false; 14223 14224 TypeInfo = I->second; 14225 return true; 14226 } 14227 14228 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14229 uint64_t MagicValue, QualType Type, 14230 bool LayoutCompatible, 14231 bool MustBeNull) { 14232 if (!TypeTagForDatatypeMagicValues) 14233 TypeTagForDatatypeMagicValues.reset( 14234 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14235 14236 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14237 (*TypeTagForDatatypeMagicValues)[Magic] = 14238 TypeTagData(Type, LayoutCompatible, MustBeNull); 14239 } 14240 14241 static bool IsSameCharType(QualType T1, QualType T2) { 14242 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14243 if (!BT1) 14244 return false; 14245 14246 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14247 if (!BT2) 14248 return false; 14249 14250 BuiltinType::Kind T1Kind = BT1->getKind(); 14251 BuiltinType::Kind T2Kind = BT2->getKind(); 14252 14253 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14254 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14255 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14256 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14257 } 14258 14259 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14260 const ArrayRef<const Expr *> ExprArgs, 14261 SourceLocation CallSiteLoc) { 14262 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14263 bool IsPointerAttr = Attr->getIsPointer(); 14264 14265 // Retrieve the argument representing the 'type_tag'. 14266 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14267 if (TypeTagIdxAST >= ExprArgs.size()) { 14268 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14269 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14270 return; 14271 } 14272 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14273 bool FoundWrongKind; 14274 TypeTagData TypeInfo; 14275 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14276 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14277 TypeInfo, isConstantEvaluated())) { 14278 if (FoundWrongKind) 14279 Diag(TypeTagExpr->getExprLoc(), 14280 diag::warn_type_tag_for_datatype_wrong_kind) 14281 << TypeTagExpr->getSourceRange(); 14282 return; 14283 } 14284 14285 // Retrieve the argument representing the 'arg_idx'. 14286 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14287 if (ArgumentIdxAST >= ExprArgs.size()) { 14288 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14289 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14290 return; 14291 } 14292 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14293 if (IsPointerAttr) { 14294 // Skip implicit cast of pointer to `void *' (as a function argument). 14295 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14296 if (ICE->getType()->isVoidPointerType() && 14297 ICE->getCastKind() == CK_BitCast) 14298 ArgumentExpr = ICE->getSubExpr(); 14299 } 14300 QualType ArgumentType = ArgumentExpr->getType(); 14301 14302 // Passing a `void*' pointer shouldn't trigger a warning. 14303 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14304 return; 14305 14306 if (TypeInfo.MustBeNull) { 14307 // Type tag with matching void type requires a null pointer. 14308 if (!ArgumentExpr->isNullPointerConstant(Context, 14309 Expr::NPC_ValueDependentIsNotNull)) { 14310 Diag(ArgumentExpr->getExprLoc(), 14311 diag::warn_type_safety_null_pointer_required) 14312 << ArgumentKind->getName() 14313 << ArgumentExpr->getSourceRange() 14314 << TypeTagExpr->getSourceRange(); 14315 } 14316 return; 14317 } 14318 14319 QualType RequiredType = TypeInfo.Type; 14320 if (IsPointerAttr) 14321 RequiredType = Context.getPointerType(RequiredType); 14322 14323 bool mismatch = false; 14324 if (!TypeInfo.LayoutCompatible) { 14325 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14326 14327 // C++11 [basic.fundamental] p1: 14328 // Plain char, signed char, and unsigned char are three distinct types. 14329 // 14330 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14331 // char' depending on the current char signedness mode. 14332 if (mismatch) 14333 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14334 RequiredType->getPointeeType())) || 14335 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14336 mismatch = false; 14337 } else 14338 if (IsPointerAttr) 14339 mismatch = !isLayoutCompatible(Context, 14340 ArgumentType->getPointeeType(), 14341 RequiredType->getPointeeType()); 14342 else 14343 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14344 14345 if (mismatch) 14346 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14347 << ArgumentType << ArgumentKind 14348 << TypeInfo.LayoutCompatible << RequiredType 14349 << ArgumentExpr->getSourceRange() 14350 << TypeTagExpr->getSourceRange(); 14351 } 14352 14353 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14354 CharUnits Alignment) { 14355 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14356 } 14357 14358 void Sema::DiagnoseMisalignedMembers() { 14359 for (MisalignedMember &m : MisalignedMembers) { 14360 const NamedDecl *ND = m.RD; 14361 if (ND->getName().empty()) { 14362 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14363 ND = TD; 14364 } 14365 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14366 << m.MD << ND << m.E->getSourceRange(); 14367 } 14368 MisalignedMembers.clear(); 14369 } 14370 14371 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14372 E = E->IgnoreParens(); 14373 if (!T->isPointerType() && !T->isIntegerType()) 14374 return; 14375 if (isa<UnaryOperator>(E) && 14376 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14377 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14378 if (isa<MemberExpr>(Op)) { 14379 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14380 if (MA != MisalignedMembers.end() && 14381 (T->isIntegerType() || 14382 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14383 Context.getTypeAlignInChars( 14384 T->getPointeeType()) <= MA->Alignment)))) 14385 MisalignedMembers.erase(MA); 14386 } 14387 } 14388 } 14389 14390 void Sema::RefersToMemberWithReducedAlignment( 14391 Expr *E, 14392 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14393 Action) { 14394 const auto *ME = dyn_cast<MemberExpr>(E); 14395 if (!ME) 14396 return; 14397 14398 // No need to check expressions with an __unaligned-qualified type. 14399 if (E->getType().getQualifiers().hasUnaligned()) 14400 return; 14401 14402 // For a chain of MemberExpr like "a.b.c.d" this list 14403 // will keep FieldDecl's like [d, c, b]. 14404 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14405 const MemberExpr *TopME = nullptr; 14406 bool AnyIsPacked = false; 14407 do { 14408 QualType BaseType = ME->getBase()->getType(); 14409 if (BaseType->isDependentType()) 14410 return; 14411 if (ME->isArrow()) 14412 BaseType = BaseType->getPointeeType(); 14413 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14414 if (RD->isInvalidDecl()) 14415 return; 14416 14417 ValueDecl *MD = ME->getMemberDecl(); 14418 auto *FD = dyn_cast<FieldDecl>(MD); 14419 // We do not care about non-data members. 14420 if (!FD || FD->isInvalidDecl()) 14421 return; 14422 14423 AnyIsPacked = 14424 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14425 ReverseMemberChain.push_back(FD); 14426 14427 TopME = ME; 14428 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14429 } while (ME); 14430 assert(TopME && "We did not compute a topmost MemberExpr!"); 14431 14432 // Not the scope of this diagnostic. 14433 if (!AnyIsPacked) 14434 return; 14435 14436 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14437 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14438 // TODO: The innermost base of the member expression may be too complicated. 14439 // For now, just disregard these cases. This is left for future 14440 // improvement. 14441 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14442 return; 14443 14444 // Alignment expected by the whole expression. 14445 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14446 14447 // No need to do anything else with this case. 14448 if (ExpectedAlignment.isOne()) 14449 return; 14450 14451 // Synthesize offset of the whole access. 14452 CharUnits Offset; 14453 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14454 I++) { 14455 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14456 } 14457 14458 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14459 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14460 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14461 14462 // The base expression of the innermost MemberExpr may give 14463 // stronger guarantees than the class containing the member. 14464 if (DRE && !TopME->isArrow()) { 14465 const ValueDecl *VD = DRE->getDecl(); 14466 if (!VD->getType()->isReferenceType()) 14467 CompleteObjectAlignment = 14468 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14469 } 14470 14471 // Check if the synthesized offset fulfills the alignment. 14472 if (Offset % ExpectedAlignment != 0 || 14473 // It may fulfill the offset it but the effective alignment may still be 14474 // lower than the expected expression alignment. 14475 CompleteObjectAlignment < ExpectedAlignment) { 14476 // If this happens, we want to determine a sensible culprit of this. 14477 // Intuitively, watching the chain of member expressions from right to 14478 // left, we start with the required alignment (as required by the field 14479 // type) but some packed attribute in that chain has reduced the alignment. 14480 // It may happen that another packed structure increases it again. But if 14481 // we are here such increase has not been enough. So pointing the first 14482 // FieldDecl that either is packed or else its RecordDecl is, 14483 // seems reasonable. 14484 FieldDecl *FD = nullptr; 14485 CharUnits Alignment; 14486 for (FieldDecl *FDI : ReverseMemberChain) { 14487 if (FDI->hasAttr<PackedAttr>() || 14488 FDI->getParent()->hasAttr<PackedAttr>()) { 14489 FD = FDI; 14490 Alignment = std::min( 14491 Context.getTypeAlignInChars(FD->getType()), 14492 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14493 break; 14494 } 14495 } 14496 assert(FD && "We did not find a packed FieldDecl!"); 14497 Action(E, FD->getParent(), FD, Alignment); 14498 } 14499 } 14500 14501 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14502 using namespace std::placeholders; 14503 14504 RefersToMemberWithReducedAlignment( 14505 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14506 _2, _3, _4)); 14507 } 14508