1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << MaxValue.toString(10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 592 /// __builtin_*_chk function, then use the object size argument specified in the 593 /// source. Otherwise, infer the object size using __builtin_object_size. 594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 595 CallExpr *TheCall) { 596 // FIXME: There are some more useful checks we could be doing here: 597 // - Evaluate strlen of strcpy arguments, use as object size. 598 599 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 600 isConstantEvaluated()) 601 return; 602 603 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 604 if (!BuiltinID) 605 return; 606 607 const TargetInfo &TI = getASTContext().getTargetInfo(); 608 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 609 610 unsigned DiagID = 0; 611 bool IsChkVariant = false; 612 Optional<llvm::APSInt> UsedSize; 613 unsigned SizeIndex, ObjectIndex; 614 switch (BuiltinID) { 615 default: 616 return; 617 case Builtin::BIsprintf: 618 case Builtin::BI__builtin___sprintf_chk: { 619 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 620 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 621 622 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 623 624 if (!Format->isAscii() && !Format->isUTF8()) 625 return; 626 627 StringRef FormatStrRef = Format->getString(); 628 EstimateSizeFormatHandler H(FormatStrRef); 629 const char *FormatBytes = FormatStrRef.data(); 630 const ConstantArrayType *T = 631 Context.getAsConstantArrayType(Format->getType()); 632 assert(T && "String literal not of constant array type!"); 633 size_t TypeSize = T->getSize().getZExtValue(); 634 635 // In case there's a null byte somewhere. 636 size_t StrLen = 637 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 638 if (!analyze_format_string::ParsePrintfString( 639 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 640 Context.getTargetInfo(), false)) { 641 DiagID = diag::warn_fortify_source_format_overflow; 642 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 643 .extOrTrunc(SizeTypeWidth); 644 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 645 IsChkVariant = true; 646 ObjectIndex = 2; 647 } else { 648 IsChkVariant = false; 649 ObjectIndex = 0; 650 } 651 break; 652 } 653 } 654 return; 655 } 656 case Builtin::BI__builtin___memcpy_chk: 657 case Builtin::BI__builtin___memmove_chk: 658 case Builtin::BI__builtin___memset_chk: 659 case Builtin::BI__builtin___strlcat_chk: 660 case Builtin::BI__builtin___strlcpy_chk: 661 case Builtin::BI__builtin___strncat_chk: 662 case Builtin::BI__builtin___strncpy_chk: 663 case Builtin::BI__builtin___stpncpy_chk: 664 case Builtin::BI__builtin___memccpy_chk: 665 case Builtin::BI__builtin___mempcpy_chk: { 666 DiagID = diag::warn_builtin_chk_overflow; 667 IsChkVariant = true; 668 SizeIndex = TheCall->getNumArgs() - 2; 669 ObjectIndex = TheCall->getNumArgs() - 1; 670 break; 671 } 672 673 case Builtin::BI__builtin___snprintf_chk: 674 case Builtin::BI__builtin___vsnprintf_chk: { 675 DiagID = diag::warn_builtin_chk_overflow; 676 IsChkVariant = true; 677 SizeIndex = 1; 678 ObjectIndex = 3; 679 break; 680 } 681 682 case Builtin::BIstrncat: 683 case Builtin::BI__builtin_strncat: 684 case Builtin::BIstrncpy: 685 case Builtin::BI__builtin_strncpy: 686 case Builtin::BIstpncpy: 687 case Builtin::BI__builtin_stpncpy: { 688 // Whether these functions overflow depends on the runtime strlen of the 689 // string, not just the buffer size, so emitting the "always overflow" 690 // diagnostic isn't quite right. We should still diagnose passing a buffer 691 // size larger than the destination buffer though; this is a runtime abort 692 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 693 DiagID = diag::warn_fortify_source_size_mismatch; 694 SizeIndex = TheCall->getNumArgs() - 1; 695 ObjectIndex = 0; 696 break; 697 } 698 699 case Builtin::BImemcpy: 700 case Builtin::BI__builtin_memcpy: 701 case Builtin::BImemmove: 702 case Builtin::BI__builtin_memmove: 703 case Builtin::BImemset: 704 case Builtin::BI__builtin_memset: 705 case Builtin::BImempcpy: 706 case Builtin::BI__builtin_mempcpy: { 707 DiagID = diag::warn_fortify_source_overflow; 708 SizeIndex = TheCall->getNumArgs() - 1; 709 ObjectIndex = 0; 710 break; 711 } 712 case Builtin::BIsnprintf: 713 case Builtin::BI__builtin_snprintf: 714 case Builtin::BIvsnprintf: 715 case Builtin::BI__builtin_vsnprintf: { 716 DiagID = diag::warn_fortify_source_size_mismatch; 717 SizeIndex = 1; 718 ObjectIndex = 0; 719 break; 720 } 721 } 722 723 llvm::APSInt ObjectSize; 724 // For __builtin___*_chk, the object size is explicitly provided by the caller 725 // (usually using __builtin_object_size). Use that value to check this call. 726 if (IsChkVariant) { 727 Expr::EvalResult Result; 728 Expr *SizeArg = TheCall->getArg(ObjectIndex); 729 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 730 return; 731 ObjectSize = Result.Val.getInt(); 732 733 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 734 } else { 735 // If the parameter has a pass_object_size attribute, then we should use its 736 // (potentially) more strict checking mode. Otherwise, conservatively assume 737 // type 0. 738 int BOSType = 0; 739 if (const auto *POS = 740 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 741 BOSType = POS->getType(); 742 743 Expr *ObjArg = TheCall->getArg(ObjectIndex); 744 uint64_t Result; 745 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 746 return; 747 // Get the object size in the target's size_t width. 748 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 749 } 750 751 // Evaluate the number of bytes of the object that this call will use. 752 if (!UsedSize) { 753 Expr::EvalResult Result; 754 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 755 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 756 return; 757 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 758 } 759 760 if (UsedSize.getValue().ule(ObjectSize)) 761 return; 762 763 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 764 // Skim off the details of whichever builtin was called to produce a better 765 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 766 if (IsChkVariant) { 767 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 768 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 769 } else if (FunctionName.startswith("__builtin_")) { 770 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 771 } 772 773 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 774 PDiag(DiagID) 775 << FunctionName << ObjectSize.toString(/*Radix=*/10) 776 << UsedSize.getValue().toString(/*Radix=*/10)); 777 } 778 779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 780 Scope::ScopeFlags NeededScopeFlags, 781 unsigned DiagID) { 782 // Scopes aren't available during instantiation. Fortunately, builtin 783 // functions cannot be template args so they cannot be formed through template 784 // instantiation. Therefore checking once during the parse is sufficient. 785 if (SemaRef.inTemplateInstantiation()) 786 return false; 787 788 Scope *S = SemaRef.getCurScope(); 789 while (S && !S->isSEHExceptScope()) 790 S = S->getParent(); 791 if (!S || !(S->getFlags() & NeededScopeFlags)) { 792 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 793 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 794 << DRE->getDecl()->getIdentifier(); 795 return true; 796 } 797 798 return false; 799 } 800 801 static inline bool isBlockPointer(Expr *Arg) { 802 return Arg->getType()->isBlockPointerType(); 803 } 804 805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 806 /// void*, which is a requirement of device side enqueue. 807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 808 const BlockPointerType *BPT = 809 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 810 ArrayRef<QualType> Params = 811 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 812 unsigned ArgCounter = 0; 813 bool IllegalParams = false; 814 // Iterate through the block parameters until either one is found that is not 815 // a local void*, or the block is valid. 816 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 817 I != E; ++I, ++ArgCounter) { 818 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 819 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 820 LangAS::opencl_local) { 821 // Get the location of the error. If a block literal has been passed 822 // (BlockExpr) then we can point straight to the offending argument, 823 // else we just point to the variable reference. 824 SourceLocation ErrorLoc; 825 if (isa<BlockExpr>(BlockArg)) { 826 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 827 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 828 } else if (isa<DeclRefExpr>(BlockArg)) { 829 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 830 } 831 S.Diag(ErrorLoc, 832 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 833 IllegalParams = true; 834 } 835 } 836 837 return IllegalParams; 838 } 839 840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 841 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 842 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 843 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 844 return true; 845 } 846 return false; 847 } 848 849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 850 if (checkArgCount(S, TheCall, 2)) 851 return true; 852 853 if (checkOpenCLSubgroupExt(S, TheCall)) 854 return true; 855 856 // First argument is an ndrange_t type. 857 Expr *NDRangeArg = TheCall->getArg(0); 858 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 859 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 860 << TheCall->getDirectCallee() << "'ndrange_t'"; 861 return true; 862 } 863 864 Expr *BlockArg = TheCall->getArg(1); 865 if (!isBlockPointer(BlockArg)) { 866 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 867 << TheCall->getDirectCallee() << "block"; 868 return true; 869 } 870 return checkOpenCLBlockArgs(S, BlockArg); 871 } 872 873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 874 /// get_kernel_work_group_size 875 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 877 if (checkArgCount(S, TheCall, 1)) 878 return true; 879 880 Expr *BlockArg = TheCall->getArg(0); 881 if (!isBlockPointer(BlockArg)) { 882 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 883 << TheCall->getDirectCallee() << "block"; 884 return true; 885 } 886 return checkOpenCLBlockArgs(S, BlockArg); 887 } 888 889 /// Diagnose integer type and any valid implicit conversion to it. 890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 891 const QualType &IntType); 892 893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 894 unsigned Start, unsigned End) { 895 bool IllegalParams = false; 896 for (unsigned I = Start; I <= End; ++I) 897 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 898 S.Context.getSizeType()); 899 return IllegalParams; 900 } 901 902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 903 /// 'local void*' parameter of passed block. 904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 905 Expr *BlockArg, 906 unsigned NumNonVarArgs) { 907 const BlockPointerType *BPT = 908 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 909 unsigned NumBlockParams = 910 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 911 unsigned TotalNumArgs = TheCall->getNumArgs(); 912 913 // For each argument passed to the block, a corresponding uint needs to 914 // be passed to describe the size of the local memory. 915 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 916 S.Diag(TheCall->getBeginLoc(), 917 diag::err_opencl_enqueue_kernel_local_size_args); 918 return true; 919 } 920 921 // Check that the sizes of the local memory are specified by integers. 922 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 923 TotalNumArgs - 1); 924 } 925 926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 927 /// overload formats specified in Table 6.13.17.1. 928 /// int enqueue_kernel(queue_t queue, 929 /// kernel_enqueue_flags_t flags, 930 /// const ndrange_t ndrange, 931 /// void (^block)(void)) 932 /// int enqueue_kernel(queue_t queue, 933 /// kernel_enqueue_flags_t flags, 934 /// const ndrange_t ndrange, 935 /// uint num_events_in_wait_list, 936 /// clk_event_t *event_wait_list, 937 /// clk_event_t *event_ret, 938 /// void (^block)(void)) 939 /// int enqueue_kernel(queue_t queue, 940 /// kernel_enqueue_flags_t flags, 941 /// const ndrange_t ndrange, 942 /// void (^block)(local void*, ...), 943 /// uint size0, ...) 944 /// int enqueue_kernel(queue_t queue, 945 /// kernel_enqueue_flags_t flags, 946 /// const ndrange_t ndrange, 947 /// uint num_events_in_wait_list, 948 /// clk_event_t *event_wait_list, 949 /// clk_event_t *event_ret, 950 /// void (^block)(local void*, ...), 951 /// uint size0, ...) 952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 953 unsigned NumArgs = TheCall->getNumArgs(); 954 955 if (NumArgs < 4) { 956 S.Diag(TheCall->getBeginLoc(), 957 diag::err_typecheck_call_too_few_args_at_least) 958 << 0 << 4 << NumArgs; 959 return true; 960 } 961 962 Expr *Arg0 = TheCall->getArg(0); 963 Expr *Arg1 = TheCall->getArg(1); 964 Expr *Arg2 = TheCall->getArg(2); 965 Expr *Arg3 = TheCall->getArg(3); 966 967 // First argument always needs to be a queue_t type. 968 if (!Arg0->getType()->isQueueT()) { 969 S.Diag(TheCall->getArg(0)->getBeginLoc(), 970 diag::err_opencl_builtin_expected_type) 971 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 972 return true; 973 } 974 975 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 976 if (!Arg1->getType()->isIntegerType()) { 977 S.Diag(TheCall->getArg(1)->getBeginLoc(), 978 diag::err_opencl_builtin_expected_type) 979 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 980 return true; 981 } 982 983 // Third argument is always an ndrange_t type. 984 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 985 S.Diag(TheCall->getArg(2)->getBeginLoc(), 986 diag::err_opencl_builtin_expected_type) 987 << TheCall->getDirectCallee() << "'ndrange_t'"; 988 return true; 989 } 990 991 // With four arguments, there is only one form that the function could be 992 // called in: no events and no variable arguments. 993 if (NumArgs == 4) { 994 // check that the last argument is the right block type. 995 if (!isBlockPointer(Arg3)) { 996 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 997 << TheCall->getDirectCallee() << "block"; 998 return true; 999 } 1000 // we have a block type, check the prototype 1001 const BlockPointerType *BPT = 1002 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1003 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1004 S.Diag(Arg3->getBeginLoc(), 1005 diag::err_opencl_enqueue_kernel_blocks_no_args); 1006 return true; 1007 } 1008 return false; 1009 } 1010 // we can have block + varargs. 1011 if (isBlockPointer(Arg3)) 1012 return (checkOpenCLBlockArgs(S, Arg3) || 1013 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1014 // last two cases with either exactly 7 args or 7 args and varargs. 1015 if (NumArgs >= 7) { 1016 // check common block argument. 1017 Expr *Arg6 = TheCall->getArg(6); 1018 if (!isBlockPointer(Arg6)) { 1019 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1020 << TheCall->getDirectCallee() << "block"; 1021 return true; 1022 } 1023 if (checkOpenCLBlockArgs(S, Arg6)) 1024 return true; 1025 1026 // Forth argument has to be any integer type. 1027 if (!Arg3->getType()->isIntegerType()) { 1028 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1029 diag::err_opencl_builtin_expected_type) 1030 << TheCall->getDirectCallee() << "integer"; 1031 return true; 1032 } 1033 // check remaining common arguments. 1034 Expr *Arg4 = TheCall->getArg(4); 1035 Expr *Arg5 = TheCall->getArg(5); 1036 1037 // Fifth argument is always passed as a pointer to clk_event_t. 1038 if (!Arg4->isNullPointerConstant(S.Context, 1039 Expr::NPC_ValueDependentIsNotNull) && 1040 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1041 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1042 diag::err_opencl_builtin_expected_type) 1043 << TheCall->getDirectCallee() 1044 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1045 return true; 1046 } 1047 1048 // Sixth argument is always passed as a pointer to clk_event_t. 1049 if (!Arg5->isNullPointerConstant(S.Context, 1050 Expr::NPC_ValueDependentIsNotNull) && 1051 !(Arg5->getType()->isPointerType() && 1052 Arg5->getType()->getPointeeType()->isClkEventT())) { 1053 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1054 diag::err_opencl_builtin_expected_type) 1055 << TheCall->getDirectCallee() 1056 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1057 return true; 1058 } 1059 1060 if (NumArgs == 7) 1061 return false; 1062 1063 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1064 } 1065 1066 // None of the specific case has been detected, give generic error 1067 S.Diag(TheCall->getBeginLoc(), 1068 diag::err_opencl_enqueue_kernel_incorrect_args); 1069 return true; 1070 } 1071 1072 /// Returns OpenCL access qual. 1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1074 return D->getAttr<OpenCLAccessAttr>(); 1075 } 1076 1077 /// Returns true if pipe element type is different from the pointer. 1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1079 const Expr *Arg0 = Call->getArg(0); 1080 // First argument type should always be pipe. 1081 if (!Arg0->getType()->isPipeType()) { 1082 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1083 << Call->getDirectCallee() << Arg0->getSourceRange(); 1084 return true; 1085 } 1086 OpenCLAccessAttr *AccessQual = 1087 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1088 // Validates the access qualifier is compatible with the call. 1089 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1090 // read_only and write_only, and assumed to be read_only if no qualifier is 1091 // specified. 1092 switch (Call->getDirectCallee()->getBuiltinID()) { 1093 case Builtin::BIread_pipe: 1094 case Builtin::BIreserve_read_pipe: 1095 case Builtin::BIcommit_read_pipe: 1096 case Builtin::BIwork_group_reserve_read_pipe: 1097 case Builtin::BIsub_group_reserve_read_pipe: 1098 case Builtin::BIwork_group_commit_read_pipe: 1099 case Builtin::BIsub_group_commit_read_pipe: 1100 if (!(!AccessQual || AccessQual->isReadOnly())) { 1101 S.Diag(Arg0->getBeginLoc(), 1102 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1103 << "read_only" << Arg0->getSourceRange(); 1104 return true; 1105 } 1106 break; 1107 case Builtin::BIwrite_pipe: 1108 case Builtin::BIreserve_write_pipe: 1109 case Builtin::BIcommit_write_pipe: 1110 case Builtin::BIwork_group_reserve_write_pipe: 1111 case Builtin::BIsub_group_reserve_write_pipe: 1112 case Builtin::BIwork_group_commit_write_pipe: 1113 case Builtin::BIsub_group_commit_write_pipe: 1114 if (!(AccessQual && AccessQual->isWriteOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "write_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 default: 1122 break; 1123 } 1124 return false; 1125 } 1126 1127 /// Returns true if pipe element type is different from the pointer. 1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1129 const Expr *Arg0 = Call->getArg(0); 1130 const Expr *ArgIdx = Call->getArg(Idx); 1131 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1132 const QualType EltTy = PipeTy->getElementType(); 1133 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1134 // The Idx argument should be a pointer and the type of the pointer and 1135 // the type of pipe element should also be the same. 1136 if (!ArgTy || 1137 !S.Context.hasSameType( 1138 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1139 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1140 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1141 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1142 return true; 1143 } 1144 return false; 1145 } 1146 1147 // Performs semantic analysis for the read/write_pipe call. 1148 // \param S Reference to the semantic analyzer. 1149 // \param Call A pointer to the builtin call. 1150 // \return True if a semantic error has been found, false otherwise. 1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1152 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1153 // functions have two forms. 1154 switch (Call->getNumArgs()) { 1155 case 2: 1156 if (checkOpenCLPipeArg(S, Call)) 1157 return true; 1158 // The call with 2 arguments should be 1159 // read/write_pipe(pipe T, T*). 1160 // Check packet type T. 1161 if (checkOpenCLPipePacketType(S, Call, 1)) 1162 return true; 1163 break; 1164 1165 case 4: { 1166 if (checkOpenCLPipeArg(S, Call)) 1167 return true; 1168 // The call with 4 arguments should be 1169 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1170 // Check reserve_id_t. 1171 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1172 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1173 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1174 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1175 return true; 1176 } 1177 1178 // Check the index. 1179 const Expr *Arg2 = Call->getArg(2); 1180 if (!Arg2->getType()->isIntegerType() && 1181 !Arg2->getType()->isUnsignedIntegerType()) { 1182 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1183 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1184 << Arg2->getType() << Arg2->getSourceRange(); 1185 return true; 1186 } 1187 1188 // Check packet type T. 1189 if (checkOpenCLPipePacketType(S, Call, 3)) 1190 return true; 1191 } break; 1192 default: 1193 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1194 << Call->getDirectCallee() << Call->getSourceRange(); 1195 return true; 1196 } 1197 1198 return false; 1199 } 1200 1201 // Performs a semantic analysis on the {work_group_/sub_group_ 1202 // /_}reserve_{read/write}_pipe 1203 // \param S Reference to the semantic analyzer. 1204 // \param Call The call to the builtin function to be analyzed. 1205 // \return True if a semantic error was found, false otherwise. 1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1207 if (checkArgCount(S, Call, 2)) 1208 return true; 1209 1210 if (checkOpenCLPipeArg(S, Call)) 1211 return true; 1212 1213 // Check the reserve size. 1214 if (!Call->getArg(1)->getType()->isIntegerType() && 1215 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1216 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1217 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1218 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1219 return true; 1220 } 1221 1222 // Since return type of reserve_read/write_pipe built-in function is 1223 // reserve_id_t, which is not defined in the builtin def file , we used int 1224 // as return type and need to override the return type of these functions. 1225 Call->setType(S.Context.OCLReserveIDTy); 1226 1227 return false; 1228 } 1229 1230 // Performs a semantic analysis on {work_group_/sub_group_ 1231 // /_}commit_{read/write}_pipe 1232 // \param S Reference to the semantic analyzer. 1233 // \param Call The call to the builtin function to be analyzed. 1234 // \return True if a semantic error was found, false otherwise. 1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1236 if (checkArgCount(S, Call, 2)) 1237 return true; 1238 1239 if (checkOpenCLPipeArg(S, Call)) 1240 return true; 1241 1242 // Check reserve_id_t. 1243 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1244 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1245 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1246 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1247 return true; 1248 } 1249 1250 return false; 1251 } 1252 1253 // Performs a semantic analysis on the call to built-in Pipe 1254 // Query Functions. 1255 // \param S Reference to the semantic analyzer. 1256 // \param Call The call to the builtin function to be analyzed. 1257 // \return True if a semantic error was found, false otherwise. 1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1259 if (checkArgCount(S, Call, 1)) 1260 return true; 1261 1262 if (!Call->getArg(0)->getType()->isPipeType()) { 1263 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1264 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1265 return true; 1266 } 1267 1268 return false; 1269 } 1270 1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1272 // Performs semantic analysis for the to_global/local/private call. 1273 // \param S Reference to the semantic analyzer. 1274 // \param BuiltinID ID of the builtin function. 1275 // \param Call A pointer to the builtin call. 1276 // \return True if a semantic error has been found, false otherwise. 1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1278 CallExpr *Call) { 1279 if (checkArgCount(S, Call, 1)) 1280 return true; 1281 1282 auto RT = Call->getArg(0)->getType(); 1283 if (!RT->isPointerType() || RT->getPointeeType() 1284 .getAddressSpace() == LangAS::opencl_constant) { 1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1286 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1287 return true; 1288 } 1289 1290 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1291 S.Diag(Call->getArg(0)->getBeginLoc(), 1292 diag::warn_opencl_generic_address_space_arg) 1293 << Call->getDirectCallee()->getNameInfo().getAsString() 1294 << Call->getArg(0)->getSourceRange(); 1295 } 1296 1297 RT = RT->getPointeeType(); 1298 auto Qual = RT.getQualifiers(); 1299 switch (BuiltinID) { 1300 case Builtin::BIto_global: 1301 Qual.setAddressSpace(LangAS::opencl_global); 1302 break; 1303 case Builtin::BIto_local: 1304 Qual.setAddressSpace(LangAS::opencl_local); 1305 break; 1306 case Builtin::BIto_private: 1307 Qual.setAddressSpace(LangAS::opencl_private); 1308 break; 1309 default: 1310 llvm_unreachable("Invalid builtin function"); 1311 } 1312 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1313 RT.getUnqualifiedType(), Qual))); 1314 1315 return false; 1316 } 1317 1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1319 if (checkArgCount(S, TheCall, 1)) 1320 return ExprError(); 1321 1322 // Compute __builtin_launder's parameter type from the argument. 1323 // The parameter type is: 1324 // * The type of the argument if it's not an array or function type, 1325 // Otherwise, 1326 // * The decayed argument type. 1327 QualType ParamTy = [&]() { 1328 QualType ArgTy = TheCall->getArg(0)->getType(); 1329 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1330 return S.Context.getPointerType(Ty->getElementType()); 1331 if (ArgTy->isFunctionType()) { 1332 return S.Context.getPointerType(ArgTy); 1333 } 1334 return ArgTy; 1335 }(); 1336 1337 TheCall->setType(ParamTy); 1338 1339 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1340 if (!ParamTy->isPointerType()) 1341 return 0; 1342 if (ParamTy->isFunctionPointerType()) 1343 return 1; 1344 if (ParamTy->isVoidPointerType()) 1345 return 2; 1346 return llvm::Optional<unsigned>{}; 1347 }(); 1348 if (DiagSelect.hasValue()) { 1349 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1350 << DiagSelect.getValue() << TheCall->getSourceRange(); 1351 return ExprError(); 1352 } 1353 1354 // We either have an incomplete class type, or we have a class template 1355 // whose instantiation has not been forced. Example: 1356 // 1357 // template <class T> struct Foo { T value; }; 1358 // Foo<int> *p = nullptr; 1359 // auto *d = __builtin_launder(p); 1360 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1361 diag::err_incomplete_type)) 1362 return ExprError(); 1363 1364 assert(ParamTy->getPointeeType()->isObjectType() && 1365 "Unhandled non-object pointer case"); 1366 1367 InitializedEntity Entity = 1368 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1369 ExprResult Arg = 1370 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1371 if (Arg.isInvalid()) 1372 return ExprError(); 1373 TheCall->setArg(0, Arg.get()); 1374 1375 return TheCall; 1376 } 1377 1378 // Emit an error and return true if the current architecture is not in the list 1379 // of supported architectures. 1380 static bool 1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1382 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1383 llvm::Triple::ArchType CurArch = 1384 S.getASTContext().getTargetInfo().getTriple().getArch(); 1385 if (llvm::is_contained(SupportedArchs, CurArch)) 1386 return false; 1387 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1388 << TheCall->getSourceRange(); 1389 return true; 1390 } 1391 1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1393 SourceLocation CallSiteLoc); 1394 1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1396 CallExpr *TheCall) { 1397 switch (TI.getTriple().getArch()) { 1398 default: 1399 // Some builtins don't require additional checking, so just consider these 1400 // acceptable. 1401 return false; 1402 case llvm::Triple::arm: 1403 case llvm::Triple::armeb: 1404 case llvm::Triple::thumb: 1405 case llvm::Triple::thumbeb: 1406 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1407 case llvm::Triple::aarch64: 1408 case llvm::Triple::aarch64_32: 1409 case llvm::Triple::aarch64_be: 1410 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1411 case llvm::Triple::bpfeb: 1412 case llvm::Triple::bpfel: 1413 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::hexagon: 1415 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1416 case llvm::Triple::mips: 1417 case llvm::Triple::mipsel: 1418 case llvm::Triple::mips64: 1419 case llvm::Triple::mips64el: 1420 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::systemz: 1422 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1423 case llvm::Triple::x86: 1424 case llvm::Triple::x86_64: 1425 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1426 case llvm::Triple::ppc: 1427 case llvm::Triple::ppcle: 1428 case llvm::Triple::ppc64: 1429 case llvm::Triple::ppc64le: 1430 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1431 case llvm::Triple::amdgcn: 1432 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1433 case llvm::Triple::riscv32: 1434 case llvm::Triple::riscv64: 1435 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1436 } 1437 } 1438 1439 ExprResult 1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1441 CallExpr *TheCall) { 1442 ExprResult TheCallResult(TheCall); 1443 1444 // Find out if any arguments are required to be integer constant expressions. 1445 unsigned ICEArguments = 0; 1446 ASTContext::GetBuiltinTypeError Error; 1447 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1448 if (Error != ASTContext::GE_None) 1449 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1450 1451 // If any arguments are required to be ICE's, check and diagnose. 1452 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1453 // Skip arguments not required to be ICE's. 1454 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1455 1456 llvm::APSInt Result; 1457 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1458 return true; 1459 ICEArguments &= ~(1 << ArgNo); 1460 } 1461 1462 switch (BuiltinID) { 1463 case Builtin::BI__builtin___CFStringMakeConstantString: 1464 assert(TheCall->getNumArgs() == 1 && 1465 "Wrong # arguments to builtin CFStringMakeConstantString"); 1466 if (CheckObjCString(TheCall->getArg(0))) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__builtin_ms_va_start: 1470 case Builtin::BI__builtin_stdarg_start: 1471 case Builtin::BI__builtin_va_start: 1472 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1473 return ExprError(); 1474 break; 1475 case Builtin::BI__va_start: { 1476 switch (Context.getTargetInfo().getTriple().getArch()) { 1477 case llvm::Triple::aarch64: 1478 case llvm::Triple::arm: 1479 case llvm::Triple::thumb: 1480 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1481 return ExprError(); 1482 break; 1483 default: 1484 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1485 return ExprError(); 1486 break; 1487 } 1488 break; 1489 } 1490 1491 // The acquire, release, and no fence variants are ARM and AArch64 only. 1492 case Builtin::BI_interlockedbittestandset_acq: 1493 case Builtin::BI_interlockedbittestandset_rel: 1494 case Builtin::BI_interlockedbittestandset_nf: 1495 case Builtin::BI_interlockedbittestandreset_acq: 1496 case Builtin::BI_interlockedbittestandreset_rel: 1497 case Builtin::BI_interlockedbittestandreset_nf: 1498 if (CheckBuiltinTargetSupport( 1499 *this, BuiltinID, TheCall, 1500 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1501 return ExprError(); 1502 break; 1503 1504 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1505 case Builtin::BI_bittest64: 1506 case Builtin::BI_bittestandcomplement64: 1507 case Builtin::BI_bittestandreset64: 1508 case Builtin::BI_bittestandset64: 1509 case Builtin::BI_interlockedbittestandreset64: 1510 case Builtin::BI_interlockedbittestandset64: 1511 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1512 {llvm::Triple::x86_64, llvm::Triple::arm, 1513 llvm::Triple::thumb, llvm::Triple::aarch64})) 1514 return ExprError(); 1515 break; 1516 1517 case Builtin::BI__builtin_isgreater: 1518 case Builtin::BI__builtin_isgreaterequal: 1519 case Builtin::BI__builtin_isless: 1520 case Builtin::BI__builtin_islessequal: 1521 case Builtin::BI__builtin_islessgreater: 1522 case Builtin::BI__builtin_isunordered: 1523 if (SemaBuiltinUnorderedCompare(TheCall)) 1524 return ExprError(); 1525 break; 1526 case Builtin::BI__builtin_fpclassify: 1527 if (SemaBuiltinFPClassification(TheCall, 6)) 1528 return ExprError(); 1529 break; 1530 case Builtin::BI__builtin_isfinite: 1531 case Builtin::BI__builtin_isinf: 1532 case Builtin::BI__builtin_isinf_sign: 1533 case Builtin::BI__builtin_isnan: 1534 case Builtin::BI__builtin_isnormal: 1535 case Builtin::BI__builtin_signbit: 1536 case Builtin::BI__builtin_signbitf: 1537 case Builtin::BI__builtin_signbitl: 1538 if (SemaBuiltinFPClassification(TheCall, 1)) 1539 return ExprError(); 1540 break; 1541 case Builtin::BI__builtin_shufflevector: 1542 return SemaBuiltinShuffleVector(TheCall); 1543 // TheCall will be freed by the smart pointer here, but that's fine, since 1544 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1545 case Builtin::BI__builtin_prefetch: 1546 if (SemaBuiltinPrefetch(TheCall)) 1547 return ExprError(); 1548 break; 1549 case Builtin::BI__builtin_alloca_with_align: 1550 if (SemaBuiltinAllocaWithAlign(TheCall)) 1551 return ExprError(); 1552 LLVM_FALLTHROUGH; 1553 case Builtin::BI__builtin_alloca: 1554 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1555 << TheCall->getDirectCallee(); 1556 break; 1557 case Builtin::BI__assume: 1558 case Builtin::BI__builtin_assume: 1559 if (SemaBuiltinAssume(TheCall)) 1560 return ExprError(); 1561 break; 1562 case Builtin::BI__builtin_assume_aligned: 1563 if (SemaBuiltinAssumeAligned(TheCall)) 1564 return ExprError(); 1565 break; 1566 case Builtin::BI__builtin_dynamic_object_size: 1567 case Builtin::BI__builtin_object_size: 1568 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1569 return ExprError(); 1570 break; 1571 case Builtin::BI__builtin_longjmp: 1572 if (SemaBuiltinLongjmp(TheCall)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__builtin_setjmp: 1576 if (SemaBuiltinSetjmp(TheCall)) 1577 return ExprError(); 1578 break; 1579 case Builtin::BI__builtin_classify_type: 1580 if (checkArgCount(*this, TheCall, 1)) return true; 1581 TheCall->setType(Context.IntTy); 1582 break; 1583 case Builtin::BI__builtin_complex: 1584 if (SemaBuiltinComplex(TheCall)) 1585 return ExprError(); 1586 break; 1587 case Builtin::BI__builtin_constant_p: { 1588 if (checkArgCount(*this, TheCall, 1)) return true; 1589 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1590 if (Arg.isInvalid()) return true; 1591 TheCall->setArg(0, Arg.get()); 1592 TheCall->setType(Context.IntTy); 1593 break; 1594 } 1595 case Builtin::BI__builtin_launder: 1596 return SemaBuiltinLaunder(*this, TheCall); 1597 case Builtin::BI__sync_fetch_and_add: 1598 case Builtin::BI__sync_fetch_and_add_1: 1599 case Builtin::BI__sync_fetch_and_add_2: 1600 case Builtin::BI__sync_fetch_and_add_4: 1601 case Builtin::BI__sync_fetch_and_add_8: 1602 case Builtin::BI__sync_fetch_and_add_16: 1603 case Builtin::BI__sync_fetch_and_sub: 1604 case Builtin::BI__sync_fetch_and_sub_1: 1605 case Builtin::BI__sync_fetch_and_sub_2: 1606 case Builtin::BI__sync_fetch_and_sub_4: 1607 case Builtin::BI__sync_fetch_and_sub_8: 1608 case Builtin::BI__sync_fetch_and_sub_16: 1609 case Builtin::BI__sync_fetch_and_or: 1610 case Builtin::BI__sync_fetch_and_or_1: 1611 case Builtin::BI__sync_fetch_and_or_2: 1612 case Builtin::BI__sync_fetch_and_or_4: 1613 case Builtin::BI__sync_fetch_and_or_8: 1614 case Builtin::BI__sync_fetch_and_or_16: 1615 case Builtin::BI__sync_fetch_and_and: 1616 case Builtin::BI__sync_fetch_and_and_1: 1617 case Builtin::BI__sync_fetch_and_and_2: 1618 case Builtin::BI__sync_fetch_and_and_4: 1619 case Builtin::BI__sync_fetch_and_and_8: 1620 case Builtin::BI__sync_fetch_and_and_16: 1621 case Builtin::BI__sync_fetch_and_xor: 1622 case Builtin::BI__sync_fetch_and_xor_1: 1623 case Builtin::BI__sync_fetch_and_xor_2: 1624 case Builtin::BI__sync_fetch_and_xor_4: 1625 case Builtin::BI__sync_fetch_and_xor_8: 1626 case Builtin::BI__sync_fetch_and_xor_16: 1627 case Builtin::BI__sync_fetch_and_nand: 1628 case Builtin::BI__sync_fetch_and_nand_1: 1629 case Builtin::BI__sync_fetch_and_nand_2: 1630 case Builtin::BI__sync_fetch_and_nand_4: 1631 case Builtin::BI__sync_fetch_and_nand_8: 1632 case Builtin::BI__sync_fetch_and_nand_16: 1633 case Builtin::BI__sync_add_and_fetch: 1634 case Builtin::BI__sync_add_and_fetch_1: 1635 case Builtin::BI__sync_add_and_fetch_2: 1636 case Builtin::BI__sync_add_and_fetch_4: 1637 case Builtin::BI__sync_add_and_fetch_8: 1638 case Builtin::BI__sync_add_and_fetch_16: 1639 case Builtin::BI__sync_sub_and_fetch: 1640 case Builtin::BI__sync_sub_and_fetch_1: 1641 case Builtin::BI__sync_sub_and_fetch_2: 1642 case Builtin::BI__sync_sub_and_fetch_4: 1643 case Builtin::BI__sync_sub_and_fetch_8: 1644 case Builtin::BI__sync_sub_and_fetch_16: 1645 case Builtin::BI__sync_and_and_fetch: 1646 case Builtin::BI__sync_and_and_fetch_1: 1647 case Builtin::BI__sync_and_and_fetch_2: 1648 case Builtin::BI__sync_and_and_fetch_4: 1649 case Builtin::BI__sync_and_and_fetch_8: 1650 case Builtin::BI__sync_and_and_fetch_16: 1651 case Builtin::BI__sync_or_and_fetch: 1652 case Builtin::BI__sync_or_and_fetch_1: 1653 case Builtin::BI__sync_or_and_fetch_2: 1654 case Builtin::BI__sync_or_and_fetch_4: 1655 case Builtin::BI__sync_or_and_fetch_8: 1656 case Builtin::BI__sync_or_and_fetch_16: 1657 case Builtin::BI__sync_xor_and_fetch: 1658 case Builtin::BI__sync_xor_and_fetch_1: 1659 case Builtin::BI__sync_xor_and_fetch_2: 1660 case Builtin::BI__sync_xor_and_fetch_4: 1661 case Builtin::BI__sync_xor_and_fetch_8: 1662 case Builtin::BI__sync_xor_and_fetch_16: 1663 case Builtin::BI__sync_nand_and_fetch: 1664 case Builtin::BI__sync_nand_and_fetch_1: 1665 case Builtin::BI__sync_nand_and_fetch_2: 1666 case Builtin::BI__sync_nand_and_fetch_4: 1667 case Builtin::BI__sync_nand_and_fetch_8: 1668 case Builtin::BI__sync_nand_and_fetch_16: 1669 case Builtin::BI__sync_val_compare_and_swap: 1670 case Builtin::BI__sync_val_compare_and_swap_1: 1671 case Builtin::BI__sync_val_compare_and_swap_2: 1672 case Builtin::BI__sync_val_compare_and_swap_4: 1673 case Builtin::BI__sync_val_compare_and_swap_8: 1674 case Builtin::BI__sync_val_compare_and_swap_16: 1675 case Builtin::BI__sync_bool_compare_and_swap: 1676 case Builtin::BI__sync_bool_compare_and_swap_1: 1677 case Builtin::BI__sync_bool_compare_and_swap_2: 1678 case Builtin::BI__sync_bool_compare_and_swap_4: 1679 case Builtin::BI__sync_bool_compare_and_swap_8: 1680 case Builtin::BI__sync_bool_compare_and_swap_16: 1681 case Builtin::BI__sync_lock_test_and_set: 1682 case Builtin::BI__sync_lock_test_and_set_1: 1683 case Builtin::BI__sync_lock_test_and_set_2: 1684 case Builtin::BI__sync_lock_test_and_set_4: 1685 case Builtin::BI__sync_lock_test_and_set_8: 1686 case Builtin::BI__sync_lock_test_and_set_16: 1687 case Builtin::BI__sync_lock_release: 1688 case Builtin::BI__sync_lock_release_1: 1689 case Builtin::BI__sync_lock_release_2: 1690 case Builtin::BI__sync_lock_release_4: 1691 case Builtin::BI__sync_lock_release_8: 1692 case Builtin::BI__sync_lock_release_16: 1693 case Builtin::BI__sync_swap: 1694 case Builtin::BI__sync_swap_1: 1695 case Builtin::BI__sync_swap_2: 1696 case Builtin::BI__sync_swap_4: 1697 case Builtin::BI__sync_swap_8: 1698 case Builtin::BI__sync_swap_16: 1699 return SemaBuiltinAtomicOverloaded(TheCallResult); 1700 case Builtin::BI__sync_synchronize: 1701 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1702 << TheCall->getCallee()->getSourceRange(); 1703 break; 1704 case Builtin::BI__builtin_nontemporal_load: 1705 case Builtin::BI__builtin_nontemporal_store: 1706 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1707 case Builtin::BI__builtin_memcpy_inline: { 1708 clang::Expr *SizeOp = TheCall->getArg(2); 1709 // We warn about copying to or from `nullptr` pointers when `size` is 1710 // greater than 0. When `size` is value dependent we cannot evaluate its 1711 // value so we bail out. 1712 if (SizeOp->isValueDependent()) 1713 break; 1714 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1715 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1716 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1717 } 1718 break; 1719 } 1720 #define BUILTIN(ID, TYPE, ATTRS) 1721 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1722 case Builtin::BI##ID: \ 1723 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1724 #include "clang/Basic/Builtins.def" 1725 case Builtin::BI__annotation: 1726 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1727 return ExprError(); 1728 break; 1729 case Builtin::BI__builtin_annotation: 1730 if (SemaBuiltinAnnotation(*this, TheCall)) 1731 return ExprError(); 1732 break; 1733 case Builtin::BI__builtin_addressof: 1734 if (SemaBuiltinAddressof(*this, TheCall)) 1735 return ExprError(); 1736 break; 1737 case Builtin::BI__builtin_is_aligned: 1738 case Builtin::BI__builtin_align_up: 1739 case Builtin::BI__builtin_align_down: 1740 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1741 return ExprError(); 1742 break; 1743 case Builtin::BI__builtin_add_overflow: 1744 case Builtin::BI__builtin_sub_overflow: 1745 case Builtin::BI__builtin_mul_overflow: 1746 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1747 return ExprError(); 1748 break; 1749 case Builtin::BI__builtin_operator_new: 1750 case Builtin::BI__builtin_operator_delete: { 1751 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1752 ExprResult Res = 1753 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1754 if (Res.isInvalid()) 1755 CorrectDelayedTyposInExpr(TheCallResult.get()); 1756 return Res; 1757 } 1758 case Builtin::BI__builtin_dump_struct: { 1759 // We first want to ensure we are called with 2 arguments 1760 if (checkArgCount(*this, TheCall, 2)) 1761 return ExprError(); 1762 // Ensure that the first argument is of type 'struct XX *' 1763 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1764 const QualType PtrArgType = PtrArg->getType(); 1765 if (!PtrArgType->isPointerType() || 1766 !PtrArgType->getPointeeType()->isRecordType()) { 1767 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1768 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1769 << "structure pointer"; 1770 return ExprError(); 1771 } 1772 1773 // Ensure that the second argument is of type 'FunctionType' 1774 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1775 const QualType FnPtrArgType = FnPtrArg->getType(); 1776 if (!FnPtrArgType->isPointerType()) { 1777 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1778 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1779 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1780 return ExprError(); 1781 } 1782 1783 const auto *FuncType = 1784 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1785 1786 if (!FuncType) { 1787 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1788 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1789 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1790 return ExprError(); 1791 } 1792 1793 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1794 if (!FT->getNumParams()) { 1795 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1796 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1797 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1798 return ExprError(); 1799 } 1800 QualType PT = FT->getParamType(0); 1801 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1802 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1803 !PT->getPointeeType().isConstQualified()) { 1804 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1805 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1806 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1807 return ExprError(); 1808 } 1809 } 1810 1811 TheCall->setType(Context.IntTy); 1812 break; 1813 } 1814 case Builtin::BI__builtin_expect_with_probability: { 1815 // We first want to ensure we are called with 3 arguments 1816 if (checkArgCount(*this, TheCall, 3)) 1817 return ExprError(); 1818 // then check probability is constant float in range [0.0, 1.0] 1819 const Expr *ProbArg = TheCall->getArg(2); 1820 SmallVector<PartialDiagnosticAt, 8> Notes; 1821 Expr::EvalResult Eval; 1822 Eval.Diag = &Notes; 1823 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1824 !Eval.Val.isFloat()) { 1825 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1826 << ProbArg->getSourceRange(); 1827 for (const PartialDiagnosticAt &PDiag : Notes) 1828 Diag(PDiag.first, PDiag.second); 1829 return ExprError(); 1830 } 1831 llvm::APFloat Probability = Eval.Val.getFloat(); 1832 bool LoseInfo = false; 1833 Probability.convert(llvm::APFloat::IEEEdouble(), 1834 llvm::RoundingMode::Dynamic, &LoseInfo); 1835 if (!(Probability >= llvm::APFloat(0.0) && 1836 Probability <= llvm::APFloat(1.0))) { 1837 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1838 << ProbArg->getSourceRange(); 1839 return ExprError(); 1840 } 1841 break; 1842 } 1843 case Builtin::BI__builtin_preserve_access_index: 1844 if (SemaBuiltinPreserveAI(*this, TheCall)) 1845 return ExprError(); 1846 break; 1847 case Builtin::BI__builtin_call_with_static_chain: 1848 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1849 return ExprError(); 1850 break; 1851 case Builtin::BI__exception_code: 1852 case Builtin::BI_exception_code: 1853 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1854 diag::err_seh___except_block)) 1855 return ExprError(); 1856 break; 1857 case Builtin::BI__exception_info: 1858 case Builtin::BI_exception_info: 1859 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1860 diag::err_seh___except_filter)) 1861 return ExprError(); 1862 break; 1863 case Builtin::BI__GetExceptionInfo: 1864 if (checkArgCount(*this, TheCall, 1)) 1865 return ExprError(); 1866 1867 if (CheckCXXThrowOperand( 1868 TheCall->getBeginLoc(), 1869 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1870 TheCall)) 1871 return ExprError(); 1872 1873 TheCall->setType(Context.VoidPtrTy); 1874 break; 1875 // OpenCL v2.0, s6.13.16 - Pipe functions 1876 case Builtin::BIread_pipe: 1877 case Builtin::BIwrite_pipe: 1878 // Since those two functions are declared with var args, we need a semantic 1879 // check for the argument. 1880 if (SemaBuiltinRWPipe(*this, TheCall)) 1881 return ExprError(); 1882 break; 1883 case Builtin::BIreserve_read_pipe: 1884 case Builtin::BIreserve_write_pipe: 1885 case Builtin::BIwork_group_reserve_read_pipe: 1886 case Builtin::BIwork_group_reserve_write_pipe: 1887 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1888 return ExprError(); 1889 break; 1890 case Builtin::BIsub_group_reserve_read_pipe: 1891 case Builtin::BIsub_group_reserve_write_pipe: 1892 if (checkOpenCLSubgroupExt(*this, TheCall) || 1893 SemaBuiltinReserveRWPipe(*this, TheCall)) 1894 return ExprError(); 1895 break; 1896 case Builtin::BIcommit_read_pipe: 1897 case Builtin::BIcommit_write_pipe: 1898 case Builtin::BIwork_group_commit_read_pipe: 1899 case Builtin::BIwork_group_commit_write_pipe: 1900 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1901 return ExprError(); 1902 break; 1903 case Builtin::BIsub_group_commit_read_pipe: 1904 case Builtin::BIsub_group_commit_write_pipe: 1905 if (checkOpenCLSubgroupExt(*this, TheCall) || 1906 SemaBuiltinCommitRWPipe(*this, TheCall)) 1907 return ExprError(); 1908 break; 1909 case Builtin::BIget_pipe_num_packets: 1910 case Builtin::BIget_pipe_max_packets: 1911 if (SemaBuiltinPipePackets(*this, TheCall)) 1912 return ExprError(); 1913 break; 1914 case Builtin::BIto_global: 1915 case Builtin::BIto_local: 1916 case Builtin::BIto_private: 1917 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1918 return ExprError(); 1919 break; 1920 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1921 case Builtin::BIenqueue_kernel: 1922 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1923 return ExprError(); 1924 break; 1925 case Builtin::BIget_kernel_work_group_size: 1926 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1927 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1928 return ExprError(); 1929 break; 1930 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1931 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1932 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1933 return ExprError(); 1934 break; 1935 case Builtin::BI__builtin_os_log_format: 1936 Cleanup.setExprNeedsCleanups(true); 1937 LLVM_FALLTHROUGH; 1938 case Builtin::BI__builtin_os_log_format_buffer_size: 1939 if (SemaBuiltinOSLogFormat(TheCall)) 1940 return ExprError(); 1941 break; 1942 case Builtin::BI__builtin_frame_address: 1943 case Builtin::BI__builtin_return_address: { 1944 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1945 return ExprError(); 1946 1947 // -Wframe-address warning if non-zero passed to builtin 1948 // return/frame address. 1949 Expr::EvalResult Result; 1950 if (!TheCall->getArg(0)->isValueDependent() && 1951 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1952 Result.Val.getInt() != 0) 1953 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1954 << ((BuiltinID == Builtin::BI__builtin_return_address) 1955 ? "__builtin_return_address" 1956 : "__builtin_frame_address") 1957 << TheCall->getSourceRange(); 1958 break; 1959 } 1960 1961 case Builtin::BI__builtin_matrix_transpose: 1962 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1963 1964 case Builtin::BI__builtin_matrix_column_major_load: 1965 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1966 1967 case Builtin::BI__builtin_matrix_column_major_store: 1968 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1969 1970 case Builtin::BI__builtin_get_device_side_mangled_name: { 1971 auto Check = [](CallExpr *TheCall) { 1972 if (TheCall->getNumArgs() != 1) 1973 return false; 1974 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1975 if (!DRE) 1976 return false; 1977 auto *D = DRE->getDecl(); 1978 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1979 return false; 1980 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1981 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 1982 }; 1983 if (!Check(TheCall)) { 1984 Diag(TheCall->getBeginLoc(), 1985 diag::err_hip_invalid_args_builtin_mangled_name); 1986 return ExprError(); 1987 } 1988 } 1989 } 1990 1991 // Since the target specific builtins for each arch overlap, only check those 1992 // of the arch we are compiling for. 1993 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1994 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1995 assert(Context.getAuxTargetInfo() && 1996 "Aux Target Builtin, but not an aux target?"); 1997 1998 if (CheckTSBuiltinFunctionCall( 1999 *Context.getAuxTargetInfo(), 2000 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2001 return ExprError(); 2002 } else { 2003 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2004 TheCall)) 2005 return ExprError(); 2006 } 2007 } 2008 2009 return TheCallResult; 2010 } 2011 2012 // Get the valid immediate range for the specified NEON type code. 2013 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2014 NeonTypeFlags Type(t); 2015 int IsQuad = ForceQuad ? true : Type.isQuad(); 2016 switch (Type.getEltType()) { 2017 case NeonTypeFlags::Int8: 2018 case NeonTypeFlags::Poly8: 2019 return shift ? 7 : (8 << IsQuad) - 1; 2020 case NeonTypeFlags::Int16: 2021 case NeonTypeFlags::Poly16: 2022 return shift ? 15 : (4 << IsQuad) - 1; 2023 case NeonTypeFlags::Int32: 2024 return shift ? 31 : (2 << IsQuad) - 1; 2025 case NeonTypeFlags::Int64: 2026 case NeonTypeFlags::Poly64: 2027 return shift ? 63 : (1 << IsQuad) - 1; 2028 case NeonTypeFlags::Poly128: 2029 return shift ? 127 : (1 << IsQuad) - 1; 2030 case NeonTypeFlags::Float16: 2031 assert(!shift && "cannot shift float types!"); 2032 return (4 << IsQuad) - 1; 2033 case NeonTypeFlags::Float32: 2034 assert(!shift && "cannot shift float types!"); 2035 return (2 << IsQuad) - 1; 2036 case NeonTypeFlags::Float64: 2037 assert(!shift && "cannot shift float types!"); 2038 return (1 << IsQuad) - 1; 2039 case NeonTypeFlags::BFloat16: 2040 assert(!shift && "cannot shift float types!"); 2041 return (4 << IsQuad) - 1; 2042 } 2043 llvm_unreachable("Invalid NeonTypeFlag!"); 2044 } 2045 2046 /// getNeonEltType - Return the QualType corresponding to the elements of 2047 /// the vector type specified by the NeonTypeFlags. This is used to check 2048 /// the pointer arguments for Neon load/store intrinsics. 2049 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2050 bool IsPolyUnsigned, bool IsInt64Long) { 2051 switch (Flags.getEltType()) { 2052 case NeonTypeFlags::Int8: 2053 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2054 case NeonTypeFlags::Int16: 2055 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2056 case NeonTypeFlags::Int32: 2057 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2058 case NeonTypeFlags::Int64: 2059 if (IsInt64Long) 2060 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2061 else 2062 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2063 : Context.LongLongTy; 2064 case NeonTypeFlags::Poly8: 2065 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2066 case NeonTypeFlags::Poly16: 2067 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2068 case NeonTypeFlags::Poly64: 2069 if (IsInt64Long) 2070 return Context.UnsignedLongTy; 2071 else 2072 return Context.UnsignedLongLongTy; 2073 case NeonTypeFlags::Poly128: 2074 break; 2075 case NeonTypeFlags::Float16: 2076 return Context.HalfTy; 2077 case NeonTypeFlags::Float32: 2078 return Context.FloatTy; 2079 case NeonTypeFlags::Float64: 2080 return Context.DoubleTy; 2081 case NeonTypeFlags::BFloat16: 2082 return Context.BFloat16Ty; 2083 } 2084 llvm_unreachable("Invalid NeonTypeFlag!"); 2085 } 2086 2087 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2088 // Range check SVE intrinsics that take immediate values. 2089 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2090 2091 switch (BuiltinID) { 2092 default: 2093 return false; 2094 #define GET_SVE_IMMEDIATE_CHECK 2095 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2096 #undef GET_SVE_IMMEDIATE_CHECK 2097 } 2098 2099 // Perform all the immediate checks for this builtin call. 2100 bool HasError = false; 2101 for (auto &I : ImmChecks) { 2102 int ArgNum, CheckTy, ElementSizeInBits; 2103 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2104 2105 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2106 2107 // Function that checks whether the operand (ArgNum) is an immediate 2108 // that is one of the predefined values. 2109 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2110 int ErrDiag) -> bool { 2111 // We can't check the value of a dependent argument. 2112 Expr *Arg = TheCall->getArg(ArgNum); 2113 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2114 return false; 2115 2116 // Check constant-ness first. 2117 llvm::APSInt Imm; 2118 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2119 return true; 2120 2121 if (!CheckImm(Imm.getSExtValue())) 2122 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2123 return false; 2124 }; 2125 2126 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2127 case SVETypeFlags::ImmCheck0_31: 2128 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2129 HasError = true; 2130 break; 2131 case SVETypeFlags::ImmCheck0_13: 2132 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2133 HasError = true; 2134 break; 2135 case SVETypeFlags::ImmCheck1_16: 2136 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2137 HasError = true; 2138 break; 2139 case SVETypeFlags::ImmCheck0_7: 2140 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2141 HasError = true; 2142 break; 2143 case SVETypeFlags::ImmCheckExtract: 2144 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2145 (2048 / ElementSizeInBits) - 1)) 2146 HasError = true; 2147 break; 2148 case SVETypeFlags::ImmCheckShiftRight: 2149 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2150 HasError = true; 2151 break; 2152 case SVETypeFlags::ImmCheckShiftRightNarrow: 2153 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2154 ElementSizeInBits / 2)) 2155 HasError = true; 2156 break; 2157 case SVETypeFlags::ImmCheckShiftLeft: 2158 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2159 ElementSizeInBits - 1)) 2160 HasError = true; 2161 break; 2162 case SVETypeFlags::ImmCheckLaneIndex: 2163 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2164 (128 / (1 * ElementSizeInBits)) - 1)) 2165 HasError = true; 2166 break; 2167 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2168 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2169 (128 / (2 * ElementSizeInBits)) - 1)) 2170 HasError = true; 2171 break; 2172 case SVETypeFlags::ImmCheckLaneIndexDot: 2173 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2174 (128 / (4 * ElementSizeInBits)) - 1)) 2175 HasError = true; 2176 break; 2177 case SVETypeFlags::ImmCheckComplexRot90_270: 2178 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2179 diag::err_rotation_argument_to_cadd)) 2180 HasError = true; 2181 break; 2182 case SVETypeFlags::ImmCheckComplexRotAll90: 2183 if (CheckImmediateInSet( 2184 [](int64_t V) { 2185 return V == 0 || V == 90 || V == 180 || V == 270; 2186 }, 2187 diag::err_rotation_argument_to_cmla)) 2188 HasError = true; 2189 break; 2190 case SVETypeFlags::ImmCheck0_1: 2191 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2192 HasError = true; 2193 break; 2194 case SVETypeFlags::ImmCheck0_2: 2195 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2196 HasError = true; 2197 break; 2198 case SVETypeFlags::ImmCheck0_3: 2199 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2200 HasError = true; 2201 break; 2202 } 2203 } 2204 2205 return HasError; 2206 } 2207 2208 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2209 unsigned BuiltinID, CallExpr *TheCall) { 2210 llvm::APSInt Result; 2211 uint64_t mask = 0; 2212 unsigned TV = 0; 2213 int PtrArgNum = -1; 2214 bool HasConstPtr = false; 2215 switch (BuiltinID) { 2216 #define GET_NEON_OVERLOAD_CHECK 2217 #include "clang/Basic/arm_neon.inc" 2218 #include "clang/Basic/arm_fp16.inc" 2219 #undef GET_NEON_OVERLOAD_CHECK 2220 } 2221 2222 // For NEON intrinsics which are overloaded on vector element type, validate 2223 // the immediate which specifies which variant to emit. 2224 unsigned ImmArg = TheCall->getNumArgs()-1; 2225 if (mask) { 2226 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2227 return true; 2228 2229 TV = Result.getLimitedValue(64); 2230 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2231 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2232 << TheCall->getArg(ImmArg)->getSourceRange(); 2233 } 2234 2235 if (PtrArgNum >= 0) { 2236 // Check that pointer arguments have the specified type. 2237 Expr *Arg = TheCall->getArg(PtrArgNum); 2238 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2239 Arg = ICE->getSubExpr(); 2240 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2241 QualType RHSTy = RHS.get()->getType(); 2242 2243 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2244 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2245 Arch == llvm::Triple::aarch64_32 || 2246 Arch == llvm::Triple::aarch64_be; 2247 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2248 QualType EltTy = 2249 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2250 if (HasConstPtr) 2251 EltTy = EltTy.withConst(); 2252 QualType LHSTy = Context.getPointerType(EltTy); 2253 AssignConvertType ConvTy; 2254 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2255 if (RHS.isInvalid()) 2256 return true; 2257 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2258 RHS.get(), AA_Assigning)) 2259 return true; 2260 } 2261 2262 // For NEON intrinsics which take an immediate value as part of the 2263 // instruction, range check them here. 2264 unsigned i = 0, l = 0, u = 0; 2265 switch (BuiltinID) { 2266 default: 2267 return false; 2268 #define GET_NEON_IMMEDIATE_CHECK 2269 #include "clang/Basic/arm_neon.inc" 2270 #include "clang/Basic/arm_fp16.inc" 2271 #undef GET_NEON_IMMEDIATE_CHECK 2272 } 2273 2274 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2275 } 2276 2277 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2278 switch (BuiltinID) { 2279 default: 2280 return false; 2281 #include "clang/Basic/arm_mve_builtin_sema.inc" 2282 } 2283 } 2284 2285 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2286 CallExpr *TheCall) { 2287 bool Err = false; 2288 switch (BuiltinID) { 2289 default: 2290 return false; 2291 #include "clang/Basic/arm_cde_builtin_sema.inc" 2292 } 2293 2294 if (Err) 2295 return true; 2296 2297 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2298 } 2299 2300 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2301 const Expr *CoprocArg, bool WantCDE) { 2302 if (isConstantEvaluated()) 2303 return false; 2304 2305 // We can't check the value of a dependent argument. 2306 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2307 return false; 2308 2309 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2310 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2311 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2312 2313 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2314 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2315 2316 if (IsCDECoproc != WantCDE) 2317 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2318 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2319 2320 return false; 2321 } 2322 2323 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2324 unsigned MaxWidth) { 2325 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2326 BuiltinID == ARM::BI__builtin_arm_ldaex || 2327 BuiltinID == ARM::BI__builtin_arm_strex || 2328 BuiltinID == ARM::BI__builtin_arm_stlex || 2329 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2330 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2331 BuiltinID == AArch64::BI__builtin_arm_strex || 2332 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2333 "unexpected ARM builtin"); 2334 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2335 BuiltinID == ARM::BI__builtin_arm_ldaex || 2336 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2337 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2338 2339 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2340 2341 // Ensure that we have the proper number of arguments. 2342 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2343 return true; 2344 2345 // Inspect the pointer argument of the atomic builtin. This should always be 2346 // a pointer type, whose element is an integral scalar or pointer type. 2347 // Because it is a pointer type, we don't have to worry about any implicit 2348 // casts here. 2349 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2350 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2351 if (PointerArgRes.isInvalid()) 2352 return true; 2353 PointerArg = PointerArgRes.get(); 2354 2355 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2356 if (!pointerType) { 2357 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2358 << PointerArg->getType() << PointerArg->getSourceRange(); 2359 return true; 2360 } 2361 2362 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2363 // task is to insert the appropriate casts into the AST. First work out just 2364 // what the appropriate type is. 2365 QualType ValType = pointerType->getPointeeType(); 2366 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2367 if (IsLdrex) 2368 AddrType.addConst(); 2369 2370 // Issue a warning if the cast is dodgy. 2371 CastKind CastNeeded = CK_NoOp; 2372 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2373 CastNeeded = CK_BitCast; 2374 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2375 << PointerArg->getType() << Context.getPointerType(AddrType) 2376 << AA_Passing << PointerArg->getSourceRange(); 2377 } 2378 2379 // Finally, do the cast and replace the argument with the corrected version. 2380 AddrType = Context.getPointerType(AddrType); 2381 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2382 if (PointerArgRes.isInvalid()) 2383 return true; 2384 PointerArg = PointerArgRes.get(); 2385 2386 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2387 2388 // In general, we allow ints, floats and pointers to be loaded and stored. 2389 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2390 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2391 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2392 << PointerArg->getType() << PointerArg->getSourceRange(); 2393 return true; 2394 } 2395 2396 // But ARM doesn't have instructions to deal with 128-bit versions. 2397 if (Context.getTypeSize(ValType) > MaxWidth) { 2398 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2399 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2400 << PointerArg->getType() << PointerArg->getSourceRange(); 2401 return true; 2402 } 2403 2404 switch (ValType.getObjCLifetime()) { 2405 case Qualifiers::OCL_None: 2406 case Qualifiers::OCL_ExplicitNone: 2407 // okay 2408 break; 2409 2410 case Qualifiers::OCL_Weak: 2411 case Qualifiers::OCL_Strong: 2412 case Qualifiers::OCL_Autoreleasing: 2413 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2414 << ValType << PointerArg->getSourceRange(); 2415 return true; 2416 } 2417 2418 if (IsLdrex) { 2419 TheCall->setType(ValType); 2420 return false; 2421 } 2422 2423 // Initialize the argument to be stored. 2424 ExprResult ValArg = TheCall->getArg(0); 2425 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2426 Context, ValType, /*consume*/ false); 2427 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2428 if (ValArg.isInvalid()) 2429 return true; 2430 TheCall->setArg(0, ValArg.get()); 2431 2432 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2433 // but the custom checker bypasses all default analysis. 2434 TheCall->setType(Context.IntTy); 2435 return false; 2436 } 2437 2438 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2439 CallExpr *TheCall) { 2440 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2441 BuiltinID == ARM::BI__builtin_arm_ldaex || 2442 BuiltinID == ARM::BI__builtin_arm_strex || 2443 BuiltinID == ARM::BI__builtin_arm_stlex) { 2444 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2445 } 2446 2447 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2448 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2449 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2450 } 2451 2452 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2453 BuiltinID == ARM::BI__builtin_arm_wsr64) 2454 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2455 2456 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2457 BuiltinID == ARM::BI__builtin_arm_rsrp || 2458 BuiltinID == ARM::BI__builtin_arm_wsr || 2459 BuiltinID == ARM::BI__builtin_arm_wsrp) 2460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2461 2462 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2463 return true; 2464 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2465 return true; 2466 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2467 return true; 2468 2469 // For intrinsics which take an immediate value as part of the instruction, 2470 // range check them here. 2471 // FIXME: VFP Intrinsics should error if VFP not present. 2472 switch (BuiltinID) { 2473 default: return false; 2474 case ARM::BI__builtin_arm_ssat: 2475 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2476 case ARM::BI__builtin_arm_usat: 2477 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2478 case ARM::BI__builtin_arm_ssat16: 2479 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2480 case ARM::BI__builtin_arm_usat16: 2481 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2482 case ARM::BI__builtin_arm_vcvtr_f: 2483 case ARM::BI__builtin_arm_vcvtr_d: 2484 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2485 case ARM::BI__builtin_arm_dmb: 2486 case ARM::BI__builtin_arm_dsb: 2487 case ARM::BI__builtin_arm_isb: 2488 case ARM::BI__builtin_arm_dbg: 2489 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2490 case ARM::BI__builtin_arm_cdp: 2491 case ARM::BI__builtin_arm_cdp2: 2492 case ARM::BI__builtin_arm_mcr: 2493 case ARM::BI__builtin_arm_mcr2: 2494 case ARM::BI__builtin_arm_mrc: 2495 case ARM::BI__builtin_arm_mrc2: 2496 case ARM::BI__builtin_arm_mcrr: 2497 case ARM::BI__builtin_arm_mcrr2: 2498 case ARM::BI__builtin_arm_mrrc: 2499 case ARM::BI__builtin_arm_mrrc2: 2500 case ARM::BI__builtin_arm_ldc: 2501 case ARM::BI__builtin_arm_ldcl: 2502 case ARM::BI__builtin_arm_ldc2: 2503 case ARM::BI__builtin_arm_ldc2l: 2504 case ARM::BI__builtin_arm_stc: 2505 case ARM::BI__builtin_arm_stcl: 2506 case ARM::BI__builtin_arm_stc2: 2507 case ARM::BI__builtin_arm_stc2l: 2508 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2509 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2510 /*WantCDE*/ false); 2511 } 2512 } 2513 2514 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2515 unsigned BuiltinID, 2516 CallExpr *TheCall) { 2517 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2518 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2519 BuiltinID == AArch64::BI__builtin_arm_strex || 2520 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2521 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2522 } 2523 2524 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2525 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2526 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2527 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2528 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2529 } 2530 2531 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2532 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2533 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2534 2535 // Memory Tagging Extensions (MTE) Intrinsics 2536 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2537 BuiltinID == AArch64::BI__builtin_arm_addg || 2538 BuiltinID == AArch64::BI__builtin_arm_gmi || 2539 BuiltinID == AArch64::BI__builtin_arm_ldg || 2540 BuiltinID == AArch64::BI__builtin_arm_stg || 2541 BuiltinID == AArch64::BI__builtin_arm_subp) { 2542 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2543 } 2544 2545 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2546 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2547 BuiltinID == AArch64::BI__builtin_arm_wsr || 2548 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2549 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2550 2551 // Only check the valid encoding range. Any constant in this range would be 2552 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2553 // an exception for incorrect registers. This matches MSVC behavior. 2554 if (BuiltinID == AArch64::BI_ReadStatusReg || 2555 BuiltinID == AArch64::BI_WriteStatusReg) 2556 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2557 2558 if (BuiltinID == AArch64::BI__getReg) 2559 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2560 2561 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2562 return true; 2563 2564 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2565 return true; 2566 2567 // For intrinsics which take an immediate value as part of the instruction, 2568 // range check them here. 2569 unsigned i = 0, l = 0, u = 0; 2570 switch (BuiltinID) { 2571 default: return false; 2572 case AArch64::BI__builtin_arm_dmb: 2573 case AArch64::BI__builtin_arm_dsb: 2574 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2575 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2576 } 2577 2578 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2579 } 2580 2581 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2582 if (Arg->getType()->getAsPlaceholderType()) 2583 return false; 2584 2585 // The first argument needs to be a record field access. 2586 // If it is an array element access, we delay decision 2587 // to BPF backend to check whether the access is a 2588 // field access or not. 2589 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2590 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2591 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2592 } 2593 2594 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2595 QualType VectorTy, QualType EltTy) { 2596 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2597 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2598 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2599 << Call->getSourceRange() << VectorEltTy << EltTy; 2600 return false; 2601 } 2602 return true; 2603 } 2604 2605 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2606 QualType ArgType = Arg->getType(); 2607 if (ArgType->getAsPlaceholderType()) 2608 return false; 2609 2610 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2611 // format: 2612 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2613 // 2. <type> var; 2614 // __builtin_preserve_type_info(var, flag); 2615 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2616 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2617 return false; 2618 2619 // Typedef type. 2620 if (ArgType->getAs<TypedefType>()) 2621 return true; 2622 2623 // Record type or Enum type. 2624 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2625 if (const auto *RT = Ty->getAs<RecordType>()) { 2626 if (!RT->getDecl()->getDeclName().isEmpty()) 2627 return true; 2628 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2629 if (!ET->getDecl()->getDeclName().isEmpty()) 2630 return true; 2631 } 2632 2633 return false; 2634 } 2635 2636 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2637 QualType ArgType = Arg->getType(); 2638 if (ArgType->getAsPlaceholderType()) 2639 return false; 2640 2641 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2642 // format: 2643 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2644 // flag); 2645 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2646 if (!UO) 2647 return false; 2648 2649 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2650 if (!CE) 2651 return false; 2652 if (CE->getCastKind() != CK_IntegralToPointer && 2653 CE->getCastKind() != CK_NullToPointer) 2654 return false; 2655 2656 // The integer must be from an EnumConstantDecl. 2657 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2658 if (!DR) 2659 return false; 2660 2661 const EnumConstantDecl *Enumerator = 2662 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2663 if (!Enumerator) 2664 return false; 2665 2666 // The type must be EnumType. 2667 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2668 const auto *ET = Ty->getAs<EnumType>(); 2669 if (!ET) 2670 return false; 2671 2672 // The enum value must be supported. 2673 for (auto *EDI : ET->getDecl()->enumerators()) { 2674 if (EDI == Enumerator) 2675 return true; 2676 } 2677 2678 return false; 2679 } 2680 2681 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2682 CallExpr *TheCall) { 2683 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2684 BuiltinID == BPF::BI__builtin_btf_type_id || 2685 BuiltinID == BPF::BI__builtin_preserve_type_info || 2686 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2687 "unexpected BPF builtin"); 2688 2689 if (checkArgCount(*this, TheCall, 2)) 2690 return true; 2691 2692 // The second argument needs to be a constant int 2693 Expr *Arg = TheCall->getArg(1); 2694 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2695 diag::kind kind; 2696 if (!Value) { 2697 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2698 kind = diag::err_preserve_field_info_not_const; 2699 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2700 kind = diag::err_btf_type_id_not_const; 2701 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2702 kind = diag::err_preserve_type_info_not_const; 2703 else 2704 kind = diag::err_preserve_enum_value_not_const; 2705 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2706 return true; 2707 } 2708 2709 // The first argument 2710 Arg = TheCall->getArg(0); 2711 bool InvalidArg = false; 2712 bool ReturnUnsignedInt = true; 2713 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2714 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2715 InvalidArg = true; 2716 kind = diag::err_preserve_field_info_not_field; 2717 } 2718 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2719 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2720 InvalidArg = true; 2721 kind = diag::err_preserve_type_info_invalid; 2722 } 2723 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2724 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2725 InvalidArg = true; 2726 kind = diag::err_preserve_enum_value_invalid; 2727 } 2728 ReturnUnsignedInt = false; 2729 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2730 ReturnUnsignedInt = false; 2731 } 2732 2733 if (InvalidArg) { 2734 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2735 return true; 2736 } 2737 2738 if (ReturnUnsignedInt) 2739 TheCall->setType(Context.UnsignedIntTy); 2740 else 2741 TheCall->setType(Context.UnsignedLongTy); 2742 return false; 2743 } 2744 2745 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2746 struct ArgInfo { 2747 uint8_t OpNum; 2748 bool IsSigned; 2749 uint8_t BitWidth; 2750 uint8_t Align; 2751 }; 2752 struct BuiltinInfo { 2753 unsigned BuiltinID; 2754 ArgInfo Infos[2]; 2755 }; 2756 2757 static BuiltinInfo Infos[] = { 2758 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2759 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2760 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2761 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2762 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2763 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2764 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2765 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2766 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2767 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2768 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2769 2770 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2781 2782 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2834 {{ 1, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2842 {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2849 { 2, false, 5, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2851 { 2, false, 6, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2853 { 3, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2855 { 3, false, 6, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2872 {{ 2, false, 4, 0 }, 2873 { 3, false, 5, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2875 {{ 2, false, 4, 0 }, 2876 { 3, false, 5, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2878 {{ 2, false, 4, 0 }, 2879 { 3, false, 5, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2881 {{ 2, false, 4, 0 }, 2882 { 3, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2894 { 2, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2896 { 2, false, 6, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2906 {{ 1, false, 4, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2909 {{ 1, false, 4, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2930 {{ 3, false, 1, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2935 {{ 3, false, 1, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2940 {{ 3, false, 1, 0 }} }, 2941 }; 2942 2943 // Use a dynamically initialized static to sort the table exactly once on 2944 // first run. 2945 static const bool SortOnce = 2946 (llvm::sort(Infos, 2947 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2948 return LHS.BuiltinID < RHS.BuiltinID; 2949 }), 2950 true); 2951 (void)SortOnce; 2952 2953 const BuiltinInfo *F = llvm::partition_point( 2954 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2955 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2956 return false; 2957 2958 bool Error = false; 2959 2960 for (const ArgInfo &A : F->Infos) { 2961 // Ignore empty ArgInfo elements. 2962 if (A.BitWidth == 0) 2963 continue; 2964 2965 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2966 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2967 if (!A.Align) { 2968 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2969 } else { 2970 unsigned M = 1 << A.Align; 2971 Min *= M; 2972 Max *= M; 2973 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2974 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2975 } 2976 } 2977 return Error; 2978 } 2979 2980 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2981 CallExpr *TheCall) { 2982 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2983 } 2984 2985 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2986 unsigned BuiltinID, CallExpr *TheCall) { 2987 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2988 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2989 } 2990 2991 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2992 CallExpr *TheCall) { 2993 2994 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2995 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2996 if (!TI.hasFeature("dsp")) 2997 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2998 } 2999 3000 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3001 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3002 if (!TI.hasFeature("dspr2")) 3003 return Diag(TheCall->getBeginLoc(), 3004 diag::err_mips_builtin_requires_dspr2); 3005 } 3006 3007 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3008 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3009 if (!TI.hasFeature("msa")) 3010 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3011 } 3012 3013 return false; 3014 } 3015 3016 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3017 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3018 // ordering for DSP is unspecified. MSA is ordered by the data format used 3019 // by the underlying instruction i.e., df/m, df/n and then by size. 3020 // 3021 // FIXME: The size tests here should instead be tablegen'd along with the 3022 // definitions from include/clang/Basic/BuiltinsMips.def. 3023 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3024 // be too. 3025 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3026 unsigned i = 0, l = 0, u = 0, m = 0; 3027 switch (BuiltinID) { 3028 default: return false; 3029 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3030 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3031 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3032 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3033 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3034 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3035 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3036 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3037 // df/m field. 3038 // These intrinsics take an unsigned 3 bit immediate. 3039 case Mips::BI__builtin_msa_bclri_b: 3040 case Mips::BI__builtin_msa_bnegi_b: 3041 case Mips::BI__builtin_msa_bseti_b: 3042 case Mips::BI__builtin_msa_sat_s_b: 3043 case Mips::BI__builtin_msa_sat_u_b: 3044 case Mips::BI__builtin_msa_slli_b: 3045 case Mips::BI__builtin_msa_srai_b: 3046 case Mips::BI__builtin_msa_srari_b: 3047 case Mips::BI__builtin_msa_srli_b: 3048 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3049 case Mips::BI__builtin_msa_binsli_b: 3050 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3051 // These intrinsics take an unsigned 4 bit immediate. 3052 case Mips::BI__builtin_msa_bclri_h: 3053 case Mips::BI__builtin_msa_bnegi_h: 3054 case Mips::BI__builtin_msa_bseti_h: 3055 case Mips::BI__builtin_msa_sat_s_h: 3056 case Mips::BI__builtin_msa_sat_u_h: 3057 case Mips::BI__builtin_msa_slli_h: 3058 case Mips::BI__builtin_msa_srai_h: 3059 case Mips::BI__builtin_msa_srari_h: 3060 case Mips::BI__builtin_msa_srli_h: 3061 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3062 case Mips::BI__builtin_msa_binsli_h: 3063 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3064 // These intrinsics take an unsigned 5 bit immediate. 3065 // The first block of intrinsics actually have an unsigned 5 bit field, 3066 // not a df/n field. 3067 case Mips::BI__builtin_msa_cfcmsa: 3068 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3069 case Mips::BI__builtin_msa_clei_u_b: 3070 case Mips::BI__builtin_msa_clei_u_h: 3071 case Mips::BI__builtin_msa_clei_u_w: 3072 case Mips::BI__builtin_msa_clei_u_d: 3073 case Mips::BI__builtin_msa_clti_u_b: 3074 case Mips::BI__builtin_msa_clti_u_h: 3075 case Mips::BI__builtin_msa_clti_u_w: 3076 case Mips::BI__builtin_msa_clti_u_d: 3077 case Mips::BI__builtin_msa_maxi_u_b: 3078 case Mips::BI__builtin_msa_maxi_u_h: 3079 case Mips::BI__builtin_msa_maxi_u_w: 3080 case Mips::BI__builtin_msa_maxi_u_d: 3081 case Mips::BI__builtin_msa_mini_u_b: 3082 case Mips::BI__builtin_msa_mini_u_h: 3083 case Mips::BI__builtin_msa_mini_u_w: 3084 case Mips::BI__builtin_msa_mini_u_d: 3085 case Mips::BI__builtin_msa_addvi_b: 3086 case Mips::BI__builtin_msa_addvi_h: 3087 case Mips::BI__builtin_msa_addvi_w: 3088 case Mips::BI__builtin_msa_addvi_d: 3089 case Mips::BI__builtin_msa_bclri_w: 3090 case Mips::BI__builtin_msa_bnegi_w: 3091 case Mips::BI__builtin_msa_bseti_w: 3092 case Mips::BI__builtin_msa_sat_s_w: 3093 case Mips::BI__builtin_msa_sat_u_w: 3094 case Mips::BI__builtin_msa_slli_w: 3095 case Mips::BI__builtin_msa_srai_w: 3096 case Mips::BI__builtin_msa_srari_w: 3097 case Mips::BI__builtin_msa_srli_w: 3098 case Mips::BI__builtin_msa_srlri_w: 3099 case Mips::BI__builtin_msa_subvi_b: 3100 case Mips::BI__builtin_msa_subvi_h: 3101 case Mips::BI__builtin_msa_subvi_w: 3102 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3103 case Mips::BI__builtin_msa_binsli_w: 3104 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3105 // These intrinsics take an unsigned 6 bit immediate. 3106 case Mips::BI__builtin_msa_bclri_d: 3107 case Mips::BI__builtin_msa_bnegi_d: 3108 case Mips::BI__builtin_msa_bseti_d: 3109 case Mips::BI__builtin_msa_sat_s_d: 3110 case Mips::BI__builtin_msa_sat_u_d: 3111 case Mips::BI__builtin_msa_slli_d: 3112 case Mips::BI__builtin_msa_srai_d: 3113 case Mips::BI__builtin_msa_srari_d: 3114 case Mips::BI__builtin_msa_srli_d: 3115 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3116 case Mips::BI__builtin_msa_binsli_d: 3117 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3118 // These intrinsics take a signed 5 bit immediate. 3119 case Mips::BI__builtin_msa_ceqi_b: 3120 case Mips::BI__builtin_msa_ceqi_h: 3121 case Mips::BI__builtin_msa_ceqi_w: 3122 case Mips::BI__builtin_msa_ceqi_d: 3123 case Mips::BI__builtin_msa_clti_s_b: 3124 case Mips::BI__builtin_msa_clti_s_h: 3125 case Mips::BI__builtin_msa_clti_s_w: 3126 case Mips::BI__builtin_msa_clti_s_d: 3127 case Mips::BI__builtin_msa_clei_s_b: 3128 case Mips::BI__builtin_msa_clei_s_h: 3129 case Mips::BI__builtin_msa_clei_s_w: 3130 case Mips::BI__builtin_msa_clei_s_d: 3131 case Mips::BI__builtin_msa_maxi_s_b: 3132 case Mips::BI__builtin_msa_maxi_s_h: 3133 case Mips::BI__builtin_msa_maxi_s_w: 3134 case Mips::BI__builtin_msa_maxi_s_d: 3135 case Mips::BI__builtin_msa_mini_s_b: 3136 case Mips::BI__builtin_msa_mini_s_h: 3137 case Mips::BI__builtin_msa_mini_s_w: 3138 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3139 // These intrinsics take an unsigned 8 bit immediate. 3140 case Mips::BI__builtin_msa_andi_b: 3141 case Mips::BI__builtin_msa_nori_b: 3142 case Mips::BI__builtin_msa_ori_b: 3143 case Mips::BI__builtin_msa_shf_b: 3144 case Mips::BI__builtin_msa_shf_h: 3145 case Mips::BI__builtin_msa_shf_w: 3146 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3147 case Mips::BI__builtin_msa_bseli_b: 3148 case Mips::BI__builtin_msa_bmnzi_b: 3149 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3150 // df/n format 3151 // These intrinsics take an unsigned 4 bit immediate. 3152 case Mips::BI__builtin_msa_copy_s_b: 3153 case Mips::BI__builtin_msa_copy_u_b: 3154 case Mips::BI__builtin_msa_insve_b: 3155 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3156 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3157 // These intrinsics take an unsigned 3 bit immediate. 3158 case Mips::BI__builtin_msa_copy_s_h: 3159 case Mips::BI__builtin_msa_copy_u_h: 3160 case Mips::BI__builtin_msa_insve_h: 3161 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3162 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3163 // These intrinsics take an unsigned 2 bit immediate. 3164 case Mips::BI__builtin_msa_copy_s_w: 3165 case Mips::BI__builtin_msa_copy_u_w: 3166 case Mips::BI__builtin_msa_insve_w: 3167 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3168 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3169 // These intrinsics take an unsigned 1 bit immediate. 3170 case Mips::BI__builtin_msa_copy_s_d: 3171 case Mips::BI__builtin_msa_copy_u_d: 3172 case Mips::BI__builtin_msa_insve_d: 3173 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3174 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3175 // Memory offsets and immediate loads. 3176 // These intrinsics take a signed 10 bit immediate. 3177 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3178 case Mips::BI__builtin_msa_ldi_h: 3179 case Mips::BI__builtin_msa_ldi_w: 3180 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3181 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3182 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3183 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3184 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3185 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3186 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3187 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3188 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3189 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3190 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3191 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3192 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3193 } 3194 3195 if (!m) 3196 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3197 3198 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3199 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3200 } 3201 3202 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3203 /// advancing the pointer over the consumed characters. The decoded type is 3204 /// returned. If the decoded type represents a constant integer with a 3205 /// constraint on its value then Mask is set to that value. The type descriptors 3206 /// used in Str are specific to PPC MMA builtins and are documented in the file 3207 /// defining the PPC builtins. 3208 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3209 unsigned &Mask) { 3210 bool RequireICE = false; 3211 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3212 switch (*Str++) { 3213 case 'V': 3214 return Context.getVectorType(Context.UnsignedCharTy, 16, 3215 VectorType::VectorKind::AltiVecVector); 3216 case 'i': { 3217 char *End; 3218 unsigned size = strtoul(Str, &End, 10); 3219 assert(End != Str && "Missing constant parameter constraint"); 3220 Str = End; 3221 Mask = size; 3222 return Context.IntTy; 3223 } 3224 case 'W': { 3225 char *End; 3226 unsigned size = strtoul(Str, &End, 10); 3227 assert(End != Str && "Missing PowerPC MMA type size"); 3228 Str = End; 3229 QualType Type; 3230 switch (size) { 3231 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3232 case size: Type = Context.Id##Ty; break; 3233 #include "clang/Basic/PPCTypes.def" 3234 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3235 } 3236 bool CheckVectorArgs = false; 3237 while (!CheckVectorArgs) { 3238 switch (*Str++) { 3239 case '*': 3240 Type = Context.getPointerType(Type); 3241 break; 3242 case 'C': 3243 Type = Type.withConst(); 3244 break; 3245 default: 3246 CheckVectorArgs = true; 3247 --Str; 3248 break; 3249 } 3250 } 3251 return Type; 3252 } 3253 default: 3254 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3255 } 3256 } 3257 3258 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3259 CallExpr *TheCall) { 3260 unsigned i = 0, l = 0, u = 0; 3261 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3262 BuiltinID == PPC::BI__builtin_divdeu || 3263 BuiltinID == PPC::BI__builtin_bpermd; 3264 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3265 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3266 BuiltinID == PPC::BI__builtin_divweu || 3267 BuiltinID == PPC::BI__builtin_divde || 3268 BuiltinID == PPC::BI__builtin_divdeu; 3269 3270 if (Is64BitBltin && !IsTarget64Bit) 3271 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3272 << TheCall->getSourceRange(); 3273 3274 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3275 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3276 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3277 << TheCall->getSourceRange(); 3278 3279 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3280 if (!TI.hasFeature("vsx")) 3281 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3282 << TheCall->getSourceRange(); 3283 return false; 3284 }; 3285 3286 switch (BuiltinID) { 3287 default: return false; 3288 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3289 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3290 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3291 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3292 case PPC::BI__builtin_altivec_dss: 3293 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3294 case PPC::BI__builtin_tbegin: 3295 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3296 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3297 case PPC::BI__builtin_tabortwc: 3298 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3299 case PPC::BI__builtin_tabortwci: 3300 case PPC::BI__builtin_tabortdci: 3301 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3302 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3303 case PPC::BI__builtin_altivec_dst: 3304 case PPC::BI__builtin_altivec_dstt: 3305 case PPC::BI__builtin_altivec_dstst: 3306 case PPC::BI__builtin_altivec_dststt: 3307 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3308 case PPC::BI__builtin_vsx_xxpermdi: 3309 case PPC::BI__builtin_vsx_xxsldwi: 3310 return SemaBuiltinVSX(TheCall); 3311 case PPC::BI__builtin_unpack_vector_int128: 3312 return SemaVSXCheck(TheCall) || 3313 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3314 case PPC::BI__builtin_pack_vector_int128: 3315 return SemaVSXCheck(TheCall); 3316 case PPC::BI__builtin_altivec_vgnb: 3317 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3318 case PPC::BI__builtin_altivec_vec_replace_elt: 3319 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3320 QualType VecTy = TheCall->getArg(0)->getType(); 3321 QualType EltTy = TheCall->getArg(1)->getType(); 3322 unsigned Width = Context.getIntWidth(EltTy); 3323 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3324 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3325 } 3326 case PPC::BI__builtin_vsx_xxeval: 3327 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3328 case PPC::BI__builtin_altivec_vsldbi: 3329 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3330 case PPC::BI__builtin_altivec_vsrdbi: 3331 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3332 case PPC::BI__builtin_vsx_xxpermx: 3333 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3334 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3335 case PPC::BI__builtin_##Name: \ 3336 return SemaBuiltinPPCMMACall(TheCall, Types); 3337 #include "clang/Basic/BuiltinsPPC.def" 3338 } 3339 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3340 } 3341 3342 // Check if the given type is a non-pointer PPC MMA type. This function is used 3343 // in Sema to prevent invalid uses of restricted PPC MMA types. 3344 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3345 if (Type->isPointerType() || Type->isArrayType()) 3346 return false; 3347 3348 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3349 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3350 if (false 3351 #include "clang/Basic/PPCTypes.def" 3352 ) { 3353 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3354 return true; 3355 } 3356 return false; 3357 } 3358 3359 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3360 CallExpr *TheCall) { 3361 // position of memory order and scope arguments in the builtin 3362 unsigned OrderIndex, ScopeIndex; 3363 switch (BuiltinID) { 3364 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3365 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3366 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3367 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3368 OrderIndex = 2; 3369 ScopeIndex = 3; 3370 break; 3371 case AMDGPU::BI__builtin_amdgcn_fence: 3372 OrderIndex = 0; 3373 ScopeIndex = 1; 3374 break; 3375 default: 3376 return false; 3377 } 3378 3379 ExprResult Arg = TheCall->getArg(OrderIndex); 3380 auto ArgExpr = Arg.get(); 3381 Expr::EvalResult ArgResult; 3382 3383 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3384 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3385 << ArgExpr->getType(); 3386 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3387 3388 // Check valididty of memory ordering as per C11 / C++11's memody model. 3389 // Only fence needs check. Atomic dec/inc allow all memory orders. 3390 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3391 return Diag(ArgExpr->getBeginLoc(), 3392 diag::warn_atomic_op_has_invalid_memory_order) 3393 << ArgExpr->getSourceRange(); 3394 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3395 case llvm::AtomicOrderingCABI::relaxed: 3396 case llvm::AtomicOrderingCABI::consume: 3397 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3398 return Diag(ArgExpr->getBeginLoc(), 3399 diag::warn_atomic_op_has_invalid_memory_order) 3400 << ArgExpr->getSourceRange(); 3401 break; 3402 case llvm::AtomicOrderingCABI::acquire: 3403 case llvm::AtomicOrderingCABI::release: 3404 case llvm::AtomicOrderingCABI::acq_rel: 3405 case llvm::AtomicOrderingCABI::seq_cst: 3406 break; 3407 } 3408 3409 Arg = TheCall->getArg(ScopeIndex); 3410 ArgExpr = Arg.get(); 3411 Expr::EvalResult ArgResult1; 3412 // Check that sync scope is a constant literal 3413 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3414 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3415 << ArgExpr->getType(); 3416 3417 return false; 3418 } 3419 3420 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3421 unsigned BuiltinID, 3422 CallExpr *TheCall) { 3423 // CodeGenFunction can also detect this, but this gives a better error 3424 // message. 3425 bool FeatureMissing = false; 3426 SmallVector<StringRef> ReqFeatures; 3427 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3428 Features.split(ReqFeatures, ','); 3429 3430 // Check if each required feature is included 3431 for (StringRef F : ReqFeatures) { 3432 if (TI.hasFeature(F)) 3433 continue; 3434 3435 // If the feature is 64bit, alter the string so it will print better in 3436 // the diagnostic. 3437 if (F == "64bit") 3438 F = "RV64"; 3439 3440 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3441 F.consume_front("experimental-"); 3442 std::string FeatureStr = F.str(); 3443 FeatureStr[0] = std::toupper(FeatureStr[0]); 3444 3445 // Error message 3446 FeatureMissing = true; 3447 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3448 << TheCall->getSourceRange() << StringRef(FeatureStr); 3449 } 3450 3451 return FeatureMissing; 3452 } 3453 3454 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3455 CallExpr *TheCall) { 3456 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3457 Expr *Arg = TheCall->getArg(0); 3458 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3459 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3460 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3461 << Arg->getSourceRange(); 3462 } 3463 3464 // For intrinsics which take an immediate value as part of the instruction, 3465 // range check them here. 3466 unsigned i = 0, l = 0, u = 0; 3467 switch (BuiltinID) { 3468 default: return false; 3469 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3470 case SystemZ::BI__builtin_s390_verimb: 3471 case SystemZ::BI__builtin_s390_verimh: 3472 case SystemZ::BI__builtin_s390_verimf: 3473 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3474 case SystemZ::BI__builtin_s390_vfaeb: 3475 case SystemZ::BI__builtin_s390_vfaeh: 3476 case SystemZ::BI__builtin_s390_vfaef: 3477 case SystemZ::BI__builtin_s390_vfaebs: 3478 case SystemZ::BI__builtin_s390_vfaehs: 3479 case SystemZ::BI__builtin_s390_vfaefs: 3480 case SystemZ::BI__builtin_s390_vfaezb: 3481 case SystemZ::BI__builtin_s390_vfaezh: 3482 case SystemZ::BI__builtin_s390_vfaezf: 3483 case SystemZ::BI__builtin_s390_vfaezbs: 3484 case SystemZ::BI__builtin_s390_vfaezhs: 3485 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3486 case SystemZ::BI__builtin_s390_vfisb: 3487 case SystemZ::BI__builtin_s390_vfidb: 3488 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3489 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3490 case SystemZ::BI__builtin_s390_vftcisb: 3491 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3492 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3493 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3494 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3495 case SystemZ::BI__builtin_s390_vstrcb: 3496 case SystemZ::BI__builtin_s390_vstrch: 3497 case SystemZ::BI__builtin_s390_vstrcf: 3498 case SystemZ::BI__builtin_s390_vstrczb: 3499 case SystemZ::BI__builtin_s390_vstrczh: 3500 case SystemZ::BI__builtin_s390_vstrczf: 3501 case SystemZ::BI__builtin_s390_vstrcbs: 3502 case SystemZ::BI__builtin_s390_vstrchs: 3503 case SystemZ::BI__builtin_s390_vstrcfs: 3504 case SystemZ::BI__builtin_s390_vstrczbs: 3505 case SystemZ::BI__builtin_s390_vstrczhs: 3506 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3507 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3508 case SystemZ::BI__builtin_s390_vfminsb: 3509 case SystemZ::BI__builtin_s390_vfmaxsb: 3510 case SystemZ::BI__builtin_s390_vfmindb: 3511 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3512 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3513 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3514 } 3515 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3516 } 3517 3518 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3519 /// This checks that the target supports __builtin_cpu_supports and 3520 /// that the string argument is constant and valid. 3521 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3522 CallExpr *TheCall) { 3523 Expr *Arg = TheCall->getArg(0); 3524 3525 // Check if the argument is a string literal. 3526 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3527 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3528 << Arg->getSourceRange(); 3529 3530 // Check the contents of the string. 3531 StringRef Feature = 3532 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3533 if (!TI.validateCpuSupports(Feature)) 3534 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3535 << Arg->getSourceRange(); 3536 return false; 3537 } 3538 3539 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3540 /// This checks that the target supports __builtin_cpu_is and 3541 /// that the string argument is constant and valid. 3542 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3543 Expr *Arg = TheCall->getArg(0); 3544 3545 // Check if the argument is a string literal. 3546 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3547 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3548 << Arg->getSourceRange(); 3549 3550 // Check the contents of the string. 3551 StringRef Feature = 3552 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3553 if (!TI.validateCpuIs(Feature)) 3554 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3555 << Arg->getSourceRange(); 3556 return false; 3557 } 3558 3559 // Check if the rounding mode is legal. 3560 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3561 // Indicates if this instruction has rounding control or just SAE. 3562 bool HasRC = false; 3563 3564 unsigned ArgNum = 0; 3565 switch (BuiltinID) { 3566 default: 3567 return false; 3568 case X86::BI__builtin_ia32_vcvttsd2si32: 3569 case X86::BI__builtin_ia32_vcvttsd2si64: 3570 case X86::BI__builtin_ia32_vcvttsd2usi32: 3571 case X86::BI__builtin_ia32_vcvttsd2usi64: 3572 case X86::BI__builtin_ia32_vcvttss2si32: 3573 case X86::BI__builtin_ia32_vcvttss2si64: 3574 case X86::BI__builtin_ia32_vcvttss2usi32: 3575 case X86::BI__builtin_ia32_vcvttss2usi64: 3576 ArgNum = 1; 3577 break; 3578 case X86::BI__builtin_ia32_maxpd512: 3579 case X86::BI__builtin_ia32_maxps512: 3580 case X86::BI__builtin_ia32_minpd512: 3581 case X86::BI__builtin_ia32_minps512: 3582 ArgNum = 2; 3583 break; 3584 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3585 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3586 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3587 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3588 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3589 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3590 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3591 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3592 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3593 case X86::BI__builtin_ia32_exp2pd_mask: 3594 case X86::BI__builtin_ia32_exp2ps_mask: 3595 case X86::BI__builtin_ia32_getexppd512_mask: 3596 case X86::BI__builtin_ia32_getexpps512_mask: 3597 case X86::BI__builtin_ia32_rcp28pd_mask: 3598 case X86::BI__builtin_ia32_rcp28ps_mask: 3599 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3600 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3601 case X86::BI__builtin_ia32_vcomisd: 3602 case X86::BI__builtin_ia32_vcomiss: 3603 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3604 ArgNum = 3; 3605 break; 3606 case X86::BI__builtin_ia32_cmppd512_mask: 3607 case X86::BI__builtin_ia32_cmpps512_mask: 3608 case X86::BI__builtin_ia32_cmpsd_mask: 3609 case X86::BI__builtin_ia32_cmpss_mask: 3610 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3611 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3612 case X86::BI__builtin_ia32_getexpss128_round_mask: 3613 case X86::BI__builtin_ia32_getmantpd512_mask: 3614 case X86::BI__builtin_ia32_getmantps512_mask: 3615 case X86::BI__builtin_ia32_maxsd_round_mask: 3616 case X86::BI__builtin_ia32_maxss_round_mask: 3617 case X86::BI__builtin_ia32_minsd_round_mask: 3618 case X86::BI__builtin_ia32_minss_round_mask: 3619 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3620 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3621 case X86::BI__builtin_ia32_reducepd512_mask: 3622 case X86::BI__builtin_ia32_reduceps512_mask: 3623 case X86::BI__builtin_ia32_rndscalepd_mask: 3624 case X86::BI__builtin_ia32_rndscaleps_mask: 3625 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3626 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3627 ArgNum = 4; 3628 break; 3629 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3630 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3631 case X86::BI__builtin_ia32_fixupimmps512_mask: 3632 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3633 case X86::BI__builtin_ia32_fixupimmsd_mask: 3634 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3635 case X86::BI__builtin_ia32_fixupimmss_mask: 3636 case X86::BI__builtin_ia32_fixupimmss_maskz: 3637 case X86::BI__builtin_ia32_getmantsd_round_mask: 3638 case X86::BI__builtin_ia32_getmantss_round_mask: 3639 case X86::BI__builtin_ia32_rangepd512_mask: 3640 case X86::BI__builtin_ia32_rangeps512_mask: 3641 case X86::BI__builtin_ia32_rangesd128_round_mask: 3642 case X86::BI__builtin_ia32_rangess128_round_mask: 3643 case X86::BI__builtin_ia32_reducesd_mask: 3644 case X86::BI__builtin_ia32_reducess_mask: 3645 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3646 case X86::BI__builtin_ia32_rndscaless_round_mask: 3647 ArgNum = 5; 3648 break; 3649 case X86::BI__builtin_ia32_vcvtsd2si64: 3650 case X86::BI__builtin_ia32_vcvtsd2si32: 3651 case X86::BI__builtin_ia32_vcvtsd2usi32: 3652 case X86::BI__builtin_ia32_vcvtsd2usi64: 3653 case X86::BI__builtin_ia32_vcvtss2si32: 3654 case X86::BI__builtin_ia32_vcvtss2si64: 3655 case X86::BI__builtin_ia32_vcvtss2usi32: 3656 case X86::BI__builtin_ia32_vcvtss2usi64: 3657 case X86::BI__builtin_ia32_sqrtpd512: 3658 case X86::BI__builtin_ia32_sqrtps512: 3659 ArgNum = 1; 3660 HasRC = true; 3661 break; 3662 case X86::BI__builtin_ia32_addpd512: 3663 case X86::BI__builtin_ia32_addps512: 3664 case X86::BI__builtin_ia32_divpd512: 3665 case X86::BI__builtin_ia32_divps512: 3666 case X86::BI__builtin_ia32_mulpd512: 3667 case X86::BI__builtin_ia32_mulps512: 3668 case X86::BI__builtin_ia32_subpd512: 3669 case X86::BI__builtin_ia32_subps512: 3670 case X86::BI__builtin_ia32_cvtsi2sd64: 3671 case X86::BI__builtin_ia32_cvtsi2ss32: 3672 case X86::BI__builtin_ia32_cvtsi2ss64: 3673 case X86::BI__builtin_ia32_cvtusi2sd64: 3674 case X86::BI__builtin_ia32_cvtusi2ss32: 3675 case X86::BI__builtin_ia32_cvtusi2ss64: 3676 ArgNum = 2; 3677 HasRC = true; 3678 break; 3679 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3680 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3681 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3682 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3683 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3684 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3685 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3686 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3687 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3688 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3689 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3690 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3691 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3692 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3693 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3694 ArgNum = 3; 3695 HasRC = true; 3696 break; 3697 case X86::BI__builtin_ia32_addss_round_mask: 3698 case X86::BI__builtin_ia32_addsd_round_mask: 3699 case X86::BI__builtin_ia32_divss_round_mask: 3700 case X86::BI__builtin_ia32_divsd_round_mask: 3701 case X86::BI__builtin_ia32_mulss_round_mask: 3702 case X86::BI__builtin_ia32_mulsd_round_mask: 3703 case X86::BI__builtin_ia32_subss_round_mask: 3704 case X86::BI__builtin_ia32_subsd_round_mask: 3705 case X86::BI__builtin_ia32_scalefpd512_mask: 3706 case X86::BI__builtin_ia32_scalefps512_mask: 3707 case X86::BI__builtin_ia32_scalefsd_round_mask: 3708 case X86::BI__builtin_ia32_scalefss_round_mask: 3709 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3710 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3711 case X86::BI__builtin_ia32_sqrtss_round_mask: 3712 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3713 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3714 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3715 case X86::BI__builtin_ia32_vfmaddss3_mask: 3716 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3717 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3718 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3719 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3720 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3721 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3722 case X86::BI__builtin_ia32_vfmaddps512_mask: 3723 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3724 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3725 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3726 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3727 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3728 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3729 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3730 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3731 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3732 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3733 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3734 ArgNum = 4; 3735 HasRC = true; 3736 break; 3737 } 3738 3739 llvm::APSInt Result; 3740 3741 // We can't check the value of a dependent argument. 3742 Expr *Arg = TheCall->getArg(ArgNum); 3743 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3744 return false; 3745 3746 // Check constant-ness first. 3747 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3748 return true; 3749 3750 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3751 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3752 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3753 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3754 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3755 Result == 8/*ROUND_NO_EXC*/ || 3756 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3757 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3758 return false; 3759 3760 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3761 << Arg->getSourceRange(); 3762 } 3763 3764 // Check if the gather/scatter scale is legal. 3765 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3766 CallExpr *TheCall) { 3767 unsigned ArgNum = 0; 3768 switch (BuiltinID) { 3769 default: 3770 return false; 3771 case X86::BI__builtin_ia32_gatherpfdpd: 3772 case X86::BI__builtin_ia32_gatherpfdps: 3773 case X86::BI__builtin_ia32_gatherpfqpd: 3774 case X86::BI__builtin_ia32_gatherpfqps: 3775 case X86::BI__builtin_ia32_scatterpfdpd: 3776 case X86::BI__builtin_ia32_scatterpfdps: 3777 case X86::BI__builtin_ia32_scatterpfqpd: 3778 case X86::BI__builtin_ia32_scatterpfqps: 3779 ArgNum = 3; 3780 break; 3781 case X86::BI__builtin_ia32_gatherd_pd: 3782 case X86::BI__builtin_ia32_gatherd_pd256: 3783 case X86::BI__builtin_ia32_gatherq_pd: 3784 case X86::BI__builtin_ia32_gatherq_pd256: 3785 case X86::BI__builtin_ia32_gatherd_ps: 3786 case X86::BI__builtin_ia32_gatherd_ps256: 3787 case X86::BI__builtin_ia32_gatherq_ps: 3788 case X86::BI__builtin_ia32_gatherq_ps256: 3789 case X86::BI__builtin_ia32_gatherd_q: 3790 case X86::BI__builtin_ia32_gatherd_q256: 3791 case X86::BI__builtin_ia32_gatherq_q: 3792 case X86::BI__builtin_ia32_gatherq_q256: 3793 case X86::BI__builtin_ia32_gatherd_d: 3794 case X86::BI__builtin_ia32_gatherd_d256: 3795 case X86::BI__builtin_ia32_gatherq_d: 3796 case X86::BI__builtin_ia32_gatherq_d256: 3797 case X86::BI__builtin_ia32_gather3div2df: 3798 case X86::BI__builtin_ia32_gather3div2di: 3799 case X86::BI__builtin_ia32_gather3div4df: 3800 case X86::BI__builtin_ia32_gather3div4di: 3801 case X86::BI__builtin_ia32_gather3div4sf: 3802 case X86::BI__builtin_ia32_gather3div4si: 3803 case X86::BI__builtin_ia32_gather3div8sf: 3804 case X86::BI__builtin_ia32_gather3div8si: 3805 case X86::BI__builtin_ia32_gather3siv2df: 3806 case X86::BI__builtin_ia32_gather3siv2di: 3807 case X86::BI__builtin_ia32_gather3siv4df: 3808 case X86::BI__builtin_ia32_gather3siv4di: 3809 case X86::BI__builtin_ia32_gather3siv4sf: 3810 case X86::BI__builtin_ia32_gather3siv4si: 3811 case X86::BI__builtin_ia32_gather3siv8sf: 3812 case X86::BI__builtin_ia32_gather3siv8si: 3813 case X86::BI__builtin_ia32_gathersiv8df: 3814 case X86::BI__builtin_ia32_gathersiv16sf: 3815 case X86::BI__builtin_ia32_gatherdiv8df: 3816 case X86::BI__builtin_ia32_gatherdiv16sf: 3817 case X86::BI__builtin_ia32_gathersiv8di: 3818 case X86::BI__builtin_ia32_gathersiv16si: 3819 case X86::BI__builtin_ia32_gatherdiv8di: 3820 case X86::BI__builtin_ia32_gatherdiv16si: 3821 case X86::BI__builtin_ia32_scatterdiv2df: 3822 case X86::BI__builtin_ia32_scatterdiv2di: 3823 case X86::BI__builtin_ia32_scatterdiv4df: 3824 case X86::BI__builtin_ia32_scatterdiv4di: 3825 case X86::BI__builtin_ia32_scatterdiv4sf: 3826 case X86::BI__builtin_ia32_scatterdiv4si: 3827 case X86::BI__builtin_ia32_scatterdiv8sf: 3828 case X86::BI__builtin_ia32_scatterdiv8si: 3829 case X86::BI__builtin_ia32_scattersiv2df: 3830 case X86::BI__builtin_ia32_scattersiv2di: 3831 case X86::BI__builtin_ia32_scattersiv4df: 3832 case X86::BI__builtin_ia32_scattersiv4di: 3833 case X86::BI__builtin_ia32_scattersiv4sf: 3834 case X86::BI__builtin_ia32_scattersiv4si: 3835 case X86::BI__builtin_ia32_scattersiv8sf: 3836 case X86::BI__builtin_ia32_scattersiv8si: 3837 case X86::BI__builtin_ia32_scattersiv8df: 3838 case X86::BI__builtin_ia32_scattersiv16sf: 3839 case X86::BI__builtin_ia32_scatterdiv8df: 3840 case X86::BI__builtin_ia32_scatterdiv16sf: 3841 case X86::BI__builtin_ia32_scattersiv8di: 3842 case X86::BI__builtin_ia32_scattersiv16si: 3843 case X86::BI__builtin_ia32_scatterdiv8di: 3844 case X86::BI__builtin_ia32_scatterdiv16si: 3845 ArgNum = 4; 3846 break; 3847 } 3848 3849 llvm::APSInt Result; 3850 3851 // We can't check the value of a dependent argument. 3852 Expr *Arg = TheCall->getArg(ArgNum); 3853 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3854 return false; 3855 3856 // Check constant-ness first. 3857 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3858 return true; 3859 3860 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3861 return false; 3862 3863 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3864 << Arg->getSourceRange(); 3865 } 3866 3867 enum { TileRegLow = 0, TileRegHigh = 7 }; 3868 3869 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3870 ArrayRef<int> ArgNums) { 3871 for (int ArgNum : ArgNums) { 3872 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3873 return true; 3874 } 3875 return false; 3876 } 3877 3878 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3879 ArrayRef<int> ArgNums) { 3880 // Because the max number of tile register is TileRegHigh + 1, so here we use 3881 // each bit to represent the usage of them in bitset. 3882 std::bitset<TileRegHigh + 1> ArgValues; 3883 for (int ArgNum : ArgNums) { 3884 Expr *Arg = TheCall->getArg(ArgNum); 3885 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3886 continue; 3887 3888 llvm::APSInt Result; 3889 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3890 return true; 3891 int ArgExtValue = Result.getExtValue(); 3892 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3893 "Incorrect tile register num."); 3894 if (ArgValues.test(ArgExtValue)) 3895 return Diag(TheCall->getBeginLoc(), 3896 diag::err_x86_builtin_tile_arg_duplicate) 3897 << TheCall->getArg(ArgNum)->getSourceRange(); 3898 ArgValues.set(ArgExtValue); 3899 } 3900 return false; 3901 } 3902 3903 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3904 ArrayRef<int> ArgNums) { 3905 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3906 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3907 } 3908 3909 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3910 switch (BuiltinID) { 3911 default: 3912 return false; 3913 case X86::BI__builtin_ia32_tileloadd64: 3914 case X86::BI__builtin_ia32_tileloaddt164: 3915 case X86::BI__builtin_ia32_tilestored64: 3916 case X86::BI__builtin_ia32_tilezero: 3917 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3918 case X86::BI__builtin_ia32_tdpbssd: 3919 case X86::BI__builtin_ia32_tdpbsud: 3920 case X86::BI__builtin_ia32_tdpbusd: 3921 case X86::BI__builtin_ia32_tdpbuud: 3922 case X86::BI__builtin_ia32_tdpbf16ps: 3923 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3924 } 3925 } 3926 static bool isX86_32Builtin(unsigned BuiltinID) { 3927 // These builtins only work on x86-32 targets. 3928 switch (BuiltinID) { 3929 case X86::BI__builtin_ia32_readeflags_u32: 3930 case X86::BI__builtin_ia32_writeeflags_u32: 3931 return true; 3932 } 3933 3934 return false; 3935 } 3936 3937 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3938 CallExpr *TheCall) { 3939 if (BuiltinID == X86::BI__builtin_cpu_supports) 3940 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3941 3942 if (BuiltinID == X86::BI__builtin_cpu_is) 3943 return SemaBuiltinCpuIs(*this, TI, TheCall); 3944 3945 // Check for 32-bit only builtins on a 64-bit target. 3946 const llvm::Triple &TT = TI.getTriple(); 3947 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3948 return Diag(TheCall->getCallee()->getBeginLoc(), 3949 diag::err_32_bit_builtin_64_bit_tgt); 3950 3951 // If the intrinsic has rounding or SAE make sure its valid. 3952 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3953 return true; 3954 3955 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3956 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3957 return true; 3958 3959 // If the intrinsic has a tile arguments, make sure they are valid. 3960 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3961 return true; 3962 3963 // For intrinsics which take an immediate value as part of the instruction, 3964 // range check them here. 3965 int i = 0, l = 0, u = 0; 3966 switch (BuiltinID) { 3967 default: 3968 return false; 3969 case X86::BI__builtin_ia32_vec_ext_v2si: 3970 case X86::BI__builtin_ia32_vec_ext_v2di: 3971 case X86::BI__builtin_ia32_vextractf128_pd256: 3972 case X86::BI__builtin_ia32_vextractf128_ps256: 3973 case X86::BI__builtin_ia32_vextractf128_si256: 3974 case X86::BI__builtin_ia32_extract128i256: 3975 case X86::BI__builtin_ia32_extractf64x4_mask: 3976 case X86::BI__builtin_ia32_extracti64x4_mask: 3977 case X86::BI__builtin_ia32_extractf32x8_mask: 3978 case X86::BI__builtin_ia32_extracti32x8_mask: 3979 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3980 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3981 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3982 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3983 i = 1; l = 0; u = 1; 3984 break; 3985 case X86::BI__builtin_ia32_vec_set_v2di: 3986 case X86::BI__builtin_ia32_vinsertf128_pd256: 3987 case X86::BI__builtin_ia32_vinsertf128_ps256: 3988 case X86::BI__builtin_ia32_vinsertf128_si256: 3989 case X86::BI__builtin_ia32_insert128i256: 3990 case X86::BI__builtin_ia32_insertf32x8: 3991 case X86::BI__builtin_ia32_inserti32x8: 3992 case X86::BI__builtin_ia32_insertf64x4: 3993 case X86::BI__builtin_ia32_inserti64x4: 3994 case X86::BI__builtin_ia32_insertf64x2_256: 3995 case X86::BI__builtin_ia32_inserti64x2_256: 3996 case X86::BI__builtin_ia32_insertf32x4_256: 3997 case X86::BI__builtin_ia32_inserti32x4_256: 3998 i = 2; l = 0; u = 1; 3999 break; 4000 case X86::BI__builtin_ia32_vpermilpd: 4001 case X86::BI__builtin_ia32_vec_ext_v4hi: 4002 case X86::BI__builtin_ia32_vec_ext_v4si: 4003 case X86::BI__builtin_ia32_vec_ext_v4sf: 4004 case X86::BI__builtin_ia32_vec_ext_v4di: 4005 case X86::BI__builtin_ia32_extractf32x4_mask: 4006 case X86::BI__builtin_ia32_extracti32x4_mask: 4007 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4008 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4009 i = 1; l = 0; u = 3; 4010 break; 4011 case X86::BI_mm_prefetch: 4012 case X86::BI__builtin_ia32_vec_ext_v8hi: 4013 case X86::BI__builtin_ia32_vec_ext_v8si: 4014 i = 1; l = 0; u = 7; 4015 break; 4016 case X86::BI__builtin_ia32_sha1rnds4: 4017 case X86::BI__builtin_ia32_blendpd: 4018 case X86::BI__builtin_ia32_shufpd: 4019 case X86::BI__builtin_ia32_vec_set_v4hi: 4020 case X86::BI__builtin_ia32_vec_set_v4si: 4021 case X86::BI__builtin_ia32_vec_set_v4di: 4022 case X86::BI__builtin_ia32_shuf_f32x4_256: 4023 case X86::BI__builtin_ia32_shuf_f64x2_256: 4024 case X86::BI__builtin_ia32_shuf_i32x4_256: 4025 case X86::BI__builtin_ia32_shuf_i64x2_256: 4026 case X86::BI__builtin_ia32_insertf64x2_512: 4027 case X86::BI__builtin_ia32_inserti64x2_512: 4028 case X86::BI__builtin_ia32_insertf32x4: 4029 case X86::BI__builtin_ia32_inserti32x4: 4030 i = 2; l = 0; u = 3; 4031 break; 4032 case X86::BI__builtin_ia32_vpermil2pd: 4033 case X86::BI__builtin_ia32_vpermil2pd256: 4034 case X86::BI__builtin_ia32_vpermil2ps: 4035 case X86::BI__builtin_ia32_vpermil2ps256: 4036 i = 3; l = 0; u = 3; 4037 break; 4038 case X86::BI__builtin_ia32_cmpb128_mask: 4039 case X86::BI__builtin_ia32_cmpw128_mask: 4040 case X86::BI__builtin_ia32_cmpd128_mask: 4041 case X86::BI__builtin_ia32_cmpq128_mask: 4042 case X86::BI__builtin_ia32_cmpb256_mask: 4043 case X86::BI__builtin_ia32_cmpw256_mask: 4044 case X86::BI__builtin_ia32_cmpd256_mask: 4045 case X86::BI__builtin_ia32_cmpq256_mask: 4046 case X86::BI__builtin_ia32_cmpb512_mask: 4047 case X86::BI__builtin_ia32_cmpw512_mask: 4048 case X86::BI__builtin_ia32_cmpd512_mask: 4049 case X86::BI__builtin_ia32_cmpq512_mask: 4050 case X86::BI__builtin_ia32_ucmpb128_mask: 4051 case X86::BI__builtin_ia32_ucmpw128_mask: 4052 case X86::BI__builtin_ia32_ucmpd128_mask: 4053 case X86::BI__builtin_ia32_ucmpq128_mask: 4054 case X86::BI__builtin_ia32_ucmpb256_mask: 4055 case X86::BI__builtin_ia32_ucmpw256_mask: 4056 case X86::BI__builtin_ia32_ucmpd256_mask: 4057 case X86::BI__builtin_ia32_ucmpq256_mask: 4058 case X86::BI__builtin_ia32_ucmpb512_mask: 4059 case X86::BI__builtin_ia32_ucmpw512_mask: 4060 case X86::BI__builtin_ia32_ucmpd512_mask: 4061 case X86::BI__builtin_ia32_ucmpq512_mask: 4062 case X86::BI__builtin_ia32_vpcomub: 4063 case X86::BI__builtin_ia32_vpcomuw: 4064 case X86::BI__builtin_ia32_vpcomud: 4065 case X86::BI__builtin_ia32_vpcomuq: 4066 case X86::BI__builtin_ia32_vpcomb: 4067 case X86::BI__builtin_ia32_vpcomw: 4068 case X86::BI__builtin_ia32_vpcomd: 4069 case X86::BI__builtin_ia32_vpcomq: 4070 case X86::BI__builtin_ia32_vec_set_v8hi: 4071 case X86::BI__builtin_ia32_vec_set_v8si: 4072 i = 2; l = 0; u = 7; 4073 break; 4074 case X86::BI__builtin_ia32_vpermilpd256: 4075 case X86::BI__builtin_ia32_roundps: 4076 case X86::BI__builtin_ia32_roundpd: 4077 case X86::BI__builtin_ia32_roundps256: 4078 case X86::BI__builtin_ia32_roundpd256: 4079 case X86::BI__builtin_ia32_getmantpd128_mask: 4080 case X86::BI__builtin_ia32_getmantpd256_mask: 4081 case X86::BI__builtin_ia32_getmantps128_mask: 4082 case X86::BI__builtin_ia32_getmantps256_mask: 4083 case X86::BI__builtin_ia32_getmantpd512_mask: 4084 case X86::BI__builtin_ia32_getmantps512_mask: 4085 case X86::BI__builtin_ia32_vec_ext_v16qi: 4086 case X86::BI__builtin_ia32_vec_ext_v16hi: 4087 i = 1; l = 0; u = 15; 4088 break; 4089 case X86::BI__builtin_ia32_pblendd128: 4090 case X86::BI__builtin_ia32_blendps: 4091 case X86::BI__builtin_ia32_blendpd256: 4092 case X86::BI__builtin_ia32_shufpd256: 4093 case X86::BI__builtin_ia32_roundss: 4094 case X86::BI__builtin_ia32_roundsd: 4095 case X86::BI__builtin_ia32_rangepd128_mask: 4096 case X86::BI__builtin_ia32_rangepd256_mask: 4097 case X86::BI__builtin_ia32_rangepd512_mask: 4098 case X86::BI__builtin_ia32_rangeps128_mask: 4099 case X86::BI__builtin_ia32_rangeps256_mask: 4100 case X86::BI__builtin_ia32_rangeps512_mask: 4101 case X86::BI__builtin_ia32_getmantsd_round_mask: 4102 case X86::BI__builtin_ia32_getmantss_round_mask: 4103 case X86::BI__builtin_ia32_vec_set_v16qi: 4104 case X86::BI__builtin_ia32_vec_set_v16hi: 4105 i = 2; l = 0; u = 15; 4106 break; 4107 case X86::BI__builtin_ia32_vec_ext_v32qi: 4108 i = 1; l = 0; u = 31; 4109 break; 4110 case X86::BI__builtin_ia32_cmpps: 4111 case X86::BI__builtin_ia32_cmpss: 4112 case X86::BI__builtin_ia32_cmppd: 4113 case X86::BI__builtin_ia32_cmpsd: 4114 case X86::BI__builtin_ia32_cmpps256: 4115 case X86::BI__builtin_ia32_cmppd256: 4116 case X86::BI__builtin_ia32_cmpps128_mask: 4117 case X86::BI__builtin_ia32_cmppd128_mask: 4118 case X86::BI__builtin_ia32_cmpps256_mask: 4119 case X86::BI__builtin_ia32_cmppd256_mask: 4120 case X86::BI__builtin_ia32_cmpps512_mask: 4121 case X86::BI__builtin_ia32_cmppd512_mask: 4122 case X86::BI__builtin_ia32_cmpsd_mask: 4123 case X86::BI__builtin_ia32_cmpss_mask: 4124 case X86::BI__builtin_ia32_vec_set_v32qi: 4125 i = 2; l = 0; u = 31; 4126 break; 4127 case X86::BI__builtin_ia32_permdf256: 4128 case X86::BI__builtin_ia32_permdi256: 4129 case X86::BI__builtin_ia32_permdf512: 4130 case X86::BI__builtin_ia32_permdi512: 4131 case X86::BI__builtin_ia32_vpermilps: 4132 case X86::BI__builtin_ia32_vpermilps256: 4133 case X86::BI__builtin_ia32_vpermilpd512: 4134 case X86::BI__builtin_ia32_vpermilps512: 4135 case X86::BI__builtin_ia32_pshufd: 4136 case X86::BI__builtin_ia32_pshufd256: 4137 case X86::BI__builtin_ia32_pshufd512: 4138 case X86::BI__builtin_ia32_pshufhw: 4139 case X86::BI__builtin_ia32_pshufhw256: 4140 case X86::BI__builtin_ia32_pshufhw512: 4141 case X86::BI__builtin_ia32_pshuflw: 4142 case X86::BI__builtin_ia32_pshuflw256: 4143 case X86::BI__builtin_ia32_pshuflw512: 4144 case X86::BI__builtin_ia32_vcvtps2ph: 4145 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4146 case X86::BI__builtin_ia32_vcvtps2ph256: 4147 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4148 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4149 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4150 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4151 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4152 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4153 case X86::BI__builtin_ia32_rndscaleps_mask: 4154 case X86::BI__builtin_ia32_rndscalepd_mask: 4155 case X86::BI__builtin_ia32_reducepd128_mask: 4156 case X86::BI__builtin_ia32_reducepd256_mask: 4157 case X86::BI__builtin_ia32_reducepd512_mask: 4158 case X86::BI__builtin_ia32_reduceps128_mask: 4159 case X86::BI__builtin_ia32_reduceps256_mask: 4160 case X86::BI__builtin_ia32_reduceps512_mask: 4161 case X86::BI__builtin_ia32_prold512: 4162 case X86::BI__builtin_ia32_prolq512: 4163 case X86::BI__builtin_ia32_prold128: 4164 case X86::BI__builtin_ia32_prold256: 4165 case X86::BI__builtin_ia32_prolq128: 4166 case X86::BI__builtin_ia32_prolq256: 4167 case X86::BI__builtin_ia32_prord512: 4168 case X86::BI__builtin_ia32_prorq512: 4169 case X86::BI__builtin_ia32_prord128: 4170 case X86::BI__builtin_ia32_prord256: 4171 case X86::BI__builtin_ia32_prorq128: 4172 case X86::BI__builtin_ia32_prorq256: 4173 case X86::BI__builtin_ia32_fpclasspd128_mask: 4174 case X86::BI__builtin_ia32_fpclasspd256_mask: 4175 case X86::BI__builtin_ia32_fpclassps128_mask: 4176 case X86::BI__builtin_ia32_fpclassps256_mask: 4177 case X86::BI__builtin_ia32_fpclassps512_mask: 4178 case X86::BI__builtin_ia32_fpclasspd512_mask: 4179 case X86::BI__builtin_ia32_fpclasssd_mask: 4180 case X86::BI__builtin_ia32_fpclassss_mask: 4181 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4182 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4183 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4184 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4185 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4186 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4187 case X86::BI__builtin_ia32_kshiftliqi: 4188 case X86::BI__builtin_ia32_kshiftlihi: 4189 case X86::BI__builtin_ia32_kshiftlisi: 4190 case X86::BI__builtin_ia32_kshiftlidi: 4191 case X86::BI__builtin_ia32_kshiftriqi: 4192 case X86::BI__builtin_ia32_kshiftrihi: 4193 case X86::BI__builtin_ia32_kshiftrisi: 4194 case X86::BI__builtin_ia32_kshiftridi: 4195 i = 1; l = 0; u = 255; 4196 break; 4197 case X86::BI__builtin_ia32_vperm2f128_pd256: 4198 case X86::BI__builtin_ia32_vperm2f128_ps256: 4199 case X86::BI__builtin_ia32_vperm2f128_si256: 4200 case X86::BI__builtin_ia32_permti256: 4201 case X86::BI__builtin_ia32_pblendw128: 4202 case X86::BI__builtin_ia32_pblendw256: 4203 case X86::BI__builtin_ia32_blendps256: 4204 case X86::BI__builtin_ia32_pblendd256: 4205 case X86::BI__builtin_ia32_palignr128: 4206 case X86::BI__builtin_ia32_palignr256: 4207 case X86::BI__builtin_ia32_palignr512: 4208 case X86::BI__builtin_ia32_alignq512: 4209 case X86::BI__builtin_ia32_alignd512: 4210 case X86::BI__builtin_ia32_alignd128: 4211 case X86::BI__builtin_ia32_alignd256: 4212 case X86::BI__builtin_ia32_alignq128: 4213 case X86::BI__builtin_ia32_alignq256: 4214 case X86::BI__builtin_ia32_vcomisd: 4215 case X86::BI__builtin_ia32_vcomiss: 4216 case X86::BI__builtin_ia32_shuf_f32x4: 4217 case X86::BI__builtin_ia32_shuf_f64x2: 4218 case X86::BI__builtin_ia32_shuf_i32x4: 4219 case X86::BI__builtin_ia32_shuf_i64x2: 4220 case X86::BI__builtin_ia32_shufpd512: 4221 case X86::BI__builtin_ia32_shufps: 4222 case X86::BI__builtin_ia32_shufps256: 4223 case X86::BI__builtin_ia32_shufps512: 4224 case X86::BI__builtin_ia32_dbpsadbw128: 4225 case X86::BI__builtin_ia32_dbpsadbw256: 4226 case X86::BI__builtin_ia32_dbpsadbw512: 4227 case X86::BI__builtin_ia32_vpshldd128: 4228 case X86::BI__builtin_ia32_vpshldd256: 4229 case X86::BI__builtin_ia32_vpshldd512: 4230 case X86::BI__builtin_ia32_vpshldq128: 4231 case X86::BI__builtin_ia32_vpshldq256: 4232 case X86::BI__builtin_ia32_vpshldq512: 4233 case X86::BI__builtin_ia32_vpshldw128: 4234 case X86::BI__builtin_ia32_vpshldw256: 4235 case X86::BI__builtin_ia32_vpshldw512: 4236 case X86::BI__builtin_ia32_vpshrdd128: 4237 case X86::BI__builtin_ia32_vpshrdd256: 4238 case X86::BI__builtin_ia32_vpshrdd512: 4239 case X86::BI__builtin_ia32_vpshrdq128: 4240 case X86::BI__builtin_ia32_vpshrdq256: 4241 case X86::BI__builtin_ia32_vpshrdq512: 4242 case X86::BI__builtin_ia32_vpshrdw128: 4243 case X86::BI__builtin_ia32_vpshrdw256: 4244 case X86::BI__builtin_ia32_vpshrdw512: 4245 i = 2; l = 0; u = 255; 4246 break; 4247 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4248 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4249 case X86::BI__builtin_ia32_fixupimmps512_mask: 4250 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4251 case X86::BI__builtin_ia32_fixupimmsd_mask: 4252 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4253 case X86::BI__builtin_ia32_fixupimmss_mask: 4254 case X86::BI__builtin_ia32_fixupimmss_maskz: 4255 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4256 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4257 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4258 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4259 case X86::BI__builtin_ia32_fixupimmps128_mask: 4260 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4261 case X86::BI__builtin_ia32_fixupimmps256_mask: 4262 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4263 case X86::BI__builtin_ia32_pternlogd512_mask: 4264 case X86::BI__builtin_ia32_pternlogd512_maskz: 4265 case X86::BI__builtin_ia32_pternlogq512_mask: 4266 case X86::BI__builtin_ia32_pternlogq512_maskz: 4267 case X86::BI__builtin_ia32_pternlogd128_mask: 4268 case X86::BI__builtin_ia32_pternlogd128_maskz: 4269 case X86::BI__builtin_ia32_pternlogd256_mask: 4270 case X86::BI__builtin_ia32_pternlogd256_maskz: 4271 case X86::BI__builtin_ia32_pternlogq128_mask: 4272 case X86::BI__builtin_ia32_pternlogq128_maskz: 4273 case X86::BI__builtin_ia32_pternlogq256_mask: 4274 case X86::BI__builtin_ia32_pternlogq256_maskz: 4275 i = 3; l = 0; u = 255; 4276 break; 4277 case X86::BI__builtin_ia32_gatherpfdpd: 4278 case X86::BI__builtin_ia32_gatherpfdps: 4279 case X86::BI__builtin_ia32_gatherpfqpd: 4280 case X86::BI__builtin_ia32_gatherpfqps: 4281 case X86::BI__builtin_ia32_scatterpfdpd: 4282 case X86::BI__builtin_ia32_scatterpfdps: 4283 case X86::BI__builtin_ia32_scatterpfqpd: 4284 case X86::BI__builtin_ia32_scatterpfqps: 4285 i = 4; l = 2; u = 3; 4286 break; 4287 case X86::BI__builtin_ia32_reducesd_mask: 4288 case X86::BI__builtin_ia32_reducess_mask: 4289 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4290 case X86::BI__builtin_ia32_rndscaless_round_mask: 4291 i = 4; l = 0; u = 255; 4292 break; 4293 } 4294 4295 // Note that we don't force a hard error on the range check here, allowing 4296 // template-generated or macro-generated dead code to potentially have out-of- 4297 // range values. These need to code generate, but don't need to necessarily 4298 // make any sense. We use a warning that defaults to an error. 4299 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4300 } 4301 4302 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4303 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4304 /// Returns true when the format fits the function and the FormatStringInfo has 4305 /// been populated. 4306 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4307 FormatStringInfo *FSI) { 4308 FSI->HasVAListArg = Format->getFirstArg() == 0; 4309 FSI->FormatIdx = Format->getFormatIdx() - 1; 4310 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4311 4312 // The way the format attribute works in GCC, the implicit this argument 4313 // of member functions is counted. However, it doesn't appear in our own 4314 // lists, so decrement format_idx in that case. 4315 if (IsCXXMember) { 4316 if(FSI->FormatIdx == 0) 4317 return false; 4318 --FSI->FormatIdx; 4319 if (FSI->FirstDataArg != 0) 4320 --FSI->FirstDataArg; 4321 } 4322 return true; 4323 } 4324 4325 /// Checks if a the given expression evaluates to null. 4326 /// 4327 /// Returns true if the value evaluates to null. 4328 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4329 // If the expression has non-null type, it doesn't evaluate to null. 4330 if (auto nullability 4331 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4332 if (*nullability == NullabilityKind::NonNull) 4333 return false; 4334 } 4335 4336 // As a special case, transparent unions initialized with zero are 4337 // considered null for the purposes of the nonnull attribute. 4338 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4339 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4340 if (const CompoundLiteralExpr *CLE = 4341 dyn_cast<CompoundLiteralExpr>(Expr)) 4342 if (const InitListExpr *ILE = 4343 dyn_cast<InitListExpr>(CLE->getInitializer())) 4344 Expr = ILE->getInit(0); 4345 } 4346 4347 bool Result; 4348 return (!Expr->isValueDependent() && 4349 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4350 !Result); 4351 } 4352 4353 static void CheckNonNullArgument(Sema &S, 4354 const Expr *ArgExpr, 4355 SourceLocation CallSiteLoc) { 4356 if (CheckNonNullExpr(S, ArgExpr)) 4357 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4358 S.PDiag(diag::warn_null_arg) 4359 << ArgExpr->getSourceRange()); 4360 } 4361 4362 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4363 FormatStringInfo FSI; 4364 if ((GetFormatStringType(Format) == FST_NSString) && 4365 getFormatStringInfo(Format, false, &FSI)) { 4366 Idx = FSI.FormatIdx; 4367 return true; 4368 } 4369 return false; 4370 } 4371 4372 /// Diagnose use of %s directive in an NSString which is being passed 4373 /// as formatting string to formatting method. 4374 static void 4375 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4376 const NamedDecl *FDecl, 4377 Expr **Args, 4378 unsigned NumArgs) { 4379 unsigned Idx = 0; 4380 bool Format = false; 4381 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4382 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4383 Idx = 2; 4384 Format = true; 4385 } 4386 else 4387 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4388 if (S.GetFormatNSStringIdx(I, Idx)) { 4389 Format = true; 4390 break; 4391 } 4392 } 4393 if (!Format || NumArgs <= Idx) 4394 return; 4395 const Expr *FormatExpr = Args[Idx]; 4396 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4397 FormatExpr = CSCE->getSubExpr(); 4398 const StringLiteral *FormatString; 4399 if (const ObjCStringLiteral *OSL = 4400 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4401 FormatString = OSL->getString(); 4402 else 4403 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4404 if (!FormatString) 4405 return; 4406 if (S.FormatStringHasSArg(FormatString)) { 4407 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4408 << "%s" << 1 << 1; 4409 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4410 << FDecl->getDeclName(); 4411 } 4412 } 4413 4414 /// Determine whether the given type has a non-null nullability annotation. 4415 static bool isNonNullType(ASTContext &ctx, QualType type) { 4416 if (auto nullability = type->getNullability(ctx)) 4417 return *nullability == NullabilityKind::NonNull; 4418 4419 return false; 4420 } 4421 4422 static void CheckNonNullArguments(Sema &S, 4423 const NamedDecl *FDecl, 4424 const FunctionProtoType *Proto, 4425 ArrayRef<const Expr *> Args, 4426 SourceLocation CallSiteLoc) { 4427 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4428 4429 // Already checked by by constant evaluator. 4430 if (S.isConstantEvaluated()) 4431 return; 4432 // Check the attributes attached to the method/function itself. 4433 llvm::SmallBitVector NonNullArgs; 4434 if (FDecl) { 4435 // Handle the nonnull attribute on the function/method declaration itself. 4436 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4437 if (!NonNull->args_size()) { 4438 // Easy case: all pointer arguments are nonnull. 4439 for (const auto *Arg : Args) 4440 if (S.isValidPointerAttrType(Arg->getType())) 4441 CheckNonNullArgument(S, Arg, CallSiteLoc); 4442 return; 4443 } 4444 4445 for (const ParamIdx &Idx : NonNull->args()) { 4446 unsigned IdxAST = Idx.getASTIndex(); 4447 if (IdxAST >= Args.size()) 4448 continue; 4449 if (NonNullArgs.empty()) 4450 NonNullArgs.resize(Args.size()); 4451 NonNullArgs.set(IdxAST); 4452 } 4453 } 4454 } 4455 4456 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4457 // Handle the nonnull attribute on the parameters of the 4458 // function/method. 4459 ArrayRef<ParmVarDecl*> parms; 4460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4461 parms = FD->parameters(); 4462 else 4463 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4464 4465 unsigned ParamIndex = 0; 4466 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4467 I != E; ++I, ++ParamIndex) { 4468 const ParmVarDecl *PVD = *I; 4469 if (PVD->hasAttr<NonNullAttr>() || 4470 isNonNullType(S.Context, PVD->getType())) { 4471 if (NonNullArgs.empty()) 4472 NonNullArgs.resize(Args.size()); 4473 4474 NonNullArgs.set(ParamIndex); 4475 } 4476 } 4477 } else { 4478 // If we have a non-function, non-method declaration but no 4479 // function prototype, try to dig out the function prototype. 4480 if (!Proto) { 4481 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4482 QualType type = VD->getType().getNonReferenceType(); 4483 if (auto pointerType = type->getAs<PointerType>()) 4484 type = pointerType->getPointeeType(); 4485 else if (auto blockType = type->getAs<BlockPointerType>()) 4486 type = blockType->getPointeeType(); 4487 // FIXME: data member pointers? 4488 4489 // Dig out the function prototype, if there is one. 4490 Proto = type->getAs<FunctionProtoType>(); 4491 } 4492 } 4493 4494 // Fill in non-null argument information from the nullability 4495 // information on the parameter types (if we have them). 4496 if (Proto) { 4497 unsigned Index = 0; 4498 for (auto paramType : Proto->getParamTypes()) { 4499 if (isNonNullType(S.Context, paramType)) { 4500 if (NonNullArgs.empty()) 4501 NonNullArgs.resize(Args.size()); 4502 4503 NonNullArgs.set(Index); 4504 } 4505 4506 ++Index; 4507 } 4508 } 4509 } 4510 4511 // Check for non-null arguments. 4512 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4513 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4514 if (NonNullArgs[ArgIndex]) 4515 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4516 } 4517 } 4518 4519 /// Warn if a pointer or reference argument passed to a function points to an 4520 /// object that is less aligned than the parameter. This can happen when 4521 /// creating a typedef with a lower alignment than the original type and then 4522 /// calling functions defined in terms of the original type. 4523 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4524 StringRef ParamName, QualType ArgTy, 4525 QualType ParamTy) { 4526 4527 // If a function accepts a pointer or reference type 4528 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4529 return; 4530 4531 // If the parameter is a pointer type, get the pointee type for the 4532 // argument too. If the parameter is a reference type, don't try to get 4533 // the pointee type for the argument. 4534 if (ParamTy->isPointerType()) 4535 ArgTy = ArgTy->getPointeeType(); 4536 4537 // Remove reference or pointer 4538 ParamTy = ParamTy->getPointeeType(); 4539 4540 // Find expected alignment, and the actual alignment of the passed object. 4541 // getTypeAlignInChars requires complete types 4542 if (ParamTy->isIncompleteType() || ArgTy->isIncompleteType()) 4543 return; 4544 4545 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4546 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4547 4548 // If the argument is less aligned than the parameter, there is a 4549 // potential alignment issue. 4550 if (ArgAlign < ParamAlign) 4551 Diag(Loc, diag::warn_param_mismatched_alignment) 4552 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4553 << ParamName << FDecl; 4554 } 4555 4556 /// Handles the checks for format strings, non-POD arguments to vararg 4557 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4558 /// attributes. 4559 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4560 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4561 bool IsMemberFunction, SourceLocation Loc, 4562 SourceRange Range, VariadicCallType CallType) { 4563 // FIXME: We should check as much as we can in the template definition. 4564 if (CurContext->isDependentContext()) 4565 return; 4566 4567 // Printf and scanf checking. 4568 llvm::SmallBitVector CheckedVarArgs; 4569 if (FDecl) { 4570 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4571 // Only create vector if there are format attributes. 4572 CheckedVarArgs.resize(Args.size()); 4573 4574 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4575 CheckedVarArgs); 4576 } 4577 } 4578 4579 // Refuse POD arguments that weren't caught by the format string 4580 // checks above. 4581 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4582 if (CallType != VariadicDoesNotApply && 4583 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4584 unsigned NumParams = Proto ? Proto->getNumParams() 4585 : FDecl && isa<FunctionDecl>(FDecl) 4586 ? cast<FunctionDecl>(FDecl)->getNumParams() 4587 : FDecl && isa<ObjCMethodDecl>(FDecl) 4588 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4589 : 0; 4590 4591 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4592 // Args[ArgIdx] can be null in malformed code. 4593 if (const Expr *Arg = Args[ArgIdx]) { 4594 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4595 checkVariadicArgument(Arg, CallType); 4596 } 4597 } 4598 } 4599 4600 if (FDecl || Proto) { 4601 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4602 4603 // Type safety checking. 4604 if (FDecl) { 4605 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4606 CheckArgumentWithTypeTag(I, Args, Loc); 4607 } 4608 } 4609 4610 // Check that passed arguments match the alignment of original arguments. 4611 // Try to get the missing prototype from the declaration. 4612 if (!Proto && FDecl) { 4613 const auto *FT = FDecl->getFunctionType(); 4614 if (isa_and_nonnull<FunctionProtoType>(FT)) 4615 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 4616 } 4617 if (Proto) { 4618 // For variadic functions, we may have more args than parameters. 4619 // For some K&R functions, we may have less args than parameters. 4620 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 4621 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 4622 // Args[ArgIdx] can be null in malformed code. 4623 if (const Expr *Arg = Args[ArgIdx]) { 4624 QualType ParamTy = Proto->getParamType(ArgIdx); 4625 QualType ArgTy = Arg->getType(); 4626 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 4627 ArgTy, ParamTy); 4628 } 4629 } 4630 } 4631 4632 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4633 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4634 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4635 if (!Arg->isValueDependent()) { 4636 Expr::EvalResult Align; 4637 if (Arg->EvaluateAsInt(Align, Context)) { 4638 const llvm::APSInt &I = Align.Val.getInt(); 4639 if (!I.isPowerOf2()) 4640 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4641 << Arg->getSourceRange(); 4642 4643 if (I > Sema::MaximumAlignment) 4644 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4645 << Arg->getSourceRange() << Sema::MaximumAlignment; 4646 } 4647 } 4648 } 4649 4650 if (FD) 4651 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4652 } 4653 4654 /// CheckConstructorCall - Check a constructor call for correctness and safety 4655 /// properties not enforced by the C type system. 4656 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 4657 ArrayRef<const Expr *> Args, 4658 const FunctionProtoType *Proto, 4659 SourceLocation Loc) { 4660 VariadicCallType CallType = 4661 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4662 4663 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 4664 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 4665 Context.getPointerType(Ctor->getThisObjectType())); 4666 4667 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4668 Loc, SourceRange(), CallType); 4669 } 4670 4671 /// CheckFunctionCall - Check a direct function call for various correctness 4672 /// and safety properties not strictly enforced by the C type system. 4673 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4674 const FunctionProtoType *Proto) { 4675 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4676 isa<CXXMethodDecl>(FDecl); 4677 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4678 IsMemberOperatorCall; 4679 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4680 TheCall->getCallee()); 4681 Expr** Args = TheCall->getArgs(); 4682 unsigned NumArgs = TheCall->getNumArgs(); 4683 4684 Expr *ImplicitThis = nullptr; 4685 if (IsMemberOperatorCall) { 4686 // If this is a call to a member operator, hide the first argument 4687 // from checkCall. 4688 // FIXME: Our choice of AST representation here is less than ideal. 4689 ImplicitThis = Args[0]; 4690 ++Args; 4691 --NumArgs; 4692 } else if (IsMemberFunction) 4693 ImplicitThis = 4694 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4695 4696 if (ImplicitThis) { 4697 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 4698 // used. 4699 QualType ThisType = ImplicitThis->getType(); 4700 if (!ThisType->isPointerType()) { 4701 assert(!ThisType->isReferenceType()); 4702 ThisType = Context.getPointerType(ThisType); 4703 } 4704 4705 QualType ThisTypeFromDecl = 4706 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 4707 4708 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 4709 ThisTypeFromDecl); 4710 } 4711 4712 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4713 IsMemberFunction, TheCall->getRParenLoc(), 4714 TheCall->getCallee()->getSourceRange(), CallType); 4715 4716 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4717 // None of the checks below are needed for functions that don't have 4718 // simple names (e.g., C++ conversion functions). 4719 if (!FnInfo) 4720 return false; 4721 4722 CheckTCBEnforcement(TheCall, FDecl); 4723 4724 CheckAbsoluteValueFunction(TheCall, FDecl); 4725 CheckMaxUnsignedZero(TheCall, FDecl); 4726 4727 if (getLangOpts().ObjC) 4728 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4729 4730 unsigned CMId = FDecl->getMemoryFunctionKind(); 4731 4732 // Handle memory setting and copying functions. 4733 switch (CMId) { 4734 case 0: 4735 return false; 4736 case Builtin::BIstrlcpy: // fallthrough 4737 case Builtin::BIstrlcat: 4738 CheckStrlcpycatArguments(TheCall, FnInfo); 4739 break; 4740 case Builtin::BIstrncat: 4741 CheckStrncatArguments(TheCall, FnInfo); 4742 break; 4743 case Builtin::BIfree: 4744 CheckFreeArguments(TheCall); 4745 break; 4746 default: 4747 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4748 } 4749 4750 return false; 4751 } 4752 4753 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4754 ArrayRef<const Expr *> Args) { 4755 VariadicCallType CallType = 4756 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4757 4758 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4759 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4760 CallType); 4761 4762 return false; 4763 } 4764 4765 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4766 const FunctionProtoType *Proto) { 4767 QualType Ty; 4768 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4769 Ty = V->getType().getNonReferenceType(); 4770 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4771 Ty = F->getType().getNonReferenceType(); 4772 else 4773 return false; 4774 4775 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4776 !Ty->isFunctionProtoType()) 4777 return false; 4778 4779 VariadicCallType CallType; 4780 if (!Proto || !Proto->isVariadic()) { 4781 CallType = VariadicDoesNotApply; 4782 } else if (Ty->isBlockPointerType()) { 4783 CallType = VariadicBlock; 4784 } else { // Ty->isFunctionPointerType() 4785 CallType = VariadicFunction; 4786 } 4787 4788 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4789 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4790 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4791 TheCall->getCallee()->getSourceRange(), CallType); 4792 4793 return false; 4794 } 4795 4796 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4797 /// such as function pointers returned from functions. 4798 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4799 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4800 TheCall->getCallee()); 4801 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4802 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4803 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4804 TheCall->getCallee()->getSourceRange(), CallType); 4805 4806 return false; 4807 } 4808 4809 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4810 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4811 return false; 4812 4813 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4814 switch (Op) { 4815 case AtomicExpr::AO__c11_atomic_init: 4816 case AtomicExpr::AO__opencl_atomic_init: 4817 llvm_unreachable("There is no ordering argument for an init"); 4818 4819 case AtomicExpr::AO__c11_atomic_load: 4820 case AtomicExpr::AO__opencl_atomic_load: 4821 case AtomicExpr::AO__atomic_load_n: 4822 case AtomicExpr::AO__atomic_load: 4823 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4824 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4825 4826 case AtomicExpr::AO__c11_atomic_store: 4827 case AtomicExpr::AO__opencl_atomic_store: 4828 case AtomicExpr::AO__atomic_store: 4829 case AtomicExpr::AO__atomic_store_n: 4830 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4831 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4832 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4833 4834 default: 4835 return true; 4836 } 4837 } 4838 4839 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4840 AtomicExpr::AtomicOp Op) { 4841 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4842 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4843 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4844 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4845 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4846 Op); 4847 } 4848 4849 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4850 SourceLocation RParenLoc, MultiExprArg Args, 4851 AtomicExpr::AtomicOp Op, 4852 AtomicArgumentOrder ArgOrder) { 4853 // All the non-OpenCL operations take one of the following forms. 4854 // The OpenCL operations take the __c11 forms with one extra argument for 4855 // synchronization scope. 4856 enum { 4857 // C __c11_atomic_init(A *, C) 4858 Init, 4859 4860 // C __c11_atomic_load(A *, int) 4861 Load, 4862 4863 // void __atomic_load(A *, CP, int) 4864 LoadCopy, 4865 4866 // void __atomic_store(A *, CP, int) 4867 Copy, 4868 4869 // C __c11_atomic_add(A *, M, int) 4870 Arithmetic, 4871 4872 // C __atomic_exchange_n(A *, CP, int) 4873 Xchg, 4874 4875 // void __atomic_exchange(A *, C *, CP, int) 4876 GNUXchg, 4877 4878 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4879 C11CmpXchg, 4880 4881 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4882 GNUCmpXchg 4883 } Form = Init; 4884 4885 const unsigned NumForm = GNUCmpXchg + 1; 4886 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4887 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4888 // where: 4889 // C is an appropriate type, 4890 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4891 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4892 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4893 // the int parameters are for orderings. 4894 4895 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4896 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4897 "need to update code for modified forms"); 4898 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4899 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4900 AtomicExpr::AO__atomic_load, 4901 "need to update code for modified C11 atomics"); 4902 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4903 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4904 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4905 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4906 IsOpenCL; 4907 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4908 Op == AtomicExpr::AO__atomic_store_n || 4909 Op == AtomicExpr::AO__atomic_exchange_n || 4910 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4911 bool IsAddSub = false; 4912 4913 switch (Op) { 4914 case AtomicExpr::AO__c11_atomic_init: 4915 case AtomicExpr::AO__opencl_atomic_init: 4916 Form = Init; 4917 break; 4918 4919 case AtomicExpr::AO__c11_atomic_load: 4920 case AtomicExpr::AO__opencl_atomic_load: 4921 case AtomicExpr::AO__atomic_load_n: 4922 Form = Load; 4923 break; 4924 4925 case AtomicExpr::AO__atomic_load: 4926 Form = LoadCopy; 4927 break; 4928 4929 case AtomicExpr::AO__c11_atomic_store: 4930 case AtomicExpr::AO__opencl_atomic_store: 4931 case AtomicExpr::AO__atomic_store: 4932 case AtomicExpr::AO__atomic_store_n: 4933 Form = Copy; 4934 break; 4935 4936 case AtomicExpr::AO__c11_atomic_fetch_add: 4937 case AtomicExpr::AO__c11_atomic_fetch_sub: 4938 case AtomicExpr::AO__opencl_atomic_fetch_add: 4939 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4940 case AtomicExpr::AO__atomic_fetch_add: 4941 case AtomicExpr::AO__atomic_fetch_sub: 4942 case AtomicExpr::AO__atomic_add_fetch: 4943 case AtomicExpr::AO__atomic_sub_fetch: 4944 IsAddSub = true; 4945 Form = Arithmetic; 4946 break; 4947 case AtomicExpr::AO__c11_atomic_fetch_and: 4948 case AtomicExpr::AO__c11_atomic_fetch_or: 4949 case AtomicExpr::AO__c11_atomic_fetch_xor: 4950 case AtomicExpr::AO__opencl_atomic_fetch_and: 4951 case AtomicExpr::AO__opencl_atomic_fetch_or: 4952 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4953 case AtomicExpr::AO__atomic_fetch_and: 4954 case AtomicExpr::AO__atomic_fetch_or: 4955 case AtomicExpr::AO__atomic_fetch_xor: 4956 case AtomicExpr::AO__atomic_fetch_nand: 4957 case AtomicExpr::AO__atomic_and_fetch: 4958 case AtomicExpr::AO__atomic_or_fetch: 4959 case AtomicExpr::AO__atomic_xor_fetch: 4960 case AtomicExpr::AO__atomic_nand_fetch: 4961 Form = Arithmetic; 4962 break; 4963 case AtomicExpr::AO__c11_atomic_fetch_min: 4964 case AtomicExpr::AO__c11_atomic_fetch_max: 4965 case AtomicExpr::AO__opencl_atomic_fetch_min: 4966 case AtomicExpr::AO__opencl_atomic_fetch_max: 4967 case AtomicExpr::AO__atomic_min_fetch: 4968 case AtomicExpr::AO__atomic_max_fetch: 4969 case AtomicExpr::AO__atomic_fetch_min: 4970 case AtomicExpr::AO__atomic_fetch_max: 4971 Form = Arithmetic; 4972 break; 4973 4974 case AtomicExpr::AO__c11_atomic_exchange: 4975 case AtomicExpr::AO__opencl_atomic_exchange: 4976 case AtomicExpr::AO__atomic_exchange_n: 4977 Form = Xchg; 4978 break; 4979 4980 case AtomicExpr::AO__atomic_exchange: 4981 Form = GNUXchg; 4982 break; 4983 4984 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4985 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4986 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4987 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4988 Form = C11CmpXchg; 4989 break; 4990 4991 case AtomicExpr::AO__atomic_compare_exchange: 4992 case AtomicExpr::AO__atomic_compare_exchange_n: 4993 Form = GNUCmpXchg; 4994 break; 4995 } 4996 4997 unsigned AdjustedNumArgs = NumArgs[Form]; 4998 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4999 ++AdjustedNumArgs; 5000 // Check we have the right number of arguments. 5001 if (Args.size() < AdjustedNumArgs) { 5002 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5003 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5004 << ExprRange; 5005 return ExprError(); 5006 } else if (Args.size() > AdjustedNumArgs) { 5007 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5008 diag::err_typecheck_call_too_many_args) 5009 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5010 << ExprRange; 5011 return ExprError(); 5012 } 5013 5014 // Inspect the first argument of the atomic operation. 5015 Expr *Ptr = Args[0]; 5016 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5017 if (ConvertedPtr.isInvalid()) 5018 return ExprError(); 5019 5020 Ptr = ConvertedPtr.get(); 5021 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5022 if (!pointerType) { 5023 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5024 << Ptr->getType() << Ptr->getSourceRange(); 5025 return ExprError(); 5026 } 5027 5028 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5029 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5030 QualType ValType = AtomTy; // 'C' 5031 if (IsC11) { 5032 if (!AtomTy->isAtomicType()) { 5033 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5034 << Ptr->getType() << Ptr->getSourceRange(); 5035 return ExprError(); 5036 } 5037 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5038 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5039 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5040 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5041 << Ptr->getSourceRange(); 5042 return ExprError(); 5043 } 5044 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5045 } else if (Form != Load && Form != LoadCopy) { 5046 if (ValType.isConstQualified()) { 5047 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5048 << Ptr->getType() << Ptr->getSourceRange(); 5049 return ExprError(); 5050 } 5051 } 5052 5053 // For an arithmetic operation, the implied arithmetic must be well-formed. 5054 if (Form == Arithmetic) { 5055 // gcc does not enforce these rules for GNU atomics, but we do so for 5056 // sanity. 5057 auto IsAllowedValueType = [&](QualType ValType) { 5058 if (ValType->isIntegerType()) 5059 return true; 5060 if (ValType->isPointerType()) 5061 return true; 5062 if (!ValType->isFloatingType()) 5063 return false; 5064 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5065 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5066 &Context.getTargetInfo().getLongDoubleFormat() == 5067 &llvm::APFloat::x87DoubleExtended()) 5068 return false; 5069 return true; 5070 }; 5071 if (IsAddSub && !IsAllowedValueType(ValType)) { 5072 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5073 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5074 return ExprError(); 5075 } 5076 if (!IsAddSub && !ValType->isIntegerType()) { 5077 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5078 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5079 return ExprError(); 5080 } 5081 if (IsC11 && ValType->isPointerType() && 5082 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5083 diag::err_incomplete_type)) { 5084 return ExprError(); 5085 } 5086 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5087 // For __atomic_*_n operations, the value type must be a scalar integral or 5088 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5089 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5090 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5091 return ExprError(); 5092 } 5093 5094 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5095 !AtomTy->isScalarType()) { 5096 // For GNU atomics, require a trivially-copyable type. This is not part of 5097 // the GNU atomics specification, but we enforce it for sanity. 5098 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5099 << Ptr->getType() << Ptr->getSourceRange(); 5100 return ExprError(); 5101 } 5102 5103 switch (ValType.getObjCLifetime()) { 5104 case Qualifiers::OCL_None: 5105 case Qualifiers::OCL_ExplicitNone: 5106 // okay 5107 break; 5108 5109 case Qualifiers::OCL_Weak: 5110 case Qualifiers::OCL_Strong: 5111 case Qualifiers::OCL_Autoreleasing: 5112 // FIXME: Can this happen? By this point, ValType should be known 5113 // to be trivially copyable. 5114 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5115 << ValType << Ptr->getSourceRange(); 5116 return ExprError(); 5117 } 5118 5119 // All atomic operations have an overload which takes a pointer to a volatile 5120 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5121 // into the result or the other operands. Similarly atomic_load takes a 5122 // pointer to a const 'A'. 5123 ValType.removeLocalVolatile(); 5124 ValType.removeLocalConst(); 5125 QualType ResultType = ValType; 5126 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5127 Form == Init) 5128 ResultType = Context.VoidTy; 5129 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5130 ResultType = Context.BoolTy; 5131 5132 // The type of a parameter passed 'by value'. In the GNU atomics, such 5133 // arguments are actually passed as pointers. 5134 QualType ByValType = ValType; // 'CP' 5135 bool IsPassedByAddress = false; 5136 if (!IsC11 && !IsN) { 5137 ByValType = Ptr->getType(); 5138 IsPassedByAddress = true; 5139 } 5140 5141 SmallVector<Expr *, 5> APIOrderedArgs; 5142 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5143 APIOrderedArgs.push_back(Args[0]); 5144 switch (Form) { 5145 case Init: 5146 case Load: 5147 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5148 break; 5149 case LoadCopy: 5150 case Copy: 5151 case Arithmetic: 5152 case Xchg: 5153 APIOrderedArgs.push_back(Args[2]); // Val1 5154 APIOrderedArgs.push_back(Args[1]); // Order 5155 break; 5156 case GNUXchg: 5157 APIOrderedArgs.push_back(Args[2]); // Val1 5158 APIOrderedArgs.push_back(Args[3]); // Val2 5159 APIOrderedArgs.push_back(Args[1]); // Order 5160 break; 5161 case C11CmpXchg: 5162 APIOrderedArgs.push_back(Args[2]); // Val1 5163 APIOrderedArgs.push_back(Args[4]); // Val2 5164 APIOrderedArgs.push_back(Args[1]); // Order 5165 APIOrderedArgs.push_back(Args[3]); // OrderFail 5166 break; 5167 case GNUCmpXchg: 5168 APIOrderedArgs.push_back(Args[2]); // Val1 5169 APIOrderedArgs.push_back(Args[4]); // Val2 5170 APIOrderedArgs.push_back(Args[5]); // Weak 5171 APIOrderedArgs.push_back(Args[1]); // Order 5172 APIOrderedArgs.push_back(Args[3]); // OrderFail 5173 break; 5174 } 5175 } else 5176 APIOrderedArgs.append(Args.begin(), Args.end()); 5177 5178 // The first argument's non-CV pointer type is used to deduce the type of 5179 // subsequent arguments, except for: 5180 // - weak flag (always converted to bool) 5181 // - memory order (always converted to int) 5182 // - scope (always converted to int) 5183 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5184 QualType Ty; 5185 if (i < NumVals[Form] + 1) { 5186 switch (i) { 5187 case 0: 5188 // The first argument is always a pointer. It has a fixed type. 5189 // It is always dereferenced, a nullptr is undefined. 5190 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5191 // Nothing else to do: we already know all we want about this pointer. 5192 continue; 5193 case 1: 5194 // The second argument is the non-atomic operand. For arithmetic, this 5195 // is always passed by value, and for a compare_exchange it is always 5196 // passed by address. For the rest, GNU uses by-address and C11 uses 5197 // by-value. 5198 assert(Form != Load); 5199 if (Form == Arithmetic && ValType->isPointerType()) 5200 Ty = Context.getPointerDiffType(); 5201 else if (Form == Init || Form == Arithmetic) 5202 Ty = ValType; 5203 else if (Form == Copy || Form == Xchg) { 5204 if (IsPassedByAddress) { 5205 // The value pointer is always dereferenced, a nullptr is undefined. 5206 CheckNonNullArgument(*this, APIOrderedArgs[i], 5207 ExprRange.getBegin()); 5208 } 5209 Ty = ByValType; 5210 } else { 5211 Expr *ValArg = APIOrderedArgs[i]; 5212 // The value pointer is always dereferenced, a nullptr is undefined. 5213 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5214 LangAS AS = LangAS::Default; 5215 // Keep address space of non-atomic pointer type. 5216 if (const PointerType *PtrTy = 5217 ValArg->getType()->getAs<PointerType>()) { 5218 AS = PtrTy->getPointeeType().getAddressSpace(); 5219 } 5220 Ty = Context.getPointerType( 5221 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5222 } 5223 break; 5224 case 2: 5225 // The third argument to compare_exchange / GNU exchange is the desired 5226 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5227 if (IsPassedByAddress) 5228 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5229 Ty = ByValType; 5230 break; 5231 case 3: 5232 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5233 Ty = Context.BoolTy; 5234 break; 5235 } 5236 } else { 5237 // The order(s) and scope are always converted to int. 5238 Ty = Context.IntTy; 5239 } 5240 5241 InitializedEntity Entity = 5242 InitializedEntity::InitializeParameter(Context, Ty, false); 5243 ExprResult Arg = APIOrderedArgs[i]; 5244 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5245 if (Arg.isInvalid()) 5246 return true; 5247 APIOrderedArgs[i] = Arg.get(); 5248 } 5249 5250 // Permute the arguments into a 'consistent' order. 5251 SmallVector<Expr*, 5> SubExprs; 5252 SubExprs.push_back(Ptr); 5253 switch (Form) { 5254 case Init: 5255 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5256 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5257 break; 5258 case Load: 5259 SubExprs.push_back(APIOrderedArgs[1]); // Order 5260 break; 5261 case LoadCopy: 5262 case Copy: 5263 case Arithmetic: 5264 case Xchg: 5265 SubExprs.push_back(APIOrderedArgs[2]); // Order 5266 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5267 break; 5268 case GNUXchg: 5269 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5270 SubExprs.push_back(APIOrderedArgs[3]); // Order 5271 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5272 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5273 break; 5274 case C11CmpXchg: 5275 SubExprs.push_back(APIOrderedArgs[3]); // Order 5276 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5277 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5278 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5279 break; 5280 case GNUCmpXchg: 5281 SubExprs.push_back(APIOrderedArgs[4]); // Order 5282 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5283 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5284 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5285 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5286 break; 5287 } 5288 5289 if (SubExprs.size() >= 2 && Form != Init) { 5290 if (Optional<llvm::APSInt> Result = 5291 SubExprs[1]->getIntegerConstantExpr(Context)) 5292 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5293 Diag(SubExprs[1]->getBeginLoc(), 5294 diag::warn_atomic_op_has_invalid_memory_order) 5295 << SubExprs[1]->getSourceRange(); 5296 } 5297 5298 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5299 auto *Scope = Args[Args.size() - 1]; 5300 if (Optional<llvm::APSInt> Result = 5301 Scope->getIntegerConstantExpr(Context)) { 5302 if (!ScopeModel->isValid(Result->getZExtValue())) 5303 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5304 << Scope->getSourceRange(); 5305 } 5306 SubExprs.push_back(Scope); 5307 } 5308 5309 AtomicExpr *AE = new (Context) 5310 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5311 5312 if ((Op == AtomicExpr::AO__c11_atomic_load || 5313 Op == AtomicExpr::AO__c11_atomic_store || 5314 Op == AtomicExpr::AO__opencl_atomic_load || 5315 Op == AtomicExpr::AO__opencl_atomic_store ) && 5316 Context.AtomicUsesUnsupportedLibcall(AE)) 5317 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5318 << ((Op == AtomicExpr::AO__c11_atomic_load || 5319 Op == AtomicExpr::AO__opencl_atomic_load) 5320 ? 0 5321 : 1); 5322 5323 if (ValType->isExtIntType()) { 5324 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5325 return ExprError(); 5326 } 5327 5328 return AE; 5329 } 5330 5331 /// checkBuiltinArgument - Given a call to a builtin function, perform 5332 /// normal type-checking on the given argument, updating the call in 5333 /// place. This is useful when a builtin function requires custom 5334 /// type-checking for some of its arguments but not necessarily all of 5335 /// them. 5336 /// 5337 /// Returns true on error. 5338 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5339 FunctionDecl *Fn = E->getDirectCallee(); 5340 assert(Fn && "builtin call without direct callee!"); 5341 5342 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5343 InitializedEntity Entity = 5344 InitializedEntity::InitializeParameter(S.Context, Param); 5345 5346 ExprResult Arg = E->getArg(0); 5347 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5348 if (Arg.isInvalid()) 5349 return true; 5350 5351 E->setArg(ArgIndex, Arg.get()); 5352 return false; 5353 } 5354 5355 /// We have a call to a function like __sync_fetch_and_add, which is an 5356 /// overloaded function based on the pointer type of its first argument. 5357 /// The main BuildCallExpr routines have already promoted the types of 5358 /// arguments because all of these calls are prototyped as void(...). 5359 /// 5360 /// This function goes through and does final semantic checking for these 5361 /// builtins, as well as generating any warnings. 5362 ExprResult 5363 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5364 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5365 Expr *Callee = TheCall->getCallee(); 5366 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5367 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5368 5369 // Ensure that we have at least one argument to do type inference from. 5370 if (TheCall->getNumArgs() < 1) { 5371 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5372 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5373 return ExprError(); 5374 } 5375 5376 // Inspect the first argument of the atomic builtin. This should always be 5377 // a pointer type, whose element is an integral scalar or pointer type. 5378 // Because it is a pointer type, we don't have to worry about any implicit 5379 // casts here. 5380 // FIXME: We don't allow floating point scalars as input. 5381 Expr *FirstArg = TheCall->getArg(0); 5382 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5383 if (FirstArgResult.isInvalid()) 5384 return ExprError(); 5385 FirstArg = FirstArgResult.get(); 5386 TheCall->setArg(0, FirstArg); 5387 5388 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5389 if (!pointerType) { 5390 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5391 << FirstArg->getType() << FirstArg->getSourceRange(); 5392 return ExprError(); 5393 } 5394 5395 QualType ValType = pointerType->getPointeeType(); 5396 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5397 !ValType->isBlockPointerType()) { 5398 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5399 << FirstArg->getType() << FirstArg->getSourceRange(); 5400 return ExprError(); 5401 } 5402 5403 if (ValType.isConstQualified()) { 5404 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5405 << FirstArg->getType() << FirstArg->getSourceRange(); 5406 return ExprError(); 5407 } 5408 5409 switch (ValType.getObjCLifetime()) { 5410 case Qualifiers::OCL_None: 5411 case Qualifiers::OCL_ExplicitNone: 5412 // okay 5413 break; 5414 5415 case Qualifiers::OCL_Weak: 5416 case Qualifiers::OCL_Strong: 5417 case Qualifiers::OCL_Autoreleasing: 5418 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5419 << ValType << FirstArg->getSourceRange(); 5420 return ExprError(); 5421 } 5422 5423 // Strip any qualifiers off ValType. 5424 ValType = ValType.getUnqualifiedType(); 5425 5426 // The majority of builtins return a value, but a few have special return 5427 // types, so allow them to override appropriately below. 5428 QualType ResultType = ValType; 5429 5430 // We need to figure out which concrete builtin this maps onto. For example, 5431 // __sync_fetch_and_add with a 2 byte object turns into 5432 // __sync_fetch_and_add_2. 5433 #define BUILTIN_ROW(x) \ 5434 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5435 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5436 5437 static const unsigned BuiltinIndices[][5] = { 5438 BUILTIN_ROW(__sync_fetch_and_add), 5439 BUILTIN_ROW(__sync_fetch_and_sub), 5440 BUILTIN_ROW(__sync_fetch_and_or), 5441 BUILTIN_ROW(__sync_fetch_and_and), 5442 BUILTIN_ROW(__sync_fetch_and_xor), 5443 BUILTIN_ROW(__sync_fetch_and_nand), 5444 5445 BUILTIN_ROW(__sync_add_and_fetch), 5446 BUILTIN_ROW(__sync_sub_and_fetch), 5447 BUILTIN_ROW(__sync_and_and_fetch), 5448 BUILTIN_ROW(__sync_or_and_fetch), 5449 BUILTIN_ROW(__sync_xor_and_fetch), 5450 BUILTIN_ROW(__sync_nand_and_fetch), 5451 5452 BUILTIN_ROW(__sync_val_compare_and_swap), 5453 BUILTIN_ROW(__sync_bool_compare_and_swap), 5454 BUILTIN_ROW(__sync_lock_test_and_set), 5455 BUILTIN_ROW(__sync_lock_release), 5456 BUILTIN_ROW(__sync_swap) 5457 }; 5458 #undef BUILTIN_ROW 5459 5460 // Determine the index of the size. 5461 unsigned SizeIndex; 5462 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5463 case 1: SizeIndex = 0; break; 5464 case 2: SizeIndex = 1; break; 5465 case 4: SizeIndex = 2; break; 5466 case 8: SizeIndex = 3; break; 5467 case 16: SizeIndex = 4; break; 5468 default: 5469 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5470 << FirstArg->getType() << FirstArg->getSourceRange(); 5471 return ExprError(); 5472 } 5473 5474 // Each of these builtins has one pointer argument, followed by some number of 5475 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5476 // that we ignore. Find out which row of BuiltinIndices to read from as well 5477 // as the number of fixed args. 5478 unsigned BuiltinID = FDecl->getBuiltinID(); 5479 unsigned BuiltinIndex, NumFixed = 1; 5480 bool WarnAboutSemanticsChange = false; 5481 switch (BuiltinID) { 5482 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5483 case Builtin::BI__sync_fetch_and_add: 5484 case Builtin::BI__sync_fetch_and_add_1: 5485 case Builtin::BI__sync_fetch_and_add_2: 5486 case Builtin::BI__sync_fetch_and_add_4: 5487 case Builtin::BI__sync_fetch_and_add_8: 5488 case Builtin::BI__sync_fetch_and_add_16: 5489 BuiltinIndex = 0; 5490 break; 5491 5492 case Builtin::BI__sync_fetch_and_sub: 5493 case Builtin::BI__sync_fetch_and_sub_1: 5494 case Builtin::BI__sync_fetch_and_sub_2: 5495 case Builtin::BI__sync_fetch_and_sub_4: 5496 case Builtin::BI__sync_fetch_and_sub_8: 5497 case Builtin::BI__sync_fetch_and_sub_16: 5498 BuiltinIndex = 1; 5499 break; 5500 5501 case Builtin::BI__sync_fetch_and_or: 5502 case Builtin::BI__sync_fetch_and_or_1: 5503 case Builtin::BI__sync_fetch_and_or_2: 5504 case Builtin::BI__sync_fetch_and_or_4: 5505 case Builtin::BI__sync_fetch_and_or_8: 5506 case Builtin::BI__sync_fetch_and_or_16: 5507 BuiltinIndex = 2; 5508 break; 5509 5510 case Builtin::BI__sync_fetch_and_and: 5511 case Builtin::BI__sync_fetch_and_and_1: 5512 case Builtin::BI__sync_fetch_and_and_2: 5513 case Builtin::BI__sync_fetch_and_and_4: 5514 case Builtin::BI__sync_fetch_and_and_8: 5515 case Builtin::BI__sync_fetch_and_and_16: 5516 BuiltinIndex = 3; 5517 break; 5518 5519 case Builtin::BI__sync_fetch_and_xor: 5520 case Builtin::BI__sync_fetch_and_xor_1: 5521 case Builtin::BI__sync_fetch_and_xor_2: 5522 case Builtin::BI__sync_fetch_and_xor_4: 5523 case Builtin::BI__sync_fetch_and_xor_8: 5524 case Builtin::BI__sync_fetch_and_xor_16: 5525 BuiltinIndex = 4; 5526 break; 5527 5528 case Builtin::BI__sync_fetch_and_nand: 5529 case Builtin::BI__sync_fetch_and_nand_1: 5530 case Builtin::BI__sync_fetch_and_nand_2: 5531 case Builtin::BI__sync_fetch_and_nand_4: 5532 case Builtin::BI__sync_fetch_and_nand_8: 5533 case Builtin::BI__sync_fetch_and_nand_16: 5534 BuiltinIndex = 5; 5535 WarnAboutSemanticsChange = true; 5536 break; 5537 5538 case Builtin::BI__sync_add_and_fetch: 5539 case Builtin::BI__sync_add_and_fetch_1: 5540 case Builtin::BI__sync_add_and_fetch_2: 5541 case Builtin::BI__sync_add_and_fetch_4: 5542 case Builtin::BI__sync_add_and_fetch_8: 5543 case Builtin::BI__sync_add_and_fetch_16: 5544 BuiltinIndex = 6; 5545 break; 5546 5547 case Builtin::BI__sync_sub_and_fetch: 5548 case Builtin::BI__sync_sub_and_fetch_1: 5549 case Builtin::BI__sync_sub_and_fetch_2: 5550 case Builtin::BI__sync_sub_and_fetch_4: 5551 case Builtin::BI__sync_sub_and_fetch_8: 5552 case Builtin::BI__sync_sub_and_fetch_16: 5553 BuiltinIndex = 7; 5554 break; 5555 5556 case Builtin::BI__sync_and_and_fetch: 5557 case Builtin::BI__sync_and_and_fetch_1: 5558 case Builtin::BI__sync_and_and_fetch_2: 5559 case Builtin::BI__sync_and_and_fetch_4: 5560 case Builtin::BI__sync_and_and_fetch_8: 5561 case Builtin::BI__sync_and_and_fetch_16: 5562 BuiltinIndex = 8; 5563 break; 5564 5565 case Builtin::BI__sync_or_and_fetch: 5566 case Builtin::BI__sync_or_and_fetch_1: 5567 case Builtin::BI__sync_or_and_fetch_2: 5568 case Builtin::BI__sync_or_and_fetch_4: 5569 case Builtin::BI__sync_or_and_fetch_8: 5570 case Builtin::BI__sync_or_and_fetch_16: 5571 BuiltinIndex = 9; 5572 break; 5573 5574 case Builtin::BI__sync_xor_and_fetch: 5575 case Builtin::BI__sync_xor_and_fetch_1: 5576 case Builtin::BI__sync_xor_and_fetch_2: 5577 case Builtin::BI__sync_xor_and_fetch_4: 5578 case Builtin::BI__sync_xor_and_fetch_8: 5579 case Builtin::BI__sync_xor_and_fetch_16: 5580 BuiltinIndex = 10; 5581 break; 5582 5583 case Builtin::BI__sync_nand_and_fetch: 5584 case Builtin::BI__sync_nand_and_fetch_1: 5585 case Builtin::BI__sync_nand_and_fetch_2: 5586 case Builtin::BI__sync_nand_and_fetch_4: 5587 case Builtin::BI__sync_nand_and_fetch_8: 5588 case Builtin::BI__sync_nand_and_fetch_16: 5589 BuiltinIndex = 11; 5590 WarnAboutSemanticsChange = true; 5591 break; 5592 5593 case Builtin::BI__sync_val_compare_and_swap: 5594 case Builtin::BI__sync_val_compare_and_swap_1: 5595 case Builtin::BI__sync_val_compare_and_swap_2: 5596 case Builtin::BI__sync_val_compare_and_swap_4: 5597 case Builtin::BI__sync_val_compare_and_swap_8: 5598 case Builtin::BI__sync_val_compare_and_swap_16: 5599 BuiltinIndex = 12; 5600 NumFixed = 2; 5601 break; 5602 5603 case Builtin::BI__sync_bool_compare_and_swap: 5604 case Builtin::BI__sync_bool_compare_and_swap_1: 5605 case Builtin::BI__sync_bool_compare_and_swap_2: 5606 case Builtin::BI__sync_bool_compare_and_swap_4: 5607 case Builtin::BI__sync_bool_compare_and_swap_8: 5608 case Builtin::BI__sync_bool_compare_and_swap_16: 5609 BuiltinIndex = 13; 5610 NumFixed = 2; 5611 ResultType = Context.BoolTy; 5612 break; 5613 5614 case Builtin::BI__sync_lock_test_and_set: 5615 case Builtin::BI__sync_lock_test_and_set_1: 5616 case Builtin::BI__sync_lock_test_and_set_2: 5617 case Builtin::BI__sync_lock_test_and_set_4: 5618 case Builtin::BI__sync_lock_test_and_set_8: 5619 case Builtin::BI__sync_lock_test_and_set_16: 5620 BuiltinIndex = 14; 5621 break; 5622 5623 case Builtin::BI__sync_lock_release: 5624 case Builtin::BI__sync_lock_release_1: 5625 case Builtin::BI__sync_lock_release_2: 5626 case Builtin::BI__sync_lock_release_4: 5627 case Builtin::BI__sync_lock_release_8: 5628 case Builtin::BI__sync_lock_release_16: 5629 BuiltinIndex = 15; 5630 NumFixed = 0; 5631 ResultType = Context.VoidTy; 5632 break; 5633 5634 case Builtin::BI__sync_swap: 5635 case Builtin::BI__sync_swap_1: 5636 case Builtin::BI__sync_swap_2: 5637 case Builtin::BI__sync_swap_4: 5638 case Builtin::BI__sync_swap_8: 5639 case Builtin::BI__sync_swap_16: 5640 BuiltinIndex = 16; 5641 break; 5642 } 5643 5644 // Now that we know how many fixed arguments we expect, first check that we 5645 // have at least that many. 5646 if (TheCall->getNumArgs() < 1+NumFixed) { 5647 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5648 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5649 << Callee->getSourceRange(); 5650 return ExprError(); 5651 } 5652 5653 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5654 << Callee->getSourceRange(); 5655 5656 if (WarnAboutSemanticsChange) { 5657 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5658 << Callee->getSourceRange(); 5659 } 5660 5661 // Get the decl for the concrete builtin from this, we can tell what the 5662 // concrete integer type we should convert to is. 5663 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5664 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5665 FunctionDecl *NewBuiltinDecl; 5666 if (NewBuiltinID == BuiltinID) 5667 NewBuiltinDecl = FDecl; 5668 else { 5669 // Perform builtin lookup to avoid redeclaring it. 5670 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5671 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5672 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5673 assert(Res.getFoundDecl()); 5674 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5675 if (!NewBuiltinDecl) 5676 return ExprError(); 5677 } 5678 5679 // The first argument --- the pointer --- has a fixed type; we 5680 // deduce the types of the rest of the arguments accordingly. Walk 5681 // the remaining arguments, converting them to the deduced value type. 5682 for (unsigned i = 0; i != NumFixed; ++i) { 5683 ExprResult Arg = TheCall->getArg(i+1); 5684 5685 // GCC does an implicit conversion to the pointer or integer ValType. This 5686 // can fail in some cases (1i -> int**), check for this error case now. 5687 // Initialize the argument. 5688 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5689 ValType, /*consume*/ false); 5690 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5691 if (Arg.isInvalid()) 5692 return ExprError(); 5693 5694 // Okay, we have something that *can* be converted to the right type. Check 5695 // to see if there is a potentially weird extension going on here. This can 5696 // happen when you do an atomic operation on something like an char* and 5697 // pass in 42. The 42 gets converted to char. This is even more strange 5698 // for things like 45.123 -> char, etc. 5699 // FIXME: Do this check. 5700 TheCall->setArg(i+1, Arg.get()); 5701 } 5702 5703 // Create a new DeclRefExpr to refer to the new decl. 5704 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5705 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5706 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5707 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5708 5709 // Set the callee in the CallExpr. 5710 // FIXME: This loses syntactic information. 5711 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5712 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5713 CK_BuiltinFnToFnPtr); 5714 TheCall->setCallee(PromotedCall.get()); 5715 5716 // Change the result type of the call to match the original value type. This 5717 // is arbitrary, but the codegen for these builtins ins design to handle it 5718 // gracefully. 5719 TheCall->setType(ResultType); 5720 5721 // Prohibit use of _ExtInt with atomic builtins. 5722 // The arguments would have already been converted to the first argument's 5723 // type, so only need to check the first argument. 5724 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5725 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5726 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5727 return ExprError(); 5728 } 5729 5730 return TheCallResult; 5731 } 5732 5733 /// SemaBuiltinNontemporalOverloaded - We have a call to 5734 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5735 /// overloaded function based on the pointer type of its last argument. 5736 /// 5737 /// This function goes through and does final semantic checking for these 5738 /// builtins. 5739 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5740 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5741 DeclRefExpr *DRE = 5742 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5743 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5744 unsigned BuiltinID = FDecl->getBuiltinID(); 5745 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5746 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5747 "Unexpected nontemporal load/store builtin!"); 5748 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5749 unsigned numArgs = isStore ? 2 : 1; 5750 5751 // Ensure that we have the proper number of arguments. 5752 if (checkArgCount(*this, TheCall, numArgs)) 5753 return ExprError(); 5754 5755 // Inspect the last argument of the nontemporal builtin. This should always 5756 // be a pointer type, from which we imply the type of the memory access. 5757 // Because it is a pointer type, we don't have to worry about any implicit 5758 // casts here. 5759 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5760 ExprResult PointerArgResult = 5761 DefaultFunctionArrayLvalueConversion(PointerArg); 5762 5763 if (PointerArgResult.isInvalid()) 5764 return ExprError(); 5765 PointerArg = PointerArgResult.get(); 5766 TheCall->setArg(numArgs - 1, PointerArg); 5767 5768 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5769 if (!pointerType) { 5770 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5771 << PointerArg->getType() << PointerArg->getSourceRange(); 5772 return ExprError(); 5773 } 5774 5775 QualType ValType = pointerType->getPointeeType(); 5776 5777 // Strip any qualifiers off ValType. 5778 ValType = ValType.getUnqualifiedType(); 5779 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5780 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5781 !ValType->isVectorType()) { 5782 Diag(DRE->getBeginLoc(), 5783 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5784 << PointerArg->getType() << PointerArg->getSourceRange(); 5785 return ExprError(); 5786 } 5787 5788 if (!isStore) { 5789 TheCall->setType(ValType); 5790 return TheCallResult; 5791 } 5792 5793 ExprResult ValArg = TheCall->getArg(0); 5794 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5795 Context, ValType, /*consume*/ false); 5796 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5797 if (ValArg.isInvalid()) 5798 return ExprError(); 5799 5800 TheCall->setArg(0, ValArg.get()); 5801 TheCall->setType(Context.VoidTy); 5802 return TheCallResult; 5803 } 5804 5805 /// CheckObjCString - Checks that the argument to the builtin 5806 /// CFString constructor is correct 5807 /// Note: It might also make sense to do the UTF-16 conversion here (would 5808 /// simplify the backend). 5809 bool Sema::CheckObjCString(Expr *Arg) { 5810 Arg = Arg->IgnoreParenCasts(); 5811 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5812 5813 if (!Literal || !Literal->isAscii()) { 5814 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5815 << Arg->getSourceRange(); 5816 return true; 5817 } 5818 5819 if (Literal->containsNonAsciiOrNull()) { 5820 StringRef String = Literal->getString(); 5821 unsigned NumBytes = String.size(); 5822 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5823 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5824 llvm::UTF16 *ToPtr = &ToBuf[0]; 5825 5826 llvm::ConversionResult Result = 5827 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5828 ToPtr + NumBytes, llvm::strictConversion); 5829 // Check for conversion failure. 5830 if (Result != llvm::conversionOK) 5831 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5832 << Arg->getSourceRange(); 5833 } 5834 return false; 5835 } 5836 5837 /// CheckObjCString - Checks that the format string argument to the os_log() 5838 /// and os_trace() functions is correct, and converts it to const char *. 5839 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5840 Arg = Arg->IgnoreParenCasts(); 5841 auto *Literal = dyn_cast<StringLiteral>(Arg); 5842 if (!Literal) { 5843 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5844 Literal = ObjcLiteral->getString(); 5845 } 5846 } 5847 5848 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5849 return ExprError( 5850 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5851 << Arg->getSourceRange()); 5852 } 5853 5854 ExprResult Result(Literal); 5855 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5856 InitializedEntity Entity = 5857 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5858 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5859 return Result; 5860 } 5861 5862 /// Check that the user is calling the appropriate va_start builtin for the 5863 /// target and calling convention. 5864 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5865 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5866 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5867 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5868 TT.getArch() == llvm::Triple::aarch64_32); 5869 bool IsWindows = TT.isOSWindows(); 5870 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5871 if (IsX64 || IsAArch64) { 5872 CallingConv CC = CC_C; 5873 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5874 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5875 if (IsMSVAStart) { 5876 // Don't allow this in System V ABI functions. 5877 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5878 return S.Diag(Fn->getBeginLoc(), 5879 diag::err_ms_va_start_used_in_sysv_function); 5880 } else { 5881 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5882 // On x64 Windows, don't allow this in System V ABI functions. 5883 // (Yes, that means there's no corresponding way to support variadic 5884 // System V ABI functions on Windows.) 5885 if ((IsWindows && CC == CC_X86_64SysV) || 5886 (!IsWindows && CC == CC_Win64)) 5887 return S.Diag(Fn->getBeginLoc(), 5888 diag::err_va_start_used_in_wrong_abi_function) 5889 << !IsWindows; 5890 } 5891 return false; 5892 } 5893 5894 if (IsMSVAStart) 5895 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5896 return false; 5897 } 5898 5899 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5900 ParmVarDecl **LastParam = nullptr) { 5901 // Determine whether the current function, block, or obj-c method is variadic 5902 // and get its parameter list. 5903 bool IsVariadic = false; 5904 ArrayRef<ParmVarDecl *> Params; 5905 DeclContext *Caller = S.CurContext; 5906 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5907 IsVariadic = Block->isVariadic(); 5908 Params = Block->parameters(); 5909 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5910 IsVariadic = FD->isVariadic(); 5911 Params = FD->parameters(); 5912 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5913 IsVariadic = MD->isVariadic(); 5914 // FIXME: This isn't correct for methods (results in bogus warning). 5915 Params = MD->parameters(); 5916 } else if (isa<CapturedDecl>(Caller)) { 5917 // We don't support va_start in a CapturedDecl. 5918 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5919 return true; 5920 } else { 5921 // This must be some other declcontext that parses exprs. 5922 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5923 return true; 5924 } 5925 5926 if (!IsVariadic) { 5927 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5928 return true; 5929 } 5930 5931 if (LastParam) 5932 *LastParam = Params.empty() ? nullptr : Params.back(); 5933 5934 return false; 5935 } 5936 5937 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5938 /// for validity. Emit an error and return true on failure; return false 5939 /// on success. 5940 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5941 Expr *Fn = TheCall->getCallee(); 5942 5943 if (checkVAStartABI(*this, BuiltinID, Fn)) 5944 return true; 5945 5946 if (checkArgCount(*this, TheCall, 2)) 5947 return true; 5948 5949 // Type-check the first argument normally. 5950 if (checkBuiltinArgument(*this, TheCall, 0)) 5951 return true; 5952 5953 // Check that the current function is variadic, and get its last parameter. 5954 ParmVarDecl *LastParam; 5955 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5956 return true; 5957 5958 // Verify that the second argument to the builtin is the last argument of the 5959 // current function or method. 5960 bool SecondArgIsLastNamedArgument = false; 5961 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5962 5963 // These are valid if SecondArgIsLastNamedArgument is false after the next 5964 // block. 5965 QualType Type; 5966 SourceLocation ParamLoc; 5967 bool IsCRegister = false; 5968 5969 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5970 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5971 SecondArgIsLastNamedArgument = PV == LastParam; 5972 5973 Type = PV->getType(); 5974 ParamLoc = PV->getLocation(); 5975 IsCRegister = 5976 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5977 } 5978 } 5979 5980 if (!SecondArgIsLastNamedArgument) 5981 Diag(TheCall->getArg(1)->getBeginLoc(), 5982 diag::warn_second_arg_of_va_start_not_last_named_param); 5983 else if (IsCRegister || Type->isReferenceType() || 5984 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5985 // Promotable integers are UB, but enumerations need a bit of 5986 // extra checking to see what their promotable type actually is. 5987 if (!Type->isPromotableIntegerType()) 5988 return false; 5989 if (!Type->isEnumeralType()) 5990 return true; 5991 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5992 return !(ED && 5993 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5994 }()) { 5995 unsigned Reason = 0; 5996 if (Type->isReferenceType()) Reason = 1; 5997 else if (IsCRegister) Reason = 2; 5998 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5999 Diag(ParamLoc, diag::note_parameter_type) << Type; 6000 } 6001 6002 TheCall->setType(Context.VoidTy); 6003 return false; 6004 } 6005 6006 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6007 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6008 // const char *named_addr); 6009 6010 Expr *Func = Call->getCallee(); 6011 6012 if (Call->getNumArgs() < 3) 6013 return Diag(Call->getEndLoc(), 6014 diag::err_typecheck_call_too_few_args_at_least) 6015 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6016 6017 // Type-check the first argument normally. 6018 if (checkBuiltinArgument(*this, Call, 0)) 6019 return true; 6020 6021 // Check that the current function is variadic. 6022 if (checkVAStartIsInVariadicFunction(*this, Func)) 6023 return true; 6024 6025 // __va_start on Windows does not validate the parameter qualifiers 6026 6027 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6028 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6029 6030 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6031 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6032 6033 const QualType &ConstCharPtrTy = 6034 Context.getPointerType(Context.CharTy.withConst()); 6035 if (!Arg1Ty->isPointerType() || 6036 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 6037 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6038 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6039 << 0 /* qualifier difference */ 6040 << 3 /* parameter mismatch */ 6041 << 2 << Arg1->getType() << ConstCharPtrTy; 6042 6043 const QualType SizeTy = Context.getSizeType(); 6044 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6045 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6046 << Arg2->getType() << SizeTy << 1 /* different class */ 6047 << 0 /* qualifier difference */ 6048 << 3 /* parameter mismatch */ 6049 << 3 << Arg2->getType() << SizeTy; 6050 6051 return false; 6052 } 6053 6054 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6055 /// friends. This is declared to take (...), so we have to check everything. 6056 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6057 if (checkArgCount(*this, TheCall, 2)) 6058 return true; 6059 6060 ExprResult OrigArg0 = TheCall->getArg(0); 6061 ExprResult OrigArg1 = TheCall->getArg(1); 6062 6063 // Do standard promotions between the two arguments, returning their common 6064 // type. 6065 QualType Res = UsualArithmeticConversions( 6066 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6067 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6068 return true; 6069 6070 // Make sure any conversions are pushed back into the call; this is 6071 // type safe since unordered compare builtins are declared as "_Bool 6072 // foo(...)". 6073 TheCall->setArg(0, OrigArg0.get()); 6074 TheCall->setArg(1, OrigArg1.get()); 6075 6076 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6077 return false; 6078 6079 // If the common type isn't a real floating type, then the arguments were 6080 // invalid for this operation. 6081 if (Res.isNull() || !Res->isRealFloatingType()) 6082 return Diag(OrigArg0.get()->getBeginLoc(), 6083 diag::err_typecheck_call_invalid_ordered_compare) 6084 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6085 << SourceRange(OrigArg0.get()->getBeginLoc(), 6086 OrigArg1.get()->getEndLoc()); 6087 6088 return false; 6089 } 6090 6091 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6092 /// __builtin_isnan and friends. This is declared to take (...), so we have 6093 /// to check everything. We expect the last argument to be a floating point 6094 /// value. 6095 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6096 if (checkArgCount(*this, TheCall, NumArgs)) 6097 return true; 6098 6099 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6100 // on all preceding parameters just being int. Try all of those. 6101 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6102 Expr *Arg = TheCall->getArg(i); 6103 6104 if (Arg->isTypeDependent()) 6105 return false; 6106 6107 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6108 6109 if (Res.isInvalid()) 6110 return true; 6111 TheCall->setArg(i, Res.get()); 6112 } 6113 6114 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6115 6116 if (OrigArg->isTypeDependent()) 6117 return false; 6118 6119 // Usual Unary Conversions will convert half to float, which we want for 6120 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6121 // type how it is, but do normal L->Rvalue conversions. 6122 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6123 OrigArg = UsualUnaryConversions(OrigArg).get(); 6124 else 6125 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6126 TheCall->setArg(NumArgs - 1, OrigArg); 6127 6128 // This operation requires a non-_Complex floating-point number. 6129 if (!OrigArg->getType()->isRealFloatingType()) 6130 return Diag(OrigArg->getBeginLoc(), 6131 diag::err_typecheck_call_invalid_unary_fp) 6132 << OrigArg->getType() << OrigArg->getSourceRange(); 6133 6134 return false; 6135 } 6136 6137 /// Perform semantic analysis for a call to __builtin_complex. 6138 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6139 if (checkArgCount(*this, TheCall, 2)) 6140 return true; 6141 6142 bool Dependent = false; 6143 for (unsigned I = 0; I != 2; ++I) { 6144 Expr *Arg = TheCall->getArg(I); 6145 QualType T = Arg->getType(); 6146 if (T->isDependentType()) { 6147 Dependent = true; 6148 continue; 6149 } 6150 6151 // Despite supporting _Complex int, GCC requires a real floating point type 6152 // for the operands of __builtin_complex. 6153 if (!T->isRealFloatingType()) { 6154 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6155 << Arg->getType() << Arg->getSourceRange(); 6156 } 6157 6158 ExprResult Converted = DefaultLvalueConversion(Arg); 6159 if (Converted.isInvalid()) 6160 return true; 6161 TheCall->setArg(I, Converted.get()); 6162 } 6163 6164 if (Dependent) { 6165 TheCall->setType(Context.DependentTy); 6166 return false; 6167 } 6168 6169 Expr *Real = TheCall->getArg(0); 6170 Expr *Imag = TheCall->getArg(1); 6171 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6172 return Diag(Real->getBeginLoc(), 6173 diag::err_typecheck_call_different_arg_types) 6174 << Real->getType() << Imag->getType() 6175 << Real->getSourceRange() << Imag->getSourceRange(); 6176 } 6177 6178 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6179 // don't allow this builtin to form those types either. 6180 // FIXME: Should we allow these types? 6181 if (Real->getType()->isFloat16Type()) 6182 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6183 << "_Float16"; 6184 if (Real->getType()->isHalfType()) 6185 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6186 << "half"; 6187 6188 TheCall->setType(Context.getComplexType(Real->getType())); 6189 return false; 6190 } 6191 6192 // Customized Sema Checking for VSX builtins that have the following signature: 6193 // vector [...] builtinName(vector [...], vector [...], const int); 6194 // Which takes the same type of vectors (any legal vector type) for the first 6195 // two arguments and takes compile time constant for the third argument. 6196 // Example builtins are : 6197 // vector double vec_xxpermdi(vector double, vector double, int); 6198 // vector short vec_xxsldwi(vector short, vector short, int); 6199 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6200 unsigned ExpectedNumArgs = 3; 6201 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6202 return true; 6203 6204 // Check the third argument is a compile time constant 6205 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6206 return Diag(TheCall->getBeginLoc(), 6207 diag::err_vsx_builtin_nonconstant_argument) 6208 << 3 /* argument index */ << TheCall->getDirectCallee() 6209 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6210 TheCall->getArg(2)->getEndLoc()); 6211 6212 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6213 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6214 6215 // Check the type of argument 1 and argument 2 are vectors. 6216 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6217 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6218 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6219 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6220 << TheCall->getDirectCallee() 6221 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6222 TheCall->getArg(1)->getEndLoc()); 6223 } 6224 6225 // Check the first two arguments are the same type. 6226 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6227 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6228 << TheCall->getDirectCallee() 6229 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6230 TheCall->getArg(1)->getEndLoc()); 6231 } 6232 6233 // When default clang type checking is turned off and the customized type 6234 // checking is used, the returning type of the function must be explicitly 6235 // set. Otherwise it is _Bool by default. 6236 TheCall->setType(Arg1Ty); 6237 6238 return false; 6239 } 6240 6241 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6242 // This is declared to take (...), so we have to check everything. 6243 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6244 if (TheCall->getNumArgs() < 2) 6245 return ExprError(Diag(TheCall->getEndLoc(), 6246 diag::err_typecheck_call_too_few_args_at_least) 6247 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6248 << TheCall->getSourceRange()); 6249 6250 // Determine which of the following types of shufflevector we're checking: 6251 // 1) unary, vector mask: (lhs, mask) 6252 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6253 QualType resType = TheCall->getArg(0)->getType(); 6254 unsigned numElements = 0; 6255 6256 if (!TheCall->getArg(0)->isTypeDependent() && 6257 !TheCall->getArg(1)->isTypeDependent()) { 6258 QualType LHSType = TheCall->getArg(0)->getType(); 6259 QualType RHSType = TheCall->getArg(1)->getType(); 6260 6261 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6262 return ExprError( 6263 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6264 << TheCall->getDirectCallee() 6265 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6266 TheCall->getArg(1)->getEndLoc())); 6267 6268 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6269 unsigned numResElements = TheCall->getNumArgs() - 2; 6270 6271 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6272 // with mask. If so, verify that RHS is an integer vector type with the 6273 // same number of elts as lhs. 6274 if (TheCall->getNumArgs() == 2) { 6275 if (!RHSType->hasIntegerRepresentation() || 6276 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6277 return ExprError(Diag(TheCall->getBeginLoc(), 6278 diag::err_vec_builtin_incompatible_vector) 6279 << TheCall->getDirectCallee() 6280 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6281 TheCall->getArg(1)->getEndLoc())); 6282 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6283 return ExprError(Diag(TheCall->getBeginLoc(), 6284 diag::err_vec_builtin_incompatible_vector) 6285 << TheCall->getDirectCallee() 6286 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6287 TheCall->getArg(1)->getEndLoc())); 6288 } else if (numElements != numResElements) { 6289 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6290 resType = Context.getVectorType(eltType, numResElements, 6291 VectorType::GenericVector); 6292 } 6293 } 6294 6295 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6296 if (TheCall->getArg(i)->isTypeDependent() || 6297 TheCall->getArg(i)->isValueDependent()) 6298 continue; 6299 6300 Optional<llvm::APSInt> Result; 6301 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6302 return ExprError(Diag(TheCall->getBeginLoc(), 6303 diag::err_shufflevector_nonconstant_argument) 6304 << TheCall->getArg(i)->getSourceRange()); 6305 6306 // Allow -1 which will be translated to undef in the IR. 6307 if (Result->isSigned() && Result->isAllOnesValue()) 6308 continue; 6309 6310 if (Result->getActiveBits() > 64 || 6311 Result->getZExtValue() >= numElements * 2) 6312 return ExprError(Diag(TheCall->getBeginLoc(), 6313 diag::err_shufflevector_argument_too_large) 6314 << TheCall->getArg(i)->getSourceRange()); 6315 } 6316 6317 SmallVector<Expr*, 32> exprs; 6318 6319 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6320 exprs.push_back(TheCall->getArg(i)); 6321 TheCall->setArg(i, nullptr); 6322 } 6323 6324 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6325 TheCall->getCallee()->getBeginLoc(), 6326 TheCall->getRParenLoc()); 6327 } 6328 6329 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6330 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6331 SourceLocation BuiltinLoc, 6332 SourceLocation RParenLoc) { 6333 ExprValueKind VK = VK_RValue; 6334 ExprObjectKind OK = OK_Ordinary; 6335 QualType DstTy = TInfo->getType(); 6336 QualType SrcTy = E->getType(); 6337 6338 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6339 return ExprError(Diag(BuiltinLoc, 6340 diag::err_convertvector_non_vector) 6341 << E->getSourceRange()); 6342 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6343 return ExprError(Diag(BuiltinLoc, 6344 diag::err_convertvector_non_vector_type)); 6345 6346 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6347 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6348 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6349 if (SrcElts != DstElts) 6350 return ExprError(Diag(BuiltinLoc, 6351 diag::err_convertvector_incompatible_vector) 6352 << E->getSourceRange()); 6353 } 6354 6355 return new (Context) 6356 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6357 } 6358 6359 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6360 // This is declared to take (const void*, ...) and can take two 6361 // optional constant int args. 6362 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6363 unsigned NumArgs = TheCall->getNumArgs(); 6364 6365 if (NumArgs > 3) 6366 return Diag(TheCall->getEndLoc(), 6367 diag::err_typecheck_call_too_many_args_at_most) 6368 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6369 6370 // Argument 0 is checked for us and the remaining arguments must be 6371 // constant integers. 6372 for (unsigned i = 1; i != NumArgs; ++i) 6373 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6374 return true; 6375 6376 return false; 6377 } 6378 6379 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6380 // __assume does not evaluate its arguments, and should warn if its argument 6381 // has side effects. 6382 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6383 Expr *Arg = TheCall->getArg(0); 6384 if (Arg->isInstantiationDependent()) return false; 6385 6386 if (Arg->HasSideEffects(Context)) 6387 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6388 << Arg->getSourceRange() 6389 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6390 6391 return false; 6392 } 6393 6394 /// Handle __builtin_alloca_with_align. This is declared 6395 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6396 /// than 8. 6397 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6398 // The alignment must be a constant integer. 6399 Expr *Arg = TheCall->getArg(1); 6400 6401 // We can't check the value of a dependent argument. 6402 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6403 if (const auto *UE = 6404 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6405 if (UE->getKind() == UETT_AlignOf || 6406 UE->getKind() == UETT_PreferredAlignOf) 6407 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6408 << Arg->getSourceRange(); 6409 6410 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6411 6412 if (!Result.isPowerOf2()) 6413 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6414 << Arg->getSourceRange(); 6415 6416 if (Result < Context.getCharWidth()) 6417 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6418 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6419 6420 if (Result > std::numeric_limits<int32_t>::max()) 6421 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6422 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6423 } 6424 6425 return false; 6426 } 6427 6428 /// Handle __builtin_assume_aligned. This is declared 6429 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6430 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6431 unsigned NumArgs = TheCall->getNumArgs(); 6432 6433 if (NumArgs > 3) 6434 return Diag(TheCall->getEndLoc(), 6435 diag::err_typecheck_call_too_many_args_at_most) 6436 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6437 6438 // The alignment must be a constant integer. 6439 Expr *Arg = TheCall->getArg(1); 6440 6441 // We can't check the value of a dependent argument. 6442 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6443 llvm::APSInt Result; 6444 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6445 return true; 6446 6447 if (!Result.isPowerOf2()) 6448 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6449 << Arg->getSourceRange(); 6450 6451 if (Result > Sema::MaximumAlignment) 6452 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6453 << Arg->getSourceRange() << Sema::MaximumAlignment; 6454 } 6455 6456 if (NumArgs > 2) { 6457 ExprResult Arg(TheCall->getArg(2)); 6458 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6459 Context.getSizeType(), false); 6460 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6461 if (Arg.isInvalid()) return true; 6462 TheCall->setArg(2, Arg.get()); 6463 } 6464 6465 return false; 6466 } 6467 6468 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6469 unsigned BuiltinID = 6470 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6471 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6472 6473 unsigned NumArgs = TheCall->getNumArgs(); 6474 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6475 if (NumArgs < NumRequiredArgs) { 6476 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6477 << 0 /* function call */ << NumRequiredArgs << NumArgs 6478 << TheCall->getSourceRange(); 6479 } 6480 if (NumArgs >= NumRequiredArgs + 0x100) { 6481 return Diag(TheCall->getEndLoc(), 6482 diag::err_typecheck_call_too_many_args_at_most) 6483 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6484 << TheCall->getSourceRange(); 6485 } 6486 unsigned i = 0; 6487 6488 // For formatting call, check buffer arg. 6489 if (!IsSizeCall) { 6490 ExprResult Arg(TheCall->getArg(i)); 6491 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6492 Context, Context.VoidPtrTy, false); 6493 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6494 if (Arg.isInvalid()) 6495 return true; 6496 TheCall->setArg(i, Arg.get()); 6497 i++; 6498 } 6499 6500 // Check string literal arg. 6501 unsigned FormatIdx = i; 6502 { 6503 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6504 if (Arg.isInvalid()) 6505 return true; 6506 TheCall->setArg(i, Arg.get()); 6507 i++; 6508 } 6509 6510 // Make sure variadic args are scalar. 6511 unsigned FirstDataArg = i; 6512 while (i < NumArgs) { 6513 ExprResult Arg = DefaultVariadicArgumentPromotion( 6514 TheCall->getArg(i), VariadicFunction, nullptr); 6515 if (Arg.isInvalid()) 6516 return true; 6517 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6518 if (ArgSize.getQuantity() >= 0x100) { 6519 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6520 << i << (int)ArgSize.getQuantity() << 0xff 6521 << TheCall->getSourceRange(); 6522 } 6523 TheCall->setArg(i, Arg.get()); 6524 i++; 6525 } 6526 6527 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6528 // call to avoid duplicate diagnostics. 6529 if (!IsSizeCall) { 6530 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6531 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6532 bool Success = CheckFormatArguments( 6533 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6534 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6535 CheckedVarArgs); 6536 if (!Success) 6537 return true; 6538 } 6539 6540 if (IsSizeCall) { 6541 TheCall->setType(Context.getSizeType()); 6542 } else { 6543 TheCall->setType(Context.VoidPtrTy); 6544 } 6545 return false; 6546 } 6547 6548 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6549 /// TheCall is a constant expression. 6550 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6551 llvm::APSInt &Result) { 6552 Expr *Arg = TheCall->getArg(ArgNum); 6553 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6554 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6555 6556 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6557 6558 Optional<llvm::APSInt> R; 6559 if (!(R = Arg->getIntegerConstantExpr(Context))) 6560 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6561 << FDecl->getDeclName() << Arg->getSourceRange(); 6562 Result = *R; 6563 return false; 6564 } 6565 6566 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6567 /// TheCall is a constant expression in the range [Low, High]. 6568 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6569 int Low, int High, bool RangeIsError) { 6570 if (isConstantEvaluated()) 6571 return false; 6572 llvm::APSInt Result; 6573 6574 // We can't check the value of a dependent argument. 6575 Expr *Arg = TheCall->getArg(ArgNum); 6576 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6577 return false; 6578 6579 // Check constant-ness first. 6580 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6581 return true; 6582 6583 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6584 if (RangeIsError) 6585 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6586 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6587 else 6588 // Defer the warning until we know if the code will be emitted so that 6589 // dead code can ignore this. 6590 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6591 PDiag(diag::warn_argument_invalid_range) 6592 << Result.toString(10) << Low << High 6593 << Arg->getSourceRange()); 6594 } 6595 6596 return false; 6597 } 6598 6599 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6600 /// TheCall is a constant expression is a multiple of Num.. 6601 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6602 unsigned Num) { 6603 llvm::APSInt Result; 6604 6605 // We can't check the value of a dependent argument. 6606 Expr *Arg = TheCall->getArg(ArgNum); 6607 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6608 return false; 6609 6610 // Check constant-ness first. 6611 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6612 return true; 6613 6614 if (Result.getSExtValue() % Num != 0) 6615 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6616 << Num << Arg->getSourceRange(); 6617 6618 return false; 6619 } 6620 6621 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6622 /// constant expression representing a power of 2. 6623 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6624 llvm::APSInt Result; 6625 6626 // We can't check the value of a dependent argument. 6627 Expr *Arg = TheCall->getArg(ArgNum); 6628 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6629 return false; 6630 6631 // Check constant-ness first. 6632 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6633 return true; 6634 6635 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6636 // and only if x is a power of 2. 6637 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6638 return false; 6639 6640 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6641 << Arg->getSourceRange(); 6642 } 6643 6644 static bool IsShiftedByte(llvm::APSInt Value) { 6645 if (Value.isNegative()) 6646 return false; 6647 6648 // Check if it's a shifted byte, by shifting it down 6649 while (true) { 6650 // If the value fits in the bottom byte, the check passes. 6651 if (Value < 0x100) 6652 return true; 6653 6654 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6655 // fails. 6656 if ((Value & 0xFF) != 0) 6657 return false; 6658 6659 // If the bottom 8 bits are all 0, but something above that is nonzero, 6660 // then shifting the value right by 8 bits won't affect whether it's a 6661 // shifted byte or not. So do that, and go round again. 6662 Value >>= 8; 6663 } 6664 } 6665 6666 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6667 /// a constant expression representing an arbitrary byte value shifted left by 6668 /// a multiple of 8 bits. 6669 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6670 unsigned ArgBits) { 6671 llvm::APSInt Result; 6672 6673 // We can't check the value of a dependent argument. 6674 Expr *Arg = TheCall->getArg(ArgNum); 6675 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6676 return false; 6677 6678 // Check constant-ness first. 6679 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6680 return true; 6681 6682 // Truncate to the given size. 6683 Result = Result.getLoBits(ArgBits); 6684 Result.setIsUnsigned(true); 6685 6686 if (IsShiftedByte(Result)) 6687 return false; 6688 6689 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6690 << Arg->getSourceRange(); 6691 } 6692 6693 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6694 /// TheCall is a constant expression representing either a shifted byte value, 6695 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6696 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6697 /// Arm MVE intrinsics. 6698 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6699 int ArgNum, 6700 unsigned ArgBits) { 6701 llvm::APSInt Result; 6702 6703 // We can't check the value of a dependent argument. 6704 Expr *Arg = TheCall->getArg(ArgNum); 6705 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6706 return false; 6707 6708 // Check constant-ness first. 6709 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6710 return true; 6711 6712 // Truncate to the given size. 6713 Result = Result.getLoBits(ArgBits); 6714 Result.setIsUnsigned(true); 6715 6716 // Check to see if it's in either of the required forms. 6717 if (IsShiftedByte(Result) || 6718 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6719 return false; 6720 6721 return Diag(TheCall->getBeginLoc(), 6722 diag::err_argument_not_shifted_byte_or_xxff) 6723 << Arg->getSourceRange(); 6724 } 6725 6726 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6727 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6728 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6729 if (checkArgCount(*this, TheCall, 2)) 6730 return true; 6731 Expr *Arg0 = TheCall->getArg(0); 6732 Expr *Arg1 = TheCall->getArg(1); 6733 6734 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6735 if (FirstArg.isInvalid()) 6736 return true; 6737 QualType FirstArgType = FirstArg.get()->getType(); 6738 if (!FirstArgType->isAnyPointerType()) 6739 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6740 << "first" << FirstArgType << Arg0->getSourceRange(); 6741 TheCall->setArg(0, FirstArg.get()); 6742 6743 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6744 if (SecArg.isInvalid()) 6745 return true; 6746 QualType SecArgType = SecArg.get()->getType(); 6747 if (!SecArgType->isIntegerType()) 6748 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6749 << "second" << SecArgType << Arg1->getSourceRange(); 6750 6751 // Derive the return type from the pointer argument. 6752 TheCall->setType(FirstArgType); 6753 return false; 6754 } 6755 6756 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6757 if (checkArgCount(*this, TheCall, 2)) 6758 return true; 6759 6760 Expr *Arg0 = TheCall->getArg(0); 6761 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6762 if (FirstArg.isInvalid()) 6763 return true; 6764 QualType FirstArgType = FirstArg.get()->getType(); 6765 if (!FirstArgType->isAnyPointerType()) 6766 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6767 << "first" << FirstArgType << Arg0->getSourceRange(); 6768 TheCall->setArg(0, FirstArg.get()); 6769 6770 // Derive the return type from the pointer argument. 6771 TheCall->setType(FirstArgType); 6772 6773 // Second arg must be an constant in range [0,15] 6774 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6775 } 6776 6777 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6778 if (checkArgCount(*this, TheCall, 2)) 6779 return true; 6780 Expr *Arg0 = TheCall->getArg(0); 6781 Expr *Arg1 = TheCall->getArg(1); 6782 6783 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6784 if (FirstArg.isInvalid()) 6785 return true; 6786 QualType FirstArgType = FirstArg.get()->getType(); 6787 if (!FirstArgType->isAnyPointerType()) 6788 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6789 << "first" << FirstArgType << Arg0->getSourceRange(); 6790 6791 QualType SecArgType = Arg1->getType(); 6792 if (!SecArgType->isIntegerType()) 6793 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6794 << "second" << SecArgType << Arg1->getSourceRange(); 6795 TheCall->setType(Context.IntTy); 6796 return false; 6797 } 6798 6799 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6800 BuiltinID == AArch64::BI__builtin_arm_stg) { 6801 if (checkArgCount(*this, TheCall, 1)) 6802 return true; 6803 Expr *Arg0 = TheCall->getArg(0); 6804 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6805 if (FirstArg.isInvalid()) 6806 return true; 6807 6808 QualType FirstArgType = FirstArg.get()->getType(); 6809 if (!FirstArgType->isAnyPointerType()) 6810 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6811 << "first" << FirstArgType << Arg0->getSourceRange(); 6812 TheCall->setArg(0, FirstArg.get()); 6813 6814 // Derive the return type from the pointer argument. 6815 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6816 TheCall->setType(FirstArgType); 6817 return false; 6818 } 6819 6820 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6821 Expr *ArgA = TheCall->getArg(0); 6822 Expr *ArgB = TheCall->getArg(1); 6823 6824 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6825 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6826 6827 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6828 return true; 6829 6830 QualType ArgTypeA = ArgExprA.get()->getType(); 6831 QualType ArgTypeB = ArgExprB.get()->getType(); 6832 6833 auto isNull = [&] (Expr *E) -> bool { 6834 return E->isNullPointerConstant( 6835 Context, Expr::NPC_ValueDependentIsNotNull); }; 6836 6837 // argument should be either a pointer or null 6838 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6839 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6840 << "first" << ArgTypeA << ArgA->getSourceRange(); 6841 6842 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6843 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6844 << "second" << ArgTypeB << ArgB->getSourceRange(); 6845 6846 // Ensure Pointee types are compatible 6847 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6848 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6849 QualType pointeeA = ArgTypeA->getPointeeType(); 6850 QualType pointeeB = ArgTypeB->getPointeeType(); 6851 if (!Context.typesAreCompatible( 6852 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6853 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6854 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6855 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6856 << ArgB->getSourceRange(); 6857 } 6858 } 6859 6860 // at least one argument should be pointer type 6861 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6862 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6863 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6864 6865 if (isNull(ArgA)) // adopt type of the other pointer 6866 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6867 6868 if (isNull(ArgB)) 6869 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6870 6871 TheCall->setArg(0, ArgExprA.get()); 6872 TheCall->setArg(1, ArgExprB.get()); 6873 TheCall->setType(Context.LongLongTy); 6874 return false; 6875 } 6876 assert(false && "Unhandled ARM MTE intrinsic"); 6877 return true; 6878 } 6879 6880 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6881 /// TheCall is an ARM/AArch64 special register string literal. 6882 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6883 int ArgNum, unsigned ExpectedFieldNum, 6884 bool AllowName) { 6885 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6886 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6887 BuiltinID == ARM::BI__builtin_arm_rsr || 6888 BuiltinID == ARM::BI__builtin_arm_rsrp || 6889 BuiltinID == ARM::BI__builtin_arm_wsr || 6890 BuiltinID == ARM::BI__builtin_arm_wsrp; 6891 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6892 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6893 BuiltinID == AArch64::BI__builtin_arm_rsr || 6894 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6895 BuiltinID == AArch64::BI__builtin_arm_wsr || 6896 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6897 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6898 6899 // We can't check the value of a dependent argument. 6900 Expr *Arg = TheCall->getArg(ArgNum); 6901 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6902 return false; 6903 6904 // Check if the argument is a string literal. 6905 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6906 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6907 << Arg->getSourceRange(); 6908 6909 // Check the type of special register given. 6910 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6911 SmallVector<StringRef, 6> Fields; 6912 Reg.split(Fields, ":"); 6913 6914 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6915 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6916 << Arg->getSourceRange(); 6917 6918 // If the string is the name of a register then we cannot check that it is 6919 // valid here but if the string is of one the forms described in ACLE then we 6920 // can check that the supplied fields are integers and within the valid 6921 // ranges. 6922 if (Fields.size() > 1) { 6923 bool FiveFields = Fields.size() == 5; 6924 6925 bool ValidString = true; 6926 if (IsARMBuiltin) { 6927 ValidString &= Fields[0].startswith_lower("cp") || 6928 Fields[0].startswith_lower("p"); 6929 if (ValidString) 6930 Fields[0] = 6931 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6932 6933 ValidString &= Fields[2].startswith_lower("c"); 6934 if (ValidString) 6935 Fields[2] = Fields[2].drop_front(1); 6936 6937 if (FiveFields) { 6938 ValidString &= Fields[3].startswith_lower("c"); 6939 if (ValidString) 6940 Fields[3] = Fields[3].drop_front(1); 6941 } 6942 } 6943 6944 SmallVector<int, 5> Ranges; 6945 if (FiveFields) 6946 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6947 else 6948 Ranges.append({15, 7, 15}); 6949 6950 for (unsigned i=0; i<Fields.size(); ++i) { 6951 int IntField; 6952 ValidString &= !Fields[i].getAsInteger(10, IntField); 6953 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6954 } 6955 6956 if (!ValidString) 6957 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6958 << Arg->getSourceRange(); 6959 } else if (IsAArch64Builtin && Fields.size() == 1) { 6960 // If the register name is one of those that appear in the condition below 6961 // and the special register builtin being used is one of the write builtins, 6962 // then we require that the argument provided for writing to the register 6963 // is an integer constant expression. This is because it will be lowered to 6964 // an MSR (immediate) instruction, so we need to know the immediate at 6965 // compile time. 6966 if (TheCall->getNumArgs() != 2) 6967 return false; 6968 6969 std::string RegLower = Reg.lower(); 6970 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6971 RegLower != "pan" && RegLower != "uao") 6972 return false; 6973 6974 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6975 } 6976 6977 return false; 6978 } 6979 6980 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 6981 /// Emit an error and return true on failure; return false on success. 6982 /// TypeStr is a string containing the type descriptor of the value returned by 6983 /// the builtin and the descriptors of the expected type of the arguments. 6984 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 6985 6986 assert((TypeStr[0] != '\0') && 6987 "Invalid types in PPC MMA builtin declaration"); 6988 6989 unsigned Mask = 0; 6990 unsigned ArgNum = 0; 6991 6992 // The first type in TypeStr is the type of the value returned by the 6993 // builtin. So we first read that type and change the type of TheCall. 6994 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6995 TheCall->setType(type); 6996 6997 while (*TypeStr != '\0') { 6998 Mask = 0; 6999 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7000 if (ArgNum >= TheCall->getNumArgs()) { 7001 ArgNum++; 7002 break; 7003 } 7004 7005 Expr *Arg = TheCall->getArg(ArgNum); 7006 QualType ArgType = Arg->getType(); 7007 7008 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 7009 (!ExpectedType->isVoidPointerType() && 7010 ArgType.getCanonicalType() != ExpectedType)) 7011 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7012 << ArgType << ExpectedType << 1 << 0 << 0; 7013 7014 // If the value of the Mask is not 0, we have a constraint in the size of 7015 // the integer argument so here we ensure the argument is a constant that 7016 // is in the valid range. 7017 if (Mask != 0 && 7018 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7019 return true; 7020 7021 ArgNum++; 7022 } 7023 7024 // In case we exited early from the previous loop, there are other types to 7025 // read from TypeStr. So we need to read them all to ensure we have the right 7026 // number of arguments in TheCall and if it is not the case, to display a 7027 // better error message. 7028 while (*TypeStr != '\0') { 7029 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7030 ArgNum++; 7031 } 7032 if (checkArgCount(*this, TheCall, ArgNum)) 7033 return true; 7034 7035 return false; 7036 } 7037 7038 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7039 /// This checks that the target supports __builtin_longjmp and 7040 /// that val is a constant 1. 7041 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7042 if (!Context.getTargetInfo().hasSjLjLowering()) 7043 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7044 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7045 7046 Expr *Arg = TheCall->getArg(1); 7047 llvm::APSInt Result; 7048 7049 // TODO: This is less than ideal. Overload this to take a value. 7050 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7051 return true; 7052 7053 if (Result != 1) 7054 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7055 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7056 7057 return false; 7058 } 7059 7060 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7061 /// This checks that the target supports __builtin_setjmp. 7062 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7063 if (!Context.getTargetInfo().hasSjLjLowering()) 7064 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7065 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7066 return false; 7067 } 7068 7069 namespace { 7070 7071 class UncoveredArgHandler { 7072 enum { Unknown = -1, AllCovered = -2 }; 7073 7074 signed FirstUncoveredArg = Unknown; 7075 SmallVector<const Expr *, 4> DiagnosticExprs; 7076 7077 public: 7078 UncoveredArgHandler() = default; 7079 7080 bool hasUncoveredArg() const { 7081 return (FirstUncoveredArg >= 0); 7082 } 7083 7084 unsigned getUncoveredArg() const { 7085 assert(hasUncoveredArg() && "no uncovered argument"); 7086 return FirstUncoveredArg; 7087 } 7088 7089 void setAllCovered() { 7090 // A string has been found with all arguments covered, so clear out 7091 // the diagnostics. 7092 DiagnosticExprs.clear(); 7093 FirstUncoveredArg = AllCovered; 7094 } 7095 7096 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7097 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7098 7099 // Don't update if a previous string covers all arguments. 7100 if (FirstUncoveredArg == AllCovered) 7101 return; 7102 7103 // UncoveredArgHandler tracks the highest uncovered argument index 7104 // and with it all the strings that match this index. 7105 if (NewFirstUncoveredArg == FirstUncoveredArg) 7106 DiagnosticExprs.push_back(StrExpr); 7107 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7108 DiagnosticExprs.clear(); 7109 DiagnosticExprs.push_back(StrExpr); 7110 FirstUncoveredArg = NewFirstUncoveredArg; 7111 } 7112 } 7113 7114 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7115 }; 7116 7117 enum StringLiteralCheckType { 7118 SLCT_NotALiteral, 7119 SLCT_UncheckedLiteral, 7120 SLCT_CheckedLiteral 7121 }; 7122 7123 } // namespace 7124 7125 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7126 BinaryOperatorKind BinOpKind, 7127 bool AddendIsRight) { 7128 unsigned BitWidth = Offset.getBitWidth(); 7129 unsigned AddendBitWidth = Addend.getBitWidth(); 7130 // There might be negative interim results. 7131 if (Addend.isUnsigned()) { 7132 Addend = Addend.zext(++AddendBitWidth); 7133 Addend.setIsSigned(true); 7134 } 7135 // Adjust the bit width of the APSInts. 7136 if (AddendBitWidth > BitWidth) { 7137 Offset = Offset.sext(AddendBitWidth); 7138 BitWidth = AddendBitWidth; 7139 } else if (BitWidth > AddendBitWidth) { 7140 Addend = Addend.sext(BitWidth); 7141 } 7142 7143 bool Ov = false; 7144 llvm::APSInt ResOffset = Offset; 7145 if (BinOpKind == BO_Add) 7146 ResOffset = Offset.sadd_ov(Addend, Ov); 7147 else { 7148 assert(AddendIsRight && BinOpKind == BO_Sub && 7149 "operator must be add or sub with addend on the right"); 7150 ResOffset = Offset.ssub_ov(Addend, Ov); 7151 } 7152 7153 // We add an offset to a pointer here so we should support an offset as big as 7154 // possible. 7155 if (Ov) { 7156 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7157 "index (intermediate) result too big"); 7158 Offset = Offset.sext(2 * BitWidth); 7159 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7160 return; 7161 } 7162 7163 Offset = ResOffset; 7164 } 7165 7166 namespace { 7167 7168 // This is a wrapper class around StringLiteral to support offsetted string 7169 // literals as format strings. It takes the offset into account when returning 7170 // the string and its length or the source locations to display notes correctly. 7171 class FormatStringLiteral { 7172 const StringLiteral *FExpr; 7173 int64_t Offset; 7174 7175 public: 7176 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7177 : FExpr(fexpr), Offset(Offset) {} 7178 7179 StringRef getString() const { 7180 return FExpr->getString().drop_front(Offset); 7181 } 7182 7183 unsigned getByteLength() const { 7184 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7185 } 7186 7187 unsigned getLength() const { return FExpr->getLength() - Offset; } 7188 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7189 7190 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7191 7192 QualType getType() const { return FExpr->getType(); } 7193 7194 bool isAscii() const { return FExpr->isAscii(); } 7195 bool isWide() const { return FExpr->isWide(); } 7196 bool isUTF8() const { return FExpr->isUTF8(); } 7197 bool isUTF16() const { return FExpr->isUTF16(); } 7198 bool isUTF32() const { return FExpr->isUTF32(); } 7199 bool isPascal() const { return FExpr->isPascal(); } 7200 7201 SourceLocation getLocationOfByte( 7202 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7203 const TargetInfo &Target, unsigned *StartToken = nullptr, 7204 unsigned *StartTokenByteOffset = nullptr) const { 7205 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7206 StartToken, StartTokenByteOffset); 7207 } 7208 7209 SourceLocation getBeginLoc() const LLVM_READONLY { 7210 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7211 } 7212 7213 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7214 }; 7215 7216 } // namespace 7217 7218 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7219 const Expr *OrigFormatExpr, 7220 ArrayRef<const Expr *> Args, 7221 bool HasVAListArg, unsigned format_idx, 7222 unsigned firstDataArg, 7223 Sema::FormatStringType Type, 7224 bool inFunctionCall, 7225 Sema::VariadicCallType CallType, 7226 llvm::SmallBitVector &CheckedVarArgs, 7227 UncoveredArgHandler &UncoveredArg, 7228 bool IgnoreStringsWithoutSpecifiers); 7229 7230 // Determine if an expression is a string literal or constant string. 7231 // If this function returns false on the arguments to a function expecting a 7232 // format string, we will usually need to emit a warning. 7233 // True string literals are then checked by CheckFormatString. 7234 static StringLiteralCheckType 7235 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7236 bool HasVAListArg, unsigned format_idx, 7237 unsigned firstDataArg, Sema::FormatStringType Type, 7238 Sema::VariadicCallType CallType, bool InFunctionCall, 7239 llvm::SmallBitVector &CheckedVarArgs, 7240 UncoveredArgHandler &UncoveredArg, 7241 llvm::APSInt Offset, 7242 bool IgnoreStringsWithoutSpecifiers = false) { 7243 if (S.isConstantEvaluated()) 7244 return SLCT_NotALiteral; 7245 tryAgain: 7246 assert(Offset.isSigned() && "invalid offset"); 7247 7248 if (E->isTypeDependent() || E->isValueDependent()) 7249 return SLCT_NotALiteral; 7250 7251 E = E->IgnoreParenCasts(); 7252 7253 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7254 // Technically -Wformat-nonliteral does not warn about this case. 7255 // The behavior of printf and friends in this case is implementation 7256 // dependent. Ideally if the format string cannot be null then 7257 // it should have a 'nonnull' attribute in the function prototype. 7258 return SLCT_UncheckedLiteral; 7259 7260 switch (E->getStmtClass()) { 7261 case Stmt::BinaryConditionalOperatorClass: 7262 case Stmt::ConditionalOperatorClass: { 7263 // The expression is a literal if both sub-expressions were, and it was 7264 // completely checked only if both sub-expressions were checked. 7265 const AbstractConditionalOperator *C = 7266 cast<AbstractConditionalOperator>(E); 7267 7268 // Determine whether it is necessary to check both sub-expressions, for 7269 // example, because the condition expression is a constant that can be 7270 // evaluated at compile time. 7271 bool CheckLeft = true, CheckRight = true; 7272 7273 bool Cond; 7274 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7275 S.isConstantEvaluated())) { 7276 if (Cond) 7277 CheckRight = false; 7278 else 7279 CheckLeft = false; 7280 } 7281 7282 // We need to maintain the offsets for the right and the left hand side 7283 // separately to check if every possible indexed expression is a valid 7284 // string literal. They might have different offsets for different string 7285 // literals in the end. 7286 StringLiteralCheckType Left; 7287 if (!CheckLeft) 7288 Left = SLCT_UncheckedLiteral; 7289 else { 7290 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7291 HasVAListArg, format_idx, firstDataArg, 7292 Type, CallType, InFunctionCall, 7293 CheckedVarArgs, UncoveredArg, Offset, 7294 IgnoreStringsWithoutSpecifiers); 7295 if (Left == SLCT_NotALiteral || !CheckRight) { 7296 return Left; 7297 } 7298 } 7299 7300 StringLiteralCheckType Right = checkFormatStringExpr( 7301 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7302 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7303 IgnoreStringsWithoutSpecifiers); 7304 7305 return (CheckLeft && Left < Right) ? Left : Right; 7306 } 7307 7308 case Stmt::ImplicitCastExprClass: 7309 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7310 goto tryAgain; 7311 7312 case Stmt::OpaqueValueExprClass: 7313 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7314 E = src; 7315 goto tryAgain; 7316 } 7317 return SLCT_NotALiteral; 7318 7319 case Stmt::PredefinedExprClass: 7320 // While __func__, etc., are technically not string literals, they 7321 // cannot contain format specifiers and thus are not a security 7322 // liability. 7323 return SLCT_UncheckedLiteral; 7324 7325 case Stmt::DeclRefExprClass: { 7326 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7327 7328 // As an exception, do not flag errors for variables binding to 7329 // const string literals. 7330 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7331 bool isConstant = false; 7332 QualType T = DR->getType(); 7333 7334 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7335 isConstant = AT->getElementType().isConstant(S.Context); 7336 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7337 isConstant = T.isConstant(S.Context) && 7338 PT->getPointeeType().isConstant(S.Context); 7339 } else if (T->isObjCObjectPointerType()) { 7340 // In ObjC, there is usually no "const ObjectPointer" type, 7341 // so don't check if the pointee type is constant. 7342 isConstant = T.isConstant(S.Context); 7343 } 7344 7345 if (isConstant) { 7346 if (const Expr *Init = VD->getAnyInitializer()) { 7347 // Look through initializers like const char c[] = { "foo" } 7348 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7349 if (InitList->isStringLiteralInit()) 7350 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7351 } 7352 return checkFormatStringExpr(S, Init, Args, 7353 HasVAListArg, format_idx, 7354 firstDataArg, Type, CallType, 7355 /*InFunctionCall*/ false, CheckedVarArgs, 7356 UncoveredArg, Offset); 7357 } 7358 } 7359 7360 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7361 // special check to see if the format string is a function parameter 7362 // of the function calling the printf function. If the function 7363 // has an attribute indicating it is a printf-like function, then we 7364 // should suppress warnings concerning non-literals being used in a call 7365 // to a vprintf function. For example: 7366 // 7367 // void 7368 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7369 // va_list ap; 7370 // va_start(ap, fmt); 7371 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7372 // ... 7373 // } 7374 if (HasVAListArg) { 7375 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7376 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7377 int PVIndex = PV->getFunctionScopeIndex() + 1; 7378 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7379 // adjust for implicit parameter 7380 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7381 if (MD->isInstance()) 7382 ++PVIndex; 7383 // We also check if the formats are compatible. 7384 // We can't pass a 'scanf' string to a 'printf' function. 7385 if (PVIndex == PVFormat->getFormatIdx() && 7386 Type == S.GetFormatStringType(PVFormat)) 7387 return SLCT_UncheckedLiteral; 7388 } 7389 } 7390 } 7391 } 7392 } 7393 7394 return SLCT_NotALiteral; 7395 } 7396 7397 case Stmt::CallExprClass: 7398 case Stmt::CXXMemberCallExprClass: { 7399 const CallExpr *CE = cast<CallExpr>(E); 7400 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7401 bool IsFirst = true; 7402 StringLiteralCheckType CommonResult; 7403 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7404 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7405 StringLiteralCheckType Result = checkFormatStringExpr( 7406 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7407 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7408 IgnoreStringsWithoutSpecifiers); 7409 if (IsFirst) { 7410 CommonResult = Result; 7411 IsFirst = false; 7412 } 7413 } 7414 if (!IsFirst) 7415 return CommonResult; 7416 7417 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7418 unsigned BuiltinID = FD->getBuiltinID(); 7419 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7420 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7421 const Expr *Arg = CE->getArg(0); 7422 return checkFormatStringExpr(S, Arg, Args, 7423 HasVAListArg, format_idx, 7424 firstDataArg, Type, CallType, 7425 InFunctionCall, CheckedVarArgs, 7426 UncoveredArg, Offset, 7427 IgnoreStringsWithoutSpecifiers); 7428 } 7429 } 7430 } 7431 7432 return SLCT_NotALiteral; 7433 } 7434 case Stmt::ObjCMessageExprClass: { 7435 const auto *ME = cast<ObjCMessageExpr>(E); 7436 if (const auto *MD = ME->getMethodDecl()) { 7437 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7438 // As a special case heuristic, if we're using the method -[NSBundle 7439 // localizedStringForKey:value:table:], ignore any key strings that lack 7440 // format specifiers. The idea is that if the key doesn't have any 7441 // format specifiers then its probably just a key to map to the 7442 // localized strings. If it does have format specifiers though, then its 7443 // likely that the text of the key is the format string in the 7444 // programmer's language, and should be checked. 7445 const ObjCInterfaceDecl *IFace; 7446 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7447 IFace->getIdentifier()->isStr("NSBundle") && 7448 MD->getSelector().isKeywordSelector( 7449 {"localizedStringForKey", "value", "table"})) { 7450 IgnoreStringsWithoutSpecifiers = true; 7451 } 7452 7453 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7454 return checkFormatStringExpr( 7455 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7456 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7457 IgnoreStringsWithoutSpecifiers); 7458 } 7459 } 7460 7461 return SLCT_NotALiteral; 7462 } 7463 case Stmt::ObjCStringLiteralClass: 7464 case Stmt::StringLiteralClass: { 7465 const StringLiteral *StrE = nullptr; 7466 7467 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7468 StrE = ObjCFExpr->getString(); 7469 else 7470 StrE = cast<StringLiteral>(E); 7471 7472 if (StrE) { 7473 if (Offset.isNegative() || Offset > StrE->getLength()) { 7474 // TODO: It would be better to have an explicit warning for out of 7475 // bounds literals. 7476 return SLCT_NotALiteral; 7477 } 7478 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7479 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7480 firstDataArg, Type, InFunctionCall, CallType, 7481 CheckedVarArgs, UncoveredArg, 7482 IgnoreStringsWithoutSpecifiers); 7483 return SLCT_CheckedLiteral; 7484 } 7485 7486 return SLCT_NotALiteral; 7487 } 7488 case Stmt::BinaryOperatorClass: { 7489 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7490 7491 // A string literal + an int offset is still a string literal. 7492 if (BinOp->isAdditiveOp()) { 7493 Expr::EvalResult LResult, RResult; 7494 7495 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7496 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7497 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7498 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7499 7500 if (LIsInt != RIsInt) { 7501 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7502 7503 if (LIsInt) { 7504 if (BinOpKind == BO_Add) { 7505 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7506 E = BinOp->getRHS(); 7507 goto tryAgain; 7508 } 7509 } else { 7510 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7511 E = BinOp->getLHS(); 7512 goto tryAgain; 7513 } 7514 } 7515 } 7516 7517 return SLCT_NotALiteral; 7518 } 7519 case Stmt::UnaryOperatorClass: { 7520 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7521 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7522 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7523 Expr::EvalResult IndexResult; 7524 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7525 Expr::SE_NoSideEffects, 7526 S.isConstantEvaluated())) { 7527 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7528 /*RHS is int*/ true); 7529 E = ASE->getBase(); 7530 goto tryAgain; 7531 } 7532 } 7533 7534 return SLCT_NotALiteral; 7535 } 7536 7537 default: 7538 return SLCT_NotALiteral; 7539 } 7540 } 7541 7542 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7543 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7544 .Case("scanf", FST_Scanf) 7545 .Cases("printf", "printf0", FST_Printf) 7546 .Cases("NSString", "CFString", FST_NSString) 7547 .Case("strftime", FST_Strftime) 7548 .Case("strfmon", FST_Strfmon) 7549 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7550 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7551 .Case("os_trace", FST_OSLog) 7552 .Case("os_log", FST_OSLog) 7553 .Default(FST_Unknown); 7554 } 7555 7556 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7557 /// functions) for correct use of format strings. 7558 /// Returns true if a format string has been fully checked. 7559 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7560 ArrayRef<const Expr *> Args, 7561 bool IsCXXMember, 7562 VariadicCallType CallType, 7563 SourceLocation Loc, SourceRange Range, 7564 llvm::SmallBitVector &CheckedVarArgs) { 7565 FormatStringInfo FSI; 7566 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7567 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7568 FSI.FirstDataArg, GetFormatStringType(Format), 7569 CallType, Loc, Range, CheckedVarArgs); 7570 return false; 7571 } 7572 7573 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7574 bool HasVAListArg, unsigned format_idx, 7575 unsigned firstDataArg, FormatStringType Type, 7576 VariadicCallType CallType, 7577 SourceLocation Loc, SourceRange Range, 7578 llvm::SmallBitVector &CheckedVarArgs) { 7579 // CHECK: printf/scanf-like function is called with no format string. 7580 if (format_idx >= Args.size()) { 7581 Diag(Loc, diag::warn_missing_format_string) << Range; 7582 return false; 7583 } 7584 7585 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7586 7587 // CHECK: format string is not a string literal. 7588 // 7589 // Dynamically generated format strings are difficult to 7590 // automatically vet at compile time. Requiring that format strings 7591 // are string literals: (1) permits the checking of format strings by 7592 // the compiler and thereby (2) can practically remove the source of 7593 // many format string exploits. 7594 7595 // Format string can be either ObjC string (e.g. @"%d") or 7596 // C string (e.g. "%d") 7597 // ObjC string uses the same format specifiers as C string, so we can use 7598 // the same format string checking logic for both ObjC and C strings. 7599 UncoveredArgHandler UncoveredArg; 7600 StringLiteralCheckType CT = 7601 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7602 format_idx, firstDataArg, Type, CallType, 7603 /*IsFunctionCall*/ true, CheckedVarArgs, 7604 UncoveredArg, 7605 /*no string offset*/ llvm::APSInt(64, false) = 0); 7606 7607 // Generate a diagnostic where an uncovered argument is detected. 7608 if (UncoveredArg.hasUncoveredArg()) { 7609 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7610 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7611 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7612 } 7613 7614 if (CT != SLCT_NotALiteral) 7615 // Literal format string found, check done! 7616 return CT == SLCT_CheckedLiteral; 7617 7618 // Strftime is particular as it always uses a single 'time' argument, 7619 // so it is safe to pass a non-literal string. 7620 if (Type == FST_Strftime) 7621 return false; 7622 7623 // Do not emit diag when the string param is a macro expansion and the 7624 // format is either NSString or CFString. This is a hack to prevent 7625 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7626 // which are usually used in place of NS and CF string literals. 7627 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7628 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7629 return false; 7630 7631 // If there are no arguments specified, warn with -Wformat-security, otherwise 7632 // warn only with -Wformat-nonliteral. 7633 if (Args.size() == firstDataArg) { 7634 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7635 << OrigFormatExpr->getSourceRange(); 7636 switch (Type) { 7637 default: 7638 break; 7639 case FST_Kprintf: 7640 case FST_FreeBSDKPrintf: 7641 case FST_Printf: 7642 Diag(FormatLoc, diag::note_format_security_fixit) 7643 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7644 break; 7645 case FST_NSString: 7646 Diag(FormatLoc, diag::note_format_security_fixit) 7647 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7648 break; 7649 } 7650 } else { 7651 Diag(FormatLoc, diag::warn_format_nonliteral) 7652 << OrigFormatExpr->getSourceRange(); 7653 } 7654 return false; 7655 } 7656 7657 namespace { 7658 7659 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7660 protected: 7661 Sema &S; 7662 const FormatStringLiteral *FExpr; 7663 const Expr *OrigFormatExpr; 7664 const Sema::FormatStringType FSType; 7665 const unsigned FirstDataArg; 7666 const unsigned NumDataArgs; 7667 const char *Beg; // Start of format string. 7668 const bool HasVAListArg; 7669 ArrayRef<const Expr *> Args; 7670 unsigned FormatIdx; 7671 llvm::SmallBitVector CoveredArgs; 7672 bool usesPositionalArgs = false; 7673 bool atFirstArg = true; 7674 bool inFunctionCall; 7675 Sema::VariadicCallType CallType; 7676 llvm::SmallBitVector &CheckedVarArgs; 7677 UncoveredArgHandler &UncoveredArg; 7678 7679 public: 7680 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7681 const Expr *origFormatExpr, 7682 const Sema::FormatStringType type, unsigned firstDataArg, 7683 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7684 ArrayRef<const Expr *> Args, unsigned formatIdx, 7685 bool inFunctionCall, Sema::VariadicCallType callType, 7686 llvm::SmallBitVector &CheckedVarArgs, 7687 UncoveredArgHandler &UncoveredArg) 7688 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7689 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7690 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7691 inFunctionCall(inFunctionCall), CallType(callType), 7692 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7693 CoveredArgs.resize(numDataArgs); 7694 CoveredArgs.reset(); 7695 } 7696 7697 void DoneProcessing(); 7698 7699 void HandleIncompleteSpecifier(const char *startSpecifier, 7700 unsigned specifierLen) override; 7701 7702 void HandleInvalidLengthModifier( 7703 const analyze_format_string::FormatSpecifier &FS, 7704 const analyze_format_string::ConversionSpecifier &CS, 7705 const char *startSpecifier, unsigned specifierLen, 7706 unsigned DiagID); 7707 7708 void HandleNonStandardLengthModifier( 7709 const analyze_format_string::FormatSpecifier &FS, 7710 const char *startSpecifier, unsigned specifierLen); 7711 7712 void HandleNonStandardConversionSpecifier( 7713 const analyze_format_string::ConversionSpecifier &CS, 7714 const char *startSpecifier, unsigned specifierLen); 7715 7716 void HandlePosition(const char *startPos, unsigned posLen) override; 7717 7718 void HandleInvalidPosition(const char *startSpecifier, 7719 unsigned specifierLen, 7720 analyze_format_string::PositionContext p) override; 7721 7722 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7723 7724 void HandleNullChar(const char *nullCharacter) override; 7725 7726 template <typename Range> 7727 static void 7728 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7729 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7730 bool IsStringLocation, Range StringRange, 7731 ArrayRef<FixItHint> Fixit = None); 7732 7733 protected: 7734 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7735 const char *startSpec, 7736 unsigned specifierLen, 7737 const char *csStart, unsigned csLen); 7738 7739 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7740 const char *startSpec, 7741 unsigned specifierLen); 7742 7743 SourceRange getFormatStringRange(); 7744 CharSourceRange getSpecifierRange(const char *startSpecifier, 7745 unsigned specifierLen); 7746 SourceLocation getLocationOfByte(const char *x); 7747 7748 const Expr *getDataArg(unsigned i) const; 7749 7750 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7751 const analyze_format_string::ConversionSpecifier &CS, 7752 const char *startSpecifier, unsigned specifierLen, 7753 unsigned argIndex); 7754 7755 template <typename Range> 7756 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7757 bool IsStringLocation, Range StringRange, 7758 ArrayRef<FixItHint> Fixit = None); 7759 }; 7760 7761 } // namespace 7762 7763 SourceRange CheckFormatHandler::getFormatStringRange() { 7764 return OrigFormatExpr->getSourceRange(); 7765 } 7766 7767 CharSourceRange CheckFormatHandler:: 7768 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7769 SourceLocation Start = getLocationOfByte(startSpecifier); 7770 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7771 7772 // Advance the end SourceLocation by one due to half-open ranges. 7773 End = End.getLocWithOffset(1); 7774 7775 return CharSourceRange::getCharRange(Start, End); 7776 } 7777 7778 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7779 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7780 S.getLangOpts(), S.Context.getTargetInfo()); 7781 } 7782 7783 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7784 unsigned specifierLen){ 7785 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7786 getLocationOfByte(startSpecifier), 7787 /*IsStringLocation*/true, 7788 getSpecifierRange(startSpecifier, specifierLen)); 7789 } 7790 7791 void CheckFormatHandler::HandleInvalidLengthModifier( 7792 const analyze_format_string::FormatSpecifier &FS, 7793 const analyze_format_string::ConversionSpecifier &CS, 7794 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7795 using namespace analyze_format_string; 7796 7797 const LengthModifier &LM = FS.getLengthModifier(); 7798 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7799 7800 // See if we know how to fix this length modifier. 7801 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7802 if (FixedLM) { 7803 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7804 getLocationOfByte(LM.getStart()), 7805 /*IsStringLocation*/true, 7806 getSpecifierRange(startSpecifier, specifierLen)); 7807 7808 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7809 << FixedLM->toString() 7810 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7811 7812 } else { 7813 FixItHint Hint; 7814 if (DiagID == diag::warn_format_nonsensical_length) 7815 Hint = FixItHint::CreateRemoval(LMRange); 7816 7817 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7818 getLocationOfByte(LM.getStart()), 7819 /*IsStringLocation*/true, 7820 getSpecifierRange(startSpecifier, specifierLen), 7821 Hint); 7822 } 7823 } 7824 7825 void CheckFormatHandler::HandleNonStandardLengthModifier( 7826 const analyze_format_string::FormatSpecifier &FS, 7827 const char *startSpecifier, unsigned specifierLen) { 7828 using namespace analyze_format_string; 7829 7830 const LengthModifier &LM = FS.getLengthModifier(); 7831 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7832 7833 // See if we know how to fix this length modifier. 7834 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7835 if (FixedLM) { 7836 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7837 << LM.toString() << 0, 7838 getLocationOfByte(LM.getStart()), 7839 /*IsStringLocation*/true, 7840 getSpecifierRange(startSpecifier, specifierLen)); 7841 7842 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7843 << FixedLM->toString() 7844 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7845 7846 } else { 7847 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7848 << LM.toString() << 0, 7849 getLocationOfByte(LM.getStart()), 7850 /*IsStringLocation*/true, 7851 getSpecifierRange(startSpecifier, specifierLen)); 7852 } 7853 } 7854 7855 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7856 const analyze_format_string::ConversionSpecifier &CS, 7857 const char *startSpecifier, unsigned specifierLen) { 7858 using namespace analyze_format_string; 7859 7860 // See if we know how to fix this conversion specifier. 7861 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7862 if (FixedCS) { 7863 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7864 << CS.toString() << /*conversion specifier*/1, 7865 getLocationOfByte(CS.getStart()), 7866 /*IsStringLocation*/true, 7867 getSpecifierRange(startSpecifier, specifierLen)); 7868 7869 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7870 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7871 << FixedCS->toString() 7872 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7873 } else { 7874 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7875 << CS.toString() << /*conversion specifier*/1, 7876 getLocationOfByte(CS.getStart()), 7877 /*IsStringLocation*/true, 7878 getSpecifierRange(startSpecifier, specifierLen)); 7879 } 7880 } 7881 7882 void CheckFormatHandler::HandlePosition(const char *startPos, 7883 unsigned posLen) { 7884 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7885 getLocationOfByte(startPos), 7886 /*IsStringLocation*/true, 7887 getSpecifierRange(startPos, posLen)); 7888 } 7889 7890 void 7891 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7892 analyze_format_string::PositionContext p) { 7893 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7894 << (unsigned) p, 7895 getLocationOfByte(startPos), /*IsStringLocation*/true, 7896 getSpecifierRange(startPos, posLen)); 7897 } 7898 7899 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7900 unsigned posLen) { 7901 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7902 getLocationOfByte(startPos), 7903 /*IsStringLocation*/true, 7904 getSpecifierRange(startPos, posLen)); 7905 } 7906 7907 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7908 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7909 // The presence of a null character is likely an error. 7910 EmitFormatDiagnostic( 7911 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7912 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7913 getFormatStringRange()); 7914 } 7915 } 7916 7917 // Note that this may return NULL if there was an error parsing or building 7918 // one of the argument expressions. 7919 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7920 return Args[FirstDataArg + i]; 7921 } 7922 7923 void CheckFormatHandler::DoneProcessing() { 7924 // Does the number of data arguments exceed the number of 7925 // format conversions in the format string? 7926 if (!HasVAListArg) { 7927 // Find any arguments that weren't covered. 7928 CoveredArgs.flip(); 7929 signed notCoveredArg = CoveredArgs.find_first(); 7930 if (notCoveredArg >= 0) { 7931 assert((unsigned)notCoveredArg < NumDataArgs); 7932 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7933 } else { 7934 UncoveredArg.setAllCovered(); 7935 } 7936 } 7937 } 7938 7939 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7940 const Expr *ArgExpr) { 7941 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7942 "Invalid state"); 7943 7944 if (!ArgExpr) 7945 return; 7946 7947 SourceLocation Loc = ArgExpr->getBeginLoc(); 7948 7949 if (S.getSourceManager().isInSystemMacro(Loc)) 7950 return; 7951 7952 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7953 for (auto E : DiagnosticExprs) 7954 PDiag << E->getSourceRange(); 7955 7956 CheckFormatHandler::EmitFormatDiagnostic( 7957 S, IsFunctionCall, DiagnosticExprs[0], 7958 PDiag, Loc, /*IsStringLocation*/false, 7959 DiagnosticExprs[0]->getSourceRange()); 7960 } 7961 7962 bool 7963 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7964 SourceLocation Loc, 7965 const char *startSpec, 7966 unsigned specifierLen, 7967 const char *csStart, 7968 unsigned csLen) { 7969 bool keepGoing = true; 7970 if (argIndex < NumDataArgs) { 7971 // Consider the argument coverered, even though the specifier doesn't 7972 // make sense. 7973 CoveredArgs.set(argIndex); 7974 } 7975 else { 7976 // If argIndex exceeds the number of data arguments we 7977 // don't issue a warning because that is just a cascade of warnings (and 7978 // they may have intended '%%' anyway). We don't want to continue processing 7979 // the format string after this point, however, as we will like just get 7980 // gibberish when trying to match arguments. 7981 keepGoing = false; 7982 } 7983 7984 StringRef Specifier(csStart, csLen); 7985 7986 // If the specifier in non-printable, it could be the first byte of a UTF-8 7987 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7988 // hex value. 7989 std::string CodePointStr; 7990 if (!llvm::sys::locale::isPrint(*csStart)) { 7991 llvm::UTF32 CodePoint; 7992 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7993 const llvm::UTF8 *E = 7994 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7995 llvm::ConversionResult Result = 7996 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7997 7998 if (Result != llvm::conversionOK) { 7999 unsigned char FirstChar = *csStart; 8000 CodePoint = (llvm::UTF32)FirstChar; 8001 } 8002 8003 llvm::raw_string_ostream OS(CodePointStr); 8004 if (CodePoint < 256) 8005 OS << "\\x" << llvm::format("%02x", CodePoint); 8006 else if (CodePoint <= 0xFFFF) 8007 OS << "\\u" << llvm::format("%04x", CodePoint); 8008 else 8009 OS << "\\U" << llvm::format("%08x", CodePoint); 8010 OS.flush(); 8011 Specifier = CodePointStr; 8012 } 8013 8014 EmitFormatDiagnostic( 8015 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8016 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8017 8018 return keepGoing; 8019 } 8020 8021 void 8022 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8023 const char *startSpec, 8024 unsigned specifierLen) { 8025 EmitFormatDiagnostic( 8026 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8027 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8028 } 8029 8030 bool 8031 CheckFormatHandler::CheckNumArgs( 8032 const analyze_format_string::FormatSpecifier &FS, 8033 const analyze_format_string::ConversionSpecifier &CS, 8034 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8035 8036 if (argIndex >= NumDataArgs) { 8037 PartialDiagnostic PDiag = FS.usesPositionalArg() 8038 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8039 << (argIndex+1) << NumDataArgs) 8040 : S.PDiag(diag::warn_printf_insufficient_data_args); 8041 EmitFormatDiagnostic( 8042 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8043 getSpecifierRange(startSpecifier, specifierLen)); 8044 8045 // Since more arguments than conversion tokens are given, by extension 8046 // all arguments are covered, so mark this as so. 8047 UncoveredArg.setAllCovered(); 8048 return false; 8049 } 8050 return true; 8051 } 8052 8053 template<typename Range> 8054 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8055 SourceLocation Loc, 8056 bool IsStringLocation, 8057 Range StringRange, 8058 ArrayRef<FixItHint> FixIt) { 8059 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8060 Loc, IsStringLocation, StringRange, FixIt); 8061 } 8062 8063 /// If the format string is not within the function call, emit a note 8064 /// so that the function call and string are in diagnostic messages. 8065 /// 8066 /// \param InFunctionCall if true, the format string is within the function 8067 /// call and only one diagnostic message will be produced. Otherwise, an 8068 /// extra note will be emitted pointing to location of the format string. 8069 /// 8070 /// \param ArgumentExpr the expression that is passed as the format string 8071 /// argument in the function call. Used for getting locations when two 8072 /// diagnostics are emitted. 8073 /// 8074 /// \param PDiag the callee should already have provided any strings for the 8075 /// diagnostic message. This function only adds locations and fixits 8076 /// to diagnostics. 8077 /// 8078 /// \param Loc primary location for diagnostic. If two diagnostics are 8079 /// required, one will be at Loc and a new SourceLocation will be created for 8080 /// the other one. 8081 /// 8082 /// \param IsStringLocation if true, Loc points to the format string should be 8083 /// used for the note. Otherwise, Loc points to the argument list and will 8084 /// be used with PDiag. 8085 /// 8086 /// \param StringRange some or all of the string to highlight. This is 8087 /// templated so it can accept either a CharSourceRange or a SourceRange. 8088 /// 8089 /// \param FixIt optional fix it hint for the format string. 8090 template <typename Range> 8091 void CheckFormatHandler::EmitFormatDiagnostic( 8092 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8093 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8094 Range StringRange, ArrayRef<FixItHint> FixIt) { 8095 if (InFunctionCall) { 8096 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8097 D << StringRange; 8098 D << FixIt; 8099 } else { 8100 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8101 << ArgumentExpr->getSourceRange(); 8102 8103 const Sema::SemaDiagnosticBuilder &Note = 8104 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8105 diag::note_format_string_defined); 8106 8107 Note << StringRange; 8108 Note << FixIt; 8109 } 8110 } 8111 8112 //===--- CHECK: Printf format string checking ------------------------------===// 8113 8114 namespace { 8115 8116 class CheckPrintfHandler : public CheckFormatHandler { 8117 public: 8118 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8119 const Expr *origFormatExpr, 8120 const Sema::FormatStringType type, unsigned firstDataArg, 8121 unsigned numDataArgs, bool isObjC, const char *beg, 8122 bool hasVAListArg, ArrayRef<const Expr *> Args, 8123 unsigned formatIdx, bool inFunctionCall, 8124 Sema::VariadicCallType CallType, 8125 llvm::SmallBitVector &CheckedVarArgs, 8126 UncoveredArgHandler &UncoveredArg) 8127 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8128 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8129 inFunctionCall, CallType, CheckedVarArgs, 8130 UncoveredArg) {} 8131 8132 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8133 8134 /// Returns true if '%@' specifiers are allowed in the format string. 8135 bool allowsObjCArg() const { 8136 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8137 FSType == Sema::FST_OSTrace; 8138 } 8139 8140 bool HandleInvalidPrintfConversionSpecifier( 8141 const analyze_printf::PrintfSpecifier &FS, 8142 const char *startSpecifier, 8143 unsigned specifierLen) override; 8144 8145 void handleInvalidMaskType(StringRef MaskType) override; 8146 8147 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8148 const char *startSpecifier, 8149 unsigned specifierLen) override; 8150 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8151 const char *StartSpecifier, 8152 unsigned SpecifierLen, 8153 const Expr *E); 8154 8155 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8156 const char *startSpecifier, unsigned specifierLen); 8157 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8158 const analyze_printf::OptionalAmount &Amt, 8159 unsigned type, 8160 const char *startSpecifier, unsigned specifierLen); 8161 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8162 const analyze_printf::OptionalFlag &flag, 8163 const char *startSpecifier, unsigned specifierLen); 8164 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8165 const analyze_printf::OptionalFlag &ignoredFlag, 8166 const analyze_printf::OptionalFlag &flag, 8167 const char *startSpecifier, unsigned specifierLen); 8168 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8169 const Expr *E); 8170 8171 void HandleEmptyObjCModifierFlag(const char *startFlag, 8172 unsigned flagLen) override; 8173 8174 void HandleInvalidObjCModifierFlag(const char *startFlag, 8175 unsigned flagLen) override; 8176 8177 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8178 const char *flagsEnd, 8179 const char *conversionPosition) 8180 override; 8181 }; 8182 8183 } // namespace 8184 8185 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8186 const analyze_printf::PrintfSpecifier &FS, 8187 const char *startSpecifier, 8188 unsigned specifierLen) { 8189 const analyze_printf::PrintfConversionSpecifier &CS = 8190 FS.getConversionSpecifier(); 8191 8192 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8193 getLocationOfByte(CS.getStart()), 8194 startSpecifier, specifierLen, 8195 CS.getStart(), CS.getLength()); 8196 } 8197 8198 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8199 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8200 } 8201 8202 bool CheckPrintfHandler::HandleAmount( 8203 const analyze_format_string::OptionalAmount &Amt, 8204 unsigned k, const char *startSpecifier, 8205 unsigned specifierLen) { 8206 if (Amt.hasDataArgument()) { 8207 if (!HasVAListArg) { 8208 unsigned argIndex = Amt.getArgIndex(); 8209 if (argIndex >= NumDataArgs) { 8210 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8211 << k, 8212 getLocationOfByte(Amt.getStart()), 8213 /*IsStringLocation*/true, 8214 getSpecifierRange(startSpecifier, specifierLen)); 8215 // Don't do any more checking. We will just emit 8216 // spurious errors. 8217 return false; 8218 } 8219 8220 // Type check the data argument. It should be an 'int'. 8221 // Although not in conformance with C99, we also allow the argument to be 8222 // an 'unsigned int' as that is a reasonably safe case. GCC also 8223 // doesn't emit a warning for that case. 8224 CoveredArgs.set(argIndex); 8225 const Expr *Arg = getDataArg(argIndex); 8226 if (!Arg) 8227 return false; 8228 8229 QualType T = Arg->getType(); 8230 8231 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8232 assert(AT.isValid()); 8233 8234 if (!AT.matchesType(S.Context, T)) { 8235 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8236 << k << AT.getRepresentativeTypeName(S.Context) 8237 << T << Arg->getSourceRange(), 8238 getLocationOfByte(Amt.getStart()), 8239 /*IsStringLocation*/true, 8240 getSpecifierRange(startSpecifier, specifierLen)); 8241 // Don't do any more checking. We will just emit 8242 // spurious errors. 8243 return false; 8244 } 8245 } 8246 } 8247 return true; 8248 } 8249 8250 void CheckPrintfHandler::HandleInvalidAmount( 8251 const analyze_printf::PrintfSpecifier &FS, 8252 const analyze_printf::OptionalAmount &Amt, 8253 unsigned type, 8254 const char *startSpecifier, 8255 unsigned specifierLen) { 8256 const analyze_printf::PrintfConversionSpecifier &CS = 8257 FS.getConversionSpecifier(); 8258 8259 FixItHint fixit = 8260 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8261 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8262 Amt.getConstantLength())) 8263 : FixItHint(); 8264 8265 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8266 << type << CS.toString(), 8267 getLocationOfByte(Amt.getStart()), 8268 /*IsStringLocation*/true, 8269 getSpecifierRange(startSpecifier, specifierLen), 8270 fixit); 8271 } 8272 8273 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8274 const analyze_printf::OptionalFlag &flag, 8275 const char *startSpecifier, 8276 unsigned specifierLen) { 8277 // Warn about pointless flag with a fixit removal. 8278 const analyze_printf::PrintfConversionSpecifier &CS = 8279 FS.getConversionSpecifier(); 8280 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8281 << flag.toString() << CS.toString(), 8282 getLocationOfByte(flag.getPosition()), 8283 /*IsStringLocation*/true, 8284 getSpecifierRange(startSpecifier, specifierLen), 8285 FixItHint::CreateRemoval( 8286 getSpecifierRange(flag.getPosition(), 1))); 8287 } 8288 8289 void CheckPrintfHandler::HandleIgnoredFlag( 8290 const analyze_printf::PrintfSpecifier &FS, 8291 const analyze_printf::OptionalFlag &ignoredFlag, 8292 const analyze_printf::OptionalFlag &flag, 8293 const char *startSpecifier, 8294 unsigned specifierLen) { 8295 // Warn about ignored flag with a fixit removal. 8296 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8297 << ignoredFlag.toString() << flag.toString(), 8298 getLocationOfByte(ignoredFlag.getPosition()), 8299 /*IsStringLocation*/true, 8300 getSpecifierRange(startSpecifier, specifierLen), 8301 FixItHint::CreateRemoval( 8302 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8303 } 8304 8305 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8306 unsigned flagLen) { 8307 // Warn about an empty flag. 8308 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8309 getLocationOfByte(startFlag), 8310 /*IsStringLocation*/true, 8311 getSpecifierRange(startFlag, flagLen)); 8312 } 8313 8314 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8315 unsigned flagLen) { 8316 // Warn about an invalid flag. 8317 auto Range = getSpecifierRange(startFlag, flagLen); 8318 StringRef flag(startFlag, flagLen); 8319 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8320 getLocationOfByte(startFlag), 8321 /*IsStringLocation*/true, 8322 Range, FixItHint::CreateRemoval(Range)); 8323 } 8324 8325 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8326 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8327 // Warn about using '[...]' without a '@' conversion. 8328 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8329 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8330 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8331 getLocationOfByte(conversionPosition), 8332 /*IsStringLocation*/true, 8333 Range, FixItHint::CreateRemoval(Range)); 8334 } 8335 8336 // Determines if the specified is a C++ class or struct containing 8337 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8338 // "c_str()"). 8339 template<typename MemberKind> 8340 static llvm::SmallPtrSet<MemberKind*, 1> 8341 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8342 const RecordType *RT = Ty->getAs<RecordType>(); 8343 llvm::SmallPtrSet<MemberKind*, 1> Results; 8344 8345 if (!RT) 8346 return Results; 8347 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8348 if (!RD || !RD->getDefinition()) 8349 return Results; 8350 8351 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8352 Sema::LookupMemberName); 8353 R.suppressDiagnostics(); 8354 8355 // We just need to include all members of the right kind turned up by the 8356 // filter, at this point. 8357 if (S.LookupQualifiedName(R, RT->getDecl())) 8358 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8359 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8360 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8361 Results.insert(FK); 8362 } 8363 return Results; 8364 } 8365 8366 /// Check if we could call '.c_str()' on an object. 8367 /// 8368 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8369 /// allow the call, or if it would be ambiguous). 8370 bool Sema::hasCStrMethod(const Expr *E) { 8371 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8372 8373 MethodSet Results = 8374 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8375 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8376 MI != ME; ++MI) 8377 if ((*MI)->getMinRequiredArguments() == 0) 8378 return true; 8379 return false; 8380 } 8381 8382 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8383 // better diagnostic if so. AT is assumed to be valid. 8384 // Returns true when a c_str() conversion method is found. 8385 bool CheckPrintfHandler::checkForCStrMembers( 8386 const analyze_printf::ArgType &AT, const Expr *E) { 8387 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8388 8389 MethodSet Results = 8390 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8391 8392 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8393 MI != ME; ++MI) { 8394 const CXXMethodDecl *Method = *MI; 8395 if (Method->getMinRequiredArguments() == 0 && 8396 AT.matchesType(S.Context, Method->getReturnType())) { 8397 // FIXME: Suggest parens if the expression needs them. 8398 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8399 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8400 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8401 return true; 8402 } 8403 } 8404 8405 return false; 8406 } 8407 8408 bool 8409 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8410 &FS, 8411 const char *startSpecifier, 8412 unsigned specifierLen) { 8413 using namespace analyze_format_string; 8414 using namespace analyze_printf; 8415 8416 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8417 8418 if (FS.consumesDataArgument()) { 8419 if (atFirstArg) { 8420 atFirstArg = false; 8421 usesPositionalArgs = FS.usesPositionalArg(); 8422 } 8423 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8424 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8425 startSpecifier, specifierLen); 8426 return false; 8427 } 8428 } 8429 8430 // First check if the field width, precision, and conversion specifier 8431 // have matching data arguments. 8432 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8433 startSpecifier, specifierLen)) { 8434 return false; 8435 } 8436 8437 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8438 startSpecifier, specifierLen)) { 8439 return false; 8440 } 8441 8442 if (!CS.consumesDataArgument()) { 8443 // FIXME: Technically specifying a precision or field width here 8444 // makes no sense. Worth issuing a warning at some point. 8445 return true; 8446 } 8447 8448 // Consume the argument. 8449 unsigned argIndex = FS.getArgIndex(); 8450 if (argIndex < NumDataArgs) { 8451 // The check to see if the argIndex is valid will come later. 8452 // We set the bit here because we may exit early from this 8453 // function if we encounter some other error. 8454 CoveredArgs.set(argIndex); 8455 } 8456 8457 // FreeBSD kernel extensions. 8458 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8459 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8460 // We need at least two arguments. 8461 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8462 return false; 8463 8464 // Claim the second argument. 8465 CoveredArgs.set(argIndex + 1); 8466 8467 // Type check the first argument (int for %b, pointer for %D) 8468 const Expr *Ex = getDataArg(argIndex); 8469 const analyze_printf::ArgType &AT = 8470 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8471 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8472 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8473 EmitFormatDiagnostic( 8474 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8475 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8476 << false << Ex->getSourceRange(), 8477 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8478 getSpecifierRange(startSpecifier, specifierLen)); 8479 8480 // Type check the second argument (char * for both %b and %D) 8481 Ex = getDataArg(argIndex + 1); 8482 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8483 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8484 EmitFormatDiagnostic( 8485 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8486 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8487 << false << Ex->getSourceRange(), 8488 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8489 getSpecifierRange(startSpecifier, specifierLen)); 8490 8491 return true; 8492 } 8493 8494 // Check for using an Objective-C specific conversion specifier 8495 // in a non-ObjC literal. 8496 if (!allowsObjCArg() && CS.isObjCArg()) { 8497 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8498 specifierLen); 8499 } 8500 8501 // %P can only be used with os_log. 8502 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8503 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8504 specifierLen); 8505 } 8506 8507 // %n is not allowed with os_log. 8508 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8509 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8510 getLocationOfByte(CS.getStart()), 8511 /*IsStringLocation*/ false, 8512 getSpecifierRange(startSpecifier, specifierLen)); 8513 8514 return true; 8515 } 8516 8517 // Only scalars are allowed for os_trace. 8518 if (FSType == Sema::FST_OSTrace && 8519 (CS.getKind() == ConversionSpecifier::PArg || 8520 CS.getKind() == ConversionSpecifier::sArg || 8521 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8522 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8523 specifierLen); 8524 } 8525 8526 // Check for use of public/private annotation outside of os_log(). 8527 if (FSType != Sema::FST_OSLog) { 8528 if (FS.isPublic().isSet()) { 8529 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8530 << "public", 8531 getLocationOfByte(FS.isPublic().getPosition()), 8532 /*IsStringLocation*/ false, 8533 getSpecifierRange(startSpecifier, specifierLen)); 8534 } 8535 if (FS.isPrivate().isSet()) { 8536 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8537 << "private", 8538 getLocationOfByte(FS.isPrivate().getPosition()), 8539 /*IsStringLocation*/ false, 8540 getSpecifierRange(startSpecifier, specifierLen)); 8541 } 8542 } 8543 8544 // Check for invalid use of field width 8545 if (!FS.hasValidFieldWidth()) { 8546 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8547 startSpecifier, specifierLen); 8548 } 8549 8550 // Check for invalid use of precision 8551 if (!FS.hasValidPrecision()) { 8552 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8553 startSpecifier, specifierLen); 8554 } 8555 8556 // Precision is mandatory for %P specifier. 8557 if (CS.getKind() == ConversionSpecifier::PArg && 8558 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8559 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8560 getLocationOfByte(startSpecifier), 8561 /*IsStringLocation*/ false, 8562 getSpecifierRange(startSpecifier, specifierLen)); 8563 } 8564 8565 // Check each flag does not conflict with any other component. 8566 if (!FS.hasValidThousandsGroupingPrefix()) 8567 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8568 if (!FS.hasValidLeadingZeros()) 8569 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8570 if (!FS.hasValidPlusPrefix()) 8571 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8572 if (!FS.hasValidSpacePrefix()) 8573 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8574 if (!FS.hasValidAlternativeForm()) 8575 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8576 if (!FS.hasValidLeftJustified()) 8577 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8578 8579 // Check that flags are not ignored by another flag 8580 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8581 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8582 startSpecifier, specifierLen); 8583 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8584 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8585 startSpecifier, specifierLen); 8586 8587 // Check the length modifier is valid with the given conversion specifier. 8588 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8589 S.getLangOpts())) 8590 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8591 diag::warn_format_nonsensical_length); 8592 else if (!FS.hasStandardLengthModifier()) 8593 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8594 else if (!FS.hasStandardLengthConversionCombination()) 8595 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8596 diag::warn_format_non_standard_conversion_spec); 8597 8598 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8599 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8600 8601 // The remaining checks depend on the data arguments. 8602 if (HasVAListArg) 8603 return true; 8604 8605 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8606 return false; 8607 8608 const Expr *Arg = getDataArg(argIndex); 8609 if (!Arg) 8610 return true; 8611 8612 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8613 } 8614 8615 static bool requiresParensToAddCast(const Expr *E) { 8616 // FIXME: We should have a general way to reason about operator 8617 // precedence and whether parens are actually needed here. 8618 // Take care of a few common cases where they aren't. 8619 const Expr *Inside = E->IgnoreImpCasts(); 8620 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8621 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8622 8623 switch (Inside->getStmtClass()) { 8624 case Stmt::ArraySubscriptExprClass: 8625 case Stmt::CallExprClass: 8626 case Stmt::CharacterLiteralClass: 8627 case Stmt::CXXBoolLiteralExprClass: 8628 case Stmt::DeclRefExprClass: 8629 case Stmt::FloatingLiteralClass: 8630 case Stmt::IntegerLiteralClass: 8631 case Stmt::MemberExprClass: 8632 case Stmt::ObjCArrayLiteralClass: 8633 case Stmt::ObjCBoolLiteralExprClass: 8634 case Stmt::ObjCBoxedExprClass: 8635 case Stmt::ObjCDictionaryLiteralClass: 8636 case Stmt::ObjCEncodeExprClass: 8637 case Stmt::ObjCIvarRefExprClass: 8638 case Stmt::ObjCMessageExprClass: 8639 case Stmt::ObjCPropertyRefExprClass: 8640 case Stmt::ObjCStringLiteralClass: 8641 case Stmt::ObjCSubscriptRefExprClass: 8642 case Stmt::ParenExprClass: 8643 case Stmt::StringLiteralClass: 8644 case Stmt::UnaryOperatorClass: 8645 return false; 8646 default: 8647 return true; 8648 } 8649 } 8650 8651 static std::pair<QualType, StringRef> 8652 shouldNotPrintDirectly(const ASTContext &Context, 8653 QualType IntendedTy, 8654 const Expr *E) { 8655 // Use a 'while' to peel off layers of typedefs. 8656 QualType TyTy = IntendedTy; 8657 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8658 StringRef Name = UserTy->getDecl()->getName(); 8659 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8660 .Case("CFIndex", Context.getNSIntegerType()) 8661 .Case("NSInteger", Context.getNSIntegerType()) 8662 .Case("NSUInteger", Context.getNSUIntegerType()) 8663 .Case("SInt32", Context.IntTy) 8664 .Case("UInt32", Context.UnsignedIntTy) 8665 .Default(QualType()); 8666 8667 if (!CastTy.isNull()) 8668 return std::make_pair(CastTy, Name); 8669 8670 TyTy = UserTy->desugar(); 8671 } 8672 8673 // Strip parens if necessary. 8674 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8675 return shouldNotPrintDirectly(Context, 8676 PE->getSubExpr()->getType(), 8677 PE->getSubExpr()); 8678 8679 // If this is a conditional expression, then its result type is constructed 8680 // via usual arithmetic conversions and thus there might be no necessary 8681 // typedef sugar there. Recurse to operands to check for NSInteger & 8682 // Co. usage condition. 8683 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8684 QualType TrueTy, FalseTy; 8685 StringRef TrueName, FalseName; 8686 8687 std::tie(TrueTy, TrueName) = 8688 shouldNotPrintDirectly(Context, 8689 CO->getTrueExpr()->getType(), 8690 CO->getTrueExpr()); 8691 std::tie(FalseTy, FalseName) = 8692 shouldNotPrintDirectly(Context, 8693 CO->getFalseExpr()->getType(), 8694 CO->getFalseExpr()); 8695 8696 if (TrueTy == FalseTy) 8697 return std::make_pair(TrueTy, TrueName); 8698 else if (TrueTy.isNull()) 8699 return std::make_pair(FalseTy, FalseName); 8700 else if (FalseTy.isNull()) 8701 return std::make_pair(TrueTy, TrueName); 8702 } 8703 8704 return std::make_pair(QualType(), StringRef()); 8705 } 8706 8707 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8708 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8709 /// type do not count. 8710 static bool 8711 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8712 QualType From = ICE->getSubExpr()->getType(); 8713 QualType To = ICE->getType(); 8714 // It's an integer promotion if the destination type is the promoted 8715 // source type. 8716 if (ICE->getCastKind() == CK_IntegralCast && 8717 From->isPromotableIntegerType() && 8718 S.Context.getPromotedIntegerType(From) == To) 8719 return true; 8720 // Look through vector types, since we do default argument promotion for 8721 // those in OpenCL. 8722 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8723 From = VecTy->getElementType(); 8724 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8725 To = VecTy->getElementType(); 8726 // It's a floating promotion if the source type is a lower rank. 8727 return ICE->getCastKind() == CK_FloatingCast && 8728 S.Context.getFloatingTypeOrder(From, To) < 0; 8729 } 8730 8731 bool 8732 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8733 const char *StartSpecifier, 8734 unsigned SpecifierLen, 8735 const Expr *E) { 8736 using namespace analyze_format_string; 8737 using namespace analyze_printf; 8738 8739 // Now type check the data expression that matches the 8740 // format specifier. 8741 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8742 if (!AT.isValid()) 8743 return true; 8744 8745 QualType ExprTy = E->getType(); 8746 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8747 ExprTy = TET->getUnderlyingExpr()->getType(); 8748 } 8749 8750 // Diagnose attempts to print a boolean value as a character. Unlike other 8751 // -Wformat diagnostics, this is fine from a type perspective, but it still 8752 // doesn't make sense. 8753 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8754 E->isKnownToHaveBooleanValue()) { 8755 const CharSourceRange &CSR = 8756 getSpecifierRange(StartSpecifier, SpecifierLen); 8757 SmallString<4> FSString; 8758 llvm::raw_svector_ostream os(FSString); 8759 FS.toString(os); 8760 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8761 << FSString, 8762 E->getExprLoc(), false, CSR); 8763 return true; 8764 } 8765 8766 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8767 if (Match == analyze_printf::ArgType::Match) 8768 return true; 8769 8770 // Look through argument promotions for our error message's reported type. 8771 // This includes the integral and floating promotions, but excludes array 8772 // and function pointer decay (seeing that an argument intended to be a 8773 // string has type 'char [6]' is probably more confusing than 'char *') and 8774 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8775 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8776 if (isArithmeticArgumentPromotion(S, ICE)) { 8777 E = ICE->getSubExpr(); 8778 ExprTy = E->getType(); 8779 8780 // Check if we didn't match because of an implicit cast from a 'char' 8781 // or 'short' to an 'int'. This is done because printf is a varargs 8782 // function. 8783 if (ICE->getType() == S.Context.IntTy || 8784 ICE->getType() == S.Context.UnsignedIntTy) { 8785 // All further checking is done on the subexpression 8786 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8787 AT.matchesType(S.Context, ExprTy); 8788 if (ImplicitMatch == analyze_printf::ArgType::Match) 8789 return true; 8790 if (ImplicitMatch == ArgType::NoMatchPedantic || 8791 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8792 Match = ImplicitMatch; 8793 } 8794 } 8795 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8796 // Special case for 'a', which has type 'int' in C. 8797 // Note, however, that we do /not/ want to treat multibyte constants like 8798 // 'MooV' as characters! This form is deprecated but still exists. In 8799 // addition, don't treat expressions as of type 'char' if one byte length 8800 // modifier is provided. 8801 if (ExprTy == S.Context.IntTy && 8802 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 8803 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8804 ExprTy = S.Context.CharTy; 8805 } 8806 8807 // Look through enums to their underlying type. 8808 bool IsEnum = false; 8809 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8810 ExprTy = EnumTy->getDecl()->getIntegerType(); 8811 IsEnum = true; 8812 } 8813 8814 // %C in an Objective-C context prints a unichar, not a wchar_t. 8815 // If the argument is an integer of some kind, believe the %C and suggest 8816 // a cast instead of changing the conversion specifier. 8817 QualType IntendedTy = ExprTy; 8818 if (isObjCContext() && 8819 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8820 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8821 !ExprTy->isCharType()) { 8822 // 'unichar' is defined as a typedef of unsigned short, but we should 8823 // prefer using the typedef if it is visible. 8824 IntendedTy = S.Context.UnsignedShortTy; 8825 8826 // While we are here, check if the value is an IntegerLiteral that happens 8827 // to be within the valid range. 8828 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8829 const llvm::APInt &V = IL->getValue(); 8830 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8831 return true; 8832 } 8833 8834 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8835 Sema::LookupOrdinaryName); 8836 if (S.LookupName(Result, S.getCurScope())) { 8837 NamedDecl *ND = Result.getFoundDecl(); 8838 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8839 if (TD->getUnderlyingType() == IntendedTy) 8840 IntendedTy = S.Context.getTypedefType(TD); 8841 } 8842 } 8843 } 8844 8845 // Special-case some of Darwin's platform-independence types by suggesting 8846 // casts to primitive types that are known to be large enough. 8847 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8848 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8849 QualType CastTy; 8850 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8851 if (!CastTy.isNull()) { 8852 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8853 // (long in ASTContext). Only complain to pedants. 8854 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8855 (AT.isSizeT() || AT.isPtrdiffT()) && 8856 AT.matchesType(S.Context, CastTy)) 8857 Match = ArgType::NoMatchPedantic; 8858 IntendedTy = CastTy; 8859 ShouldNotPrintDirectly = true; 8860 } 8861 } 8862 8863 // We may be able to offer a FixItHint if it is a supported type. 8864 PrintfSpecifier fixedFS = FS; 8865 bool Success = 8866 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8867 8868 if (Success) { 8869 // Get the fix string from the fixed format specifier 8870 SmallString<16> buf; 8871 llvm::raw_svector_ostream os(buf); 8872 fixedFS.toString(os); 8873 8874 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8875 8876 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8877 unsigned Diag; 8878 switch (Match) { 8879 case ArgType::Match: llvm_unreachable("expected non-matching"); 8880 case ArgType::NoMatchPedantic: 8881 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8882 break; 8883 case ArgType::NoMatchTypeConfusion: 8884 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8885 break; 8886 case ArgType::NoMatch: 8887 Diag = diag::warn_format_conversion_argument_type_mismatch; 8888 break; 8889 } 8890 8891 // In this case, the specifier is wrong and should be changed to match 8892 // the argument. 8893 EmitFormatDiagnostic(S.PDiag(Diag) 8894 << AT.getRepresentativeTypeName(S.Context) 8895 << IntendedTy << IsEnum << E->getSourceRange(), 8896 E->getBeginLoc(), 8897 /*IsStringLocation*/ false, SpecRange, 8898 FixItHint::CreateReplacement(SpecRange, os.str())); 8899 } else { 8900 // The canonical type for formatting this value is different from the 8901 // actual type of the expression. (This occurs, for example, with Darwin's 8902 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8903 // should be printed as 'long' for 64-bit compatibility.) 8904 // Rather than emitting a normal format/argument mismatch, we want to 8905 // add a cast to the recommended type (and correct the format string 8906 // if necessary). 8907 SmallString<16> CastBuf; 8908 llvm::raw_svector_ostream CastFix(CastBuf); 8909 CastFix << "("; 8910 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8911 CastFix << ")"; 8912 8913 SmallVector<FixItHint,4> Hints; 8914 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8915 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8916 8917 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8918 // If there's already a cast present, just replace it. 8919 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8920 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8921 8922 } else if (!requiresParensToAddCast(E)) { 8923 // If the expression has high enough precedence, 8924 // just write the C-style cast. 8925 Hints.push_back( 8926 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8927 } else { 8928 // Otherwise, add parens around the expression as well as the cast. 8929 CastFix << "("; 8930 Hints.push_back( 8931 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8932 8933 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8934 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8935 } 8936 8937 if (ShouldNotPrintDirectly) { 8938 // The expression has a type that should not be printed directly. 8939 // We extract the name from the typedef because we don't want to show 8940 // the underlying type in the diagnostic. 8941 StringRef Name; 8942 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8943 Name = TypedefTy->getDecl()->getName(); 8944 else 8945 Name = CastTyName; 8946 unsigned Diag = Match == ArgType::NoMatchPedantic 8947 ? diag::warn_format_argument_needs_cast_pedantic 8948 : diag::warn_format_argument_needs_cast; 8949 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8950 << E->getSourceRange(), 8951 E->getBeginLoc(), /*IsStringLocation=*/false, 8952 SpecRange, Hints); 8953 } else { 8954 // In this case, the expression could be printed using a different 8955 // specifier, but we've decided that the specifier is probably correct 8956 // and we should cast instead. Just use the normal warning message. 8957 EmitFormatDiagnostic( 8958 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8959 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8960 << E->getSourceRange(), 8961 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8962 } 8963 } 8964 } else { 8965 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8966 SpecifierLen); 8967 // Since the warning for passing non-POD types to variadic functions 8968 // was deferred until now, we emit a warning for non-POD 8969 // arguments here. 8970 switch (S.isValidVarArgType(ExprTy)) { 8971 case Sema::VAK_Valid: 8972 case Sema::VAK_ValidInCXX11: { 8973 unsigned Diag; 8974 switch (Match) { 8975 case ArgType::Match: llvm_unreachable("expected non-matching"); 8976 case ArgType::NoMatchPedantic: 8977 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8978 break; 8979 case ArgType::NoMatchTypeConfusion: 8980 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8981 break; 8982 case ArgType::NoMatch: 8983 Diag = diag::warn_format_conversion_argument_type_mismatch; 8984 break; 8985 } 8986 8987 EmitFormatDiagnostic( 8988 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8989 << IsEnum << CSR << E->getSourceRange(), 8990 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8991 break; 8992 } 8993 case Sema::VAK_Undefined: 8994 case Sema::VAK_MSVCUndefined: 8995 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8996 << S.getLangOpts().CPlusPlus11 << ExprTy 8997 << CallType 8998 << AT.getRepresentativeTypeName(S.Context) << CSR 8999 << E->getSourceRange(), 9000 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9001 checkForCStrMembers(AT, E); 9002 break; 9003 9004 case Sema::VAK_Invalid: 9005 if (ExprTy->isObjCObjectType()) 9006 EmitFormatDiagnostic( 9007 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9008 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9009 << AT.getRepresentativeTypeName(S.Context) << CSR 9010 << E->getSourceRange(), 9011 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9012 else 9013 // FIXME: If this is an initializer list, suggest removing the braces 9014 // or inserting a cast to the target type. 9015 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9016 << isa<InitListExpr>(E) << ExprTy << CallType 9017 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9018 break; 9019 } 9020 9021 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9022 "format string specifier index out of range"); 9023 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9024 } 9025 9026 return true; 9027 } 9028 9029 //===--- CHECK: Scanf format string checking ------------------------------===// 9030 9031 namespace { 9032 9033 class CheckScanfHandler : public CheckFormatHandler { 9034 public: 9035 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9036 const Expr *origFormatExpr, Sema::FormatStringType type, 9037 unsigned firstDataArg, unsigned numDataArgs, 9038 const char *beg, bool hasVAListArg, 9039 ArrayRef<const Expr *> Args, unsigned formatIdx, 9040 bool inFunctionCall, Sema::VariadicCallType CallType, 9041 llvm::SmallBitVector &CheckedVarArgs, 9042 UncoveredArgHandler &UncoveredArg) 9043 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9044 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9045 inFunctionCall, CallType, CheckedVarArgs, 9046 UncoveredArg) {} 9047 9048 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9049 const char *startSpecifier, 9050 unsigned specifierLen) override; 9051 9052 bool HandleInvalidScanfConversionSpecifier( 9053 const analyze_scanf::ScanfSpecifier &FS, 9054 const char *startSpecifier, 9055 unsigned specifierLen) override; 9056 9057 void HandleIncompleteScanList(const char *start, const char *end) override; 9058 }; 9059 9060 } // namespace 9061 9062 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9063 const char *end) { 9064 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9065 getLocationOfByte(end), /*IsStringLocation*/true, 9066 getSpecifierRange(start, end - start)); 9067 } 9068 9069 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9070 const analyze_scanf::ScanfSpecifier &FS, 9071 const char *startSpecifier, 9072 unsigned specifierLen) { 9073 const analyze_scanf::ScanfConversionSpecifier &CS = 9074 FS.getConversionSpecifier(); 9075 9076 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9077 getLocationOfByte(CS.getStart()), 9078 startSpecifier, specifierLen, 9079 CS.getStart(), CS.getLength()); 9080 } 9081 9082 bool CheckScanfHandler::HandleScanfSpecifier( 9083 const analyze_scanf::ScanfSpecifier &FS, 9084 const char *startSpecifier, 9085 unsigned specifierLen) { 9086 using namespace analyze_scanf; 9087 using namespace analyze_format_string; 9088 9089 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9090 9091 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9092 // be used to decide if we are using positional arguments consistently. 9093 if (FS.consumesDataArgument()) { 9094 if (atFirstArg) { 9095 atFirstArg = false; 9096 usesPositionalArgs = FS.usesPositionalArg(); 9097 } 9098 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9099 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9100 startSpecifier, specifierLen); 9101 return false; 9102 } 9103 } 9104 9105 // Check if the field with is non-zero. 9106 const OptionalAmount &Amt = FS.getFieldWidth(); 9107 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9108 if (Amt.getConstantAmount() == 0) { 9109 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9110 Amt.getConstantLength()); 9111 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9112 getLocationOfByte(Amt.getStart()), 9113 /*IsStringLocation*/true, R, 9114 FixItHint::CreateRemoval(R)); 9115 } 9116 } 9117 9118 if (!FS.consumesDataArgument()) { 9119 // FIXME: Technically specifying a precision or field width here 9120 // makes no sense. Worth issuing a warning at some point. 9121 return true; 9122 } 9123 9124 // Consume the argument. 9125 unsigned argIndex = FS.getArgIndex(); 9126 if (argIndex < NumDataArgs) { 9127 // The check to see if the argIndex is valid will come later. 9128 // We set the bit here because we may exit early from this 9129 // function if we encounter some other error. 9130 CoveredArgs.set(argIndex); 9131 } 9132 9133 // Check the length modifier is valid with the given conversion specifier. 9134 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9135 S.getLangOpts())) 9136 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9137 diag::warn_format_nonsensical_length); 9138 else if (!FS.hasStandardLengthModifier()) 9139 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9140 else if (!FS.hasStandardLengthConversionCombination()) 9141 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9142 diag::warn_format_non_standard_conversion_spec); 9143 9144 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9145 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9146 9147 // The remaining checks depend on the data arguments. 9148 if (HasVAListArg) 9149 return true; 9150 9151 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9152 return false; 9153 9154 // Check that the argument type matches the format specifier. 9155 const Expr *Ex = getDataArg(argIndex); 9156 if (!Ex) 9157 return true; 9158 9159 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9160 9161 if (!AT.isValid()) { 9162 return true; 9163 } 9164 9165 analyze_format_string::ArgType::MatchKind Match = 9166 AT.matchesType(S.Context, Ex->getType()); 9167 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9168 if (Match == analyze_format_string::ArgType::Match) 9169 return true; 9170 9171 ScanfSpecifier fixedFS = FS; 9172 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9173 S.getLangOpts(), S.Context); 9174 9175 unsigned Diag = 9176 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9177 : diag::warn_format_conversion_argument_type_mismatch; 9178 9179 if (Success) { 9180 // Get the fix string from the fixed format specifier. 9181 SmallString<128> buf; 9182 llvm::raw_svector_ostream os(buf); 9183 fixedFS.toString(os); 9184 9185 EmitFormatDiagnostic( 9186 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9187 << Ex->getType() << false << Ex->getSourceRange(), 9188 Ex->getBeginLoc(), 9189 /*IsStringLocation*/ false, 9190 getSpecifierRange(startSpecifier, specifierLen), 9191 FixItHint::CreateReplacement( 9192 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9193 } else { 9194 EmitFormatDiagnostic(S.PDiag(Diag) 9195 << AT.getRepresentativeTypeName(S.Context) 9196 << Ex->getType() << false << Ex->getSourceRange(), 9197 Ex->getBeginLoc(), 9198 /*IsStringLocation*/ false, 9199 getSpecifierRange(startSpecifier, specifierLen)); 9200 } 9201 9202 return true; 9203 } 9204 9205 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9206 const Expr *OrigFormatExpr, 9207 ArrayRef<const Expr *> Args, 9208 bool HasVAListArg, unsigned format_idx, 9209 unsigned firstDataArg, 9210 Sema::FormatStringType Type, 9211 bool inFunctionCall, 9212 Sema::VariadicCallType CallType, 9213 llvm::SmallBitVector &CheckedVarArgs, 9214 UncoveredArgHandler &UncoveredArg, 9215 bool IgnoreStringsWithoutSpecifiers) { 9216 // CHECK: is the format string a wide literal? 9217 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9218 CheckFormatHandler::EmitFormatDiagnostic( 9219 S, inFunctionCall, Args[format_idx], 9220 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9221 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9222 return; 9223 } 9224 9225 // Str - The format string. NOTE: this is NOT null-terminated! 9226 StringRef StrRef = FExpr->getString(); 9227 const char *Str = StrRef.data(); 9228 // Account for cases where the string literal is truncated in a declaration. 9229 const ConstantArrayType *T = 9230 S.Context.getAsConstantArrayType(FExpr->getType()); 9231 assert(T && "String literal not of constant array type!"); 9232 size_t TypeSize = T->getSize().getZExtValue(); 9233 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9234 const unsigned numDataArgs = Args.size() - firstDataArg; 9235 9236 if (IgnoreStringsWithoutSpecifiers && 9237 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9238 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9239 return; 9240 9241 // Emit a warning if the string literal is truncated and does not contain an 9242 // embedded null character. 9243 if (TypeSize <= StrRef.size() && 9244 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9245 CheckFormatHandler::EmitFormatDiagnostic( 9246 S, inFunctionCall, Args[format_idx], 9247 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9248 FExpr->getBeginLoc(), 9249 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9250 return; 9251 } 9252 9253 // CHECK: empty format string? 9254 if (StrLen == 0 && numDataArgs > 0) { 9255 CheckFormatHandler::EmitFormatDiagnostic( 9256 S, inFunctionCall, Args[format_idx], 9257 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9258 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9259 return; 9260 } 9261 9262 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9263 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9264 Type == Sema::FST_OSTrace) { 9265 CheckPrintfHandler H( 9266 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9267 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9268 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9269 CheckedVarArgs, UncoveredArg); 9270 9271 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9272 S.getLangOpts(), 9273 S.Context.getTargetInfo(), 9274 Type == Sema::FST_FreeBSDKPrintf)) 9275 H.DoneProcessing(); 9276 } else if (Type == Sema::FST_Scanf) { 9277 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9278 numDataArgs, Str, HasVAListArg, Args, format_idx, 9279 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9280 9281 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9282 S.getLangOpts(), 9283 S.Context.getTargetInfo())) 9284 H.DoneProcessing(); 9285 } // TODO: handle other formats 9286 } 9287 9288 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9289 // Str - The format string. NOTE: this is NOT null-terminated! 9290 StringRef StrRef = FExpr->getString(); 9291 const char *Str = StrRef.data(); 9292 // Account for cases where the string literal is truncated in a declaration. 9293 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9294 assert(T && "String literal not of constant array type!"); 9295 size_t TypeSize = T->getSize().getZExtValue(); 9296 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9297 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9298 getLangOpts(), 9299 Context.getTargetInfo()); 9300 } 9301 9302 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9303 9304 // Returns the related absolute value function that is larger, of 0 if one 9305 // does not exist. 9306 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9307 switch (AbsFunction) { 9308 default: 9309 return 0; 9310 9311 case Builtin::BI__builtin_abs: 9312 return Builtin::BI__builtin_labs; 9313 case Builtin::BI__builtin_labs: 9314 return Builtin::BI__builtin_llabs; 9315 case Builtin::BI__builtin_llabs: 9316 return 0; 9317 9318 case Builtin::BI__builtin_fabsf: 9319 return Builtin::BI__builtin_fabs; 9320 case Builtin::BI__builtin_fabs: 9321 return Builtin::BI__builtin_fabsl; 9322 case Builtin::BI__builtin_fabsl: 9323 return 0; 9324 9325 case Builtin::BI__builtin_cabsf: 9326 return Builtin::BI__builtin_cabs; 9327 case Builtin::BI__builtin_cabs: 9328 return Builtin::BI__builtin_cabsl; 9329 case Builtin::BI__builtin_cabsl: 9330 return 0; 9331 9332 case Builtin::BIabs: 9333 return Builtin::BIlabs; 9334 case Builtin::BIlabs: 9335 return Builtin::BIllabs; 9336 case Builtin::BIllabs: 9337 return 0; 9338 9339 case Builtin::BIfabsf: 9340 return Builtin::BIfabs; 9341 case Builtin::BIfabs: 9342 return Builtin::BIfabsl; 9343 case Builtin::BIfabsl: 9344 return 0; 9345 9346 case Builtin::BIcabsf: 9347 return Builtin::BIcabs; 9348 case Builtin::BIcabs: 9349 return Builtin::BIcabsl; 9350 case Builtin::BIcabsl: 9351 return 0; 9352 } 9353 } 9354 9355 // Returns the argument type of the absolute value function. 9356 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9357 unsigned AbsType) { 9358 if (AbsType == 0) 9359 return QualType(); 9360 9361 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9362 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9363 if (Error != ASTContext::GE_None) 9364 return QualType(); 9365 9366 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9367 if (!FT) 9368 return QualType(); 9369 9370 if (FT->getNumParams() != 1) 9371 return QualType(); 9372 9373 return FT->getParamType(0); 9374 } 9375 9376 // Returns the best absolute value function, or zero, based on type and 9377 // current absolute value function. 9378 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9379 unsigned AbsFunctionKind) { 9380 unsigned BestKind = 0; 9381 uint64_t ArgSize = Context.getTypeSize(ArgType); 9382 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9383 Kind = getLargerAbsoluteValueFunction(Kind)) { 9384 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9385 if (Context.getTypeSize(ParamType) >= ArgSize) { 9386 if (BestKind == 0) 9387 BestKind = Kind; 9388 else if (Context.hasSameType(ParamType, ArgType)) { 9389 BestKind = Kind; 9390 break; 9391 } 9392 } 9393 } 9394 return BestKind; 9395 } 9396 9397 enum AbsoluteValueKind { 9398 AVK_Integer, 9399 AVK_Floating, 9400 AVK_Complex 9401 }; 9402 9403 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9404 if (T->isIntegralOrEnumerationType()) 9405 return AVK_Integer; 9406 if (T->isRealFloatingType()) 9407 return AVK_Floating; 9408 if (T->isAnyComplexType()) 9409 return AVK_Complex; 9410 9411 llvm_unreachable("Type not integer, floating, or complex"); 9412 } 9413 9414 // Changes the absolute value function to a different type. Preserves whether 9415 // the function is a builtin. 9416 static unsigned changeAbsFunction(unsigned AbsKind, 9417 AbsoluteValueKind ValueKind) { 9418 switch (ValueKind) { 9419 case AVK_Integer: 9420 switch (AbsKind) { 9421 default: 9422 return 0; 9423 case Builtin::BI__builtin_fabsf: 9424 case Builtin::BI__builtin_fabs: 9425 case Builtin::BI__builtin_fabsl: 9426 case Builtin::BI__builtin_cabsf: 9427 case Builtin::BI__builtin_cabs: 9428 case Builtin::BI__builtin_cabsl: 9429 return Builtin::BI__builtin_abs; 9430 case Builtin::BIfabsf: 9431 case Builtin::BIfabs: 9432 case Builtin::BIfabsl: 9433 case Builtin::BIcabsf: 9434 case Builtin::BIcabs: 9435 case Builtin::BIcabsl: 9436 return Builtin::BIabs; 9437 } 9438 case AVK_Floating: 9439 switch (AbsKind) { 9440 default: 9441 return 0; 9442 case Builtin::BI__builtin_abs: 9443 case Builtin::BI__builtin_labs: 9444 case Builtin::BI__builtin_llabs: 9445 case Builtin::BI__builtin_cabsf: 9446 case Builtin::BI__builtin_cabs: 9447 case Builtin::BI__builtin_cabsl: 9448 return Builtin::BI__builtin_fabsf; 9449 case Builtin::BIabs: 9450 case Builtin::BIlabs: 9451 case Builtin::BIllabs: 9452 case Builtin::BIcabsf: 9453 case Builtin::BIcabs: 9454 case Builtin::BIcabsl: 9455 return Builtin::BIfabsf; 9456 } 9457 case AVK_Complex: 9458 switch (AbsKind) { 9459 default: 9460 return 0; 9461 case Builtin::BI__builtin_abs: 9462 case Builtin::BI__builtin_labs: 9463 case Builtin::BI__builtin_llabs: 9464 case Builtin::BI__builtin_fabsf: 9465 case Builtin::BI__builtin_fabs: 9466 case Builtin::BI__builtin_fabsl: 9467 return Builtin::BI__builtin_cabsf; 9468 case Builtin::BIabs: 9469 case Builtin::BIlabs: 9470 case Builtin::BIllabs: 9471 case Builtin::BIfabsf: 9472 case Builtin::BIfabs: 9473 case Builtin::BIfabsl: 9474 return Builtin::BIcabsf; 9475 } 9476 } 9477 llvm_unreachable("Unable to convert function"); 9478 } 9479 9480 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9481 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9482 if (!FnInfo) 9483 return 0; 9484 9485 switch (FDecl->getBuiltinID()) { 9486 default: 9487 return 0; 9488 case Builtin::BI__builtin_abs: 9489 case Builtin::BI__builtin_fabs: 9490 case Builtin::BI__builtin_fabsf: 9491 case Builtin::BI__builtin_fabsl: 9492 case Builtin::BI__builtin_labs: 9493 case Builtin::BI__builtin_llabs: 9494 case Builtin::BI__builtin_cabs: 9495 case Builtin::BI__builtin_cabsf: 9496 case Builtin::BI__builtin_cabsl: 9497 case Builtin::BIabs: 9498 case Builtin::BIlabs: 9499 case Builtin::BIllabs: 9500 case Builtin::BIfabs: 9501 case Builtin::BIfabsf: 9502 case Builtin::BIfabsl: 9503 case Builtin::BIcabs: 9504 case Builtin::BIcabsf: 9505 case Builtin::BIcabsl: 9506 return FDecl->getBuiltinID(); 9507 } 9508 llvm_unreachable("Unknown Builtin type"); 9509 } 9510 9511 // If the replacement is valid, emit a note with replacement function. 9512 // Additionally, suggest including the proper header if not already included. 9513 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9514 unsigned AbsKind, QualType ArgType) { 9515 bool EmitHeaderHint = true; 9516 const char *HeaderName = nullptr; 9517 const char *FunctionName = nullptr; 9518 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9519 FunctionName = "std::abs"; 9520 if (ArgType->isIntegralOrEnumerationType()) { 9521 HeaderName = "cstdlib"; 9522 } else if (ArgType->isRealFloatingType()) { 9523 HeaderName = "cmath"; 9524 } else { 9525 llvm_unreachable("Invalid Type"); 9526 } 9527 9528 // Lookup all std::abs 9529 if (NamespaceDecl *Std = S.getStdNamespace()) { 9530 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9531 R.suppressDiagnostics(); 9532 S.LookupQualifiedName(R, Std); 9533 9534 for (const auto *I : R) { 9535 const FunctionDecl *FDecl = nullptr; 9536 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9537 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9538 } else { 9539 FDecl = dyn_cast<FunctionDecl>(I); 9540 } 9541 if (!FDecl) 9542 continue; 9543 9544 // Found std::abs(), check that they are the right ones. 9545 if (FDecl->getNumParams() != 1) 9546 continue; 9547 9548 // Check that the parameter type can handle the argument. 9549 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9550 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9551 S.Context.getTypeSize(ArgType) <= 9552 S.Context.getTypeSize(ParamType)) { 9553 // Found a function, don't need the header hint. 9554 EmitHeaderHint = false; 9555 break; 9556 } 9557 } 9558 } 9559 } else { 9560 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9561 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9562 9563 if (HeaderName) { 9564 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9565 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9566 R.suppressDiagnostics(); 9567 S.LookupName(R, S.getCurScope()); 9568 9569 if (R.isSingleResult()) { 9570 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9571 if (FD && FD->getBuiltinID() == AbsKind) { 9572 EmitHeaderHint = false; 9573 } else { 9574 return; 9575 } 9576 } else if (!R.empty()) { 9577 return; 9578 } 9579 } 9580 } 9581 9582 S.Diag(Loc, diag::note_replace_abs_function) 9583 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9584 9585 if (!HeaderName) 9586 return; 9587 9588 if (!EmitHeaderHint) 9589 return; 9590 9591 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9592 << FunctionName; 9593 } 9594 9595 template <std::size_t StrLen> 9596 static bool IsStdFunction(const FunctionDecl *FDecl, 9597 const char (&Str)[StrLen]) { 9598 if (!FDecl) 9599 return false; 9600 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9601 return false; 9602 if (!FDecl->isInStdNamespace()) 9603 return false; 9604 9605 return true; 9606 } 9607 9608 // Warn when using the wrong abs() function. 9609 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9610 const FunctionDecl *FDecl) { 9611 if (Call->getNumArgs() != 1) 9612 return; 9613 9614 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9615 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9616 if (AbsKind == 0 && !IsStdAbs) 9617 return; 9618 9619 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9620 QualType ParamType = Call->getArg(0)->getType(); 9621 9622 // Unsigned types cannot be negative. Suggest removing the absolute value 9623 // function call. 9624 if (ArgType->isUnsignedIntegerType()) { 9625 const char *FunctionName = 9626 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9627 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9628 Diag(Call->getExprLoc(), diag::note_remove_abs) 9629 << FunctionName 9630 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9631 return; 9632 } 9633 9634 // Taking the absolute value of a pointer is very suspicious, they probably 9635 // wanted to index into an array, dereference a pointer, call a function, etc. 9636 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9637 unsigned DiagType = 0; 9638 if (ArgType->isFunctionType()) 9639 DiagType = 1; 9640 else if (ArgType->isArrayType()) 9641 DiagType = 2; 9642 9643 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9644 return; 9645 } 9646 9647 // std::abs has overloads which prevent most of the absolute value problems 9648 // from occurring. 9649 if (IsStdAbs) 9650 return; 9651 9652 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9653 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9654 9655 // The argument and parameter are the same kind. Check if they are the right 9656 // size. 9657 if (ArgValueKind == ParamValueKind) { 9658 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9659 return; 9660 9661 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9662 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9663 << FDecl << ArgType << ParamType; 9664 9665 if (NewAbsKind == 0) 9666 return; 9667 9668 emitReplacement(*this, Call->getExprLoc(), 9669 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9670 return; 9671 } 9672 9673 // ArgValueKind != ParamValueKind 9674 // The wrong type of absolute value function was used. Attempt to find the 9675 // proper one. 9676 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9677 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9678 if (NewAbsKind == 0) 9679 return; 9680 9681 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9682 << FDecl << ParamValueKind << ArgValueKind; 9683 9684 emitReplacement(*this, Call->getExprLoc(), 9685 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9686 } 9687 9688 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9689 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9690 const FunctionDecl *FDecl) { 9691 if (!Call || !FDecl) return; 9692 9693 // Ignore template specializations and macros. 9694 if (inTemplateInstantiation()) return; 9695 if (Call->getExprLoc().isMacroID()) return; 9696 9697 // Only care about the one template argument, two function parameter std::max 9698 if (Call->getNumArgs() != 2) return; 9699 if (!IsStdFunction(FDecl, "max")) return; 9700 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9701 if (!ArgList) return; 9702 if (ArgList->size() != 1) return; 9703 9704 // Check that template type argument is unsigned integer. 9705 const auto& TA = ArgList->get(0); 9706 if (TA.getKind() != TemplateArgument::Type) return; 9707 QualType ArgType = TA.getAsType(); 9708 if (!ArgType->isUnsignedIntegerType()) return; 9709 9710 // See if either argument is a literal zero. 9711 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9712 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9713 if (!MTE) return false; 9714 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9715 if (!Num) return false; 9716 if (Num->getValue() != 0) return false; 9717 return true; 9718 }; 9719 9720 const Expr *FirstArg = Call->getArg(0); 9721 const Expr *SecondArg = Call->getArg(1); 9722 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9723 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9724 9725 // Only warn when exactly one argument is zero. 9726 if (IsFirstArgZero == IsSecondArgZero) return; 9727 9728 SourceRange FirstRange = FirstArg->getSourceRange(); 9729 SourceRange SecondRange = SecondArg->getSourceRange(); 9730 9731 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9732 9733 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9734 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9735 9736 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9737 SourceRange RemovalRange; 9738 if (IsFirstArgZero) { 9739 RemovalRange = SourceRange(FirstRange.getBegin(), 9740 SecondRange.getBegin().getLocWithOffset(-1)); 9741 } else { 9742 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9743 SecondRange.getEnd()); 9744 } 9745 9746 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9747 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9748 << FixItHint::CreateRemoval(RemovalRange); 9749 } 9750 9751 //===--- CHECK: Standard memory functions ---------------------------------===// 9752 9753 /// Takes the expression passed to the size_t parameter of functions 9754 /// such as memcmp, strncat, etc and warns if it's a comparison. 9755 /// 9756 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9757 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9758 IdentifierInfo *FnName, 9759 SourceLocation FnLoc, 9760 SourceLocation RParenLoc) { 9761 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9762 if (!Size) 9763 return false; 9764 9765 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9766 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9767 return false; 9768 9769 SourceRange SizeRange = Size->getSourceRange(); 9770 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9771 << SizeRange << FnName; 9772 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9773 << FnName 9774 << FixItHint::CreateInsertion( 9775 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9776 << FixItHint::CreateRemoval(RParenLoc); 9777 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9778 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9779 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9780 ")"); 9781 9782 return true; 9783 } 9784 9785 /// Determine whether the given type is or contains a dynamic class type 9786 /// (e.g., whether it has a vtable). 9787 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9788 bool &IsContained) { 9789 // Look through array types while ignoring qualifiers. 9790 const Type *Ty = T->getBaseElementTypeUnsafe(); 9791 IsContained = false; 9792 9793 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9794 RD = RD ? RD->getDefinition() : nullptr; 9795 if (!RD || RD->isInvalidDecl()) 9796 return nullptr; 9797 9798 if (RD->isDynamicClass()) 9799 return RD; 9800 9801 // Check all the fields. If any bases were dynamic, the class is dynamic. 9802 // It's impossible for a class to transitively contain itself by value, so 9803 // infinite recursion is impossible. 9804 for (auto *FD : RD->fields()) { 9805 bool SubContained; 9806 if (const CXXRecordDecl *ContainedRD = 9807 getContainedDynamicClass(FD->getType(), SubContained)) { 9808 IsContained = true; 9809 return ContainedRD; 9810 } 9811 } 9812 9813 return nullptr; 9814 } 9815 9816 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9817 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9818 if (Unary->getKind() == UETT_SizeOf) 9819 return Unary; 9820 return nullptr; 9821 } 9822 9823 /// If E is a sizeof expression, returns its argument expression, 9824 /// otherwise returns NULL. 9825 static const Expr *getSizeOfExprArg(const Expr *E) { 9826 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9827 if (!SizeOf->isArgumentType()) 9828 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9829 return nullptr; 9830 } 9831 9832 /// If E is a sizeof expression, returns its argument type. 9833 static QualType getSizeOfArgType(const Expr *E) { 9834 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9835 return SizeOf->getTypeOfArgument(); 9836 return QualType(); 9837 } 9838 9839 namespace { 9840 9841 struct SearchNonTrivialToInitializeField 9842 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9843 using Super = 9844 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9845 9846 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9847 9848 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9849 SourceLocation SL) { 9850 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9851 asDerived().visitArray(PDIK, AT, SL); 9852 return; 9853 } 9854 9855 Super::visitWithKind(PDIK, FT, SL); 9856 } 9857 9858 void visitARCStrong(QualType FT, SourceLocation SL) { 9859 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9860 } 9861 void visitARCWeak(QualType FT, SourceLocation SL) { 9862 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9863 } 9864 void visitStruct(QualType FT, SourceLocation SL) { 9865 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9866 visit(FD->getType(), FD->getLocation()); 9867 } 9868 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9869 const ArrayType *AT, SourceLocation SL) { 9870 visit(getContext().getBaseElementType(AT), SL); 9871 } 9872 void visitTrivial(QualType FT, SourceLocation SL) {} 9873 9874 static void diag(QualType RT, const Expr *E, Sema &S) { 9875 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9876 } 9877 9878 ASTContext &getContext() { return S.getASTContext(); } 9879 9880 const Expr *E; 9881 Sema &S; 9882 }; 9883 9884 struct SearchNonTrivialToCopyField 9885 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9886 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9887 9888 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9889 9890 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9891 SourceLocation SL) { 9892 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9893 asDerived().visitArray(PCK, AT, SL); 9894 return; 9895 } 9896 9897 Super::visitWithKind(PCK, FT, SL); 9898 } 9899 9900 void visitARCStrong(QualType FT, SourceLocation SL) { 9901 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9902 } 9903 void visitARCWeak(QualType FT, SourceLocation SL) { 9904 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9905 } 9906 void visitStruct(QualType FT, SourceLocation SL) { 9907 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9908 visit(FD->getType(), FD->getLocation()); 9909 } 9910 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9911 SourceLocation SL) { 9912 visit(getContext().getBaseElementType(AT), SL); 9913 } 9914 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9915 SourceLocation SL) {} 9916 void visitTrivial(QualType FT, SourceLocation SL) {} 9917 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9918 9919 static void diag(QualType RT, const Expr *E, Sema &S) { 9920 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9921 } 9922 9923 ASTContext &getContext() { return S.getASTContext(); } 9924 9925 const Expr *E; 9926 Sema &S; 9927 }; 9928 9929 } 9930 9931 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9932 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9933 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9934 9935 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9936 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9937 return false; 9938 9939 return doesExprLikelyComputeSize(BO->getLHS()) || 9940 doesExprLikelyComputeSize(BO->getRHS()); 9941 } 9942 9943 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9944 } 9945 9946 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9947 /// 9948 /// \code 9949 /// #define MACRO 0 9950 /// foo(MACRO); 9951 /// foo(0); 9952 /// \endcode 9953 /// 9954 /// This should return true for the first call to foo, but not for the second 9955 /// (regardless of whether foo is a macro or function). 9956 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9957 SourceLocation CallLoc, 9958 SourceLocation ArgLoc) { 9959 if (!CallLoc.isMacroID()) 9960 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9961 9962 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9963 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9964 } 9965 9966 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9967 /// last two arguments transposed. 9968 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9969 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9970 return; 9971 9972 const Expr *SizeArg = 9973 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9974 9975 auto isLiteralZero = [](const Expr *E) { 9976 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9977 }; 9978 9979 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9980 SourceLocation CallLoc = Call->getRParenLoc(); 9981 SourceManager &SM = S.getSourceManager(); 9982 if (isLiteralZero(SizeArg) && 9983 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9984 9985 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9986 9987 // Some platforms #define bzero to __builtin_memset. See if this is the 9988 // case, and if so, emit a better diagnostic. 9989 if (BId == Builtin::BIbzero || 9990 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9991 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9992 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9993 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9994 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9995 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9996 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9997 } 9998 return; 9999 } 10000 10001 // If the second argument to a memset is a sizeof expression and the third 10002 // isn't, this is also likely an error. This should catch 10003 // 'memset(buf, sizeof(buf), 0xff)'. 10004 if (BId == Builtin::BImemset && 10005 doesExprLikelyComputeSize(Call->getArg(1)) && 10006 !doesExprLikelyComputeSize(Call->getArg(2))) { 10007 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10008 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10009 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10010 return; 10011 } 10012 } 10013 10014 /// Check for dangerous or invalid arguments to memset(). 10015 /// 10016 /// This issues warnings on known problematic, dangerous or unspecified 10017 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10018 /// function calls. 10019 /// 10020 /// \param Call The call expression to diagnose. 10021 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10022 unsigned BId, 10023 IdentifierInfo *FnName) { 10024 assert(BId != 0); 10025 10026 // It is possible to have a non-standard definition of memset. Validate 10027 // we have enough arguments, and if not, abort further checking. 10028 unsigned ExpectedNumArgs = 10029 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10030 if (Call->getNumArgs() < ExpectedNumArgs) 10031 return; 10032 10033 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10034 BId == Builtin::BIstrndup ? 1 : 2); 10035 unsigned LenArg = 10036 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10037 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10038 10039 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10040 Call->getBeginLoc(), Call->getRParenLoc())) 10041 return; 10042 10043 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10044 CheckMemaccessSize(*this, BId, Call); 10045 10046 // We have special checking when the length is a sizeof expression. 10047 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10048 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10049 llvm::FoldingSetNodeID SizeOfArgID; 10050 10051 // Although widely used, 'bzero' is not a standard function. Be more strict 10052 // with the argument types before allowing diagnostics and only allow the 10053 // form bzero(ptr, sizeof(...)). 10054 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10055 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10056 return; 10057 10058 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10059 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10060 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10061 10062 QualType DestTy = Dest->getType(); 10063 QualType PointeeTy; 10064 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10065 PointeeTy = DestPtrTy->getPointeeType(); 10066 10067 // Never warn about void type pointers. This can be used to suppress 10068 // false positives. 10069 if (PointeeTy->isVoidType()) 10070 continue; 10071 10072 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10073 // actually comparing the expressions for equality. Because computing the 10074 // expression IDs can be expensive, we only do this if the diagnostic is 10075 // enabled. 10076 if (SizeOfArg && 10077 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10078 SizeOfArg->getExprLoc())) { 10079 // We only compute IDs for expressions if the warning is enabled, and 10080 // cache the sizeof arg's ID. 10081 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10082 SizeOfArg->Profile(SizeOfArgID, Context, true); 10083 llvm::FoldingSetNodeID DestID; 10084 Dest->Profile(DestID, Context, true); 10085 if (DestID == SizeOfArgID) { 10086 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10087 // over sizeof(src) as well. 10088 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10089 StringRef ReadableName = FnName->getName(); 10090 10091 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10092 if (UnaryOp->getOpcode() == UO_AddrOf) 10093 ActionIdx = 1; // If its an address-of operator, just remove it. 10094 if (!PointeeTy->isIncompleteType() && 10095 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10096 ActionIdx = 2; // If the pointee's size is sizeof(char), 10097 // suggest an explicit length. 10098 10099 // If the function is defined as a builtin macro, do not show macro 10100 // expansion. 10101 SourceLocation SL = SizeOfArg->getExprLoc(); 10102 SourceRange DSR = Dest->getSourceRange(); 10103 SourceRange SSR = SizeOfArg->getSourceRange(); 10104 SourceManager &SM = getSourceManager(); 10105 10106 if (SM.isMacroArgExpansion(SL)) { 10107 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10108 SL = SM.getSpellingLoc(SL); 10109 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10110 SM.getSpellingLoc(DSR.getEnd())); 10111 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10112 SM.getSpellingLoc(SSR.getEnd())); 10113 } 10114 10115 DiagRuntimeBehavior(SL, SizeOfArg, 10116 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10117 << ReadableName 10118 << PointeeTy 10119 << DestTy 10120 << DSR 10121 << SSR); 10122 DiagRuntimeBehavior(SL, SizeOfArg, 10123 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10124 << ActionIdx 10125 << SSR); 10126 10127 break; 10128 } 10129 } 10130 10131 // Also check for cases where the sizeof argument is the exact same 10132 // type as the memory argument, and where it points to a user-defined 10133 // record type. 10134 if (SizeOfArgTy != QualType()) { 10135 if (PointeeTy->isRecordType() && 10136 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10137 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10138 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10139 << FnName << SizeOfArgTy << ArgIdx 10140 << PointeeTy << Dest->getSourceRange() 10141 << LenExpr->getSourceRange()); 10142 break; 10143 } 10144 } 10145 } else if (DestTy->isArrayType()) { 10146 PointeeTy = DestTy; 10147 } 10148 10149 if (PointeeTy == QualType()) 10150 continue; 10151 10152 // Always complain about dynamic classes. 10153 bool IsContained; 10154 if (const CXXRecordDecl *ContainedRD = 10155 getContainedDynamicClass(PointeeTy, IsContained)) { 10156 10157 unsigned OperationType = 0; 10158 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10159 // "overwritten" if we're warning about the destination for any call 10160 // but memcmp; otherwise a verb appropriate to the call. 10161 if (ArgIdx != 0 || IsCmp) { 10162 if (BId == Builtin::BImemcpy) 10163 OperationType = 1; 10164 else if(BId == Builtin::BImemmove) 10165 OperationType = 2; 10166 else if (IsCmp) 10167 OperationType = 3; 10168 } 10169 10170 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10171 PDiag(diag::warn_dyn_class_memaccess) 10172 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10173 << IsContained << ContainedRD << OperationType 10174 << Call->getCallee()->getSourceRange()); 10175 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10176 BId != Builtin::BImemset) 10177 DiagRuntimeBehavior( 10178 Dest->getExprLoc(), Dest, 10179 PDiag(diag::warn_arc_object_memaccess) 10180 << ArgIdx << FnName << PointeeTy 10181 << Call->getCallee()->getSourceRange()); 10182 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10183 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10184 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10185 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10186 PDiag(diag::warn_cstruct_memaccess) 10187 << ArgIdx << FnName << PointeeTy << 0); 10188 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10189 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10190 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10191 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10192 PDiag(diag::warn_cstruct_memaccess) 10193 << ArgIdx << FnName << PointeeTy << 1); 10194 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10195 } else { 10196 continue; 10197 } 10198 } else 10199 continue; 10200 10201 DiagRuntimeBehavior( 10202 Dest->getExprLoc(), Dest, 10203 PDiag(diag::note_bad_memaccess_silence) 10204 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10205 break; 10206 } 10207 } 10208 10209 // A little helper routine: ignore addition and subtraction of integer literals. 10210 // This intentionally does not ignore all integer constant expressions because 10211 // we don't want to remove sizeof(). 10212 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10213 Ex = Ex->IgnoreParenCasts(); 10214 10215 while (true) { 10216 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10217 if (!BO || !BO->isAdditiveOp()) 10218 break; 10219 10220 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10221 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10222 10223 if (isa<IntegerLiteral>(RHS)) 10224 Ex = LHS; 10225 else if (isa<IntegerLiteral>(LHS)) 10226 Ex = RHS; 10227 else 10228 break; 10229 } 10230 10231 return Ex; 10232 } 10233 10234 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10235 ASTContext &Context) { 10236 // Only handle constant-sized or VLAs, but not flexible members. 10237 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10238 // Only issue the FIXIT for arrays of size > 1. 10239 if (CAT->getSize().getSExtValue() <= 1) 10240 return false; 10241 } else if (!Ty->isVariableArrayType()) { 10242 return false; 10243 } 10244 return true; 10245 } 10246 10247 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10248 // be the size of the source, instead of the destination. 10249 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10250 IdentifierInfo *FnName) { 10251 10252 // Don't crash if the user has the wrong number of arguments 10253 unsigned NumArgs = Call->getNumArgs(); 10254 if ((NumArgs != 3) && (NumArgs != 4)) 10255 return; 10256 10257 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10258 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10259 const Expr *CompareWithSrc = nullptr; 10260 10261 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10262 Call->getBeginLoc(), Call->getRParenLoc())) 10263 return; 10264 10265 // Look for 'strlcpy(dst, x, sizeof(x))' 10266 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10267 CompareWithSrc = Ex; 10268 else { 10269 // Look for 'strlcpy(dst, x, strlen(x))' 10270 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10271 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10272 SizeCall->getNumArgs() == 1) 10273 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10274 } 10275 } 10276 10277 if (!CompareWithSrc) 10278 return; 10279 10280 // Determine if the argument to sizeof/strlen is equal to the source 10281 // argument. In principle there's all kinds of things you could do 10282 // here, for instance creating an == expression and evaluating it with 10283 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10284 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10285 if (!SrcArgDRE) 10286 return; 10287 10288 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10289 if (!CompareWithSrcDRE || 10290 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10291 return; 10292 10293 const Expr *OriginalSizeArg = Call->getArg(2); 10294 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10295 << OriginalSizeArg->getSourceRange() << FnName; 10296 10297 // Output a FIXIT hint if the destination is an array (rather than a 10298 // pointer to an array). This could be enhanced to handle some 10299 // pointers if we know the actual size, like if DstArg is 'array+2' 10300 // we could say 'sizeof(array)-2'. 10301 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10302 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10303 return; 10304 10305 SmallString<128> sizeString; 10306 llvm::raw_svector_ostream OS(sizeString); 10307 OS << "sizeof("; 10308 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10309 OS << ")"; 10310 10311 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10312 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10313 OS.str()); 10314 } 10315 10316 /// Check if two expressions refer to the same declaration. 10317 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10318 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10319 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10320 return D1->getDecl() == D2->getDecl(); 10321 return false; 10322 } 10323 10324 static const Expr *getStrlenExprArg(const Expr *E) { 10325 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10326 const FunctionDecl *FD = CE->getDirectCallee(); 10327 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10328 return nullptr; 10329 return CE->getArg(0)->IgnoreParenCasts(); 10330 } 10331 return nullptr; 10332 } 10333 10334 // Warn on anti-patterns as the 'size' argument to strncat. 10335 // The correct size argument should look like following: 10336 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10337 void Sema::CheckStrncatArguments(const CallExpr *CE, 10338 IdentifierInfo *FnName) { 10339 // Don't crash if the user has the wrong number of arguments. 10340 if (CE->getNumArgs() < 3) 10341 return; 10342 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10343 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10344 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10345 10346 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10347 CE->getRParenLoc())) 10348 return; 10349 10350 // Identify common expressions, which are wrongly used as the size argument 10351 // to strncat and may lead to buffer overflows. 10352 unsigned PatternType = 0; 10353 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10354 // - sizeof(dst) 10355 if (referToTheSameDecl(SizeOfArg, DstArg)) 10356 PatternType = 1; 10357 // - sizeof(src) 10358 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10359 PatternType = 2; 10360 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10361 if (BE->getOpcode() == BO_Sub) { 10362 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10363 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10364 // - sizeof(dst) - strlen(dst) 10365 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10366 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10367 PatternType = 1; 10368 // - sizeof(src) - (anything) 10369 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10370 PatternType = 2; 10371 } 10372 } 10373 10374 if (PatternType == 0) 10375 return; 10376 10377 // Generate the diagnostic. 10378 SourceLocation SL = LenArg->getBeginLoc(); 10379 SourceRange SR = LenArg->getSourceRange(); 10380 SourceManager &SM = getSourceManager(); 10381 10382 // If the function is defined as a builtin macro, do not show macro expansion. 10383 if (SM.isMacroArgExpansion(SL)) { 10384 SL = SM.getSpellingLoc(SL); 10385 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10386 SM.getSpellingLoc(SR.getEnd())); 10387 } 10388 10389 // Check if the destination is an array (rather than a pointer to an array). 10390 QualType DstTy = DstArg->getType(); 10391 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10392 Context); 10393 if (!isKnownSizeArray) { 10394 if (PatternType == 1) 10395 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10396 else 10397 Diag(SL, diag::warn_strncat_src_size) << SR; 10398 return; 10399 } 10400 10401 if (PatternType == 1) 10402 Diag(SL, diag::warn_strncat_large_size) << SR; 10403 else 10404 Diag(SL, diag::warn_strncat_src_size) << SR; 10405 10406 SmallString<128> sizeString; 10407 llvm::raw_svector_ostream OS(sizeString); 10408 OS << "sizeof("; 10409 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10410 OS << ") - "; 10411 OS << "strlen("; 10412 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10413 OS << ") - 1"; 10414 10415 Diag(SL, diag::note_strncat_wrong_size) 10416 << FixItHint::CreateReplacement(SR, OS.str()); 10417 } 10418 10419 namespace { 10420 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10421 const UnaryOperator *UnaryExpr, const Decl *D) { 10422 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10423 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10424 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10425 return; 10426 } 10427 } 10428 10429 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10430 const UnaryOperator *UnaryExpr) { 10431 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10432 const Decl *D = Lvalue->getDecl(); 10433 if (isa<VarDecl, FunctionDecl>(D)) 10434 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10435 } 10436 10437 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10438 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10439 Lvalue->getMemberDecl()); 10440 } 10441 10442 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10443 const UnaryOperator *UnaryExpr) { 10444 const auto *Lambda = dyn_cast<LambdaExpr>( 10445 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10446 if (!Lambda) 10447 return; 10448 10449 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10450 << CalleeName << 2 /*object: lambda expression*/; 10451 } 10452 10453 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10454 const DeclRefExpr *Lvalue) { 10455 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10456 if (Var == nullptr) 10457 return; 10458 10459 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10460 << CalleeName << 0 /*object: */ << Var; 10461 } 10462 10463 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10464 const CastExpr *Cast) { 10465 SmallString<128> SizeString; 10466 llvm::raw_svector_ostream OS(SizeString); 10467 10468 clang::CastKind Kind = Cast->getCastKind(); 10469 if (Kind == clang::CK_BitCast && 10470 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10471 return; 10472 if (Kind == clang::CK_IntegralToPointer && 10473 !isa<IntegerLiteral>( 10474 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10475 return; 10476 10477 switch (Cast->getCastKind()) { 10478 case clang::CK_BitCast: 10479 case clang::CK_IntegralToPointer: 10480 case clang::CK_FunctionToPointerDecay: 10481 OS << '\''; 10482 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10483 OS << '\''; 10484 break; 10485 default: 10486 return; 10487 } 10488 10489 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10490 << CalleeName << 0 /*object: */ << OS.str(); 10491 } 10492 } // namespace 10493 10494 /// Alerts the user that they are attempting to free a non-malloc'd object. 10495 void Sema::CheckFreeArguments(const CallExpr *E) { 10496 const std::string CalleeName = 10497 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10498 10499 { // Prefer something that doesn't involve a cast to make things simpler. 10500 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10501 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10502 switch (UnaryExpr->getOpcode()) { 10503 case UnaryOperator::Opcode::UO_AddrOf: 10504 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10505 case UnaryOperator::Opcode::UO_Plus: 10506 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10507 default: 10508 break; 10509 } 10510 10511 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10512 if (Lvalue->getType()->isArrayType()) 10513 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10514 10515 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10516 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10517 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10518 return; 10519 } 10520 10521 if (isa<BlockExpr>(Arg)) { 10522 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10523 << CalleeName << 1 /*object: block*/; 10524 return; 10525 } 10526 } 10527 // Maybe the cast was important, check after the other cases. 10528 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10529 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10530 } 10531 10532 void 10533 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10534 SourceLocation ReturnLoc, 10535 bool isObjCMethod, 10536 const AttrVec *Attrs, 10537 const FunctionDecl *FD) { 10538 // Check if the return value is null but should not be. 10539 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10540 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10541 CheckNonNullExpr(*this, RetValExp)) 10542 Diag(ReturnLoc, diag::warn_null_ret) 10543 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10544 10545 // C++11 [basic.stc.dynamic.allocation]p4: 10546 // If an allocation function declared with a non-throwing 10547 // exception-specification fails to allocate storage, it shall return 10548 // a null pointer. Any other allocation function that fails to allocate 10549 // storage shall indicate failure only by throwing an exception [...] 10550 if (FD) { 10551 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10552 if (Op == OO_New || Op == OO_Array_New) { 10553 const FunctionProtoType *Proto 10554 = FD->getType()->castAs<FunctionProtoType>(); 10555 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10556 CheckNonNullExpr(*this, RetValExp)) 10557 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10558 << FD << getLangOpts().CPlusPlus11; 10559 } 10560 } 10561 10562 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10563 // here prevent the user from using a PPC MMA type as trailing return type. 10564 if (Context.getTargetInfo().getTriple().isPPC64()) 10565 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10566 } 10567 10568 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10569 10570 /// Check for comparisons of floating point operands using != and ==. 10571 /// Issue a warning if these are no self-comparisons, as they are not likely 10572 /// to do what the programmer intended. 10573 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10574 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10575 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10576 10577 // Special case: check for x == x (which is OK). 10578 // Do not emit warnings for such cases. 10579 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10580 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10581 if (DRL->getDecl() == DRR->getDecl()) 10582 return; 10583 10584 // Special case: check for comparisons against literals that can be exactly 10585 // represented by APFloat. In such cases, do not emit a warning. This 10586 // is a heuristic: often comparison against such literals are used to 10587 // detect if a value in a variable has not changed. This clearly can 10588 // lead to false negatives. 10589 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10590 if (FLL->isExact()) 10591 return; 10592 } else 10593 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10594 if (FLR->isExact()) 10595 return; 10596 10597 // Check for comparisons with builtin types. 10598 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10599 if (CL->getBuiltinCallee()) 10600 return; 10601 10602 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10603 if (CR->getBuiltinCallee()) 10604 return; 10605 10606 // Emit the diagnostic. 10607 Diag(Loc, diag::warn_floatingpoint_eq) 10608 << LHS->getSourceRange() << RHS->getSourceRange(); 10609 } 10610 10611 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10612 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10613 10614 namespace { 10615 10616 /// Structure recording the 'active' range of an integer-valued 10617 /// expression. 10618 struct IntRange { 10619 /// The number of bits active in the int. Note that this includes exactly one 10620 /// sign bit if !NonNegative. 10621 unsigned Width; 10622 10623 /// True if the int is known not to have negative values. If so, all leading 10624 /// bits before Width are known zero, otherwise they are known to be the 10625 /// same as the MSB within Width. 10626 bool NonNegative; 10627 10628 IntRange(unsigned Width, bool NonNegative) 10629 : Width(Width), NonNegative(NonNegative) {} 10630 10631 /// Number of bits excluding the sign bit. 10632 unsigned valueBits() const { 10633 return NonNegative ? Width : Width - 1; 10634 } 10635 10636 /// Returns the range of the bool type. 10637 static IntRange forBoolType() { 10638 return IntRange(1, true); 10639 } 10640 10641 /// Returns the range of an opaque value of the given integral type. 10642 static IntRange forValueOfType(ASTContext &C, QualType T) { 10643 return forValueOfCanonicalType(C, 10644 T->getCanonicalTypeInternal().getTypePtr()); 10645 } 10646 10647 /// Returns the range of an opaque value of a canonical integral type. 10648 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10649 assert(T->isCanonicalUnqualified()); 10650 10651 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10652 T = VT->getElementType().getTypePtr(); 10653 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10654 T = CT->getElementType().getTypePtr(); 10655 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10656 T = AT->getValueType().getTypePtr(); 10657 10658 if (!C.getLangOpts().CPlusPlus) { 10659 // For enum types in C code, use the underlying datatype. 10660 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10661 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10662 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10663 // For enum types in C++, use the known bit width of the enumerators. 10664 EnumDecl *Enum = ET->getDecl(); 10665 // In C++11, enums can have a fixed underlying type. Use this type to 10666 // compute the range. 10667 if (Enum->isFixed()) { 10668 return IntRange(C.getIntWidth(QualType(T, 0)), 10669 !ET->isSignedIntegerOrEnumerationType()); 10670 } 10671 10672 unsigned NumPositive = Enum->getNumPositiveBits(); 10673 unsigned NumNegative = Enum->getNumNegativeBits(); 10674 10675 if (NumNegative == 0) 10676 return IntRange(NumPositive, true/*NonNegative*/); 10677 else 10678 return IntRange(std::max(NumPositive + 1, NumNegative), 10679 false/*NonNegative*/); 10680 } 10681 10682 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10683 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10684 10685 const BuiltinType *BT = cast<BuiltinType>(T); 10686 assert(BT->isInteger()); 10687 10688 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10689 } 10690 10691 /// Returns the "target" range of a canonical integral type, i.e. 10692 /// the range of values expressible in the type. 10693 /// 10694 /// This matches forValueOfCanonicalType except that enums have the 10695 /// full range of their type, not the range of their enumerators. 10696 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10697 assert(T->isCanonicalUnqualified()); 10698 10699 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10700 T = VT->getElementType().getTypePtr(); 10701 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10702 T = CT->getElementType().getTypePtr(); 10703 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10704 T = AT->getValueType().getTypePtr(); 10705 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10706 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10707 10708 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10709 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10710 10711 const BuiltinType *BT = cast<BuiltinType>(T); 10712 assert(BT->isInteger()); 10713 10714 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10715 } 10716 10717 /// Returns the supremum of two ranges: i.e. their conservative merge. 10718 static IntRange join(IntRange L, IntRange R) { 10719 bool Unsigned = L.NonNegative && R.NonNegative; 10720 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10721 L.NonNegative && R.NonNegative); 10722 } 10723 10724 /// Return the range of a bitwise-AND of the two ranges. 10725 static IntRange bit_and(IntRange L, IntRange R) { 10726 unsigned Bits = std::max(L.Width, R.Width); 10727 bool NonNegative = false; 10728 if (L.NonNegative) { 10729 Bits = std::min(Bits, L.Width); 10730 NonNegative = true; 10731 } 10732 if (R.NonNegative) { 10733 Bits = std::min(Bits, R.Width); 10734 NonNegative = true; 10735 } 10736 return IntRange(Bits, NonNegative); 10737 } 10738 10739 /// Return the range of a sum of the two ranges. 10740 static IntRange sum(IntRange L, IntRange R) { 10741 bool Unsigned = L.NonNegative && R.NonNegative; 10742 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10743 Unsigned); 10744 } 10745 10746 /// Return the range of a difference of the two ranges. 10747 static IntRange difference(IntRange L, IntRange R) { 10748 // We need a 1-bit-wider range if: 10749 // 1) LHS can be negative: least value can be reduced. 10750 // 2) RHS can be negative: greatest value can be increased. 10751 bool CanWiden = !L.NonNegative || !R.NonNegative; 10752 bool Unsigned = L.NonNegative && R.Width == 0; 10753 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10754 !Unsigned, 10755 Unsigned); 10756 } 10757 10758 /// Return the range of a product of the two ranges. 10759 static IntRange product(IntRange L, IntRange R) { 10760 // If both LHS and RHS can be negative, we can form 10761 // -2^L * -2^R = 2^(L + R) 10762 // which requires L + R + 1 value bits to represent. 10763 bool CanWiden = !L.NonNegative && !R.NonNegative; 10764 bool Unsigned = L.NonNegative && R.NonNegative; 10765 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10766 Unsigned); 10767 } 10768 10769 /// Return the range of a remainder operation between the two ranges. 10770 static IntRange rem(IntRange L, IntRange R) { 10771 // The result of a remainder can't be larger than the result of 10772 // either side. The sign of the result is the sign of the LHS. 10773 bool Unsigned = L.NonNegative; 10774 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10775 Unsigned); 10776 } 10777 }; 10778 10779 } // namespace 10780 10781 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10782 unsigned MaxWidth) { 10783 if (value.isSigned() && value.isNegative()) 10784 return IntRange(value.getMinSignedBits(), false); 10785 10786 if (value.getBitWidth() > MaxWidth) 10787 value = value.trunc(MaxWidth); 10788 10789 // isNonNegative() just checks the sign bit without considering 10790 // signedness. 10791 return IntRange(value.getActiveBits(), true); 10792 } 10793 10794 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10795 unsigned MaxWidth) { 10796 if (result.isInt()) 10797 return GetValueRange(C, result.getInt(), MaxWidth); 10798 10799 if (result.isVector()) { 10800 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10801 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10802 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10803 R = IntRange::join(R, El); 10804 } 10805 return R; 10806 } 10807 10808 if (result.isComplexInt()) { 10809 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10810 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10811 return IntRange::join(R, I); 10812 } 10813 10814 // This can happen with lossless casts to intptr_t of "based" lvalues. 10815 // Assume it might use arbitrary bits. 10816 // FIXME: The only reason we need to pass the type in here is to get 10817 // the sign right on this one case. It would be nice if APValue 10818 // preserved this. 10819 assert(result.isLValue() || result.isAddrLabelDiff()); 10820 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10821 } 10822 10823 static QualType GetExprType(const Expr *E) { 10824 QualType Ty = E->getType(); 10825 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10826 Ty = AtomicRHS->getValueType(); 10827 return Ty; 10828 } 10829 10830 /// Pseudo-evaluate the given integer expression, estimating the 10831 /// range of values it might take. 10832 /// 10833 /// \param MaxWidth The width to which the value will be truncated. 10834 /// \param Approximate If \c true, return a likely range for the result: in 10835 /// particular, assume that aritmetic on narrower types doesn't leave 10836 /// those types. If \c false, return a range including all possible 10837 /// result values. 10838 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10839 bool InConstantContext, bool Approximate) { 10840 E = E->IgnoreParens(); 10841 10842 // Try a full evaluation first. 10843 Expr::EvalResult result; 10844 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10845 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10846 10847 // I think we only want to look through implicit casts here; if the 10848 // user has an explicit widening cast, we should treat the value as 10849 // being of the new, wider type. 10850 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10851 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10852 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 10853 Approximate); 10854 10855 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10856 10857 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10858 CE->getCastKind() == CK_BooleanToSignedIntegral; 10859 10860 // Assume that non-integer casts can span the full range of the type. 10861 if (!isIntegerCast) 10862 return OutputTypeRange; 10863 10864 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10865 std::min(MaxWidth, OutputTypeRange.Width), 10866 InConstantContext, Approximate); 10867 10868 // Bail out if the subexpr's range is as wide as the cast type. 10869 if (SubRange.Width >= OutputTypeRange.Width) 10870 return OutputTypeRange; 10871 10872 // Otherwise, we take the smaller width, and we're non-negative if 10873 // either the output type or the subexpr is. 10874 return IntRange(SubRange.Width, 10875 SubRange.NonNegative || OutputTypeRange.NonNegative); 10876 } 10877 10878 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10879 // If we can fold the condition, just take that operand. 10880 bool CondResult; 10881 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10882 return GetExprRange(C, 10883 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10884 MaxWidth, InConstantContext, Approximate); 10885 10886 // Otherwise, conservatively merge. 10887 // GetExprRange requires an integer expression, but a throw expression 10888 // results in a void type. 10889 Expr *E = CO->getTrueExpr(); 10890 IntRange L = E->getType()->isVoidType() 10891 ? IntRange{0, true} 10892 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10893 E = CO->getFalseExpr(); 10894 IntRange R = E->getType()->isVoidType() 10895 ? IntRange{0, true} 10896 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10897 return IntRange::join(L, R); 10898 } 10899 10900 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10901 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 10902 10903 switch (BO->getOpcode()) { 10904 case BO_Cmp: 10905 llvm_unreachable("builtin <=> should have class type"); 10906 10907 // Boolean-valued operations are single-bit and positive. 10908 case BO_LAnd: 10909 case BO_LOr: 10910 case BO_LT: 10911 case BO_GT: 10912 case BO_LE: 10913 case BO_GE: 10914 case BO_EQ: 10915 case BO_NE: 10916 return IntRange::forBoolType(); 10917 10918 // The type of the assignments is the type of the LHS, so the RHS 10919 // is not necessarily the same type. 10920 case BO_MulAssign: 10921 case BO_DivAssign: 10922 case BO_RemAssign: 10923 case BO_AddAssign: 10924 case BO_SubAssign: 10925 case BO_XorAssign: 10926 case BO_OrAssign: 10927 // TODO: bitfields? 10928 return IntRange::forValueOfType(C, GetExprType(E)); 10929 10930 // Simple assignments just pass through the RHS, which will have 10931 // been coerced to the LHS type. 10932 case BO_Assign: 10933 // TODO: bitfields? 10934 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10935 Approximate); 10936 10937 // Operations with opaque sources are black-listed. 10938 case BO_PtrMemD: 10939 case BO_PtrMemI: 10940 return IntRange::forValueOfType(C, GetExprType(E)); 10941 10942 // Bitwise-and uses the *infinum* of the two source ranges. 10943 case BO_And: 10944 case BO_AndAssign: 10945 Combine = IntRange::bit_and; 10946 break; 10947 10948 // Left shift gets black-listed based on a judgement call. 10949 case BO_Shl: 10950 // ...except that we want to treat '1 << (blah)' as logically 10951 // positive. It's an important idiom. 10952 if (IntegerLiteral *I 10953 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10954 if (I->getValue() == 1) { 10955 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10956 return IntRange(R.Width, /*NonNegative*/ true); 10957 } 10958 } 10959 LLVM_FALLTHROUGH; 10960 10961 case BO_ShlAssign: 10962 return IntRange::forValueOfType(C, GetExprType(E)); 10963 10964 // Right shift by a constant can narrow its left argument. 10965 case BO_Shr: 10966 case BO_ShrAssign: { 10967 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 10968 Approximate); 10969 10970 // If the shift amount is a positive constant, drop the width by 10971 // that much. 10972 if (Optional<llvm::APSInt> shift = 10973 BO->getRHS()->getIntegerConstantExpr(C)) { 10974 if (shift->isNonNegative()) { 10975 unsigned zext = shift->getZExtValue(); 10976 if (zext >= L.Width) 10977 L.Width = (L.NonNegative ? 0 : 1); 10978 else 10979 L.Width -= zext; 10980 } 10981 } 10982 10983 return L; 10984 } 10985 10986 // Comma acts as its right operand. 10987 case BO_Comma: 10988 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10989 Approximate); 10990 10991 case BO_Add: 10992 if (!Approximate) 10993 Combine = IntRange::sum; 10994 break; 10995 10996 case BO_Sub: 10997 if (BO->getLHS()->getType()->isPointerType()) 10998 return IntRange::forValueOfType(C, GetExprType(E)); 10999 if (!Approximate) 11000 Combine = IntRange::difference; 11001 break; 11002 11003 case BO_Mul: 11004 if (!Approximate) 11005 Combine = IntRange::product; 11006 break; 11007 11008 // The width of a division result is mostly determined by the size 11009 // of the LHS. 11010 case BO_Div: { 11011 // Don't 'pre-truncate' the operands. 11012 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11013 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11014 Approximate); 11015 11016 // If the divisor is constant, use that. 11017 if (Optional<llvm::APSInt> divisor = 11018 BO->getRHS()->getIntegerConstantExpr(C)) { 11019 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11020 if (log2 >= L.Width) 11021 L.Width = (L.NonNegative ? 0 : 1); 11022 else 11023 L.Width = std::min(L.Width - log2, MaxWidth); 11024 return L; 11025 } 11026 11027 // Otherwise, just use the LHS's width. 11028 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11029 // could be -1. 11030 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11031 Approximate); 11032 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11033 } 11034 11035 case BO_Rem: 11036 Combine = IntRange::rem; 11037 break; 11038 11039 // The default behavior is okay for these. 11040 case BO_Xor: 11041 case BO_Or: 11042 break; 11043 } 11044 11045 // Combine the two ranges, but limit the result to the type in which we 11046 // performed the computation. 11047 QualType T = GetExprType(E); 11048 unsigned opWidth = C.getIntWidth(T); 11049 IntRange L = 11050 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11051 IntRange R = 11052 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11053 IntRange C = Combine(L, R); 11054 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11055 C.Width = std::min(C.Width, MaxWidth); 11056 return C; 11057 } 11058 11059 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11060 switch (UO->getOpcode()) { 11061 // Boolean-valued operations are white-listed. 11062 case UO_LNot: 11063 return IntRange::forBoolType(); 11064 11065 // Operations with opaque sources are black-listed. 11066 case UO_Deref: 11067 case UO_AddrOf: // should be impossible 11068 return IntRange::forValueOfType(C, GetExprType(E)); 11069 11070 default: 11071 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11072 Approximate); 11073 } 11074 } 11075 11076 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11077 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11078 Approximate); 11079 11080 if (const auto *BitField = E->getSourceBitField()) 11081 return IntRange(BitField->getBitWidthValue(C), 11082 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11083 11084 return IntRange::forValueOfType(C, GetExprType(E)); 11085 } 11086 11087 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11088 bool InConstantContext, bool Approximate) { 11089 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11090 Approximate); 11091 } 11092 11093 /// Checks whether the given value, which currently has the given 11094 /// source semantics, has the same value when coerced through the 11095 /// target semantics. 11096 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11097 const llvm::fltSemantics &Src, 11098 const llvm::fltSemantics &Tgt) { 11099 llvm::APFloat truncated = value; 11100 11101 bool ignored; 11102 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11103 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11104 11105 return truncated.bitwiseIsEqual(value); 11106 } 11107 11108 /// Checks whether the given value, which currently has the given 11109 /// source semantics, has the same value when coerced through the 11110 /// target semantics. 11111 /// 11112 /// The value might be a vector of floats (or a complex number). 11113 static bool IsSameFloatAfterCast(const APValue &value, 11114 const llvm::fltSemantics &Src, 11115 const llvm::fltSemantics &Tgt) { 11116 if (value.isFloat()) 11117 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11118 11119 if (value.isVector()) { 11120 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11121 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11122 return false; 11123 return true; 11124 } 11125 11126 assert(value.isComplexFloat()); 11127 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11128 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11129 } 11130 11131 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11132 bool IsListInit = false); 11133 11134 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11135 // Suppress cases where we are comparing against an enum constant. 11136 if (const DeclRefExpr *DR = 11137 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11138 if (isa<EnumConstantDecl>(DR->getDecl())) 11139 return true; 11140 11141 // Suppress cases where the value is expanded from a macro, unless that macro 11142 // is how a language represents a boolean literal. This is the case in both C 11143 // and Objective-C. 11144 SourceLocation BeginLoc = E->getBeginLoc(); 11145 if (BeginLoc.isMacroID()) { 11146 StringRef MacroName = Lexer::getImmediateMacroName( 11147 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11148 return MacroName != "YES" && MacroName != "NO" && 11149 MacroName != "true" && MacroName != "false"; 11150 } 11151 11152 return false; 11153 } 11154 11155 static bool isKnownToHaveUnsignedValue(Expr *E) { 11156 return E->getType()->isIntegerType() && 11157 (!E->getType()->isSignedIntegerType() || 11158 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11159 } 11160 11161 namespace { 11162 /// The promoted range of values of a type. In general this has the 11163 /// following structure: 11164 /// 11165 /// |-----------| . . . |-----------| 11166 /// ^ ^ ^ ^ 11167 /// Min HoleMin HoleMax Max 11168 /// 11169 /// ... where there is only a hole if a signed type is promoted to unsigned 11170 /// (in which case Min and Max are the smallest and largest representable 11171 /// values). 11172 struct PromotedRange { 11173 // Min, or HoleMax if there is a hole. 11174 llvm::APSInt PromotedMin; 11175 // Max, or HoleMin if there is a hole. 11176 llvm::APSInt PromotedMax; 11177 11178 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11179 if (R.Width == 0) 11180 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11181 else if (R.Width >= BitWidth && !Unsigned) { 11182 // Promotion made the type *narrower*. This happens when promoting 11183 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11184 // Treat all values of 'signed int' as being in range for now. 11185 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11186 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11187 } else { 11188 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11189 .extOrTrunc(BitWidth); 11190 PromotedMin.setIsUnsigned(Unsigned); 11191 11192 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11193 .extOrTrunc(BitWidth); 11194 PromotedMax.setIsUnsigned(Unsigned); 11195 } 11196 } 11197 11198 // Determine whether this range is contiguous (has no hole). 11199 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11200 11201 // Where a constant value is within the range. 11202 enum ComparisonResult { 11203 LT = 0x1, 11204 LE = 0x2, 11205 GT = 0x4, 11206 GE = 0x8, 11207 EQ = 0x10, 11208 NE = 0x20, 11209 InRangeFlag = 0x40, 11210 11211 Less = LE | LT | NE, 11212 Min = LE | InRangeFlag, 11213 InRange = InRangeFlag, 11214 Max = GE | InRangeFlag, 11215 Greater = GE | GT | NE, 11216 11217 OnlyValue = LE | GE | EQ | InRangeFlag, 11218 InHole = NE 11219 }; 11220 11221 ComparisonResult compare(const llvm::APSInt &Value) const { 11222 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11223 Value.isUnsigned() == PromotedMin.isUnsigned()); 11224 if (!isContiguous()) { 11225 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11226 if (Value.isMinValue()) return Min; 11227 if (Value.isMaxValue()) return Max; 11228 if (Value >= PromotedMin) return InRange; 11229 if (Value <= PromotedMax) return InRange; 11230 return InHole; 11231 } 11232 11233 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11234 case -1: return Less; 11235 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11236 case 1: 11237 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11238 case -1: return InRange; 11239 case 0: return Max; 11240 case 1: return Greater; 11241 } 11242 } 11243 11244 llvm_unreachable("impossible compare result"); 11245 } 11246 11247 static llvm::Optional<StringRef> 11248 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11249 if (Op == BO_Cmp) { 11250 ComparisonResult LTFlag = LT, GTFlag = GT; 11251 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11252 11253 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11254 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11255 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11256 return llvm::None; 11257 } 11258 11259 ComparisonResult TrueFlag, FalseFlag; 11260 if (Op == BO_EQ) { 11261 TrueFlag = EQ; 11262 FalseFlag = NE; 11263 } else if (Op == BO_NE) { 11264 TrueFlag = NE; 11265 FalseFlag = EQ; 11266 } else { 11267 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11268 TrueFlag = LT; 11269 FalseFlag = GE; 11270 } else { 11271 TrueFlag = GT; 11272 FalseFlag = LE; 11273 } 11274 if (Op == BO_GE || Op == BO_LE) 11275 std::swap(TrueFlag, FalseFlag); 11276 } 11277 if (R & TrueFlag) 11278 return StringRef("true"); 11279 if (R & FalseFlag) 11280 return StringRef("false"); 11281 return llvm::None; 11282 } 11283 }; 11284 } 11285 11286 static bool HasEnumType(Expr *E) { 11287 // Strip off implicit integral promotions. 11288 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11289 if (ICE->getCastKind() != CK_IntegralCast && 11290 ICE->getCastKind() != CK_NoOp) 11291 break; 11292 E = ICE->getSubExpr(); 11293 } 11294 11295 return E->getType()->isEnumeralType(); 11296 } 11297 11298 static int classifyConstantValue(Expr *Constant) { 11299 // The values of this enumeration are used in the diagnostics 11300 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11301 enum ConstantValueKind { 11302 Miscellaneous = 0, 11303 LiteralTrue, 11304 LiteralFalse 11305 }; 11306 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11307 return BL->getValue() ? ConstantValueKind::LiteralTrue 11308 : ConstantValueKind::LiteralFalse; 11309 return ConstantValueKind::Miscellaneous; 11310 } 11311 11312 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11313 Expr *Constant, Expr *Other, 11314 const llvm::APSInt &Value, 11315 bool RhsConstant) { 11316 if (S.inTemplateInstantiation()) 11317 return false; 11318 11319 Expr *OriginalOther = Other; 11320 11321 Constant = Constant->IgnoreParenImpCasts(); 11322 Other = Other->IgnoreParenImpCasts(); 11323 11324 // Suppress warnings on tautological comparisons between values of the same 11325 // enumeration type. There are only two ways we could warn on this: 11326 // - If the constant is outside the range of representable values of 11327 // the enumeration. In such a case, we should warn about the cast 11328 // to enumeration type, not about the comparison. 11329 // - If the constant is the maximum / minimum in-range value. For an 11330 // enumeratin type, such comparisons can be meaningful and useful. 11331 if (Constant->getType()->isEnumeralType() && 11332 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11333 return false; 11334 11335 IntRange OtherValueRange = GetExprRange( 11336 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11337 11338 QualType OtherT = Other->getType(); 11339 if (const auto *AT = OtherT->getAs<AtomicType>()) 11340 OtherT = AT->getValueType(); 11341 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11342 11343 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11344 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11345 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11346 S.NSAPIObj->isObjCBOOLType(OtherT) && 11347 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11348 11349 // Whether we're treating Other as being a bool because of the form of 11350 // expression despite it having another type (typically 'int' in C). 11351 bool OtherIsBooleanDespiteType = 11352 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11353 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11354 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11355 11356 // Check if all values in the range of possible values of this expression 11357 // lead to the same comparison outcome. 11358 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11359 Value.isUnsigned()); 11360 auto Cmp = OtherPromotedValueRange.compare(Value); 11361 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11362 if (!Result) 11363 return false; 11364 11365 // Also consider the range determined by the type alone. This allows us to 11366 // classify the warning under the proper diagnostic group. 11367 bool TautologicalTypeCompare = false; 11368 { 11369 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11370 Value.isUnsigned()); 11371 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11372 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11373 RhsConstant)) { 11374 TautologicalTypeCompare = true; 11375 Cmp = TypeCmp; 11376 Result = TypeResult; 11377 } 11378 } 11379 11380 // Don't warn if the non-constant operand actually always evaluates to the 11381 // same value. 11382 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11383 return false; 11384 11385 // Suppress the diagnostic for an in-range comparison if the constant comes 11386 // from a macro or enumerator. We don't want to diagnose 11387 // 11388 // some_long_value <= INT_MAX 11389 // 11390 // when sizeof(int) == sizeof(long). 11391 bool InRange = Cmp & PromotedRange::InRangeFlag; 11392 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11393 return false; 11394 11395 // A comparison of an unsigned bit-field against 0 is really a type problem, 11396 // even though at the type level the bit-field might promote to 'signed int'. 11397 if (Other->refersToBitField() && InRange && Value == 0 && 11398 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11399 TautologicalTypeCompare = true; 11400 11401 // If this is a comparison to an enum constant, include that 11402 // constant in the diagnostic. 11403 const EnumConstantDecl *ED = nullptr; 11404 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11405 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11406 11407 // Should be enough for uint128 (39 decimal digits) 11408 SmallString<64> PrettySourceValue; 11409 llvm::raw_svector_ostream OS(PrettySourceValue); 11410 if (ED) { 11411 OS << '\'' << *ED << "' (" << Value << ")"; 11412 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11413 Constant->IgnoreParenImpCasts())) { 11414 OS << (BL->getValue() ? "YES" : "NO"); 11415 } else { 11416 OS << Value; 11417 } 11418 11419 if (!TautologicalTypeCompare) { 11420 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11421 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11422 << E->getOpcodeStr() << OS.str() << *Result 11423 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11424 return true; 11425 } 11426 11427 if (IsObjCSignedCharBool) { 11428 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11429 S.PDiag(diag::warn_tautological_compare_objc_bool) 11430 << OS.str() << *Result); 11431 return true; 11432 } 11433 11434 // FIXME: We use a somewhat different formatting for the in-range cases and 11435 // cases involving boolean values for historical reasons. We should pick a 11436 // consistent way of presenting these diagnostics. 11437 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11438 11439 S.DiagRuntimeBehavior( 11440 E->getOperatorLoc(), E, 11441 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11442 : diag::warn_tautological_bool_compare) 11443 << OS.str() << classifyConstantValue(Constant) << OtherT 11444 << OtherIsBooleanDespiteType << *Result 11445 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11446 } else { 11447 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11448 unsigned Diag = 11449 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11450 ? (HasEnumType(OriginalOther) 11451 ? diag::warn_unsigned_enum_always_true_comparison 11452 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11453 : diag::warn_unsigned_always_true_comparison) 11454 : diag::warn_tautological_constant_compare; 11455 11456 S.Diag(E->getOperatorLoc(), Diag) 11457 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11458 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11459 } 11460 11461 return true; 11462 } 11463 11464 /// Analyze the operands of the given comparison. Implements the 11465 /// fallback case from AnalyzeComparison. 11466 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11467 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11468 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11469 } 11470 11471 /// Implements -Wsign-compare. 11472 /// 11473 /// \param E the binary operator to check for warnings 11474 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11475 // The type the comparison is being performed in. 11476 QualType T = E->getLHS()->getType(); 11477 11478 // Only analyze comparison operators where both sides have been converted to 11479 // the same type. 11480 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11481 return AnalyzeImpConvsInComparison(S, E); 11482 11483 // Don't analyze value-dependent comparisons directly. 11484 if (E->isValueDependent()) 11485 return AnalyzeImpConvsInComparison(S, E); 11486 11487 Expr *LHS = E->getLHS(); 11488 Expr *RHS = E->getRHS(); 11489 11490 if (T->isIntegralType(S.Context)) { 11491 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11492 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11493 11494 // We don't care about expressions whose result is a constant. 11495 if (RHSValue && LHSValue) 11496 return AnalyzeImpConvsInComparison(S, E); 11497 11498 // We only care about expressions where just one side is literal 11499 if ((bool)RHSValue ^ (bool)LHSValue) { 11500 // Is the constant on the RHS or LHS? 11501 const bool RhsConstant = (bool)RHSValue; 11502 Expr *Const = RhsConstant ? RHS : LHS; 11503 Expr *Other = RhsConstant ? LHS : RHS; 11504 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11505 11506 // Check whether an integer constant comparison results in a value 11507 // of 'true' or 'false'. 11508 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11509 return AnalyzeImpConvsInComparison(S, E); 11510 } 11511 } 11512 11513 if (!T->hasUnsignedIntegerRepresentation()) { 11514 // We don't do anything special if this isn't an unsigned integral 11515 // comparison: we're only interested in integral comparisons, and 11516 // signed comparisons only happen in cases we don't care to warn about. 11517 return AnalyzeImpConvsInComparison(S, E); 11518 } 11519 11520 LHS = LHS->IgnoreParenImpCasts(); 11521 RHS = RHS->IgnoreParenImpCasts(); 11522 11523 if (!S.getLangOpts().CPlusPlus) { 11524 // Avoid warning about comparison of integers with different signs when 11525 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11526 // the type of `E`. 11527 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11528 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11529 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11530 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11531 } 11532 11533 // Check to see if one of the (unmodified) operands is of different 11534 // signedness. 11535 Expr *signedOperand, *unsignedOperand; 11536 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11537 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11538 "unsigned comparison between two signed integer expressions?"); 11539 signedOperand = LHS; 11540 unsignedOperand = RHS; 11541 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11542 signedOperand = RHS; 11543 unsignedOperand = LHS; 11544 } else { 11545 return AnalyzeImpConvsInComparison(S, E); 11546 } 11547 11548 // Otherwise, calculate the effective range of the signed operand. 11549 IntRange signedRange = GetExprRange( 11550 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11551 11552 // Go ahead and analyze implicit conversions in the operands. Note 11553 // that we skip the implicit conversions on both sides. 11554 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11555 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11556 11557 // If the signed range is non-negative, -Wsign-compare won't fire. 11558 if (signedRange.NonNegative) 11559 return; 11560 11561 // For (in)equality comparisons, if the unsigned operand is a 11562 // constant which cannot collide with a overflowed signed operand, 11563 // then reinterpreting the signed operand as unsigned will not 11564 // change the result of the comparison. 11565 if (E->isEqualityOp()) { 11566 unsigned comparisonWidth = S.Context.getIntWidth(T); 11567 IntRange unsignedRange = 11568 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11569 /*Approximate*/ true); 11570 11571 // We should never be unable to prove that the unsigned operand is 11572 // non-negative. 11573 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11574 11575 if (unsignedRange.Width < comparisonWidth) 11576 return; 11577 } 11578 11579 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11580 S.PDiag(diag::warn_mixed_sign_comparison) 11581 << LHS->getType() << RHS->getType() 11582 << LHS->getSourceRange() << RHS->getSourceRange()); 11583 } 11584 11585 /// Analyzes an attempt to assign the given value to a bitfield. 11586 /// 11587 /// Returns true if there was something fishy about the attempt. 11588 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11589 SourceLocation InitLoc) { 11590 assert(Bitfield->isBitField()); 11591 if (Bitfield->isInvalidDecl()) 11592 return false; 11593 11594 // White-list bool bitfields. 11595 QualType BitfieldType = Bitfield->getType(); 11596 if (BitfieldType->isBooleanType()) 11597 return false; 11598 11599 if (BitfieldType->isEnumeralType()) { 11600 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11601 // If the underlying enum type was not explicitly specified as an unsigned 11602 // type and the enum contain only positive values, MSVC++ will cause an 11603 // inconsistency by storing this as a signed type. 11604 if (S.getLangOpts().CPlusPlus11 && 11605 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11606 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11607 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11608 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11609 << BitfieldEnumDecl; 11610 } 11611 } 11612 11613 if (Bitfield->getType()->isBooleanType()) 11614 return false; 11615 11616 // Ignore value- or type-dependent expressions. 11617 if (Bitfield->getBitWidth()->isValueDependent() || 11618 Bitfield->getBitWidth()->isTypeDependent() || 11619 Init->isValueDependent() || 11620 Init->isTypeDependent()) 11621 return false; 11622 11623 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11624 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11625 11626 Expr::EvalResult Result; 11627 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11628 Expr::SE_AllowSideEffects)) { 11629 // The RHS is not constant. If the RHS has an enum type, make sure the 11630 // bitfield is wide enough to hold all the values of the enum without 11631 // truncation. 11632 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11633 EnumDecl *ED = EnumTy->getDecl(); 11634 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11635 11636 // Enum types are implicitly signed on Windows, so check if there are any 11637 // negative enumerators to see if the enum was intended to be signed or 11638 // not. 11639 bool SignedEnum = ED->getNumNegativeBits() > 0; 11640 11641 // Check for surprising sign changes when assigning enum values to a 11642 // bitfield of different signedness. If the bitfield is signed and we 11643 // have exactly the right number of bits to store this unsigned enum, 11644 // suggest changing the enum to an unsigned type. This typically happens 11645 // on Windows where unfixed enums always use an underlying type of 'int'. 11646 unsigned DiagID = 0; 11647 if (SignedEnum && !SignedBitfield) { 11648 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11649 } else if (SignedBitfield && !SignedEnum && 11650 ED->getNumPositiveBits() == FieldWidth) { 11651 DiagID = diag::warn_signed_bitfield_enum_conversion; 11652 } 11653 11654 if (DiagID) { 11655 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11656 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11657 SourceRange TypeRange = 11658 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11659 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11660 << SignedEnum << TypeRange; 11661 } 11662 11663 // Compute the required bitwidth. If the enum has negative values, we need 11664 // one more bit than the normal number of positive bits to represent the 11665 // sign bit. 11666 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11667 ED->getNumNegativeBits()) 11668 : ED->getNumPositiveBits(); 11669 11670 // Check the bitwidth. 11671 if (BitsNeeded > FieldWidth) { 11672 Expr *WidthExpr = Bitfield->getBitWidth(); 11673 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11674 << Bitfield << ED; 11675 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11676 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11677 } 11678 } 11679 11680 return false; 11681 } 11682 11683 llvm::APSInt Value = Result.Val.getInt(); 11684 11685 unsigned OriginalWidth = Value.getBitWidth(); 11686 11687 if (!Value.isSigned() || Value.isNegative()) 11688 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11689 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11690 OriginalWidth = Value.getMinSignedBits(); 11691 11692 if (OriginalWidth <= FieldWidth) 11693 return false; 11694 11695 // Compute the value which the bitfield will contain. 11696 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11697 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11698 11699 // Check whether the stored value is equal to the original value. 11700 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11701 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11702 return false; 11703 11704 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11705 // therefore don't strictly fit into a signed bitfield of width 1. 11706 if (FieldWidth == 1 && Value == 1) 11707 return false; 11708 11709 std::string PrettyValue = Value.toString(10); 11710 std::string PrettyTrunc = TruncatedValue.toString(10); 11711 11712 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11713 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11714 << Init->getSourceRange(); 11715 11716 return true; 11717 } 11718 11719 /// Analyze the given simple or compound assignment for warning-worthy 11720 /// operations. 11721 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11722 // Just recurse on the LHS. 11723 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11724 11725 // We want to recurse on the RHS as normal unless we're assigning to 11726 // a bitfield. 11727 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11728 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11729 E->getOperatorLoc())) { 11730 // Recurse, ignoring any implicit conversions on the RHS. 11731 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11732 E->getOperatorLoc()); 11733 } 11734 } 11735 11736 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11737 11738 // Diagnose implicitly sequentially-consistent atomic assignment. 11739 if (E->getLHS()->getType()->isAtomicType()) 11740 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11741 } 11742 11743 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11744 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11745 SourceLocation CContext, unsigned diag, 11746 bool pruneControlFlow = false) { 11747 if (pruneControlFlow) { 11748 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11749 S.PDiag(diag) 11750 << SourceType << T << E->getSourceRange() 11751 << SourceRange(CContext)); 11752 return; 11753 } 11754 S.Diag(E->getExprLoc(), diag) 11755 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11756 } 11757 11758 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11759 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11760 SourceLocation CContext, 11761 unsigned diag, bool pruneControlFlow = false) { 11762 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11763 } 11764 11765 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11766 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11767 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11768 } 11769 11770 static void adornObjCBoolConversionDiagWithTernaryFixit( 11771 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11772 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11773 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11774 Ignored = OVE->getSourceExpr(); 11775 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11776 isa<BinaryOperator>(Ignored) || 11777 isa<CXXOperatorCallExpr>(Ignored); 11778 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11779 if (NeedsParens) 11780 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11781 << FixItHint::CreateInsertion(EndLoc, ")"); 11782 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11783 } 11784 11785 /// Diagnose an implicit cast from a floating point value to an integer value. 11786 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11787 SourceLocation CContext) { 11788 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11789 const bool PruneWarnings = S.inTemplateInstantiation(); 11790 11791 Expr *InnerE = E->IgnoreParenImpCasts(); 11792 // We also want to warn on, e.g., "int i = -1.234" 11793 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11794 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11795 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11796 11797 const bool IsLiteral = 11798 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11799 11800 llvm::APFloat Value(0.0); 11801 bool IsConstant = 11802 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11803 if (!IsConstant) { 11804 if (isObjCSignedCharBool(S, T)) { 11805 return adornObjCBoolConversionDiagWithTernaryFixit( 11806 S, E, 11807 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11808 << E->getType()); 11809 } 11810 11811 return DiagnoseImpCast(S, E, T, CContext, 11812 diag::warn_impcast_float_integer, PruneWarnings); 11813 } 11814 11815 bool isExact = false; 11816 11817 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11818 T->hasUnsignedIntegerRepresentation()); 11819 llvm::APFloat::opStatus Result = Value.convertToInteger( 11820 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11821 11822 // FIXME: Force the precision of the source value down so we don't print 11823 // digits which are usually useless (we don't really care here if we 11824 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11825 // would automatically print the shortest representation, but it's a bit 11826 // tricky to implement. 11827 SmallString<16> PrettySourceValue; 11828 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11829 precision = (precision * 59 + 195) / 196; 11830 Value.toString(PrettySourceValue, precision); 11831 11832 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11833 return adornObjCBoolConversionDiagWithTernaryFixit( 11834 S, E, 11835 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11836 << PrettySourceValue); 11837 } 11838 11839 if (Result == llvm::APFloat::opOK && isExact) { 11840 if (IsLiteral) return; 11841 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11842 PruneWarnings); 11843 } 11844 11845 // Conversion of a floating-point value to a non-bool integer where the 11846 // integral part cannot be represented by the integer type is undefined. 11847 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11848 return DiagnoseImpCast( 11849 S, E, T, CContext, 11850 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11851 : diag::warn_impcast_float_to_integer_out_of_range, 11852 PruneWarnings); 11853 11854 unsigned DiagID = 0; 11855 if (IsLiteral) { 11856 // Warn on floating point literal to integer. 11857 DiagID = diag::warn_impcast_literal_float_to_integer; 11858 } else if (IntegerValue == 0) { 11859 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11860 return DiagnoseImpCast(S, E, T, CContext, 11861 diag::warn_impcast_float_integer, PruneWarnings); 11862 } 11863 // Warn on non-zero to zero conversion. 11864 DiagID = diag::warn_impcast_float_to_integer_zero; 11865 } else { 11866 if (IntegerValue.isUnsigned()) { 11867 if (!IntegerValue.isMaxValue()) { 11868 return DiagnoseImpCast(S, E, T, CContext, 11869 diag::warn_impcast_float_integer, PruneWarnings); 11870 } 11871 } else { // IntegerValue.isSigned() 11872 if (!IntegerValue.isMaxSignedValue() && 11873 !IntegerValue.isMinSignedValue()) { 11874 return DiagnoseImpCast(S, E, T, CContext, 11875 diag::warn_impcast_float_integer, PruneWarnings); 11876 } 11877 } 11878 // Warn on evaluatable floating point expression to integer conversion. 11879 DiagID = diag::warn_impcast_float_to_integer; 11880 } 11881 11882 SmallString<16> PrettyTargetValue; 11883 if (IsBool) 11884 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11885 else 11886 IntegerValue.toString(PrettyTargetValue); 11887 11888 if (PruneWarnings) { 11889 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11890 S.PDiag(DiagID) 11891 << E->getType() << T.getUnqualifiedType() 11892 << PrettySourceValue << PrettyTargetValue 11893 << E->getSourceRange() << SourceRange(CContext)); 11894 } else { 11895 S.Diag(E->getExprLoc(), DiagID) 11896 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11897 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11898 } 11899 } 11900 11901 /// Analyze the given compound assignment for the possible losing of 11902 /// floating-point precision. 11903 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11904 assert(isa<CompoundAssignOperator>(E) && 11905 "Must be compound assignment operation"); 11906 // Recurse on the LHS and RHS in here 11907 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11908 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11909 11910 if (E->getLHS()->getType()->isAtomicType()) 11911 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11912 11913 // Now check the outermost expression 11914 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11915 const auto *RBT = cast<CompoundAssignOperator>(E) 11916 ->getComputationResultType() 11917 ->getAs<BuiltinType>(); 11918 11919 // The below checks assume source is floating point. 11920 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11921 11922 // If source is floating point but target is an integer. 11923 if (ResultBT->isInteger()) 11924 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11925 E->getExprLoc(), diag::warn_impcast_float_integer); 11926 11927 if (!ResultBT->isFloatingPoint()) 11928 return; 11929 11930 // If both source and target are floating points, warn about losing precision. 11931 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11932 QualType(ResultBT, 0), QualType(RBT, 0)); 11933 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11934 // warn about dropping FP rank. 11935 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11936 diag::warn_impcast_float_result_precision); 11937 } 11938 11939 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11940 IntRange Range) { 11941 if (!Range.Width) return "0"; 11942 11943 llvm::APSInt ValueInRange = Value; 11944 ValueInRange.setIsSigned(!Range.NonNegative); 11945 ValueInRange = ValueInRange.trunc(Range.Width); 11946 return ValueInRange.toString(10); 11947 } 11948 11949 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11950 if (!isa<ImplicitCastExpr>(Ex)) 11951 return false; 11952 11953 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11954 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11955 const Type *Source = 11956 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11957 if (Target->isDependentType()) 11958 return false; 11959 11960 const BuiltinType *FloatCandidateBT = 11961 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11962 const Type *BoolCandidateType = ToBool ? Target : Source; 11963 11964 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11965 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11966 } 11967 11968 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11969 SourceLocation CC) { 11970 unsigned NumArgs = TheCall->getNumArgs(); 11971 for (unsigned i = 0; i < NumArgs; ++i) { 11972 Expr *CurrA = TheCall->getArg(i); 11973 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11974 continue; 11975 11976 bool IsSwapped = ((i > 0) && 11977 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11978 IsSwapped |= ((i < (NumArgs - 1)) && 11979 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11980 if (IsSwapped) { 11981 // Warn on this floating-point to bool conversion. 11982 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11983 CurrA->getType(), CC, 11984 diag::warn_impcast_floating_point_to_bool); 11985 } 11986 } 11987 } 11988 11989 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11990 SourceLocation CC) { 11991 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11992 E->getExprLoc())) 11993 return; 11994 11995 // Don't warn on functions which have return type nullptr_t. 11996 if (isa<CallExpr>(E)) 11997 return; 11998 11999 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12000 const Expr::NullPointerConstantKind NullKind = 12001 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12002 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12003 return; 12004 12005 // Return if target type is a safe conversion. 12006 if (T->isAnyPointerType() || T->isBlockPointerType() || 12007 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12008 return; 12009 12010 SourceLocation Loc = E->getSourceRange().getBegin(); 12011 12012 // Venture through the macro stacks to get to the source of macro arguments. 12013 // The new location is a better location than the complete location that was 12014 // passed in. 12015 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12016 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12017 12018 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12019 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12020 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12021 Loc, S.SourceMgr, S.getLangOpts()); 12022 if (MacroName == "NULL") 12023 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12024 } 12025 12026 // Only warn if the null and context location are in the same macro expansion. 12027 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12028 return; 12029 12030 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12031 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12032 << FixItHint::CreateReplacement(Loc, 12033 S.getFixItZeroLiteralForType(T, Loc)); 12034 } 12035 12036 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12037 ObjCArrayLiteral *ArrayLiteral); 12038 12039 static void 12040 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12041 ObjCDictionaryLiteral *DictionaryLiteral); 12042 12043 /// Check a single element within a collection literal against the 12044 /// target element type. 12045 static void checkObjCCollectionLiteralElement(Sema &S, 12046 QualType TargetElementType, 12047 Expr *Element, 12048 unsigned ElementKind) { 12049 // Skip a bitcast to 'id' or qualified 'id'. 12050 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12051 if (ICE->getCastKind() == CK_BitCast && 12052 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12053 Element = ICE->getSubExpr(); 12054 } 12055 12056 QualType ElementType = Element->getType(); 12057 ExprResult ElementResult(Element); 12058 if (ElementType->getAs<ObjCObjectPointerType>() && 12059 S.CheckSingleAssignmentConstraints(TargetElementType, 12060 ElementResult, 12061 false, false) 12062 != Sema::Compatible) { 12063 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12064 << ElementType << ElementKind << TargetElementType 12065 << Element->getSourceRange(); 12066 } 12067 12068 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12069 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12070 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12071 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12072 } 12073 12074 /// Check an Objective-C array literal being converted to the given 12075 /// target type. 12076 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12077 ObjCArrayLiteral *ArrayLiteral) { 12078 if (!S.NSArrayDecl) 12079 return; 12080 12081 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12082 if (!TargetObjCPtr) 12083 return; 12084 12085 if (TargetObjCPtr->isUnspecialized() || 12086 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12087 != S.NSArrayDecl->getCanonicalDecl()) 12088 return; 12089 12090 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12091 if (TypeArgs.size() != 1) 12092 return; 12093 12094 QualType TargetElementType = TypeArgs[0]; 12095 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12096 checkObjCCollectionLiteralElement(S, TargetElementType, 12097 ArrayLiteral->getElement(I), 12098 0); 12099 } 12100 } 12101 12102 /// Check an Objective-C dictionary literal being converted to the given 12103 /// target type. 12104 static void 12105 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12106 ObjCDictionaryLiteral *DictionaryLiteral) { 12107 if (!S.NSDictionaryDecl) 12108 return; 12109 12110 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12111 if (!TargetObjCPtr) 12112 return; 12113 12114 if (TargetObjCPtr->isUnspecialized() || 12115 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12116 != S.NSDictionaryDecl->getCanonicalDecl()) 12117 return; 12118 12119 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12120 if (TypeArgs.size() != 2) 12121 return; 12122 12123 QualType TargetKeyType = TypeArgs[0]; 12124 QualType TargetObjectType = TypeArgs[1]; 12125 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12126 auto Element = DictionaryLiteral->getKeyValueElement(I); 12127 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12128 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12129 } 12130 } 12131 12132 // Helper function to filter out cases for constant width constant conversion. 12133 // Don't warn on char array initialization or for non-decimal values. 12134 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12135 SourceLocation CC) { 12136 // If initializing from a constant, and the constant starts with '0', 12137 // then it is a binary, octal, or hexadecimal. Allow these constants 12138 // to fill all the bits, even if there is a sign change. 12139 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12140 const char FirstLiteralCharacter = 12141 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12142 if (FirstLiteralCharacter == '0') 12143 return false; 12144 } 12145 12146 // If the CC location points to a '{', and the type is char, then assume 12147 // assume it is an array initialization. 12148 if (CC.isValid() && T->isCharType()) { 12149 const char FirstContextCharacter = 12150 S.getSourceManager().getCharacterData(CC)[0]; 12151 if (FirstContextCharacter == '{') 12152 return false; 12153 } 12154 12155 return true; 12156 } 12157 12158 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12159 const auto *IL = dyn_cast<IntegerLiteral>(E); 12160 if (!IL) { 12161 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12162 if (UO->getOpcode() == UO_Minus) 12163 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12164 } 12165 } 12166 12167 return IL; 12168 } 12169 12170 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12171 E = E->IgnoreParenImpCasts(); 12172 SourceLocation ExprLoc = E->getExprLoc(); 12173 12174 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12175 BinaryOperator::Opcode Opc = BO->getOpcode(); 12176 Expr::EvalResult Result; 12177 // Do not diagnose unsigned shifts. 12178 if (Opc == BO_Shl) { 12179 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12180 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12181 if (LHS && LHS->getValue() == 0) 12182 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12183 else if (!E->isValueDependent() && LHS && RHS && 12184 RHS->getValue().isNonNegative() && 12185 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12186 S.Diag(ExprLoc, diag::warn_left_shift_always) 12187 << (Result.Val.getInt() != 0); 12188 else if (E->getType()->isSignedIntegerType()) 12189 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12190 } 12191 } 12192 12193 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12194 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12195 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12196 if (!LHS || !RHS) 12197 return; 12198 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12199 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12200 // Do not diagnose common idioms. 12201 return; 12202 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12203 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12204 } 12205 } 12206 12207 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12208 SourceLocation CC, 12209 bool *ICContext = nullptr, 12210 bool IsListInit = false) { 12211 if (E->isTypeDependent() || E->isValueDependent()) return; 12212 12213 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12214 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12215 if (Source == Target) return; 12216 if (Target->isDependentType()) return; 12217 12218 // If the conversion context location is invalid don't complain. We also 12219 // don't want to emit a warning if the issue occurs from the expansion of 12220 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12221 // delay this check as long as possible. Once we detect we are in that 12222 // scenario, we just return. 12223 if (CC.isInvalid()) 12224 return; 12225 12226 if (Source->isAtomicType()) 12227 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12228 12229 // Diagnose implicit casts to bool. 12230 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12231 if (isa<StringLiteral>(E)) 12232 // Warn on string literal to bool. Checks for string literals in logical 12233 // and expressions, for instance, assert(0 && "error here"), are 12234 // prevented by a check in AnalyzeImplicitConversions(). 12235 return DiagnoseImpCast(S, E, T, CC, 12236 diag::warn_impcast_string_literal_to_bool); 12237 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12238 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12239 // This covers the literal expressions that evaluate to Objective-C 12240 // objects. 12241 return DiagnoseImpCast(S, E, T, CC, 12242 diag::warn_impcast_objective_c_literal_to_bool); 12243 } 12244 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12245 // Warn on pointer to bool conversion that is always true. 12246 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12247 SourceRange(CC)); 12248 } 12249 } 12250 12251 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12252 // is a typedef for signed char (macOS), then that constant value has to be 1 12253 // or 0. 12254 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12255 Expr::EvalResult Result; 12256 if (E->EvaluateAsInt(Result, S.getASTContext(), 12257 Expr::SE_AllowSideEffects)) { 12258 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12259 adornObjCBoolConversionDiagWithTernaryFixit( 12260 S, E, 12261 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12262 << Result.Val.getInt().toString(10)); 12263 } 12264 return; 12265 } 12266 } 12267 12268 // Check implicit casts from Objective-C collection literals to specialized 12269 // collection types, e.g., NSArray<NSString *> *. 12270 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12271 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12272 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12273 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12274 12275 // Strip vector types. 12276 if (const auto *SourceVT = dyn_cast<VectorType>(Source)) { 12277 if (Target->isVLSTBuiltinType()) { 12278 auto SourceVectorKind = SourceVT->getVectorKind(); 12279 if (SourceVectorKind == VectorType::SveFixedLengthDataVector || 12280 SourceVectorKind == VectorType::SveFixedLengthPredicateVector || 12281 (SourceVectorKind == VectorType::GenericVector && 12282 S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits)) 12283 return; 12284 } 12285 12286 if (!isa<VectorType>(Target)) { 12287 if (S.SourceMgr.isInSystemMacro(CC)) 12288 return; 12289 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12290 } 12291 12292 // If the vector cast is cast between two vectors of the same size, it is 12293 // a bitcast, not a conversion. 12294 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12295 return; 12296 12297 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12298 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12299 } 12300 if (auto VecTy = dyn_cast<VectorType>(Target)) 12301 Target = VecTy->getElementType().getTypePtr(); 12302 12303 // Strip complex types. 12304 if (isa<ComplexType>(Source)) { 12305 if (!isa<ComplexType>(Target)) { 12306 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12307 return; 12308 12309 return DiagnoseImpCast(S, E, T, CC, 12310 S.getLangOpts().CPlusPlus 12311 ? diag::err_impcast_complex_scalar 12312 : diag::warn_impcast_complex_scalar); 12313 } 12314 12315 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12316 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12317 } 12318 12319 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12320 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12321 12322 // If the source is floating point... 12323 if (SourceBT && SourceBT->isFloatingPoint()) { 12324 // ...and the target is floating point... 12325 if (TargetBT && TargetBT->isFloatingPoint()) { 12326 // ...then warn if we're dropping FP rank. 12327 12328 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12329 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12330 if (Order > 0) { 12331 // Don't warn about float constants that are precisely 12332 // representable in the target type. 12333 Expr::EvalResult result; 12334 if (E->EvaluateAsRValue(result, S.Context)) { 12335 // Value might be a float, a float vector, or a float complex. 12336 if (IsSameFloatAfterCast(result.Val, 12337 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12338 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12339 return; 12340 } 12341 12342 if (S.SourceMgr.isInSystemMacro(CC)) 12343 return; 12344 12345 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12346 } 12347 // ... or possibly if we're increasing rank, too 12348 else if (Order < 0) { 12349 if (S.SourceMgr.isInSystemMacro(CC)) 12350 return; 12351 12352 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12353 } 12354 return; 12355 } 12356 12357 // If the target is integral, always warn. 12358 if (TargetBT && TargetBT->isInteger()) { 12359 if (S.SourceMgr.isInSystemMacro(CC)) 12360 return; 12361 12362 DiagnoseFloatingImpCast(S, E, T, CC); 12363 } 12364 12365 // Detect the case where a call result is converted from floating-point to 12366 // to bool, and the final argument to the call is converted from bool, to 12367 // discover this typo: 12368 // 12369 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12370 // 12371 // FIXME: This is an incredibly special case; is there some more general 12372 // way to detect this class of misplaced-parentheses bug? 12373 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12374 // Check last argument of function call to see if it is an 12375 // implicit cast from a type matching the type the result 12376 // is being cast to. 12377 CallExpr *CEx = cast<CallExpr>(E); 12378 if (unsigned NumArgs = CEx->getNumArgs()) { 12379 Expr *LastA = CEx->getArg(NumArgs - 1); 12380 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12381 if (isa<ImplicitCastExpr>(LastA) && 12382 InnerE->getType()->isBooleanType()) { 12383 // Warn on this floating-point to bool conversion 12384 DiagnoseImpCast(S, E, T, CC, 12385 diag::warn_impcast_floating_point_to_bool); 12386 } 12387 } 12388 } 12389 return; 12390 } 12391 12392 // Valid casts involving fixed point types should be accounted for here. 12393 if (Source->isFixedPointType()) { 12394 if (Target->isUnsaturatedFixedPointType()) { 12395 Expr::EvalResult Result; 12396 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12397 S.isConstantEvaluated())) { 12398 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12399 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12400 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12401 if (Value > MaxVal || Value < MinVal) { 12402 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12403 S.PDiag(diag::warn_impcast_fixed_point_range) 12404 << Value.toString() << T 12405 << E->getSourceRange() 12406 << clang::SourceRange(CC)); 12407 return; 12408 } 12409 } 12410 } else if (Target->isIntegerType()) { 12411 Expr::EvalResult Result; 12412 if (!S.isConstantEvaluated() && 12413 E->EvaluateAsFixedPoint(Result, S.Context, 12414 Expr::SE_AllowSideEffects)) { 12415 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12416 12417 bool Overflowed; 12418 llvm::APSInt IntResult = FXResult.convertToInt( 12419 S.Context.getIntWidth(T), 12420 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12421 12422 if (Overflowed) { 12423 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12424 S.PDiag(diag::warn_impcast_fixed_point_range) 12425 << FXResult.toString() << T 12426 << E->getSourceRange() 12427 << clang::SourceRange(CC)); 12428 return; 12429 } 12430 } 12431 } 12432 } else if (Target->isUnsaturatedFixedPointType()) { 12433 if (Source->isIntegerType()) { 12434 Expr::EvalResult Result; 12435 if (!S.isConstantEvaluated() && 12436 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12437 llvm::APSInt Value = Result.Val.getInt(); 12438 12439 bool Overflowed; 12440 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12441 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12442 12443 if (Overflowed) { 12444 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12445 S.PDiag(diag::warn_impcast_fixed_point_range) 12446 << Value.toString(/*Radix=*/10) << T 12447 << E->getSourceRange() 12448 << clang::SourceRange(CC)); 12449 return; 12450 } 12451 } 12452 } 12453 } 12454 12455 // If we are casting an integer type to a floating point type without 12456 // initialization-list syntax, we might lose accuracy if the floating 12457 // point type has a narrower significand than the integer type. 12458 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12459 TargetBT->isFloatingType() && !IsListInit) { 12460 // Determine the number of precision bits in the source integer type. 12461 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12462 /*Approximate*/ true); 12463 unsigned int SourcePrecision = SourceRange.Width; 12464 12465 // Determine the number of precision bits in the 12466 // target floating point type. 12467 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12468 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12469 12470 if (SourcePrecision > 0 && TargetPrecision > 0 && 12471 SourcePrecision > TargetPrecision) { 12472 12473 if (Optional<llvm::APSInt> SourceInt = 12474 E->getIntegerConstantExpr(S.Context)) { 12475 // If the source integer is a constant, convert it to the target 12476 // floating point type. Issue a warning if the value changes 12477 // during the whole conversion. 12478 llvm::APFloat TargetFloatValue( 12479 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12480 llvm::APFloat::opStatus ConversionStatus = 12481 TargetFloatValue.convertFromAPInt( 12482 *SourceInt, SourceBT->isSignedInteger(), 12483 llvm::APFloat::rmNearestTiesToEven); 12484 12485 if (ConversionStatus != llvm::APFloat::opOK) { 12486 std::string PrettySourceValue = SourceInt->toString(10); 12487 SmallString<32> PrettyTargetValue; 12488 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12489 12490 S.DiagRuntimeBehavior( 12491 E->getExprLoc(), E, 12492 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12493 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12494 << E->getSourceRange() << clang::SourceRange(CC)); 12495 } 12496 } else { 12497 // Otherwise, the implicit conversion may lose precision. 12498 DiagnoseImpCast(S, E, T, CC, 12499 diag::warn_impcast_integer_float_precision); 12500 } 12501 } 12502 } 12503 12504 DiagnoseNullConversion(S, E, T, CC); 12505 12506 S.DiscardMisalignedMemberAddress(Target, E); 12507 12508 if (Target->isBooleanType()) 12509 DiagnoseIntInBoolContext(S, E); 12510 12511 if (!Source->isIntegerType() || !Target->isIntegerType()) 12512 return; 12513 12514 // TODO: remove this early return once the false positives for constant->bool 12515 // in templates, macros, etc, are reduced or removed. 12516 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12517 return; 12518 12519 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12520 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12521 return adornObjCBoolConversionDiagWithTernaryFixit( 12522 S, E, 12523 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12524 << E->getType()); 12525 } 12526 12527 IntRange SourceTypeRange = 12528 IntRange::forTargetOfCanonicalType(S.Context, Source); 12529 IntRange LikelySourceRange = 12530 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12531 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12532 12533 if (LikelySourceRange.Width > TargetRange.Width) { 12534 // If the source is a constant, use a default-on diagnostic. 12535 // TODO: this should happen for bitfield stores, too. 12536 Expr::EvalResult Result; 12537 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12538 S.isConstantEvaluated())) { 12539 llvm::APSInt Value(32); 12540 Value = Result.Val.getInt(); 12541 12542 if (S.SourceMgr.isInSystemMacro(CC)) 12543 return; 12544 12545 std::string PrettySourceValue = Value.toString(10); 12546 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12547 12548 S.DiagRuntimeBehavior( 12549 E->getExprLoc(), E, 12550 S.PDiag(diag::warn_impcast_integer_precision_constant) 12551 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12552 << E->getSourceRange() << SourceRange(CC)); 12553 return; 12554 } 12555 12556 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12557 if (S.SourceMgr.isInSystemMacro(CC)) 12558 return; 12559 12560 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12561 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12562 /* pruneControlFlow */ true); 12563 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12564 } 12565 12566 if (TargetRange.Width > SourceTypeRange.Width) { 12567 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12568 if (UO->getOpcode() == UO_Minus) 12569 if (Source->isUnsignedIntegerType()) { 12570 if (Target->isUnsignedIntegerType()) 12571 return DiagnoseImpCast(S, E, T, CC, 12572 diag::warn_impcast_high_order_zero_bits); 12573 if (Target->isSignedIntegerType()) 12574 return DiagnoseImpCast(S, E, T, CC, 12575 diag::warn_impcast_nonnegative_result); 12576 } 12577 } 12578 12579 if (TargetRange.Width == LikelySourceRange.Width && 12580 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12581 Source->isSignedIntegerType()) { 12582 // Warn when doing a signed to signed conversion, warn if the positive 12583 // source value is exactly the width of the target type, which will 12584 // cause a negative value to be stored. 12585 12586 Expr::EvalResult Result; 12587 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12588 !S.SourceMgr.isInSystemMacro(CC)) { 12589 llvm::APSInt Value = Result.Val.getInt(); 12590 if (isSameWidthConstantConversion(S, E, T, CC)) { 12591 std::string PrettySourceValue = Value.toString(10); 12592 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12593 12594 S.DiagRuntimeBehavior( 12595 E->getExprLoc(), E, 12596 S.PDiag(diag::warn_impcast_integer_precision_constant) 12597 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12598 << E->getSourceRange() << SourceRange(CC)); 12599 return; 12600 } 12601 } 12602 12603 // Fall through for non-constants to give a sign conversion warning. 12604 } 12605 12606 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12607 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12608 LikelySourceRange.Width == TargetRange.Width)) { 12609 if (S.SourceMgr.isInSystemMacro(CC)) 12610 return; 12611 12612 unsigned DiagID = diag::warn_impcast_integer_sign; 12613 12614 // Traditionally, gcc has warned about this under -Wsign-compare. 12615 // We also want to warn about it in -Wconversion. 12616 // So if -Wconversion is off, use a completely identical diagnostic 12617 // in the sign-compare group. 12618 // The conditional-checking code will 12619 if (ICContext) { 12620 DiagID = diag::warn_impcast_integer_sign_conditional; 12621 *ICContext = true; 12622 } 12623 12624 return DiagnoseImpCast(S, E, T, CC, DiagID); 12625 } 12626 12627 // Diagnose conversions between different enumeration types. 12628 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12629 // type, to give us better diagnostics. 12630 QualType SourceType = E->getType(); 12631 if (!S.getLangOpts().CPlusPlus) { 12632 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12633 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12634 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12635 SourceType = S.Context.getTypeDeclType(Enum); 12636 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12637 } 12638 } 12639 12640 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12641 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12642 if (SourceEnum->getDecl()->hasNameForLinkage() && 12643 TargetEnum->getDecl()->hasNameForLinkage() && 12644 SourceEnum != TargetEnum) { 12645 if (S.SourceMgr.isInSystemMacro(CC)) 12646 return; 12647 12648 return DiagnoseImpCast(S, E, SourceType, T, CC, 12649 diag::warn_impcast_different_enum_types); 12650 } 12651 } 12652 12653 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12654 SourceLocation CC, QualType T); 12655 12656 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12657 SourceLocation CC, bool &ICContext) { 12658 E = E->IgnoreParenImpCasts(); 12659 12660 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12661 return CheckConditionalOperator(S, CO, CC, T); 12662 12663 AnalyzeImplicitConversions(S, E, CC); 12664 if (E->getType() != T) 12665 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12666 } 12667 12668 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12669 SourceLocation CC, QualType T) { 12670 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12671 12672 Expr *TrueExpr = E->getTrueExpr(); 12673 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12674 TrueExpr = BCO->getCommon(); 12675 12676 bool Suspicious = false; 12677 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12678 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12679 12680 if (T->isBooleanType()) 12681 DiagnoseIntInBoolContext(S, E); 12682 12683 // If -Wconversion would have warned about either of the candidates 12684 // for a signedness conversion to the context type... 12685 if (!Suspicious) return; 12686 12687 // ...but it's currently ignored... 12688 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12689 return; 12690 12691 // ...then check whether it would have warned about either of the 12692 // candidates for a signedness conversion to the condition type. 12693 if (E->getType() == T) return; 12694 12695 Suspicious = false; 12696 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12697 E->getType(), CC, &Suspicious); 12698 if (!Suspicious) 12699 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12700 E->getType(), CC, &Suspicious); 12701 } 12702 12703 /// Check conversion of given expression to boolean. 12704 /// Input argument E is a logical expression. 12705 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12706 if (S.getLangOpts().Bool) 12707 return; 12708 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12709 return; 12710 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12711 } 12712 12713 namespace { 12714 struct AnalyzeImplicitConversionsWorkItem { 12715 Expr *E; 12716 SourceLocation CC; 12717 bool IsListInit; 12718 }; 12719 } 12720 12721 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12722 /// that should be visited are added to WorkList. 12723 static void AnalyzeImplicitConversions( 12724 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12725 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12726 Expr *OrigE = Item.E; 12727 SourceLocation CC = Item.CC; 12728 12729 QualType T = OrigE->getType(); 12730 Expr *E = OrigE->IgnoreParenImpCasts(); 12731 12732 // Propagate whether we are in a C++ list initialization expression. 12733 // If so, we do not issue warnings for implicit int-float conversion 12734 // precision loss, because C++11 narrowing already handles it. 12735 bool IsListInit = Item.IsListInit || 12736 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12737 12738 if (E->isTypeDependent() || E->isValueDependent()) 12739 return; 12740 12741 Expr *SourceExpr = E; 12742 // Examine, but don't traverse into the source expression of an 12743 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12744 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12745 // evaluate it in the context of checking the specific conversion to T though. 12746 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12747 if (auto *Src = OVE->getSourceExpr()) 12748 SourceExpr = Src; 12749 12750 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12751 if (UO->getOpcode() == UO_Not && 12752 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12753 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12754 << OrigE->getSourceRange() << T->isBooleanType() 12755 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12756 12757 // For conditional operators, we analyze the arguments as if they 12758 // were being fed directly into the output. 12759 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12760 CheckConditionalOperator(S, CO, CC, T); 12761 return; 12762 } 12763 12764 // Check implicit argument conversions for function calls. 12765 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12766 CheckImplicitArgumentConversions(S, Call, CC); 12767 12768 // Go ahead and check any implicit conversions we might have skipped. 12769 // The non-canonical typecheck is just an optimization; 12770 // CheckImplicitConversion will filter out dead implicit conversions. 12771 if (SourceExpr->getType() != T) 12772 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12773 12774 // Now continue drilling into this expression. 12775 12776 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12777 // The bound subexpressions in a PseudoObjectExpr are not reachable 12778 // as transitive children. 12779 // FIXME: Use a more uniform representation for this. 12780 for (auto *SE : POE->semantics()) 12781 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12782 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12783 } 12784 12785 // Skip past explicit casts. 12786 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12787 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12788 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12789 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12790 WorkList.push_back({E, CC, IsListInit}); 12791 return; 12792 } 12793 12794 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12795 // Do a somewhat different check with comparison operators. 12796 if (BO->isComparisonOp()) 12797 return AnalyzeComparison(S, BO); 12798 12799 // And with simple assignments. 12800 if (BO->getOpcode() == BO_Assign) 12801 return AnalyzeAssignment(S, BO); 12802 // And with compound assignments. 12803 if (BO->isAssignmentOp()) 12804 return AnalyzeCompoundAssignment(S, BO); 12805 } 12806 12807 // These break the otherwise-useful invariant below. Fortunately, 12808 // we don't really need to recurse into them, because any internal 12809 // expressions should have been analyzed already when they were 12810 // built into statements. 12811 if (isa<StmtExpr>(E)) return; 12812 12813 // Don't descend into unevaluated contexts. 12814 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12815 12816 // Now just recurse over the expression's children. 12817 CC = E->getExprLoc(); 12818 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12819 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12820 for (Stmt *SubStmt : E->children()) { 12821 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12822 if (!ChildExpr) 12823 continue; 12824 12825 if (IsLogicalAndOperator && 12826 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12827 // Ignore checking string literals that are in logical and operators. 12828 // This is a common pattern for asserts. 12829 continue; 12830 WorkList.push_back({ChildExpr, CC, IsListInit}); 12831 } 12832 12833 if (BO && BO->isLogicalOp()) { 12834 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12835 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12836 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12837 12838 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12839 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12840 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12841 } 12842 12843 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12844 if (U->getOpcode() == UO_LNot) { 12845 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12846 } else if (U->getOpcode() != UO_AddrOf) { 12847 if (U->getSubExpr()->getType()->isAtomicType()) 12848 S.Diag(U->getSubExpr()->getBeginLoc(), 12849 diag::warn_atomic_implicit_seq_cst); 12850 } 12851 } 12852 } 12853 12854 /// AnalyzeImplicitConversions - Find and report any interesting 12855 /// implicit conversions in the given expression. There are a couple 12856 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12857 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12858 bool IsListInit/*= false*/) { 12859 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12860 WorkList.push_back({OrigE, CC, IsListInit}); 12861 while (!WorkList.empty()) 12862 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12863 } 12864 12865 /// Diagnose integer type and any valid implicit conversion to it. 12866 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12867 // Taking into account implicit conversions, 12868 // allow any integer. 12869 if (!E->getType()->isIntegerType()) { 12870 S.Diag(E->getBeginLoc(), 12871 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12872 return true; 12873 } 12874 // Potentially emit standard warnings for implicit conversions if enabled 12875 // using -Wconversion. 12876 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12877 return false; 12878 } 12879 12880 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12881 // Returns true when emitting a warning about taking the address of a reference. 12882 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12883 const PartialDiagnostic &PD) { 12884 E = E->IgnoreParenImpCasts(); 12885 12886 const FunctionDecl *FD = nullptr; 12887 12888 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12889 if (!DRE->getDecl()->getType()->isReferenceType()) 12890 return false; 12891 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12892 if (!M->getMemberDecl()->getType()->isReferenceType()) 12893 return false; 12894 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12895 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12896 return false; 12897 FD = Call->getDirectCallee(); 12898 } else { 12899 return false; 12900 } 12901 12902 SemaRef.Diag(E->getExprLoc(), PD); 12903 12904 // If possible, point to location of function. 12905 if (FD) { 12906 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12907 } 12908 12909 return true; 12910 } 12911 12912 // Returns true if the SourceLocation is expanded from any macro body. 12913 // Returns false if the SourceLocation is invalid, is from not in a macro 12914 // expansion, or is from expanded from a top-level macro argument. 12915 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12916 if (Loc.isInvalid()) 12917 return false; 12918 12919 while (Loc.isMacroID()) { 12920 if (SM.isMacroBodyExpansion(Loc)) 12921 return true; 12922 Loc = SM.getImmediateMacroCallerLoc(Loc); 12923 } 12924 12925 return false; 12926 } 12927 12928 /// Diagnose pointers that are always non-null. 12929 /// \param E the expression containing the pointer 12930 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12931 /// compared to a null pointer 12932 /// \param IsEqual True when the comparison is equal to a null pointer 12933 /// \param Range Extra SourceRange to highlight in the diagnostic 12934 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12935 Expr::NullPointerConstantKind NullKind, 12936 bool IsEqual, SourceRange Range) { 12937 if (!E) 12938 return; 12939 12940 // Don't warn inside macros. 12941 if (E->getExprLoc().isMacroID()) { 12942 const SourceManager &SM = getSourceManager(); 12943 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12944 IsInAnyMacroBody(SM, Range.getBegin())) 12945 return; 12946 } 12947 E = E->IgnoreImpCasts(); 12948 12949 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12950 12951 if (isa<CXXThisExpr>(E)) { 12952 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12953 : diag::warn_this_bool_conversion; 12954 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12955 return; 12956 } 12957 12958 bool IsAddressOf = false; 12959 12960 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12961 if (UO->getOpcode() != UO_AddrOf) 12962 return; 12963 IsAddressOf = true; 12964 E = UO->getSubExpr(); 12965 } 12966 12967 if (IsAddressOf) { 12968 unsigned DiagID = IsCompare 12969 ? diag::warn_address_of_reference_null_compare 12970 : diag::warn_address_of_reference_bool_conversion; 12971 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12972 << IsEqual; 12973 if (CheckForReference(*this, E, PD)) { 12974 return; 12975 } 12976 } 12977 12978 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12979 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12980 std::string Str; 12981 llvm::raw_string_ostream S(Str); 12982 E->printPretty(S, nullptr, getPrintingPolicy()); 12983 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12984 : diag::warn_cast_nonnull_to_bool; 12985 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12986 << E->getSourceRange() << Range << IsEqual; 12987 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12988 }; 12989 12990 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12991 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12992 if (auto *Callee = Call->getDirectCallee()) { 12993 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12994 ComplainAboutNonnullParamOrCall(A); 12995 return; 12996 } 12997 } 12998 } 12999 13000 // Expect to find a single Decl. Skip anything more complicated. 13001 ValueDecl *D = nullptr; 13002 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13003 D = R->getDecl(); 13004 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13005 D = M->getMemberDecl(); 13006 } 13007 13008 // Weak Decls can be null. 13009 if (!D || D->isWeak()) 13010 return; 13011 13012 // Check for parameter decl with nonnull attribute 13013 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13014 if (getCurFunction() && 13015 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13016 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13017 ComplainAboutNonnullParamOrCall(A); 13018 return; 13019 } 13020 13021 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13022 // Skip function template not specialized yet. 13023 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13024 return; 13025 auto ParamIter = llvm::find(FD->parameters(), PV); 13026 assert(ParamIter != FD->param_end()); 13027 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13028 13029 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13030 if (!NonNull->args_size()) { 13031 ComplainAboutNonnullParamOrCall(NonNull); 13032 return; 13033 } 13034 13035 for (const ParamIdx &ArgNo : NonNull->args()) { 13036 if (ArgNo.getASTIndex() == ParamNo) { 13037 ComplainAboutNonnullParamOrCall(NonNull); 13038 return; 13039 } 13040 } 13041 } 13042 } 13043 } 13044 } 13045 13046 QualType T = D->getType(); 13047 const bool IsArray = T->isArrayType(); 13048 const bool IsFunction = T->isFunctionType(); 13049 13050 // Address of function is used to silence the function warning. 13051 if (IsAddressOf && IsFunction) { 13052 return; 13053 } 13054 13055 // Found nothing. 13056 if (!IsAddressOf && !IsFunction && !IsArray) 13057 return; 13058 13059 // Pretty print the expression for the diagnostic. 13060 std::string Str; 13061 llvm::raw_string_ostream S(Str); 13062 E->printPretty(S, nullptr, getPrintingPolicy()); 13063 13064 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13065 : diag::warn_impcast_pointer_to_bool; 13066 enum { 13067 AddressOf, 13068 FunctionPointer, 13069 ArrayPointer 13070 } DiagType; 13071 if (IsAddressOf) 13072 DiagType = AddressOf; 13073 else if (IsFunction) 13074 DiagType = FunctionPointer; 13075 else if (IsArray) 13076 DiagType = ArrayPointer; 13077 else 13078 llvm_unreachable("Could not determine diagnostic."); 13079 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13080 << Range << IsEqual; 13081 13082 if (!IsFunction) 13083 return; 13084 13085 // Suggest '&' to silence the function warning. 13086 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13087 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13088 13089 // Check to see if '()' fixit should be emitted. 13090 QualType ReturnType; 13091 UnresolvedSet<4> NonTemplateOverloads; 13092 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13093 if (ReturnType.isNull()) 13094 return; 13095 13096 if (IsCompare) { 13097 // There are two cases here. If there is null constant, the only suggest 13098 // for a pointer return type. If the null is 0, then suggest if the return 13099 // type is a pointer or an integer type. 13100 if (!ReturnType->isPointerType()) { 13101 if (NullKind == Expr::NPCK_ZeroExpression || 13102 NullKind == Expr::NPCK_ZeroLiteral) { 13103 if (!ReturnType->isIntegerType()) 13104 return; 13105 } else { 13106 return; 13107 } 13108 } 13109 } else { // !IsCompare 13110 // For function to bool, only suggest if the function pointer has bool 13111 // return type. 13112 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13113 return; 13114 } 13115 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13116 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13117 } 13118 13119 /// Diagnoses "dangerous" implicit conversions within the given 13120 /// expression (which is a full expression). Implements -Wconversion 13121 /// and -Wsign-compare. 13122 /// 13123 /// \param CC the "context" location of the implicit conversion, i.e. 13124 /// the most location of the syntactic entity requiring the implicit 13125 /// conversion 13126 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13127 // Don't diagnose in unevaluated contexts. 13128 if (isUnevaluatedContext()) 13129 return; 13130 13131 // Don't diagnose for value- or type-dependent expressions. 13132 if (E->isTypeDependent() || E->isValueDependent()) 13133 return; 13134 13135 // Check for array bounds violations in cases where the check isn't triggered 13136 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13137 // ArraySubscriptExpr is on the RHS of a variable initialization. 13138 CheckArrayAccess(E); 13139 13140 // This is not the right CC for (e.g.) a variable initialization. 13141 AnalyzeImplicitConversions(*this, E, CC); 13142 } 13143 13144 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13145 /// Input argument E is a logical expression. 13146 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13147 ::CheckBoolLikeConversion(*this, E, CC); 13148 } 13149 13150 /// Diagnose when expression is an integer constant expression and its evaluation 13151 /// results in integer overflow 13152 void Sema::CheckForIntOverflow (Expr *E) { 13153 // Use a work list to deal with nested struct initializers. 13154 SmallVector<Expr *, 2> Exprs(1, E); 13155 13156 do { 13157 Expr *OriginalE = Exprs.pop_back_val(); 13158 Expr *E = OriginalE->IgnoreParenCasts(); 13159 13160 if (isa<BinaryOperator>(E)) { 13161 E->EvaluateForOverflow(Context); 13162 continue; 13163 } 13164 13165 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13166 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13167 else if (isa<ObjCBoxedExpr>(OriginalE)) 13168 E->EvaluateForOverflow(Context); 13169 else if (auto Call = dyn_cast<CallExpr>(E)) 13170 Exprs.append(Call->arg_begin(), Call->arg_end()); 13171 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13172 Exprs.append(Message->arg_begin(), Message->arg_end()); 13173 } while (!Exprs.empty()); 13174 } 13175 13176 namespace { 13177 13178 /// Visitor for expressions which looks for unsequenced operations on the 13179 /// same object. 13180 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13181 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13182 13183 /// A tree of sequenced regions within an expression. Two regions are 13184 /// unsequenced if one is an ancestor or a descendent of the other. When we 13185 /// finish processing an expression with sequencing, such as a comma 13186 /// expression, we fold its tree nodes into its parent, since they are 13187 /// unsequenced with respect to nodes we will visit later. 13188 class SequenceTree { 13189 struct Value { 13190 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13191 unsigned Parent : 31; 13192 unsigned Merged : 1; 13193 }; 13194 SmallVector<Value, 8> Values; 13195 13196 public: 13197 /// A region within an expression which may be sequenced with respect 13198 /// to some other region. 13199 class Seq { 13200 friend class SequenceTree; 13201 13202 unsigned Index; 13203 13204 explicit Seq(unsigned N) : Index(N) {} 13205 13206 public: 13207 Seq() : Index(0) {} 13208 }; 13209 13210 SequenceTree() { Values.push_back(Value(0)); } 13211 Seq root() const { return Seq(0); } 13212 13213 /// Create a new sequence of operations, which is an unsequenced 13214 /// subset of \p Parent. This sequence of operations is sequenced with 13215 /// respect to other children of \p Parent. 13216 Seq allocate(Seq Parent) { 13217 Values.push_back(Value(Parent.Index)); 13218 return Seq(Values.size() - 1); 13219 } 13220 13221 /// Merge a sequence of operations into its parent. 13222 void merge(Seq S) { 13223 Values[S.Index].Merged = true; 13224 } 13225 13226 /// Determine whether two operations are unsequenced. This operation 13227 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13228 /// should have been merged into its parent as appropriate. 13229 bool isUnsequenced(Seq Cur, Seq Old) { 13230 unsigned C = representative(Cur.Index); 13231 unsigned Target = representative(Old.Index); 13232 while (C >= Target) { 13233 if (C == Target) 13234 return true; 13235 C = Values[C].Parent; 13236 } 13237 return false; 13238 } 13239 13240 private: 13241 /// Pick a representative for a sequence. 13242 unsigned representative(unsigned K) { 13243 if (Values[K].Merged) 13244 // Perform path compression as we go. 13245 return Values[K].Parent = representative(Values[K].Parent); 13246 return K; 13247 } 13248 }; 13249 13250 /// An object for which we can track unsequenced uses. 13251 using Object = const NamedDecl *; 13252 13253 /// Different flavors of object usage which we track. We only track the 13254 /// least-sequenced usage of each kind. 13255 enum UsageKind { 13256 /// A read of an object. Multiple unsequenced reads are OK. 13257 UK_Use, 13258 13259 /// A modification of an object which is sequenced before the value 13260 /// computation of the expression, such as ++n in C++. 13261 UK_ModAsValue, 13262 13263 /// A modification of an object which is not sequenced before the value 13264 /// computation of the expression, such as n++. 13265 UK_ModAsSideEffect, 13266 13267 UK_Count = UK_ModAsSideEffect + 1 13268 }; 13269 13270 /// Bundle together a sequencing region and the expression corresponding 13271 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13272 struct Usage { 13273 const Expr *UsageExpr; 13274 SequenceTree::Seq Seq; 13275 13276 Usage() : UsageExpr(nullptr), Seq() {} 13277 }; 13278 13279 struct UsageInfo { 13280 Usage Uses[UK_Count]; 13281 13282 /// Have we issued a diagnostic for this object already? 13283 bool Diagnosed; 13284 13285 UsageInfo() : Uses(), Diagnosed(false) {} 13286 }; 13287 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13288 13289 Sema &SemaRef; 13290 13291 /// Sequenced regions within the expression. 13292 SequenceTree Tree; 13293 13294 /// Declaration modifications and references which we have seen. 13295 UsageInfoMap UsageMap; 13296 13297 /// The region we are currently within. 13298 SequenceTree::Seq Region; 13299 13300 /// Filled in with declarations which were modified as a side-effect 13301 /// (that is, post-increment operations). 13302 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13303 13304 /// Expressions to check later. We defer checking these to reduce 13305 /// stack usage. 13306 SmallVectorImpl<const Expr *> &WorkList; 13307 13308 /// RAII object wrapping the visitation of a sequenced subexpression of an 13309 /// expression. At the end of this process, the side-effects of the evaluation 13310 /// become sequenced with respect to the value computation of the result, so 13311 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13312 /// UK_ModAsValue. 13313 struct SequencedSubexpression { 13314 SequencedSubexpression(SequenceChecker &Self) 13315 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13316 Self.ModAsSideEffect = &ModAsSideEffect; 13317 } 13318 13319 ~SequencedSubexpression() { 13320 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13321 // Add a new usage with usage kind UK_ModAsValue, and then restore 13322 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13323 // the previous one was empty). 13324 UsageInfo &UI = Self.UsageMap[M.first]; 13325 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13326 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13327 SideEffectUsage = M.second; 13328 } 13329 Self.ModAsSideEffect = OldModAsSideEffect; 13330 } 13331 13332 SequenceChecker &Self; 13333 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13334 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13335 }; 13336 13337 /// RAII object wrapping the visitation of a subexpression which we might 13338 /// choose to evaluate as a constant. If any subexpression is evaluated and 13339 /// found to be non-constant, this allows us to suppress the evaluation of 13340 /// the outer expression. 13341 class EvaluationTracker { 13342 public: 13343 EvaluationTracker(SequenceChecker &Self) 13344 : Self(Self), Prev(Self.EvalTracker) { 13345 Self.EvalTracker = this; 13346 } 13347 13348 ~EvaluationTracker() { 13349 Self.EvalTracker = Prev; 13350 if (Prev) 13351 Prev->EvalOK &= EvalOK; 13352 } 13353 13354 bool evaluate(const Expr *E, bool &Result) { 13355 if (!EvalOK || E->isValueDependent()) 13356 return false; 13357 EvalOK = E->EvaluateAsBooleanCondition( 13358 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13359 return EvalOK; 13360 } 13361 13362 private: 13363 SequenceChecker &Self; 13364 EvaluationTracker *Prev; 13365 bool EvalOK = true; 13366 } *EvalTracker = nullptr; 13367 13368 /// Find the object which is produced by the specified expression, 13369 /// if any. 13370 Object getObject(const Expr *E, bool Mod) const { 13371 E = E->IgnoreParenCasts(); 13372 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13373 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13374 return getObject(UO->getSubExpr(), Mod); 13375 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13376 if (BO->getOpcode() == BO_Comma) 13377 return getObject(BO->getRHS(), Mod); 13378 if (Mod && BO->isAssignmentOp()) 13379 return getObject(BO->getLHS(), Mod); 13380 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13381 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13382 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13383 return ME->getMemberDecl(); 13384 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13385 // FIXME: If this is a reference, map through to its value. 13386 return DRE->getDecl(); 13387 return nullptr; 13388 } 13389 13390 /// Note that an object \p O was modified or used by an expression 13391 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13392 /// the object \p O as obtained via the \p UsageMap. 13393 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13394 // Get the old usage for the given object and usage kind. 13395 Usage &U = UI.Uses[UK]; 13396 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13397 // If we have a modification as side effect and are in a sequenced 13398 // subexpression, save the old Usage so that we can restore it later 13399 // in SequencedSubexpression::~SequencedSubexpression. 13400 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13401 ModAsSideEffect->push_back(std::make_pair(O, U)); 13402 // Then record the new usage with the current sequencing region. 13403 U.UsageExpr = UsageExpr; 13404 U.Seq = Region; 13405 } 13406 } 13407 13408 /// Check whether a modification or use of an object \p O in an expression 13409 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13410 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13411 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13412 /// usage and false we are checking for a mod-use unsequenced usage. 13413 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13414 UsageKind OtherKind, bool IsModMod) { 13415 if (UI.Diagnosed) 13416 return; 13417 13418 const Usage &U = UI.Uses[OtherKind]; 13419 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13420 return; 13421 13422 const Expr *Mod = U.UsageExpr; 13423 const Expr *ModOrUse = UsageExpr; 13424 if (OtherKind == UK_Use) 13425 std::swap(Mod, ModOrUse); 13426 13427 SemaRef.DiagRuntimeBehavior( 13428 Mod->getExprLoc(), {Mod, ModOrUse}, 13429 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13430 : diag::warn_unsequenced_mod_use) 13431 << O << SourceRange(ModOrUse->getExprLoc())); 13432 UI.Diagnosed = true; 13433 } 13434 13435 // A note on note{Pre, Post}{Use, Mod}: 13436 // 13437 // (It helps to follow the algorithm with an expression such as 13438 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13439 // operations before C++17 and both are well-defined in C++17). 13440 // 13441 // When visiting a node which uses/modify an object we first call notePreUse 13442 // or notePreMod before visiting its sub-expression(s). At this point the 13443 // children of the current node have not yet been visited and so the eventual 13444 // uses/modifications resulting from the children of the current node have not 13445 // been recorded yet. 13446 // 13447 // We then visit the children of the current node. After that notePostUse or 13448 // notePostMod is called. These will 1) detect an unsequenced modification 13449 // as side effect (as in "k++ + k") and 2) add a new usage with the 13450 // appropriate usage kind. 13451 // 13452 // We also have to be careful that some operation sequences modification as 13453 // side effect as well (for example: || or ,). To account for this we wrap 13454 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13455 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13456 // which record usages which are modifications as side effect, and then 13457 // downgrade them (or more accurately restore the previous usage which was a 13458 // modification as side effect) when exiting the scope of the sequenced 13459 // subexpression. 13460 13461 void notePreUse(Object O, const Expr *UseExpr) { 13462 UsageInfo &UI = UsageMap[O]; 13463 // Uses conflict with other modifications. 13464 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13465 } 13466 13467 void notePostUse(Object O, const Expr *UseExpr) { 13468 UsageInfo &UI = UsageMap[O]; 13469 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13470 /*IsModMod=*/false); 13471 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13472 } 13473 13474 void notePreMod(Object O, const Expr *ModExpr) { 13475 UsageInfo &UI = UsageMap[O]; 13476 // Modifications conflict with other modifications and with uses. 13477 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13478 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13479 } 13480 13481 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13482 UsageInfo &UI = UsageMap[O]; 13483 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13484 /*IsModMod=*/true); 13485 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13486 } 13487 13488 public: 13489 SequenceChecker(Sema &S, const Expr *E, 13490 SmallVectorImpl<const Expr *> &WorkList) 13491 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13492 Visit(E); 13493 // Silence a -Wunused-private-field since WorkList is now unused. 13494 // TODO: Evaluate if it can be used, and if not remove it. 13495 (void)this->WorkList; 13496 } 13497 13498 void VisitStmt(const Stmt *S) { 13499 // Skip all statements which aren't expressions for now. 13500 } 13501 13502 void VisitExpr(const Expr *E) { 13503 // By default, just recurse to evaluated subexpressions. 13504 Base::VisitStmt(E); 13505 } 13506 13507 void VisitCastExpr(const CastExpr *E) { 13508 Object O = Object(); 13509 if (E->getCastKind() == CK_LValueToRValue) 13510 O = getObject(E->getSubExpr(), false); 13511 13512 if (O) 13513 notePreUse(O, E); 13514 VisitExpr(E); 13515 if (O) 13516 notePostUse(O, E); 13517 } 13518 13519 void VisitSequencedExpressions(const Expr *SequencedBefore, 13520 const Expr *SequencedAfter) { 13521 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13522 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13523 SequenceTree::Seq OldRegion = Region; 13524 13525 { 13526 SequencedSubexpression SeqBefore(*this); 13527 Region = BeforeRegion; 13528 Visit(SequencedBefore); 13529 } 13530 13531 Region = AfterRegion; 13532 Visit(SequencedAfter); 13533 13534 Region = OldRegion; 13535 13536 Tree.merge(BeforeRegion); 13537 Tree.merge(AfterRegion); 13538 } 13539 13540 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13541 // C++17 [expr.sub]p1: 13542 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13543 // expression E1 is sequenced before the expression E2. 13544 if (SemaRef.getLangOpts().CPlusPlus17) 13545 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13546 else { 13547 Visit(ASE->getLHS()); 13548 Visit(ASE->getRHS()); 13549 } 13550 } 13551 13552 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13553 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13554 void VisitBinPtrMem(const BinaryOperator *BO) { 13555 // C++17 [expr.mptr.oper]p4: 13556 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13557 // the expression E1 is sequenced before the expression E2. 13558 if (SemaRef.getLangOpts().CPlusPlus17) 13559 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13560 else { 13561 Visit(BO->getLHS()); 13562 Visit(BO->getRHS()); 13563 } 13564 } 13565 13566 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13567 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13568 void VisitBinShlShr(const BinaryOperator *BO) { 13569 // C++17 [expr.shift]p4: 13570 // The expression E1 is sequenced before the expression E2. 13571 if (SemaRef.getLangOpts().CPlusPlus17) 13572 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13573 else { 13574 Visit(BO->getLHS()); 13575 Visit(BO->getRHS()); 13576 } 13577 } 13578 13579 void VisitBinComma(const BinaryOperator *BO) { 13580 // C++11 [expr.comma]p1: 13581 // Every value computation and side effect associated with the left 13582 // expression is sequenced before every value computation and side 13583 // effect associated with the right expression. 13584 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13585 } 13586 13587 void VisitBinAssign(const BinaryOperator *BO) { 13588 SequenceTree::Seq RHSRegion; 13589 SequenceTree::Seq LHSRegion; 13590 if (SemaRef.getLangOpts().CPlusPlus17) { 13591 RHSRegion = Tree.allocate(Region); 13592 LHSRegion = Tree.allocate(Region); 13593 } else { 13594 RHSRegion = Region; 13595 LHSRegion = Region; 13596 } 13597 SequenceTree::Seq OldRegion = Region; 13598 13599 // C++11 [expr.ass]p1: 13600 // [...] the assignment is sequenced after the value computation 13601 // of the right and left operands, [...] 13602 // 13603 // so check it before inspecting the operands and update the 13604 // map afterwards. 13605 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13606 if (O) 13607 notePreMod(O, BO); 13608 13609 if (SemaRef.getLangOpts().CPlusPlus17) { 13610 // C++17 [expr.ass]p1: 13611 // [...] The right operand is sequenced before the left operand. [...] 13612 { 13613 SequencedSubexpression SeqBefore(*this); 13614 Region = RHSRegion; 13615 Visit(BO->getRHS()); 13616 } 13617 13618 Region = LHSRegion; 13619 Visit(BO->getLHS()); 13620 13621 if (O && isa<CompoundAssignOperator>(BO)) 13622 notePostUse(O, BO); 13623 13624 } else { 13625 // C++11 does not specify any sequencing between the LHS and RHS. 13626 Region = LHSRegion; 13627 Visit(BO->getLHS()); 13628 13629 if (O && isa<CompoundAssignOperator>(BO)) 13630 notePostUse(O, BO); 13631 13632 Region = RHSRegion; 13633 Visit(BO->getRHS()); 13634 } 13635 13636 // C++11 [expr.ass]p1: 13637 // the assignment is sequenced [...] before the value computation of the 13638 // assignment expression. 13639 // C11 6.5.16/3 has no such rule. 13640 Region = OldRegion; 13641 if (O) 13642 notePostMod(O, BO, 13643 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13644 : UK_ModAsSideEffect); 13645 if (SemaRef.getLangOpts().CPlusPlus17) { 13646 Tree.merge(RHSRegion); 13647 Tree.merge(LHSRegion); 13648 } 13649 } 13650 13651 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13652 VisitBinAssign(CAO); 13653 } 13654 13655 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13656 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13657 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13658 Object O = getObject(UO->getSubExpr(), true); 13659 if (!O) 13660 return VisitExpr(UO); 13661 13662 notePreMod(O, UO); 13663 Visit(UO->getSubExpr()); 13664 // C++11 [expr.pre.incr]p1: 13665 // the expression ++x is equivalent to x+=1 13666 notePostMod(O, UO, 13667 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13668 : UK_ModAsSideEffect); 13669 } 13670 13671 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13672 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13673 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13674 Object O = getObject(UO->getSubExpr(), true); 13675 if (!O) 13676 return VisitExpr(UO); 13677 13678 notePreMod(O, UO); 13679 Visit(UO->getSubExpr()); 13680 notePostMod(O, UO, UK_ModAsSideEffect); 13681 } 13682 13683 void VisitBinLOr(const BinaryOperator *BO) { 13684 // C++11 [expr.log.or]p2: 13685 // If the second expression is evaluated, every value computation and 13686 // side effect associated with the first expression is sequenced before 13687 // every value computation and side effect associated with the 13688 // second expression. 13689 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13690 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13691 SequenceTree::Seq OldRegion = Region; 13692 13693 EvaluationTracker Eval(*this); 13694 { 13695 SequencedSubexpression Sequenced(*this); 13696 Region = LHSRegion; 13697 Visit(BO->getLHS()); 13698 } 13699 13700 // C++11 [expr.log.or]p1: 13701 // [...] the second operand is not evaluated if the first operand 13702 // evaluates to true. 13703 bool EvalResult = false; 13704 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13705 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13706 if (ShouldVisitRHS) { 13707 Region = RHSRegion; 13708 Visit(BO->getRHS()); 13709 } 13710 13711 Region = OldRegion; 13712 Tree.merge(LHSRegion); 13713 Tree.merge(RHSRegion); 13714 } 13715 13716 void VisitBinLAnd(const BinaryOperator *BO) { 13717 // C++11 [expr.log.and]p2: 13718 // If the second expression is evaluated, every value computation and 13719 // side effect associated with the first expression is sequenced before 13720 // every value computation and side effect associated with the 13721 // second expression. 13722 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13723 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13724 SequenceTree::Seq OldRegion = Region; 13725 13726 EvaluationTracker Eval(*this); 13727 { 13728 SequencedSubexpression Sequenced(*this); 13729 Region = LHSRegion; 13730 Visit(BO->getLHS()); 13731 } 13732 13733 // C++11 [expr.log.and]p1: 13734 // [...] the second operand is not evaluated if the first operand is false. 13735 bool EvalResult = false; 13736 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13737 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13738 if (ShouldVisitRHS) { 13739 Region = RHSRegion; 13740 Visit(BO->getRHS()); 13741 } 13742 13743 Region = OldRegion; 13744 Tree.merge(LHSRegion); 13745 Tree.merge(RHSRegion); 13746 } 13747 13748 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13749 // C++11 [expr.cond]p1: 13750 // [...] Every value computation and side effect associated with the first 13751 // expression is sequenced before every value computation and side effect 13752 // associated with the second or third expression. 13753 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13754 13755 // No sequencing is specified between the true and false expression. 13756 // However since exactly one of both is going to be evaluated we can 13757 // consider them to be sequenced. This is needed to avoid warning on 13758 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13759 // both the true and false expressions because we can't evaluate x. 13760 // This will still allow us to detect an expression like (pre C++17) 13761 // "(x ? y += 1 : y += 2) = y". 13762 // 13763 // We don't wrap the visitation of the true and false expression with 13764 // SequencedSubexpression because we don't want to downgrade modifications 13765 // as side effect in the true and false expressions after the visition 13766 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13767 // not warn between the two "y++", but we should warn between the "y++" 13768 // and the "y". 13769 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13770 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13771 SequenceTree::Seq OldRegion = Region; 13772 13773 EvaluationTracker Eval(*this); 13774 { 13775 SequencedSubexpression Sequenced(*this); 13776 Region = ConditionRegion; 13777 Visit(CO->getCond()); 13778 } 13779 13780 // C++11 [expr.cond]p1: 13781 // [...] The first expression is contextually converted to bool (Clause 4). 13782 // It is evaluated and if it is true, the result of the conditional 13783 // expression is the value of the second expression, otherwise that of the 13784 // third expression. Only one of the second and third expressions is 13785 // evaluated. [...] 13786 bool EvalResult = false; 13787 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13788 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13789 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13790 if (ShouldVisitTrueExpr) { 13791 Region = TrueRegion; 13792 Visit(CO->getTrueExpr()); 13793 } 13794 if (ShouldVisitFalseExpr) { 13795 Region = FalseRegion; 13796 Visit(CO->getFalseExpr()); 13797 } 13798 13799 Region = OldRegion; 13800 Tree.merge(ConditionRegion); 13801 Tree.merge(TrueRegion); 13802 Tree.merge(FalseRegion); 13803 } 13804 13805 void VisitCallExpr(const CallExpr *CE) { 13806 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13807 13808 if (CE->isUnevaluatedBuiltinCall(Context)) 13809 return; 13810 13811 // C++11 [intro.execution]p15: 13812 // When calling a function [...], every value computation and side effect 13813 // associated with any argument expression, or with the postfix expression 13814 // designating the called function, is sequenced before execution of every 13815 // expression or statement in the body of the function [and thus before 13816 // the value computation of its result]. 13817 SequencedSubexpression Sequenced(*this); 13818 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13819 // C++17 [expr.call]p5 13820 // The postfix-expression is sequenced before each expression in the 13821 // expression-list and any default argument. [...] 13822 SequenceTree::Seq CalleeRegion; 13823 SequenceTree::Seq OtherRegion; 13824 if (SemaRef.getLangOpts().CPlusPlus17) { 13825 CalleeRegion = Tree.allocate(Region); 13826 OtherRegion = Tree.allocate(Region); 13827 } else { 13828 CalleeRegion = Region; 13829 OtherRegion = Region; 13830 } 13831 SequenceTree::Seq OldRegion = Region; 13832 13833 // Visit the callee expression first. 13834 Region = CalleeRegion; 13835 if (SemaRef.getLangOpts().CPlusPlus17) { 13836 SequencedSubexpression Sequenced(*this); 13837 Visit(CE->getCallee()); 13838 } else { 13839 Visit(CE->getCallee()); 13840 } 13841 13842 // Then visit the argument expressions. 13843 Region = OtherRegion; 13844 for (const Expr *Argument : CE->arguments()) 13845 Visit(Argument); 13846 13847 Region = OldRegion; 13848 if (SemaRef.getLangOpts().CPlusPlus17) { 13849 Tree.merge(CalleeRegion); 13850 Tree.merge(OtherRegion); 13851 } 13852 }); 13853 } 13854 13855 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13856 // C++17 [over.match.oper]p2: 13857 // [...] the operator notation is first transformed to the equivalent 13858 // function-call notation as summarized in Table 12 (where @ denotes one 13859 // of the operators covered in the specified subclause). However, the 13860 // operands are sequenced in the order prescribed for the built-in 13861 // operator (Clause 8). 13862 // 13863 // From the above only overloaded binary operators and overloaded call 13864 // operators have sequencing rules in C++17 that we need to handle 13865 // separately. 13866 if (!SemaRef.getLangOpts().CPlusPlus17 || 13867 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13868 return VisitCallExpr(CXXOCE); 13869 13870 enum { 13871 NoSequencing, 13872 LHSBeforeRHS, 13873 RHSBeforeLHS, 13874 LHSBeforeRest 13875 } SequencingKind; 13876 switch (CXXOCE->getOperator()) { 13877 case OO_Equal: 13878 case OO_PlusEqual: 13879 case OO_MinusEqual: 13880 case OO_StarEqual: 13881 case OO_SlashEqual: 13882 case OO_PercentEqual: 13883 case OO_CaretEqual: 13884 case OO_AmpEqual: 13885 case OO_PipeEqual: 13886 case OO_LessLessEqual: 13887 case OO_GreaterGreaterEqual: 13888 SequencingKind = RHSBeforeLHS; 13889 break; 13890 13891 case OO_LessLess: 13892 case OO_GreaterGreater: 13893 case OO_AmpAmp: 13894 case OO_PipePipe: 13895 case OO_Comma: 13896 case OO_ArrowStar: 13897 case OO_Subscript: 13898 SequencingKind = LHSBeforeRHS; 13899 break; 13900 13901 case OO_Call: 13902 SequencingKind = LHSBeforeRest; 13903 break; 13904 13905 default: 13906 SequencingKind = NoSequencing; 13907 break; 13908 } 13909 13910 if (SequencingKind == NoSequencing) 13911 return VisitCallExpr(CXXOCE); 13912 13913 // This is a call, so all subexpressions are sequenced before the result. 13914 SequencedSubexpression Sequenced(*this); 13915 13916 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13917 assert(SemaRef.getLangOpts().CPlusPlus17 && 13918 "Should only get there with C++17 and above!"); 13919 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13920 "Should only get there with an overloaded binary operator" 13921 " or an overloaded call operator!"); 13922 13923 if (SequencingKind == LHSBeforeRest) { 13924 assert(CXXOCE->getOperator() == OO_Call && 13925 "We should only have an overloaded call operator here!"); 13926 13927 // This is very similar to VisitCallExpr, except that we only have the 13928 // C++17 case. The postfix-expression is the first argument of the 13929 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13930 // are in the following arguments. 13931 // 13932 // Note that we intentionally do not visit the callee expression since 13933 // it is just a decayed reference to a function. 13934 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13935 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13936 SequenceTree::Seq OldRegion = Region; 13937 13938 assert(CXXOCE->getNumArgs() >= 1 && 13939 "An overloaded call operator must have at least one argument" 13940 " for the postfix-expression!"); 13941 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13942 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13943 CXXOCE->getNumArgs() - 1); 13944 13945 // Visit the postfix-expression first. 13946 { 13947 Region = PostfixExprRegion; 13948 SequencedSubexpression Sequenced(*this); 13949 Visit(PostfixExpr); 13950 } 13951 13952 // Then visit the argument expressions. 13953 Region = ArgsRegion; 13954 for (const Expr *Arg : Args) 13955 Visit(Arg); 13956 13957 Region = OldRegion; 13958 Tree.merge(PostfixExprRegion); 13959 Tree.merge(ArgsRegion); 13960 } else { 13961 assert(CXXOCE->getNumArgs() == 2 && 13962 "Should only have two arguments here!"); 13963 assert((SequencingKind == LHSBeforeRHS || 13964 SequencingKind == RHSBeforeLHS) && 13965 "Unexpected sequencing kind!"); 13966 13967 // We do not visit the callee expression since it is just a decayed 13968 // reference to a function. 13969 const Expr *E1 = CXXOCE->getArg(0); 13970 const Expr *E2 = CXXOCE->getArg(1); 13971 if (SequencingKind == RHSBeforeLHS) 13972 std::swap(E1, E2); 13973 13974 return VisitSequencedExpressions(E1, E2); 13975 } 13976 }); 13977 } 13978 13979 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13980 // This is a call, so all subexpressions are sequenced before the result. 13981 SequencedSubexpression Sequenced(*this); 13982 13983 if (!CCE->isListInitialization()) 13984 return VisitExpr(CCE); 13985 13986 // In C++11, list initializations are sequenced. 13987 SmallVector<SequenceTree::Seq, 32> Elts; 13988 SequenceTree::Seq Parent = Region; 13989 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13990 E = CCE->arg_end(); 13991 I != E; ++I) { 13992 Region = Tree.allocate(Parent); 13993 Elts.push_back(Region); 13994 Visit(*I); 13995 } 13996 13997 // Forget that the initializers are sequenced. 13998 Region = Parent; 13999 for (unsigned I = 0; I < Elts.size(); ++I) 14000 Tree.merge(Elts[I]); 14001 } 14002 14003 void VisitInitListExpr(const InitListExpr *ILE) { 14004 if (!SemaRef.getLangOpts().CPlusPlus11) 14005 return VisitExpr(ILE); 14006 14007 // In C++11, list initializations are sequenced. 14008 SmallVector<SequenceTree::Seq, 32> Elts; 14009 SequenceTree::Seq Parent = Region; 14010 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14011 const Expr *E = ILE->getInit(I); 14012 if (!E) 14013 continue; 14014 Region = Tree.allocate(Parent); 14015 Elts.push_back(Region); 14016 Visit(E); 14017 } 14018 14019 // Forget that the initializers are sequenced. 14020 Region = Parent; 14021 for (unsigned I = 0; I < Elts.size(); ++I) 14022 Tree.merge(Elts[I]); 14023 } 14024 }; 14025 14026 } // namespace 14027 14028 void Sema::CheckUnsequencedOperations(const Expr *E) { 14029 SmallVector<const Expr *, 8> WorkList; 14030 WorkList.push_back(E); 14031 while (!WorkList.empty()) { 14032 const Expr *Item = WorkList.pop_back_val(); 14033 SequenceChecker(*this, Item, WorkList); 14034 } 14035 } 14036 14037 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14038 bool IsConstexpr) { 14039 llvm::SaveAndRestore<bool> ConstantContext( 14040 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14041 CheckImplicitConversions(E, CheckLoc); 14042 if (!E->isInstantiationDependent()) 14043 CheckUnsequencedOperations(E); 14044 if (!IsConstexpr && !E->isValueDependent()) 14045 CheckForIntOverflow(E); 14046 DiagnoseMisalignedMembers(); 14047 } 14048 14049 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14050 FieldDecl *BitField, 14051 Expr *Init) { 14052 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14053 } 14054 14055 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14056 SourceLocation Loc) { 14057 if (!PType->isVariablyModifiedType()) 14058 return; 14059 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14060 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14061 return; 14062 } 14063 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14064 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14065 return; 14066 } 14067 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14068 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14069 return; 14070 } 14071 14072 const ArrayType *AT = S.Context.getAsArrayType(PType); 14073 if (!AT) 14074 return; 14075 14076 if (AT->getSizeModifier() != ArrayType::Star) { 14077 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14078 return; 14079 } 14080 14081 S.Diag(Loc, diag::err_array_star_in_function_definition); 14082 } 14083 14084 /// CheckParmsForFunctionDef - Check that the parameters of the given 14085 /// function are appropriate for the definition of a function. This 14086 /// takes care of any checks that cannot be performed on the 14087 /// declaration itself, e.g., that the types of each of the function 14088 /// parameters are complete. 14089 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14090 bool CheckParameterNames) { 14091 bool HasInvalidParm = false; 14092 for (ParmVarDecl *Param : Parameters) { 14093 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14094 // function declarator that is part of a function definition of 14095 // that function shall not have incomplete type. 14096 // 14097 // This is also C++ [dcl.fct]p6. 14098 if (!Param->isInvalidDecl() && 14099 RequireCompleteType(Param->getLocation(), Param->getType(), 14100 diag::err_typecheck_decl_incomplete_type)) { 14101 Param->setInvalidDecl(); 14102 HasInvalidParm = true; 14103 } 14104 14105 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14106 // declaration of each parameter shall include an identifier. 14107 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14108 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14109 // Diagnose this as an extension in C17 and earlier. 14110 if (!getLangOpts().C2x) 14111 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14112 } 14113 14114 // C99 6.7.5.3p12: 14115 // If the function declarator is not part of a definition of that 14116 // function, parameters may have incomplete type and may use the [*] 14117 // notation in their sequences of declarator specifiers to specify 14118 // variable length array types. 14119 QualType PType = Param->getOriginalType(); 14120 // FIXME: This diagnostic should point the '[*]' if source-location 14121 // information is added for it. 14122 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14123 14124 // If the parameter is a c++ class type and it has to be destructed in the 14125 // callee function, declare the destructor so that it can be called by the 14126 // callee function. Do not perform any direct access check on the dtor here. 14127 if (!Param->isInvalidDecl()) { 14128 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14129 if (!ClassDecl->isInvalidDecl() && 14130 !ClassDecl->hasIrrelevantDestructor() && 14131 !ClassDecl->isDependentContext() && 14132 ClassDecl->isParamDestroyedInCallee()) { 14133 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14134 MarkFunctionReferenced(Param->getLocation(), Destructor); 14135 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14136 } 14137 } 14138 } 14139 14140 // Parameters with the pass_object_size attribute only need to be marked 14141 // constant at function definitions. Because we lack information about 14142 // whether we're on a declaration or definition when we're instantiating the 14143 // attribute, we need to check for constness here. 14144 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14145 if (!Param->getType().isConstQualified()) 14146 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14147 << Attr->getSpelling() << 1; 14148 14149 // Check for parameter names shadowing fields from the class. 14150 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14151 // The owning context for the parameter should be the function, but we 14152 // want to see if this function's declaration context is a record. 14153 DeclContext *DC = Param->getDeclContext(); 14154 if (DC && DC->isFunctionOrMethod()) { 14155 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14156 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14157 RD, /*DeclIsField*/ false); 14158 } 14159 } 14160 } 14161 14162 return HasInvalidParm; 14163 } 14164 14165 Optional<std::pair<CharUnits, CharUnits>> 14166 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14167 14168 /// Compute the alignment and offset of the base class object given the 14169 /// derived-to-base cast expression and the alignment and offset of the derived 14170 /// class object. 14171 static std::pair<CharUnits, CharUnits> 14172 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14173 CharUnits BaseAlignment, CharUnits Offset, 14174 ASTContext &Ctx) { 14175 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14176 ++PathI) { 14177 const CXXBaseSpecifier *Base = *PathI; 14178 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14179 if (Base->isVirtual()) { 14180 // The complete object may have a lower alignment than the non-virtual 14181 // alignment of the base, in which case the base may be misaligned. Choose 14182 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14183 // conservative lower bound of the complete object alignment. 14184 CharUnits NonVirtualAlignment = 14185 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14186 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14187 Offset = CharUnits::Zero(); 14188 } else { 14189 const ASTRecordLayout &RL = 14190 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14191 Offset += RL.getBaseClassOffset(BaseDecl); 14192 } 14193 DerivedType = Base->getType(); 14194 } 14195 14196 return std::make_pair(BaseAlignment, Offset); 14197 } 14198 14199 /// Compute the alignment and offset of a binary additive operator. 14200 static Optional<std::pair<CharUnits, CharUnits>> 14201 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14202 bool IsSub, ASTContext &Ctx) { 14203 QualType PointeeType = PtrE->getType()->getPointeeType(); 14204 14205 if (!PointeeType->isConstantSizeType()) 14206 return llvm::None; 14207 14208 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14209 14210 if (!P) 14211 return llvm::None; 14212 14213 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14214 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14215 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14216 if (IsSub) 14217 Offset = -Offset; 14218 return std::make_pair(P->first, P->second + Offset); 14219 } 14220 14221 // If the integer expression isn't a constant expression, compute the lower 14222 // bound of the alignment using the alignment and offset of the pointer 14223 // expression and the element size. 14224 return std::make_pair( 14225 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14226 CharUnits::Zero()); 14227 } 14228 14229 /// This helper function takes an lvalue expression and returns the alignment of 14230 /// a VarDecl and a constant offset from the VarDecl. 14231 Optional<std::pair<CharUnits, CharUnits>> 14232 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14233 E = E->IgnoreParens(); 14234 switch (E->getStmtClass()) { 14235 default: 14236 break; 14237 case Stmt::CStyleCastExprClass: 14238 case Stmt::CXXStaticCastExprClass: 14239 case Stmt::ImplicitCastExprClass: { 14240 auto *CE = cast<CastExpr>(E); 14241 const Expr *From = CE->getSubExpr(); 14242 switch (CE->getCastKind()) { 14243 default: 14244 break; 14245 case CK_NoOp: 14246 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14247 case CK_UncheckedDerivedToBase: 14248 case CK_DerivedToBase: { 14249 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14250 if (!P) 14251 break; 14252 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14253 P->second, Ctx); 14254 } 14255 } 14256 break; 14257 } 14258 case Stmt::ArraySubscriptExprClass: { 14259 auto *ASE = cast<ArraySubscriptExpr>(E); 14260 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14261 false, Ctx); 14262 } 14263 case Stmt::DeclRefExprClass: { 14264 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14265 // FIXME: If VD is captured by copy or is an escaping __block variable, 14266 // use the alignment of VD's type. 14267 if (!VD->getType()->isReferenceType()) 14268 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14269 if (VD->hasInit()) 14270 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14271 } 14272 break; 14273 } 14274 case Stmt::MemberExprClass: { 14275 auto *ME = cast<MemberExpr>(E); 14276 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14277 if (!FD || FD->getType()->isReferenceType()) 14278 break; 14279 Optional<std::pair<CharUnits, CharUnits>> P; 14280 if (ME->isArrow()) 14281 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14282 else 14283 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14284 if (!P) 14285 break; 14286 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14287 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14288 return std::make_pair(P->first, 14289 P->second + CharUnits::fromQuantity(Offset)); 14290 } 14291 case Stmt::UnaryOperatorClass: { 14292 auto *UO = cast<UnaryOperator>(E); 14293 switch (UO->getOpcode()) { 14294 default: 14295 break; 14296 case UO_Deref: 14297 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14298 } 14299 break; 14300 } 14301 case Stmt::BinaryOperatorClass: { 14302 auto *BO = cast<BinaryOperator>(E); 14303 auto Opcode = BO->getOpcode(); 14304 switch (Opcode) { 14305 default: 14306 break; 14307 case BO_Comma: 14308 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14309 } 14310 break; 14311 } 14312 } 14313 return llvm::None; 14314 } 14315 14316 /// This helper function takes a pointer expression and returns the alignment of 14317 /// a VarDecl and a constant offset from the VarDecl. 14318 Optional<std::pair<CharUnits, CharUnits>> 14319 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14320 E = E->IgnoreParens(); 14321 switch (E->getStmtClass()) { 14322 default: 14323 break; 14324 case Stmt::CStyleCastExprClass: 14325 case Stmt::CXXStaticCastExprClass: 14326 case Stmt::ImplicitCastExprClass: { 14327 auto *CE = cast<CastExpr>(E); 14328 const Expr *From = CE->getSubExpr(); 14329 switch (CE->getCastKind()) { 14330 default: 14331 break; 14332 case CK_NoOp: 14333 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14334 case CK_ArrayToPointerDecay: 14335 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14336 case CK_UncheckedDerivedToBase: 14337 case CK_DerivedToBase: { 14338 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14339 if (!P) 14340 break; 14341 return getDerivedToBaseAlignmentAndOffset( 14342 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14343 } 14344 } 14345 break; 14346 } 14347 case Stmt::CXXThisExprClass: { 14348 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14349 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14350 return std::make_pair(Alignment, CharUnits::Zero()); 14351 } 14352 case Stmt::UnaryOperatorClass: { 14353 auto *UO = cast<UnaryOperator>(E); 14354 if (UO->getOpcode() == UO_AddrOf) 14355 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14356 break; 14357 } 14358 case Stmt::BinaryOperatorClass: { 14359 auto *BO = cast<BinaryOperator>(E); 14360 auto Opcode = BO->getOpcode(); 14361 switch (Opcode) { 14362 default: 14363 break; 14364 case BO_Add: 14365 case BO_Sub: { 14366 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14367 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14368 std::swap(LHS, RHS); 14369 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14370 Ctx); 14371 } 14372 case BO_Comma: 14373 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14374 } 14375 break; 14376 } 14377 } 14378 return llvm::None; 14379 } 14380 14381 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14382 // See if we can compute the alignment of a VarDecl and an offset from it. 14383 Optional<std::pair<CharUnits, CharUnits>> P = 14384 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14385 14386 if (P) 14387 return P->first.alignmentAtOffset(P->second); 14388 14389 // If that failed, return the type's alignment. 14390 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14391 } 14392 14393 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14394 /// pointer cast increases the alignment requirements. 14395 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14396 // This is actually a lot of work to potentially be doing on every 14397 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14398 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14399 return; 14400 14401 // Ignore dependent types. 14402 if (T->isDependentType() || Op->getType()->isDependentType()) 14403 return; 14404 14405 // Require that the destination be a pointer type. 14406 const PointerType *DestPtr = T->getAs<PointerType>(); 14407 if (!DestPtr) return; 14408 14409 // If the destination has alignment 1, we're done. 14410 QualType DestPointee = DestPtr->getPointeeType(); 14411 if (DestPointee->isIncompleteType()) return; 14412 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14413 if (DestAlign.isOne()) return; 14414 14415 // Require that the source be a pointer type. 14416 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14417 if (!SrcPtr) return; 14418 QualType SrcPointee = SrcPtr->getPointeeType(); 14419 14420 // Explicitly allow casts from cv void*. We already implicitly 14421 // allowed casts to cv void*, since they have alignment 1. 14422 // Also allow casts involving incomplete types, which implicitly 14423 // includes 'void'. 14424 if (SrcPointee->isIncompleteType()) return; 14425 14426 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14427 14428 if (SrcAlign >= DestAlign) return; 14429 14430 Diag(TRange.getBegin(), diag::warn_cast_align) 14431 << Op->getType() << T 14432 << static_cast<unsigned>(SrcAlign.getQuantity()) 14433 << static_cast<unsigned>(DestAlign.getQuantity()) 14434 << TRange << Op->getSourceRange(); 14435 } 14436 14437 /// Check whether this array fits the idiom of a size-one tail padded 14438 /// array member of a struct. 14439 /// 14440 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14441 /// commonly used to emulate flexible arrays in C89 code. 14442 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14443 const NamedDecl *ND) { 14444 if (Size != 1 || !ND) return false; 14445 14446 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14447 if (!FD) return false; 14448 14449 // Don't consider sizes resulting from macro expansions or template argument 14450 // substitution to form C89 tail-padded arrays. 14451 14452 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14453 while (TInfo) { 14454 TypeLoc TL = TInfo->getTypeLoc(); 14455 // Look through typedefs. 14456 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14457 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14458 TInfo = TDL->getTypeSourceInfo(); 14459 continue; 14460 } 14461 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14462 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14463 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14464 return false; 14465 } 14466 break; 14467 } 14468 14469 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14470 if (!RD) return false; 14471 if (RD->isUnion()) return false; 14472 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14473 if (!CRD->isStandardLayout()) return false; 14474 } 14475 14476 // See if this is the last field decl in the record. 14477 const Decl *D = FD; 14478 while ((D = D->getNextDeclInContext())) 14479 if (isa<FieldDecl>(D)) 14480 return false; 14481 return true; 14482 } 14483 14484 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14485 const ArraySubscriptExpr *ASE, 14486 bool AllowOnePastEnd, bool IndexNegated) { 14487 // Already diagnosed by the constant evaluator. 14488 if (isConstantEvaluated()) 14489 return; 14490 14491 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14492 if (IndexExpr->isValueDependent()) 14493 return; 14494 14495 const Type *EffectiveType = 14496 BaseExpr->getType()->getPointeeOrArrayElementType(); 14497 BaseExpr = BaseExpr->IgnoreParenCasts(); 14498 const ConstantArrayType *ArrayTy = 14499 Context.getAsConstantArrayType(BaseExpr->getType()); 14500 14501 if (!ArrayTy) 14502 return; 14503 14504 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 14505 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 14506 return; 14507 14508 Expr::EvalResult Result; 14509 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14510 return; 14511 14512 llvm::APSInt index = Result.Val.getInt(); 14513 if (IndexNegated) 14514 index = -index; 14515 14516 const NamedDecl *ND = nullptr; 14517 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14518 ND = DRE->getDecl(); 14519 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14520 ND = ME->getMemberDecl(); 14521 14522 if (index.isUnsigned() || !index.isNegative()) { 14523 // It is possible that the type of the base expression after 14524 // IgnoreParenCasts is incomplete, even though the type of the base 14525 // expression before IgnoreParenCasts is complete (see PR39746 for an 14526 // example). In this case we have no information about whether the array 14527 // access exceeds the array bounds. However we can still diagnose an array 14528 // access which precedes the array bounds. 14529 if (BaseType->isIncompleteType()) 14530 return; 14531 14532 llvm::APInt size = ArrayTy->getSize(); 14533 if (!size.isStrictlyPositive()) 14534 return; 14535 14536 if (BaseType != EffectiveType) { 14537 // Make sure we're comparing apples to apples when comparing index to size 14538 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14539 uint64_t array_typesize = Context.getTypeSize(BaseType); 14540 // Handle ptrarith_typesize being zero, such as when casting to void* 14541 if (!ptrarith_typesize) ptrarith_typesize = 1; 14542 if (ptrarith_typesize != array_typesize) { 14543 // There's a cast to a different size type involved 14544 uint64_t ratio = array_typesize / ptrarith_typesize; 14545 // TODO: Be smarter about handling cases where array_typesize is not a 14546 // multiple of ptrarith_typesize 14547 if (ptrarith_typesize * ratio == array_typesize) 14548 size *= llvm::APInt(size.getBitWidth(), ratio); 14549 } 14550 } 14551 14552 if (size.getBitWidth() > index.getBitWidth()) 14553 index = index.zext(size.getBitWidth()); 14554 else if (size.getBitWidth() < index.getBitWidth()) 14555 size = size.zext(index.getBitWidth()); 14556 14557 // For array subscripting the index must be less than size, but for pointer 14558 // arithmetic also allow the index (offset) to be equal to size since 14559 // computing the next address after the end of the array is legal and 14560 // commonly done e.g. in C++ iterators and range-based for loops. 14561 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14562 return; 14563 14564 // Also don't warn for arrays of size 1 which are members of some 14565 // structure. These are often used to approximate flexible arrays in C89 14566 // code. 14567 if (IsTailPaddedMemberArray(*this, size, ND)) 14568 return; 14569 14570 // Suppress the warning if the subscript expression (as identified by the 14571 // ']' location) and the index expression are both from macro expansions 14572 // within a system header. 14573 if (ASE) { 14574 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14575 ASE->getRBracketLoc()); 14576 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14577 SourceLocation IndexLoc = 14578 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14579 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14580 return; 14581 } 14582 } 14583 14584 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 14585 if (ASE) 14586 DiagID = diag::warn_array_index_exceeds_bounds; 14587 14588 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14589 PDiag(DiagID) << index.toString(10, true) 14590 << size.toString(10, true) 14591 << (unsigned)size.getLimitedValue(~0U) 14592 << IndexExpr->getSourceRange()); 14593 } else { 14594 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14595 if (!ASE) { 14596 DiagID = diag::warn_ptr_arith_precedes_bounds; 14597 if (index.isNegative()) index = -index; 14598 } 14599 14600 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14601 PDiag(DiagID) << index.toString(10, true) 14602 << IndexExpr->getSourceRange()); 14603 } 14604 14605 if (!ND) { 14606 // Try harder to find a NamedDecl to point at in the note. 14607 while (const ArraySubscriptExpr *ASE = 14608 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14609 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14610 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14611 ND = DRE->getDecl(); 14612 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14613 ND = ME->getMemberDecl(); 14614 } 14615 14616 if (ND) 14617 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14618 PDiag(diag::note_array_declared_here) << ND); 14619 } 14620 14621 void Sema::CheckArrayAccess(const Expr *expr) { 14622 int AllowOnePastEnd = 0; 14623 while (expr) { 14624 expr = expr->IgnoreParenImpCasts(); 14625 switch (expr->getStmtClass()) { 14626 case Stmt::ArraySubscriptExprClass: { 14627 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14628 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14629 AllowOnePastEnd > 0); 14630 expr = ASE->getBase(); 14631 break; 14632 } 14633 case Stmt::MemberExprClass: { 14634 expr = cast<MemberExpr>(expr)->getBase(); 14635 break; 14636 } 14637 case Stmt::OMPArraySectionExprClass: { 14638 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14639 if (ASE->getLowerBound()) 14640 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14641 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14642 return; 14643 } 14644 case Stmt::UnaryOperatorClass: { 14645 // Only unwrap the * and & unary operators 14646 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14647 expr = UO->getSubExpr(); 14648 switch (UO->getOpcode()) { 14649 case UO_AddrOf: 14650 AllowOnePastEnd++; 14651 break; 14652 case UO_Deref: 14653 AllowOnePastEnd--; 14654 break; 14655 default: 14656 return; 14657 } 14658 break; 14659 } 14660 case Stmt::ConditionalOperatorClass: { 14661 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14662 if (const Expr *lhs = cond->getLHS()) 14663 CheckArrayAccess(lhs); 14664 if (const Expr *rhs = cond->getRHS()) 14665 CheckArrayAccess(rhs); 14666 return; 14667 } 14668 case Stmt::CXXOperatorCallExprClass: { 14669 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14670 for (const auto *Arg : OCE->arguments()) 14671 CheckArrayAccess(Arg); 14672 return; 14673 } 14674 default: 14675 return; 14676 } 14677 } 14678 } 14679 14680 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14681 14682 namespace { 14683 14684 struct RetainCycleOwner { 14685 VarDecl *Variable = nullptr; 14686 SourceRange Range; 14687 SourceLocation Loc; 14688 bool Indirect = false; 14689 14690 RetainCycleOwner() = default; 14691 14692 void setLocsFrom(Expr *e) { 14693 Loc = e->getExprLoc(); 14694 Range = e->getSourceRange(); 14695 } 14696 }; 14697 14698 } // namespace 14699 14700 /// Consider whether capturing the given variable can possibly lead to 14701 /// a retain cycle. 14702 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14703 // In ARC, it's captured strongly iff the variable has __strong 14704 // lifetime. In MRR, it's captured strongly if the variable is 14705 // __block and has an appropriate type. 14706 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14707 return false; 14708 14709 owner.Variable = var; 14710 if (ref) 14711 owner.setLocsFrom(ref); 14712 return true; 14713 } 14714 14715 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14716 while (true) { 14717 e = e->IgnoreParens(); 14718 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14719 switch (cast->getCastKind()) { 14720 case CK_BitCast: 14721 case CK_LValueBitCast: 14722 case CK_LValueToRValue: 14723 case CK_ARCReclaimReturnedObject: 14724 e = cast->getSubExpr(); 14725 continue; 14726 14727 default: 14728 return false; 14729 } 14730 } 14731 14732 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14733 ObjCIvarDecl *ivar = ref->getDecl(); 14734 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14735 return false; 14736 14737 // Try to find a retain cycle in the base. 14738 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14739 return false; 14740 14741 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14742 owner.Indirect = true; 14743 return true; 14744 } 14745 14746 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14747 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14748 if (!var) return false; 14749 return considerVariable(var, ref, owner); 14750 } 14751 14752 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14753 if (member->isArrow()) return false; 14754 14755 // Don't count this as an indirect ownership. 14756 e = member->getBase(); 14757 continue; 14758 } 14759 14760 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14761 // Only pay attention to pseudo-objects on property references. 14762 ObjCPropertyRefExpr *pre 14763 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14764 ->IgnoreParens()); 14765 if (!pre) return false; 14766 if (pre->isImplicitProperty()) return false; 14767 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14768 if (!property->isRetaining() && 14769 !(property->getPropertyIvarDecl() && 14770 property->getPropertyIvarDecl()->getType() 14771 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14772 return false; 14773 14774 owner.Indirect = true; 14775 if (pre->isSuperReceiver()) { 14776 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14777 if (!owner.Variable) 14778 return false; 14779 owner.Loc = pre->getLocation(); 14780 owner.Range = pre->getSourceRange(); 14781 return true; 14782 } 14783 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14784 ->getSourceExpr()); 14785 continue; 14786 } 14787 14788 // Array ivars? 14789 14790 return false; 14791 } 14792 } 14793 14794 namespace { 14795 14796 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14797 ASTContext &Context; 14798 VarDecl *Variable; 14799 Expr *Capturer = nullptr; 14800 bool VarWillBeReased = false; 14801 14802 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14803 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14804 Context(Context), Variable(variable) {} 14805 14806 void VisitDeclRefExpr(DeclRefExpr *ref) { 14807 if (ref->getDecl() == Variable && !Capturer) 14808 Capturer = ref; 14809 } 14810 14811 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14812 if (Capturer) return; 14813 Visit(ref->getBase()); 14814 if (Capturer && ref->isFreeIvar()) 14815 Capturer = ref; 14816 } 14817 14818 void VisitBlockExpr(BlockExpr *block) { 14819 // Look inside nested blocks 14820 if (block->getBlockDecl()->capturesVariable(Variable)) 14821 Visit(block->getBlockDecl()->getBody()); 14822 } 14823 14824 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14825 if (Capturer) return; 14826 if (OVE->getSourceExpr()) 14827 Visit(OVE->getSourceExpr()); 14828 } 14829 14830 void VisitBinaryOperator(BinaryOperator *BinOp) { 14831 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14832 return; 14833 Expr *LHS = BinOp->getLHS(); 14834 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14835 if (DRE->getDecl() != Variable) 14836 return; 14837 if (Expr *RHS = BinOp->getRHS()) { 14838 RHS = RHS->IgnoreParenCasts(); 14839 Optional<llvm::APSInt> Value; 14840 VarWillBeReased = 14841 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14842 *Value == 0); 14843 } 14844 } 14845 } 14846 }; 14847 14848 } // namespace 14849 14850 /// Check whether the given argument is a block which captures a 14851 /// variable. 14852 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14853 assert(owner.Variable && owner.Loc.isValid()); 14854 14855 e = e->IgnoreParenCasts(); 14856 14857 // Look through [^{...} copy] and Block_copy(^{...}). 14858 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14859 Selector Cmd = ME->getSelector(); 14860 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14861 e = ME->getInstanceReceiver(); 14862 if (!e) 14863 return nullptr; 14864 e = e->IgnoreParenCasts(); 14865 } 14866 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14867 if (CE->getNumArgs() == 1) { 14868 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14869 if (Fn) { 14870 const IdentifierInfo *FnI = Fn->getIdentifier(); 14871 if (FnI && FnI->isStr("_Block_copy")) { 14872 e = CE->getArg(0)->IgnoreParenCasts(); 14873 } 14874 } 14875 } 14876 } 14877 14878 BlockExpr *block = dyn_cast<BlockExpr>(e); 14879 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14880 return nullptr; 14881 14882 FindCaptureVisitor visitor(S.Context, owner.Variable); 14883 visitor.Visit(block->getBlockDecl()->getBody()); 14884 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14885 } 14886 14887 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14888 RetainCycleOwner &owner) { 14889 assert(capturer); 14890 assert(owner.Variable && owner.Loc.isValid()); 14891 14892 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14893 << owner.Variable << capturer->getSourceRange(); 14894 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14895 << owner.Indirect << owner.Range; 14896 } 14897 14898 /// Check for a keyword selector that starts with the word 'add' or 14899 /// 'set'. 14900 static bool isSetterLikeSelector(Selector sel) { 14901 if (sel.isUnarySelector()) return false; 14902 14903 StringRef str = sel.getNameForSlot(0); 14904 while (!str.empty() && str.front() == '_') str = str.substr(1); 14905 if (str.startswith("set")) 14906 str = str.substr(3); 14907 else if (str.startswith("add")) { 14908 // Specially allow 'addOperationWithBlock:'. 14909 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14910 return false; 14911 str = str.substr(3); 14912 } 14913 else 14914 return false; 14915 14916 if (str.empty()) return true; 14917 return !isLowercase(str.front()); 14918 } 14919 14920 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14921 ObjCMessageExpr *Message) { 14922 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14923 Message->getReceiverInterface(), 14924 NSAPI::ClassId_NSMutableArray); 14925 if (!IsMutableArray) { 14926 return None; 14927 } 14928 14929 Selector Sel = Message->getSelector(); 14930 14931 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14932 S.NSAPIObj->getNSArrayMethodKind(Sel); 14933 if (!MKOpt) { 14934 return None; 14935 } 14936 14937 NSAPI::NSArrayMethodKind MK = *MKOpt; 14938 14939 switch (MK) { 14940 case NSAPI::NSMutableArr_addObject: 14941 case NSAPI::NSMutableArr_insertObjectAtIndex: 14942 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14943 return 0; 14944 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14945 return 1; 14946 14947 default: 14948 return None; 14949 } 14950 14951 return None; 14952 } 14953 14954 static 14955 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14956 ObjCMessageExpr *Message) { 14957 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14958 Message->getReceiverInterface(), 14959 NSAPI::ClassId_NSMutableDictionary); 14960 if (!IsMutableDictionary) { 14961 return None; 14962 } 14963 14964 Selector Sel = Message->getSelector(); 14965 14966 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14967 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14968 if (!MKOpt) { 14969 return None; 14970 } 14971 14972 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14973 14974 switch (MK) { 14975 case NSAPI::NSMutableDict_setObjectForKey: 14976 case NSAPI::NSMutableDict_setValueForKey: 14977 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14978 return 0; 14979 14980 default: 14981 return None; 14982 } 14983 14984 return None; 14985 } 14986 14987 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14988 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14989 Message->getReceiverInterface(), 14990 NSAPI::ClassId_NSMutableSet); 14991 14992 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14993 Message->getReceiverInterface(), 14994 NSAPI::ClassId_NSMutableOrderedSet); 14995 if (!IsMutableSet && !IsMutableOrderedSet) { 14996 return None; 14997 } 14998 14999 Selector Sel = Message->getSelector(); 15000 15001 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15002 if (!MKOpt) { 15003 return None; 15004 } 15005 15006 NSAPI::NSSetMethodKind MK = *MKOpt; 15007 15008 switch (MK) { 15009 case NSAPI::NSMutableSet_addObject: 15010 case NSAPI::NSOrderedSet_setObjectAtIndex: 15011 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15012 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15013 return 0; 15014 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15015 return 1; 15016 } 15017 15018 return None; 15019 } 15020 15021 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15022 if (!Message->isInstanceMessage()) { 15023 return; 15024 } 15025 15026 Optional<int> ArgOpt; 15027 15028 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15029 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15030 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15031 return; 15032 } 15033 15034 int ArgIndex = *ArgOpt; 15035 15036 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15037 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15038 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15039 } 15040 15041 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15042 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15043 if (ArgRE->isObjCSelfExpr()) { 15044 Diag(Message->getSourceRange().getBegin(), 15045 diag::warn_objc_circular_container) 15046 << ArgRE->getDecl() << StringRef("'super'"); 15047 } 15048 } 15049 } else { 15050 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15051 15052 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15053 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15054 } 15055 15056 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15057 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15058 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15059 ValueDecl *Decl = ReceiverRE->getDecl(); 15060 Diag(Message->getSourceRange().getBegin(), 15061 diag::warn_objc_circular_container) 15062 << Decl << Decl; 15063 if (!ArgRE->isObjCSelfExpr()) { 15064 Diag(Decl->getLocation(), 15065 diag::note_objc_circular_container_declared_here) 15066 << Decl; 15067 } 15068 } 15069 } 15070 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15071 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15072 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15073 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15074 Diag(Message->getSourceRange().getBegin(), 15075 diag::warn_objc_circular_container) 15076 << Decl << Decl; 15077 Diag(Decl->getLocation(), 15078 diag::note_objc_circular_container_declared_here) 15079 << Decl; 15080 } 15081 } 15082 } 15083 } 15084 } 15085 15086 /// Check a message send to see if it's likely to cause a retain cycle. 15087 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15088 // Only check instance methods whose selector looks like a setter. 15089 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15090 return; 15091 15092 // Try to find a variable that the receiver is strongly owned by. 15093 RetainCycleOwner owner; 15094 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15095 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15096 return; 15097 } else { 15098 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15099 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15100 owner.Loc = msg->getSuperLoc(); 15101 owner.Range = msg->getSuperLoc(); 15102 } 15103 15104 // Check whether the receiver is captured by any of the arguments. 15105 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15106 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15107 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15108 // noescape blocks should not be retained by the method. 15109 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15110 continue; 15111 return diagnoseRetainCycle(*this, capturer, owner); 15112 } 15113 } 15114 } 15115 15116 /// Check a property assign to see if it's likely to cause a retain cycle. 15117 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15118 RetainCycleOwner owner; 15119 if (!findRetainCycleOwner(*this, receiver, owner)) 15120 return; 15121 15122 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15123 diagnoseRetainCycle(*this, capturer, owner); 15124 } 15125 15126 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15127 RetainCycleOwner Owner; 15128 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15129 return; 15130 15131 // Because we don't have an expression for the variable, we have to set the 15132 // location explicitly here. 15133 Owner.Loc = Var->getLocation(); 15134 Owner.Range = Var->getSourceRange(); 15135 15136 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15137 diagnoseRetainCycle(*this, Capturer, Owner); 15138 } 15139 15140 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15141 Expr *RHS, bool isProperty) { 15142 // Check if RHS is an Objective-C object literal, which also can get 15143 // immediately zapped in a weak reference. Note that we explicitly 15144 // allow ObjCStringLiterals, since those are designed to never really die. 15145 RHS = RHS->IgnoreParenImpCasts(); 15146 15147 // This enum needs to match with the 'select' in 15148 // warn_objc_arc_literal_assign (off-by-1). 15149 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15150 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15151 return false; 15152 15153 S.Diag(Loc, diag::warn_arc_literal_assign) 15154 << (unsigned) Kind 15155 << (isProperty ? 0 : 1) 15156 << RHS->getSourceRange(); 15157 15158 return true; 15159 } 15160 15161 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15162 Qualifiers::ObjCLifetime LT, 15163 Expr *RHS, bool isProperty) { 15164 // Strip off any implicit cast added to get to the one ARC-specific. 15165 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15166 if (cast->getCastKind() == CK_ARCConsumeObject) { 15167 S.Diag(Loc, diag::warn_arc_retained_assign) 15168 << (LT == Qualifiers::OCL_ExplicitNone) 15169 << (isProperty ? 0 : 1) 15170 << RHS->getSourceRange(); 15171 return true; 15172 } 15173 RHS = cast->getSubExpr(); 15174 } 15175 15176 if (LT == Qualifiers::OCL_Weak && 15177 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15178 return true; 15179 15180 return false; 15181 } 15182 15183 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15184 QualType LHS, Expr *RHS) { 15185 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15186 15187 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15188 return false; 15189 15190 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15191 return true; 15192 15193 return false; 15194 } 15195 15196 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15197 Expr *LHS, Expr *RHS) { 15198 QualType LHSType; 15199 // PropertyRef on LHS type need be directly obtained from 15200 // its declaration as it has a PseudoType. 15201 ObjCPropertyRefExpr *PRE 15202 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15203 if (PRE && !PRE->isImplicitProperty()) { 15204 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15205 if (PD) 15206 LHSType = PD->getType(); 15207 } 15208 15209 if (LHSType.isNull()) 15210 LHSType = LHS->getType(); 15211 15212 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15213 15214 if (LT == Qualifiers::OCL_Weak) { 15215 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15216 getCurFunction()->markSafeWeakUse(LHS); 15217 } 15218 15219 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15220 return; 15221 15222 // FIXME. Check for other life times. 15223 if (LT != Qualifiers::OCL_None) 15224 return; 15225 15226 if (PRE) { 15227 if (PRE->isImplicitProperty()) 15228 return; 15229 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15230 if (!PD) 15231 return; 15232 15233 unsigned Attributes = PD->getPropertyAttributes(); 15234 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15235 // when 'assign' attribute was not explicitly specified 15236 // by user, ignore it and rely on property type itself 15237 // for lifetime info. 15238 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15239 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15240 LHSType->isObjCRetainableType()) 15241 return; 15242 15243 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15244 if (cast->getCastKind() == CK_ARCConsumeObject) { 15245 Diag(Loc, diag::warn_arc_retained_property_assign) 15246 << RHS->getSourceRange(); 15247 return; 15248 } 15249 RHS = cast->getSubExpr(); 15250 } 15251 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15252 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15253 return; 15254 } 15255 } 15256 } 15257 15258 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15259 15260 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15261 SourceLocation StmtLoc, 15262 const NullStmt *Body) { 15263 // Do not warn if the body is a macro that expands to nothing, e.g: 15264 // 15265 // #define CALL(x) 15266 // if (condition) 15267 // CALL(0); 15268 if (Body->hasLeadingEmptyMacro()) 15269 return false; 15270 15271 // Get line numbers of statement and body. 15272 bool StmtLineInvalid; 15273 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15274 &StmtLineInvalid); 15275 if (StmtLineInvalid) 15276 return false; 15277 15278 bool BodyLineInvalid; 15279 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15280 &BodyLineInvalid); 15281 if (BodyLineInvalid) 15282 return false; 15283 15284 // Warn if null statement and body are on the same line. 15285 if (StmtLine != BodyLine) 15286 return false; 15287 15288 return true; 15289 } 15290 15291 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15292 const Stmt *Body, 15293 unsigned DiagID) { 15294 // Since this is a syntactic check, don't emit diagnostic for template 15295 // instantiations, this just adds noise. 15296 if (CurrentInstantiationScope) 15297 return; 15298 15299 // The body should be a null statement. 15300 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15301 if (!NBody) 15302 return; 15303 15304 // Do the usual checks. 15305 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15306 return; 15307 15308 Diag(NBody->getSemiLoc(), DiagID); 15309 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15310 } 15311 15312 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15313 const Stmt *PossibleBody) { 15314 assert(!CurrentInstantiationScope); // Ensured by caller 15315 15316 SourceLocation StmtLoc; 15317 const Stmt *Body; 15318 unsigned DiagID; 15319 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15320 StmtLoc = FS->getRParenLoc(); 15321 Body = FS->getBody(); 15322 DiagID = diag::warn_empty_for_body; 15323 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15324 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15325 Body = WS->getBody(); 15326 DiagID = diag::warn_empty_while_body; 15327 } else 15328 return; // Neither `for' nor `while'. 15329 15330 // The body should be a null statement. 15331 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15332 if (!NBody) 15333 return; 15334 15335 // Skip expensive checks if diagnostic is disabled. 15336 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15337 return; 15338 15339 // Do the usual checks. 15340 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15341 return; 15342 15343 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15344 // noise level low, emit diagnostics only if for/while is followed by a 15345 // CompoundStmt, e.g.: 15346 // for (int i = 0; i < n; i++); 15347 // { 15348 // a(i); 15349 // } 15350 // or if for/while is followed by a statement with more indentation 15351 // than for/while itself: 15352 // for (int i = 0; i < n; i++); 15353 // a(i); 15354 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15355 if (!ProbableTypo) { 15356 bool BodyColInvalid; 15357 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15358 PossibleBody->getBeginLoc(), &BodyColInvalid); 15359 if (BodyColInvalid) 15360 return; 15361 15362 bool StmtColInvalid; 15363 unsigned StmtCol = 15364 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15365 if (StmtColInvalid) 15366 return; 15367 15368 if (BodyCol > StmtCol) 15369 ProbableTypo = true; 15370 } 15371 15372 if (ProbableTypo) { 15373 Diag(NBody->getSemiLoc(), DiagID); 15374 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15375 } 15376 } 15377 15378 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15379 15380 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15381 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15382 SourceLocation OpLoc) { 15383 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15384 return; 15385 15386 if (inTemplateInstantiation()) 15387 return; 15388 15389 // Strip parens and casts away. 15390 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15391 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15392 15393 // Check for a call expression 15394 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15395 if (!CE || CE->getNumArgs() != 1) 15396 return; 15397 15398 // Check for a call to std::move 15399 if (!CE->isCallToStdMove()) 15400 return; 15401 15402 // Get argument from std::move 15403 RHSExpr = CE->getArg(0); 15404 15405 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15406 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15407 15408 // Two DeclRefExpr's, check that the decls are the same. 15409 if (LHSDeclRef && RHSDeclRef) { 15410 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15411 return; 15412 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15413 RHSDeclRef->getDecl()->getCanonicalDecl()) 15414 return; 15415 15416 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15417 << LHSExpr->getSourceRange() 15418 << RHSExpr->getSourceRange(); 15419 return; 15420 } 15421 15422 // Member variables require a different approach to check for self moves. 15423 // MemberExpr's are the same if every nested MemberExpr refers to the same 15424 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15425 // the base Expr's are CXXThisExpr's. 15426 const Expr *LHSBase = LHSExpr; 15427 const Expr *RHSBase = RHSExpr; 15428 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15429 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15430 if (!LHSME || !RHSME) 15431 return; 15432 15433 while (LHSME && RHSME) { 15434 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15435 RHSME->getMemberDecl()->getCanonicalDecl()) 15436 return; 15437 15438 LHSBase = LHSME->getBase(); 15439 RHSBase = RHSME->getBase(); 15440 LHSME = dyn_cast<MemberExpr>(LHSBase); 15441 RHSME = dyn_cast<MemberExpr>(RHSBase); 15442 } 15443 15444 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15445 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15446 if (LHSDeclRef && RHSDeclRef) { 15447 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15448 return; 15449 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15450 RHSDeclRef->getDecl()->getCanonicalDecl()) 15451 return; 15452 15453 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15454 << LHSExpr->getSourceRange() 15455 << RHSExpr->getSourceRange(); 15456 return; 15457 } 15458 15459 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15460 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15461 << LHSExpr->getSourceRange() 15462 << RHSExpr->getSourceRange(); 15463 } 15464 15465 //===--- Layout compatibility ----------------------------------------------// 15466 15467 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15468 15469 /// Check if two enumeration types are layout-compatible. 15470 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15471 // C++11 [dcl.enum] p8: 15472 // Two enumeration types are layout-compatible if they have the same 15473 // underlying type. 15474 return ED1->isComplete() && ED2->isComplete() && 15475 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15476 } 15477 15478 /// Check if two fields are layout-compatible. 15479 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15480 FieldDecl *Field2) { 15481 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15482 return false; 15483 15484 if (Field1->isBitField() != Field2->isBitField()) 15485 return false; 15486 15487 if (Field1->isBitField()) { 15488 // Make sure that the bit-fields are the same length. 15489 unsigned Bits1 = Field1->getBitWidthValue(C); 15490 unsigned Bits2 = Field2->getBitWidthValue(C); 15491 15492 if (Bits1 != Bits2) 15493 return false; 15494 } 15495 15496 return true; 15497 } 15498 15499 /// Check if two standard-layout structs are layout-compatible. 15500 /// (C++11 [class.mem] p17) 15501 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15502 RecordDecl *RD2) { 15503 // If both records are C++ classes, check that base classes match. 15504 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15505 // If one of records is a CXXRecordDecl we are in C++ mode, 15506 // thus the other one is a CXXRecordDecl, too. 15507 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15508 // Check number of base classes. 15509 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15510 return false; 15511 15512 // Check the base classes. 15513 for (CXXRecordDecl::base_class_const_iterator 15514 Base1 = D1CXX->bases_begin(), 15515 BaseEnd1 = D1CXX->bases_end(), 15516 Base2 = D2CXX->bases_begin(); 15517 Base1 != BaseEnd1; 15518 ++Base1, ++Base2) { 15519 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15520 return false; 15521 } 15522 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15523 // If only RD2 is a C++ class, it should have zero base classes. 15524 if (D2CXX->getNumBases() > 0) 15525 return false; 15526 } 15527 15528 // Check the fields. 15529 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15530 Field2End = RD2->field_end(), 15531 Field1 = RD1->field_begin(), 15532 Field1End = RD1->field_end(); 15533 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15534 if (!isLayoutCompatible(C, *Field1, *Field2)) 15535 return false; 15536 } 15537 if (Field1 != Field1End || Field2 != Field2End) 15538 return false; 15539 15540 return true; 15541 } 15542 15543 /// Check if two standard-layout unions are layout-compatible. 15544 /// (C++11 [class.mem] p18) 15545 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15546 RecordDecl *RD2) { 15547 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15548 for (auto *Field2 : RD2->fields()) 15549 UnmatchedFields.insert(Field2); 15550 15551 for (auto *Field1 : RD1->fields()) { 15552 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15553 I = UnmatchedFields.begin(), 15554 E = UnmatchedFields.end(); 15555 15556 for ( ; I != E; ++I) { 15557 if (isLayoutCompatible(C, Field1, *I)) { 15558 bool Result = UnmatchedFields.erase(*I); 15559 (void) Result; 15560 assert(Result); 15561 break; 15562 } 15563 } 15564 if (I == E) 15565 return false; 15566 } 15567 15568 return UnmatchedFields.empty(); 15569 } 15570 15571 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15572 RecordDecl *RD2) { 15573 if (RD1->isUnion() != RD2->isUnion()) 15574 return false; 15575 15576 if (RD1->isUnion()) 15577 return isLayoutCompatibleUnion(C, RD1, RD2); 15578 else 15579 return isLayoutCompatibleStruct(C, RD1, RD2); 15580 } 15581 15582 /// Check if two types are layout-compatible in C++11 sense. 15583 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15584 if (T1.isNull() || T2.isNull()) 15585 return false; 15586 15587 // C++11 [basic.types] p11: 15588 // If two types T1 and T2 are the same type, then T1 and T2 are 15589 // layout-compatible types. 15590 if (C.hasSameType(T1, T2)) 15591 return true; 15592 15593 T1 = T1.getCanonicalType().getUnqualifiedType(); 15594 T2 = T2.getCanonicalType().getUnqualifiedType(); 15595 15596 const Type::TypeClass TC1 = T1->getTypeClass(); 15597 const Type::TypeClass TC2 = T2->getTypeClass(); 15598 15599 if (TC1 != TC2) 15600 return false; 15601 15602 if (TC1 == Type::Enum) { 15603 return isLayoutCompatible(C, 15604 cast<EnumType>(T1)->getDecl(), 15605 cast<EnumType>(T2)->getDecl()); 15606 } else if (TC1 == Type::Record) { 15607 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15608 return false; 15609 15610 return isLayoutCompatible(C, 15611 cast<RecordType>(T1)->getDecl(), 15612 cast<RecordType>(T2)->getDecl()); 15613 } 15614 15615 return false; 15616 } 15617 15618 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15619 15620 /// Given a type tag expression find the type tag itself. 15621 /// 15622 /// \param TypeExpr Type tag expression, as it appears in user's code. 15623 /// 15624 /// \param VD Declaration of an identifier that appears in a type tag. 15625 /// 15626 /// \param MagicValue Type tag magic value. 15627 /// 15628 /// \param isConstantEvaluated wether the evalaution should be performed in 15629 15630 /// constant context. 15631 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15632 const ValueDecl **VD, uint64_t *MagicValue, 15633 bool isConstantEvaluated) { 15634 while(true) { 15635 if (!TypeExpr) 15636 return false; 15637 15638 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15639 15640 switch (TypeExpr->getStmtClass()) { 15641 case Stmt::UnaryOperatorClass: { 15642 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15643 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15644 TypeExpr = UO->getSubExpr(); 15645 continue; 15646 } 15647 return false; 15648 } 15649 15650 case Stmt::DeclRefExprClass: { 15651 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15652 *VD = DRE->getDecl(); 15653 return true; 15654 } 15655 15656 case Stmt::IntegerLiteralClass: { 15657 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15658 llvm::APInt MagicValueAPInt = IL->getValue(); 15659 if (MagicValueAPInt.getActiveBits() <= 64) { 15660 *MagicValue = MagicValueAPInt.getZExtValue(); 15661 return true; 15662 } else 15663 return false; 15664 } 15665 15666 case Stmt::BinaryConditionalOperatorClass: 15667 case Stmt::ConditionalOperatorClass: { 15668 const AbstractConditionalOperator *ACO = 15669 cast<AbstractConditionalOperator>(TypeExpr); 15670 bool Result; 15671 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15672 isConstantEvaluated)) { 15673 if (Result) 15674 TypeExpr = ACO->getTrueExpr(); 15675 else 15676 TypeExpr = ACO->getFalseExpr(); 15677 continue; 15678 } 15679 return false; 15680 } 15681 15682 case Stmt::BinaryOperatorClass: { 15683 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15684 if (BO->getOpcode() == BO_Comma) { 15685 TypeExpr = BO->getRHS(); 15686 continue; 15687 } 15688 return false; 15689 } 15690 15691 default: 15692 return false; 15693 } 15694 } 15695 } 15696 15697 /// Retrieve the C type corresponding to type tag TypeExpr. 15698 /// 15699 /// \param TypeExpr Expression that specifies a type tag. 15700 /// 15701 /// \param MagicValues Registered magic values. 15702 /// 15703 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15704 /// kind. 15705 /// 15706 /// \param TypeInfo Information about the corresponding C type. 15707 /// 15708 /// \param isConstantEvaluated wether the evalaution should be performed in 15709 /// constant context. 15710 /// 15711 /// \returns true if the corresponding C type was found. 15712 static bool GetMatchingCType( 15713 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15714 const ASTContext &Ctx, 15715 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15716 *MagicValues, 15717 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15718 bool isConstantEvaluated) { 15719 FoundWrongKind = false; 15720 15721 // Variable declaration that has type_tag_for_datatype attribute. 15722 const ValueDecl *VD = nullptr; 15723 15724 uint64_t MagicValue; 15725 15726 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15727 return false; 15728 15729 if (VD) { 15730 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15731 if (I->getArgumentKind() != ArgumentKind) { 15732 FoundWrongKind = true; 15733 return false; 15734 } 15735 TypeInfo.Type = I->getMatchingCType(); 15736 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15737 TypeInfo.MustBeNull = I->getMustBeNull(); 15738 return true; 15739 } 15740 return false; 15741 } 15742 15743 if (!MagicValues) 15744 return false; 15745 15746 llvm::DenseMap<Sema::TypeTagMagicValue, 15747 Sema::TypeTagData>::const_iterator I = 15748 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15749 if (I == MagicValues->end()) 15750 return false; 15751 15752 TypeInfo = I->second; 15753 return true; 15754 } 15755 15756 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15757 uint64_t MagicValue, QualType Type, 15758 bool LayoutCompatible, 15759 bool MustBeNull) { 15760 if (!TypeTagForDatatypeMagicValues) 15761 TypeTagForDatatypeMagicValues.reset( 15762 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15763 15764 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15765 (*TypeTagForDatatypeMagicValues)[Magic] = 15766 TypeTagData(Type, LayoutCompatible, MustBeNull); 15767 } 15768 15769 static bool IsSameCharType(QualType T1, QualType T2) { 15770 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15771 if (!BT1) 15772 return false; 15773 15774 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15775 if (!BT2) 15776 return false; 15777 15778 BuiltinType::Kind T1Kind = BT1->getKind(); 15779 BuiltinType::Kind T2Kind = BT2->getKind(); 15780 15781 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15782 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15783 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15784 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15785 } 15786 15787 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15788 const ArrayRef<const Expr *> ExprArgs, 15789 SourceLocation CallSiteLoc) { 15790 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15791 bool IsPointerAttr = Attr->getIsPointer(); 15792 15793 // Retrieve the argument representing the 'type_tag'. 15794 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15795 if (TypeTagIdxAST >= ExprArgs.size()) { 15796 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15797 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15798 return; 15799 } 15800 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15801 bool FoundWrongKind; 15802 TypeTagData TypeInfo; 15803 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15804 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15805 TypeInfo, isConstantEvaluated())) { 15806 if (FoundWrongKind) 15807 Diag(TypeTagExpr->getExprLoc(), 15808 diag::warn_type_tag_for_datatype_wrong_kind) 15809 << TypeTagExpr->getSourceRange(); 15810 return; 15811 } 15812 15813 // Retrieve the argument representing the 'arg_idx'. 15814 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15815 if (ArgumentIdxAST >= ExprArgs.size()) { 15816 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15817 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15818 return; 15819 } 15820 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15821 if (IsPointerAttr) { 15822 // Skip implicit cast of pointer to `void *' (as a function argument). 15823 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15824 if (ICE->getType()->isVoidPointerType() && 15825 ICE->getCastKind() == CK_BitCast) 15826 ArgumentExpr = ICE->getSubExpr(); 15827 } 15828 QualType ArgumentType = ArgumentExpr->getType(); 15829 15830 // Passing a `void*' pointer shouldn't trigger a warning. 15831 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15832 return; 15833 15834 if (TypeInfo.MustBeNull) { 15835 // Type tag with matching void type requires a null pointer. 15836 if (!ArgumentExpr->isNullPointerConstant(Context, 15837 Expr::NPC_ValueDependentIsNotNull)) { 15838 Diag(ArgumentExpr->getExprLoc(), 15839 diag::warn_type_safety_null_pointer_required) 15840 << ArgumentKind->getName() 15841 << ArgumentExpr->getSourceRange() 15842 << TypeTagExpr->getSourceRange(); 15843 } 15844 return; 15845 } 15846 15847 QualType RequiredType = TypeInfo.Type; 15848 if (IsPointerAttr) 15849 RequiredType = Context.getPointerType(RequiredType); 15850 15851 bool mismatch = false; 15852 if (!TypeInfo.LayoutCompatible) { 15853 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15854 15855 // C++11 [basic.fundamental] p1: 15856 // Plain char, signed char, and unsigned char are three distinct types. 15857 // 15858 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15859 // char' depending on the current char signedness mode. 15860 if (mismatch) 15861 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15862 RequiredType->getPointeeType())) || 15863 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15864 mismatch = false; 15865 } else 15866 if (IsPointerAttr) 15867 mismatch = !isLayoutCompatible(Context, 15868 ArgumentType->getPointeeType(), 15869 RequiredType->getPointeeType()); 15870 else 15871 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15872 15873 if (mismatch) 15874 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15875 << ArgumentType << ArgumentKind 15876 << TypeInfo.LayoutCompatible << RequiredType 15877 << ArgumentExpr->getSourceRange() 15878 << TypeTagExpr->getSourceRange(); 15879 } 15880 15881 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15882 CharUnits Alignment) { 15883 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15884 } 15885 15886 void Sema::DiagnoseMisalignedMembers() { 15887 for (MisalignedMember &m : MisalignedMembers) { 15888 const NamedDecl *ND = m.RD; 15889 if (ND->getName().empty()) { 15890 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15891 ND = TD; 15892 } 15893 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15894 << m.MD << ND << m.E->getSourceRange(); 15895 } 15896 MisalignedMembers.clear(); 15897 } 15898 15899 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15900 E = E->IgnoreParens(); 15901 if (!T->isPointerType() && !T->isIntegerType()) 15902 return; 15903 if (isa<UnaryOperator>(E) && 15904 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15905 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15906 if (isa<MemberExpr>(Op)) { 15907 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15908 if (MA != MisalignedMembers.end() && 15909 (T->isIntegerType() || 15910 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15911 Context.getTypeAlignInChars( 15912 T->getPointeeType()) <= MA->Alignment)))) 15913 MisalignedMembers.erase(MA); 15914 } 15915 } 15916 } 15917 15918 void Sema::RefersToMemberWithReducedAlignment( 15919 Expr *E, 15920 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15921 Action) { 15922 const auto *ME = dyn_cast<MemberExpr>(E); 15923 if (!ME) 15924 return; 15925 15926 // No need to check expressions with an __unaligned-qualified type. 15927 if (E->getType().getQualifiers().hasUnaligned()) 15928 return; 15929 15930 // For a chain of MemberExpr like "a.b.c.d" this list 15931 // will keep FieldDecl's like [d, c, b]. 15932 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15933 const MemberExpr *TopME = nullptr; 15934 bool AnyIsPacked = false; 15935 do { 15936 QualType BaseType = ME->getBase()->getType(); 15937 if (BaseType->isDependentType()) 15938 return; 15939 if (ME->isArrow()) 15940 BaseType = BaseType->getPointeeType(); 15941 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15942 if (RD->isInvalidDecl()) 15943 return; 15944 15945 ValueDecl *MD = ME->getMemberDecl(); 15946 auto *FD = dyn_cast<FieldDecl>(MD); 15947 // We do not care about non-data members. 15948 if (!FD || FD->isInvalidDecl()) 15949 return; 15950 15951 AnyIsPacked = 15952 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15953 ReverseMemberChain.push_back(FD); 15954 15955 TopME = ME; 15956 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15957 } while (ME); 15958 assert(TopME && "We did not compute a topmost MemberExpr!"); 15959 15960 // Not the scope of this diagnostic. 15961 if (!AnyIsPacked) 15962 return; 15963 15964 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15965 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15966 // TODO: The innermost base of the member expression may be too complicated. 15967 // For now, just disregard these cases. This is left for future 15968 // improvement. 15969 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15970 return; 15971 15972 // Alignment expected by the whole expression. 15973 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15974 15975 // No need to do anything else with this case. 15976 if (ExpectedAlignment.isOne()) 15977 return; 15978 15979 // Synthesize offset of the whole access. 15980 CharUnits Offset; 15981 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15982 I++) { 15983 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15984 } 15985 15986 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15987 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15988 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15989 15990 // The base expression of the innermost MemberExpr may give 15991 // stronger guarantees than the class containing the member. 15992 if (DRE && !TopME->isArrow()) { 15993 const ValueDecl *VD = DRE->getDecl(); 15994 if (!VD->getType()->isReferenceType()) 15995 CompleteObjectAlignment = 15996 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15997 } 15998 15999 // Check if the synthesized offset fulfills the alignment. 16000 if (Offset % ExpectedAlignment != 0 || 16001 // It may fulfill the offset it but the effective alignment may still be 16002 // lower than the expected expression alignment. 16003 CompleteObjectAlignment < ExpectedAlignment) { 16004 // If this happens, we want to determine a sensible culprit of this. 16005 // Intuitively, watching the chain of member expressions from right to 16006 // left, we start with the required alignment (as required by the field 16007 // type) but some packed attribute in that chain has reduced the alignment. 16008 // It may happen that another packed structure increases it again. But if 16009 // we are here such increase has not been enough. So pointing the first 16010 // FieldDecl that either is packed or else its RecordDecl is, 16011 // seems reasonable. 16012 FieldDecl *FD = nullptr; 16013 CharUnits Alignment; 16014 for (FieldDecl *FDI : ReverseMemberChain) { 16015 if (FDI->hasAttr<PackedAttr>() || 16016 FDI->getParent()->hasAttr<PackedAttr>()) { 16017 FD = FDI; 16018 Alignment = std::min( 16019 Context.getTypeAlignInChars(FD->getType()), 16020 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16021 break; 16022 } 16023 } 16024 assert(FD && "We did not find a packed FieldDecl!"); 16025 Action(E, FD->getParent(), FD, Alignment); 16026 } 16027 } 16028 16029 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16030 using namespace std::placeholders; 16031 16032 RefersToMemberWithReducedAlignment( 16033 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16034 _2, _3, _4)); 16035 } 16036 16037 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16038 ExprResult CallResult) { 16039 if (checkArgCount(*this, TheCall, 1)) 16040 return ExprError(); 16041 16042 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16043 if (MatrixArg.isInvalid()) 16044 return MatrixArg; 16045 Expr *Matrix = MatrixArg.get(); 16046 16047 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16048 if (!MType) { 16049 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16050 return ExprError(); 16051 } 16052 16053 // Create returned matrix type by swapping rows and columns of the argument 16054 // matrix type. 16055 QualType ResultType = Context.getConstantMatrixType( 16056 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16057 16058 // Change the return type to the type of the returned matrix. 16059 TheCall->setType(ResultType); 16060 16061 // Update call argument to use the possibly converted matrix argument. 16062 TheCall->setArg(0, Matrix); 16063 return CallResult; 16064 } 16065 16066 // Get and verify the matrix dimensions. 16067 static llvm::Optional<unsigned> 16068 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16069 SourceLocation ErrorPos; 16070 Optional<llvm::APSInt> Value = 16071 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16072 if (!Value) { 16073 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16074 << Name; 16075 return {}; 16076 } 16077 uint64_t Dim = Value->getZExtValue(); 16078 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16079 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16080 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16081 return {}; 16082 } 16083 return Dim; 16084 } 16085 16086 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16087 ExprResult CallResult) { 16088 if (!getLangOpts().MatrixTypes) { 16089 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16090 return ExprError(); 16091 } 16092 16093 if (checkArgCount(*this, TheCall, 4)) 16094 return ExprError(); 16095 16096 unsigned PtrArgIdx = 0; 16097 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16098 Expr *RowsExpr = TheCall->getArg(1); 16099 Expr *ColumnsExpr = TheCall->getArg(2); 16100 Expr *StrideExpr = TheCall->getArg(3); 16101 16102 bool ArgError = false; 16103 16104 // Check pointer argument. 16105 { 16106 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16107 if (PtrConv.isInvalid()) 16108 return PtrConv; 16109 PtrExpr = PtrConv.get(); 16110 TheCall->setArg(0, PtrExpr); 16111 if (PtrExpr->isTypeDependent()) { 16112 TheCall->setType(Context.DependentTy); 16113 return TheCall; 16114 } 16115 } 16116 16117 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16118 QualType ElementTy; 16119 if (!PtrTy) { 16120 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16121 << PtrArgIdx + 1; 16122 ArgError = true; 16123 } else { 16124 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16125 16126 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16127 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16128 << PtrArgIdx + 1; 16129 ArgError = true; 16130 } 16131 } 16132 16133 // Apply default Lvalue conversions and convert the expression to size_t. 16134 auto ApplyArgumentConversions = [this](Expr *E) { 16135 ExprResult Conv = DefaultLvalueConversion(E); 16136 if (Conv.isInvalid()) 16137 return Conv; 16138 16139 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16140 }; 16141 16142 // Apply conversion to row and column expressions. 16143 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16144 if (!RowsConv.isInvalid()) { 16145 RowsExpr = RowsConv.get(); 16146 TheCall->setArg(1, RowsExpr); 16147 } else 16148 RowsExpr = nullptr; 16149 16150 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16151 if (!ColumnsConv.isInvalid()) { 16152 ColumnsExpr = ColumnsConv.get(); 16153 TheCall->setArg(2, ColumnsExpr); 16154 } else 16155 ColumnsExpr = nullptr; 16156 16157 // If any any part of the result matrix type is still pending, just use 16158 // Context.DependentTy, until all parts are resolved. 16159 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16160 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16161 TheCall->setType(Context.DependentTy); 16162 return CallResult; 16163 } 16164 16165 // Check row and column dimenions. 16166 llvm::Optional<unsigned> MaybeRows; 16167 if (RowsExpr) 16168 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16169 16170 llvm::Optional<unsigned> MaybeColumns; 16171 if (ColumnsExpr) 16172 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16173 16174 // Check stride argument. 16175 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16176 if (StrideConv.isInvalid()) 16177 return ExprError(); 16178 StrideExpr = StrideConv.get(); 16179 TheCall->setArg(3, StrideExpr); 16180 16181 if (MaybeRows) { 16182 if (Optional<llvm::APSInt> Value = 16183 StrideExpr->getIntegerConstantExpr(Context)) { 16184 uint64_t Stride = Value->getZExtValue(); 16185 if (Stride < *MaybeRows) { 16186 Diag(StrideExpr->getBeginLoc(), 16187 diag::err_builtin_matrix_stride_too_small); 16188 ArgError = true; 16189 } 16190 } 16191 } 16192 16193 if (ArgError || !MaybeRows || !MaybeColumns) 16194 return ExprError(); 16195 16196 TheCall->setType( 16197 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16198 return CallResult; 16199 } 16200 16201 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16202 ExprResult CallResult) { 16203 if (checkArgCount(*this, TheCall, 3)) 16204 return ExprError(); 16205 16206 unsigned PtrArgIdx = 1; 16207 Expr *MatrixExpr = TheCall->getArg(0); 16208 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16209 Expr *StrideExpr = TheCall->getArg(2); 16210 16211 bool ArgError = false; 16212 16213 { 16214 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16215 if (MatrixConv.isInvalid()) 16216 return MatrixConv; 16217 MatrixExpr = MatrixConv.get(); 16218 TheCall->setArg(0, MatrixExpr); 16219 } 16220 if (MatrixExpr->isTypeDependent()) { 16221 TheCall->setType(Context.DependentTy); 16222 return TheCall; 16223 } 16224 16225 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16226 if (!MatrixTy) { 16227 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16228 ArgError = true; 16229 } 16230 16231 { 16232 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16233 if (PtrConv.isInvalid()) 16234 return PtrConv; 16235 PtrExpr = PtrConv.get(); 16236 TheCall->setArg(1, PtrExpr); 16237 if (PtrExpr->isTypeDependent()) { 16238 TheCall->setType(Context.DependentTy); 16239 return TheCall; 16240 } 16241 } 16242 16243 // Check pointer argument. 16244 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16245 if (!PtrTy) { 16246 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16247 << PtrArgIdx + 1; 16248 ArgError = true; 16249 } else { 16250 QualType ElementTy = PtrTy->getPointeeType(); 16251 if (ElementTy.isConstQualified()) { 16252 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16253 ArgError = true; 16254 } 16255 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16256 if (MatrixTy && 16257 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16258 Diag(PtrExpr->getBeginLoc(), 16259 diag::err_builtin_matrix_pointer_arg_mismatch) 16260 << ElementTy << MatrixTy->getElementType(); 16261 ArgError = true; 16262 } 16263 } 16264 16265 // Apply default Lvalue conversions and convert the stride expression to 16266 // size_t. 16267 { 16268 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16269 if (StrideConv.isInvalid()) 16270 return StrideConv; 16271 16272 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16273 if (StrideConv.isInvalid()) 16274 return StrideConv; 16275 StrideExpr = StrideConv.get(); 16276 TheCall->setArg(2, StrideExpr); 16277 } 16278 16279 // Check stride argument. 16280 if (MatrixTy) { 16281 if (Optional<llvm::APSInt> Value = 16282 StrideExpr->getIntegerConstantExpr(Context)) { 16283 uint64_t Stride = Value->getZExtValue(); 16284 if (Stride < MatrixTy->getNumRows()) { 16285 Diag(StrideExpr->getBeginLoc(), 16286 diag::err_builtin_matrix_stride_too_small); 16287 ArgError = true; 16288 } 16289 } 16290 } 16291 16292 if (ArgError) 16293 return ExprError(); 16294 16295 return CallResult; 16296 } 16297 16298 /// \brief Enforce the bounds of a TCB 16299 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16300 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16301 /// and enforce_tcb_leaf attributes. 16302 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16303 const FunctionDecl *Callee) { 16304 const FunctionDecl *Caller = getCurFunctionDecl(); 16305 16306 // Calls to builtins are not enforced. 16307 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16308 Callee->getBuiltinID() != 0) 16309 return; 16310 16311 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16312 // all TCBs the callee is a part of. 16313 llvm::StringSet<> CalleeTCBs; 16314 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16315 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16316 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16317 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16318 16319 // Go through the TCBs the caller is a part of and emit warnings if Caller 16320 // is in a TCB that the Callee is not. 16321 for_each( 16322 Caller->specific_attrs<EnforceTCBAttr>(), 16323 [&](const auto *A) { 16324 StringRef CallerTCB = A->getTCBName(); 16325 if (CalleeTCBs.count(CallerTCB) == 0) { 16326 this->Diag(TheCall->getExprLoc(), 16327 diag::warn_tcb_enforcement_violation) << Callee 16328 << CallerTCB; 16329 } 16330 }); 16331 } 16332