1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/Stmt.h" 34 #include "clang/AST/TemplateBase.h" 35 #include "clang/AST/Type.h" 36 #include "clang/AST/TypeLoc.h" 37 #include "clang/AST/UnresolvedSet.h" 38 #include "clang/Basic/AddressSpaces.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/Diagnostic.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/OpenCLOptions.h" 45 #include "clang/Basic/OperatorKinds.h" 46 #include "clang/Basic/PartialDiagnostic.h" 47 #include "clang/Basic/SourceLocation.h" 48 #include "clang/Basic/SourceManager.h" 49 #include "clang/Basic/Specifiers.h" 50 #include "clang/Basic/SyncScope.h" 51 #include "clang/Basic/TargetBuiltins.h" 52 #include "clang/Basic/TargetCXXABI.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "clang/Basic/TypeTraits.h" 55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 56 #include "clang/Sema/Initialization.h" 57 #include "clang/Sema/Lookup.h" 58 #include "clang/Sema/Ownership.h" 59 #include "clang/Sema/Scope.h" 60 #include "clang/Sema/ScopeInfo.h" 61 #include "clang/Sema/Sema.h" 62 #include "clang/Sema/SemaInternal.h" 63 #include "llvm/ADT/APFloat.h" 64 #include "llvm/ADT/APInt.h" 65 #include "llvm/ADT/APSInt.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/FoldingSet.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/SmallBitVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallString.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSwitch.h" 78 #include "llvm/ADT/Triple.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/ConvertUTF.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/Locale.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/SaveAndRestore.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <functional> 94 #include <limits> 95 #include <string> 96 #include <tuple> 97 #include <utility> 98 99 using namespace clang; 100 using namespace sema; 101 102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 103 unsigned ByteNo) const { 104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 105 Context.getTargetInfo()); 106 } 107 108 /// Checks that a call expression's argument count is the desired number. 109 /// This is useful when doing custom type-checking. Returns true on error. 110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 111 unsigned argCount = call->getNumArgs(); 112 if (argCount == desiredArgCount) return false; 113 114 if (argCount < desiredArgCount) 115 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 116 << 0 /*function call*/ << desiredArgCount << argCount 117 << call->getSourceRange(); 118 119 // Highlight all the excess arguments. 120 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 121 call->getArg(argCount - 1)->getEndLoc()); 122 123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 124 << 0 /*function call*/ << desiredArgCount << argCount 125 << call->getArg(1)->getSourceRange(); 126 } 127 128 /// Check that the first argument to __builtin_annotation is an integer 129 /// and the second argument is a non-wide string literal. 130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 131 if (checkArgCount(S, TheCall, 2)) 132 return true; 133 134 // First argument should be an integer. 135 Expr *ValArg = TheCall->getArg(0); 136 QualType Ty = ValArg->getType(); 137 if (!Ty->isIntegerType()) { 138 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 139 << ValArg->getSourceRange(); 140 return true; 141 } 142 143 // Second argument should be a constant string. 144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 146 if (!Literal || !Literal->isAscii()) { 147 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 148 << StrArg->getSourceRange(); 149 return true; 150 } 151 152 TheCall->setType(Ty); 153 return false; 154 } 155 156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 157 // We need at least one argument. 158 if (TheCall->getNumArgs() < 1) { 159 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 160 << 0 << 1 << TheCall->getNumArgs() 161 << TheCall->getCallee()->getSourceRange(); 162 return true; 163 } 164 165 // All arguments should be wide string literals. 166 for (Expr *Arg : TheCall->arguments()) { 167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 168 if (!Literal || !Literal->isWide()) { 169 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 170 << Arg->getSourceRange(); 171 return true; 172 } 173 } 174 175 return false; 176 } 177 178 /// Check that the argument to __builtin_addressof is a glvalue, and set the 179 /// result type to the corresponding pointer type. 180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 181 if (checkArgCount(S, TheCall, 1)) 182 return true; 183 184 ExprResult Arg(TheCall->getArg(0)); 185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 186 if (ResultType.isNull()) 187 return true; 188 189 TheCall->setArg(0, Arg.get()); 190 TheCall->setType(ResultType); 191 return false; 192 } 193 194 /// Check the number of arguments and set the result type to 195 /// the argument type. 196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 197 if (checkArgCount(S, TheCall, 1)) 198 return true; 199 200 TheCall->setType(TheCall->getArg(0)->getType()); 201 return false; 202 } 203 204 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 205 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 206 /// type (but not a function pointer) and that the alignment is a power-of-two. 207 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 208 if (checkArgCount(S, TheCall, 2)) 209 return true; 210 211 clang::Expr *Source = TheCall->getArg(0); 212 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 213 214 auto IsValidIntegerType = [](QualType Ty) { 215 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 216 }; 217 QualType SrcTy = Source->getType(); 218 // We should also be able to use it with arrays (but not functions!). 219 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 220 SrcTy = S.Context.getDecayedType(SrcTy); 221 } 222 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 223 SrcTy->isFunctionPointerType()) { 224 // FIXME: this is not quite the right error message since we don't allow 225 // floating point types, or member pointers. 226 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 227 << SrcTy; 228 return true; 229 } 230 231 clang::Expr *AlignOp = TheCall->getArg(1); 232 if (!IsValidIntegerType(AlignOp->getType())) { 233 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 234 << AlignOp->getType(); 235 return true; 236 } 237 Expr::EvalResult AlignResult; 238 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 239 // We can't check validity of alignment if it is type dependent. 240 if (!AlignOp->isInstantiationDependent() && 241 AlignOp->EvaluateAsInt(AlignResult, S.Context, 242 Expr::SE_AllowSideEffects)) { 243 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 244 llvm::APSInt MaxValue( 245 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 246 if (AlignValue < 1) { 247 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 248 return true; 249 } 250 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 252 << MaxValue.toString(10); 253 return true; 254 } 255 if (!AlignValue.isPowerOf2()) { 256 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 257 return true; 258 } 259 if (AlignValue == 1) { 260 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 261 << IsBooleanAlignBuiltin; 262 } 263 } 264 265 ExprResult SrcArg = S.PerformCopyInitialization( 266 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 267 SourceLocation(), Source); 268 if (SrcArg.isInvalid()) 269 return true; 270 TheCall->setArg(0, SrcArg.get()); 271 ExprResult AlignArg = 272 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 273 S.Context, AlignOp->getType(), false), 274 SourceLocation(), AlignOp); 275 if (AlignArg.isInvalid()) 276 return true; 277 TheCall->setArg(1, AlignArg.get()); 278 // For align_up/align_down, the return type is the same as the (potentially 279 // decayed) argument type including qualifiers. For is_aligned(), the result 280 // is always bool. 281 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 282 return false; 283 } 284 285 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 286 if (checkArgCount(S, TheCall, 3)) 287 return true; 288 289 // First two arguments should be integers. 290 for (unsigned I = 0; I < 2; ++I) { 291 ExprResult Arg = TheCall->getArg(I); 292 QualType Ty = Arg.get()->getType(); 293 if (!Ty->isIntegerType()) { 294 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 295 << Ty << Arg.get()->getSourceRange(); 296 return true; 297 } 298 InitializedEntity Entity = InitializedEntity::InitializeParameter( 299 S.getASTContext(), Ty, /*consume*/ false); 300 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 301 if (Arg.isInvalid()) 302 return true; 303 TheCall->setArg(I, Arg.get()); 304 } 305 306 // Third argument should be a pointer to a non-const integer. 307 // IRGen correctly handles volatile, restrict, and address spaces, and 308 // the other qualifiers aren't possible. 309 { 310 ExprResult Arg = TheCall->getArg(2); 311 QualType Ty = Arg.get()->getType(); 312 const auto *PtrTy = Ty->getAs<PointerType>(); 313 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 314 !PtrTy->getPointeeType().isConstQualified())) { 315 S.Diag(Arg.get()->getBeginLoc(), 316 diag::err_overflow_builtin_must_be_ptr_int) 317 << Ty << Arg.get()->getSourceRange(); 318 return true; 319 } 320 InitializedEntity Entity = InitializedEntity::InitializeParameter( 321 S.getASTContext(), Ty, /*consume*/ false); 322 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 323 if (Arg.isInvalid()) 324 return true; 325 TheCall->setArg(2, Arg.get()); 326 } 327 return false; 328 } 329 330 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 331 if (checkArgCount(S, BuiltinCall, 2)) 332 return true; 333 334 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 335 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 336 Expr *Call = BuiltinCall->getArg(0); 337 Expr *Chain = BuiltinCall->getArg(1); 338 339 if (Call->getStmtClass() != Stmt::CallExprClass) { 340 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 341 << Call->getSourceRange(); 342 return true; 343 } 344 345 auto CE = cast<CallExpr>(Call); 346 if (CE->getCallee()->getType()->isBlockPointerType()) { 347 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 348 << Call->getSourceRange(); 349 return true; 350 } 351 352 const Decl *TargetDecl = CE->getCalleeDecl(); 353 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 354 if (FD->getBuiltinID()) { 355 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 356 << Call->getSourceRange(); 357 return true; 358 } 359 360 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 361 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 362 << Call->getSourceRange(); 363 return true; 364 } 365 366 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 367 if (ChainResult.isInvalid()) 368 return true; 369 if (!ChainResult.get()->getType()->isPointerType()) { 370 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 371 << Chain->getSourceRange(); 372 return true; 373 } 374 375 QualType ReturnTy = CE->getCallReturnType(S.Context); 376 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 377 QualType BuiltinTy = S.Context.getFunctionType( 378 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 379 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 380 381 Builtin = 382 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 383 384 BuiltinCall->setType(CE->getType()); 385 BuiltinCall->setValueKind(CE->getValueKind()); 386 BuiltinCall->setObjectKind(CE->getObjectKind()); 387 BuiltinCall->setCallee(Builtin); 388 BuiltinCall->setArg(1, ChainResult.get()); 389 390 return false; 391 } 392 393 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 394 /// __builtin_*_chk function, then use the object size argument specified in the 395 /// source. Otherwise, infer the object size using __builtin_object_size. 396 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 397 CallExpr *TheCall) { 398 // FIXME: There are some more useful checks we could be doing here: 399 // - Analyze the format string of sprintf to see how much of buffer is used. 400 // - Evaluate strlen of strcpy arguments, use as object size. 401 402 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 403 isConstantEvaluated()) 404 return; 405 406 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 407 if (!BuiltinID) 408 return; 409 410 unsigned DiagID = 0; 411 bool IsChkVariant = false; 412 unsigned SizeIndex, ObjectIndex; 413 switch (BuiltinID) { 414 default: 415 return; 416 case Builtin::BI__builtin___memcpy_chk: 417 case Builtin::BI__builtin___memmove_chk: 418 case Builtin::BI__builtin___memset_chk: 419 case Builtin::BI__builtin___strlcat_chk: 420 case Builtin::BI__builtin___strlcpy_chk: 421 case Builtin::BI__builtin___strncat_chk: 422 case Builtin::BI__builtin___strncpy_chk: 423 case Builtin::BI__builtin___stpncpy_chk: 424 case Builtin::BI__builtin___memccpy_chk: 425 case Builtin::BI__builtin___mempcpy_chk: { 426 DiagID = diag::warn_builtin_chk_overflow; 427 IsChkVariant = true; 428 SizeIndex = TheCall->getNumArgs() - 2; 429 ObjectIndex = TheCall->getNumArgs() - 1; 430 break; 431 } 432 433 case Builtin::BI__builtin___snprintf_chk: 434 case Builtin::BI__builtin___vsnprintf_chk: { 435 DiagID = diag::warn_builtin_chk_overflow; 436 IsChkVariant = true; 437 SizeIndex = 1; 438 ObjectIndex = 3; 439 break; 440 } 441 442 case Builtin::BIstrncat: 443 case Builtin::BI__builtin_strncat: 444 case Builtin::BIstrncpy: 445 case Builtin::BI__builtin_strncpy: 446 case Builtin::BIstpncpy: 447 case Builtin::BI__builtin_stpncpy: { 448 // Whether these functions overflow depends on the runtime strlen of the 449 // string, not just the buffer size, so emitting the "always overflow" 450 // diagnostic isn't quite right. We should still diagnose passing a buffer 451 // size larger than the destination buffer though; this is a runtime abort 452 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 453 DiagID = diag::warn_fortify_source_size_mismatch; 454 SizeIndex = TheCall->getNumArgs() - 1; 455 ObjectIndex = 0; 456 break; 457 } 458 459 case Builtin::BImemcpy: 460 case Builtin::BI__builtin_memcpy: 461 case Builtin::BImemmove: 462 case Builtin::BI__builtin_memmove: 463 case Builtin::BImemset: 464 case Builtin::BI__builtin_memset: 465 case Builtin::BImempcpy: 466 case Builtin::BI__builtin_mempcpy: { 467 DiagID = diag::warn_fortify_source_overflow; 468 SizeIndex = TheCall->getNumArgs() - 1; 469 ObjectIndex = 0; 470 break; 471 } 472 case Builtin::BIsnprintf: 473 case Builtin::BI__builtin_snprintf: 474 case Builtin::BIvsnprintf: 475 case Builtin::BI__builtin_vsnprintf: { 476 DiagID = diag::warn_fortify_source_size_mismatch; 477 SizeIndex = 1; 478 ObjectIndex = 0; 479 break; 480 } 481 } 482 483 llvm::APSInt ObjectSize; 484 // For __builtin___*_chk, the object size is explicitly provided by the caller 485 // (usually using __builtin_object_size). Use that value to check this call. 486 if (IsChkVariant) { 487 Expr::EvalResult Result; 488 Expr *SizeArg = TheCall->getArg(ObjectIndex); 489 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 490 return; 491 ObjectSize = Result.Val.getInt(); 492 493 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 494 } else { 495 // If the parameter has a pass_object_size attribute, then we should use its 496 // (potentially) more strict checking mode. Otherwise, conservatively assume 497 // type 0. 498 int BOSType = 0; 499 if (const auto *POS = 500 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 501 BOSType = POS->getType(); 502 503 Expr *ObjArg = TheCall->getArg(ObjectIndex); 504 uint64_t Result; 505 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 506 return; 507 // Get the object size in the target's size_t width. 508 const TargetInfo &TI = getASTContext().getTargetInfo(); 509 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 510 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 511 } 512 513 // Evaluate the number of bytes of the object that this call will use. 514 Expr::EvalResult Result; 515 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 516 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 517 return; 518 llvm::APSInt UsedSize = Result.Val.getInt(); 519 520 if (UsedSize.ule(ObjectSize)) 521 return; 522 523 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 524 // Skim off the details of whichever builtin was called to produce a better 525 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 526 if (IsChkVariant) { 527 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 528 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 529 } else if (FunctionName.startswith("__builtin_")) { 530 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 531 } 532 533 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 534 PDiag(DiagID) 535 << FunctionName << ObjectSize.toString(/*Radix=*/10) 536 << UsedSize.toString(/*Radix=*/10)); 537 } 538 539 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 540 Scope::ScopeFlags NeededScopeFlags, 541 unsigned DiagID) { 542 // Scopes aren't available during instantiation. Fortunately, builtin 543 // functions cannot be template args so they cannot be formed through template 544 // instantiation. Therefore checking once during the parse is sufficient. 545 if (SemaRef.inTemplateInstantiation()) 546 return false; 547 548 Scope *S = SemaRef.getCurScope(); 549 while (S && !S->isSEHExceptScope()) 550 S = S->getParent(); 551 if (!S || !(S->getFlags() & NeededScopeFlags)) { 552 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 553 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 554 << DRE->getDecl()->getIdentifier(); 555 return true; 556 } 557 558 return false; 559 } 560 561 static inline bool isBlockPointer(Expr *Arg) { 562 return Arg->getType()->isBlockPointerType(); 563 } 564 565 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 566 /// void*, which is a requirement of device side enqueue. 567 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 568 const BlockPointerType *BPT = 569 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 570 ArrayRef<QualType> Params = 571 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 572 unsigned ArgCounter = 0; 573 bool IllegalParams = false; 574 // Iterate through the block parameters until either one is found that is not 575 // a local void*, or the block is valid. 576 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 577 I != E; ++I, ++ArgCounter) { 578 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 579 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 580 LangAS::opencl_local) { 581 // Get the location of the error. If a block literal has been passed 582 // (BlockExpr) then we can point straight to the offending argument, 583 // else we just point to the variable reference. 584 SourceLocation ErrorLoc; 585 if (isa<BlockExpr>(BlockArg)) { 586 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 587 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 588 } else if (isa<DeclRefExpr>(BlockArg)) { 589 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 590 } 591 S.Diag(ErrorLoc, 592 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 593 IllegalParams = true; 594 } 595 } 596 597 return IllegalParams; 598 } 599 600 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 601 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 602 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 603 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 604 return true; 605 } 606 return false; 607 } 608 609 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 610 if (checkArgCount(S, TheCall, 2)) 611 return true; 612 613 if (checkOpenCLSubgroupExt(S, TheCall)) 614 return true; 615 616 // First argument is an ndrange_t type. 617 Expr *NDRangeArg = TheCall->getArg(0); 618 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 619 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 620 << TheCall->getDirectCallee() << "'ndrange_t'"; 621 return true; 622 } 623 624 Expr *BlockArg = TheCall->getArg(1); 625 if (!isBlockPointer(BlockArg)) { 626 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 627 << TheCall->getDirectCallee() << "block"; 628 return true; 629 } 630 return checkOpenCLBlockArgs(S, BlockArg); 631 } 632 633 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 634 /// get_kernel_work_group_size 635 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 636 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 637 if (checkArgCount(S, TheCall, 1)) 638 return true; 639 640 Expr *BlockArg = TheCall->getArg(0); 641 if (!isBlockPointer(BlockArg)) { 642 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 643 << TheCall->getDirectCallee() << "block"; 644 return true; 645 } 646 return checkOpenCLBlockArgs(S, BlockArg); 647 } 648 649 /// Diagnose integer type and any valid implicit conversion to it. 650 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 651 const QualType &IntType); 652 653 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 654 unsigned Start, unsigned End) { 655 bool IllegalParams = false; 656 for (unsigned I = Start; I <= End; ++I) 657 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 658 S.Context.getSizeType()); 659 return IllegalParams; 660 } 661 662 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 663 /// 'local void*' parameter of passed block. 664 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 665 Expr *BlockArg, 666 unsigned NumNonVarArgs) { 667 const BlockPointerType *BPT = 668 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 669 unsigned NumBlockParams = 670 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 671 unsigned TotalNumArgs = TheCall->getNumArgs(); 672 673 // For each argument passed to the block, a corresponding uint needs to 674 // be passed to describe the size of the local memory. 675 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 676 S.Diag(TheCall->getBeginLoc(), 677 diag::err_opencl_enqueue_kernel_local_size_args); 678 return true; 679 } 680 681 // Check that the sizes of the local memory are specified by integers. 682 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 683 TotalNumArgs - 1); 684 } 685 686 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 687 /// overload formats specified in Table 6.13.17.1. 688 /// int enqueue_kernel(queue_t queue, 689 /// kernel_enqueue_flags_t flags, 690 /// const ndrange_t ndrange, 691 /// void (^block)(void)) 692 /// int enqueue_kernel(queue_t queue, 693 /// kernel_enqueue_flags_t flags, 694 /// const ndrange_t ndrange, 695 /// uint num_events_in_wait_list, 696 /// clk_event_t *event_wait_list, 697 /// clk_event_t *event_ret, 698 /// void (^block)(void)) 699 /// int enqueue_kernel(queue_t queue, 700 /// kernel_enqueue_flags_t flags, 701 /// const ndrange_t ndrange, 702 /// void (^block)(local void*, ...), 703 /// uint size0, ...) 704 /// int enqueue_kernel(queue_t queue, 705 /// kernel_enqueue_flags_t flags, 706 /// const ndrange_t ndrange, 707 /// uint num_events_in_wait_list, 708 /// clk_event_t *event_wait_list, 709 /// clk_event_t *event_ret, 710 /// void (^block)(local void*, ...), 711 /// uint size0, ...) 712 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 713 unsigned NumArgs = TheCall->getNumArgs(); 714 715 if (NumArgs < 4) { 716 S.Diag(TheCall->getBeginLoc(), 717 diag::err_typecheck_call_too_few_args_at_least) 718 << 0 << 4 << NumArgs; 719 return true; 720 } 721 722 Expr *Arg0 = TheCall->getArg(0); 723 Expr *Arg1 = TheCall->getArg(1); 724 Expr *Arg2 = TheCall->getArg(2); 725 Expr *Arg3 = TheCall->getArg(3); 726 727 // First argument always needs to be a queue_t type. 728 if (!Arg0->getType()->isQueueT()) { 729 S.Diag(TheCall->getArg(0)->getBeginLoc(), 730 diag::err_opencl_builtin_expected_type) 731 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 732 return true; 733 } 734 735 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 736 if (!Arg1->getType()->isIntegerType()) { 737 S.Diag(TheCall->getArg(1)->getBeginLoc(), 738 diag::err_opencl_builtin_expected_type) 739 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 740 return true; 741 } 742 743 // Third argument is always an ndrange_t type. 744 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 745 S.Diag(TheCall->getArg(2)->getBeginLoc(), 746 diag::err_opencl_builtin_expected_type) 747 << TheCall->getDirectCallee() << "'ndrange_t'"; 748 return true; 749 } 750 751 // With four arguments, there is only one form that the function could be 752 // called in: no events and no variable arguments. 753 if (NumArgs == 4) { 754 // check that the last argument is the right block type. 755 if (!isBlockPointer(Arg3)) { 756 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 757 << TheCall->getDirectCallee() << "block"; 758 return true; 759 } 760 // we have a block type, check the prototype 761 const BlockPointerType *BPT = 762 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 763 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 764 S.Diag(Arg3->getBeginLoc(), 765 diag::err_opencl_enqueue_kernel_blocks_no_args); 766 return true; 767 } 768 return false; 769 } 770 // we can have block + varargs. 771 if (isBlockPointer(Arg3)) 772 return (checkOpenCLBlockArgs(S, Arg3) || 773 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 774 // last two cases with either exactly 7 args or 7 args and varargs. 775 if (NumArgs >= 7) { 776 // check common block argument. 777 Expr *Arg6 = TheCall->getArg(6); 778 if (!isBlockPointer(Arg6)) { 779 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 780 << TheCall->getDirectCallee() << "block"; 781 return true; 782 } 783 if (checkOpenCLBlockArgs(S, Arg6)) 784 return true; 785 786 // Forth argument has to be any integer type. 787 if (!Arg3->getType()->isIntegerType()) { 788 S.Diag(TheCall->getArg(3)->getBeginLoc(), 789 diag::err_opencl_builtin_expected_type) 790 << TheCall->getDirectCallee() << "integer"; 791 return true; 792 } 793 // check remaining common arguments. 794 Expr *Arg4 = TheCall->getArg(4); 795 Expr *Arg5 = TheCall->getArg(5); 796 797 // Fifth argument is always passed as a pointer to clk_event_t. 798 if (!Arg4->isNullPointerConstant(S.Context, 799 Expr::NPC_ValueDependentIsNotNull) && 800 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 801 S.Diag(TheCall->getArg(4)->getBeginLoc(), 802 diag::err_opencl_builtin_expected_type) 803 << TheCall->getDirectCallee() 804 << S.Context.getPointerType(S.Context.OCLClkEventTy); 805 return true; 806 } 807 808 // Sixth argument is always passed as a pointer to clk_event_t. 809 if (!Arg5->isNullPointerConstant(S.Context, 810 Expr::NPC_ValueDependentIsNotNull) && 811 !(Arg5->getType()->isPointerType() && 812 Arg5->getType()->getPointeeType()->isClkEventT())) { 813 S.Diag(TheCall->getArg(5)->getBeginLoc(), 814 diag::err_opencl_builtin_expected_type) 815 << TheCall->getDirectCallee() 816 << S.Context.getPointerType(S.Context.OCLClkEventTy); 817 return true; 818 } 819 820 if (NumArgs == 7) 821 return false; 822 823 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 824 } 825 826 // None of the specific case has been detected, give generic error 827 S.Diag(TheCall->getBeginLoc(), 828 diag::err_opencl_enqueue_kernel_incorrect_args); 829 return true; 830 } 831 832 /// Returns OpenCL access qual. 833 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 834 return D->getAttr<OpenCLAccessAttr>(); 835 } 836 837 /// Returns true if pipe element type is different from the pointer. 838 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 839 const Expr *Arg0 = Call->getArg(0); 840 // First argument type should always be pipe. 841 if (!Arg0->getType()->isPipeType()) { 842 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 843 << Call->getDirectCallee() << Arg0->getSourceRange(); 844 return true; 845 } 846 OpenCLAccessAttr *AccessQual = 847 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 848 // Validates the access qualifier is compatible with the call. 849 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 850 // read_only and write_only, and assumed to be read_only if no qualifier is 851 // specified. 852 switch (Call->getDirectCallee()->getBuiltinID()) { 853 case Builtin::BIread_pipe: 854 case Builtin::BIreserve_read_pipe: 855 case Builtin::BIcommit_read_pipe: 856 case Builtin::BIwork_group_reserve_read_pipe: 857 case Builtin::BIsub_group_reserve_read_pipe: 858 case Builtin::BIwork_group_commit_read_pipe: 859 case Builtin::BIsub_group_commit_read_pipe: 860 if (!(!AccessQual || AccessQual->isReadOnly())) { 861 S.Diag(Arg0->getBeginLoc(), 862 diag::err_opencl_builtin_pipe_invalid_access_modifier) 863 << "read_only" << Arg0->getSourceRange(); 864 return true; 865 } 866 break; 867 case Builtin::BIwrite_pipe: 868 case Builtin::BIreserve_write_pipe: 869 case Builtin::BIcommit_write_pipe: 870 case Builtin::BIwork_group_reserve_write_pipe: 871 case Builtin::BIsub_group_reserve_write_pipe: 872 case Builtin::BIwork_group_commit_write_pipe: 873 case Builtin::BIsub_group_commit_write_pipe: 874 if (!(AccessQual && AccessQual->isWriteOnly())) { 875 S.Diag(Arg0->getBeginLoc(), 876 diag::err_opencl_builtin_pipe_invalid_access_modifier) 877 << "write_only" << Arg0->getSourceRange(); 878 return true; 879 } 880 break; 881 default: 882 break; 883 } 884 return false; 885 } 886 887 /// Returns true if pipe element type is different from the pointer. 888 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 889 const Expr *Arg0 = Call->getArg(0); 890 const Expr *ArgIdx = Call->getArg(Idx); 891 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 892 const QualType EltTy = PipeTy->getElementType(); 893 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 894 // The Idx argument should be a pointer and the type of the pointer and 895 // the type of pipe element should also be the same. 896 if (!ArgTy || 897 !S.Context.hasSameType( 898 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 899 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 900 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 901 << ArgIdx->getType() << ArgIdx->getSourceRange(); 902 return true; 903 } 904 return false; 905 } 906 907 // Performs semantic analysis for the read/write_pipe call. 908 // \param S Reference to the semantic analyzer. 909 // \param Call A pointer to the builtin call. 910 // \return True if a semantic error has been found, false otherwise. 911 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 912 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 913 // functions have two forms. 914 switch (Call->getNumArgs()) { 915 case 2: 916 if (checkOpenCLPipeArg(S, Call)) 917 return true; 918 // The call with 2 arguments should be 919 // read/write_pipe(pipe T, T*). 920 // Check packet type T. 921 if (checkOpenCLPipePacketType(S, Call, 1)) 922 return true; 923 break; 924 925 case 4: { 926 if (checkOpenCLPipeArg(S, Call)) 927 return true; 928 // The call with 4 arguments should be 929 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 930 // Check reserve_id_t. 931 if (!Call->getArg(1)->getType()->isReserveIDT()) { 932 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 933 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 934 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 935 return true; 936 } 937 938 // Check the index. 939 const Expr *Arg2 = Call->getArg(2); 940 if (!Arg2->getType()->isIntegerType() && 941 !Arg2->getType()->isUnsignedIntegerType()) { 942 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 943 << Call->getDirectCallee() << S.Context.UnsignedIntTy 944 << Arg2->getType() << Arg2->getSourceRange(); 945 return true; 946 } 947 948 // Check packet type T. 949 if (checkOpenCLPipePacketType(S, Call, 3)) 950 return true; 951 } break; 952 default: 953 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 954 << Call->getDirectCallee() << Call->getSourceRange(); 955 return true; 956 } 957 958 return false; 959 } 960 961 // Performs a semantic analysis on the {work_group_/sub_group_ 962 // /_}reserve_{read/write}_pipe 963 // \param S Reference to the semantic analyzer. 964 // \param Call The call to the builtin function to be analyzed. 965 // \return True if a semantic error was found, false otherwise. 966 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 967 if (checkArgCount(S, Call, 2)) 968 return true; 969 970 if (checkOpenCLPipeArg(S, Call)) 971 return true; 972 973 // Check the reserve size. 974 if (!Call->getArg(1)->getType()->isIntegerType() && 975 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 976 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 977 << Call->getDirectCallee() << S.Context.UnsignedIntTy 978 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 979 return true; 980 } 981 982 // Since return type of reserve_read/write_pipe built-in function is 983 // reserve_id_t, which is not defined in the builtin def file , we used int 984 // as return type and need to override the return type of these functions. 985 Call->setType(S.Context.OCLReserveIDTy); 986 987 return false; 988 } 989 990 // Performs a semantic analysis on {work_group_/sub_group_ 991 // /_}commit_{read/write}_pipe 992 // \param S Reference to the semantic analyzer. 993 // \param Call The call to the builtin function to be analyzed. 994 // \return True if a semantic error was found, false otherwise. 995 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 996 if (checkArgCount(S, Call, 2)) 997 return true; 998 999 if (checkOpenCLPipeArg(S, Call)) 1000 return true; 1001 1002 // Check reserve_id_t. 1003 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1004 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1005 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1006 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1007 return true; 1008 } 1009 1010 return false; 1011 } 1012 1013 // Performs a semantic analysis on the call to built-in Pipe 1014 // Query Functions. 1015 // \param S Reference to the semantic analyzer. 1016 // \param Call The call to the builtin function to be analyzed. 1017 // \return True if a semantic error was found, false otherwise. 1018 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1019 if (checkArgCount(S, Call, 1)) 1020 return true; 1021 1022 if (!Call->getArg(0)->getType()->isPipeType()) { 1023 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1024 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1025 return true; 1026 } 1027 1028 return false; 1029 } 1030 1031 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1032 // Performs semantic analysis for the to_global/local/private call. 1033 // \param S Reference to the semantic analyzer. 1034 // \param BuiltinID ID of the builtin function. 1035 // \param Call A pointer to the builtin call. 1036 // \return True if a semantic error has been found, false otherwise. 1037 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1038 CallExpr *Call) { 1039 if (Call->getNumArgs() != 1) { 1040 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 1041 << Call->getDirectCallee() << Call->getSourceRange(); 1042 return true; 1043 } 1044 1045 auto RT = Call->getArg(0)->getType(); 1046 if (!RT->isPointerType() || RT->getPointeeType() 1047 .getAddressSpace() == LangAS::opencl_constant) { 1048 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1049 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1050 return true; 1051 } 1052 1053 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1054 S.Diag(Call->getArg(0)->getBeginLoc(), 1055 diag::warn_opencl_generic_address_space_arg) 1056 << Call->getDirectCallee()->getNameInfo().getAsString() 1057 << Call->getArg(0)->getSourceRange(); 1058 } 1059 1060 RT = RT->getPointeeType(); 1061 auto Qual = RT.getQualifiers(); 1062 switch (BuiltinID) { 1063 case Builtin::BIto_global: 1064 Qual.setAddressSpace(LangAS::opencl_global); 1065 break; 1066 case Builtin::BIto_local: 1067 Qual.setAddressSpace(LangAS::opencl_local); 1068 break; 1069 case Builtin::BIto_private: 1070 Qual.setAddressSpace(LangAS::opencl_private); 1071 break; 1072 default: 1073 llvm_unreachable("Invalid builtin function"); 1074 } 1075 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1076 RT.getUnqualifiedType(), Qual))); 1077 1078 return false; 1079 } 1080 1081 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1082 if (checkArgCount(S, TheCall, 1)) 1083 return ExprError(); 1084 1085 // Compute __builtin_launder's parameter type from the argument. 1086 // The parameter type is: 1087 // * The type of the argument if it's not an array or function type, 1088 // Otherwise, 1089 // * The decayed argument type. 1090 QualType ParamTy = [&]() { 1091 QualType ArgTy = TheCall->getArg(0)->getType(); 1092 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1093 return S.Context.getPointerType(Ty->getElementType()); 1094 if (ArgTy->isFunctionType()) { 1095 return S.Context.getPointerType(ArgTy); 1096 } 1097 return ArgTy; 1098 }(); 1099 1100 TheCall->setType(ParamTy); 1101 1102 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1103 if (!ParamTy->isPointerType()) 1104 return 0; 1105 if (ParamTy->isFunctionPointerType()) 1106 return 1; 1107 if (ParamTy->isVoidPointerType()) 1108 return 2; 1109 return llvm::Optional<unsigned>{}; 1110 }(); 1111 if (DiagSelect.hasValue()) { 1112 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1113 << DiagSelect.getValue() << TheCall->getSourceRange(); 1114 return ExprError(); 1115 } 1116 1117 // We either have an incomplete class type, or we have a class template 1118 // whose instantiation has not been forced. Example: 1119 // 1120 // template <class T> struct Foo { T value; }; 1121 // Foo<int> *p = nullptr; 1122 // auto *d = __builtin_launder(p); 1123 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1124 diag::err_incomplete_type)) 1125 return ExprError(); 1126 1127 assert(ParamTy->getPointeeType()->isObjectType() && 1128 "Unhandled non-object pointer case"); 1129 1130 InitializedEntity Entity = 1131 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1132 ExprResult Arg = 1133 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1134 if (Arg.isInvalid()) 1135 return ExprError(); 1136 TheCall->setArg(0, Arg.get()); 1137 1138 return TheCall; 1139 } 1140 1141 // Emit an error and return true if the current architecture is not in the list 1142 // of supported architectures. 1143 static bool 1144 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1145 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1146 llvm::Triple::ArchType CurArch = 1147 S.getASTContext().getTargetInfo().getTriple().getArch(); 1148 if (llvm::is_contained(SupportedArchs, CurArch)) 1149 return false; 1150 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1151 << TheCall->getSourceRange(); 1152 return true; 1153 } 1154 1155 ExprResult 1156 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1157 CallExpr *TheCall) { 1158 ExprResult TheCallResult(TheCall); 1159 1160 // Find out if any arguments are required to be integer constant expressions. 1161 unsigned ICEArguments = 0; 1162 ASTContext::GetBuiltinTypeError Error; 1163 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1164 if (Error != ASTContext::GE_None) 1165 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1166 1167 // If any arguments are required to be ICE's, check and diagnose. 1168 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1169 // Skip arguments not required to be ICE's. 1170 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1171 1172 llvm::APSInt Result; 1173 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1174 return true; 1175 ICEArguments &= ~(1 << ArgNo); 1176 } 1177 1178 switch (BuiltinID) { 1179 case Builtin::BI__builtin___CFStringMakeConstantString: 1180 assert(TheCall->getNumArgs() == 1 && 1181 "Wrong # arguments to builtin CFStringMakeConstantString"); 1182 if (CheckObjCString(TheCall->getArg(0))) 1183 return ExprError(); 1184 break; 1185 case Builtin::BI__builtin_ms_va_start: 1186 case Builtin::BI__builtin_stdarg_start: 1187 case Builtin::BI__builtin_va_start: 1188 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1189 return ExprError(); 1190 break; 1191 case Builtin::BI__va_start: { 1192 switch (Context.getTargetInfo().getTriple().getArch()) { 1193 case llvm::Triple::aarch64: 1194 case llvm::Triple::arm: 1195 case llvm::Triple::thumb: 1196 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1197 return ExprError(); 1198 break; 1199 default: 1200 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1201 return ExprError(); 1202 break; 1203 } 1204 break; 1205 } 1206 1207 // The acquire, release, and no fence variants are ARM and AArch64 only. 1208 case Builtin::BI_interlockedbittestandset_acq: 1209 case Builtin::BI_interlockedbittestandset_rel: 1210 case Builtin::BI_interlockedbittestandset_nf: 1211 case Builtin::BI_interlockedbittestandreset_acq: 1212 case Builtin::BI_interlockedbittestandreset_rel: 1213 case Builtin::BI_interlockedbittestandreset_nf: 1214 if (CheckBuiltinTargetSupport( 1215 *this, BuiltinID, TheCall, 1216 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1217 return ExprError(); 1218 break; 1219 1220 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1221 case Builtin::BI_bittest64: 1222 case Builtin::BI_bittestandcomplement64: 1223 case Builtin::BI_bittestandreset64: 1224 case Builtin::BI_bittestandset64: 1225 case Builtin::BI_interlockedbittestandreset64: 1226 case Builtin::BI_interlockedbittestandset64: 1227 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1228 {llvm::Triple::x86_64, llvm::Triple::arm, 1229 llvm::Triple::thumb, llvm::Triple::aarch64})) 1230 return ExprError(); 1231 break; 1232 1233 case Builtin::BI__builtin_isgreater: 1234 case Builtin::BI__builtin_isgreaterequal: 1235 case Builtin::BI__builtin_isless: 1236 case Builtin::BI__builtin_islessequal: 1237 case Builtin::BI__builtin_islessgreater: 1238 case Builtin::BI__builtin_isunordered: 1239 if (SemaBuiltinUnorderedCompare(TheCall)) 1240 return ExprError(); 1241 break; 1242 case Builtin::BI__builtin_fpclassify: 1243 if (SemaBuiltinFPClassification(TheCall, 6)) 1244 return ExprError(); 1245 break; 1246 case Builtin::BI__builtin_isfinite: 1247 case Builtin::BI__builtin_isinf: 1248 case Builtin::BI__builtin_isinf_sign: 1249 case Builtin::BI__builtin_isnan: 1250 case Builtin::BI__builtin_isnormal: 1251 case Builtin::BI__builtin_signbit: 1252 case Builtin::BI__builtin_signbitf: 1253 case Builtin::BI__builtin_signbitl: 1254 if (SemaBuiltinFPClassification(TheCall, 1)) 1255 return ExprError(); 1256 break; 1257 case Builtin::BI__builtin_shufflevector: 1258 return SemaBuiltinShuffleVector(TheCall); 1259 // TheCall will be freed by the smart pointer here, but that's fine, since 1260 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1261 case Builtin::BI__builtin_prefetch: 1262 if (SemaBuiltinPrefetch(TheCall)) 1263 return ExprError(); 1264 break; 1265 case Builtin::BI__builtin_alloca_with_align: 1266 if (SemaBuiltinAllocaWithAlign(TheCall)) 1267 return ExprError(); 1268 LLVM_FALLTHROUGH; 1269 case Builtin::BI__builtin_alloca: 1270 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1271 << TheCall->getDirectCallee(); 1272 break; 1273 case Builtin::BI__assume: 1274 case Builtin::BI__builtin_assume: 1275 if (SemaBuiltinAssume(TheCall)) 1276 return ExprError(); 1277 break; 1278 case Builtin::BI__builtin_assume_aligned: 1279 if (SemaBuiltinAssumeAligned(TheCall)) 1280 return ExprError(); 1281 break; 1282 case Builtin::BI__builtin_dynamic_object_size: 1283 case Builtin::BI__builtin_object_size: 1284 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1285 return ExprError(); 1286 break; 1287 case Builtin::BI__builtin_longjmp: 1288 if (SemaBuiltinLongjmp(TheCall)) 1289 return ExprError(); 1290 break; 1291 case Builtin::BI__builtin_setjmp: 1292 if (SemaBuiltinSetjmp(TheCall)) 1293 return ExprError(); 1294 break; 1295 case Builtin::BI_setjmp: 1296 case Builtin::BI_setjmpex: 1297 if (checkArgCount(*this, TheCall, 1)) 1298 return true; 1299 break; 1300 case Builtin::BI__builtin_classify_type: 1301 if (checkArgCount(*this, TheCall, 1)) return true; 1302 TheCall->setType(Context.IntTy); 1303 break; 1304 case Builtin::BI__builtin_constant_p: { 1305 if (checkArgCount(*this, TheCall, 1)) return true; 1306 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1307 if (Arg.isInvalid()) return true; 1308 TheCall->setArg(0, Arg.get()); 1309 TheCall->setType(Context.IntTy); 1310 break; 1311 } 1312 case Builtin::BI__builtin_launder: 1313 return SemaBuiltinLaunder(*this, TheCall); 1314 case Builtin::BI__sync_fetch_and_add: 1315 case Builtin::BI__sync_fetch_and_add_1: 1316 case Builtin::BI__sync_fetch_and_add_2: 1317 case Builtin::BI__sync_fetch_and_add_4: 1318 case Builtin::BI__sync_fetch_and_add_8: 1319 case Builtin::BI__sync_fetch_and_add_16: 1320 case Builtin::BI__sync_fetch_and_sub: 1321 case Builtin::BI__sync_fetch_and_sub_1: 1322 case Builtin::BI__sync_fetch_and_sub_2: 1323 case Builtin::BI__sync_fetch_and_sub_4: 1324 case Builtin::BI__sync_fetch_and_sub_8: 1325 case Builtin::BI__sync_fetch_and_sub_16: 1326 case Builtin::BI__sync_fetch_and_or: 1327 case Builtin::BI__sync_fetch_and_or_1: 1328 case Builtin::BI__sync_fetch_and_or_2: 1329 case Builtin::BI__sync_fetch_and_or_4: 1330 case Builtin::BI__sync_fetch_and_or_8: 1331 case Builtin::BI__sync_fetch_and_or_16: 1332 case Builtin::BI__sync_fetch_and_and: 1333 case Builtin::BI__sync_fetch_and_and_1: 1334 case Builtin::BI__sync_fetch_and_and_2: 1335 case Builtin::BI__sync_fetch_and_and_4: 1336 case Builtin::BI__sync_fetch_and_and_8: 1337 case Builtin::BI__sync_fetch_and_and_16: 1338 case Builtin::BI__sync_fetch_and_xor: 1339 case Builtin::BI__sync_fetch_and_xor_1: 1340 case Builtin::BI__sync_fetch_and_xor_2: 1341 case Builtin::BI__sync_fetch_and_xor_4: 1342 case Builtin::BI__sync_fetch_and_xor_8: 1343 case Builtin::BI__sync_fetch_and_xor_16: 1344 case Builtin::BI__sync_fetch_and_nand: 1345 case Builtin::BI__sync_fetch_and_nand_1: 1346 case Builtin::BI__sync_fetch_and_nand_2: 1347 case Builtin::BI__sync_fetch_and_nand_4: 1348 case Builtin::BI__sync_fetch_and_nand_8: 1349 case Builtin::BI__sync_fetch_and_nand_16: 1350 case Builtin::BI__sync_add_and_fetch: 1351 case Builtin::BI__sync_add_and_fetch_1: 1352 case Builtin::BI__sync_add_and_fetch_2: 1353 case Builtin::BI__sync_add_and_fetch_4: 1354 case Builtin::BI__sync_add_and_fetch_8: 1355 case Builtin::BI__sync_add_and_fetch_16: 1356 case Builtin::BI__sync_sub_and_fetch: 1357 case Builtin::BI__sync_sub_and_fetch_1: 1358 case Builtin::BI__sync_sub_and_fetch_2: 1359 case Builtin::BI__sync_sub_and_fetch_4: 1360 case Builtin::BI__sync_sub_and_fetch_8: 1361 case Builtin::BI__sync_sub_and_fetch_16: 1362 case Builtin::BI__sync_and_and_fetch: 1363 case Builtin::BI__sync_and_and_fetch_1: 1364 case Builtin::BI__sync_and_and_fetch_2: 1365 case Builtin::BI__sync_and_and_fetch_4: 1366 case Builtin::BI__sync_and_and_fetch_8: 1367 case Builtin::BI__sync_and_and_fetch_16: 1368 case Builtin::BI__sync_or_and_fetch: 1369 case Builtin::BI__sync_or_and_fetch_1: 1370 case Builtin::BI__sync_or_and_fetch_2: 1371 case Builtin::BI__sync_or_and_fetch_4: 1372 case Builtin::BI__sync_or_and_fetch_8: 1373 case Builtin::BI__sync_or_and_fetch_16: 1374 case Builtin::BI__sync_xor_and_fetch: 1375 case Builtin::BI__sync_xor_and_fetch_1: 1376 case Builtin::BI__sync_xor_and_fetch_2: 1377 case Builtin::BI__sync_xor_and_fetch_4: 1378 case Builtin::BI__sync_xor_and_fetch_8: 1379 case Builtin::BI__sync_xor_and_fetch_16: 1380 case Builtin::BI__sync_nand_and_fetch: 1381 case Builtin::BI__sync_nand_and_fetch_1: 1382 case Builtin::BI__sync_nand_and_fetch_2: 1383 case Builtin::BI__sync_nand_and_fetch_4: 1384 case Builtin::BI__sync_nand_and_fetch_8: 1385 case Builtin::BI__sync_nand_and_fetch_16: 1386 case Builtin::BI__sync_val_compare_and_swap: 1387 case Builtin::BI__sync_val_compare_and_swap_1: 1388 case Builtin::BI__sync_val_compare_and_swap_2: 1389 case Builtin::BI__sync_val_compare_and_swap_4: 1390 case Builtin::BI__sync_val_compare_and_swap_8: 1391 case Builtin::BI__sync_val_compare_and_swap_16: 1392 case Builtin::BI__sync_bool_compare_and_swap: 1393 case Builtin::BI__sync_bool_compare_and_swap_1: 1394 case Builtin::BI__sync_bool_compare_and_swap_2: 1395 case Builtin::BI__sync_bool_compare_and_swap_4: 1396 case Builtin::BI__sync_bool_compare_and_swap_8: 1397 case Builtin::BI__sync_bool_compare_and_swap_16: 1398 case Builtin::BI__sync_lock_test_and_set: 1399 case Builtin::BI__sync_lock_test_and_set_1: 1400 case Builtin::BI__sync_lock_test_and_set_2: 1401 case Builtin::BI__sync_lock_test_and_set_4: 1402 case Builtin::BI__sync_lock_test_and_set_8: 1403 case Builtin::BI__sync_lock_test_and_set_16: 1404 case Builtin::BI__sync_lock_release: 1405 case Builtin::BI__sync_lock_release_1: 1406 case Builtin::BI__sync_lock_release_2: 1407 case Builtin::BI__sync_lock_release_4: 1408 case Builtin::BI__sync_lock_release_8: 1409 case Builtin::BI__sync_lock_release_16: 1410 case Builtin::BI__sync_swap: 1411 case Builtin::BI__sync_swap_1: 1412 case Builtin::BI__sync_swap_2: 1413 case Builtin::BI__sync_swap_4: 1414 case Builtin::BI__sync_swap_8: 1415 case Builtin::BI__sync_swap_16: 1416 return SemaBuiltinAtomicOverloaded(TheCallResult); 1417 case Builtin::BI__sync_synchronize: 1418 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1419 << TheCall->getCallee()->getSourceRange(); 1420 break; 1421 case Builtin::BI__builtin_nontemporal_load: 1422 case Builtin::BI__builtin_nontemporal_store: 1423 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1424 #define BUILTIN(ID, TYPE, ATTRS) 1425 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1426 case Builtin::BI##ID: \ 1427 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1428 #include "clang/Basic/Builtins.def" 1429 case Builtin::BI__annotation: 1430 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1431 return ExprError(); 1432 break; 1433 case Builtin::BI__builtin_annotation: 1434 if (SemaBuiltinAnnotation(*this, TheCall)) 1435 return ExprError(); 1436 break; 1437 case Builtin::BI__builtin_addressof: 1438 if (SemaBuiltinAddressof(*this, TheCall)) 1439 return ExprError(); 1440 break; 1441 case Builtin::BI__builtin_is_aligned: 1442 case Builtin::BI__builtin_align_up: 1443 case Builtin::BI__builtin_align_down: 1444 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1445 return ExprError(); 1446 break; 1447 case Builtin::BI__builtin_add_overflow: 1448 case Builtin::BI__builtin_sub_overflow: 1449 case Builtin::BI__builtin_mul_overflow: 1450 if (SemaBuiltinOverflow(*this, TheCall)) 1451 return ExprError(); 1452 break; 1453 case Builtin::BI__builtin_operator_new: 1454 case Builtin::BI__builtin_operator_delete: { 1455 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1456 ExprResult Res = 1457 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1458 if (Res.isInvalid()) 1459 CorrectDelayedTyposInExpr(TheCallResult.get()); 1460 return Res; 1461 } 1462 case Builtin::BI__builtin_dump_struct: { 1463 // We first want to ensure we are called with 2 arguments 1464 if (checkArgCount(*this, TheCall, 2)) 1465 return ExprError(); 1466 // Ensure that the first argument is of type 'struct XX *' 1467 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1468 const QualType PtrArgType = PtrArg->getType(); 1469 if (!PtrArgType->isPointerType() || 1470 !PtrArgType->getPointeeType()->isRecordType()) { 1471 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1472 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1473 << "structure pointer"; 1474 return ExprError(); 1475 } 1476 1477 // Ensure that the second argument is of type 'FunctionType' 1478 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1479 const QualType FnPtrArgType = FnPtrArg->getType(); 1480 if (!FnPtrArgType->isPointerType()) { 1481 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1482 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1483 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1484 return ExprError(); 1485 } 1486 1487 const auto *FuncType = 1488 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1489 1490 if (!FuncType) { 1491 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1492 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1493 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1494 return ExprError(); 1495 } 1496 1497 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1498 if (!FT->getNumParams()) { 1499 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1500 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1501 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1502 return ExprError(); 1503 } 1504 QualType PT = FT->getParamType(0); 1505 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1506 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1507 !PT->getPointeeType().isConstQualified()) { 1508 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1509 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1510 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1511 return ExprError(); 1512 } 1513 } 1514 1515 TheCall->setType(Context.IntTy); 1516 break; 1517 } 1518 case Builtin::BI__builtin_preserve_access_index: 1519 if (SemaBuiltinPreserveAI(*this, TheCall)) 1520 return ExprError(); 1521 break; 1522 case Builtin::BI__builtin_call_with_static_chain: 1523 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1524 return ExprError(); 1525 break; 1526 case Builtin::BI__exception_code: 1527 case Builtin::BI_exception_code: 1528 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1529 diag::err_seh___except_block)) 1530 return ExprError(); 1531 break; 1532 case Builtin::BI__exception_info: 1533 case Builtin::BI_exception_info: 1534 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1535 diag::err_seh___except_filter)) 1536 return ExprError(); 1537 break; 1538 case Builtin::BI__GetExceptionInfo: 1539 if (checkArgCount(*this, TheCall, 1)) 1540 return ExprError(); 1541 1542 if (CheckCXXThrowOperand( 1543 TheCall->getBeginLoc(), 1544 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1545 TheCall)) 1546 return ExprError(); 1547 1548 TheCall->setType(Context.VoidPtrTy); 1549 break; 1550 // OpenCL v2.0, s6.13.16 - Pipe functions 1551 case Builtin::BIread_pipe: 1552 case Builtin::BIwrite_pipe: 1553 // Since those two functions are declared with var args, we need a semantic 1554 // check for the argument. 1555 if (SemaBuiltinRWPipe(*this, TheCall)) 1556 return ExprError(); 1557 break; 1558 case Builtin::BIreserve_read_pipe: 1559 case Builtin::BIreserve_write_pipe: 1560 case Builtin::BIwork_group_reserve_read_pipe: 1561 case Builtin::BIwork_group_reserve_write_pipe: 1562 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1563 return ExprError(); 1564 break; 1565 case Builtin::BIsub_group_reserve_read_pipe: 1566 case Builtin::BIsub_group_reserve_write_pipe: 1567 if (checkOpenCLSubgroupExt(*this, TheCall) || 1568 SemaBuiltinReserveRWPipe(*this, TheCall)) 1569 return ExprError(); 1570 break; 1571 case Builtin::BIcommit_read_pipe: 1572 case Builtin::BIcommit_write_pipe: 1573 case Builtin::BIwork_group_commit_read_pipe: 1574 case Builtin::BIwork_group_commit_write_pipe: 1575 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1576 return ExprError(); 1577 break; 1578 case Builtin::BIsub_group_commit_read_pipe: 1579 case Builtin::BIsub_group_commit_write_pipe: 1580 if (checkOpenCLSubgroupExt(*this, TheCall) || 1581 SemaBuiltinCommitRWPipe(*this, TheCall)) 1582 return ExprError(); 1583 break; 1584 case Builtin::BIget_pipe_num_packets: 1585 case Builtin::BIget_pipe_max_packets: 1586 if (SemaBuiltinPipePackets(*this, TheCall)) 1587 return ExprError(); 1588 break; 1589 case Builtin::BIto_global: 1590 case Builtin::BIto_local: 1591 case Builtin::BIto_private: 1592 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1593 return ExprError(); 1594 break; 1595 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1596 case Builtin::BIenqueue_kernel: 1597 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1598 return ExprError(); 1599 break; 1600 case Builtin::BIget_kernel_work_group_size: 1601 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1602 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1603 return ExprError(); 1604 break; 1605 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1606 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1607 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1608 return ExprError(); 1609 break; 1610 case Builtin::BI__builtin_os_log_format: 1611 case Builtin::BI__builtin_os_log_format_buffer_size: 1612 if (SemaBuiltinOSLogFormat(TheCall)) 1613 return ExprError(); 1614 break; 1615 } 1616 1617 // Since the target specific builtins for each arch overlap, only check those 1618 // of the arch we are compiling for. 1619 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1620 switch (Context.getTargetInfo().getTriple().getArch()) { 1621 case llvm::Triple::arm: 1622 case llvm::Triple::armeb: 1623 case llvm::Triple::thumb: 1624 case llvm::Triple::thumbeb: 1625 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1626 return ExprError(); 1627 break; 1628 case llvm::Triple::aarch64: 1629 case llvm::Triple::aarch64_32: 1630 case llvm::Triple::aarch64_be: 1631 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1632 return ExprError(); 1633 break; 1634 case llvm::Triple::bpfeb: 1635 case llvm::Triple::bpfel: 1636 if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall)) 1637 return ExprError(); 1638 break; 1639 case llvm::Triple::hexagon: 1640 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1641 return ExprError(); 1642 break; 1643 case llvm::Triple::mips: 1644 case llvm::Triple::mipsel: 1645 case llvm::Triple::mips64: 1646 case llvm::Triple::mips64el: 1647 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1648 return ExprError(); 1649 break; 1650 case llvm::Triple::systemz: 1651 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1652 return ExprError(); 1653 break; 1654 case llvm::Triple::x86: 1655 case llvm::Triple::x86_64: 1656 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1657 return ExprError(); 1658 break; 1659 case llvm::Triple::ppc: 1660 case llvm::Triple::ppc64: 1661 case llvm::Triple::ppc64le: 1662 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1663 return ExprError(); 1664 break; 1665 default: 1666 break; 1667 } 1668 } 1669 1670 return TheCallResult; 1671 } 1672 1673 // Get the valid immediate range for the specified NEON type code. 1674 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1675 NeonTypeFlags Type(t); 1676 int IsQuad = ForceQuad ? true : Type.isQuad(); 1677 switch (Type.getEltType()) { 1678 case NeonTypeFlags::Int8: 1679 case NeonTypeFlags::Poly8: 1680 return shift ? 7 : (8 << IsQuad) - 1; 1681 case NeonTypeFlags::Int16: 1682 case NeonTypeFlags::Poly16: 1683 return shift ? 15 : (4 << IsQuad) - 1; 1684 case NeonTypeFlags::Int32: 1685 return shift ? 31 : (2 << IsQuad) - 1; 1686 case NeonTypeFlags::Int64: 1687 case NeonTypeFlags::Poly64: 1688 return shift ? 63 : (1 << IsQuad) - 1; 1689 case NeonTypeFlags::Poly128: 1690 return shift ? 127 : (1 << IsQuad) - 1; 1691 case NeonTypeFlags::Float16: 1692 assert(!shift && "cannot shift float types!"); 1693 return (4 << IsQuad) - 1; 1694 case NeonTypeFlags::Float32: 1695 assert(!shift && "cannot shift float types!"); 1696 return (2 << IsQuad) - 1; 1697 case NeonTypeFlags::Float64: 1698 assert(!shift && "cannot shift float types!"); 1699 return (1 << IsQuad) - 1; 1700 } 1701 llvm_unreachable("Invalid NeonTypeFlag!"); 1702 } 1703 1704 /// getNeonEltType - Return the QualType corresponding to the elements of 1705 /// the vector type specified by the NeonTypeFlags. This is used to check 1706 /// the pointer arguments for Neon load/store intrinsics. 1707 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1708 bool IsPolyUnsigned, bool IsInt64Long) { 1709 switch (Flags.getEltType()) { 1710 case NeonTypeFlags::Int8: 1711 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1712 case NeonTypeFlags::Int16: 1713 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1714 case NeonTypeFlags::Int32: 1715 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1716 case NeonTypeFlags::Int64: 1717 if (IsInt64Long) 1718 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1719 else 1720 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1721 : Context.LongLongTy; 1722 case NeonTypeFlags::Poly8: 1723 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1724 case NeonTypeFlags::Poly16: 1725 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1726 case NeonTypeFlags::Poly64: 1727 if (IsInt64Long) 1728 return Context.UnsignedLongTy; 1729 else 1730 return Context.UnsignedLongLongTy; 1731 case NeonTypeFlags::Poly128: 1732 break; 1733 case NeonTypeFlags::Float16: 1734 return Context.HalfTy; 1735 case NeonTypeFlags::Float32: 1736 return Context.FloatTy; 1737 case NeonTypeFlags::Float64: 1738 return Context.DoubleTy; 1739 } 1740 llvm_unreachable("Invalid NeonTypeFlag!"); 1741 } 1742 1743 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1744 llvm::APSInt Result; 1745 uint64_t mask = 0; 1746 unsigned TV = 0; 1747 int PtrArgNum = -1; 1748 bool HasConstPtr = false; 1749 switch (BuiltinID) { 1750 #define GET_NEON_OVERLOAD_CHECK 1751 #include "clang/Basic/arm_neon.inc" 1752 #include "clang/Basic/arm_fp16.inc" 1753 #undef GET_NEON_OVERLOAD_CHECK 1754 } 1755 1756 // For NEON intrinsics which are overloaded on vector element type, validate 1757 // the immediate which specifies which variant to emit. 1758 unsigned ImmArg = TheCall->getNumArgs()-1; 1759 if (mask) { 1760 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1761 return true; 1762 1763 TV = Result.getLimitedValue(64); 1764 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1765 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1766 << TheCall->getArg(ImmArg)->getSourceRange(); 1767 } 1768 1769 if (PtrArgNum >= 0) { 1770 // Check that pointer arguments have the specified type. 1771 Expr *Arg = TheCall->getArg(PtrArgNum); 1772 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1773 Arg = ICE->getSubExpr(); 1774 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1775 QualType RHSTy = RHS.get()->getType(); 1776 1777 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1778 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1779 Arch == llvm::Triple::aarch64_32 || 1780 Arch == llvm::Triple::aarch64_be; 1781 bool IsInt64Long = 1782 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1783 QualType EltTy = 1784 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1785 if (HasConstPtr) 1786 EltTy = EltTy.withConst(); 1787 QualType LHSTy = Context.getPointerType(EltTy); 1788 AssignConvertType ConvTy; 1789 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1790 if (RHS.isInvalid()) 1791 return true; 1792 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1793 RHS.get(), AA_Assigning)) 1794 return true; 1795 } 1796 1797 // For NEON intrinsics which take an immediate value as part of the 1798 // instruction, range check them here. 1799 unsigned i = 0, l = 0, u = 0; 1800 switch (BuiltinID) { 1801 default: 1802 return false; 1803 #define GET_NEON_IMMEDIATE_CHECK 1804 #include "clang/Basic/arm_neon.inc" 1805 #include "clang/Basic/arm_fp16.inc" 1806 #undef GET_NEON_IMMEDIATE_CHECK 1807 } 1808 1809 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1810 } 1811 1812 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1813 switch (BuiltinID) { 1814 default: 1815 return false; 1816 #include "clang/Basic/arm_mve_builtin_sema.inc" 1817 } 1818 } 1819 1820 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1821 unsigned MaxWidth) { 1822 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1823 BuiltinID == ARM::BI__builtin_arm_ldaex || 1824 BuiltinID == ARM::BI__builtin_arm_strex || 1825 BuiltinID == ARM::BI__builtin_arm_stlex || 1826 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1827 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1828 BuiltinID == AArch64::BI__builtin_arm_strex || 1829 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1830 "unexpected ARM builtin"); 1831 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1832 BuiltinID == ARM::BI__builtin_arm_ldaex || 1833 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1834 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1835 1836 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1837 1838 // Ensure that we have the proper number of arguments. 1839 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1840 return true; 1841 1842 // Inspect the pointer argument of the atomic builtin. This should always be 1843 // a pointer type, whose element is an integral scalar or pointer type. 1844 // Because it is a pointer type, we don't have to worry about any implicit 1845 // casts here. 1846 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1847 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1848 if (PointerArgRes.isInvalid()) 1849 return true; 1850 PointerArg = PointerArgRes.get(); 1851 1852 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1853 if (!pointerType) { 1854 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1855 << PointerArg->getType() << PointerArg->getSourceRange(); 1856 return true; 1857 } 1858 1859 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1860 // task is to insert the appropriate casts into the AST. First work out just 1861 // what the appropriate type is. 1862 QualType ValType = pointerType->getPointeeType(); 1863 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1864 if (IsLdrex) 1865 AddrType.addConst(); 1866 1867 // Issue a warning if the cast is dodgy. 1868 CastKind CastNeeded = CK_NoOp; 1869 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1870 CastNeeded = CK_BitCast; 1871 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1872 << PointerArg->getType() << Context.getPointerType(AddrType) 1873 << AA_Passing << PointerArg->getSourceRange(); 1874 } 1875 1876 // Finally, do the cast and replace the argument with the corrected version. 1877 AddrType = Context.getPointerType(AddrType); 1878 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1879 if (PointerArgRes.isInvalid()) 1880 return true; 1881 PointerArg = PointerArgRes.get(); 1882 1883 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1884 1885 // In general, we allow ints, floats and pointers to be loaded and stored. 1886 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1887 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1888 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1889 << PointerArg->getType() << PointerArg->getSourceRange(); 1890 return true; 1891 } 1892 1893 // But ARM doesn't have instructions to deal with 128-bit versions. 1894 if (Context.getTypeSize(ValType) > MaxWidth) { 1895 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1896 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1897 << PointerArg->getType() << PointerArg->getSourceRange(); 1898 return true; 1899 } 1900 1901 switch (ValType.getObjCLifetime()) { 1902 case Qualifiers::OCL_None: 1903 case Qualifiers::OCL_ExplicitNone: 1904 // okay 1905 break; 1906 1907 case Qualifiers::OCL_Weak: 1908 case Qualifiers::OCL_Strong: 1909 case Qualifiers::OCL_Autoreleasing: 1910 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1911 << ValType << PointerArg->getSourceRange(); 1912 return true; 1913 } 1914 1915 if (IsLdrex) { 1916 TheCall->setType(ValType); 1917 return false; 1918 } 1919 1920 // Initialize the argument to be stored. 1921 ExprResult ValArg = TheCall->getArg(0); 1922 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1923 Context, ValType, /*consume*/ false); 1924 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1925 if (ValArg.isInvalid()) 1926 return true; 1927 TheCall->setArg(0, ValArg.get()); 1928 1929 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1930 // but the custom checker bypasses all default analysis. 1931 TheCall->setType(Context.IntTy); 1932 return false; 1933 } 1934 1935 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1936 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1937 BuiltinID == ARM::BI__builtin_arm_ldaex || 1938 BuiltinID == ARM::BI__builtin_arm_strex || 1939 BuiltinID == ARM::BI__builtin_arm_stlex) { 1940 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1941 } 1942 1943 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1944 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1945 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1946 } 1947 1948 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1949 BuiltinID == ARM::BI__builtin_arm_wsr64) 1950 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1951 1952 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1953 BuiltinID == ARM::BI__builtin_arm_rsrp || 1954 BuiltinID == ARM::BI__builtin_arm_wsr || 1955 BuiltinID == ARM::BI__builtin_arm_wsrp) 1956 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1957 1958 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1959 return true; 1960 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 1961 return true; 1962 1963 // For intrinsics which take an immediate value as part of the instruction, 1964 // range check them here. 1965 // FIXME: VFP Intrinsics should error if VFP not present. 1966 switch (BuiltinID) { 1967 default: return false; 1968 case ARM::BI__builtin_arm_ssat: 1969 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1970 case ARM::BI__builtin_arm_usat: 1971 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1972 case ARM::BI__builtin_arm_ssat16: 1973 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1974 case ARM::BI__builtin_arm_usat16: 1975 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1976 case ARM::BI__builtin_arm_vcvtr_f: 1977 case ARM::BI__builtin_arm_vcvtr_d: 1978 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1979 case ARM::BI__builtin_arm_dmb: 1980 case ARM::BI__builtin_arm_dsb: 1981 case ARM::BI__builtin_arm_isb: 1982 case ARM::BI__builtin_arm_dbg: 1983 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1984 } 1985 } 1986 1987 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1988 CallExpr *TheCall) { 1989 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1990 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1991 BuiltinID == AArch64::BI__builtin_arm_strex || 1992 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1993 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1994 } 1995 1996 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1997 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1998 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1999 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2000 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2001 } 2002 2003 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2004 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2005 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2006 2007 // Memory Tagging Extensions (MTE) Intrinsics 2008 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2009 BuiltinID == AArch64::BI__builtin_arm_addg || 2010 BuiltinID == AArch64::BI__builtin_arm_gmi || 2011 BuiltinID == AArch64::BI__builtin_arm_ldg || 2012 BuiltinID == AArch64::BI__builtin_arm_stg || 2013 BuiltinID == AArch64::BI__builtin_arm_subp) { 2014 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2015 } 2016 2017 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2018 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2019 BuiltinID == AArch64::BI__builtin_arm_wsr || 2020 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2021 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2022 2023 // Only check the valid encoding range. Any constant in this range would be 2024 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2025 // an exception for incorrect registers. This matches MSVC behavior. 2026 if (BuiltinID == AArch64::BI_ReadStatusReg || 2027 BuiltinID == AArch64::BI_WriteStatusReg) 2028 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2029 2030 if (BuiltinID == AArch64::BI__getReg) 2031 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2032 2033 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2034 return true; 2035 2036 // For intrinsics which take an immediate value as part of the instruction, 2037 // range check them here. 2038 unsigned i = 0, l = 0, u = 0; 2039 switch (BuiltinID) { 2040 default: return false; 2041 case AArch64::BI__builtin_arm_dmb: 2042 case AArch64::BI__builtin_arm_dsb: 2043 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2044 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2045 } 2046 2047 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2048 } 2049 2050 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2051 CallExpr *TheCall) { 2052 assert(BuiltinID == BPF::BI__builtin_preserve_field_info && 2053 "unexpected ARM builtin"); 2054 2055 if (checkArgCount(*this, TheCall, 2)) 2056 return true; 2057 2058 // The first argument needs to be a record field access. 2059 // If it is an array element access, we delay decision 2060 // to BPF backend to check whether the access is a 2061 // field access or not. 2062 Expr *Arg = TheCall->getArg(0); 2063 if (Arg->getType()->getAsPlaceholderType() || 2064 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2065 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2066 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2067 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2068 << 1 << Arg->getSourceRange(); 2069 return true; 2070 } 2071 2072 // The second argument needs to be a constant int 2073 llvm::APSInt Value; 2074 if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) { 2075 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2076 << 2 << Arg->getSourceRange(); 2077 return true; 2078 } 2079 2080 TheCall->setType(Context.UnsignedIntTy); 2081 return false; 2082 } 2083 2084 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 2085 struct BuiltinAndString { 2086 unsigned BuiltinID; 2087 const char *Str; 2088 }; 2089 2090 static BuiltinAndString ValidCPU[] = { 2091 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" }, 2092 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" }, 2093 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" }, 2094 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" }, 2095 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" }, 2096 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" }, 2097 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" }, 2098 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" }, 2099 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" }, 2100 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" }, 2101 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" }, 2102 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" }, 2103 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" }, 2104 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" }, 2105 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" }, 2106 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" }, 2107 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" }, 2108 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" }, 2109 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" }, 2110 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" }, 2111 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" }, 2112 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" }, 2113 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" }, 2114 }; 2115 2116 static BuiltinAndString ValidHVX[] = { 2117 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" }, 2526 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" }, 2527 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" }, 2528 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" }, 2529 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" }, 2530 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" }, 2531 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" }, 2532 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" }, 2533 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" }, 2534 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" }, 2535 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" }, 2536 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" }, 2537 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" }, 2538 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" }, 2539 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" }, 2540 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" }, 2541 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" }, 2542 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" }, 2543 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" }, 2544 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" }, 2545 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" }, 2546 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" }, 2547 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" }, 2548 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" }, 2549 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" }, 2550 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" }, 2551 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" }, 2552 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" }, 2553 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" }, 2554 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" }, 2555 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" }, 2556 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" }, 2557 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" }, 2558 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" }, 2559 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" }, 2560 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" }, 2561 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" }, 2562 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" }, 2563 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" }, 2564 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" }, 2565 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" }, 2566 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2567 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" }, 2568 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" }, 2569 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" }, 2570 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" }, 2571 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" }, 2572 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" }, 2573 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" }, 2574 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" }, 2575 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" }, 2576 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" }, 2577 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" }, 2578 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" }, 2579 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" }, 2580 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" }, 2581 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" }, 2582 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" }, 2583 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" }, 2584 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" }, 2585 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" }, 2586 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" }, 2587 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" }, 2588 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" }, 2589 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" }, 2590 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" }, 2591 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" }, 2592 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" }, 2593 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" }, 2594 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" }, 2595 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" }, 2596 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" }, 2597 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" }, 2598 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" }, 2599 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" }, 2600 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" }, 2601 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" }, 2602 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" }, 2603 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" }, 2604 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" }, 2605 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" }, 2606 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" }, 2607 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" }, 2608 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" }, 2609 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" }, 2610 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" }, 2611 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" }, 2612 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" }, 2613 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" }, 2614 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" }, 2615 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" }, 2616 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" }, 2617 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" }, 2618 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" }, 2619 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" }, 2620 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" }, 2621 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" }, 2622 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" }, 2623 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" }, 2624 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" }, 2625 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" }, 2626 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" }, 2627 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" }, 2628 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" }, 2629 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" }, 2630 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" }, 2631 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" }, 2632 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" }, 2633 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" }, 2634 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" }, 2635 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" }, 2636 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" }, 2637 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" }, 2638 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" }, 2639 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" }, 2640 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" }, 2641 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" }, 2642 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" }, 2643 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" }, 2644 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" }, 2645 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" }, 2646 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" }, 2647 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" }, 2648 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" }, 2649 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" }, 2650 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" }, 2651 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" }, 2652 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" }, 2653 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" }, 2654 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" }, 2655 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" }, 2656 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" }, 2657 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" }, 2658 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" }, 2659 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" }, 2660 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" }, 2661 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" }, 2662 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" }, 2663 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" }, 2664 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" }, 2665 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" }, 2666 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" }, 2667 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" }, 2668 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" }, 2669 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" }, 2670 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" }, 2671 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" }, 2672 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" }, 2673 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" }, 2674 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" }, 2675 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" }, 2676 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" }, 2677 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" }, 2678 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" }, 2679 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" }, 2680 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" }, 2681 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" }, 2682 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" }, 2683 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" }, 2684 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" }, 2685 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, 2686 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, 2687 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, 2688 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, 2689 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" }, 2690 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" }, 2691 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" }, 2692 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" }, 2693 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" }, 2694 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" }, 2695 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" }, 2696 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" }, 2697 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" }, 2698 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" }, 2699 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" }, 2700 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" }, 2701 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" }, 2702 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" }, 2703 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" }, 2704 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" }, 2705 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" }, 2706 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" }, 2707 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" }, 2708 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" }, 2709 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" }, 2710 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" }, 2711 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" }, 2712 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" }, 2713 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, 2714 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, 2715 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, 2716 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, 2717 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" }, 2718 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" }, 2719 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" }, 2720 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" }, 2721 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" }, 2722 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" }, 2723 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" }, 2724 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" }, 2725 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" }, 2726 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" }, 2727 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" }, 2728 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" }, 2729 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" }, 2730 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" }, 2731 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" }, 2732 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" }, 2733 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" }, 2734 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" }, 2735 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" }, 2736 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" }, 2737 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" }, 2738 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" }, 2739 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" }, 2740 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" }, 2741 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" }, 2742 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" }, 2743 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" }, 2744 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" }, 2745 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" }, 2746 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" }, 2747 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" }, 2748 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" }, 2749 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" }, 2750 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" }, 2751 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" }, 2752 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" }, 2753 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" }, 2754 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" }, 2755 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" }, 2756 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" }, 2757 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" }, 2758 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" }, 2759 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" }, 2760 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" }, 2761 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" }, 2762 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" }, 2763 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" }, 2764 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" }, 2765 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" }, 2766 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" }, 2767 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" }, 2768 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" }, 2769 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" }, 2770 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" }, 2771 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" }, 2772 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" }, 2773 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" }, 2774 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" }, 2775 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" }, 2776 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" }, 2777 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" }, 2778 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" }, 2779 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" }, 2780 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" }, 2781 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" }, 2782 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" }, 2783 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" }, 2784 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" }, 2785 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" }, 2786 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" }, 2787 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" }, 2788 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" }, 2789 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" }, 2790 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" }, 2791 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" }, 2792 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" }, 2793 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" }, 2794 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" }, 2795 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" }, 2796 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" }, 2797 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" }, 2798 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" }, 2799 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" }, 2800 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" }, 2801 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" }, 2802 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" }, 2803 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" }, 2804 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" }, 2805 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" }, 2806 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" }, 2807 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" }, 2808 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" }, 2809 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" }, 2810 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" }, 2811 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" }, 2812 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" }, 2813 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" }, 2814 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" }, 2815 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" }, 2816 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" }, 2817 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" }, 2818 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" }, 2819 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" }, 2820 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" }, 2821 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" }, 2822 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" }, 2823 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" }, 2824 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" }, 2825 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" }, 2826 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" }, 2827 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" }, 2828 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" }, 2829 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" }, 2830 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" }, 2831 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" }, 2832 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" }, 2833 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" }, 2834 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" }, 2835 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" }, 2836 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" }, 2837 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" }, 2838 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" }, 2839 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" }, 2840 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" }, 2841 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" }, 2842 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" }, 2843 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" }, 2844 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" }, 2845 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" }, 2846 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" }, 2847 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" }, 2848 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" }, 2849 }; 2850 2851 // Sort the tables on first execution so we can binary search them. 2852 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { 2853 return LHS.BuiltinID < RHS.BuiltinID; 2854 }; 2855 static const bool SortOnce = 2856 (llvm::sort(ValidCPU, SortCmp), 2857 llvm::sort(ValidHVX, SortCmp), true); 2858 (void)SortOnce; 2859 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { 2860 return BI.BuiltinID < BuiltinID; 2861 }; 2862 2863 const TargetInfo &TI = Context.getTargetInfo(); 2864 2865 const BuiltinAndString *FC = 2866 llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp); 2867 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { 2868 const TargetOptions &Opts = TI.getTargetOpts(); 2869 StringRef CPU = Opts.CPU; 2870 if (!CPU.empty()) { 2871 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2872 CPU.consume_front("hexagon"); 2873 SmallVector<StringRef, 3> CPUs; 2874 StringRef(FC->Str).split(CPUs, ','); 2875 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) 2876 return Diag(TheCall->getBeginLoc(), 2877 diag::err_hexagon_builtin_unsupported_cpu); 2878 } 2879 } 2880 2881 const BuiltinAndString *FH = 2882 llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp); 2883 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { 2884 if (!TI.hasFeature("hvx")) 2885 return Diag(TheCall->getBeginLoc(), 2886 diag::err_hexagon_builtin_requires_hvx); 2887 2888 SmallVector<StringRef, 3> HVXs; 2889 StringRef(FH->Str).split(HVXs, ','); 2890 bool IsValid = llvm::any_of(HVXs, 2891 [&TI] (StringRef V) { 2892 std::string F = "hvx" + V.str(); 2893 return TI.hasFeature(F); 2894 }); 2895 if (!IsValid) 2896 return Diag(TheCall->getBeginLoc(), 2897 diag::err_hexagon_builtin_unsupported_hvx); 2898 } 2899 2900 return false; 2901 } 2902 2903 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2904 struct ArgInfo { 2905 uint8_t OpNum; 2906 bool IsSigned; 2907 uint8_t BitWidth; 2908 uint8_t Align; 2909 }; 2910 struct BuiltinInfo { 2911 unsigned BuiltinID; 2912 ArgInfo Infos[2]; 2913 }; 2914 2915 static BuiltinInfo Infos[] = { 2916 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2917 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2918 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2919 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2920 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2921 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2922 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2923 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2924 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2925 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2926 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2927 2928 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2939 2940 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2948 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2950 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2953 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2955 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2956 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2957 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2958 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2959 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2960 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2961 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2962 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2963 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2964 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2965 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2966 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2967 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2968 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2969 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2970 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2971 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2972 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2973 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2974 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2975 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2976 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2977 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2978 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2979 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2980 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2981 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2982 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2983 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2984 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2985 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2986 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2987 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2988 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2989 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2990 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2991 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2992 {{ 1, false, 6, 0 }} }, 2993 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2994 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2995 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2996 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2997 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2998 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2999 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 3000 {{ 1, false, 5, 0 }} }, 3001 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 3002 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 3003 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 3004 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 3005 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 3006 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 3007 { 2, false, 5, 0 }} }, 3008 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 3009 { 2, false, 6, 0 }} }, 3010 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 3011 { 3, false, 5, 0 }} }, 3012 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 3013 { 3, false, 6, 0 }} }, 3014 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 3015 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 3016 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 3017 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 3018 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 3019 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 3020 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 3021 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 3022 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 3023 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 3024 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 3025 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 3026 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 3027 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 3028 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 3029 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 3030 {{ 2, false, 4, 0 }, 3031 { 3, false, 5, 0 }} }, 3032 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 3033 {{ 2, false, 4, 0 }, 3034 { 3, false, 5, 0 }} }, 3035 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 3036 {{ 2, false, 4, 0 }, 3037 { 3, false, 5, 0 }} }, 3038 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 3039 {{ 2, false, 4, 0 }, 3040 { 3, false, 5, 0 }} }, 3041 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 3042 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 3043 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 3044 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 3045 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 3046 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 3047 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 3048 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 3049 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 3050 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 3051 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 3052 { 2, false, 5, 0 }} }, 3053 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 3054 { 2, false, 6, 0 }} }, 3055 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 3056 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 3057 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 3058 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 3059 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 3060 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 3061 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 3062 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 3063 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 3064 {{ 1, false, 4, 0 }} }, 3065 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 3066 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 3067 {{ 1, false, 4, 0 }} }, 3068 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 3069 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 3070 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 3071 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 3072 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 3073 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 3074 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 3075 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 3076 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 3077 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 3078 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 3079 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 3080 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 3081 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 3082 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 3083 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 3084 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 3085 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 3086 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 3087 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 3088 {{ 3, false, 1, 0 }} }, 3089 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 3090 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 3091 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 3092 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 3093 {{ 3, false, 1, 0 }} }, 3094 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 3095 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 3096 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 3097 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 3098 {{ 3, false, 1, 0 }} }, 3099 }; 3100 3101 // Use a dynamically initialized static to sort the table exactly once on 3102 // first run. 3103 static const bool SortOnce = 3104 (llvm::sort(Infos, 3105 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 3106 return LHS.BuiltinID < RHS.BuiltinID; 3107 }), 3108 true); 3109 (void)SortOnce; 3110 3111 const BuiltinInfo *F = llvm::partition_point( 3112 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 3113 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 3114 return false; 3115 3116 bool Error = false; 3117 3118 for (const ArgInfo &A : F->Infos) { 3119 // Ignore empty ArgInfo elements. 3120 if (A.BitWidth == 0) 3121 continue; 3122 3123 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 3124 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 3125 if (!A.Align) { 3126 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3127 } else { 3128 unsigned M = 1 << A.Align; 3129 Min *= M; 3130 Max *= M; 3131 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 3132 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 3133 } 3134 } 3135 return Error; 3136 } 3137 3138 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3139 CallExpr *TheCall) { 3140 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 3141 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3142 } 3143 3144 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3145 return CheckMipsBuiltinCpu(BuiltinID, TheCall) || 3146 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3147 } 3148 3149 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 3150 const TargetInfo &TI = Context.getTargetInfo(); 3151 3152 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3153 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3154 if (!TI.hasFeature("dsp")) 3155 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3156 } 3157 3158 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3159 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3160 if (!TI.hasFeature("dspr2")) 3161 return Diag(TheCall->getBeginLoc(), 3162 diag::err_mips_builtin_requires_dspr2); 3163 } 3164 3165 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3166 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3167 if (!TI.hasFeature("msa")) 3168 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3169 } 3170 3171 return false; 3172 } 3173 3174 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3175 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3176 // ordering for DSP is unspecified. MSA is ordered by the data format used 3177 // by the underlying instruction i.e., df/m, df/n and then by size. 3178 // 3179 // FIXME: The size tests here should instead be tablegen'd along with the 3180 // definitions from include/clang/Basic/BuiltinsMips.def. 3181 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3182 // be too. 3183 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3184 unsigned i = 0, l = 0, u = 0, m = 0; 3185 switch (BuiltinID) { 3186 default: return false; 3187 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3188 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3189 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3190 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3191 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3192 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3193 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3194 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3195 // df/m field. 3196 // These intrinsics take an unsigned 3 bit immediate. 3197 case Mips::BI__builtin_msa_bclri_b: 3198 case Mips::BI__builtin_msa_bnegi_b: 3199 case Mips::BI__builtin_msa_bseti_b: 3200 case Mips::BI__builtin_msa_sat_s_b: 3201 case Mips::BI__builtin_msa_sat_u_b: 3202 case Mips::BI__builtin_msa_slli_b: 3203 case Mips::BI__builtin_msa_srai_b: 3204 case Mips::BI__builtin_msa_srari_b: 3205 case Mips::BI__builtin_msa_srli_b: 3206 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3207 case Mips::BI__builtin_msa_binsli_b: 3208 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3209 // These intrinsics take an unsigned 4 bit immediate. 3210 case Mips::BI__builtin_msa_bclri_h: 3211 case Mips::BI__builtin_msa_bnegi_h: 3212 case Mips::BI__builtin_msa_bseti_h: 3213 case Mips::BI__builtin_msa_sat_s_h: 3214 case Mips::BI__builtin_msa_sat_u_h: 3215 case Mips::BI__builtin_msa_slli_h: 3216 case Mips::BI__builtin_msa_srai_h: 3217 case Mips::BI__builtin_msa_srari_h: 3218 case Mips::BI__builtin_msa_srli_h: 3219 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3220 case Mips::BI__builtin_msa_binsli_h: 3221 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3222 // These intrinsics take an unsigned 5 bit immediate. 3223 // The first block of intrinsics actually have an unsigned 5 bit field, 3224 // not a df/n field. 3225 case Mips::BI__builtin_msa_cfcmsa: 3226 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3227 case Mips::BI__builtin_msa_clei_u_b: 3228 case Mips::BI__builtin_msa_clei_u_h: 3229 case Mips::BI__builtin_msa_clei_u_w: 3230 case Mips::BI__builtin_msa_clei_u_d: 3231 case Mips::BI__builtin_msa_clti_u_b: 3232 case Mips::BI__builtin_msa_clti_u_h: 3233 case Mips::BI__builtin_msa_clti_u_w: 3234 case Mips::BI__builtin_msa_clti_u_d: 3235 case Mips::BI__builtin_msa_maxi_u_b: 3236 case Mips::BI__builtin_msa_maxi_u_h: 3237 case Mips::BI__builtin_msa_maxi_u_w: 3238 case Mips::BI__builtin_msa_maxi_u_d: 3239 case Mips::BI__builtin_msa_mini_u_b: 3240 case Mips::BI__builtin_msa_mini_u_h: 3241 case Mips::BI__builtin_msa_mini_u_w: 3242 case Mips::BI__builtin_msa_mini_u_d: 3243 case Mips::BI__builtin_msa_addvi_b: 3244 case Mips::BI__builtin_msa_addvi_h: 3245 case Mips::BI__builtin_msa_addvi_w: 3246 case Mips::BI__builtin_msa_addvi_d: 3247 case Mips::BI__builtin_msa_bclri_w: 3248 case Mips::BI__builtin_msa_bnegi_w: 3249 case Mips::BI__builtin_msa_bseti_w: 3250 case Mips::BI__builtin_msa_sat_s_w: 3251 case Mips::BI__builtin_msa_sat_u_w: 3252 case Mips::BI__builtin_msa_slli_w: 3253 case Mips::BI__builtin_msa_srai_w: 3254 case Mips::BI__builtin_msa_srari_w: 3255 case Mips::BI__builtin_msa_srli_w: 3256 case Mips::BI__builtin_msa_srlri_w: 3257 case Mips::BI__builtin_msa_subvi_b: 3258 case Mips::BI__builtin_msa_subvi_h: 3259 case Mips::BI__builtin_msa_subvi_w: 3260 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3261 case Mips::BI__builtin_msa_binsli_w: 3262 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3263 // These intrinsics take an unsigned 6 bit immediate. 3264 case Mips::BI__builtin_msa_bclri_d: 3265 case Mips::BI__builtin_msa_bnegi_d: 3266 case Mips::BI__builtin_msa_bseti_d: 3267 case Mips::BI__builtin_msa_sat_s_d: 3268 case Mips::BI__builtin_msa_sat_u_d: 3269 case Mips::BI__builtin_msa_slli_d: 3270 case Mips::BI__builtin_msa_srai_d: 3271 case Mips::BI__builtin_msa_srari_d: 3272 case Mips::BI__builtin_msa_srli_d: 3273 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3274 case Mips::BI__builtin_msa_binsli_d: 3275 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3276 // These intrinsics take a signed 5 bit immediate. 3277 case Mips::BI__builtin_msa_ceqi_b: 3278 case Mips::BI__builtin_msa_ceqi_h: 3279 case Mips::BI__builtin_msa_ceqi_w: 3280 case Mips::BI__builtin_msa_ceqi_d: 3281 case Mips::BI__builtin_msa_clti_s_b: 3282 case Mips::BI__builtin_msa_clti_s_h: 3283 case Mips::BI__builtin_msa_clti_s_w: 3284 case Mips::BI__builtin_msa_clti_s_d: 3285 case Mips::BI__builtin_msa_clei_s_b: 3286 case Mips::BI__builtin_msa_clei_s_h: 3287 case Mips::BI__builtin_msa_clei_s_w: 3288 case Mips::BI__builtin_msa_clei_s_d: 3289 case Mips::BI__builtin_msa_maxi_s_b: 3290 case Mips::BI__builtin_msa_maxi_s_h: 3291 case Mips::BI__builtin_msa_maxi_s_w: 3292 case Mips::BI__builtin_msa_maxi_s_d: 3293 case Mips::BI__builtin_msa_mini_s_b: 3294 case Mips::BI__builtin_msa_mini_s_h: 3295 case Mips::BI__builtin_msa_mini_s_w: 3296 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3297 // These intrinsics take an unsigned 8 bit immediate. 3298 case Mips::BI__builtin_msa_andi_b: 3299 case Mips::BI__builtin_msa_nori_b: 3300 case Mips::BI__builtin_msa_ori_b: 3301 case Mips::BI__builtin_msa_shf_b: 3302 case Mips::BI__builtin_msa_shf_h: 3303 case Mips::BI__builtin_msa_shf_w: 3304 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3305 case Mips::BI__builtin_msa_bseli_b: 3306 case Mips::BI__builtin_msa_bmnzi_b: 3307 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3308 // df/n format 3309 // These intrinsics take an unsigned 4 bit immediate. 3310 case Mips::BI__builtin_msa_copy_s_b: 3311 case Mips::BI__builtin_msa_copy_u_b: 3312 case Mips::BI__builtin_msa_insve_b: 3313 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3314 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3315 // These intrinsics take an unsigned 3 bit immediate. 3316 case Mips::BI__builtin_msa_copy_s_h: 3317 case Mips::BI__builtin_msa_copy_u_h: 3318 case Mips::BI__builtin_msa_insve_h: 3319 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3320 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3321 // These intrinsics take an unsigned 2 bit immediate. 3322 case Mips::BI__builtin_msa_copy_s_w: 3323 case Mips::BI__builtin_msa_copy_u_w: 3324 case Mips::BI__builtin_msa_insve_w: 3325 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3326 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3327 // These intrinsics take an unsigned 1 bit immediate. 3328 case Mips::BI__builtin_msa_copy_s_d: 3329 case Mips::BI__builtin_msa_copy_u_d: 3330 case Mips::BI__builtin_msa_insve_d: 3331 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3332 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3333 // Memory offsets and immediate loads. 3334 // These intrinsics take a signed 10 bit immediate. 3335 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3336 case Mips::BI__builtin_msa_ldi_h: 3337 case Mips::BI__builtin_msa_ldi_w: 3338 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3339 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3340 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3341 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3342 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3343 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3344 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3345 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3346 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3347 } 3348 3349 if (!m) 3350 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3351 3352 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3353 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3354 } 3355 3356 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3357 unsigned i = 0, l = 0, u = 0; 3358 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3359 BuiltinID == PPC::BI__builtin_divdeu || 3360 BuiltinID == PPC::BI__builtin_bpermd; 3361 bool IsTarget64Bit = Context.getTargetInfo() 3362 .getTypeWidth(Context 3363 .getTargetInfo() 3364 .getIntPtrType()) == 64; 3365 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3366 BuiltinID == PPC::BI__builtin_divweu || 3367 BuiltinID == PPC::BI__builtin_divde || 3368 BuiltinID == PPC::BI__builtin_divdeu; 3369 3370 if (Is64BitBltin && !IsTarget64Bit) 3371 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3372 << TheCall->getSourceRange(); 3373 3374 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 3375 (BuiltinID == PPC::BI__builtin_bpermd && 3376 !Context.getTargetInfo().hasFeature("bpermd"))) 3377 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3378 << TheCall->getSourceRange(); 3379 3380 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3381 if (!Context.getTargetInfo().hasFeature("vsx")) 3382 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3383 << TheCall->getSourceRange(); 3384 return false; 3385 }; 3386 3387 switch (BuiltinID) { 3388 default: return false; 3389 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3390 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3391 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3392 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3393 case PPC::BI__builtin_altivec_dss: 3394 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3395 case PPC::BI__builtin_tbegin: 3396 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3397 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3398 case PPC::BI__builtin_tabortwc: 3399 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3400 case PPC::BI__builtin_tabortwci: 3401 case PPC::BI__builtin_tabortdci: 3402 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3403 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3404 case PPC::BI__builtin_altivec_dst: 3405 case PPC::BI__builtin_altivec_dstt: 3406 case PPC::BI__builtin_altivec_dstst: 3407 case PPC::BI__builtin_altivec_dststt: 3408 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3409 case PPC::BI__builtin_vsx_xxpermdi: 3410 case PPC::BI__builtin_vsx_xxsldwi: 3411 return SemaBuiltinVSX(TheCall); 3412 case PPC::BI__builtin_unpack_vector_int128: 3413 return SemaVSXCheck(TheCall) || 3414 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3415 case PPC::BI__builtin_pack_vector_int128: 3416 return SemaVSXCheck(TheCall); 3417 } 3418 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3419 } 3420 3421 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3422 CallExpr *TheCall) { 3423 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3424 Expr *Arg = TheCall->getArg(0); 3425 llvm::APSInt AbortCode(32); 3426 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3427 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3428 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3429 << Arg->getSourceRange(); 3430 } 3431 3432 // For intrinsics which take an immediate value as part of the instruction, 3433 // range check them here. 3434 unsigned i = 0, l = 0, u = 0; 3435 switch (BuiltinID) { 3436 default: return false; 3437 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3438 case SystemZ::BI__builtin_s390_verimb: 3439 case SystemZ::BI__builtin_s390_verimh: 3440 case SystemZ::BI__builtin_s390_verimf: 3441 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3442 case SystemZ::BI__builtin_s390_vfaeb: 3443 case SystemZ::BI__builtin_s390_vfaeh: 3444 case SystemZ::BI__builtin_s390_vfaef: 3445 case SystemZ::BI__builtin_s390_vfaebs: 3446 case SystemZ::BI__builtin_s390_vfaehs: 3447 case SystemZ::BI__builtin_s390_vfaefs: 3448 case SystemZ::BI__builtin_s390_vfaezb: 3449 case SystemZ::BI__builtin_s390_vfaezh: 3450 case SystemZ::BI__builtin_s390_vfaezf: 3451 case SystemZ::BI__builtin_s390_vfaezbs: 3452 case SystemZ::BI__builtin_s390_vfaezhs: 3453 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3454 case SystemZ::BI__builtin_s390_vfisb: 3455 case SystemZ::BI__builtin_s390_vfidb: 3456 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3457 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3458 case SystemZ::BI__builtin_s390_vftcisb: 3459 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3460 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3461 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3462 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3463 case SystemZ::BI__builtin_s390_vstrcb: 3464 case SystemZ::BI__builtin_s390_vstrch: 3465 case SystemZ::BI__builtin_s390_vstrcf: 3466 case SystemZ::BI__builtin_s390_vstrczb: 3467 case SystemZ::BI__builtin_s390_vstrczh: 3468 case SystemZ::BI__builtin_s390_vstrczf: 3469 case SystemZ::BI__builtin_s390_vstrcbs: 3470 case SystemZ::BI__builtin_s390_vstrchs: 3471 case SystemZ::BI__builtin_s390_vstrcfs: 3472 case SystemZ::BI__builtin_s390_vstrczbs: 3473 case SystemZ::BI__builtin_s390_vstrczhs: 3474 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3475 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3476 case SystemZ::BI__builtin_s390_vfminsb: 3477 case SystemZ::BI__builtin_s390_vfmaxsb: 3478 case SystemZ::BI__builtin_s390_vfmindb: 3479 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3480 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3481 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3482 } 3483 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3484 } 3485 3486 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3487 /// This checks that the target supports __builtin_cpu_supports and 3488 /// that the string argument is constant and valid. 3489 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3490 Expr *Arg = TheCall->getArg(0); 3491 3492 // Check if the argument is a string literal. 3493 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3494 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3495 << Arg->getSourceRange(); 3496 3497 // Check the contents of the string. 3498 StringRef Feature = 3499 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3500 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3501 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3502 << Arg->getSourceRange(); 3503 return false; 3504 } 3505 3506 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3507 /// This checks that the target supports __builtin_cpu_is and 3508 /// that the string argument is constant and valid. 3509 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3510 Expr *Arg = TheCall->getArg(0); 3511 3512 // Check if the argument is a string literal. 3513 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3514 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3515 << Arg->getSourceRange(); 3516 3517 // Check the contents of the string. 3518 StringRef Feature = 3519 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3520 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3521 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3522 << Arg->getSourceRange(); 3523 return false; 3524 } 3525 3526 // Check if the rounding mode is legal. 3527 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3528 // Indicates if this instruction has rounding control or just SAE. 3529 bool HasRC = false; 3530 3531 unsigned ArgNum = 0; 3532 switch (BuiltinID) { 3533 default: 3534 return false; 3535 case X86::BI__builtin_ia32_vcvttsd2si32: 3536 case X86::BI__builtin_ia32_vcvttsd2si64: 3537 case X86::BI__builtin_ia32_vcvttsd2usi32: 3538 case X86::BI__builtin_ia32_vcvttsd2usi64: 3539 case X86::BI__builtin_ia32_vcvttss2si32: 3540 case X86::BI__builtin_ia32_vcvttss2si64: 3541 case X86::BI__builtin_ia32_vcvttss2usi32: 3542 case X86::BI__builtin_ia32_vcvttss2usi64: 3543 ArgNum = 1; 3544 break; 3545 case X86::BI__builtin_ia32_maxpd512: 3546 case X86::BI__builtin_ia32_maxps512: 3547 case X86::BI__builtin_ia32_minpd512: 3548 case X86::BI__builtin_ia32_minps512: 3549 ArgNum = 2; 3550 break; 3551 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3552 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3553 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3554 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3555 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3556 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3557 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3558 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3559 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3560 case X86::BI__builtin_ia32_exp2pd_mask: 3561 case X86::BI__builtin_ia32_exp2ps_mask: 3562 case X86::BI__builtin_ia32_getexppd512_mask: 3563 case X86::BI__builtin_ia32_getexpps512_mask: 3564 case X86::BI__builtin_ia32_rcp28pd_mask: 3565 case X86::BI__builtin_ia32_rcp28ps_mask: 3566 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3567 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3568 case X86::BI__builtin_ia32_vcomisd: 3569 case X86::BI__builtin_ia32_vcomiss: 3570 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3571 ArgNum = 3; 3572 break; 3573 case X86::BI__builtin_ia32_cmppd512_mask: 3574 case X86::BI__builtin_ia32_cmpps512_mask: 3575 case X86::BI__builtin_ia32_cmpsd_mask: 3576 case X86::BI__builtin_ia32_cmpss_mask: 3577 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3578 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3579 case X86::BI__builtin_ia32_getexpss128_round_mask: 3580 case X86::BI__builtin_ia32_getmantpd512_mask: 3581 case X86::BI__builtin_ia32_getmantps512_mask: 3582 case X86::BI__builtin_ia32_maxsd_round_mask: 3583 case X86::BI__builtin_ia32_maxss_round_mask: 3584 case X86::BI__builtin_ia32_minsd_round_mask: 3585 case X86::BI__builtin_ia32_minss_round_mask: 3586 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3587 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3588 case X86::BI__builtin_ia32_reducepd512_mask: 3589 case X86::BI__builtin_ia32_reduceps512_mask: 3590 case X86::BI__builtin_ia32_rndscalepd_mask: 3591 case X86::BI__builtin_ia32_rndscaleps_mask: 3592 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3593 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3594 ArgNum = 4; 3595 break; 3596 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3597 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3598 case X86::BI__builtin_ia32_fixupimmps512_mask: 3599 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3600 case X86::BI__builtin_ia32_fixupimmsd_mask: 3601 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3602 case X86::BI__builtin_ia32_fixupimmss_mask: 3603 case X86::BI__builtin_ia32_fixupimmss_maskz: 3604 case X86::BI__builtin_ia32_getmantsd_round_mask: 3605 case X86::BI__builtin_ia32_getmantss_round_mask: 3606 case X86::BI__builtin_ia32_rangepd512_mask: 3607 case X86::BI__builtin_ia32_rangeps512_mask: 3608 case X86::BI__builtin_ia32_rangesd128_round_mask: 3609 case X86::BI__builtin_ia32_rangess128_round_mask: 3610 case X86::BI__builtin_ia32_reducesd_mask: 3611 case X86::BI__builtin_ia32_reducess_mask: 3612 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3613 case X86::BI__builtin_ia32_rndscaless_round_mask: 3614 ArgNum = 5; 3615 break; 3616 case X86::BI__builtin_ia32_vcvtsd2si64: 3617 case X86::BI__builtin_ia32_vcvtsd2si32: 3618 case X86::BI__builtin_ia32_vcvtsd2usi32: 3619 case X86::BI__builtin_ia32_vcvtsd2usi64: 3620 case X86::BI__builtin_ia32_vcvtss2si32: 3621 case X86::BI__builtin_ia32_vcvtss2si64: 3622 case X86::BI__builtin_ia32_vcvtss2usi32: 3623 case X86::BI__builtin_ia32_vcvtss2usi64: 3624 case X86::BI__builtin_ia32_sqrtpd512: 3625 case X86::BI__builtin_ia32_sqrtps512: 3626 ArgNum = 1; 3627 HasRC = true; 3628 break; 3629 case X86::BI__builtin_ia32_addpd512: 3630 case X86::BI__builtin_ia32_addps512: 3631 case X86::BI__builtin_ia32_divpd512: 3632 case X86::BI__builtin_ia32_divps512: 3633 case X86::BI__builtin_ia32_mulpd512: 3634 case X86::BI__builtin_ia32_mulps512: 3635 case X86::BI__builtin_ia32_subpd512: 3636 case X86::BI__builtin_ia32_subps512: 3637 case X86::BI__builtin_ia32_cvtsi2sd64: 3638 case X86::BI__builtin_ia32_cvtsi2ss32: 3639 case X86::BI__builtin_ia32_cvtsi2ss64: 3640 case X86::BI__builtin_ia32_cvtusi2sd64: 3641 case X86::BI__builtin_ia32_cvtusi2ss32: 3642 case X86::BI__builtin_ia32_cvtusi2ss64: 3643 ArgNum = 2; 3644 HasRC = true; 3645 break; 3646 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3647 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3648 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3649 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3650 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3651 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3652 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3653 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3654 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3655 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3656 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3657 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3658 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3659 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3660 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3661 ArgNum = 3; 3662 HasRC = true; 3663 break; 3664 case X86::BI__builtin_ia32_addss_round_mask: 3665 case X86::BI__builtin_ia32_addsd_round_mask: 3666 case X86::BI__builtin_ia32_divss_round_mask: 3667 case X86::BI__builtin_ia32_divsd_round_mask: 3668 case X86::BI__builtin_ia32_mulss_round_mask: 3669 case X86::BI__builtin_ia32_mulsd_round_mask: 3670 case X86::BI__builtin_ia32_subss_round_mask: 3671 case X86::BI__builtin_ia32_subsd_round_mask: 3672 case X86::BI__builtin_ia32_scalefpd512_mask: 3673 case X86::BI__builtin_ia32_scalefps512_mask: 3674 case X86::BI__builtin_ia32_scalefsd_round_mask: 3675 case X86::BI__builtin_ia32_scalefss_round_mask: 3676 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3677 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3678 case X86::BI__builtin_ia32_sqrtss_round_mask: 3679 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3680 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3681 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3682 case X86::BI__builtin_ia32_vfmaddss3_mask: 3683 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3684 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3685 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3686 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3687 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3688 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3689 case X86::BI__builtin_ia32_vfmaddps512_mask: 3690 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3691 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3692 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3693 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3694 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3695 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3696 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3697 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3698 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3699 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3700 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3701 ArgNum = 4; 3702 HasRC = true; 3703 break; 3704 } 3705 3706 llvm::APSInt Result; 3707 3708 // We can't check the value of a dependent argument. 3709 Expr *Arg = TheCall->getArg(ArgNum); 3710 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3711 return false; 3712 3713 // Check constant-ness first. 3714 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3715 return true; 3716 3717 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3718 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3719 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3720 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3721 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3722 Result == 8/*ROUND_NO_EXC*/ || 3723 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3724 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3725 return false; 3726 3727 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3728 << Arg->getSourceRange(); 3729 } 3730 3731 // Check if the gather/scatter scale is legal. 3732 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3733 CallExpr *TheCall) { 3734 unsigned ArgNum = 0; 3735 switch (BuiltinID) { 3736 default: 3737 return false; 3738 case X86::BI__builtin_ia32_gatherpfdpd: 3739 case X86::BI__builtin_ia32_gatherpfdps: 3740 case X86::BI__builtin_ia32_gatherpfqpd: 3741 case X86::BI__builtin_ia32_gatherpfqps: 3742 case X86::BI__builtin_ia32_scatterpfdpd: 3743 case X86::BI__builtin_ia32_scatterpfdps: 3744 case X86::BI__builtin_ia32_scatterpfqpd: 3745 case X86::BI__builtin_ia32_scatterpfqps: 3746 ArgNum = 3; 3747 break; 3748 case X86::BI__builtin_ia32_gatherd_pd: 3749 case X86::BI__builtin_ia32_gatherd_pd256: 3750 case X86::BI__builtin_ia32_gatherq_pd: 3751 case X86::BI__builtin_ia32_gatherq_pd256: 3752 case X86::BI__builtin_ia32_gatherd_ps: 3753 case X86::BI__builtin_ia32_gatherd_ps256: 3754 case X86::BI__builtin_ia32_gatherq_ps: 3755 case X86::BI__builtin_ia32_gatherq_ps256: 3756 case X86::BI__builtin_ia32_gatherd_q: 3757 case X86::BI__builtin_ia32_gatherd_q256: 3758 case X86::BI__builtin_ia32_gatherq_q: 3759 case X86::BI__builtin_ia32_gatherq_q256: 3760 case X86::BI__builtin_ia32_gatherd_d: 3761 case X86::BI__builtin_ia32_gatherd_d256: 3762 case X86::BI__builtin_ia32_gatherq_d: 3763 case X86::BI__builtin_ia32_gatherq_d256: 3764 case X86::BI__builtin_ia32_gather3div2df: 3765 case X86::BI__builtin_ia32_gather3div2di: 3766 case X86::BI__builtin_ia32_gather3div4df: 3767 case X86::BI__builtin_ia32_gather3div4di: 3768 case X86::BI__builtin_ia32_gather3div4sf: 3769 case X86::BI__builtin_ia32_gather3div4si: 3770 case X86::BI__builtin_ia32_gather3div8sf: 3771 case X86::BI__builtin_ia32_gather3div8si: 3772 case X86::BI__builtin_ia32_gather3siv2df: 3773 case X86::BI__builtin_ia32_gather3siv2di: 3774 case X86::BI__builtin_ia32_gather3siv4df: 3775 case X86::BI__builtin_ia32_gather3siv4di: 3776 case X86::BI__builtin_ia32_gather3siv4sf: 3777 case X86::BI__builtin_ia32_gather3siv4si: 3778 case X86::BI__builtin_ia32_gather3siv8sf: 3779 case X86::BI__builtin_ia32_gather3siv8si: 3780 case X86::BI__builtin_ia32_gathersiv8df: 3781 case X86::BI__builtin_ia32_gathersiv16sf: 3782 case X86::BI__builtin_ia32_gatherdiv8df: 3783 case X86::BI__builtin_ia32_gatherdiv16sf: 3784 case X86::BI__builtin_ia32_gathersiv8di: 3785 case X86::BI__builtin_ia32_gathersiv16si: 3786 case X86::BI__builtin_ia32_gatherdiv8di: 3787 case X86::BI__builtin_ia32_gatherdiv16si: 3788 case X86::BI__builtin_ia32_scatterdiv2df: 3789 case X86::BI__builtin_ia32_scatterdiv2di: 3790 case X86::BI__builtin_ia32_scatterdiv4df: 3791 case X86::BI__builtin_ia32_scatterdiv4di: 3792 case X86::BI__builtin_ia32_scatterdiv4sf: 3793 case X86::BI__builtin_ia32_scatterdiv4si: 3794 case X86::BI__builtin_ia32_scatterdiv8sf: 3795 case X86::BI__builtin_ia32_scatterdiv8si: 3796 case X86::BI__builtin_ia32_scattersiv2df: 3797 case X86::BI__builtin_ia32_scattersiv2di: 3798 case X86::BI__builtin_ia32_scattersiv4df: 3799 case X86::BI__builtin_ia32_scattersiv4di: 3800 case X86::BI__builtin_ia32_scattersiv4sf: 3801 case X86::BI__builtin_ia32_scattersiv4si: 3802 case X86::BI__builtin_ia32_scattersiv8sf: 3803 case X86::BI__builtin_ia32_scattersiv8si: 3804 case X86::BI__builtin_ia32_scattersiv8df: 3805 case X86::BI__builtin_ia32_scattersiv16sf: 3806 case X86::BI__builtin_ia32_scatterdiv8df: 3807 case X86::BI__builtin_ia32_scatterdiv16sf: 3808 case X86::BI__builtin_ia32_scattersiv8di: 3809 case X86::BI__builtin_ia32_scattersiv16si: 3810 case X86::BI__builtin_ia32_scatterdiv8di: 3811 case X86::BI__builtin_ia32_scatterdiv16si: 3812 ArgNum = 4; 3813 break; 3814 } 3815 3816 llvm::APSInt Result; 3817 3818 // We can't check the value of a dependent argument. 3819 Expr *Arg = TheCall->getArg(ArgNum); 3820 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3821 return false; 3822 3823 // Check constant-ness first. 3824 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3825 return true; 3826 3827 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3828 return false; 3829 3830 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3831 << Arg->getSourceRange(); 3832 } 3833 3834 static bool isX86_32Builtin(unsigned BuiltinID) { 3835 // These builtins only work on x86-32 targets. 3836 switch (BuiltinID) { 3837 case X86::BI__builtin_ia32_readeflags_u32: 3838 case X86::BI__builtin_ia32_writeeflags_u32: 3839 return true; 3840 } 3841 3842 return false; 3843 } 3844 3845 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3846 if (BuiltinID == X86::BI__builtin_cpu_supports) 3847 return SemaBuiltinCpuSupports(*this, TheCall); 3848 3849 if (BuiltinID == X86::BI__builtin_cpu_is) 3850 return SemaBuiltinCpuIs(*this, TheCall); 3851 3852 // Check for 32-bit only builtins on a 64-bit target. 3853 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3854 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3855 return Diag(TheCall->getCallee()->getBeginLoc(), 3856 diag::err_32_bit_builtin_64_bit_tgt); 3857 3858 // If the intrinsic has rounding or SAE make sure its valid. 3859 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3860 return true; 3861 3862 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3863 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3864 return true; 3865 3866 // For intrinsics which take an immediate value as part of the instruction, 3867 // range check them here. 3868 int i = 0, l = 0, u = 0; 3869 switch (BuiltinID) { 3870 default: 3871 return false; 3872 case X86::BI__builtin_ia32_vec_ext_v2si: 3873 case X86::BI__builtin_ia32_vec_ext_v2di: 3874 case X86::BI__builtin_ia32_vextractf128_pd256: 3875 case X86::BI__builtin_ia32_vextractf128_ps256: 3876 case X86::BI__builtin_ia32_vextractf128_si256: 3877 case X86::BI__builtin_ia32_extract128i256: 3878 case X86::BI__builtin_ia32_extractf64x4_mask: 3879 case X86::BI__builtin_ia32_extracti64x4_mask: 3880 case X86::BI__builtin_ia32_extractf32x8_mask: 3881 case X86::BI__builtin_ia32_extracti32x8_mask: 3882 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3883 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3884 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3885 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3886 i = 1; l = 0; u = 1; 3887 break; 3888 case X86::BI__builtin_ia32_vec_set_v2di: 3889 case X86::BI__builtin_ia32_vinsertf128_pd256: 3890 case X86::BI__builtin_ia32_vinsertf128_ps256: 3891 case X86::BI__builtin_ia32_vinsertf128_si256: 3892 case X86::BI__builtin_ia32_insert128i256: 3893 case X86::BI__builtin_ia32_insertf32x8: 3894 case X86::BI__builtin_ia32_inserti32x8: 3895 case X86::BI__builtin_ia32_insertf64x4: 3896 case X86::BI__builtin_ia32_inserti64x4: 3897 case X86::BI__builtin_ia32_insertf64x2_256: 3898 case X86::BI__builtin_ia32_inserti64x2_256: 3899 case X86::BI__builtin_ia32_insertf32x4_256: 3900 case X86::BI__builtin_ia32_inserti32x4_256: 3901 i = 2; l = 0; u = 1; 3902 break; 3903 case X86::BI__builtin_ia32_vpermilpd: 3904 case X86::BI__builtin_ia32_vec_ext_v4hi: 3905 case X86::BI__builtin_ia32_vec_ext_v4si: 3906 case X86::BI__builtin_ia32_vec_ext_v4sf: 3907 case X86::BI__builtin_ia32_vec_ext_v4di: 3908 case X86::BI__builtin_ia32_extractf32x4_mask: 3909 case X86::BI__builtin_ia32_extracti32x4_mask: 3910 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3911 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3912 i = 1; l = 0; u = 3; 3913 break; 3914 case X86::BI_mm_prefetch: 3915 case X86::BI__builtin_ia32_vec_ext_v8hi: 3916 case X86::BI__builtin_ia32_vec_ext_v8si: 3917 i = 1; l = 0; u = 7; 3918 break; 3919 case X86::BI__builtin_ia32_sha1rnds4: 3920 case X86::BI__builtin_ia32_blendpd: 3921 case X86::BI__builtin_ia32_shufpd: 3922 case X86::BI__builtin_ia32_vec_set_v4hi: 3923 case X86::BI__builtin_ia32_vec_set_v4si: 3924 case X86::BI__builtin_ia32_vec_set_v4di: 3925 case X86::BI__builtin_ia32_shuf_f32x4_256: 3926 case X86::BI__builtin_ia32_shuf_f64x2_256: 3927 case X86::BI__builtin_ia32_shuf_i32x4_256: 3928 case X86::BI__builtin_ia32_shuf_i64x2_256: 3929 case X86::BI__builtin_ia32_insertf64x2_512: 3930 case X86::BI__builtin_ia32_inserti64x2_512: 3931 case X86::BI__builtin_ia32_insertf32x4: 3932 case X86::BI__builtin_ia32_inserti32x4: 3933 i = 2; l = 0; u = 3; 3934 break; 3935 case X86::BI__builtin_ia32_vpermil2pd: 3936 case X86::BI__builtin_ia32_vpermil2pd256: 3937 case X86::BI__builtin_ia32_vpermil2ps: 3938 case X86::BI__builtin_ia32_vpermil2ps256: 3939 i = 3; l = 0; u = 3; 3940 break; 3941 case X86::BI__builtin_ia32_cmpb128_mask: 3942 case X86::BI__builtin_ia32_cmpw128_mask: 3943 case X86::BI__builtin_ia32_cmpd128_mask: 3944 case X86::BI__builtin_ia32_cmpq128_mask: 3945 case X86::BI__builtin_ia32_cmpb256_mask: 3946 case X86::BI__builtin_ia32_cmpw256_mask: 3947 case X86::BI__builtin_ia32_cmpd256_mask: 3948 case X86::BI__builtin_ia32_cmpq256_mask: 3949 case X86::BI__builtin_ia32_cmpb512_mask: 3950 case X86::BI__builtin_ia32_cmpw512_mask: 3951 case X86::BI__builtin_ia32_cmpd512_mask: 3952 case X86::BI__builtin_ia32_cmpq512_mask: 3953 case X86::BI__builtin_ia32_ucmpb128_mask: 3954 case X86::BI__builtin_ia32_ucmpw128_mask: 3955 case X86::BI__builtin_ia32_ucmpd128_mask: 3956 case X86::BI__builtin_ia32_ucmpq128_mask: 3957 case X86::BI__builtin_ia32_ucmpb256_mask: 3958 case X86::BI__builtin_ia32_ucmpw256_mask: 3959 case X86::BI__builtin_ia32_ucmpd256_mask: 3960 case X86::BI__builtin_ia32_ucmpq256_mask: 3961 case X86::BI__builtin_ia32_ucmpb512_mask: 3962 case X86::BI__builtin_ia32_ucmpw512_mask: 3963 case X86::BI__builtin_ia32_ucmpd512_mask: 3964 case X86::BI__builtin_ia32_ucmpq512_mask: 3965 case X86::BI__builtin_ia32_vpcomub: 3966 case X86::BI__builtin_ia32_vpcomuw: 3967 case X86::BI__builtin_ia32_vpcomud: 3968 case X86::BI__builtin_ia32_vpcomuq: 3969 case X86::BI__builtin_ia32_vpcomb: 3970 case X86::BI__builtin_ia32_vpcomw: 3971 case X86::BI__builtin_ia32_vpcomd: 3972 case X86::BI__builtin_ia32_vpcomq: 3973 case X86::BI__builtin_ia32_vec_set_v8hi: 3974 case X86::BI__builtin_ia32_vec_set_v8si: 3975 i = 2; l = 0; u = 7; 3976 break; 3977 case X86::BI__builtin_ia32_vpermilpd256: 3978 case X86::BI__builtin_ia32_roundps: 3979 case X86::BI__builtin_ia32_roundpd: 3980 case X86::BI__builtin_ia32_roundps256: 3981 case X86::BI__builtin_ia32_roundpd256: 3982 case X86::BI__builtin_ia32_getmantpd128_mask: 3983 case X86::BI__builtin_ia32_getmantpd256_mask: 3984 case X86::BI__builtin_ia32_getmantps128_mask: 3985 case X86::BI__builtin_ia32_getmantps256_mask: 3986 case X86::BI__builtin_ia32_getmantpd512_mask: 3987 case X86::BI__builtin_ia32_getmantps512_mask: 3988 case X86::BI__builtin_ia32_vec_ext_v16qi: 3989 case X86::BI__builtin_ia32_vec_ext_v16hi: 3990 i = 1; l = 0; u = 15; 3991 break; 3992 case X86::BI__builtin_ia32_pblendd128: 3993 case X86::BI__builtin_ia32_blendps: 3994 case X86::BI__builtin_ia32_blendpd256: 3995 case X86::BI__builtin_ia32_shufpd256: 3996 case X86::BI__builtin_ia32_roundss: 3997 case X86::BI__builtin_ia32_roundsd: 3998 case X86::BI__builtin_ia32_rangepd128_mask: 3999 case X86::BI__builtin_ia32_rangepd256_mask: 4000 case X86::BI__builtin_ia32_rangepd512_mask: 4001 case X86::BI__builtin_ia32_rangeps128_mask: 4002 case X86::BI__builtin_ia32_rangeps256_mask: 4003 case X86::BI__builtin_ia32_rangeps512_mask: 4004 case X86::BI__builtin_ia32_getmantsd_round_mask: 4005 case X86::BI__builtin_ia32_getmantss_round_mask: 4006 case X86::BI__builtin_ia32_vec_set_v16qi: 4007 case X86::BI__builtin_ia32_vec_set_v16hi: 4008 i = 2; l = 0; u = 15; 4009 break; 4010 case X86::BI__builtin_ia32_vec_ext_v32qi: 4011 i = 1; l = 0; u = 31; 4012 break; 4013 case X86::BI__builtin_ia32_cmpps: 4014 case X86::BI__builtin_ia32_cmpss: 4015 case X86::BI__builtin_ia32_cmppd: 4016 case X86::BI__builtin_ia32_cmpsd: 4017 case X86::BI__builtin_ia32_cmpps256: 4018 case X86::BI__builtin_ia32_cmppd256: 4019 case X86::BI__builtin_ia32_cmpps128_mask: 4020 case X86::BI__builtin_ia32_cmppd128_mask: 4021 case X86::BI__builtin_ia32_cmpps256_mask: 4022 case X86::BI__builtin_ia32_cmppd256_mask: 4023 case X86::BI__builtin_ia32_cmpps512_mask: 4024 case X86::BI__builtin_ia32_cmppd512_mask: 4025 case X86::BI__builtin_ia32_cmpsd_mask: 4026 case X86::BI__builtin_ia32_cmpss_mask: 4027 case X86::BI__builtin_ia32_vec_set_v32qi: 4028 i = 2; l = 0; u = 31; 4029 break; 4030 case X86::BI__builtin_ia32_permdf256: 4031 case X86::BI__builtin_ia32_permdi256: 4032 case X86::BI__builtin_ia32_permdf512: 4033 case X86::BI__builtin_ia32_permdi512: 4034 case X86::BI__builtin_ia32_vpermilps: 4035 case X86::BI__builtin_ia32_vpermilps256: 4036 case X86::BI__builtin_ia32_vpermilpd512: 4037 case X86::BI__builtin_ia32_vpermilps512: 4038 case X86::BI__builtin_ia32_pshufd: 4039 case X86::BI__builtin_ia32_pshufd256: 4040 case X86::BI__builtin_ia32_pshufd512: 4041 case X86::BI__builtin_ia32_pshufhw: 4042 case X86::BI__builtin_ia32_pshufhw256: 4043 case X86::BI__builtin_ia32_pshufhw512: 4044 case X86::BI__builtin_ia32_pshuflw: 4045 case X86::BI__builtin_ia32_pshuflw256: 4046 case X86::BI__builtin_ia32_pshuflw512: 4047 case X86::BI__builtin_ia32_vcvtps2ph: 4048 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4049 case X86::BI__builtin_ia32_vcvtps2ph256: 4050 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4051 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4052 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4053 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4054 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4055 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4056 case X86::BI__builtin_ia32_rndscaleps_mask: 4057 case X86::BI__builtin_ia32_rndscalepd_mask: 4058 case X86::BI__builtin_ia32_reducepd128_mask: 4059 case X86::BI__builtin_ia32_reducepd256_mask: 4060 case X86::BI__builtin_ia32_reducepd512_mask: 4061 case X86::BI__builtin_ia32_reduceps128_mask: 4062 case X86::BI__builtin_ia32_reduceps256_mask: 4063 case X86::BI__builtin_ia32_reduceps512_mask: 4064 case X86::BI__builtin_ia32_prold512: 4065 case X86::BI__builtin_ia32_prolq512: 4066 case X86::BI__builtin_ia32_prold128: 4067 case X86::BI__builtin_ia32_prold256: 4068 case X86::BI__builtin_ia32_prolq128: 4069 case X86::BI__builtin_ia32_prolq256: 4070 case X86::BI__builtin_ia32_prord512: 4071 case X86::BI__builtin_ia32_prorq512: 4072 case X86::BI__builtin_ia32_prord128: 4073 case X86::BI__builtin_ia32_prord256: 4074 case X86::BI__builtin_ia32_prorq128: 4075 case X86::BI__builtin_ia32_prorq256: 4076 case X86::BI__builtin_ia32_fpclasspd128_mask: 4077 case X86::BI__builtin_ia32_fpclasspd256_mask: 4078 case X86::BI__builtin_ia32_fpclassps128_mask: 4079 case X86::BI__builtin_ia32_fpclassps256_mask: 4080 case X86::BI__builtin_ia32_fpclassps512_mask: 4081 case X86::BI__builtin_ia32_fpclasspd512_mask: 4082 case X86::BI__builtin_ia32_fpclasssd_mask: 4083 case X86::BI__builtin_ia32_fpclassss_mask: 4084 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4085 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4086 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4087 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4088 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4089 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4090 case X86::BI__builtin_ia32_kshiftliqi: 4091 case X86::BI__builtin_ia32_kshiftlihi: 4092 case X86::BI__builtin_ia32_kshiftlisi: 4093 case X86::BI__builtin_ia32_kshiftlidi: 4094 case X86::BI__builtin_ia32_kshiftriqi: 4095 case X86::BI__builtin_ia32_kshiftrihi: 4096 case X86::BI__builtin_ia32_kshiftrisi: 4097 case X86::BI__builtin_ia32_kshiftridi: 4098 i = 1; l = 0; u = 255; 4099 break; 4100 case X86::BI__builtin_ia32_vperm2f128_pd256: 4101 case X86::BI__builtin_ia32_vperm2f128_ps256: 4102 case X86::BI__builtin_ia32_vperm2f128_si256: 4103 case X86::BI__builtin_ia32_permti256: 4104 case X86::BI__builtin_ia32_pblendw128: 4105 case X86::BI__builtin_ia32_pblendw256: 4106 case X86::BI__builtin_ia32_blendps256: 4107 case X86::BI__builtin_ia32_pblendd256: 4108 case X86::BI__builtin_ia32_palignr128: 4109 case X86::BI__builtin_ia32_palignr256: 4110 case X86::BI__builtin_ia32_palignr512: 4111 case X86::BI__builtin_ia32_alignq512: 4112 case X86::BI__builtin_ia32_alignd512: 4113 case X86::BI__builtin_ia32_alignd128: 4114 case X86::BI__builtin_ia32_alignd256: 4115 case X86::BI__builtin_ia32_alignq128: 4116 case X86::BI__builtin_ia32_alignq256: 4117 case X86::BI__builtin_ia32_vcomisd: 4118 case X86::BI__builtin_ia32_vcomiss: 4119 case X86::BI__builtin_ia32_shuf_f32x4: 4120 case X86::BI__builtin_ia32_shuf_f64x2: 4121 case X86::BI__builtin_ia32_shuf_i32x4: 4122 case X86::BI__builtin_ia32_shuf_i64x2: 4123 case X86::BI__builtin_ia32_shufpd512: 4124 case X86::BI__builtin_ia32_shufps: 4125 case X86::BI__builtin_ia32_shufps256: 4126 case X86::BI__builtin_ia32_shufps512: 4127 case X86::BI__builtin_ia32_dbpsadbw128: 4128 case X86::BI__builtin_ia32_dbpsadbw256: 4129 case X86::BI__builtin_ia32_dbpsadbw512: 4130 case X86::BI__builtin_ia32_vpshldd128: 4131 case X86::BI__builtin_ia32_vpshldd256: 4132 case X86::BI__builtin_ia32_vpshldd512: 4133 case X86::BI__builtin_ia32_vpshldq128: 4134 case X86::BI__builtin_ia32_vpshldq256: 4135 case X86::BI__builtin_ia32_vpshldq512: 4136 case X86::BI__builtin_ia32_vpshldw128: 4137 case X86::BI__builtin_ia32_vpshldw256: 4138 case X86::BI__builtin_ia32_vpshldw512: 4139 case X86::BI__builtin_ia32_vpshrdd128: 4140 case X86::BI__builtin_ia32_vpshrdd256: 4141 case X86::BI__builtin_ia32_vpshrdd512: 4142 case X86::BI__builtin_ia32_vpshrdq128: 4143 case X86::BI__builtin_ia32_vpshrdq256: 4144 case X86::BI__builtin_ia32_vpshrdq512: 4145 case X86::BI__builtin_ia32_vpshrdw128: 4146 case X86::BI__builtin_ia32_vpshrdw256: 4147 case X86::BI__builtin_ia32_vpshrdw512: 4148 i = 2; l = 0; u = 255; 4149 break; 4150 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4151 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4152 case X86::BI__builtin_ia32_fixupimmps512_mask: 4153 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4154 case X86::BI__builtin_ia32_fixupimmsd_mask: 4155 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4156 case X86::BI__builtin_ia32_fixupimmss_mask: 4157 case X86::BI__builtin_ia32_fixupimmss_maskz: 4158 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4159 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4160 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4161 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4162 case X86::BI__builtin_ia32_fixupimmps128_mask: 4163 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4164 case X86::BI__builtin_ia32_fixupimmps256_mask: 4165 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4166 case X86::BI__builtin_ia32_pternlogd512_mask: 4167 case X86::BI__builtin_ia32_pternlogd512_maskz: 4168 case X86::BI__builtin_ia32_pternlogq512_mask: 4169 case X86::BI__builtin_ia32_pternlogq512_maskz: 4170 case X86::BI__builtin_ia32_pternlogd128_mask: 4171 case X86::BI__builtin_ia32_pternlogd128_maskz: 4172 case X86::BI__builtin_ia32_pternlogd256_mask: 4173 case X86::BI__builtin_ia32_pternlogd256_maskz: 4174 case X86::BI__builtin_ia32_pternlogq128_mask: 4175 case X86::BI__builtin_ia32_pternlogq128_maskz: 4176 case X86::BI__builtin_ia32_pternlogq256_mask: 4177 case X86::BI__builtin_ia32_pternlogq256_maskz: 4178 i = 3; l = 0; u = 255; 4179 break; 4180 case X86::BI__builtin_ia32_gatherpfdpd: 4181 case X86::BI__builtin_ia32_gatherpfdps: 4182 case X86::BI__builtin_ia32_gatherpfqpd: 4183 case X86::BI__builtin_ia32_gatherpfqps: 4184 case X86::BI__builtin_ia32_scatterpfdpd: 4185 case X86::BI__builtin_ia32_scatterpfdps: 4186 case X86::BI__builtin_ia32_scatterpfqpd: 4187 case X86::BI__builtin_ia32_scatterpfqps: 4188 i = 4; l = 2; u = 3; 4189 break; 4190 case X86::BI__builtin_ia32_reducesd_mask: 4191 case X86::BI__builtin_ia32_reducess_mask: 4192 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4193 case X86::BI__builtin_ia32_rndscaless_round_mask: 4194 i = 4; l = 0; u = 255; 4195 break; 4196 } 4197 4198 // Note that we don't force a hard error on the range check here, allowing 4199 // template-generated or macro-generated dead code to potentially have out-of- 4200 // range values. These need to code generate, but don't need to necessarily 4201 // make any sense. We use a warning that defaults to an error. 4202 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4203 } 4204 4205 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4206 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4207 /// Returns true when the format fits the function and the FormatStringInfo has 4208 /// been populated. 4209 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4210 FormatStringInfo *FSI) { 4211 FSI->HasVAListArg = Format->getFirstArg() == 0; 4212 FSI->FormatIdx = Format->getFormatIdx() - 1; 4213 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4214 4215 // The way the format attribute works in GCC, the implicit this argument 4216 // of member functions is counted. However, it doesn't appear in our own 4217 // lists, so decrement format_idx in that case. 4218 if (IsCXXMember) { 4219 if(FSI->FormatIdx == 0) 4220 return false; 4221 --FSI->FormatIdx; 4222 if (FSI->FirstDataArg != 0) 4223 --FSI->FirstDataArg; 4224 } 4225 return true; 4226 } 4227 4228 /// Checks if a the given expression evaluates to null. 4229 /// 4230 /// Returns true if the value evaluates to null. 4231 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4232 // If the expression has non-null type, it doesn't evaluate to null. 4233 if (auto nullability 4234 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4235 if (*nullability == NullabilityKind::NonNull) 4236 return false; 4237 } 4238 4239 // As a special case, transparent unions initialized with zero are 4240 // considered null for the purposes of the nonnull attribute. 4241 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4242 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4243 if (const CompoundLiteralExpr *CLE = 4244 dyn_cast<CompoundLiteralExpr>(Expr)) 4245 if (const InitListExpr *ILE = 4246 dyn_cast<InitListExpr>(CLE->getInitializer())) 4247 Expr = ILE->getInit(0); 4248 } 4249 4250 bool Result; 4251 return (!Expr->isValueDependent() && 4252 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4253 !Result); 4254 } 4255 4256 static void CheckNonNullArgument(Sema &S, 4257 const Expr *ArgExpr, 4258 SourceLocation CallSiteLoc) { 4259 if (CheckNonNullExpr(S, ArgExpr)) 4260 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4261 S.PDiag(diag::warn_null_arg) 4262 << ArgExpr->getSourceRange()); 4263 } 4264 4265 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4266 FormatStringInfo FSI; 4267 if ((GetFormatStringType(Format) == FST_NSString) && 4268 getFormatStringInfo(Format, false, &FSI)) { 4269 Idx = FSI.FormatIdx; 4270 return true; 4271 } 4272 return false; 4273 } 4274 4275 /// Diagnose use of %s directive in an NSString which is being passed 4276 /// as formatting string to formatting method. 4277 static void 4278 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4279 const NamedDecl *FDecl, 4280 Expr **Args, 4281 unsigned NumArgs) { 4282 unsigned Idx = 0; 4283 bool Format = false; 4284 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4285 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4286 Idx = 2; 4287 Format = true; 4288 } 4289 else 4290 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4291 if (S.GetFormatNSStringIdx(I, Idx)) { 4292 Format = true; 4293 break; 4294 } 4295 } 4296 if (!Format || NumArgs <= Idx) 4297 return; 4298 const Expr *FormatExpr = Args[Idx]; 4299 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4300 FormatExpr = CSCE->getSubExpr(); 4301 const StringLiteral *FormatString; 4302 if (const ObjCStringLiteral *OSL = 4303 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4304 FormatString = OSL->getString(); 4305 else 4306 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4307 if (!FormatString) 4308 return; 4309 if (S.FormatStringHasSArg(FormatString)) { 4310 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4311 << "%s" << 1 << 1; 4312 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4313 << FDecl->getDeclName(); 4314 } 4315 } 4316 4317 /// Determine whether the given type has a non-null nullability annotation. 4318 static bool isNonNullType(ASTContext &ctx, QualType type) { 4319 if (auto nullability = type->getNullability(ctx)) 4320 return *nullability == NullabilityKind::NonNull; 4321 4322 return false; 4323 } 4324 4325 static void CheckNonNullArguments(Sema &S, 4326 const NamedDecl *FDecl, 4327 const FunctionProtoType *Proto, 4328 ArrayRef<const Expr *> Args, 4329 SourceLocation CallSiteLoc) { 4330 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4331 4332 // Already checked by by constant evaluator. 4333 if (S.isConstantEvaluated()) 4334 return; 4335 // Check the attributes attached to the method/function itself. 4336 llvm::SmallBitVector NonNullArgs; 4337 if (FDecl) { 4338 // Handle the nonnull attribute on the function/method declaration itself. 4339 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4340 if (!NonNull->args_size()) { 4341 // Easy case: all pointer arguments are nonnull. 4342 for (const auto *Arg : Args) 4343 if (S.isValidPointerAttrType(Arg->getType())) 4344 CheckNonNullArgument(S, Arg, CallSiteLoc); 4345 return; 4346 } 4347 4348 for (const ParamIdx &Idx : NonNull->args()) { 4349 unsigned IdxAST = Idx.getASTIndex(); 4350 if (IdxAST >= Args.size()) 4351 continue; 4352 if (NonNullArgs.empty()) 4353 NonNullArgs.resize(Args.size()); 4354 NonNullArgs.set(IdxAST); 4355 } 4356 } 4357 } 4358 4359 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4360 // Handle the nonnull attribute on the parameters of the 4361 // function/method. 4362 ArrayRef<ParmVarDecl*> parms; 4363 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4364 parms = FD->parameters(); 4365 else 4366 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4367 4368 unsigned ParamIndex = 0; 4369 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4370 I != E; ++I, ++ParamIndex) { 4371 const ParmVarDecl *PVD = *I; 4372 if (PVD->hasAttr<NonNullAttr>() || 4373 isNonNullType(S.Context, PVD->getType())) { 4374 if (NonNullArgs.empty()) 4375 NonNullArgs.resize(Args.size()); 4376 4377 NonNullArgs.set(ParamIndex); 4378 } 4379 } 4380 } else { 4381 // If we have a non-function, non-method declaration but no 4382 // function prototype, try to dig out the function prototype. 4383 if (!Proto) { 4384 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4385 QualType type = VD->getType().getNonReferenceType(); 4386 if (auto pointerType = type->getAs<PointerType>()) 4387 type = pointerType->getPointeeType(); 4388 else if (auto blockType = type->getAs<BlockPointerType>()) 4389 type = blockType->getPointeeType(); 4390 // FIXME: data member pointers? 4391 4392 // Dig out the function prototype, if there is one. 4393 Proto = type->getAs<FunctionProtoType>(); 4394 } 4395 } 4396 4397 // Fill in non-null argument information from the nullability 4398 // information on the parameter types (if we have them). 4399 if (Proto) { 4400 unsigned Index = 0; 4401 for (auto paramType : Proto->getParamTypes()) { 4402 if (isNonNullType(S.Context, paramType)) { 4403 if (NonNullArgs.empty()) 4404 NonNullArgs.resize(Args.size()); 4405 4406 NonNullArgs.set(Index); 4407 } 4408 4409 ++Index; 4410 } 4411 } 4412 } 4413 4414 // Check for non-null arguments. 4415 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4416 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4417 if (NonNullArgs[ArgIndex]) 4418 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4419 } 4420 } 4421 4422 /// Handles the checks for format strings, non-POD arguments to vararg 4423 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4424 /// attributes. 4425 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4426 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4427 bool IsMemberFunction, SourceLocation Loc, 4428 SourceRange Range, VariadicCallType CallType) { 4429 // FIXME: We should check as much as we can in the template definition. 4430 if (CurContext->isDependentContext()) 4431 return; 4432 4433 // Printf and scanf checking. 4434 llvm::SmallBitVector CheckedVarArgs; 4435 if (FDecl) { 4436 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4437 // Only create vector if there are format attributes. 4438 CheckedVarArgs.resize(Args.size()); 4439 4440 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4441 CheckedVarArgs); 4442 } 4443 } 4444 4445 // Refuse POD arguments that weren't caught by the format string 4446 // checks above. 4447 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4448 if (CallType != VariadicDoesNotApply && 4449 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4450 unsigned NumParams = Proto ? Proto->getNumParams() 4451 : FDecl && isa<FunctionDecl>(FDecl) 4452 ? cast<FunctionDecl>(FDecl)->getNumParams() 4453 : FDecl && isa<ObjCMethodDecl>(FDecl) 4454 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4455 : 0; 4456 4457 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4458 // Args[ArgIdx] can be null in malformed code. 4459 if (const Expr *Arg = Args[ArgIdx]) { 4460 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4461 checkVariadicArgument(Arg, CallType); 4462 } 4463 } 4464 } 4465 4466 if (FDecl || Proto) { 4467 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4468 4469 // Type safety checking. 4470 if (FDecl) { 4471 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4472 CheckArgumentWithTypeTag(I, Args, Loc); 4473 } 4474 } 4475 4476 if (FD) 4477 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4478 } 4479 4480 /// CheckConstructorCall - Check a constructor call for correctness and safety 4481 /// properties not enforced by the C type system. 4482 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4483 ArrayRef<const Expr *> Args, 4484 const FunctionProtoType *Proto, 4485 SourceLocation Loc) { 4486 VariadicCallType CallType = 4487 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4488 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4489 Loc, SourceRange(), CallType); 4490 } 4491 4492 /// CheckFunctionCall - Check a direct function call for various correctness 4493 /// and safety properties not strictly enforced by the C type system. 4494 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4495 const FunctionProtoType *Proto) { 4496 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4497 isa<CXXMethodDecl>(FDecl); 4498 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4499 IsMemberOperatorCall; 4500 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4501 TheCall->getCallee()); 4502 Expr** Args = TheCall->getArgs(); 4503 unsigned NumArgs = TheCall->getNumArgs(); 4504 4505 Expr *ImplicitThis = nullptr; 4506 if (IsMemberOperatorCall) { 4507 // If this is a call to a member operator, hide the first argument 4508 // from checkCall. 4509 // FIXME: Our choice of AST representation here is less than ideal. 4510 ImplicitThis = Args[0]; 4511 ++Args; 4512 --NumArgs; 4513 } else if (IsMemberFunction) 4514 ImplicitThis = 4515 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4516 4517 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4518 IsMemberFunction, TheCall->getRParenLoc(), 4519 TheCall->getCallee()->getSourceRange(), CallType); 4520 4521 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4522 // None of the checks below are needed for functions that don't have 4523 // simple names (e.g., C++ conversion functions). 4524 if (!FnInfo) 4525 return false; 4526 4527 CheckAbsoluteValueFunction(TheCall, FDecl); 4528 CheckMaxUnsignedZero(TheCall, FDecl); 4529 4530 if (getLangOpts().ObjC) 4531 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4532 4533 unsigned CMId = FDecl->getMemoryFunctionKind(); 4534 if (CMId == 0) 4535 return false; 4536 4537 // Handle memory setting and copying functions. 4538 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4539 CheckStrlcpycatArguments(TheCall, FnInfo); 4540 else if (CMId == Builtin::BIstrncat) 4541 CheckStrncatArguments(TheCall, FnInfo); 4542 else 4543 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4544 4545 return false; 4546 } 4547 4548 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4549 ArrayRef<const Expr *> Args) { 4550 VariadicCallType CallType = 4551 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4552 4553 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4554 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4555 CallType); 4556 4557 return false; 4558 } 4559 4560 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4561 const FunctionProtoType *Proto) { 4562 QualType Ty; 4563 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4564 Ty = V->getType().getNonReferenceType(); 4565 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4566 Ty = F->getType().getNonReferenceType(); 4567 else 4568 return false; 4569 4570 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4571 !Ty->isFunctionProtoType()) 4572 return false; 4573 4574 VariadicCallType CallType; 4575 if (!Proto || !Proto->isVariadic()) { 4576 CallType = VariadicDoesNotApply; 4577 } else if (Ty->isBlockPointerType()) { 4578 CallType = VariadicBlock; 4579 } else { // Ty->isFunctionPointerType() 4580 CallType = VariadicFunction; 4581 } 4582 4583 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4584 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4585 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4586 TheCall->getCallee()->getSourceRange(), CallType); 4587 4588 return false; 4589 } 4590 4591 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4592 /// such as function pointers returned from functions. 4593 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4594 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4595 TheCall->getCallee()); 4596 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4597 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4598 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4599 TheCall->getCallee()->getSourceRange(), CallType); 4600 4601 return false; 4602 } 4603 4604 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4605 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4606 return false; 4607 4608 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4609 switch (Op) { 4610 case AtomicExpr::AO__c11_atomic_init: 4611 case AtomicExpr::AO__opencl_atomic_init: 4612 llvm_unreachable("There is no ordering argument for an init"); 4613 4614 case AtomicExpr::AO__c11_atomic_load: 4615 case AtomicExpr::AO__opencl_atomic_load: 4616 case AtomicExpr::AO__atomic_load_n: 4617 case AtomicExpr::AO__atomic_load: 4618 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4619 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4620 4621 case AtomicExpr::AO__c11_atomic_store: 4622 case AtomicExpr::AO__opencl_atomic_store: 4623 case AtomicExpr::AO__atomic_store: 4624 case AtomicExpr::AO__atomic_store_n: 4625 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4626 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4627 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4628 4629 default: 4630 return true; 4631 } 4632 } 4633 4634 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4635 AtomicExpr::AtomicOp Op) { 4636 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4637 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4638 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4639 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4640 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4641 Op); 4642 } 4643 4644 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4645 SourceLocation RParenLoc, MultiExprArg Args, 4646 AtomicExpr::AtomicOp Op, 4647 AtomicArgumentOrder ArgOrder) { 4648 // All the non-OpenCL operations take one of the following forms. 4649 // The OpenCL operations take the __c11 forms with one extra argument for 4650 // synchronization scope. 4651 enum { 4652 // C __c11_atomic_init(A *, C) 4653 Init, 4654 4655 // C __c11_atomic_load(A *, int) 4656 Load, 4657 4658 // void __atomic_load(A *, CP, int) 4659 LoadCopy, 4660 4661 // void __atomic_store(A *, CP, int) 4662 Copy, 4663 4664 // C __c11_atomic_add(A *, M, int) 4665 Arithmetic, 4666 4667 // C __atomic_exchange_n(A *, CP, int) 4668 Xchg, 4669 4670 // void __atomic_exchange(A *, C *, CP, int) 4671 GNUXchg, 4672 4673 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4674 C11CmpXchg, 4675 4676 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4677 GNUCmpXchg 4678 } Form = Init; 4679 4680 const unsigned NumForm = GNUCmpXchg + 1; 4681 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4682 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4683 // where: 4684 // C is an appropriate type, 4685 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4686 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4687 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4688 // the int parameters are for orderings. 4689 4690 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4691 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4692 "need to update code for modified forms"); 4693 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4694 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4695 AtomicExpr::AO__atomic_load, 4696 "need to update code for modified C11 atomics"); 4697 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4698 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4699 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4700 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4701 IsOpenCL; 4702 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4703 Op == AtomicExpr::AO__atomic_store_n || 4704 Op == AtomicExpr::AO__atomic_exchange_n || 4705 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4706 bool IsAddSub = false; 4707 4708 switch (Op) { 4709 case AtomicExpr::AO__c11_atomic_init: 4710 case AtomicExpr::AO__opencl_atomic_init: 4711 Form = Init; 4712 break; 4713 4714 case AtomicExpr::AO__c11_atomic_load: 4715 case AtomicExpr::AO__opencl_atomic_load: 4716 case AtomicExpr::AO__atomic_load_n: 4717 Form = Load; 4718 break; 4719 4720 case AtomicExpr::AO__atomic_load: 4721 Form = LoadCopy; 4722 break; 4723 4724 case AtomicExpr::AO__c11_atomic_store: 4725 case AtomicExpr::AO__opencl_atomic_store: 4726 case AtomicExpr::AO__atomic_store: 4727 case AtomicExpr::AO__atomic_store_n: 4728 Form = Copy; 4729 break; 4730 4731 case AtomicExpr::AO__c11_atomic_fetch_add: 4732 case AtomicExpr::AO__c11_atomic_fetch_sub: 4733 case AtomicExpr::AO__opencl_atomic_fetch_add: 4734 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4735 case AtomicExpr::AO__atomic_fetch_add: 4736 case AtomicExpr::AO__atomic_fetch_sub: 4737 case AtomicExpr::AO__atomic_add_fetch: 4738 case AtomicExpr::AO__atomic_sub_fetch: 4739 IsAddSub = true; 4740 LLVM_FALLTHROUGH; 4741 case AtomicExpr::AO__c11_atomic_fetch_and: 4742 case AtomicExpr::AO__c11_atomic_fetch_or: 4743 case AtomicExpr::AO__c11_atomic_fetch_xor: 4744 case AtomicExpr::AO__opencl_atomic_fetch_and: 4745 case AtomicExpr::AO__opencl_atomic_fetch_or: 4746 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4747 case AtomicExpr::AO__atomic_fetch_and: 4748 case AtomicExpr::AO__atomic_fetch_or: 4749 case AtomicExpr::AO__atomic_fetch_xor: 4750 case AtomicExpr::AO__atomic_fetch_nand: 4751 case AtomicExpr::AO__atomic_and_fetch: 4752 case AtomicExpr::AO__atomic_or_fetch: 4753 case AtomicExpr::AO__atomic_xor_fetch: 4754 case AtomicExpr::AO__atomic_nand_fetch: 4755 case AtomicExpr::AO__c11_atomic_fetch_min: 4756 case AtomicExpr::AO__c11_atomic_fetch_max: 4757 case AtomicExpr::AO__opencl_atomic_fetch_min: 4758 case AtomicExpr::AO__opencl_atomic_fetch_max: 4759 case AtomicExpr::AO__atomic_min_fetch: 4760 case AtomicExpr::AO__atomic_max_fetch: 4761 case AtomicExpr::AO__atomic_fetch_min: 4762 case AtomicExpr::AO__atomic_fetch_max: 4763 Form = Arithmetic; 4764 break; 4765 4766 case AtomicExpr::AO__c11_atomic_exchange: 4767 case AtomicExpr::AO__opencl_atomic_exchange: 4768 case AtomicExpr::AO__atomic_exchange_n: 4769 Form = Xchg; 4770 break; 4771 4772 case AtomicExpr::AO__atomic_exchange: 4773 Form = GNUXchg; 4774 break; 4775 4776 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4777 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4778 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4779 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4780 Form = C11CmpXchg; 4781 break; 4782 4783 case AtomicExpr::AO__atomic_compare_exchange: 4784 case AtomicExpr::AO__atomic_compare_exchange_n: 4785 Form = GNUCmpXchg; 4786 break; 4787 } 4788 4789 unsigned AdjustedNumArgs = NumArgs[Form]; 4790 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4791 ++AdjustedNumArgs; 4792 // Check we have the right number of arguments. 4793 if (Args.size() < AdjustedNumArgs) { 4794 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4795 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4796 << ExprRange; 4797 return ExprError(); 4798 } else if (Args.size() > AdjustedNumArgs) { 4799 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4800 diag::err_typecheck_call_too_many_args) 4801 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4802 << ExprRange; 4803 return ExprError(); 4804 } 4805 4806 // Inspect the first argument of the atomic operation. 4807 Expr *Ptr = Args[0]; 4808 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4809 if (ConvertedPtr.isInvalid()) 4810 return ExprError(); 4811 4812 Ptr = ConvertedPtr.get(); 4813 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4814 if (!pointerType) { 4815 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4816 << Ptr->getType() << Ptr->getSourceRange(); 4817 return ExprError(); 4818 } 4819 4820 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4821 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4822 QualType ValType = AtomTy; // 'C' 4823 if (IsC11) { 4824 if (!AtomTy->isAtomicType()) { 4825 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4826 << Ptr->getType() << Ptr->getSourceRange(); 4827 return ExprError(); 4828 } 4829 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4830 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4831 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4832 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4833 << Ptr->getSourceRange(); 4834 return ExprError(); 4835 } 4836 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4837 } else if (Form != Load && Form != LoadCopy) { 4838 if (ValType.isConstQualified()) { 4839 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4840 << Ptr->getType() << Ptr->getSourceRange(); 4841 return ExprError(); 4842 } 4843 } 4844 4845 // For an arithmetic operation, the implied arithmetic must be well-formed. 4846 if (Form == Arithmetic) { 4847 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4848 if (IsAddSub && !ValType->isIntegerType() 4849 && !ValType->isPointerType()) { 4850 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4851 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4852 return ExprError(); 4853 } 4854 if (!IsAddSub && !ValType->isIntegerType()) { 4855 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4856 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4857 return ExprError(); 4858 } 4859 if (IsC11 && ValType->isPointerType() && 4860 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4861 diag::err_incomplete_type)) { 4862 return ExprError(); 4863 } 4864 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4865 // For __atomic_*_n operations, the value type must be a scalar integral or 4866 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4867 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4868 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4869 return ExprError(); 4870 } 4871 4872 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4873 !AtomTy->isScalarType()) { 4874 // For GNU atomics, require a trivially-copyable type. This is not part of 4875 // the GNU atomics specification, but we enforce it for sanity. 4876 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4877 << Ptr->getType() << Ptr->getSourceRange(); 4878 return ExprError(); 4879 } 4880 4881 switch (ValType.getObjCLifetime()) { 4882 case Qualifiers::OCL_None: 4883 case Qualifiers::OCL_ExplicitNone: 4884 // okay 4885 break; 4886 4887 case Qualifiers::OCL_Weak: 4888 case Qualifiers::OCL_Strong: 4889 case Qualifiers::OCL_Autoreleasing: 4890 // FIXME: Can this happen? By this point, ValType should be known 4891 // to be trivially copyable. 4892 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4893 << ValType << Ptr->getSourceRange(); 4894 return ExprError(); 4895 } 4896 4897 // All atomic operations have an overload which takes a pointer to a volatile 4898 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4899 // into the result or the other operands. Similarly atomic_load takes a 4900 // pointer to a const 'A'. 4901 ValType.removeLocalVolatile(); 4902 ValType.removeLocalConst(); 4903 QualType ResultType = ValType; 4904 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4905 Form == Init) 4906 ResultType = Context.VoidTy; 4907 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4908 ResultType = Context.BoolTy; 4909 4910 // The type of a parameter passed 'by value'. In the GNU atomics, such 4911 // arguments are actually passed as pointers. 4912 QualType ByValType = ValType; // 'CP' 4913 bool IsPassedByAddress = false; 4914 if (!IsC11 && !IsN) { 4915 ByValType = Ptr->getType(); 4916 IsPassedByAddress = true; 4917 } 4918 4919 SmallVector<Expr *, 5> APIOrderedArgs; 4920 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4921 APIOrderedArgs.push_back(Args[0]); 4922 switch (Form) { 4923 case Init: 4924 case Load: 4925 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4926 break; 4927 case LoadCopy: 4928 case Copy: 4929 case Arithmetic: 4930 case Xchg: 4931 APIOrderedArgs.push_back(Args[2]); // Val1 4932 APIOrderedArgs.push_back(Args[1]); // Order 4933 break; 4934 case GNUXchg: 4935 APIOrderedArgs.push_back(Args[2]); // Val1 4936 APIOrderedArgs.push_back(Args[3]); // Val2 4937 APIOrderedArgs.push_back(Args[1]); // Order 4938 break; 4939 case C11CmpXchg: 4940 APIOrderedArgs.push_back(Args[2]); // Val1 4941 APIOrderedArgs.push_back(Args[4]); // Val2 4942 APIOrderedArgs.push_back(Args[1]); // Order 4943 APIOrderedArgs.push_back(Args[3]); // OrderFail 4944 break; 4945 case GNUCmpXchg: 4946 APIOrderedArgs.push_back(Args[2]); // Val1 4947 APIOrderedArgs.push_back(Args[4]); // Val2 4948 APIOrderedArgs.push_back(Args[5]); // Weak 4949 APIOrderedArgs.push_back(Args[1]); // Order 4950 APIOrderedArgs.push_back(Args[3]); // OrderFail 4951 break; 4952 } 4953 } else 4954 APIOrderedArgs.append(Args.begin(), Args.end()); 4955 4956 // The first argument's non-CV pointer type is used to deduce the type of 4957 // subsequent arguments, except for: 4958 // - weak flag (always converted to bool) 4959 // - memory order (always converted to int) 4960 // - scope (always converted to int) 4961 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4962 QualType Ty; 4963 if (i < NumVals[Form] + 1) { 4964 switch (i) { 4965 case 0: 4966 // The first argument is always a pointer. It has a fixed type. 4967 // It is always dereferenced, a nullptr is undefined. 4968 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4969 // Nothing else to do: we already know all we want about this pointer. 4970 continue; 4971 case 1: 4972 // The second argument is the non-atomic operand. For arithmetic, this 4973 // is always passed by value, and for a compare_exchange it is always 4974 // passed by address. For the rest, GNU uses by-address and C11 uses 4975 // by-value. 4976 assert(Form != Load); 4977 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4978 Ty = ValType; 4979 else if (Form == Copy || Form == Xchg) { 4980 if (IsPassedByAddress) { 4981 // The value pointer is always dereferenced, a nullptr is undefined. 4982 CheckNonNullArgument(*this, APIOrderedArgs[i], 4983 ExprRange.getBegin()); 4984 } 4985 Ty = ByValType; 4986 } else if (Form == Arithmetic) 4987 Ty = Context.getPointerDiffType(); 4988 else { 4989 Expr *ValArg = APIOrderedArgs[i]; 4990 // The value pointer is always dereferenced, a nullptr is undefined. 4991 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4992 LangAS AS = LangAS::Default; 4993 // Keep address space of non-atomic pointer type. 4994 if (const PointerType *PtrTy = 4995 ValArg->getType()->getAs<PointerType>()) { 4996 AS = PtrTy->getPointeeType().getAddressSpace(); 4997 } 4998 Ty = Context.getPointerType( 4999 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5000 } 5001 break; 5002 case 2: 5003 // The third argument to compare_exchange / GNU exchange is the desired 5004 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5005 if (IsPassedByAddress) 5006 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5007 Ty = ByValType; 5008 break; 5009 case 3: 5010 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5011 Ty = Context.BoolTy; 5012 break; 5013 } 5014 } else { 5015 // The order(s) and scope are always converted to int. 5016 Ty = Context.IntTy; 5017 } 5018 5019 InitializedEntity Entity = 5020 InitializedEntity::InitializeParameter(Context, Ty, false); 5021 ExprResult Arg = APIOrderedArgs[i]; 5022 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5023 if (Arg.isInvalid()) 5024 return true; 5025 APIOrderedArgs[i] = Arg.get(); 5026 } 5027 5028 // Permute the arguments into a 'consistent' order. 5029 SmallVector<Expr*, 5> SubExprs; 5030 SubExprs.push_back(Ptr); 5031 switch (Form) { 5032 case Init: 5033 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5034 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5035 break; 5036 case Load: 5037 SubExprs.push_back(APIOrderedArgs[1]); // Order 5038 break; 5039 case LoadCopy: 5040 case Copy: 5041 case Arithmetic: 5042 case Xchg: 5043 SubExprs.push_back(APIOrderedArgs[2]); // Order 5044 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5045 break; 5046 case GNUXchg: 5047 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5048 SubExprs.push_back(APIOrderedArgs[3]); // Order 5049 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5050 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5051 break; 5052 case C11CmpXchg: 5053 SubExprs.push_back(APIOrderedArgs[3]); // Order 5054 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5055 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5056 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5057 break; 5058 case GNUCmpXchg: 5059 SubExprs.push_back(APIOrderedArgs[4]); // Order 5060 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5061 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5062 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5063 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5064 break; 5065 } 5066 5067 if (SubExprs.size() >= 2 && Form != Init) { 5068 llvm::APSInt Result(32); 5069 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 5070 !isValidOrderingForOp(Result.getSExtValue(), Op)) 5071 Diag(SubExprs[1]->getBeginLoc(), 5072 diag::warn_atomic_op_has_invalid_memory_order) 5073 << SubExprs[1]->getSourceRange(); 5074 } 5075 5076 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5077 auto *Scope = Args[Args.size() - 1]; 5078 llvm::APSInt Result(32); 5079 if (Scope->isIntegerConstantExpr(Result, Context) && 5080 !ScopeModel->isValid(Result.getZExtValue())) { 5081 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5082 << Scope->getSourceRange(); 5083 } 5084 SubExprs.push_back(Scope); 5085 } 5086 5087 AtomicExpr *AE = new (Context) 5088 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5089 5090 if ((Op == AtomicExpr::AO__c11_atomic_load || 5091 Op == AtomicExpr::AO__c11_atomic_store || 5092 Op == AtomicExpr::AO__opencl_atomic_load || 5093 Op == AtomicExpr::AO__opencl_atomic_store ) && 5094 Context.AtomicUsesUnsupportedLibcall(AE)) 5095 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5096 << ((Op == AtomicExpr::AO__c11_atomic_load || 5097 Op == AtomicExpr::AO__opencl_atomic_load) 5098 ? 0 5099 : 1); 5100 5101 return AE; 5102 } 5103 5104 /// checkBuiltinArgument - Given a call to a builtin function, perform 5105 /// normal type-checking on the given argument, updating the call in 5106 /// place. This is useful when a builtin function requires custom 5107 /// type-checking for some of its arguments but not necessarily all of 5108 /// them. 5109 /// 5110 /// Returns true on error. 5111 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5112 FunctionDecl *Fn = E->getDirectCallee(); 5113 assert(Fn && "builtin call without direct callee!"); 5114 5115 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5116 InitializedEntity Entity = 5117 InitializedEntity::InitializeParameter(S.Context, Param); 5118 5119 ExprResult Arg = E->getArg(0); 5120 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5121 if (Arg.isInvalid()) 5122 return true; 5123 5124 E->setArg(ArgIndex, Arg.get()); 5125 return false; 5126 } 5127 5128 /// We have a call to a function like __sync_fetch_and_add, which is an 5129 /// overloaded function based on the pointer type of its first argument. 5130 /// The main BuildCallExpr routines have already promoted the types of 5131 /// arguments because all of these calls are prototyped as void(...). 5132 /// 5133 /// This function goes through and does final semantic checking for these 5134 /// builtins, as well as generating any warnings. 5135 ExprResult 5136 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5137 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5138 Expr *Callee = TheCall->getCallee(); 5139 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5140 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5141 5142 // Ensure that we have at least one argument to do type inference from. 5143 if (TheCall->getNumArgs() < 1) { 5144 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5145 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5146 return ExprError(); 5147 } 5148 5149 // Inspect the first argument of the atomic builtin. This should always be 5150 // a pointer type, whose element is an integral scalar or pointer type. 5151 // Because it is a pointer type, we don't have to worry about any implicit 5152 // casts here. 5153 // FIXME: We don't allow floating point scalars as input. 5154 Expr *FirstArg = TheCall->getArg(0); 5155 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5156 if (FirstArgResult.isInvalid()) 5157 return ExprError(); 5158 FirstArg = FirstArgResult.get(); 5159 TheCall->setArg(0, FirstArg); 5160 5161 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5162 if (!pointerType) { 5163 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5164 << FirstArg->getType() << FirstArg->getSourceRange(); 5165 return ExprError(); 5166 } 5167 5168 QualType ValType = pointerType->getPointeeType(); 5169 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5170 !ValType->isBlockPointerType()) { 5171 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5172 << FirstArg->getType() << FirstArg->getSourceRange(); 5173 return ExprError(); 5174 } 5175 5176 if (ValType.isConstQualified()) { 5177 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5178 << FirstArg->getType() << FirstArg->getSourceRange(); 5179 return ExprError(); 5180 } 5181 5182 switch (ValType.getObjCLifetime()) { 5183 case Qualifiers::OCL_None: 5184 case Qualifiers::OCL_ExplicitNone: 5185 // okay 5186 break; 5187 5188 case Qualifiers::OCL_Weak: 5189 case Qualifiers::OCL_Strong: 5190 case Qualifiers::OCL_Autoreleasing: 5191 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5192 << ValType << FirstArg->getSourceRange(); 5193 return ExprError(); 5194 } 5195 5196 // Strip any qualifiers off ValType. 5197 ValType = ValType.getUnqualifiedType(); 5198 5199 // The majority of builtins return a value, but a few have special return 5200 // types, so allow them to override appropriately below. 5201 QualType ResultType = ValType; 5202 5203 // We need to figure out which concrete builtin this maps onto. For example, 5204 // __sync_fetch_and_add with a 2 byte object turns into 5205 // __sync_fetch_and_add_2. 5206 #define BUILTIN_ROW(x) \ 5207 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5208 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5209 5210 static const unsigned BuiltinIndices[][5] = { 5211 BUILTIN_ROW(__sync_fetch_and_add), 5212 BUILTIN_ROW(__sync_fetch_and_sub), 5213 BUILTIN_ROW(__sync_fetch_and_or), 5214 BUILTIN_ROW(__sync_fetch_and_and), 5215 BUILTIN_ROW(__sync_fetch_and_xor), 5216 BUILTIN_ROW(__sync_fetch_and_nand), 5217 5218 BUILTIN_ROW(__sync_add_and_fetch), 5219 BUILTIN_ROW(__sync_sub_and_fetch), 5220 BUILTIN_ROW(__sync_and_and_fetch), 5221 BUILTIN_ROW(__sync_or_and_fetch), 5222 BUILTIN_ROW(__sync_xor_and_fetch), 5223 BUILTIN_ROW(__sync_nand_and_fetch), 5224 5225 BUILTIN_ROW(__sync_val_compare_and_swap), 5226 BUILTIN_ROW(__sync_bool_compare_and_swap), 5227 BUILTIN_ROW(__sync_lock_test_and_set), 5228 BUILTIN_ROW(__sync_lock_release), 5229 BUILTIN_ROW(__sync_swap) 5230 }; 5231 #undef BUILTIN_ROW 5232 5233 // Determine the index of the size. 5234 unsigned SizeIndex; 5235 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5236 case 1: SizeIndex = 0; break; 5237 case 2: SizeIndex = 1; break; 5238 case 4: SizeIndex = 2; break; 5239 case 8: SizeIndex = 3; break; 5240 case 16: SizeIndex = 4; break; 5241 default: 5242 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5243 << FirstArg->getType() << FirstArg->getSourceRange(); 5244 return ExprError(); 5245 } 5246 5247 // Each of these builtins has one pointer argument, followed by some number of 5248 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5249 // that we ignore. Find out which row of BuiltinIndices to read from as well 5250 // as the number of fixed args. 5251 unsigned BuiltinID = FDecl->getBuiltinID(); 5252 unsigned BuiltinIndex, NumFixed = 1; 5253 bool WarnAboutSemanticsChange = false; 5254 switch (BuiltinID) { 5255 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5256 case Builtin::BI__sync_fetch_and_add: 5257 case Builtin::BI__sync_fetch_and_add_1: 5258 case Builtin::BI__sync_fetch_and_add_2: 5259 case Builtin::BI__sync_fetch_and_add_4: 5260 case Builtin::BI__sync_fetch_and_add_8: 5261 case Builtin::BI__sync_fetch_and_add_16: 5262 BuiltinIndex = 0; 5263 break; 5264 5265 case Builtin::BI__sync_fetch_and_sub: 5266 case Builtin::BI__sync_fetch_and_sub_1: 5267 case Builtin::BI__sync_fetch_and_sub_2: 5268 case Builtin::BI__sync_fetch_and_sub_4: 5269 case Builtin::BI__sync_fetch_and_sub_8: 5270 case Builtin::BI__sync_fetch_and_sub_16: 5271 BuiltinIndex = 1; 5272 break; 5273 5274 case Builtin::BI__sync_fetch_and_or: 5275 case Builtin::BI__sync_fetch_and_or_1: 5276 case Builtin::BI__sync_fetch_and_or_2: 5277 case Builtin::BI__sync_fetch_and_or_4: 5278 case Builtin::BI__sync_fetch_and_or_8: 5279 case Builtin::BI__sync_fetch_and_or_16: 5280 BuiltinIndex = 2; 5281 break; 5282 5283 case Builtin::BI__sync_fetch_and_and: 5284 case Builtin::BI__sync_fetch_and_and_1: 5285 case Builtin::BI__sync_fetch_and_and_2: 5286 case Builtin::BI__sync_fetch_and_and_4: 5287 case Builtin::BI__sync_fetch_and_and_8: 5288 case Builtin::BI__sync_fetch_and_and_16: 5289 BuiltinIndex = 3; 5290 break; 5291 5292 case Builtin::BI__sync_fetch_and_xor: 5293 case Builtin::BI__sync_fetch_and_xor_1: 5294 case Builtin::BI__sync_fetch_and_xor_2: 5295 case Builtin::BI__sync_fetch_and_xor_4: 5296 case Builtin::BI__sync_fetch_and_xor_8: 5297 case Builtin::BI__sync_fetch_and_xor_16: 5298 BuiltinIndex = 4; 5299 break; 5300 5301 case Builtin::BI__sync_fetch_and_nand: 5302 case Builtin::BI__sync_fetch_and_nand_1: 5303 case Builtin::BI__sync_fetch_and_nand_2: 5304 case Builtin::BI__sync_fetch_and_nand_4: 5305 case Builtin::BI__sync_fetch_and_nand_8: 5306 case Builtin::BI__sync_fetch_and_nand_16: 5307 BuiltinIndex = 5; 5308 WarnAboutSemanticsChange = true; 5309 break; 5310 5311 case Builtin::BI__sync_add_and_fetch: 5312 case Builtin::BI__sync_add_and_fetch_1: 5313 case Builtin::BI__sync_add_and_fetch_2: 5314 case Builtin::BI__sync_add_and_fetch_4: 5315 case Builtin::BI__sync_add_and_fetch_8: 5316 case Builtin::BI__sync_add_and_fetch_16: 5317 BuiltinIndex = 6; 5318 break; 5319 5320 case Builtin::BI__sync_sub_and_fetch: 5321 case Builtin::BI__sync_sub_and_fetch_1: 5322 case Builtin::BI__sync_sub_and_fetch_2: 5323 case Builtin::BI__sync_sub_and_fetch_4: 5324 case Builtin::BI__sync_sub_and_fetch_8: 5325 case Builtin::BI__sync_sub_and_fetch_16: 5326 BuiltinIndex = 7; 5327 break; 5328 5329 case Builtin::BI__sync_and_and_fetch: 5330 case Builtin::BI__sync_and_and_fetch_1: 5331 case Builtin::BI__sync_and_and_fetch_2: 5332 case Builtin::BI__sync_and_and_fetch_4: 5333 case Builtin::BI__sync_and_and_fetch_8: 5334 case Builtin::BI__sync_and_and_fetch_16: 5335 BuiltinIndex = 8; 5336 break; 5337 5338 case Builtin::BI__sync_or_and_fetch: 5339 case Builtin::BI__sync_or_and_fetch_1: 5340 case Builtin::BI__sync_or_and_fetch_2: 5341 case Builtin::BI__sync_or_and_fetch_4: 5342 case Builtin::BI__sync_or_and_fetch_8: 5343 case Builtin::BI__sync_or_and_fetch_16: 5344 BuiltinIndex = 9; 5345 break; 5346 5347 case Builtin::BI__sync_xor_and_fetch: 5348 case Builtin::BI__sync_xor_and_fetch_1: 5349 case Builtin::BI__sync_xor_and_fetch_2: 5350 case Builtin::BI__sync_xor_and_fetch_4: 5351 case Builtin::BI__sync_xor_and_fetch_8: 5352 case Builtin::BI__sync_xor_and_fetch_16: 5353 BuiltinIndex = 10; 5354 break; 5355 5356 case Builtin::BI__sync_nand_and_fetch: 5357 case Builtin::BI__sync_nand_and_fetch_1: 5358 case Builtin::BI__sync_nand_and_fetch_2: 5359 case Builtin::BI__sync_nand_and_fetch_4: 5360 case Builtin::BI__sync_nand_and_fetch_8: 5361 case Builtin::BI__sync_nand_and_fetch_16: 5362 BuiltinIndex = 11; 5363 WarnAboutSemanticsChange = true; 5364 break; 5365 5366 case Builtin::BI__sync_val_compare_and_swap: 5367 case Builtin::BI__sync_val_compare_and_swap_1: 5368 case Builtin::BI__sync_val_compare_and_swap_2: 5369 case Builtin::BI__sync_val_compare_and_swap_4: 5370 case Builtin::BI__sync_val_compare_and_swap_8: 5371 case Builtin::BI__sync_val_compare_and_swap_16: 5372 BuiltinIndex = 12; 5373 NumFixed = 2; 5374 break; 5375 5376 case Builtin::BI__sync_bool_compare_and_swap: 5377 case Builtin::BI__sync_bool_compare_and_swap_1: 5378 case Builtin::BI__sync_bool_compare_and_swap_2: 5379 case Builtin::BI__sync_bool_compare_and_swap_4: 5380 case Builtin::BI__sync_bool_compare_and_swap_8: 5381 case Builtin::BI__sync_bool_compare_and_swap_16: 5382 BuiltinIndex = 13; 5383 NumFixed = 2; 5384 ResultType = Context.BoolTy; 5385 break; 5386 5387 case Builtin::BI__sync_lock_test_and_set: 5388 case Builtin::BI__sync_lock_test_and_set_1: 5389 case Builtin::BI__sync_lock_test_and_set_2: 5390 case Builtin::BI__sync_lock_test_and_set_4: 5391 case Builtin::BI__sync_lock_test_and_set_8: 5392 case Builtin::BI__sync_lock_test_and_set_16: 5393 BuiltinIndex = 14; 5394 break; 5395 5396 case Builtin::BI__sync_lock_release: 5397 case Builtin::BI__sync_lock_release_1: 5398 case Builtin::BI__sync_lock_release_2: 5399 case Builtin::BI__sync_lock_release_4: 5400 case Builtin::BI__sync_lock_release_8: 5401 case Builtin::BI__sync_lock_release_16: 5402 BuiltinIndex = 15; 5403 NumFixed = 0; 5404 ResultType = Context.VoidTy; 5405 break; 5406 5407 case Builtin::BI__sync_swap: 5408 case Builtin::BI__sync_swap_1: 5409 case Builtin::BI__sync_swap_2: 5410 case Builtin::BI__sync_swap_4: 5411 case Builtin::BI__sync_swap_8: 5412 case Builtin::BI__sync_swap_16: 5413 BuiltinIndex = 16; 5414 break; 5415 } 5416 5417 // Now that we know how many fixed arguments we expect, first check that we 5418 // have at least that many. 5419 if (TheCall->getNumArgs() < 1+NumFixed) { 5420 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5421 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5422 << Callee->getSourceRange(); 5423 return ExprError(); 5424 } 5425 5426 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5427 << Callee->getSourceRange(); 5428 5429 if (WarnAboutSemanticsChange) { 5430 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5431 << Callee->getSourceRange(); 5432 } 5433 5434 // Get the decl for the concrete builtin from this, we can tell what the 5435 // concrete integer type we should convert to is. 5436 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5437 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5438 FunctionDecl *NewBuiltinDecl; 5439 if (NewBuiltinID == BuiltinID) 5440 NewBuiltinDecl = FDecl; 5441 else { 5442 // Perform builtin lookup to avoid redeclaring it. 5443 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5444 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5445 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5446 assert(Res.getFoundDecl()); 5447 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5448 if (!NewBuiltinDecl) 5449 return ExprError(); 5450 } 5451 5452 // The first argument --- the pointer --- has a fixed type; we 5453 // deduce the types of the rest of the arguments accordingly. Walk 5454 // the remaining arguments, converting them to the deduced value type. 5455 for (unsigned i = 0; i != NumFixed; ++i) { 5456 ExprResult Arg = TheCall->getArg(i+1); 5457 5458 // GCC does an implicit conversion to the pointer or integer ValType. This 5459 // can fail in some cases (1i -> int**), check for this error case now. 5460 // Initialize the argument. 5461 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5462 ValType, /*consume*/ false); 5463 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5464 if (Arg.isInvalid()) 5465 return ExprError(); 5466 5467 // Okay, we have something that *can* be converted to the right type. Check 5468 // to see if there is a potentially weird extension going on here. This can 5469 // happen when you do an atomic operation on something like an char* and 5470 // pass in 42. The 42 gets converted to char. This is even more strange 5471 // for things like 45.123 -> char, etc. 5472 // FIXME: Do this check. 5473 TheCall->setArg(i+1, Arg.get()); 5474 } 5475 5476 // Create a new DeclRefExpr to refer to the new decl. 5477 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5478 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5479 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5480 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5481 5482 // Set the callee in the CallExpr. 5483 // FIXME: This loses syntactic information. 5484 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5485 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5486 CK_BuiltinFnToFnPtr); 5487 TheCall->setCallee(PromotedCall.get()); 5488 5489 // Change the result type of the call to match the original value type. This 5490 // is arbitrary, but the codegen for these builtins ins design to handle it 5491 // gracefully. 5492 TheCall->setType(ResultType); 5493 5494 return TheCallResult; 5495 } 5496 5497 /// SemaBuiltinNontemporalOverloaded - We have a call to 5498 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5499 /// overloaded function based on the pointer type of its last argument. 5500 /// 5501 /// This function goes through and does final semantic checking for these 5502 /// builtins. 5503 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5504 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5505 DeclRefExpr *DRE = 5506 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5507 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5508 unsigned BuiltinID = FDecl->getBuiltinID(); 5509 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5510 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5511 "Unexpected nontemporal load/store builtin!"); 5512 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5513 unsigned numArgs = isStore ? 2 : 1; 5514 5515 // Ensure that we have the proper number of arguments. 5516 if (checkArgCount(*this, TheCall, numArgs)) 5517 return ExprError(); 5518 5519 // Inspect the last argument of the nontemporal builtin. This should always 5520 // be a pointer type, from which we imply the type of the memory access. 5521 // Because it is a pointer type, we don't have to worry about any implicit 5522 // casts here. 5523 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5524 ExprResult PointerArgResult = 5525 DefaultFunctionArrayLvalueConversion(PointerArg); 5526 5527 if (PointerArgResult.isInvalid()) 5528 return ExprError(); 5529 PointerArg = PointerArgResult.get(); 5530 TheCall->setArg(numArgs - 1, PointerArg); 5531 5532 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5533 if (!pointerType) { 5534 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5535 << PointerArg->getType() << PointerArg->getSourceRange(); 5536 return ExprError(); 5537 } 5538 5539 QualType ValType = pointerType->getPointeeType(); 5540 5541 // Strip any qualifiers off ValType. 5542 ValType = ValType.getUnqualifiedType(); 5543 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5544 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5545 !ValType->isVectorType()) { 5546 Diag(DRE->getBeginLoc(), 5547 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5548 << PointerArg->getType() << PointerArg->getSourceRange(); 5549 return ExprError(); 5550 } 5551 5552 if (!isStore) { 5553 TheCall->setType(ValType); 5554 return TheCallResult; 5555 } 5556 5557 ExprResult ValArg = TheCall->getArg(0); 5558 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5559 Context, ValType, /*consume*/ false); 5560 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5561 if (ValArg.isInvalid()) 5562 return ExprError(); 5563 5564 TheCall->setArg(0, ValArg.get()); 5565 TheCall->setType(Context.VoidTy); 5566 return TheCallResult; 5567 } 5568 5569 /// CheckObjCString - Checks that the argument to the builtin 5570 /// CFString constructor is correct 5571 /// Note: It might also make sense to do the UTF-16 conversion here (would 5572 /// simplify the backend). 5573 bool Sema::CheckObjCString(Expr *Arg) { 5574 Arg = Arg->IgnoreParenCasts(); 5575 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5576 5577 if (!Literal || !Literal->isAscii()) { 5578 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5579 << Arg->getSourceRange(); 5580 return true; 5581 } 5582 5583 if (Literal->containsNonAsciiOrNull()) { 5584 StringRef String = Literal->getString(); 5585 unsigned NumBytes = String.size(); 5586 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5587 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5588 llvm::UTF16 *ToPtr = &ToBuf[0]; 5589 5590 llvm::ConversionResult Result = 5591 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5592 ToPtr + NumBytes, llvm::strictConversion); 5593 // Check for conversion failure. 5594 if (Result != llvm::conversionOK) 5595 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5596 << Arg->getSourceRange(); 5597 } 5598 return false; 5599 } 5600 5601 /// CheckObjCString - Checks that the format string argument to the os_log() 5602 /// and os_trace() functions is correct, and converts it to const char *. 5603 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5604 Arg = Arg->IgnoreParenCasts(); 5605 auto *Literal = dyn_cast<StringLiteral>(Arg); 5606 if (!Literal) { 5607 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5608 Literal = ObjcLiteral->getString(); 5609 } 5610 } 5611 5612 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5613 return ExprError( 5614 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5615 << Arg->getSourceRange()); 5616 } 5617 5618 ExprResult Result(Literal); 5619 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5620 InitializedEntity Entity = 5621 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5622 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5623 return Result; 5624 } 5625 5626 /// Check that the user is calling the appropriate va_start builtin for the 5627 /// target and calling convention. 5628 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5629 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5630 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5631 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5632 TT.getArch() == llvm::Triple::aarch64_32); 5633 bool IsWindows = TT.isOSWindows(); 5634 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5635 if (IsX64 || IsAArch64) { 5636 CallingConv CC = CC_C; 5637 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5638 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5639 if (IsMSVAStart) { 5640 // Don't allow this in System V ABI functions. 5641 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5642 return S.Diag(Fn->getBeginLoc(), 5643 diag::err_ms_va_start_used_in_sysv_function); 5644 } else { 5645 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5646 // On x64 Windows, don't allow this in System V ABI functions. 5647 // (Yes, that means there's no corresponding way to support variadic 5648 // System V ABI functions on Windows.) 5649 if ((IsWindows && CC == CC_X86_64SysV) || 5650 (!IsWindows && CC == CC_Win64)) 5651 return S.Diag(Fn->getBeginLoc(), 5652 diag::err_va_start_used_in_wrong_abi_function) 5653 << !IsWindows; 5654 } 5655 return false; 5656 } 5657 5658 if (IsMSVAStart) 5659 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5660 return false; 5661 } 5662 5663 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5664 ParmVarDecl **LastParam = nullptr) { 5665 // Determine whether the current function, block, or obj-c method is variadic 5666 // and get its parameter list. 5667 bool IsVariadic = false; 5668 ArrayRef<ParmVarDecl *> Params; 5669 DeclContext *Caller = S.CurContext; 5670 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5671 IsVariadic = Block->isVariadic(); 5672 Params = Block->parameters(); 5673 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5674 IsVariadic = FD->isVariadic(); 5675 Params = FD->parameters(); 5676 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5677 IsVariadic = MD->isVariadic(); 5678 // FIXME: This isn't correct for methods (results in bogus warning). 5679 Params = MD->parameters(); 5680 } else if (isa<CapturedDecl>(Caller)) { 5681 // We don't support va_start in a CapturedDecl. 5682 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5683 return true; 5684 } else { 5685 // This must be some other declcontext that parses exprs. 5686 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5687 return true; 5688 } 5689 5690 if (!IsVariadic) { 5691 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5692 return true; 5693 } 5694 5695 if (LastParam) 5696 *LastParam = Params.empty() ? nullptr : Params.back(); 5697 5698 return false; 5699 } 5700 5701 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5702 /// for validity. Emit an error and return true on failure; return false 5703 /// on success. 5704 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5705 Expr *Fn = TheCall->getCallee(); 5706 5707 if (checkVAStartABI(*this, BuiltinID, Fn)) 5708 return true; 5709 5710 if (TheCall->getNumArgs() > 2) { 5711 Diag(TheCall->getArg(2)->getBeginLoc(), 5712 diag::err_typecheck_call_too_many_args) 5713 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5714 << Fn->getSourceRange() 5715 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5716 (*(TheCall->arg_end() - 1))->getEndLoc()); 5717 return true; 5718 } 5719 5720 if (TheCall->getNumArgs() < 2) { 5721 return Diag(TheCall->getEndLoc(), 5722 diag::err_typecheck_call_too_few_args_at_least) 5723 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5724 } 5725 5726 // Type-check the first argument normally. 5727 if (checkBuiltinArgument(*this, TheCall, 0)) 5728 return true; 5729 5730 // Check that the current function is variadic, and get its last parameter. 5731 ParmVarDecl *LastParam; 5732 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5733 return true; 5734 5735 // Verify that the second argument to the builtin is the last argument of the 5736 // current function or method. 5737 bool SecondArgIsLastNamedArgument = false; 5738 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5739 5740 // These are valid if SecondArgIsLastNamedArgument is false after the next 5741 // block. 5742 QualType Type; 5743 SourceLocation ParamLoc; 5744 bool IsCRegister = false; 5745 5746 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5747 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5748 SecondArgIsLastNamedArgument = PV == LastParam; 5749 5750 Type = PV->getType(); 5751 ParamLoc = PV->getLocation(); 5752 IsCRegister = 5753 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5754 } 5755 } 5756 5757 if (!SecondArgIsLastNamedArgument) 5758 Diag(TheCall->getArg(1)->getBeginLoc(), 5759 diag::warn_second_arg_of_va_start_not_last_named_param); 5760 else if (IsCRegister || Type->isReferenceType() || 5761 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5762 // Promotable integers are UB, but enumerations need a bit of 5763 // extra checking to see what their promotable type actually is. 5764 if (!Type->isPromotableIntegerType()) 5765 return false; 5766 if (!Type->isEnumeralType()) 5767 return true; 5768 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5769 return !(ED && 5770 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5771 }()) { 5772 unsigned Reason = 0; 5773 if (Type->isReferenceType()) Reason = 1; 5774 else if (IsCRegister) Reason = 2; 5775 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5776 Diag(ParamLoc, diag::note_parameter_type) << Type; 5777 } 5778 5779 TheCall->setType(Context.VoidTy); 5780 return false; 5781 } 5782 5783 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5784 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5785 // const char *named_addr); 5786 5787 Expr *Func = Call->getCallee(); 5788 5789 if (Call->getNumArgs() < 3) 5790 return Diag(Call->getEndLoc(), 5791 diag::err_typecheck_call_too_few_args_at_least) 5792 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5793 5794 // Type-check the first argument normally. 5795 if (checkBuiltinArgument(*this, Call, 0)) 5796 return true; 5797 5798 // Check that the current function is variadic. 5799 if (checkVAStartIsInVariadicFunction(*this, Func)) 5800 return true; 5801 5802 // __va_start on Windows does not validate the parameter qualifiers 5803 5804 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5805 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5806 5807 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5808 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5809 5810 const QualType &ConstCharPtrTy = 5811 Context.getPointerType(Context.CharTy.withConst()); 5812 if (!Arg1Ty->isPointerType() || 5813 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5814 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5815 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5816 << 0 /* qualifier difference */ 5817 << 3 /* parameter mismatch */ 5818 << 2 << Arg1->getType() << ConstCharPtrTy; 5819 5820 const QualType SizeTy = Context.getSizeType(); 5821 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5822 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5823 << Arg2->getType() << SizeTy << 1 /* different class */ 5824 << 0 /* qualifier difference */ 5825 << 3 /* parameter mismatch */ 5826 << 3 << Arg2->getType() << SizeTy; 5827 5828 return false; 5829 } 5830 5831 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5832 /// friends. This is declared to take (...), so we have to check everything. 5833 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5834 if (TheCall->getNumArgs() < 2) 5835 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5836 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5837 if (TheCall->getNumArgs() > 2) 5838 return Diag(TheCall->getArg(2)->getBeginLoc(), 5839 diag::err_typecheck_call_too_many_args) 5840 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5841 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5842 (*(TheCall->arg_end() - 1))->getEndLoc()); 5843 5844 ExprResult OrigArg0 = TheCall->getArg(0); 5845 ExprResult OrigArg1 = TheCall->getArg(1); 5846 5847 // Do standard promotions between the two arguments, returning their common 5848 // type. 5849 QualType Res = UsualArithmeticConversions( 5850 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5851 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5852 return true; 5853 5854 // Make sure any conversions are pushed back into the call; this is 5855 // type safe since unordered compare builtins are declared as "_Bool 5856 // foo(...)". 5857 TheCall->setArg(0, OrigArg0.get()); 5858 TheCall->setArg(1, OrigArg1.get()); 5859 5860 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5861 return false; 5862 5863 // If the common type isn't a real floating type, then the arguments were 5864 // invalid for this operation. 5865 if (Res.isNull() || !Res->isRealFloatingType()) 5866 return Diag(OrigArg0.get()->getBeginLoc(), 5867 diag::err_typecheck_call_invalid_ordered_compare) 5868 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5869 << SourceRange(OrigArg0.get()->getBeginLoc(), 5870 OrigArg1.get()->getEndLoc()); 5871 5872 return false; 5873 } 5874 5875 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5876 /// __builtin_isnan and friends. This is declared to take (...), so we have 5877 /// to check everything. We expect the last argument to be a floating point 5878 /// value. 5879 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5880 if (TheCall->getNumArgs() < NumArgs) 5881 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5882 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5883 if (TheCall->getNumArgs() > NumArgs) 5884 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5885 diag::err_typecheck_call_too_many_args) 5886 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5887 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5888 (*(TheCall->arg_end() - 1))->getEndLoc()); 5889 5890 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5891 // on all preceding parameters just being int. Try all of those. 5892 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5893 Expr *Arg = TheCall->getArg(i); 5894 5895 if (Arg->isTypeDependent()) 5896 return false; 5897 5898 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5899 5900 if (Res.isInvalid()) 5901 return true; 5902 TheCall->setArg(i, Res.get()); 5903 } 5904 5905 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5906 5907 if (OrigArg->isTypeDependent()) 5908 return false; 5909 5910 // Usual Unary Conversions will convert half to float, which we want for 5911 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5912 // type how it is, but do normal L->Rvalue conversions. 5913 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5914 OrigArg = UsualUnaryConversions(OrigArg).get(); 5915 else 5916 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5917 TheCall->setArg(NumArgs - 1, OrigArg); 5918 5919 // This operation requires a non-_Complex floating-point number. 5920 if (!OrigArg->getType()->isRealFloatingType()) 5921 return Diag(OrigArg->getBeginLoc(), 5922 diag::err_typecheck_call_invalid_unary_fp) 5923 << OrigArg->getType() << OrigArg->getSourceRange(); 5924 5925 return false; 5926 } 5927 5928 // Customized Sema Checking for VSX builtins that have the following signature: 5929 // vector [...] builtinName(vector [...], vector [...], const int); 5930 // Which takes the same type of vectors (any legal vector type) for the first 5931 // two arguments and takes compile time constant for the third argument. 5932 // Example builtins are : 5933 // vector double vec_xxpermdi(vector double, vector double, int); 5934 // vector short vec_xxsldwi(vector short, vector short, int); 5935 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5936 unsigned ExpectedNumArgs = 3; 5937 if (TheCall->getNumArgs() < ExpectedNumArgs) 5938 return Diag(TheCall->getEndLoc(), 5939 diag::err_typecheck_call_too_few_args_at_least) 5940 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5941 << TheCall->getSourceRange(); 5942 5943 if (TheCall->getNumArgs() > ExpectedNumArgs) 5944 return Diag(TheCall->getEndLoc(), 5945 diag::err_typecheck_call_too_many_args_at_most) 5946 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5947 << TheCall->getSourceRange(); 5948 5949 // Check the third argument is a compile time constant 5950 llvm::APSInt Value; 5951 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5952 return Diag(TheCall->getBeginLoc(), 5953 diag::err_vsx_builtin_nonconstant_argument) 5954 << 3 /* argument index */ << TheCall->getDirectCallee() 5955 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5956 TheCall->getArg(2)->getEndLoc()); 5957 5958 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5959 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5960 5961 // Check the type of argument 1 and argument 2 are vectors. 5962 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5963 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5964 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5965 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5966 << TheCall->getDirectCallee() 5967 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5968 TheCall->getArg(1)->getEndLoc()); 5969 } 5970 5971 // Check the first two arguments are the same type. 5972 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5973 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5974 << TheCall->getDirectCallee() 5975 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5976 TheCall->getArg(1)->getEndLoc()); 5977 } 5978 5979 // When default clang type checking is turned off and the customized type 5980 // checking is used, the returning type of the function must be explicitly 5981 // set. Otherwise it is _Bool by default. 5982 TheCall->setType(Arg1Ty); 5983 5984 return false; 5985 } 5986 5987 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5988 // This is declared to take (...), so we have to check everything. 5989 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5990 if (TheCall->getNumArgs() < 2) 5991 return ExprError(Diag(TheCall->getEndLoc(), 5992 diag::err_typecheck_call_too_few_args_at_least) 5993 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5994 << TheCall->getSourceRange()); 5995 5996 // Determine which of the following types of shufflevector we're checking: 5997 // 1) unary, vector mask: (lhs, mask) 5998 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5999 QualType resType = TheCall->getArg(0)->getType(); 6000 unsigned numElements = 0; 6001 6002 if (!TheCall->getArg(0)->isTypeDependent() && 6003 !TheCall->getArg(1)->isTypeDependent()) { 6004 QualType LHSType = TheCall->getArg(0)->getType(); 6005 QualType RHSType = TheCall->getArg(1)->getType(); 6006 6007 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6008 return ExprError( 6009 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6010 << TheCall->getDirectCallee() 6011 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6012 TheCall->getArg(1)->getEndLoc())); 6013 6014 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6015 unsigned numResElements = TheCall->getNumArgs() - 2; 6016 6017 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6018 // with mask. If so, verify that RHS is an integer vector type with the 6019 // same number of elts as lhs. 6020 if (TheCall->getNumArgs() == 2) { 6021 if (!RHSType->hasIntegerRepresentation() || 6022 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6023 return ExprError(Diag(TheCall->getBeginLoc(), 6024 diag::err_vec_builtin_incompatible_vector) 6025 << TheCall->getDirectCallee() 6026 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6027 TheCall->getArg(1)->getEndLoc())); 6028 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6029 return ExprError(Diag(TheCall->getBeginLoc(), 6030 diag::err_vec_builtin_incompatible_vector) 6031 << TheCall->getDirectCallee() 6032 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6033 TheCall->getArg(1)->getEndLoc())); 6034 } else if (numElements != numResElements) { 6035 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6036 resType = Context.getVectorType(eltType, numResElements, 6037 VectorType::GenericVector); 6038 } 6039 } 6040 6041 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6042 if (TheCall->getArg(i)->isTypeDependent() || 6043 TheCall->getArg(i)->isValueDependent()) 6044 continue; 6045 6046 llvm::APSInt Result(32); 6047 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 6048 return ExprError(Diag(TheCall->getBeginLoc(), 6049 diag::err_shufflevector_nonconstant_argument) 6050 << TheCall->getArg(i)->getSourceRange()); 6051 6052 // Allow -1 which will be translated to undef in the IR. 6053 if (Result.isSigned() && Result.isAllOnesValue()) 6054 continue; 6055 6056 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 6057 return ExprError(Diag(TheCall->getBeginLoc(), 6058 diag::err_shufflevector_argument_too_large) 6059 << TheCall->getArg(i)->getSourceRange()); 6060 } 6061 6062 SmallVector<Expr*, 32> exprs; 6063 6064 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6065 exprs.push_back(TheCall->getArg(i)); 6066 TheCall->setArg(i, nullptr); 6067 } 6068 6069 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6070 TheCall->getCallee()->getBeginLoc(), 6071 TheCall->getRParenLoc()); 6072 } 6073 6074 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6075 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6076 SourceLocation BuiltinLoc, 6077 SourceLocation RParenLoc) { 6078 ExprValueKind VK = VK_RValue; 6079 ExprObjectKind OK = OK_Ordinary; 6080 QualType DstTy = TInfo->getType(); 6081 QualType SrcTy = E->getType(); 6082 6083 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6084 return ExprError(Diag(BuiltinLoc, 6085 diag::err_convertvector_non_vector) 6086 << E->getSourceRange()); 6087 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6088 return ExprError(Diag(BuiltinLoc, 6089 diag::err_convertvector_non_vector_type)); 6090 6091 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6092 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6093 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6094 if (SrcElts != DstElts) 6095 return ExprError(Diag(BuiltinLoc, 6096 diag::err_convertvector_incompatible_vector) 6097 << E->getSourceRange()); 6098 } 6099 6100 return new (Context) 6101 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6102 } 6103 6104 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6105 // This is declared to take (const void*, ...) and can take two 6106 // optional constant int args. 6107 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6108 unsigned NumArgs = TheCall->getNumArgs(); 6109 6110 if (NumArgs > 3) 6111 return Diag(TheCall->getEndLoc(), 6112 diag::err_typecheck_call_too_many_args_at_most) 6113 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6114 6115 // Argument 0 is checked for us and the remaining arguments must be 6116 // constant integers. 6117 for (unsigned i = 1; i != NumArgs; ++i) 6118 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6119 return true; 6120 6121 return false; 6122 } 6123 6124 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6125 // __assume does not evaluate its arguments, and should warn if its argument 6126 // has side effects. 6127 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6128 Expr *Arg = TheCall->getArg(0); 6129 if (Arg->isInstantiationDependent()) return false; 6130 6131 if (Arg->HasSideEffects(Context)) 6132 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6133 << Arg->getSourceRange() 6134 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6135 6136 return false; 6137 } 6138 6139 /// Handle __builtin_alloca_with_align. This is declared 6140 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6141 /// than 8. 6142 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6143 // The alignment must be a constant integer. 6144 Expr *Arg = TheCall->getArg(1); 6145 6146 // We can't check the value of a dependent argument. 6147 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6148 if (const auto *UE = 6149 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6150 if (UE->getKind() == UETT_AlignOf || 6151 UE->getKind() == UETT_PreferredAlignOf) 6152 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6153 << Arg->getSourceRange(); 6154 6155 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6156 6157 if (!Result.isPowerOf2()) 6158 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6159 << Arg->getSourceRange(); 6160 6161 if (Result < Context.getCharWidth()) 6162 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6163 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6164 6165 if (Result > std::numeric_limits<int32_t>::max()) 6166 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6167 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6168 } 6169 6170 return false; 6171 } 6172 6173 /// Handle __builtin_assume_aligned. This is declared 6174 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6175 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6176 unsigned NumArgs = TheCall->getNumArgs(); 6177 6178 if (NumArgs > 3) 6179 return Diag(TheCall->getEndLoc(), 6180 diag::err_typecheck_call_too_many_args_at_most) 6181 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6182 6183 // The alignment must be a constant integer. 6184 Expr *Arg = TheCall->getArg(1); 6185 6186 // We can't check the value of a dependent argument. 6187 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6188 llvm::APSInt Result; 6189 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6190 return true; 6191 6192 if (!Result.isPowerOf2()) 6193 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6194 << Arg->getSourceRange(); 6195 6196 // Alignment calculations can wrap around if it's greater than 2**29. 6197 unsigned MaximumAlignment = 536870912; 6198 if (Result > MaximumAlignment) 6199 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6200 << Arg->getSourceRange() << MaximumAlignment; 6201 } 6202 6203 if (NumArgs > 2) { 6204 ExprResult Arg(TheCall->getArg(2)); 6205 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6206 Context.getSizeType(), false); 6207 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6208 if (Arg.isInvalid()) return true; 6209 TheCall->setArg(2, Arg.get()); 6210 } 6211 6212 return false; 6213 } 6214 6215 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6216 unsigned BuiltinID = 6217 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6218 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6219 6220 unsigned NumArgs = TheCall->getNumArgs(); 6221 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6222 if (NumArgs < NumRequiredArgs) { 6223 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6224 << 0 /* function call */ << NumRequiredArgs << NumArgs 6225 << TheCall->getSourceRange(); 6226 } 6227 if (NumArgs >= NumRequiredArgs + 0x100) { 6228 return Diag(TheCall->getEndLoc(), 6229 diag::err_typecheck_call_too_many_args_at_most) 6230 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6231 << TheCall->getSourceRange(); 6232 } 6233 unsigned i = 0; 6234 6235 // For formatting call, check buffer arg. 6236 if (!IsSizeCall) { 6237 ExprResult Arg(TheCall->getArg(i)); 6238 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6239 Context, Context.VoidPtrTy, false); 6240 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6241 if (Arg.isInvalid()) 6242 return true; 6243 TheCall->setArg(i, Arg.get()); 6244 i++; 6245 } 6246 6247 // Check string literal arg. 6248 unsigned FormatIdx = i; 6249 { 6250 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6251 if (Arg.isInvalid()) 6252 return true; 6253 TheCall->setArg(i, Arg.get()); 6254 i++; 6255 } 6256 6257 // Make sure variadic args are scalar. 6258 unsigned FirstDataArg = i; 6259 while (i < NumArgs) { 6260 ExprResult Arg = DefaultVariadicArgumentPromotion( 6261 TheCall->getArg(i), VariadicFunction, nullptr); 6262 if (Arg.isInvalid()) 6263 return true; 6264 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6265 if (ArgSize.getQuantity() >= 0x100) { 6266 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6267 << i << (int)ArgSize.getQuantity() << 0xff 6268 << TheCall->getSourceRange(); 6269 } 6270 TheCall->setArg(i, Arg.get()); 6271 i++; 6272 } 6273 6274 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6275 // call to avoid duplicate diagnostics. 6276 if (!IsSizeCall) { 6277 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6278 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6279 bool Success = CheckFormatArguments( 6280 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6281 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6282 CheckedVarArgs); 6283 if (!Success) 6284 return true; 6285 } 6286 6287 if (IsSizeCall) { 6288 TheCall->setType(Context.getSizeType()); 6289 } else { 6290 TheCall->setType(Context.VoidPtrTy); 6291 } 6292 return false; 6293 } 6294 6295 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6296 /// TheCall is a constant expression. 6297 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6298 llvm::APSInt &Result) { 6299 Expr *Arg = TheCall->getArg(ArgNum); 6300 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6301 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6302 6303 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6304 6305 if (!Arg->isIntegerConstantExpr(Result, Context)) 6306 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6307 << FDecl->getDeclName() << Arg->getSourceRange(); 6308 6309 return false; 6310 } 6311 6312 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6313 /// TheCall is a constant expression in the range [Low, High]. 6314 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6315 int Low, int High, bool RangeIsError) { 6316 if (isConstantEvaluated()) 6317 return false; 6318 llvm::APSInt Result; 6319 6320 // We can't check the value of a dependent argument. 6321 Expr *Arg = TheCall->getArg(ArgNum); 6322 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6323 return false; 6324 6325 // Check constant-ness first. 6326 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6327 return true; 6328 6329 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6330 if (RangeIsError) 6331 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6332 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6333 else 6334 // Defer the warning until we know if the code will be emitted so that 6335 // dead code can ignore this. 6336 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6337 PDiag(diag::warn_argument_invalid_range) 6338 << Result.toString(10) << Low << High 6339 << Arg->getSourceRange()); 6340 } 6341 6342 return false; 6343 } 6344 6345 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6346 /// TheCall is a constant expression is a multiple of Num.. 6347 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6348 unsigned Num) { 6349 llvm::APSInt Result; 6350 6351 // We can't check the value of a dependent argument. 6352 Expr *Arg = TheCall->getArg(ArgNum); 6353 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6354 return false; 6355 6356 // Check constant-ness first. 6357 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6358 return true; 6359 6360 if (Result.getSExtValue() % Num != 0) 6361 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6362 << Num << Arg->getSourceRange(); 6363 6364 return false; 6365 } 6366 6367 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6368 /// constant expression representing a power of 2. 6369 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6370 llvm::APSInt Result; 6371 6372 // We can't check the value of a dependent argument. 6373 Expr *Arg = TheCall->getArg(ArgNum); 6374 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6375 return false; 6376 6377 // Check constant-ness first. 6378 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6379 return true; 6380 6381 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6382 // and only if x is a power of 2. 6383 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6384 return false; 6385 6386 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6387 << Arg->getSourceRange(); 6388 } 6389 6390 static bool IsShiftedByte(llvm::APSInt Value) { 6391 if (Value.isNegative()) 6392 return false; 6393 6394 // Check if it's a shifted byte, by shifting it down 6395 while (true) { 6396 // If the value fits in the bottom byte, the check passes. 6397 if (Value < 0x100) 6398 return true; 6399 6400 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6401 // fails. 6402 if ((Value & 0xFF) != 0) 6403 return false; 6404 6405 // If the bottom 8 bits are all 0, but something above that is nonzero, 6406 // then shifting the value right by 8 bits won't affect whether it's a 6407 // shifted byte or not. So do that, and go round again. 6408 Value >>= 8; 6409 } 6410 } 6411 6412 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6413 /// a constant expression representing an arbitrary byte value shifted left by 6414 /// a multiple of 8 bits. 6415 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum) { 6416 llvm::APSInt Result; 6417 6418 // We can't check the value of a dependent argument. 6419 Expr *Arg = TheCall->getArg(ArgNum); 6420 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6421 return false; 6422 6423 // Check constant-ness first. 6424 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6425 return true; 6426 6427 if (IsShiftedByte(Result)) 6428 return false; 6429 6430 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6431 << Arg->getSourceRange(); 6432 } 6433 6434 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6435 /// TheCall is a constant expression representing either a shifted byte value, 6436 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6437 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6438 /// Arm MVE intrinsics. 6439 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6440 int ArgNum) { 6441 llvm::APSInt Result; 6442 6443 // We can't check the value of a dependent argument. 6444 Expr *Arg = TheCall->getArg(ArgNum); 6445 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6446 return false; 6447 6448 // Check constant-ness first. 6449 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6450 return true; 6451 6452 // Check to see if it's in either of the required forms. 6453 if (IsShiftedByte(Result) || 6454 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6455 return false; 6456 6457 return Diag(TheCall->getBeginLoc(), 6458 diag::err_argument_not_shifted_byte_or_xxff) 6459 << Arg->getSourceRange(); 6460 } 6461 6462 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6463 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6464 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6465 if (checkArgCount(*this, TheCall, 2)) 6466 return true; 6467 Expr *Arg0 = TheCall->getArg(0); 6468 Expr *Arg1 = TheCall->getArg(1); 6469 6470 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6471 if (FirstArg.isInvalid()) 6472 return true; 6473 QualType FirstArgType = FirstArg.get()->getType(); 6474 if (!FirstArgType->isAnyPointerType()) 6475 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6476 << "first" << FirstArgType << Arg0->getSourceRange(); 6477 TheCall->setArg(0, FirstArg.get()); 6478 6479 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6480 if (SecArg.isInvalid()) 6481 return true; 6482 QualType SecArgType = SecArg.get()->getType(); 6483 if (!SecArgType->isIntegerType()) 6484 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6485 << "second" << SecArgType << Arg1->getSourceRange(); 6486 6487 // Derive the return type from the pointer argument. 6488 TheCall->setType(FirstArgType); 6489 return false; 6490 } 6491 6492 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6493 if (checkArgCount(*this, TheCall, 2)) 6494 return true; 6495 6496 Expr *Arg0 = TheCall->getArg(0); 6497 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6498 if (FirstArg.isInvalid()) 6499 return true; 6500 QualType FirstArgType = FirstArg.get()->getType(); 6501 if (!FirstArgType->isAnyPointerType()) 6502 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6503 << "first" << FirstArgType << Arg0->getSourceRange(); 6504 TheCall->setArg(0, FirstArg.get()); 6505 6506 // Derive the return type from the pointer argument. 6507 TheCall->setType(FirstArgType); 6508 6509 // Second arg must be an constant in range [0,15] 6510 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6511 } 6512 6513 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6514 if (checkArgCount(*this, TheCall, 2)) 6515 return true; 6516 Expr *Arg0 = TheCall->getArg(0); 6517 Expr *Arg1 = TheCall->getArg(1); 6518 6519 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6520 if (FirstArg.isInvalid()) 6521 return true; 6522 QualType FirstArgType = FirstArg.get()->getType(); 6523 if (!FirstArgType->isAnyPointerType()) 6524 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6525 << "first" << FirstArgType << Arg0->getSourceRange(); 6526 6527 QualType SecArgType = Arg1->getType(); 6528 if (!SecArgType->isIntegerType()) 6529 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6530 << "second" << SecArgType << Arg1->getSourceRange(); 6531 TheCall->setType(Context.IntTy); 6532 return false; 6533 } 6534 6535 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6536 BuiltinID == AArch64::BI__builtin_arm_stg) { 6537 if (checkArgCount(*this, TheCall, 1)) 6538 return true; 6539 Expr *Arg0 = TheCall->getArg(0); 6540 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6541 if (FirstArg.isInvalid()) 6542 return true; 6543 6544 QualType FirstArgType = FirstArg.get()->getType(); 6545 if (!FirstArgType->isAnyPointerType()) 6546 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6547 << "first" << FirstArgType << Arg0->getSourceRange(); 6548 TheCall->setArg(0, FirstArg.get()); 6549 6550 // Derive the return type from the pointer argument. 6551 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6552 TheCall->setType(FirstArgType); 6553 return false; 6554 } 6555 6556 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6557 Expr *ArgA = TheCall->getArg(0); 6558 Expr *ArgB = TheCall->getArg(1); 6559 6560 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6561 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6562 6563 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6564 return true; 6565 6566 QualType ArgTypeA = ArgExprA.get()->getType(); 6567 QualType ArgTypeB = ArgExprB.get()->getType(); 6568 6569 auto isNull = [&] (Expr *E) -> bool { 6570 return E->isNullPointerConstant( 6571 Context, Expr::NPC_ValueDependentIsNotNull); }; 6572 6573 // argument should be either a pointer or null 6574 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6575 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6576 << "first" << ArgTypeA << ArgA->getSourceRange(); 6577 6578 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6579 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6580 << "second" << ArgTypeB << ArgB->getSourceRange(); 6581 6582 // Ensure Pointee types are compatible 6583 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6584 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6585 QualType pointeeA = ArgTypeA->getPointeeType(); 6586 QualType pointeeB = ArgTypeB->getPointeeType(); 6587 if (!Context.typesAreCompatible( 6588 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6589 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6590 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6591 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6592 << ArgB->getSourceRange(); 6593 } 6594 } 6595 6596 // at least one argument should be pointer type 6597 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6598 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6599 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6600 6601 if (isNull(ArgA)) // adopt type of the other pointer 6602 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6603 6604 if (isNull(ArgB)) 6605 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6606 6607 TheCall->setArg(0, ArgExprA.get()); 6608 TheCall->setArg(1, ArgExprB.get()); 6609 TheCall->setType(Context.LongLongTy); 6610 return false; 6611 } 6612 assert(false && "Unhandled ARM MTE intrinsic"); 6613 return true; 6614 } 6615 6616 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6617 /// TheCall is an ARM/AArch64 special register string literal. 6618 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6619 int ArgNum, unsigned ExpectedFieldNum, 6620 bool AllowName) { 6621 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6622 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6623 BuiltinID == ARM::BI__builtin_arm_rsr || 6624 BuiltinID == ARM::BI__builtin_arm_rsrp || 6625 BuiltinID == ARM::BI__builtin_arm_wsr || 6626 BuiltinID == ARM::BI__builtin_arm_wsrp; 6627 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6628 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6629 BuiltinID == AArch64::BI__builtin_arm_rsr || 6630 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6631 BuiltinID == AArch64::BI__builtin_arm_wsr || 6632 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6633 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6634 6635 // We can't check the value of a dependent argument. 6636 Expr *Arg = TheCall->getArg(ArgNum); 6637 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6638 return false; 6639 6640 // Check if the argument is a string literal. 6641 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6642 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6643 << Arg->getSourceRange(); 6644 6645 // Check the type of special register given. 6646 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6647 SmallVector<StringRef, 6> Fields; 6648 Reg.split(Fields, ":"); 6649 6650 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6651 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6652 << Arg->getSourceRange(); 6653 6654 // If the string is the name of a register then we cannot check that it is 6655 // valid here but if the string is of one the forms described in ACLE then we 6656 // can check that the supplied fields are integers and within the valid 6657 // ranges. 6658 if (Fields.size() > 1) { 6659 bool FiveFields = Fields.size() == 5; 6660 6661 bool ValidString = true; 6662 if (IsARMBuiltin) { 6663 ValidString &= Fields[0].startswith_lower("cp") || 6664 Fields[0].startswith_lower("p"); 6665 if (ValidString) 6666 Fields[0] = 6667 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6668 6669 ValidString &= Fields[2].startswith_lower("c"); 6670 if (ValidString) 6671 Fields[2] = Fields[2].drop_front(1); 6672 6673 if (FiveFields) { 6674 ValidString &= Fields[3].startswith_lower("c"); 6675 if (ValidString) 6676 Fields[3] = Fields[3].drop_front(1); 6677 } 6678 } 6679 6680 SmallVector<int, 5> Ranges; 6681 if (FiveFields) 6682 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6683 else 6684 Ranges.append({15, 7, 15}); 6685 6686 for (unsigned i=0; i<Fields.size(); ++i) { 6687 int IntField; 6688 ValidString &= !Fields[i].getAsInteger(10, IntField); 6689 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6690 } 6691 6692 if (!ValidString) 6693 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6694 << Arg->getSourceRange(); 6695 } else if (IsAArch64Builtin && Fields.size() == 1) { 6696 // If the register name is one of those that appear in the condition below 6697 // and the special register builtin being used is one of the write builtins, 6698 // then we require that the argument provided for writing to the register 6699 // is an integer constant expression. This is because it will be lowered to 6700 // an MSR (immediate) instruction, so we need to know the immediate at 6701 // compile time. 6702 if (TheCall->getNumArgs() != 2) 6703 return false; 6704 6705 std::string RegLower = Reg.lower(); 6706 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6707 RegLower != "pan" && RegLower != "uao") 6708 return false; 6709 6710 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6711 } 6712 6713 return false; 6714 } 6715 6716 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6717 /// This checks that the target supports __builtin_longjmp and 6718 /// that val is a constant 1. 6719 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6720 if (!Context.getTargetInfo().hasSjLjLowering()) 6721 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6722 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6723 6724 Expr *Arg = TheCall->getArg(1); 6725 llvm::APSInt Result; 6726 6727 // TODO: This is less than ideal. Overload this to take a value. 6728 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6729 return true; 6730 6731 if (Result != 1) 6732 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6733 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6734 6735 return false; 6736 } 6737 6738 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6739 /// This checks that the target supports __builtin_setjmp. 6740 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6741 if (!Context.getTargetInfo().hasSjLjLowering()) 6742 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6743 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6744 return false; 6745 } 6746 6747 namespace { 6748 6749 class UncoveredArgHandler { 6750 enum { Unknown = -1, AllCovered = -2 }; 6751 6752 signed FirstUncoveredArg = Unknown; 6753 SmallVector<const Expr *, 4> DiagnosticExprs; 6754 6755 public: 6756 UncoveredArgHandler() = default; 6757 6758 bool hasUncoveredArg() const { 6759 return (FirstUncoveredArg >= 0); 6760 } 6761 6762 unsigned getUncoveredArg() const { 6763 assert(hasUncoveredArg() && "no uncovered argument"); 6764 return FirstUncoveredArg; 6765 } 6766 6767 void setAllCovered() { 6768 // A string has been found with all arguments covered, so clear out 6769 // the diagnostics. 6770 DiagnosticExprs.clear(); 6771 FirstUncoveredArg = AllCovered; 6772 } 6773 6774 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6775 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6776 6777 // Don't update if a previous string covers all arguments. 6778 if (FirstUncoveredArg == AllCovered) 6779 return; 6780 6781 // UncoveredArgHandler tracks the highest uncovered argument index 6782 // and with it all the strings that match this index. 6783 if (NewFirstUncoveredArg == FirstUncoveredArg) 6784 DiagnosticExprs.push_back(StrExpr); 6785 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6786 DiagnosticExprs.clear(); 6787 DiagnosticExprs.push_back(StrExpr); 6788 FirstUncoveredArg = NewFirstUncoveredArg; 6789 } 6790 } 6791 6792 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6793 }; 6794 6795 enum StringLiteralCheckType { 6796 SLCT_NotALiteral, 6797 SLCT_UncheckedLiteral, 6798 SLCT_CheckedLiteral 6799 }; 6800 6801 } // namespace 6802 6803 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6804 BinaryOperatorKind BinOpKind, 6805 bool AddendIsRight) { 6806 unsigned BitWidth = Offset.getBitWidth(); 6807 unsigned AddendBitWidth = Addend.getBitWidth(); 6808 // There might be negative interim results. 6809 if (Addend.isUnsigned()) { 6810 Addend = Addend.zext(++AddendBitWidth); 6811 Addend.setIsSigned(true); 6812 } 6813 // Adjust the bit width of the APSInts. 6814 if (AddendBitWidth > BitWidth) { 6815 Offset = Offset.sext(AddendBitWidth); 6816 BitWidth = AddendBitWidth; 6817 } else if (BitWidth > AddendBitWidth) { 6818 Addend = Addend.sext(BitWidth); 6819 } 6820 6821 bool Ov = false; 6822 llvm::APSInt ResOffset = Offset; 6823 if (BinOpKind == BO_Add) 6824 ResOffset = Offset.sadd_ov(Addend, Ov); 6825 else { 6826 assert(AddendIsRight && BinOpKind == BO_Sub && 6827 "operator must be add or sub with addend on the right"); 6828 ResOffset = Offset.ssub_ov(Addend, Ov); 6829 } 6830 6831 // We add an offset to a pointer here so we should support an offset as big as 6832 // possible. 6833 if (Ov) { 6834 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6835 "index (intermediate) result too big"); 6836 Offset = Offset.sext(2 * BitWidth); 6837 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6838 return; 6839 } 6840 6841 Offset = ResOffset; 6842 } 6843 6844 namespace { 6845 6846 // This is a wrapper class around StringLiteral to support offsetted string 6847 // literals as format strings. It takes the offset into account when returning 6848 // the string and its length or the source locations to display notes correctly. 6849 class FormatStringLiteral { 6850 const StringLiteral *FExpr; 6851 int64_t Offset; 6852 6853 public: 6854 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6855 : FExpr(fexpr), Offset(Offset) {} 6856 6857 StringRef getString() const { 6858 return FExpr->getString().drop_front(Offset); 6859 } 6860 6861 unsigned getByteLength() const { 6862 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6863 } 6864 6865 unsigned getLength() const { return FExpr->getLength() - Offset; } 6866 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6867 6868 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6869 6870 QualType getType() const { return FExpr->getType(); } 6871 6872 bool isAscii() const { return FExpr->isAscii(); } 6873 bool isWide() const { return FExpr->isWide(); } 6874 bool isUTF8() const { return FExpr->isUTF8(); } 6875 bool isUTF16() const { return FExpr->isUTF16(); } 6876 bool isUTF32() const { return FExpr->isUTF32(); } 6877 bool isPascal() const { return FExpr->isPascal(); } 6878 6879 SourceLocation getLocationOfByte( 6880 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6881 const TargetInfo &Target, unsigned *StartToken = nullptr, 6882 unsigned *StartTokenByteOffset = nullptr) const { 6883 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6884 StartToken, StartTokenByteOffset); 6885 } 6886 6887 SourceLocation getBeginLoc() const LLVM_READONLY { 6888 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6889 } 6890 6891 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6892 }; 6893 6894 } // namespace 6895 6896 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6897 const Expr *OrigFormatExpr, 6898 ArrayRef<const Expr *> Args, 6899 bool HasVAListArg, unsigned format_idx, 6900 unsigned firstDataArg, 6901 Sema::FormatStringType Type, 6902 bool inFunctionCall, 6903 Sema::VariadicCallType CallType, 6904 llvm::SmallBitVector &CheckedVarArgs, 6905 UncoveredArgHandler &UncoveredArg, 6906 bool IgnoreStringsWithoutSpecifiers); 6907 6908 // Determine if an expression is a string literal or constant string. 6909 // If this function returns false on the arguments to a function expecting a 6910 // format string, we will usually need to emit a warning. 6911 // True string literals are then checked by CheckFormatString. 6912 static StringLiteralCheckType 6913 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6914 bool HasVAListArg, unsigned format_idx, 6915 unsigned firstDataArg, Sema::FormatStringType Type, 6916 Sema::VariadicCallType CallType, bool InFunctionCall, 6917 llvm::SmallBitVector &CheckedVarArgs, 6918 UncoveredArgHandler &UncoveredArg, 6919 llvm::APSInt Offset, 6920 bool IgnoreStringsWithoutSpecifiers = false) { 6921 if (S.isConstantEvaluated()) 6922 return SLCT_NotALiteral; 6923 tryAgain: 6924 assert(Offset.isSigned() && "invalid offset"); 6925 6926 if (E->isTypeDependent() || E->isValueDependent()) 6927 return SLCT_NotALiteral; 6928 6929 E = E->IgnoreParenCasts(); 6930 6931 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6932 // Technically -Wformat-nonliteral does not warn about this case. 6933 // The behavior of printf and friends in this case is implementation 6934 // dependent. Ideally if the format string cannot be null then 6935 // it should have a 'nonnull' attribute in the function prototype. 6936 return SLCT_UncheckedLiteral; 6937 6938 switch (E->getStmtClass()) { 6939 case Stmt::BinaryConditionalOperatorClass: 6940 case Stmt::ConditionalOperatorClass: { 6941 // The expression is a literal if both sub-expressions were, and it was 6942 // completely checked only if both sub-expressions were checked. 6943 const AbstractConditionalOperator *C = 6944 cast<AbstractConditionalOperator>(E); 6945 6946 // Determine whether it is necessary to check both sub-expressions, for 6947 // example, because the condition expression is a constant that can be 6948 // evaluated at compile time. 6949 bool CheckLeft = true, CheckRight = true; 6950 6951 bool Cond; 6952 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6953 S.isConstantEvaluated())) { 6954 if (Cond) 6955 CheckRight = false; 6956 else 6957 CheckLeft = false; 6958 } 6959 6960 // We need to maintain the offsets for the right and the left hand side 6961 // separately to check if every possible indexed expression is a valid 6962 // string literal. They might have different offsets for different string 6963 // literals in the end. 6964 StringLiteralCheckType Left; 6965 if (!CheckLeft) 6966 Left = SLCT_UncheckedLiteral; 6967 else { 6968 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6969 HasVAListArg, format_idx, firstDataArg, 6970 Type, CallType, InFunctionCall, 6971 CheckedVarArgs, UncoveredArg, Offset, 6972 IgnoreStringsWithoutSpecifiers); 6973 if (Left == SLCT_NotALiteral || !CheckRight) { 6974 return Left; 6975 } 6976 } 6977 6978 StringLiteralCheckType Right = checkFormatStringExpr( 6979 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6980 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6981 IgnoreStringsWithoutSpecifiers); 6982 6983 return (CheckLeft && Left < Right) ? Left : Right; 6984 } 6985 6986 case Stmt::ImplicitCastExprClass: 6987 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6988 goto tryAgain; 6989 6990 case Stmt::OpaqueValueExprClass: 6991 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6992 E = src; 6993 goto tryAgain; 6994 } 6995 return SLCT_NotALiteral; 6996 6997 case Stmt::PredefinedExprClass: 6998 // While __func__, etc., are technically not string literals, they 6999 // cannot contain format specifiers and thus are not a security 7000 // liability. 7001 return SLCT_UncheckedLiteral; 7002 7003 case Stmt::DeclRefExprClass: { 7004 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7005 7006 // As an exception, do not flag errors for variables binding to 7007 // const string literals. 7008 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7009 bool isConstant = false; 7010 QualType T = DR->getType(); 7011 7012 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7013 isConstant = AT->getElementType().isConstant(S.Context); 7014 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7015 isConstant = T.isConstant(S.Context) && 7016 PT->getPointeeType().isConstant(S.Context); 7017 } else if (T->isObjCObjectPointerType()) { 7018 // In ObjC, there is usually no "const ObjectPointer" type, 7019 // so don't check if the pointee type is constant. 7020 isConstant = T.isConstant(S.Context); 7021 } 7022 7023 if (isConstant) { 7024 if (const Expr *Init = VD->getAnyInitializer()) { 7025 // Look through initializers like const char c[] = { "foo" } 7026 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7027 if (InitList->isStringLiteralInit()) 7028 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7029 } 7030 return checkFormatStringExpr(S, Init, Args, 7031 HasVAListArg, format_idx, 7032 firstDataArg, Type, CallType, 7033 /*InFunctionCall*/ false, CheckedVarArgs, 7034 UncoveredArg, Offset); 7035 } 7036 } 7037 7038 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7039 // special check to see if the format string is a function parameter 7040 // of the function calling the printf function. If the function 7041 // has an attribute indicating it is a printf-like function, then we 7042 // should suppress warnings concerning non-literals being used in a call 7043 // to a vprintf function. For example: 7044 // 7045 // void 7046 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7047 // va_list ap; 7048 // va_start(ap, fmt); 7049 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7050 // ... 7051 // } 7052 if (HasVAListArg) { 7053 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7054 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7055 int PVIndex = PV->getFunctionScopeIndex() + 1; 7056 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7057 // adjust for implicit parameter 7058 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7059 if (MD->isInstance()) 7060 ++PVIndex; 7061 // We also check if the formats are compatible. 7062 // We can't pass a 'scanf' string to a 'printf' function. 7063 if (PVIndex == PVFormat->getFormatIdx() && 7064 Type == S.GetFormatStringType(PVFormat)) 7065 return SLCT_UncheckedLiteral; 7066 } 7067 } 7068 } 7069 } 7070 } 7071 7072 return SLCT_NotALiteral; 7073 } 7074 7075 case Stmt::CallExprClass: 7076 case Stmt::CXXMemberCallExprClass: { 7077 const CallExpr *CE = cast<CallExpr>(E); 7078 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7079 bool IsFirst = true; 7080 StringLiteralCheckType CommonResult; 7081 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7082 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7083 StringLiteralCheckType Result = checkFormatStringExpr( 7084 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7085 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7086 IgnoreStringsWithoutSpecifiers); 7087 if (IsFirst) { 7088 CommonResult = Result; 7089 IsFirst = false; 7090 } 7091 } 7092 if (!IsFirst) 7093 return CommonResult; 7094 7095 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7096 unsigned BuiltinID = FD->getBuiltinID(); 7097 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7098 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7099 const Expr *Arg = CE->getArg(0); 7100 return checkFormatStringExpr(S, Arg, Args, 7101 HasVAListArg, format_idx, 7102 firstDataArg, Type, CallType, 7103 InFunctionCall, CheckedVarArgs, 7104 UncoveredArg, Offset, 7105 IgnoreStringsWithoutSpecifiers); 7106 } 7107 } 7108 } 7109 7110 return SLCT_NotALiteral; 7111 } 7112 case Stmt::ObjCMessageExprClass: { 7113 const auto *ME = cast<ObjCMessageExpr>(E); 7114 if (const auto *MD = ME->getMethodDecl()) { 7115 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7116 // As a special case heuristic, if we're using the method -[NSBundle 7117 // localizedStringForKey:value:table:], ignore any key strings that lack 7118 // format specifiers. The idea is that if the key doesn't have any 7119 // format specifiers then its probably just a key to map to the 7120 // localized strings. If it does have format specifiers though, then its 7121 // likely that the text of the key is the format string in the 7122 // programmer's language, and should be checked. 7123 const ObjCInterfaceDecl *IFace; 7124 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7125 IFace->getIdentifier()->isStr("NSBundle") && 7126 MD->getSelector().isKeywordSelector( 7127 {"localizedStringForKey", "value", "table"})) { 7128 IgnoreStringsWithoutSpecifiers = true; 7129 } 7130 7131 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7132 return checkFormatStringExpr( 7133 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7134 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7135 IgnoreStringsWithoutSpecifiers); 7136 } 7137 } 7138 7139 return SLCT_NotALiteral; 7140 } 7141 case Stmt::ObjCStringLiteralClass: 7142 case Stmt::StringLiteralClass: { 7143 const StringLiteral *StrE = nullptr; 7144 7145 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7146 StrE = ObjCFExpr->getString(); 7147 else 7148 StrE = cast<StringLiteral>(E); 7149 7150 if (StrE) { 7151 if (Offset.isNegative() || Offset > StrE->getLength()) { 7152 // TODO: It would be better to have an explicit warning for out of 7153 // bounds literals. 7154 return SLCT_NotALiteral; 7155 } 7156 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7157 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7158 firstDataArg, Type, InFunctionCall, CallType, 7159 CheckedVarArgs, UncoveredArg, 7160 IgnoreStringsWithoutSpecifiers); 7161 return SLCT_CheckedLiteral; 7162 } 7163 7164 return SLCT_NotALiteral; 7165 } 7166 case Stmt::BinaryOperatorClass: { 7167 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7168 7169 // A string literal + an int offset is still a string literal. 7170 if (BinOp->isAdditiveOp()) { 7171 Expr::EvalResult LResult, RResult; 7172 7173 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7174 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7175 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7176 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7177 7178 if (LIsInt != RIsInt) { 7179 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7180 7181 if (LIsInt) { 7182 if (BinOpKind == BO_Add) { 7183 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7184 E = BinOp->getRHS(); 7185 goto tryAgain; 7186 } 7187 } else { 7188 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7189 E = BinOp->getLHS(); 7190 goto tryAgain; 7191 } 7192 } 7193 } 7194 7195 return SLCT_NotALiteral; 7196 } 7197 case Stmt::UnaryOperatorClass: { 7198 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7199 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7200 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7201 Expr::EvalResult IndexResult; 7202 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7203 Expr::SE_NoSideEffects, 7204 S.isConstantEvaluated())) { 7205 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7206 /*RHS is int*/ true); 7207 E = ASE->getBase(); 7208 goto tryAgain; 7209 } 7210 } 7211 7212 return SLCT_NotALiteral; 7213 } 7214 7215 default: 7216 return SLCT_NotALiteral; 7217 } 7218 } 7219 7220 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7221 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7222 .Case("scanf", FST_Scanf) 7223 .Cases("printf", "printf0", "syslog", FST_Printf) 7224 .Cases("NSString", "CFString", FST_NSString) 7225 .Case("strftime", FST_Strftime) 7226 .Case("strfmon", FST_Strfmon) 7227 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7228 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7229 .Case("os_trace", FST_OSLog) 7230 .Case("os_log", FST_OSLog) 7231 .Default(FST_Unknown); 7232 } 7233 7234 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7235 /// functions) for correct use of format strings. 7236 /// Returns true if a format string has been fully checked. 7237 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7238 ArrayRef<const Expr *> Args, 7239 bool IsCXXMember, 7240 VariadicCallType CallType, 7241 SourceLocation Loc, SourceRange Range, 7242 llvm::SmallBitVector &CheckedVarArgs) { 7243 FormatStringInfo FSI; 7244 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7245 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7246 FSI.FirstDataArg, GetFormatStringType(Format), 7247 CallType, Loc, Range, CheckedVarArgs); 7248 return false; 7249 } 7250 7251 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7252 bool HasVAListArg, unsigned format_idx, 7253 unsigned firstDataArg, FormatStringType Type, 7254 VariadicCallType CallType, 7255 SourceLocation Loc, SourceRange Range, 7256 llvm::SmallBitVector &CheckedVarArgs) { 7257 // CHECK: printf/scanf-like function is called with no format string. 7258 if (format_idx >= Args.size()) { 7259 Diag(Loc, diag::warn_missing_format_string) << Range; 7260 return false; 7261 } 7262 7263 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7264 7265 // CHECK: format string is not a string literal. 7266 // 7267 // Dynamically generated format strings are difficult to 7268 // automatically vet at compile time. Requiring that format strings 7269 // are string literals: (1) permits the checking of format strings by 7270 // the compiler and thereby (2) can practically remove the source of 7271 // many format string exploits. 7272 7273 // Format string can be either ObjC string (e.g. @"%d") or 7274 // C string (e.g. "%d") 7275 // ObjC string uses the same format specifiers as C string, so we can use 7276 // the same format string checking logic for both ObjC and C strings. 7277 UncoveredArgHandler UncoveredArg; 7278 StringLiteralCheckType CT = 7279 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7280 format_idx, firstDataArg, Type, CallType, 7281 /*IsFunctionCall*/ true, CheckedVarArgs, 7282 UncoveredArg, 7283 /*no string offset*/ llvm::APSInt(64, false) = 0); 7284 7285 // Generate a diagnostic where an uncovered argument is detected. 7286 if (UncoveredArg.hasUncoveredArg()) { 7287 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7288 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7289 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7290 } 7291 7292 if (CT != SLCT_NotALiteral) 7293 // Literal format string found, check done! 7294 return CT == SLCT_CheckedLiteral; 7295 7296 // Strftime is particular as it always uses a single 'time' argument, 7297 // so it is safe to pass a non-literal string. 7298 if (Type == FST_Strftime) 7299 return false; 7300 7301 // Do not emit diag when the string param is a macro expansion and the 7302 // format is either NSString or CFString. This is a hack to prevent 7303 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7304 // which are usually used in place of NS and CF string literals. 7305 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7306 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7307 return false; 7308 7309 // If there are no arguments specified, warn with -Wformat-security, otherwise 7310 // warn only with -Wformat-nonliteral. 7311 if (Args.size() == firstDataArg) { 7312 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7313 << OrigFormatExpr->getSourceRange(); 7314 switch (Type) { 7315 default: 7316 break; 7317 case FST_Kprintf: 7318 case FST_FreeBSDKPrintf: 7319 case FST_Printf: 7320 case FST_Syslog: 7321 Diag(FormatLoc, diag::note_format_security_fixit) 7322 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7323 break; 7324 case FST_NSString: 7325 Diag(FormatLoc, diag::note_format_security_fixit) 7326 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7327 break; 7328 } 7329 } else { 7330 Diag(FormatLoc, diag::warn_format_nonliteral) 7331 << OrigFormatExpr->getSourceRange(); 7332 } 7333 return false; 7334 } 7335 7336 namespace { 7337 7338 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7339 protected: 7340 Sema &S; 7341 const FormatStringLiteral *FExpr; 7342 const Expr *OrigFormatExpr; 7343 const Sema::FormatStringType FSType; 7344 const unsigned FirstDataArg; 7345 const unsigned NumDataArgs; 7346 const char *Beg; // Start of format string. 7347 const bool HasVAListArg; 7348 ArrayRef<const Expr *> Args; 7349 unsigned FormatIdx; 7350 llvm::SmallBitVector CoveredArgs; 7351 bool usesPositionalArgs = false; 7352 bool atFirstArg = true; 7353 bool inFunctionCall; 7354 Sema::VariadicCallType CallType; 7355 llvm::SmallBitVector &CheckedVarArgs; 7356 UncoveredArgHandler &UncoveredArg; 7357 7358 public: 7359 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7360 const Expr *origFormatExpr, 7361 const Sema::FormatStringType type, unsigned firstDataArg, 7362 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7363 ArrayRef<const Expr *> Args, unsigned formatIdx, 7364 bool inFunctionCall, Sema::VariadicCallType callType, 7365 llvm::SmallBitVector &CheckedVarArgs, 7366 UncoveredArgHandler &UncoveredArg) 7367 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7368 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7369 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7370 inFunctionCall(inFunctionCall), CallType(callType), 7371 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7372 CoveredArgs.resize(numDataArgs); 7373 CoveredArgs.reset(); 7374 } 7375 7376 void DoneProcessing(); 7377 7378 void HandleIncompleteSpecifier(const char *startSpecifier, 7379 unsigned specifierLen) override; 7380 7381 void HandleInvalidLengthModifier( 7382 const analyze_format_string::FormatSpecifier &FS, 7383 const analyze_format_string::ConversionSpecifier &CS, 7384 const char *startSpecifier, unsigned specifierLen, 7385 unsigned DiagID); 7386 7387 void HandleNonStandardLengthModifier( 7388 const analyze_format_string::FormatSpecifier &FS, 7389 const char *startSpecifier, unsigned specifierLen); 7390 7391 void HandleNonStandardConversionSpecifier( 7392 const analyze_format_string::ConversionSpecifier &CS, 7393 const char *startSpecifier, unsigned specifierLen); 7394 7395 void HandlePosition(const char *startPos, unsigned posLen) override; 7396 7397 void HandleInvalidPosition(const char *startSpecifier, 7398 unsigned specifierLen, 7399 analyze_format_string::PositionContext p) override; 7400 7401 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7402 7403 void HandleNullChar(const char *nullCharacter) override; 7404 7405 template <typename Range> 7406 static void 7407 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7408 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7409 bool IsStringLocation, Range StringRange, 7410 ArrayRef<FixItHint> Fixit = None); 7411 7412 protected: 7413 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7414 const char *startSpec, 7415 unsigned specifierLen, 7416 const char *csStart, unsigned csLen); 7417 7418 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7419 const char *startSpec, 7420 unsigned specifierLen); 7421 7422 SourceRange getFormatStringRange(); 7423 CharSourceRange getSpecifierRange(const char *startSpecifier, 7424 unsigned specifierLen); 7425 SourceLocation getLocationOfByte(const char *x); 7426 7427 const Expr *getDataArg(unsigned i) const; 7428 7429 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7430 const analyze_format_string::ConversionSpecifier &CS, 7431 const char *startSpecifier, unsigned specifierLen, 7432 unsigned argIndex); 7433 7434 template <typename Range> 7435 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7436 bool IsStringLocation, Range StringRange, 7437 ArrayRef<FixItHint> Fixit = None); 7438 }; 7439 7440 } // namespace 7441 7442 SourceRange CheckFormatHandler::getFormatStringRange() { 7443 return OrigFormatExpr->getSourceRange(); 7444 } 7445 7446 CharSourceRange CheckFormatHandler:: 7447 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7448 SourceLocation Start = getLocationOfByte(startSpecifier); 7449 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7450 7451 // Advance the end SourceLocation by one due to half-open ranges. 7452 End = End.getLocWithOffset(1); 7453 7454 return CharSourceRange::getCharRange(Start, End); 7455 } 7456 7457 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7458 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7459 S.getLangOpts(), S.Context.getTargetInfo()); 7460 } 7461 7462 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7463 unsigned specifierLen){ 7464 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7465 getLocationOfByte(startSpecifier), 7466 /*IsStringLocation*/true, 7467 getSpecifierRange(startSpecifier, specifierLen)); 7468 } 7469 7470 void CheckFormatHandler::HandleInvalidLengthModifier( 7471 const analyze_format_string::FormatSpecifier &FS, 7472 const analyze_format_string::ConversionSpecifier &CS, 7473 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7474 using namespace analyze_format_string; 7475 7476 const LengthModifier &LM = FS.getLengthModifier(); 7477 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7478 7479 // See if we know how to fix this length modifier. 7480 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7481 if (FixedLM) { 7482 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7483 getLocationOfByte(LM.getStart()), 7484 /*IsStringLocation*/true, 7485 getSpecifierRange(startSpecifier, specifierLen)); 7486 7487 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7488 << FixedLM->toString() 7489 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7490 7491 } else { 7492 FixItHint Hint; 7493 if (DiagID == diag::warn_format_nonsensical_length) 7494 Hint = FixItHint::CreateRemoval(LMRange); 7495 7496 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7497 getLocationOfByte(LM.getStart()), 7498 /*IsStringLocation*/true, 7499 getSpecifierRange(startSpecifier, specifierLen), 7500 Hint); 7501 } 7502 } 7503 7504 void CheckFormatHandler::HandleNonStandardLengthModifier( 7505 const analyze_format_string::FormatSpecifier &FS, 7506 const char *startSpecifier, unsigned specifierLen) { 7507 using namespace analyze_format_string; 7508 7509 const LengthModifier &LM = FS.getLengthModifier(); 7510 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7511 7512 // See if we know how to fix this length modifier. 7513 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7514 if (FixedLM) { 7515 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7516 << LM.toString() << 0, 7517 getLocationOfByte(LM.getStart()), 7518 /*IsStringLocation*/true, 7519 getSpecifierRange(startSpecifier, specifierLen)); 7520 7521 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7522 << FixedLM->toString() 7523 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7524 7525 } else { 7526 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7527 << LM.toString() << 0, 7528 getLocationOfByte(LM.getStart()), 7529 /*IsStringLocation*/true, 7530 getSpecifierRange(startSpecifier, specifierLen)); 7531 } 7532 } 7533 7534 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7535 const analyze_format_string::ConversionSpecifier &CS, 7536 const char *startSpecifier, unsigned specifierLen) { 7537 using namespace analyze_format_string; 7538 7539 // See if we know how to fix this conversion specifier. 7540 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7541 if (FixedCS) { 7542 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7543 << CS.toString() << /*conversion specifier*/1, 7544 getLocationOfByte(CS.getStart()), 7545 /*IsStringLocation*/true, 7546 getSpecifierRange(startSpecifier, specifierLen)); 7547 7548 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7549 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7550 << FixedCS->toString() 7551 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7552 } else { 7553 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7554 << CS.toString() << /*conversion specifier*/1, 7555 getLocationOfByte(CS.getStart()), 7556 /*IsStringLocation*/true, 7557 getSpecifierRange(startSpecifier, specifierLen)); 7558 } 7559 } 7560 7561 void CheckFormatHandler::HandlePosition(const char *startPos, 7562 unsigned posLen) { 7563 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7564 getLocationOfByte(startPos), 7565 /*IsStringLocation*/true, 7566 getSpecifierRange(startPos, posLen)); 7567 } 7568 7569 void 7570 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7571 analyze_format_string::PositionContext p) { 7572 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7573 << (unsigned) p, 7574 getLocationOfByte(startPos), /*IsStringLocation*/true, 7575 getSpecifierRange(startPos, posLen)); 7576 } 7577 7578 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7579 unsigned posLen) { 7580 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7581 getLocationOfByte(startPos), 7582 /*IsStringLocation*/true, 7583 getSpecifierRange(startPos, posLen)); 7584 } 7585 7586 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7587 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7588 // The presence of a null character is likely an error. 7589 EmitFormatDiagnostic( 7590 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7591 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7592 getFormatStringRange()); 7593 } 7594 } 7595 7596 // Note that this may return NULL if there was an error parsing or building 7597 // one of the argument expressions. 7598 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7599 return Args[FirstDataArg + i]; 7600 } 7601 7602 void CheckFormatHandler::DoneProcessing() { 7603 // Does the number of data arguments exceed the number of 7604 // format conversions in the format string? 7605 if (!HasVAListArg) { 7606 // Find any arguments that weren't covered. 7607 CoveredArgs.flip(); 7608 signed notCoveredArg = CoveredArgs.find_first(); 7609 if (notCoveredArg >= 0) { 7610 assert((unsigned)notCoveredArg < NumDataArgs); 7611 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7612 } else { 7613 UncoveredArg.setAllCovered(); 7614 } 7615 } 7616 } 7617 7618 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7619 const Expr *ArgExpr) { 7620 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7621 "Invalid state"); 7622 7623 if (!ArgExpr) 7624 return; 7625 7626 SourceLocation Loc = ArgExpr->getBeginLoc(); 7627 7628 if (S.getSourceManager().isInSystemMacro(Loc)) 7629 return; 7630 7631 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7632 for (auto E : DiagnosticExprs) 7633 PDiag << E->getSourceRange(); 7634 7635 CheckFormatHandler::EmitFormatDiagnostic( 7636 S, IsFunctionCall, DiagnosticExprs[0], 7637 PDiag, Loc, /*IsStringLocation*/false, 7638 DiagnosticExprs[0]->getSourceRange()); 7639 } 7640 7641 bool 7642 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7643 SourceLocation Loc, 7644 const char *startSpec, 7645 unsigned specifierLen, 7646 const char *csStart, 7647 unsigned csLen) { 7648 bool keepGoing = true; 7649 if (argIndex < NumDataArgs) { 7650 // Consider the argument coverered, even though the specifier doesn't 7651 // make sense. 7652 CoveredArgs.set(argIndex); 7653 } 7654 else { 7655 // If argIndex exceeds the number of data arguments we 7656 // don't issue a warning because that is just a cascade of warnings (and 7657 // they may have intended '%%' anyway). We don't want to continue processing 7658 // the format string after this point, however, as we will like just get 7659 // gibberish when trying to match arguments. 7660 keepGoing = false; 7661 } 7662 7663 StringRef Specifier(csStart, csLen); 7664 7665 // If the specifier in non-printable, it could be the first byte of a UTF-8 7666 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7667 // hex value. 7668 std::string CodePointStr; 7669 if (!llvm::sys::locale::isPrint(*csStart)) { 7670 llvm::UTF32 CodePoint; 7671 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7672 const llvm::UTF8 *E = 7673 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7674 llvm::ConversionResult Result = 7675 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7676 7677 if (Result != llvm::conversionOK) { 7678 unsigned char FirstChar = *csStart; 7679 CodePoint = (llvm::UTF32)FirstChar; 7680 } 7681 7682 llvm::raw_string_ostream OS(CodePointStr); 7683 if (CodePoint < 256) 7684 OS << "\\x" << llvm::format("%02x", CodePoint); 7685 else if (CodePoint <= 0xFFFF) 7686 OS << "\\u" << llvm::format("%04x", CodePoint); 7687 else 7688 OS << "\\U" << llvm::format("%08x", CodePoint); 7689 OS.flush(); 7690 Specifier = CodePointStr; 7691 } 7692 7693 EmitFormatDiagnostic( 7694 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7695 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7696 7697 return keepGoing; 7698 } 7699 7700 void 7701 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7702 const char *startSpec, 7703 unsigned specifierLen) { 7704 EmitFormatDiagnostic( 7705 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7706 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7707 } 7708 7709 bool 7710 CheckFormatHandler::CheckNumArgs( 7711 const analyze_format_string::FormatSpecifier &FS, 7712 const analyze_format_string::ConversionSpecifier &CS, 7713 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7714 7715 if (argIndex >= NumDataArgs) { 7716 PartialDiagnostic PDiag = FS.usesPositionalArg() 7717 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7718 << (argIndex+1) << NumDataArgs) 7719 : S.PDiag(diag::warn_printf_insufficient_data_args); 7720 EmitFormatDiagnostic( 7721 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7722 getSpecifierRange(startSpecifier, specifierLen)); 7723 7724 // Since more arguments than conversion tokens are given, by extension 7725 // all arguments are covered, so mark this as so. 7726 UncoveredArg.setAllCovered(); 7727 return false; 7728 } 7729 return true; 7730 } 7731 7732 template<typename Range> 7733 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7734 SourceLocation Loc, 7735 bool IsStringLocation, 7736 Range StringRange, 7737 ArrayRef<FixItHint> FixIt) { 7738 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7739 Loc, IsStringLocation, StringRange, FixIt); 7740 } 7741 7742 /// If the format string is not within the function call, emit a note 7743 /// so that the function call and string are in diagnostic messages. 7744 /// 7745 /// \param InFunctionCall if true, the format string is within the function 7746 /// call and only one diagnostic message will be produced. Otherwise, an 7747 /// extra note will be emitted pointing to location of the format string. 7748 /// 7749 /// \param ArgumentExpr the expression that is passed as the format string 7750 /// argument in the function call. Used for getting locations when two 7751 /// diagnostics are emitted. 7752 /// 7753 /// \param PDiag the callee should already have provided any strings for the 7754 /// diagnostic message. This function only adds locations and fixits 7755 /// to diagnostics. 7756 /// 7757 /// \param Loc primary location for diagnostic. If two diagnostics are 7758 /// required, one will be at Loc and a new SourceLocation will be created for 7759 /// the other one. 7760 /// 7761 /// \param IsStringLocation if true, Loc points to the format string should be 7762 /// used for the note. Otherwise, Loc points to the argument list and will 7763 /// be used with PDiag. 7764 /// 7765 /// \param StringRange some or all of the string to highlight. This is 7766 /// templated so it can accept either a CharSourceRange or a SourceRange. 7767 /// 7768 /// \param FixIt optional fix it hint for the format string. 7769 template <typename Range> 7770 void CheckFormatHandler::EmitFormatDiagnostic( 7771 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7772 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7773 Range StringRange, ArrayRef<FixItHint> FixIt) { 7774 if (InFunctionCall) { 7775 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7776 D << StringRange; 7777 D << FixIt; 7778 } else { 7779 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7780 << ArgumentExpr->getSourceRange(); 7781 7782 const Sema::SemaDiagnosticBuilder &Note = 7783 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7784 diag::note_format_string_defined); 7785 7786 Note << StringRange; 7787 Note << FixIt; 7788 } 7789 } 7790 7791 //===--- CHECK: Printf format string checking ------------------------------===// 7792 7793 namespace { 7794 7795 class CheckPrintfHandler : public CheckFormatHandler { 7796 public: 7797 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7798 const Expr *origFormatExpr, 7799 const Sema::FormatStringType type, unsigned firstDataArg, 7800 unsigned numDataArgs, bool isObjC, const char *beg, 7801 bool hasVAListArg, ArrayRef<const Expr *> Args, 7802 unsigned formatIdx, bool inFunctionCall, 7803 Sema::VariadicCallType CallType, 7804 llvm::SmallBitVector &CheckedVarArgs, 7805 UncoveredArgHandler &UncoveredArg) 7806 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7807 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7808 inFunctionCall, CallType, CheckedVarArgs, 7809 UncoveredArg) {} 7810 7811 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7812 7813 /// Returns true if '%@' specifiers are allowed in the format string. 7814 bool allowsObjCArg() const { 7815 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7816 FSType == Sema::FST_OSTrace; 7817 } 7818 7819 bool HandleInvalidPrintfConversionSpecifier( 7820 const analyze_printf::PrintfSpecifier &FS, 7821 const char *startSpecifier, 7822 unsigned specifierLen) override; 7823 7824 void handleInvalidMaskType(StringRef MaskType) override; 7825 7826 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7827 const char *startSpecifier, 7828 unsigned specifierLen) override; 7829 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7830 const char *StartSpecifier, 7831 unsigned SpecifierLen, 7832 const Expr *E); 7833 7834 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7835 const char *startSpecifier, unsigned specifierLen); 7836 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7837 const analyze_printf::OptionalAmount &Amt, 7838 unsigned type, 7839 const char *startSpecifier, unsigned specifierLen); 7840 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7841 const analyze_printf::OptionalFlag &flag, 7842 const char *startSpecifier, unsigned specifierLen); 7843 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7844 const analyze_printf::OptionalFlag &ignoredFlag, 7845 const analyze_printf::OptionalFlag &flag, 7846 const char *startSpecifier, unsigned specifierLen); 7847 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7848 const Expr *E); 7849 7850 void HandleEmptyObjCModifierFlag(const char *startFlag, 7851 unsigned flagLen) override; 7852 7853 void HandleInvalidObjCModifierFlag(const char *startFlag, 7854 unsigned flagLen) override; 7855 7856 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7857 const char *flagsEnd, 7858 const char *conversionPosition) 7859 override; 7860 }; 7861 7862 } // namespace 7863 7864 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7865 const analyze_printf::PrintfSpecifier &FS, 7866 const char *startSpecifier, 7867 unsigned specifierLen) { 7868 const analyze_printf::PrintfConversionSpecifier &CS = 7869 FS.getConversionSpecifier(); 7870 7871 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7872 getLocationOfByte(CS.getStart()), 7873 startSpecifier, specifierLen, 7874 CS.getStart(), CS.getLength()); 7875 } 7876 7877 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7878 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7879 } 7880 7881 bool CheckPrintfHandler::HandleAmount( 7882 const analyze_format_string::OptionalAmount &Amt, 7883 unsigned k, const char *startSpecifier, 7884 unsigned specifierLen) { 7885 if (Amt.hasDataArgument()) { 7886 if (!HasVAListArg) { 7887 unsigned argIndex = Amt.getArgIndex(); 7888 if (argIndex >= NumDataArgs) { 7889 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7890 << k, 7891 getLocationOfByte(Amt.getStart()), 7892 /*IsStringLocation*/true, 7893 getSpecifierRange(startSpecifier, specifierLen)); 7894 // Don't do any more checking. We will just emit 7895 // spurious errors. 7896 return false; 7897 } 7898 7899 // Type check the data argument. It should be an 'int'. 7900 // Although not in conformance with C99, we also allow the argument to be 7901 // an 'unsigned int' as that is a reasonably safe case. GCC also 7902 // doesn't emit a warning for that case. 7903 CoveredArgs.set(argIndex); 7904 const Expr *Arg = getDataArg(argIndex); 7905 if (!Arg) 7906 return false; 7907 7908 QualType T = Arg->getType(); 7909 7910 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7911 assert(AT.isValid()); 7912 7913 if (!AT.matchesType(S.Context, T)) { 7914 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7915 << k << AT.getRepresentativeTypeName(S.Context) 7916 << T << Arg->getSourceRange(), 7917 getLocationOfByte(Amt.getStart()), 7918 /*IsStringLocation*/true, 7919 getSpecifierRange(startSpecifier, specifierLen)); 7920 // Don't do any more checking. We will just emit 7921 // spurious errors. 7922 return false; 7923 } 7924 } 7925 } 7926 return true; 7927 } 7928 7929 void CheckPrintfHandler::HandleInvalidAmount( 7930 const analyze_printf::PrintfSpecifier &FS, 7931 const analyze_printf::OptionalAmount &Amt, 7932 unsigned type, 7933 const char *startSpecifier, 7934 unsigned specifierLen) { 7935 const analyze_printf::PrintfConversionSpecifier &CS = 7936 FS.getConversionSpecifier(); 7937 7938 FixItHint fixit = 7939 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7940 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7941 Amt.getConstantLength())) 7942 : FixItHint(); 7943 7944 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7945 << type << CS.toString(), 7946 getLocationOfByte(Amt.getStart()), 7947 /*IsStringLocation*/true, 7948 getSpecifierRange(startSpecifier, specifierLen), 7949 fixit); 7950 } 7951 7952 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7953 const analyze_printf::OptionalFlag &flag, 7954 const char *startSpecifier, 7955 unsigned specifierLen) { 7956 // Warn about pointless flag with a fixit removal. 7957 const analyze_printf::PrintfConversionSpecifier &CS = 7958 FS.getConversionSpecifier(); 7959 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7960 << flag.toString() << CS.toString(), 7961 getLocationOfByte(flag.getPosition()), 7962 /*IsStringLocation*/true, 7963 getSpecifierRange(startSpecifier, specifierLen), 7964 FixItHint::CreateRemoval( 7965 getSpecifierRange(flag.getPosition(), 1))); 7966 } 7967 7968 void CheckPrintfHandler::HandleIgnoredFlag( 7969 const analyze_printf::PrintfSpecifier &FS, 7970 const analyze_printf::OptionalFlag &ignoredFlag, 7971 const analyze_printf::OptionalFlag &flag, 7972 const char *startSpecifier, 7973 unsigned specifierLen) { 7974 // Warn about ignored flag with a fixit removal. 7975 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7976 << ignoredFlag.toString() << flag.toString(), 7977 getLocationOfByte(ignoredFlag.getPosition()), 7978 /*IsStringLocation*/true, 7979 getSpecifierRange(startSpecifier, specifierLen), 7980 FixItHint::CreateRemoval( 7981 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7982 } 7983 7984 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7985 unsigned flagLen) { 7986 // Warn about an empty flag. 7987 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7988 getLocationOfByte(startFlag), 7989 /*IsStringLocation*/true, 7990 getSpecifierRange(startFlag, flagLen)); 7991 } 7992 7993 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7994 unsigned flagLen) { 7995 // Warn about an invalid flag. 7996 auto Range = getSpecifierRange(startFlag, flagLen); 7997 StringRef flag(startFlag, flagLen); 7998 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7999 getLocationOfByte(startFlag), 8000 /*IsStringLocation*/true, 8001 Range, FixItHint::CreateRemoval(Range)); 8002 } 8003 8004 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8005 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8006 // Warn about using '[...]' without a '@' conversion. 8007 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8008 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8009 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8010 getLocationOfByte(conversionPosition), 8011 /*IsStringLocation*/true, 8012 Range, FixItHint::CreateRemoval(Range)); 8013 } 8014 8015 // Determines if the specified is a C++ class or struct containing 8016 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8017 // "c_str()"). 8018 template<typename MemberKind> 8019 static llvm::SmallPtrSet<MemberKind*, 1> 8020 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8021 const RecordType *RT = Ty->getAs<RecordType>(); 8022 llvm::SmallPtrSet<MemberKind*, 1> Results; 8023 8024 if (!RT) 8025 return Results; 8026 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8027 if (!RD || !RD->getDefinition()) 8028 return Results; 8029 8030 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8031 Sema::LookupMemberName); 8032 R.suppressDiagnostics(); 8033 8034 // We just need to include all members of the right kind turned up by the 8035 // filter, at this point. 8036 if (S.LookupQualifiedName(R, RT->getDecl())) 8037 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8038 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8039 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8040 Results.insert(FK); 8041 } 8042 return Results; 8043 } 8044 8045 /// Check if we could call '.c_str()' on an object. 8046 /// 8047 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8048 /// allow the call, or if it would be ambiguous). 8049 bool Sema::hasCStrMethod(const Expr *E) { 8050 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8051 8052 MethodSet Results = 8053 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8054 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8055 MI != ME; ++MI) 8056 if ((*MI)->getMinRequiredArguments() == 0) 8057 return true; 8058 return false; 8059 } 8060 8061 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8062 // better diagnostic if so. AT is assumed to be valid. 8063 // Returns true when a c_str() conversion method is found. 8064 bool CheckPrintfHandler::checkForCStrMembers( 8065 const analyze_printf::ArgType &AT, const Expr *E) { 8066 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8067 8068 MethodSet Results = 8069 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8070 8071 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8072 MI != ME; ++MI) { 8073 const CXXMethodDecl *Method = *MI; 8074 if (Method->getMinRequiredArguments() == 0 && 8075 AT.matchesType(S.Context, Method->getReturnType())) { 8076 // FIXME: Suggest parens if the expression needs them. 8077 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8078 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8079 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8080 return true; 8081 } 8082 } 8083 8084 return false; 8085 } 8086 8087 bool 8088 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8089 &FS, 8090 const char *startSpecifier, 8091 unsigned specifierLen) { 8092 using namespace analyze_format_string; 8093 using namespace analyze_printf; 8094 8095 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8096 8097 if (FS.consumesDataArgument()) { 8098 if (atFirstArg) { 8099 atFirstArg = false; 8100 usesPositionalArgs = FS.usesPositionalArg(); 8101 } 8102 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8103 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8104 startSpecifier, specifierLen); 8105 return false; 8106 } 8107 } 8108 8109 // First check if the field width, precision, and conversion specifier 8110 // have matching data arguments. 8111 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8112 startSpecifier, specifierLen)) { 8113 return false; 8114 } 8115 8116 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8117 startSpecifier, specifierLen)) { 8118 return false; 8119 } 8120 8121 if (!CS.consumesDataArgument()) { 8122 // FIXME: Technically specifying a precision or field width here 8123 // makes no sense. Worth issuing a warning at some point. 8124 return true; 8125 } 8126 8127 // Consume the argument. 8128 unsigned argIndex = FS.getArgIndex(); 8129 if (argIndex < NumDataArgs) { 8130 // The check to see if the argIndex is valid will come later. 8131 // We set the bit here because we may exit early from this 8132 // function if we encounter some other error. 8133 CoveredArgs.set(argIndex); 8134 } 8135 8136 // FreeBSD kernel extensions. 8137 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8138 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8139 // We need at least two arguments. 8140 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8141 return false; 8142 8143 // Claim the second argument. 8144 CoveredArgs.set(argIndex + 1); 8145 8146 const Expr *Ex = getDataArg(argIndex); 8147 if (CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8148 // Type check the first argument (pointer for %D) 8149 const analyze_printf::ArgType &AT = ArgType::CPointerTy; 8150 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8151 EmitFormatDiagnostic( 8152 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8153 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8154 << false << Ex->getSourceRange(), 8155 Ex->getBeginLoc(), /*IsStringLocation*/false, 8156 getSpecifierRange(startSpecifier, specifierLen)); 8157 } else { 8158 // Check the length modifier for %b 8159 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8160 S.getLangOpts())) 8161 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8162 diag::warn_format_nonsensical_length); 8163 else if (!FS.hasStandardLengthModifier()) 8164 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8165 else if (!FS.hasStandardLengthConversionCombination()) 8166 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8167 diag::warn_format_non_standard_conversion_spec); 8168 8169 // Type check the first argument of %b 8170 if (!checkFormatExpr(FS, startSpecifier, specifierLen, Ex)) 8171 return false; 8172 } 8173 8174 // Type check the second argument (char * for both %b and %D) 8175 Ex = getDataArg(argIndex + 1); 8176 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8177 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8178 EmitFormatDiagnostic( 8179 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8180 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8181 << false << Ex->getSourceRange(), 8182 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8183 getSpecifierRange(startSpecifier, specifierLen)); 8184 8185 return true; 8186 } 8187 8188 // Check for using an Objective-C specific conversion specifier 8189 // in a non-ObjC literal. 8190 if (!allowsObjCArg() && CS.isObjCArg()) { 8191 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8192 specifierLen); 8193 } 8194 8195 // %P can only be used with os_log. 8196 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8197 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8198 specifierLen); 8199 } 8200 8201 // %n is not allowed with os_log. 8202 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8203 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8204 getLocationOfByte(CS.getStart()), 8205 /*IsStringLocation*/ false, 8206 getSpecifierRange(startSpecifier, specifierLen)); 8207 8208 return true; 8209 } 8210 8211 // Only scalars are allowed for os_trace. 8212 if (FSType == Sema::FST_OSTrace && 8213 (CS.getKind() == ConversionSpecifier::PArg || 8214 CS.getKind() == ConversionSpecifier::sArg || 8215 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8216 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8217 specifierLen); 8218 } 8219 8220 // Check for use of public/private annotation outside of os_log(). 8221 if (FSType != Sema::FST_OSLog) { 8222 if (FS.isPublic().isSet()) { 8223 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8224 << "public", 8225 getLocationOfByte(FS.isPublic().getPosition()), 8226 /*IsStringLocation*/ false, 8227 getSpecifierRange(startSpecifier, specifierLen)); 8228 } 8229 if (FS.isPrivate().isSet()) { 8230 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8231 << "private", 8232 getLocationOfByte(FS.isPrivate().getPosition()), 8233 /*IsStringLocation*/ false, 8234 getSpecifierRange(startSpecifier, specifierLen)); 8235 } 8236 } 8237 8238 // Check for invalid use of field width 8239 if (!FS.hasValidFieldWidth()) { 8240 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8241 startSpecifier, specifierLen); 8242 } 8243 8244 // Check for invalid use of precision 8245 if (!FS.hasValidPrecision()) { 8246 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8247 startSpecifier, specifierLen); 8248 } 8249 8250 // Precision is mandatory for %P specifier. 8251 if (CS.getKind() == ConversionSpecifier::PArg && 8252 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8253 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8254 getLocationOfByte(startSpecifier), 8255 /*IsStringLocation*/ false, 8256 getSpecifierRange(startSpecifier, specifierLen)); 8257 } 8258 8259 // Check each flag does not conflict with any other component. 8260 if (!FS.hasValidThousandsGroupingPrefix()) 8261 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8262 if (!FS.hasValidLeadingZeros()) 8263 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8264 if (!FS.hasValidPlusPrefix()) 8265 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8266 if (!FS.hasValidSpacePrefix()) 8267 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8268 if (!FS.hasValidAlternativeForm()) 8269 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8270 if (!FS.hasValidLeftJustified()) 8271 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8272 8273 // Check that flags are not ignored by another flag 8274 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8275 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8276 startSpecifier, specifierLen); 8277 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8278 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8279 startSpecifier, specifierLen); 8280 8281 // Check the length modifier is valid with the given conversion specifier. 8282 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8283 S.getLangOpts())) 8284 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8285 diag::warn_format_nonsensical_length); 8286 else if (!FS.hasStandardLengthModifier()) 8287 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8288 else if (!FS.hasStandardLengthConversionCombination()) 8289 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8290 diag::warn_format_non_standard_conversion_spec); 8291 8292 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8293 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8294 8295 // The remaining checks depend on the data arguments. 8296 if (HasVAListArg) 8297 return true; 8298 8299 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8300 return false; 8301 8302 const Expr *Arg = getDataArg(argIndex); 8303 if (!Arg) 8304 return true; 8305 8306 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8307 } 8308 8309 static bool requiresParensToAddCast(const Expr *E) { 8310 // FIXME: We should have a general way to reason about operator 8311 // precedence and whether parens are actually needed here. 8312 // Take care of a few common cases where they aren't. 8313 const Expr *Inside = E->IgnoreImpCasts(); 8314 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8315 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8316 8317 switch (Inside->getStmtClass()) { 8318 case Stmt::ArraySubscriptExprClass: 8319 case Stmt::CallExprClass: 8320 case Stmt::CharacterLiteralClass: 8321 case Stmt::CXXBoolLiteralExprClass: 8322 case Stmt::DeclRefExprClass: 8323 case Stmt::FloatingLiteralClass: 8324 case Stmt::IntegerLiteralClass: 8325 case Stmt::MemberExprClass: 8326 case Stmt::ObjCArrayLiteralClass: 8327 case Stmt::ObjCBoolLiteralExprClass: 8328 case Stmt::ObjCBoxedExprClass: 8329 case Stmt::ObjCDictionaryLiteralClass: 8330 case Stmt::ObjCEncodeExprClass: 8331 case Stmt::ObjCIvarRefExprClass: 8332 case Stmt::ObjCMessageExprClass: 8333 case Stmt::ObjCPropertyRefExprClass: 8334 case Stmt::ObjCStringLiteralClass: 8335 case Stmt::ObjCSubscriptRefExprClass: 8336 case Stmt::ParenExprClass: 8337 case Stmt::StringLiteralClass: 8338 case Stmt::UnaryOperatorClass: 8339 return false; 8340 default: 8341 return true; 8342 } 8343 } 8344 8345 static std::pair<QualType, StringRef> 8346 shouldNotPrintDirectly(const ASTContext &Context, 8347 QualType IntendedTy, 8348 const Expr *E) { 8349 // Use a 'while' to peel off layers of typedefs. 8350 QualType TyTy = IntendedTy; 8351 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8352 StringRef Name = UserTy->getDecl()->getName(); 8353 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8354 .Case("CFIndex", Context.getNSIntegerType()) 8355 .Case("NSInteger", Context.getNSIntegerType()) 8356 .Case("NSUInteger", Context.getNSUIntegerType()) 8357 .Case("SInt32", Context.IntTy) 8358 .Case("UInt32", Context.UnsignedIntTy) 8359 .Default(QualType()); 8360 8361 if (!CastTy.isNull()) 8362 return std::make_pair(CastTy, Name); 8363 8364 TyTy = UserTy->desugar(); 8365 } 8366 8367 // Strip parens if necessary. 8368 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8369 return shouldNotPrintDirectly(Context, 8370 PE->getSubExpr()->getType(), 8371 PE->getSubExpr()); 8372 8373 // If this is a conditional expression, then its result type is constructed 8374 // via usual arithmetic conversions and thus there might be no necessary 8375 // typedef sugar there. Recurse to operands to check for NSInteger & 8376 // Co. usage condition. 8377 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8378 QualType TrueTy, FalseTy; 8379 StringRef TrueName, FalseName; 8380 8381 std::tie(TrueTy, TrueName) = 8382 shouldNotPrintDirectly(Context, 8383 CO->getTrueExpr()->getType(), 8384 CO->getTrueExpr()); 8385 std::tie(FalseTy, FalseName) = 8386 shouldNotPrintDirectly(Context, 8387 CO->getFalseExpr()->getType(), 8388 CO->getFalseExpr()); 8389 8390 if (TrueTy == FalseTy) 8391 return std::make_pair(TrueTy, TrueName); 8392 else if (TrueTy.isNull()) 8393 return std::make_pair(FalseTy, FalseName); 8394 else if (FalseTy.isNull()) 8395 return std::make_pair(TrueTy, TrueName); 8396 } 8397 8398 return std::make_pair(QualType(), StringRef()); 8399 } 8400 8401 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8402 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8403 /// type do not count. 8404 static bool 8405 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8406 QualType From = ICE->getSubExpr()->getType(); 8407 QualType To = ICE->getType(); 8408 // It's an integer promotion if the destination type is the promoted 8409 // source type. 8410 if (ICE->getCastKind() == CK_IntegralCast && 8411 From->isPromotableIntegerType() && 8412 S.Context.getPromotedIntegerType(From) == To) 8413 return true; 8414 // Look through vector types, since we do default argument promotion for 8415 // those in OpenCL. 8416 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8417 From = VecTy->getElementType(); 8418 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8419 To = VecTy->getElementType(); 8420 // It's a floating promotion if the source type is a lower rank. 8421 return ICE->getCastKind() == CK_FloatingCast && 8422 S.Context.getFloatingTypeOrder(From, To) < 0; 8423 } 8424 8425 bool 8426 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8427 const char *StartSpecifier, 8428 unsigned SpecifierLen, 8429 const Expr *E) { 8430 using namespace analyze_format_string; 8431 using namespace analyze_printf; 8432 8433 // Now type check the data expression that matches the 8434 // format specifier. 8435 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8436 if (!AT.isValid()) 8437 return true; 8438 8439 QualType ExprTy = E->getType(); 8440 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8441 ExprTy = TET->getUnderlyingExpr()->getType(); 8442 } 8443 8444 // Diagnose attempts to print a boolean value as a character. Unlike other 8445 // -Wformat diagnostics, this is fine from a type perspective, but it still 8446 // doesn't make sense. 8447 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8448 E->isKnownToHaveBooleanValue()) { 8449 const CharSourceRange &CSR = 8450 getSpecifierRange(StartSpecifier, SpecifierLen); 8451 SmallString<4> FSString; 8452 llvm::raw_svector_ostream os(FSString); 8453 FS.toString(os); 8454 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8455 << FSString, 8456 E->getExprLoc(), false, CSR); 8457 return true; 8458 } 8459 8460 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8461 if (Match == analyze_printf::ArgType::Match) 8462 return true; 8463 8464 // Look through argument promotions for our error message's reported type. 8465 // This includes the integral and floating promotions, but excludes array 8466 // and function pointer decay (seeing that an argument intended to be a 8467 // string has type 'char [6]' is probably more confusing than 'char *') and 8468 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8469 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8470 if (isArithmeticArgumentPromotion(S, ICE)) { 8471 E = ICE->getSubExpr(); 8472 ExprTy = E->getType(); 8473 8474 // Check if we didn't match because of an implicit cast from a 'char' 8475 // or 'short' to an 'int'. This is done because printf is a varargs 8476 // function. 8477 if (ICE->getType() == S.Context.IntTy || 8478 ICE->getType() == S.Context.UnsignedIntTy) { 8479 // All further checking is done on the subexpression 8480 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8481 AT.matchesType(S.Context, ExprTy); 8482 if (ImplicitMatch == analyze_printf::ArgType::Match) 8483 return true; 8484 if (ImplicitMatch == ArgType::NoMatchPedantic || 8485 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8486 Match = ImplicitMatch; 8487 } 8488 } 8489 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8490 // Special case for 'a', which has type 'int' in C. 8491 // Note, however, that we do /not/ want to treat multibyte constants like 8492 // 'MooV' as characters! This form is deprecated but still exists. 8493 if (ExprTy == S.Context.IntTy) 8494 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8495 ExprTy = S.Context.CharTy; 8496 } 8497 8498 // Look through enums to their underlying type. 8499 bool IsEnum = false; 8500 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8501 ExprTy = EnumTy->getDecl()->getIntegerType(); 8502 IsEnum = true; 8503 } 8504 8505 // %C in an Objective-C context prints a unichar, not a wchar_t. 8506 // If the argument is an integer of some kind, believe the %C and suggest 8507 // a cast instead of changing the conversion specifier. 8508 QualType IntendedTy = ExprTy; 8509 if (isObjCContext() && 8510 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8511 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8512 !ExprTy->isCharType()) { 8513 // 'unichar' is defined as a typedef of unsigned short, but we should 8514 // prefer using the typedef if it is visible. 8515 IntendedTy = S.Context.UnsignedShortTy; 8516 8517 // While we are here, check if the value is an IntegerLiteral that happens 8518 // to be within the valid range. 8519 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8520 const llvm::APInt &V = IL->getValue(); 8521 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8522 return true; 8523 } 8524 8525 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8526 Sema::LookupOrdinaryName); 8527 if (S.LookupName(Result, S.getCurScope())) { 8528 NamedDecl *ND = Result.getFoundDecl(); 8529 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8530 if (TD->getUnderlyingType() == IntendedTy) 8531 IntendedTy = S.Context.getTypedefType(TD); 8532 } 8533 } 8534 } 8535 8536 // Special-case some of Darwin's platform-independence types by suggesting 8537 // casts to primitive types that are known to be large enough. 8538 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8539 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8540 QualType CastTy; 8541 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8542 if (!CastTy.isNull()) { 8543 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8544 // (long in ASTContext). Only complain to pedants. 8545 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8546 (AT.isSizeT() || AT.isPtrdiffT()) && 8547 AT.matchesType(S.Context, CastTy)) 8548 Match = ArgType::NoMatchPedantic; 8549 IntendedTy = CastTy; 8550 ShouldNotPrintDirectly = true; 8551 } 8552 } 8553 8554 // We may be able to offer a FixItHint if it is a supported type. 8555 PrintfSpecifier fixedFS = FS; 8556 bool Success = 8557 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8558 8559 if (Success) { 8560 // Get the fix string from the fixed format specifier 8561 SmallString<16> buf; 8562 llvm::raw_svector_ostream os(buf); 8563 fixedFS.toString(os); 8564 8565 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8566 8567 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8568 unsigned Diag; 8569 switch (Match) { 8570 case ArgType::Match: llvm_unreachable("expected non-matching"); 8571 case ArgType::NoMatchPedantic: 8572 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8573 break; 8574 case ArgType::NoMatchTypeConfusion: 8575 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8576 break; 8577 case ArgType::NoMatch: 8578 Diag = diag::warn_format_conversion_argument_type_mismatch; 8579 break; 8580 } 8581 8582 // In this case, the specifier is wrong and should be changed to match 8583 // the argument. 8584 EmitFormatDiagnostic(S.PDiag(Diag) 8585 << AT.getRepresentativeTypeName(S.Context) 8586 << IntendedTy << IsEnum << E->getSourceRange(), 8587 E->getBeginLoc(), 8588 /*IsStringLocation*/ false, SpecRange, 8589 FixItHint::CreateReplacement(SpecRange, os.str())); 8590 } else { 8591 // The canonical type for formatting this value is different from the 8592 // actual type of the expression. (This occurs, for example, with Darwin's 8593 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8594 // should be printed as 'long' for 64-bit compatibility.) 8595 // Rather than emitting a normal format/argument mismatch, we want to 8596 // add a cast to the recommended type (and correct the format string 8597 // if necessary). 8598 SmallString<16> CastBuf; 8599 llvm::raw_svector_ostream CastFix(CastBuf); 8600 CastFix << "("; 8601 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8602 CastFix << ")"; 8603 8604 SmallVector<FixItHint,4> Hints; 8605 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8606 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8607 8608 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8609 // If there's already a cast present, just replace it. 8610 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8611 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8612 8613 } else if (!requiresParensToAddCast(E)) { 8614 // If the expression has high enough precedence, 8615 // just write the C-style cast. 8616 Hints.push_back( 8617 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8618 } else { 8619 // Otherwise, add parens around the expression as well as the cast. 8620 CastFix << "("; 8621 Hints.push_back( 8622 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8623 8624 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8625 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8626 } 8627 8628 if (ShouldNotPrintDirectly) { 8629 // The expression has a type that should not be printed directly. 8630 // We extract the name from the typedef because we don't want to show 8631 // the underlying type in the diagnostic. 8632 StringRef Name; 8633 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8634 Name = TypedefTy->getDecl()->getName(); 8635 else 8636 Name = CastTyName; 8637 unsigned Diag = Match == ArgType::NoMatchPedantic 8638 ? diag::warn_format_argument_needs_cast_pedantic 8639 : diag::warn_format_argument_needs_cast; 8640 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8641 << E->getSourceRange(), 8642 E->getBeginLoc(), /*IsStringLocation=*/false, 8643 SpecRange, Hints); 8644 } else { 8645 // In this case, the expression could be printed using a different 8646 // specifier, but we've decided that the specifier is probably correct 8647 // and we should cast instead. Just use the normal warning message. 8648 EmitFormatDiagnostic( 8649 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8650 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8651 << E->getSourceRange(), 8652 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8653 } 8654 } 8655 } else { 8656 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8657 SpecifierLen); 8658 // Since the warning for passing non-POD types to variadic functions 8659 // was deferred until now, we emit a warning for non-POD 8660 // arguments here. 8661 switch (S.isValidVarArgType(ExprTy)) { 8662 case Sema::VAK_Valid: 8663 case Sema::VAK_ValidInCXX11: { 8664 unsigned Diag; 8665 switch (Match) { 8666 case ArgType::Match: llvm_unreachable("expected non-matching"); 8667 case ArgType::NoMatchPedantic: 8668 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8669 break; 8670 case ArgType::NoMatchTypeConfusion: 8671 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8672 break; 8673 case ArgType::NoMatch: 8674 Diag = diag::warn_format_conversion_argument_type_mismatch; 8675 break; 8676 } 8677 8678 EmitFormatDiagnostic( 8679 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8680 << IsEnum << CSR << E->getSourceRange(), 8681 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8682 break; 8683 } 8684 case Sema::VAK_Undefined: 8685 case Sema::VAK_MSVCUndefined: 8686 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8687 << S.getLangOpts().CPlusPlus11 << ExprTy 8688 << CallType 8689 << AT.getRepresentativeTypeName(S.Context) << CSR 8690 << E->getSourceRange(), 8691 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8692 checkForCStrMembers(AT, E); 8693 break; 8694 8695 case Sema::VAK_Invalid: 8696 if (ExprTy->isObjCObjectType()) 8697 EmitFormatDiagnostic( 8698 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8699 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8700 << AT.getRepresentativeTypeName(S.Context) << CSR 8701 << E->getSourceRange(), 8702 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8703 else 8704 // FIXME: If this is an initializer list, suggest removing the braces 8705 // or inserting a cast to the target type. 8706 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8707 << isa<InitListExpr>(E) << ExprTy << CallType 8708 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8709 break; 8710 } 8711 8712 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8713 "format string specifier index out of range"); 8714 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8715 } 8716 8717 return true; 8718 } 8719 8720 //===--- CHECK: Scanf format string checking ------------------------------===// 8721 8722 namespace { 8723 8724 class CheckScanfHandler : public CheckFormatHandler { 8725 public: 8726 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8727 const Expr *origFormatExpr, Sema::FormatStringType type, 8728 unsigned firstDataArg, unsigned numDataArgs, 8729 const char *beg, bool hasVAListArg, 8730 ArrayRef<const Expr *> Args, unsigned formatIdx, 8731 bool inFunctionCall, Sema::VariadicCallType CallType, 8732 llvm::SmallBitVector &CheckedVarArgs, 8733 UncoveredArgHandler &UncoveredArg) 8734 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8735 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8736 inFunctionCall, CallType, CheckedVarArgs, 8737 UncoveredArg) {} 8738 8739 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8740 const char *startSpecifier, 8741 unsigned specifierLen) override; 8742 8743 bool HandleInvalidScanfConversionSpecifier( 8744 const analyze_scanf::ScanfSpecifier &FS, 8745 const char *startSpecifier, 8746 unsigned specifierLen) override; 8747 8748 void HandleIncompleteScanList(const char *start, const char *end) override; 8749 }; 8750 8751 } // namespace 8752 8753 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8754 const char *end) { 8755 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8756 getLocationOfByte(end), /*IsStringLocation*/true, 8757 getSpecifierRange(start, end - start)); 8758 } 8759 8760 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8761 const analyze_scanf::ScanfSpecifier &FS, 8762 const char *startSpecifier, 8763 unsigned specifierLen) { 8764 const analyze_scanf::ScanfConversionSpecifier &CS = 8765 FS.getConversionSpecifier(); 8766 8767 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8768 getLocationOfByte(CS.getStart()), 8769 startSpecifier, specifierLen, 8770 CS.getStart(), CS.getLength()); 8771 } 8772 8773 bool CheckScanfHandler::HandleScanfSpecifier( 8774 const analyze_scanf::ScanfSpecifier &FS, 8775 const char *startSpecifier, 8776 unsigned specifierLen) { 8777 using namespace analyze_scanf; 8778 using namespace analyze_format_string; 8779 8780 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8781 8782 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8783 // be used to decide if we are using positional arguments consistently. 8784 if (FS.consumesDataArgument()) { 8785 if (atFirstArg) { 8786 atFirstArg = false; 8787 usesPositionalArgs = FS.usesPositionalArg(); 8788 } 8789 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8790 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8791 startSpecifier, specifierLen); 8792 return false; 8793 } 8794 } 8795 8796 // Check if the field with is non-zero. 8797 const OptionalAmount &Amt = FS.getFieldWidth(); 8798 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8799 if (Amt.getConstantAmount() == 0) { 8800 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8801 Amt.getConstantLength()); 8802 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8803 getLocationOfByte(Amt.getStart()), 8804 /*IsStringLocation*/true, R, 8805 FixItHint::CreateRemoval(R)); 8806 } 8807 } 8808 8809 if (!FS.consumesDataArgument()) { 8810 // FIXME: Technically specifying a precision or field width here 8811 // makes no sense. Worth issuing a warning at some point. 8812 return true; 8813 } 8814 8815 // Consume the argument. 8816 unsigned argIndex = FS.getArgIndex(); 8817 if (argIndex < NumDataArgs) { 8818 // The check to see if the argIndex is valid will come later. 8819 // We set the bit here because we may exit early from this 8820 // function if we encounter some other error. 8821 CoveredArgs.set(argIndex); 8822 } 8823 8824 // Check the length modifier is valid with the given conversion specifier. 8825 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8826 S.getLangOpts())) 8827 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8828 diag::warn_format_nonsensical_length); 8829 else if (!FS.hasStandardLengthModifier()) 8830 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8831 else if (!FS.hasStandardLengthConversionCombination()) 8832 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8833 diag::warn_format_non_standard_conversion_spec); 8834 8835 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8836 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8837 8838 // The remaining checks depend on the data arguments. 8839 if (HasVAListArg) 8840 return true; 8841 8842 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8843 return false; 8844 8845 // Check that the argument type matches the format specifier. 8846 const Expr *Ex = getDataArg(argIndex); 8847 if (!Ex) 8848 return true; 8849 8850 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8851 8852 if (!AT.isValid()) { 8853 return true; 8854 } 8855 8856 analyze_format_string::ArgType::MatchKind Match = 8857 AT.matchesType(S.Context, Ex->getType()); 8858 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8859 if (Match == analyze_format_string::ArgType::Match) 8860 return true; 8861 8862 ScanfSpecifier fixedFS = FS; 8863 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8864 S.getLangOpts(), S.Context); 8865 8866 unsigned Diag = 8867 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8868 : diag::warn_format_conversion_argument_type_mismatch; 8869 8870 if (Success) { 8871 // Get the fix string from the fixed format specifier. 8872 SmallString<128> buf; 8873 llvm::raw_svector_ostream os(buf); 8874 fixedFS.toString(os); 8875 8876 EmitFormatDiagnostic( 8877 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8878 << Ex->getType() << false << Ex->getSourceRange(), 8879 Ex->getBeginLoc(), 8880 /*IsStringLocation*/ false, 8881 getSpecifierRange(startSpecifier, specifierLen), 8882 FixItHint::CreateReplacement( 8883 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8884 } else { 8885 EmitFormatDiagnostic(S.PDiag(Diag) 8886 << AT.getRepresentativeTypeName(S.Context) 8887 << Ex->getType() << false << Ex->getSourceRange(), 8888 Ex->getBeginLoc(), 8889 /*IsStringLocation*/ false, 8890 getSpecifierRange(startSpecifier, specifierLen)); 8891 } 8892 8893 return true; 8894 } 8895 8896 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8897 const Expr *OrigFormatExpr, 8898 ArrayRef<const Expr *> Args, 8899 bool HasVAListArg, unsigned format_idx, 8900 unsigned firstDataArg, 8901 Sema::FormatStringType Type, 8902 bool inFunctionCall, 8903 Sema::VariadicCallType CallType, 8904 llvm::SmallBitVector &CheckedVarArgs, 8905 UncoveredArgHandler &UncoveredArg, 8906 bool IgnoreStringsWithoutSpecifiers) { 8907 // CHECK: is the format string a wide literal? 8908 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8909 CheckFormatHandler::EmitFormatDiagnostic( 8910 S, inFunctionCall, Args[format_idx], 8911 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8912 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8913 return; 8914 } 8915 8916 // Str - The format string. NOTE: this is NOT null-terminated! 8917 StringRef StrRef = FExpr->getString(); 8918 const char *Str = StrRef.data(); 8919 // Account for cases where the string literal is truncated in a declaration. 8920 const ConstantArrayType *T = 8921 S.Context.getAsConstantArrayType(FExpr->getType()); 8922 assert(T && "String literal not of constant array type!"); 8923 size_t TypeSize = T->getSize().getZExtValue(); 8924 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8925 const unsigned numDataArgs = Args.size() - firstDataArg; 8926 8927 if (IgnoreStringsWithoutSpecifiers && 8928 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8929 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8930 return; 8931 8932 // Emit a warning if the string literal is truncated and does not contain an 8933 // embedded null character. 8934 if (TypeSize <= StrRef.size() && 8935 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8936 CheckFormatHandler::EmitFormatDiagnostic( 8937 S, inFunctionCall, Args[format_idx], 8938 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8939 FExpr->getBeginLoc(), 8940 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8941 return; 8942 } 8943 8944 // CHECK: empty format string? 8945 if (StrLen == 0 && numDataArgs > 0) { 8946 CheckFormatHandler::EmitFormatDiagnostic( 8947 S, inFunctionCall, Args[format_idx], 8948 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8949 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8950 return; 8951 } 8952 8953 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8954 Type == Sema::FST_Kprintf || Type == Sema::FST_FreeBSDKPrintf || 8955 Type == Sema::FST_OSLog || Type == Sema::FST_OSTrace || 8956 Type == Sema::FST_Syslog) { 8957 CheckPrintfHandler H( 8958 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8959 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8960 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8961 CheckedVarArgs, UncoveredArg); 8962 8963 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8964 S.getLangOpts(), 8965 S.Context.getTargetInfo(), 8966 Type == Sema::FST_Kprintf || Type == Sema::FST_FreeBSDKPrintf)) 8967 H.DoneProcessing(); 8968 } else if (Type == Sema::FST_Scanf) { 8969 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8970 numDataArgs, Str, HasVAListArg, Args, format_idx, 8971 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8972 8973 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8974 S.getLangOpts(), 8975 S.Context.getTargetInfo())) 8976 H.DoneProcessing(); 8977 } // TODO: handle other formats 8978 } 8979 8980 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8981 // Str - The format string. NOTE: this is NOT null-terminated! 8982 StringRef StrRef = FExpr->getString(); 8983 const char *Str = StrRef.data(); 8984 // Account for cases where the string literal is truncated in a declaration. 8985 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8986 assert(T && "String literal not of constant array type!"); 8987 size_t TypeSize = T->getSize().getZExtValue(); 8988 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8989 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8990 getLangOpts(), 8991 Context.getTargetInfo()); 8992 } 8993 8994 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8995 8996 // Returns the related absolute value function that is larger, of 0 if one 8997 // does not exist. 8998 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8999 switch (AbsFunction) { 9000 default: 9001 return 0; 9002 9003 case Builtin::BI__builtin_abs: 9004 return Builtin::BI__builtin_labs; 9005 case Builtin::BI__builtin_labs: 9006 return Builtin::BI__builtin_llabs; 9007 case Builtin::BI__builtin_llabs: 9008 return 0; 9009 9010 case Builtin::BI__builtin_fabsf: 9011 return Builtin::BI__builtin_fabs; 9012 case Builtin::BI__builtin_fabs: 9013 return Builtin::BI__builtin_fabsl; 9014 case Builtin::BI__builtin_fabsl: 9015 return 0; 9016 9017 case Builtin::BI__builtin_cabsf: 9018 return Builtin::BI__builtin_cabs; 9019 case Builtin::BI__builtin_cabs: 9020 return Builtin::BI__builtin_cabsl; 9021 case Builtin::BI__builtin_cabsl: 9022 return 0; 9023 9024 case Builtin::BIabs: 9025 return Builtin::BIlabs; 9026 case Builtin::BIlabs: 9027 return Builtin::BIllabs; 9028 case Builtin::BIllabs: 9029 return 0; 9030 9031 case Builtin::BIfabsf: 9032 return Builtin::BIfabs; 9033 case Builtin::BIfabs: 9034 return Builtin::BIfabsl; 9035 case Builtin::BIfabsl: 9036 return 0; 9037 9038 case Builtin::BIcabsf: 9039 return Builtin::BIcabs; 9040 case Builtin::BIcabs: 9041 return Builtin::BIcabsl; 9042 case Builtin::BIcabsl: 9043 return 0; 9044 } 9045 } 9046 9047 // Returns the argument type of the absolute value function. 9048 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9049 unsigned AbsType) { 9050 if (AbsType == 0) 9051 return QualType(); 9052 9053 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9054 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9055 if (Error != ASTContext::GE_None) 9056 return QualType(); 9057 9058 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9059 if (!FT) 9060 return QualType(); 9061 9062 if (FT->getNumParams() != 1) 9063 return QualType(); 9064 9065 return FT->getParamType(0); 9066 } 9067 9068 // Returns the best absolute value function, or zero, based on type and 9069 // current absolute value function. 9070 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9071 unsigned AbsFunctionKind) { 9072 unsigned BestKind = 0; 9073 uint64_t ArgSize = Context.getTypeSize(ArgType); 9074 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9075 Kind = getLargerAbsoluteValueFunction(Kind)) { 9076 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9077 if (Context.getTypeSize(ParamType) >= ArgSize) { 9078 if (BestKind == 0) 9079 BestKind = Kind; 9080 else if (Context.hasSameType(ParamType, ArgType)) { 9081 BestKind = Kind; 9082 break; 9083 } 9084 } 9085 } 9086 return BestKind; 9087 } 9088 9089 enum AbsoluteValueKind { 9090 AVK_Integer, 9091 AVK_Floating, 9092 AVK_Complex 9093 }; 9094 9095 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9096 if (T->isIntegralOrEnumerationType()) 9097 return AVK_Integer; 9098 if (T->isRealFloatingType()) 9099 return AVK_Floating; 9100 if (T->isAnyComplexType()) 9101 return AVK_Complex; 9102 9103 llvm_unreachable("Type not integer, floating, or complex"); 9104 } 9105 9106 // Changes the absolute value function to a different type. Preserves whether 9107 // the function is a builtin. 9108 static unsigned changeAbsFunction(unsigned AbsKind, 9109 AbsoluteValueKind ValueKind) { 9110 switch (ValueKind) { 9111 case AVK_Integer: 9112 switch (AbsKind) { 9113 default: 9114 return 0; 9115 case Builtin::BI__builtin_fabsf: 9116 case Builtin::BI__builtin_fabs: 9117 case Builtin::BI__builtin_fabsl: 9118 case Builtin::BI__builtin_cabsf: 9119 case Builtin::BI__builtin_cabs: 9120 case Builtin::BI__builtin_cabsl: 9121 return Builtin::BI__builtin_abs; 9122 case Builtin::BIfabsf: 9123 case Builtin::BIfabs: 9124 case Builtin::BIfabsl: 9125 case Builtin::BIcabsf: 9126 case Builtin::BIcabs: 9127 case Builtin::BIcabsl: 9128 return Builtin::BIabs; 9129 } 9130 case AVK_Floating: 9131 switch (AbsKind) { 9132 default: 9133 return 0; 9134 case Builtin::BI__builtin_abs: 9135 case Builtin::BI__builtin_labs: 9136 case Builtin::BI__builtin_llabs: 9137 case Builtin::BI__builtin_cabsf: 9138 case Builtin::BI__builtin_cabs: 9139 case Builtin::BI__builtin_cabsl: 9140 return Builtin::BI__builtin_fabsf; 9141 case Builtin::BIabs: 9142 case Builtin::BIlabs: 9143 case Builtin::BIllabs: 9144 case Builtin::BIcabsf: 9145 case Builtin::BIcabs: 9146 case Builtin::BIcabsl: 9147 return Builtin::BIfabsf; 9148 } 9149 case AVK_Complex: 9150 switch (AbsKind) { 9151 default: 9152 return 0; 9153 case Builtin::BI__builtin_abs: 9154 case Builtin::BI__builtin_labs: 9155 case Builtin::BI__builtin_llabs: 9156 case Builtin::BI__builtin_fabsf: 9157 case Builtin::BI__builtin_fabs: 9158 case Builtin::BI__builtin_fabsl: 9159 return Builtin::BI__builtin_cabsf; 9160 case Builtin::BIabs: 9161 case Builtin::BIlabs: 9162 case Builtin::BIllabs: 9163 case Builtin::BIfabsf: 9164 case Builtin::BIfabs: 9165 case Builtin::BIfabsl: 9166 return Builtin::BIcabsf; 9167 } 9168 } 9169 llvm_unreachable("Unable to convert function"); 9170 } 9171 9172 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9173 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9174 if (!FnInfo) 9175 return 0; 9176 9177 switch (FDecl->getBuiltinID()) { 9178 default: 9179 return 0; 9180 case Builtin::BI__builtin_abs: 9181 case Builtin::BI__builtin_fabs: 9182 case Builtin::BI__builtin_fabsf: 9183 case Builtin::BI__builtin_fabsl: 9184 case Builtin::BI__builtin_labs: 9185 case Builtin::BI__builtin_llabs: 9186 case Builtin::BI__builtin_cabs: 9187 case Builtin::BI__builtin_cabsf: 9188 case Builtin::BI__builtin_cabsl: 9189 case Builtin::BIabs: 9190 case Builtin::BIlabs: 9191 case Builtin::BIllabs: 9192 case Builtin::BIfabs: 9193 case Builtin::BIfabsf: 9194 case Builtin::BIfabsl: 9195 case Builtin::BIcabs: 9196 case Builtin::BIcabsf: 9197 case Builtin::BIcabsl: 9198 return FDecl->getBuiltinID(); 9199 } 9200 llvm_unreachable("Unknown Builtin type"); 9201 } 9202 9203 // If the replacement is valid, emit a note with replacement function. 9204 // Additionally, suggest including the proper header if not already included. 9205 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9206 unsigned AbsKind, QualType ArgType) { 9207 bool EmitHeaderHint = true; 9208 const char *HeaderName = nullptr; 9209 const char *FunctionName = nullptr; 9210 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9211 FunctionName = "std::abs"; 9212 if (ArgType->isIntegralOrEnumerationType()) { 9213 HeaderName = "cstdlib"; 9214 } else if (ArgType->isRealFloatingType()) { 9215 HeaderName = "cmath"; 9216 } else { 9217 llvm_unreachable("Invalid Type"); 9218 } 9219 9220 // Lookup all std::abs 9221 if (NamespaceDecl *Std = S.getStdNamespace()) { 9222 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9223 R.suppressDiagnostics(); 9224 S.LookupQualifiedName(R, Std); 9225 9226 for (const auto *I : R) { 9227 const FunctionDecl *FDecl = nullptr; 9228 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9229 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9230 } else { 9231 FDecl = dyn_cast<FunctionDecl>(I); 9232 } 9233 if (!FDecl) 9234 continue; 9235 9236 // Found std::abs(), check that they are the right ones. 9237 if (FDecl->getNumParams() != 1) 9238 continue; 9239 9240 // Check that the parameter type can handle the argument. 9241 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9242 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9243 S.Context.getTypeSize(ArgType) <= 9244 S.Context.getTypeSize(ParamType)) { 9245 // Found a function, don't need the header hint. 9246 EmitHeaderHint = false; 9247 break; 9248 } 9249 } 9250 } 9251 } else { 9252 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9253 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9254 9255 if (HeaderName) { 9256 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9257 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9258 R.suppressDiagnostics(); 9259 S.LookupName(R, S.getCurScope()); 9260 9261 if (R.isSingleResult()) { 9262 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9263 if (FD && FD->getBuiltinID() == AbsKind) { 9264 EmitHeaderHint = false; 9265 } else { 9266 return; 9267 } 9268 } else if (!R.empty()) { 9269 return; 9270 } 9271 } 9272 } 9273 9274 S.Diag(Loc, diag::note_replace_abs_function) 9275 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9276 9277 if (!HeaderName) 9278 return; 9279 9280 if (!EmitHeaderHint) 9281 return; 9282 9283 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9284 << FunctionName; 9285 } 9286 9287 template <std::size_t StrLen> 9288 static bool IsStdFunction(const FunctionDecl *FDecl, 9289 const char (&Str)[StrLen]) { 9290 if (!FDecl) 9291 return false; 9292 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9293 return false; 9294 if (!FDecl->isInStdNamespace()) 9295 return false; 9296 9297 return true; 9298 } 9299 9300 // Warn when using the wrong abs() function. 9301 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9302 const FunctionDecl *FDecl) { 9303 if (Call->getNumArgs() != 1) 9304 return; 9305 9306 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9307 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9308 if (AbsKind == 0 && !IsStdAbs) 9309 return; 9310 9311 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9312 QualType ParamType = Call->getArg(0)->getType(); 9313 9314 // Unsigned types cannot be negative. Suggest removing the absolute value 9315 // function call. 9316 if (ArgType->isUnsignedIntegerType()) { 9317 const char *FunctionName = 9318 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9319 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9320 Diag(Call->getExprLoc(), diag::note_remove_abs) 9321 << FunctionName 9322 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9323 return; 9324 } 9325 9326 // Taking the absolute value of a pointer is very suspicious, they probably 9327 // wanted to index into an array, dereference a pointer, call a function, etc. 9328 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9329 unsigned DiagType = 0; 9330 if (ArgType->isFunctionType()) 9331 DiagType = 1; 9332 else if (ArgType->isArrayType()) 9333 DiagType = 2; 9334 9335 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9336 return; 9337 } 9338 9339 // std::abs has overloads which prevent most of the absolute value problems 9340 // from occurring. 9341 if (IsStdAbs) 9342 return; 9343 9344 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9345 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9346 9347 // The argument and parameter are the same kind. Check if they are the right 9348 // size. 9349 if (ArgValueKind == ParamValueKind) { 9350 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9351 return; 9352 9353 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9354 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9355 << FDecl << ArgType << ParamType; 9356 9357 if (NewAbsKind == 0) 9358 return; 9359 9360 emitReplacement(*this, Call->getExprLoc(), 9361 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9362 return; 9363 } 9364 9365 // ArgValueKind != ParamValueKind 9366 // The wrong type of absolute value function was used. Attempt to find the 9367 // proper one. 9368 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9369 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9370 if (NewAbsKind == 0) 9371 return; 9372 9373 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9374 << FDecl << ParamValueKind << ArgValueKind; 9375 9376 emitReplacement(*this, Call->getExprLoc(), 9377 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9378 } 9379 9380 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9381 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9382 const FunctionDecl *FDecl) { 9383 if (!Call || !FDecl) return; 9384 9385 // Ignore template specializations and macros. 9386 if (inTemplateInstantiation()) return; 9387 if (Call->getExprLoc().isMacroID()) return; 9388 9389 // Only care about the one template argument, two function parameter std::max 9390 if (Call->getNumArgs() != 2) return; 9391 if (!IsStdFunction(FDecl, "max")) return; 9392 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9393 if (!ArgList) return; 9394 if (ArgList->size() != 1) return; 9395 9396 // Check that template type argument is unsigned integer. 9397 const auto& TA = ArgList->get(0); 9398 if (TA.getKind() != TemplateArgument::Type) return; 9399 QualType ArgType = TA.getAsType(); 9400 if (!ArgType->isUnsignedIntegerType()) return; 9401 9402 // See if either argument is a literal zero. 9403 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9404 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9405 if (!MTE) return false; 9406 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9407 if (!Num) return false; 9408 if (Num->getValue() != 0) return false; 9409 return true; 9410 }; 9411 9412 const Expr *FirstArg = Call->getArg(0); 9413 const Expr *SecondArg = Call->getArg(1); 9414 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9415 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9416 9417 // Only warn when exactly one argument is zero. 9418 if (IsFirstArgZero == IsSecondArgZero) return; 9419 9420 SourceRange FirstRange = FirstArg->getSourceRange(); 9421 SourceRange SecondRange = SecondArg->getSourceRange(); 9422 9423 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9424 9425 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9426 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9427 9428 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9429 SourceRange RemovalRange; 9430 if (IsFirstArgZero) { 9431 RemovalRange = SourceRange(FirstRange.getBegin(), 9432 SecondRange.getBegin().getLocWithOffset(-1)); 9433 } else { 9434 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9435 SecondRange.getEnd()); 9436 } 9437 9438 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9439 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9440 << FixItHint::CreateRemoval(RemovalRange); 9441 } 9442 9443 //===--- CHECK: Standard memory functions ---------------------------------===// 9444 9445 /// Takes the expression passed to the size_t parameter of functions 9446 /// such as memcmp, strncat, etc and warns if it's a comparison. 9447 /// 9448 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9449 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9450 IdentifierInfo *FnName, 9451 SourceLocation FnLoc, 9452 SourceLocation RParenLoc) { 9453 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9454 if (!Size) 9455 return false; 9456 9457 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9458 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9459 return false; 9460 9461 SourceRange SizeRange = Size->getSourceRange(); 9462 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9463 << SizeRange << FnName; 9464 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9465 << FnName 9466 << FixItHint::CreateInsertion( 9467 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9468 << FixItHint::CreateRemoval(RParenLoc); 9469 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9470 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9471 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9472 ")"); 9473 9474 return true; 9475 } 9476 9477 /// Determine whether the given type is or contains a dynamic class type 9478 /// (e.g., whether it has a vtable). 9479 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9480 bool &IsContained) { 9481 // Look through array types while ignoring qualifiers. 9482 const Type *Ty = T->getBaseElementTypeUnsafe(); 9483 IsContained = false; 9484 9485 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9486 RD = RD ? RD->getDefinition() : nullptr; 9487 if (!RD || RD->isInvalidDecl()) 9488 return nullptr; 9489 9490 if (RD->isDynamicClass()) 9491 return RD; 9492 9493 // Check all the fields. If any bases were dynamic, the class is dynamic. 9494 // It's impossible for a class to transitively contain itself by value, so 9495 // infinite recursion is impossible. 9496 for (auto *FD : RD->fields()) { 9497 bool SubContained; 9498 if (const CXXRecordDecl *ContainedRD = 9499 getContainedDynamicClass(FD->getType(), SubContained)) { 9500 IsContained = true; 9501 return ContainedRD; 9502 } 9503 } 9504 9505 return nullptr; 9506 } 9507 9508 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9509 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9510 if (Unary->getKind() == UETT_SizeOf) 9511 return Unary; 9512 return nullptr; 9513 } 9514 9515 /// If E is a sizeof expression, returns its argument expression, 9516 /// otherwise returns NULL. 9517 static const Expr *getSizeOfExprArg(const Expr *E) { 9518 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9519 if (!SizeOf->isArgumentType()) 9520 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9521 return nullptr; 9522 } 9523 9524 /// If E is a sizeof expression, returns its argument type. 9525 static QualType getSizeOfArgType(const Expr *E) { 9526 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9527 return SizeOf->getTypeOfArgument(); 9528 return QualType(); 9529 } 9530 9531 namespace { 9532 9533 struct SearchNonTrivialToInitializeField 9534 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9535 using Super = 9536 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9537 9538 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9539 9540 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9541 SourceLocation SL) { 9542 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9543 asDerived().visitArray(PDIK, AT, SL); 9544 return; 9545 } 9546 9547 Super::visitWithKind(PDIK, FT, SL); 9548 } 9549 9550 void visitARCStrong(QualType FT, SourceLocation SL) { 9551 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9552 } 9553 void visitARCWeak(QualType FT, SourceLocation SL) { 9554 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9555 } 9556 void visitStruct(QualType FT, SourceLocation SL) { 9557 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9558 visit(FD->getType(), FD->getLocation()); 9559 } 9560 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9561 const ArrayType *AT, SourceLocation SL) { 9562 visit(getContext().getBaseElementType(AT), SL); 9563 } 9564 void visitTrivial(QualType FT, SourceLocation SL) {} 9565 9566 static void diag(QualType RT, const Expr *E, Sema &S) { 9567 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9568 } 9569 9570 ASTContext &getContext() { return S.getASTContext(); } 9571 9572 const Expr *E; 9573 Sema &S; 9574 }; 9575 9576 struct SearchNonTrivialToCopyField 9577 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9578 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9579 9580 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9581 9582 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9583 SourceLocation SL) { 9584 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9585 asDerived().visitArray(PCK, AT, SL); 9586 return; 9587 } 9588 9589 Super::visitWithKind(PCK, FT, SL); 9590 } 9591 9592 void visitARCStrong(QualType FT, SourceLocation SL) { 9593 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9594 } 9595 void visitARCWeak(QualType FT, SourceLocation SL) { 9596 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9597 } 9598 void visitStruct(QualType FT, SourceLocation SL) { 9599 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9600 visit(FD->getType(), FD->getLocation()); 9601 } 9602 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9603 SourceLocation SL) { 9604 visit(getContext().getBaseElementType(AT), SL); 9605 } 9606 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9607 SourceLocation SL) {} 9608 void visitTrivial(QualType FT, SourceLocation SL) {} 9609 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9610 9611 static void diag(QualType RT, const Expr *E, Sema &S) { 9612 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9613 } 9614 9615 ASTContext &getContext() { return S.getASTContext(); } 9616 9617 const Expr *E; 9618 Sema &S; 9619 }; 9620 9621 } 9622 9623 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9624 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9625 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9626 9627 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9628 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9629 return false; 9630 9631 return doesExprLikelyComputeSize(BO->getLHS()) || 9632 doesExprLikelyComputeSize(BO->getRHS()); 9633 } 9634 9635 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9636 } 9637 9638 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9639 /// 9640 /// \code 9641 /// #define MACRO 0 9642 /// foo(MACRO); 9643 /// foo(0); 9644 /// \endcode 9645 /// 9646 /// This should return true for the first call to foo, but not for the second 9647 /// (regardless of whether foo is a macro or function). 9648 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9649 SourceLocation CallLoc, 9650 SourceLocation ArgLoc) { 9651 if (!CallLoc.isMacroID()) 9652 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9653 9654 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9655 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9656 } 9657 9658 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9659 /// last two arguments transposed. 9660 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9661 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9662 return; 9663 9664 const Expr *SizeArg = 9665 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9666 9667 auto isLiteralZero = [](const Expr *E) { 9668 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9669 }; 9670 9671 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9672 SourceLocation CallLoc = Call->getRParenLoc(); 9673 SourceManager &SM = S.getSourceManager(); 9674 if (isLiteralZero(SizeArg) && 9675 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9676 9677 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9678 9679 // Some platforms #define bzero to __builtin_memset. See if this is the 9680 // case, and if so, emit a better diagnostic. 9681 if (BId == Builtin::BIbzero || 9682 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9683 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9684 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9685 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9686 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9687 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9688 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9689 } 9690 return; 9691 } 9692 9693 // If the second argument to a memset is a sizeof expression and the third 9694 // isn't, this is also likely an error. This should catch 9695 // 'memset(buf, sizeof(buf), 0xff)'. 9696 if (BId == Builtin::BImemset && 9697 doesExprLikelyComputeSize(Call->getArg(1)) && 9698 !doesExprLikelyComputeSize(Call->getArg(2))) { 9699 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9700 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9701 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9702 return; 9703 } 9704 } 9705 9706 /// Check for dangerous or invalid arguments to memset(). 9707 /// 9708 /// This issues warnings on known problematic, dangerous or unspecified 9709 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9710 /// function calls. 9711 /// 9712 /// \param Call The call expression to diagnose. 9713 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9714 unsigned BId, 9715 IdentifierInfo *FnName) { 9716 assert(BId != 0); 9717 9718 // It is possible to have a non-standard definition of memset. Validate 9719 // we have enough arguments, and if not, abort further checking. 9720 unsigned ExpectedNumArgs = 9721 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9722 if (Call->getNumArgs() < ExpectedNumArgs) 9723 return; 9724 9725 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9726 BId == Builtin::BIstrndup ? 1 : 2); 9727 unsigned LenArg = 9728 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9729 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9730 9731 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9732 Call->getBeginLoc(), Call->getRParenLoc())) 9733 return; 9734 9735 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9736 CheckMemaccessSize(*this, BId, Call); 9737 9738 // We have special checking when the length is a sizeof expression. 9739 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9740 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9741 llvm::FoldingSetNodeID SizeOfArgID; 9742 9743 // Although widely used, 'bzero' is not a standard function. Be more strict 9744 // with the argument types before allowing diagnostics and only allow the 9745 // form bzero(ptr, sizeof(...)). 9746 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9747 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9748 return; 9749 9750 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9751 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9752 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9753 9754 QualType DestTy = Dest->getType(); 9755 QualType PointeeTy; 9756 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9757 PointeeTy = DestPtrTy->getPointeeType(); 9758 9759 // Never warn about void type pointers. This can be used to suppress 9760 // false positives. 9761 if (PointeeTy->isVoidType()) 9762 continue; 9763 9764 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9765 // actually comparing the expressions for equality. Because computing the 9766 // expression IDs can be expensive, we only do this if the diagnostic is 9767 // enabled. 9768 if (SizeOfArg && 9769 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9770 SizeOfArg->getExprLoc())) { 9771 // We only compute IDs for expressions if the warning is enabled, and 9772 // cache the sizeof arg's ID. 9773 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9774 SizeOfArg->Profile(SizeOfArgID, Context, true); 9775 llvm::FoldingSetNodeID DestID; 9776 Dest->Profile(DestID, Context, true); 9777 if (DestID == SizeOfArgID) { 9778 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9779 // over sizeof(src) as well. 9780 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9781 StringRef ReadableName = FnName->getName(); 9782 9783 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9784 if (UnaryOp->getOpcode() == UO_AddrOf) 9785 ActionIdx = 1; // If its an address-of operator, just remove it. 9786 if (!PointeeTy->isIncompleteType() && 9787 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9788 ActionIdx = 2; // If the pointee's size is sizeof(char), 9789 // suggest an explicit length. 9790 9791 // If the function is defined as a builtin macro, do not show macro 9792 // expansion. 9793 SourceLocation SL = SizeOfArg->getExprLoc(); 9794 SourceRange DSR = Dest->getSourceRange(); 9795 SourceRange SSR = SizeOfArg->getSourceRange(); 9796 SourceManager &SM = getSourceManager(); 9797 9798 if (SM.isMacroArgExpansion(SL)) { 9799 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9800 SL = SM.getSpellingLoc(SL); 9801 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9802 SM.getSpellingLoc(DSR.getEnd())); 9803 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9804 SM.getSpellingLoc(SSR.getEnd())); 9805 } 9806 9807 DiagRuntimeBehavior(SL, SizeOfArg, 9808 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9809 << ReadableName 9810 << PointeeTy 9811 << DestTy 9812 << DSR 9813 << SSR); 9814 DiagRuntimeBehavior(SL, SizeOfArg, 9815 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9816 << ActionIdx 9817 << SSR); 9818 9819 break; 9820 } 9821 } 9822 9823 // Also check for cases where the sizeof argument is the exact same 9824 // type as the memory argument, and where it points to a user-defined 9825 // record type. 9826 if (SizeOfArgTy != QualType()) { 9827 if (PointeeTy->isRecordType() && 9828 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9829 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9830 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9831 << FnName << SizeOfArgTy << ArgIdx 9832 << PointeeTy << Dest->getSourceRange() 9833 << LenExpr->getSourceRange()); 9834 break; 9835 } 9836 } 9837 } else if (DestTy->isArrayType()) { 9838 PointeeTy = DestTy; 9839 } 9840 9841 if (PointeeTy == QualType()) 9842 continue; 9843 9844 // Always complain about dynamic classes. 9845 bool IsContained; 9846 if (const CXXRecordDecl *ContainedRD = 9847 getContainedDynamicClass(PointeeTy, IsContained)) { 9848 9849 unsigned OperationType = 0; 9850 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9851 // "overwritten" if we're warning about the destination for any call 9852 // but memcmp; otherwise a verb appropriate to the call. 9853 if (ArgIdx != 0 || IsCmp) { 9854 if (BId == Builtin::BImemcpy) 9855 OperationType = 1; 9856 else if(BId == Builtin::BImemmove) 9857 OperationType = 2; 9858 else if (IsCmp) 9859 OperationType = 3; 9860 } 9861 9862 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9863 PDiag(diag::warn_dyn_class_memaccess) 9864 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9865 << IsContained << ContainedRD << OperationType 9866 << Call->getCallee()->getSourceRange()); 9867 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9868 BId != Builtin::BImemset) 9869 DiagRuntimeBehavior( 9870 Dest->getExprLoc(), Dest, 9871 PDiag(diag::warn_arc_object_memaccess) 9872 << ArgIdx << FnName << PointeeTy 9873 << Call->getCallee()->getSourceRange()); 9874 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9875 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9876 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9877 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9878 PDiag(diag::warn_cstruct_memaccess) 9879 << ArgIdx << FnName << PointeeTy << 0); 9880 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9881 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9882 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9883 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9884 PDiag(diag::warn_cstruct_memaccess) 9885 << ArgIdx << FnName << PointeeTy << 1); 9886 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9887 } else { 9888 continue; 9889 } 9890 } else 9891 continue; 9892 9893 DiagRuntimeBehavior( 9894 Dest->getExprLoc(), Dest, 9895 PDiag(diag::note_bad_memaccess_silence) 9896 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9897 break; 9898 } 9899 } 9900 9901 // A little helper routine: ignore addition and subtraction of integer literals. 9902 // This intentionally does not ignore all integer constant expressions because 9903 // we don't want to remove sizeof(). 9904 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9905 Ex = Ex->IgnoreParenCasts(); 9906 9907 while (true) { 9908 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9909 if (!BO || !BO->isAdditiveOp()) 9910 break; 9911 9912 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9913 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9914 9915 if (isa<IntegerLiteral>(RHS)) 9916 Ex = LHS; 9917 else if (isa<IntegerLiteral>(LHS)) 9918 Ex = RHS; 9919 else 9920 break; 9921 } 9922 9923 return Ex; 9924 } 9925 9926 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9927 ASTContext &Context) { 9928 // Only handle constant-sized or VLAs, but not flexible members. 9929 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9930 // Only issue the FIXIT for arrays of size > 1. 9931 if (CAT->getSize().getSExtValue() <= 1) 9932 return false; 9933 } else if (!Ty->isVariableArrayType()) { 9934 return false; 9935 } 9936 return true; 9937 } 9938 9939 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9940 // be the size of the source, instead of the destination. 9941 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9942 IdentifierInfo *FnName) { 9943 9944 // Don't crash if the user has the wrong number of arguments 9945 unsigned NumArgs = Call->getNumArgs(); 9946 if ((NumArgs != 3) && (NumArgs != 4)) 9947 return; 9948 9949 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9950 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9951 const Expr *CompareWithSrc = nullptr; 9952 9953 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9954 Call->getBeginLoc(), Call->getRParenLoc())) 9955 return; 9956 9957 // Look for 'strlcpy(dst, x, sizeof(x))' 9958 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9959 CompareWithSrc = Ex; 9960 else { 9961 // Look for 'strlcpy(dst, x, strlen(x))' 9962 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9963 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9964 SizeCall->getNumArgs() == 1) 9965 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9966 } 9967 } 9968 9969 if (!CompareWithSrc) 9970 return; 9971 9972 // Determine if the argument to sizeof/strlen is equal to the source 9973 // argument. In principle there's all kinds of things you could do 9974 // here, for instance creating an == expression and evaluating it with 9975 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9976 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9977 if (!SrcArgDRE) 9978 return; 9979 9980 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9981 if (!CompareWithSrcDRE || 9982 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9983 return; 9984 9985 const Expr *OriginalSizeArg = Call->getArg(2); 9986 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9987 << OriginalSizeArg->getSourceRange() << FnName; 9988 9989 // Output a FIXIT hint if the destination is an array (rather than a 9990 // pointer to an array). This could be enhanced to handle some 9991 // pointers if we know the actual size, like if DstArg is 'array+2' 9992 // we could say 'sizeof(array)-2'. 9993 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9994 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9995 return; 9996 9997 SmallString<128> sizeString; 9998 llvm::raw_svector_ostream OS(sizeString); 9999 OS << "sizeof("; 10000 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10001 OS << ")"; 10002 10003 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10004 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10005 OS.str()); 10006 } 10007 10008 /// Check if two expressions refer to the same declaration. 10009 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10010 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10011 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10012 return D1->getDecl() == D2->getDecl(); 10013 return false; 10014 } 10015 10016 static const Expr *getStrlenExprArg(const Expr *E) { 10017 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10018 const FunctionDecl *FD = CE->getDirectCallee(); 10019 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10020 return nullptr; 10021 return CE->getArg(0)->IgnoreParenCasts(); 10022 } 10023 return nullptr; 10024 } 10025 10026 // Warn on anti-patterns as the 'size' argument to strncat. 10027 // The correct size argument should look like following: 10028 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10029 void Sema::CheckStrncatArguments(const CallExpr *CE, 10030 IdentifierInfo *FnName) { 10031 // Don't crash if the user has the wrong number of arguments. 10032 if (CE->getNumArgs() < 3) 10033 return; 10034 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10035 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10036 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10037 10038 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10039 CE->getRParenLoc())) 10040 return; 10041 10042 // Identify common expressions, which are wrongly used as the size argument 10043 // to strncat and may lead to buffer overflows. 10044 unsigned PatternType = 0; 10045 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10046 // - sizeof(dst) 10047 if (referToTheSameDecl(SizeOfArg, DstArg)) 10048 PatternType = 1; 10049 // - sizeof(src) 10050 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10051 PatternType = 2; 10052 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10053 if (BE->getOpcode() == BO_Sub) { 10054 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10055 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10056 // - sizeof(dst) - strlen(dst) 10057 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10058 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10059 PatternType = 1; 10060 // - sizeof(src) - (anything) 10061 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10062 PatternType = 2; 10063 } 10064 } 10065 10066 if (PatternType == 0) 10067 return; 10068 10069 // Generate the diagnostic. 10070 SourceLocation SL = LenArg->getBeginLoc(); 10071 SourceRange SR = LenArg->getSourceRange(); 10072 SourceManager &SM = getSourceManager(); 10073 10074 // If the function is defined as a builtin macro, do not show macro expansion. 10075 if (SM.isMacroArgExpansion(SL)) { 10076 SL = SM.getSpellingLoc(SL); 10077 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10078 SM.getSpellingLoc(SR.getEnd())); 10079 } 10080 10081 // Check if the destination is an array (rather than a pointer to an array). 10082 QualType DstTy = DstArg->getType(); 10083 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10084 Context); 10085 if (!isKnownSizeArray) { 10086 if (PatternType == 1) 10087 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10088 else 10089 Diag(SL, diag::warn_strncat_src_size) << SR; 10090 return; 10091 } 10092 10093 if (PatternType == 1) 10094 Diag(SL, diag::warn_strncat_large_size) << SR; 10095 else 10096 Diag(SL, diag::warn_strncat_src_size) << SR; 10097 10098 SmallString<128> sizeString; 10099 llvm::raw_svector_ostream OS(sizeString); 10100 OS << "sizeof("; 10101 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10102 OS << ") - "; 10103 OS << "strlen("; 10104 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10105 OS << ") - 1"; 10106 10107 Diag(SL, diag::note_strncat_wrong_size) 10108 << FixItHint::CreateReplacement(SR, OS.str()); 10109 } 10110 10111 void 10112 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10113 SourceLocation ReturnLoc, 10114 bool isObjCMethod, 10115 const AttrVec *Attrs, 10116 const FunctionDecl *FD) { 10117 // Check if the return value is null but should not be. 10118 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10119 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10120 CheckNonNullExpr(*this, RetValExp)) 10121 Diag(ReturnLoc, diag::warn_null_ret) 10122 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10123 10124 // C++11 [basic.stc.dynamic.allocation]p4: 10125 // If an allocation function declared with a non-throwing 10126 // exception-specification fails to allocate storage, it shall return 10127 // a null pointer. Any other allocation function that fails to allocate 10128 // storage shall indicate failure only by throwing an exception [...] 10129 if (FD) { 10130 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10131 if (Op == OO_New || Op == OO_Array_New) { 10132 const FunctionProtoType *Proto 10133 = FD->getType()->castAs<FunctionProtoType>(); 10134 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10135 CheckNonNullExpr(*this, RetValExp)) 10136 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10137 << FD << getLangOpts().CPlusPlus11; 10138 } 10139 } 10140 } 10141 10142 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10143 10144 /// Check for comparisons of floating point operands using != and ==. 10145 /// Issue a warning if these are no self-comparisons, as they are not likely 10146 /// to do what the programmer intended. 10147 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10148 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10149 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10150 10151 // Special case: check for x == x (which is OK). 10152 // Do not emit warnings for such cases. 10153 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10154 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10155 if (DRL->getDecl() == DRR->getDecl()) 10156 return; 10157 10158 // Special case: check for comparisons against literals that can be exactly 10159 // represented by APFloat. In such cases, do not emit a warning. This 10160 // is a heuristic: often comparison against such literals are used to 10161 // detect if a value in a variable has not changed. This clearly can 10162 // lead to false negatives. 10163 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10164 if (FLL->isExact()) 10165 return; 10166 } else 10167 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10168 if (FLR->isExact()) 10169 return; 10170 10171 // Check for comparisons with builtin types. 10172 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10173 if (CL->getBuiltinCallee()) 10174 return; 10175 10176 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10177 if (CR->getBuiltinCallee()) 10178 return; 10179 10180 // Emit the diagnostic. 10181 Diag(Loc, diag::warn_floatingpoint_eq) 10182 << LHS->getSourceRange() << RHS->getSourceRange(); 10183 } 10184 10185 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10186 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10187 10188 namespace { 10189 10190 /// Structure recording the 'active' range of an integer-valued 10191 /// expression. 10192 struct IntRange { 10193 /// The number of bits active in the int. 10194 unsigned Width; 10195 10196 /// True if the int is known not to have negative values. 10197 bool NonNegative; 10198 10199 IntRange(unsigned Width, bool NonNegative) 10200 : Width(Width), NonNegative(NonNegative) {} 10201 10202 /// Returns the range of the bool type. 10203 static IntRange forBoolType() { 10204 return IntRange(1, true); 10205 } 10206 10207 /// Returns the range of an opaque value of the given integral type. 10208 static IntRange forValueOfType(ASTContext &C, QualType T) { 10209 return forValueOfCanonicalType(C, 10210 T->getCanonicalTypeInternal().getTypePtr()); 10211 } 10212 10213 /// Returns the range of an opaque value of a canonical integral type. 10214 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10215 assert(T->isCanonicalUnqualified()); 10216 10217 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10218 T = VT->getElementType().getTypePtr(); 10219 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10220 T = CT->getElementType().getTypePtr(); 10221 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10222 T = AT->getValueType().getTypePtr(); 10223 10224 if (!C.getLangOpts().CPlusPlus) { 10225 // For enum types in C code, use the underlying datatype. 10226 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10227 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10228 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10229 // For enum types in C++, use the known bit width of the enumerators. 10230 EnumDecl *Enum = ET->getDecl(); 10231 // In C++11, enums can have a fixed underlying type. Use this type to 10232 // compute the range. 10233 if (Enum->isFixed()) { 10234 return IntRange(C.getIntWidth(QualType(T, 0)), 10235 !ET->isSignedIntegerOrEnumerationType()); 10236 } 10237 10238 unsigned NumPositive = Enum->getNumPositiveBits(); 10239 unsigned NumNegative = Enum->getNumNegativeBits(); 10240 10241 if (NumNegative == 0) 10242 return IntRange(NumPositive, true/*NonNegative*/); 10243 else 10244 return IntRange(std::max(NumPositive + 1, NumNegative), 10245 false/*NonNegative*/); 10246 } 10247 10248 const BuiltinType *BT = cast<BuiltinType>(T); 10249 assert(BT->isInteger()); 10250 10251 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10252 } 10253 10254 /// Returns the "target" range of a canonical integral type, i.e. 10255 /// the range of values expressible in the type. 10256 /// 10257 /// This matches forValueOfCanonicalType except that enums have the 10258 /// full range of their type, not the range of their enumerators. 10259 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10260 assert(T->isCanonicalUnqualified()); 10261 10262 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10263 T = VT->getElementType().getTypePtr(); 10264 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10265 T = CT->getElementType().getTypePtr(); 10266 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10267 T = AT->getValueType().getTypePtr(); 10268 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10269 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10270 10271 const BuiltinType *BT = cast<BuiltinType>(T); 10272 assert(BT->isInteger()); 10273 10274 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10275 } 10276 10277 /// Returns the supremum of two ranges: i.e. their conservative merge. 10278 static IntRange join(IntRange L, IntRange R) { 10279 return IntRange(std::max(L.Width, R.Width), 10280 L.NonNegative && R.NonNegative); 10281 } 10282 10283 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10284 static IntRange meet(IntRange L, IntRange R) { 10285 return IntRange(std::min(L.Width, R.Width), 10286 L.NonNegative || R.NonNegative); 10287 } 10288 }; 10289 10290 } // namespace 10291 10292 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10293 unsigned MaxWidth) { 10294 if (value.isSigned() && value.isNegative()) 10295 return IntRange(value.getMinSignedBits(), false); 10296 10297 if (value.getBitWidth() > MaxWidth) 10298 value = value.trunc(MaxWidth); 10299 10300 // isNonNegative() just checks the sign bit without considering 10301 // signedness. 10302 return IntRange(value.getActiveBits(), true); 10303 } 10304 10305 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10306 unsigned MaxWidth) { 10307 if (result.isInt()) 10308 return GetValueRange(C, result.getInt(), MaxWidth); 10309 10310 if (result.isVector()) { 10311 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10312 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10313 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10314 R = IntRange::join(R, El); 10315 } 10316 return R; 10317 } 10318 10319 if (result.isComplexInt()) { 10320 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10321 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10322 return IntRange::join(R, I); 10323 } 10324 10325 // This can happen with lossless casts to intptr_t of "based" lvalues. 10326 // Assume it might use arbitrary bits. 10327 // FIXME: The only reason we need to pass the type in here is to get 10328 // the sign right on this one case. It would be nice if APValue 10329 // preserved this. 10330 assert(result.isLValue() || result.isAddrLabelDiff()); 10331 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10332 } 10333 10334 static QualType GetExprType(const Expr *E) { 10335 QualType Ty = E->getType(); 10336 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10337 Ty = AtomicRHS->getValueType(); 10338 return Ty; 10339 } 10340 10341 /// Pseudo-evaluate the given integer expression, estimating the 10342 /// range of values it might take. 10343 /// 10344 /// \param MaxWidth - the width to which the value will be truncated 10345 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10346 bool InConstantContext) { 10347 E = E->IgnoreParens(); 10348 10349 // Try a full evaluation first. 10350 Expr::EvalResult result; 10351 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10352 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10353 10354 // I think we only want to look through implicit casts here; if the 10355 // user has an explicit widening cast, we should treat the value as 10356 // being of the new, wider type. 10357 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10358 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10359 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10360 10361 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10362 10363 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10364 CE->getCastKind() == CK_BooleanToSignedIntegral; 10365 10366 // Assume that non-integer casts can span the full range of the type. 10367 if (!isIntegerCast) 10368 return OutputTypeRange; 10369 10370 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10371 std::min(MaxWidth, OutputTypeRange.Width), 10372 InConstantContext); 10373 10374 // Bail out if the subexpr's range is as wide as the cast type. 10375 if (SubRange.Width >= OutputTypeRange.Width) 10376 return OutputTypeRange; 10377 10378 // Otherwise, we take the smaller width, and we're non-negative if 10379 // either the output type or the subexpr is. 10380 return IntRange(SubRange.Width, 10381 SubRange.NonNegative || OutputTypeRange.NonNegative); 10382 } 10383 10384 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10385 // If we can fold the condition, just take that operand. 10386 bool CondResult; 10387 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10388 return GetExprRange(C, 10389 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10390 MaxWidth, InConstantContext); 10391 10392 // Otherwise, conservatively merge. 10393 IntRange L = 10394 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10395 IntRange R = 10396 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10397 return IntRange::join(L, R); 10398 } 10399 10400 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10401 switch (BO->getOpcode()) { 10402 case BO_Cmp: 10403 llvm_unreachable("builtin <=> should have class type"); 10404 10405 // Boolean-valued operations are single-bit and positive. 10406 case BO_LAnd: 10407 case BO_LOr: 10408 case BO_LT: 10409 case BO_GT: 10410 case BO_LE: 10411 case BO_GE: 10412 case BO_EQ: 10413 case BO_NE: 10414 return IntRange::forBoolType(); 10415 10416 // The type of the assignments is the type of the LHS, so the RHS 10417 // is not necessarily the same type. 10418 case BO_MulAssign: 10419 case BO_DivAssign: 10420 case BO_RemAssign: 10421 case BO_AddAssign: 10422 case BO_SubAssign: 10423 case BO_XorAssign: 10424 case BO_OrAssign: 10425 // TODO: bitfields? 10426 return IntRange::forValueOfType(C, GetExprType(E)); 10427 10428 // Simple assignments just pass through the RHS, which will have 10429 // been coerced to the LHS type. 10430 case BO_Assign: 10431 // TODO: bitfields? 10432 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10433 10434 // Operations with opaque sources are black-listed. 10435 case BO_PtrMemD: 10436 case BO_PtrMemI: 10437 return IntRange::forValueOfType(C, GetExprType(E)); 10438 10439 // Bitwise-and uses the *infinum* of the two source ranges. 10440 case BO_And: 10441 case BO_AndAssign: 10442 return IntRange::meet( 10443 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10444 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10445 10446 // Left shift gets black-listed based on a judgement call. 10447 case BO_Shl: 10448 // ...except that we want to treat '1 << (blah)' as logically 10449 // positive. It's an important idiom. 10450 if (IntegerLiteral *I 10451 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10452 if (I->getValue() == 1) { 10453 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10454 return IntRange(R.Width, /*NonNegative*/ true); 10455 } 10456 } 10457 LLVM_FALLTHROUGH; 10458 10459 case BO_ShlAssign: 10460 return IntRange::forValueOfType(C, GetExprType(E)); 10461 10462 // Right shift by a constant can narrow its left argument. 10463 case BO_Shr: 10464 case BO_ShrAssign: { 10465 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10466 10467 // If the shift amount is a positive constant, drop the width by 10468 // that much. 10469 llvm::APSInt shift; 10470 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10471 shift.isNonNegative()) { 10472 unsigned zext = shift.getZExtValue(); 10473 if (zext >= L.Width) 10474 L.Width = (L.NonNegative ? 0 : 1); 10475 else 10476 L.Width -= zext; 10477 } 10478 10479 return L; 10480 } 10481 10482 // Comma acts as its right operand. 10483 case BO_Comma: 10484 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10485 10486 // Black-list pointer subtractions. 10487 case BO_Sub: 10488 if (BO->getLHS()->getType()->isPointerType()) 10489 return IntRange::forValueOfType(C, GetExprType(E)); 10490 break; 10491 10492 // The width of a division result is mostly determined by the size 10493 // of the LHS. 10494 case BO_Div: { 10495 // Don't 'pre-truncate' the operands. 10496 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10497 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10498 10499 // If the divisor is constant, use that. 10500 llvm::APSInt divisor; 10501 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10502 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10503 if (log2 >= L.Width) 10504 L.Width = (L.NonNegative ? 0 : 1); 10505 else 10506 L.Width = std::min(L.Width - log2, MaxWidth); 10507 return L; 10508 } 10509 10510 // Otherwise, just use the LHS's width. 10511 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10512 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10513 } 10514 10515 // The result of a remainder can't be larger than the result of 10516 // either side. 10517 case BO_Rem: { 10518 // Don't 'pre-truncate' the operands. 10519 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10520 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10521 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10522 10523 IntRange meet = IntRange::meet(L, R); 10524 meet.Width = std::min(meet.Width, MaxWidth); 10525 return meet; 10526 } 10527 10528 // The default behavior is okay for these. 10529 case BO_Mul: 10530 case BO_Add: 10531 case BO_Xor: 10532 case BO_Or: 10533 break; 10534 } 10535 10536 // The default case is to treat the operation as if it were closed 10537 // on the narrowest type that encompasses both operands. 10538 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10539 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10540 return IntRange::join(L, R); 10541 } 10542 10543 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10544 switch (UO->getOpcode()) { 10545 // Boolean-valued operations are white-listed. 10546 case UO_LNot: 10547 return IntRange::forBoolType(); 10548 10549 // Operations with opaque sources are black-listed. 10550 case UO_Deref: 10551 case UO_AddrOf: // should be impossible 10552 return IntRange::forValueOfType(C, GetExprType(E)); 10553 10554 default: 10555 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10556 } 10557 } 10558 10559 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10560 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10561 10562 if (const auto *BitField = E->getSourceBitField()) 10563 return IntRange(BitField->getBitWidthValue(C), 10564 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10565 10566 return IntRange::forValueOfType(C, GetExprType(E)); 10567 } 10568 10569 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10570 bool InConstantContext) { 10571 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10572 } 10573 10574 /// Checks whether the given value, which currently has the given 10575 /// source semantics, has the same value when coerced through the 10576 /// target semantics. 10577 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10578 const llvm::fltSemantics &Src, 10579 const llvm::fltSemantics &Tgt) { 10580 llvm::APFloat truncated = value; 10581 10582 bool ignored; 10583 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10584 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10585 10586 return truncated.bitwiseIsEqual(value); 10587 } 10588 10589 /// Checks whether the given value, which currently has the given 10590 /// source semantics, has the same value when coerced through the 10591 /// target semantics. 10592 /// 10593 /// The value might be a vector of floats (or a complex number). 10594 static bool IsSameFloatAfterCast(const APValue &value, 10595 const llvm::fltSemantics &Src, 10596 const llvm::fltSemantics &Tgt) { 10597 if (value.isFloat()) 10598 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10599 10600 if (value.isVector()) { 10601 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10602 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10603 return false; 10604 return true; 10605 } 10606 10607 assert(value.isComplexFloat()); 10608 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10609 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10610 } 10611 10612 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10613 bool IsListInit = false); 10614 10615 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10616 // Suppress cases where we are comparing against an enum constant. 10617 if (const DeclRefExpr *DR = 10618 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10619 if (isa<EnumConstantDecl>(DR->getDecl())) 10620 return true; 10621 10622 // Suppress cases where the value is expanded from a macro, unless that macro 10623 // is how a language represents a boolean literal. This is the case in both C 10624 // and Objective-C. 10625 SourceLocation BeginLoc = E->getBeginLoc(); 10626 if (BeginLoc.isMacroID()) { 10627 StringRef MacroName = Lexer::getImmediateMacroName( 10628 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10629 return MacroName != "YES" && MacroName != "NO" && 10630 MacroName != "true" && MacroName != "false"; 10631 } 10632 10633 return false; 10634 } 10635 10636 static bool isKnownToHaveUnsignedValue(Expr *E) { 10637 return E->getType()->isIntegerType() && 10638 (!E->getType()->isSignedIntegerType() || 10639 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10640 } 10641 10642 namespace { 10643 /// The promoted range of values of a type. In general this has the 10644 /// following structure: 10645 /// 10646 /// |-----------| . . . |-----------| 10647 /// ^ ^ ^ ^ 10648 /// Min HoleMin HoleMax Max 10649 /// 10650 /// ... where there is only a hole if a signed type is promoted to unsigned 10651 /// (in which case Min and Max are the smallest and largest representable 10652 /// values). 10653 struct PromotedRange { 10654 // Min, or HoleMax if there is a hole. 10655 llvm::APSInt PromotedMin; 10656 // Max, or HoleMin if there is a hole. 10657 llvm::APSInt PromotedMax; 10658 10659 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10660 if (R.Width == 0) 10661 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10662 else if (R.Width >= BitWidth && !Unsigned) { 10663 // Promotion made the type *narrower*. This happens when promoting 10664 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10665 // Treat all values of 'signed int' as being in range for now. 10666 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10667 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10668 } else { 10669 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10670 .extOrTrunc(BitWidth); 10671 PromotedMin.setIsUnsigned(Unsigned); 10672 10673 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10674 .extOrTrunc(BitWidth); 10675 PromotedMax.setIsUnsigned(Unsigned); 10676 } 10677 } 10678 10679 // Determine whether this range is contiguous (has no hole). 10680 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10681 10682 // Where a constant value is within the range. 10683 enum ComparisonResult { 10684 LT = 0x1, 10685 LE = 0x2, 10686 GT = 0x4, 10687 GE = 0x8, 10688 EQ = 0x10, 10689 NE = 0x20, 10690 InRangeFlag = 0x40, 10691 10692 Less = LE | LT | NE, 10693 Min = LE | InRangeFlag, 10694 InRange = InRangeFlag, 10695 Max = GE | InRangeFlag, 10696 Greater = GE | GT | NE, 10697 10698 OnlyValue = LE | GE | EQ | InRangeFlag, 10699 InHole = NE 10700 }; 10701 10702 ComparisonResult compare(const llvm::APSInt &Value) const { 10703 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10704 Value.isUnsigned() == PromotedMin.isUnsigned()); 10705 if (!isContiguous()) { 10706 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10707 if (Value.isMinValue()) return Min; 10708 if (Value.isMaxValue()) return Max; 10709 if (Value >= PromotedMin) return InRange; 10710 if (Value <= PromotedMax) return InRange; 10711 return InHole; 10712 } 10713 10714 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10715 case -1: return Less; 10716 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10717 case 1: 10718 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10719 case -1: return InRange; 10720 case 0: return Max; 10721 case 1: return Greater; 10722 } 10723 } 10724 10725 llvm_unreachable("impossible compare result"); 10726 } 10727 10728 static llvm::Optional<StringRef> 10729 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10730 if (Op == BO_Cmp) { 10731 ComparisonResult LTFlag = LT, GTFlag = GT; 10732 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10733 10734 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10735 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10736 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10737 return llvm::None; 10738 } 10739 10740 ComparisonResult TrueFlag, FalseFlag; 10741 if (Op == BO_EQ) { 10742 TrueFlag = EQ; 10743 FalseFlag = NE; 10744 } else if (Op == BO_NE) { 10745 TrueFlag = NE; 10746 FalseFlag = EQ; 10747 } else { 10748 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10749 TrueFlag = LT; 10750 FalseFlag = GE; 10751 } else { 10752 TrueFlag = GT; 10753 FalseFlag = LE; 10754 } 10755 if (Op == BO_GE || Op == BO_LE) 10756 std::swap(TrueFlag, FalseFlag); 10757 } 10758 if (R & TrueFlag) 10759 return StringRef("true"); 10760 if (R & FalseFlag) 10761 return StringRef("false"); 10762 return llvm::None; 10763 } 10764 }; 10765 } 10766 10767 static bool HasEnumType(Expr *E) { 10768 // Strip off implicit integral promotions. 10769 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10770 if (ICE->getCastKind() != CK_IntegralCast && 10771 ICE->getCastKind() != CK_NoOp) 10772 break; 10773 E = ICE->getSubExpr(); 10774 } 10775 10776 return E->getType()->isEnumeralType(); 10777 } 10778 10779 static int classifyConstantValue(Expr *Constant) { 10780 // The values of this enumeration are used in the diagnostics 10781 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10782 enum ConstantValueKind { 10783 Miscellaneous = 0, 10784 LiteralTrue, 10785 LiteralFalse 10786 }; 10787 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10788 return BL->getValue() ? ConstantValueKind::LiteralTrue 10789 : ConstantValueKind::LiteralFalse; 10790 return ConstantValueKind::Miscellaneous; 10791 } 10792 10793 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10794 Expr *Constant, Expr *Other, 10795 const llvm::APSInt &Value, 10796 bool RhsConstant) { 10797 if (S.inTemplateInstantiation()) 10798 return false; 10799 10800 Expr *OriginalOther = Other; 10801 10802 Constant = Constant->IgnoreParenImpCasts(); 10803 Other = Other->IgnoreParenImpCasts(); 10804 10805 // Suppress warnings on tautological comparisons between values of the same 10806 // enumeration type. There are only two ways we could warn on this: 10807 // - If the constant is outside the range of representable values of 10808 // the enumeration. In such a case, we should warn about the cast 10809 // to enumeration type, not about the comparison. 10810 // - If the constant is the maximum / minimum in-range value. For an 10811 // enumeratin type, such comparisons can be meaningful and useful. 10812 if (Constant->getType()->isEnumeralType() && 10813 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10814 return false; 10815 10816 // TODO: Investigate using GetExprRange() to get tighter bounds 10817 // on the bit ranges. 10818 QualType OtherT = Other->getType(); 10819 if (const auto *AT = OtherT->getAs<AtomicType>()) 10820 OtherT = AT->getValueType(); 10821 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10822 10823 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10824 // (Namely, macOS). 10825 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10826 S.NSAPIObj->isObjCBOOLType(OtherT) && 10827 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10828 10829 // Whether we're treating Other as being a bool because of the form of 10830 // expression despite it having another type (typically 'int' in C). 10831 bool OtherIsBooleanDespiteType = 10832 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10833 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10834 OtherRange = IntRange::forBoolType(); 10835 10836 // Determine the promoted range of the other type and see if a comparison of 10837 // the constant against that range is tautological. 10838 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10839 Value.isUnsigned()); 10840 auto Cmp = OtherPromotedRange.compare(Value); 10841 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10842 if (!Result) 10843 return false; 10844 10845 // Suppress the diagnostic for an in-range comparison if the constant comes 10846 // from a macro or enumerator. We don't want to diagnose 10847 // 10848 // some_long_value <= INT_MAX 10849 // 10850 // when sizeof(int) == sizeof(long). 10851 bool InRange = Cmp & PromotedRange::InRangeFlag; 10852 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10853 return false; 10854 10855 // If this is a comparison to an enum constant, include that 10856 // constant in the diagnostic. 10857 const EnumConstantDecl *ED = nullptr; 10858 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10859 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10860 10861 // Should be enough for uint128 (39 decimal digits) 10862 SmallString<64> PrettySourceValue; 10863 llvm::raw_svector_ostream OS(PrettySourceValue); 10864 if (ED) { 10865 OS << '\'' << *ED << "' (" << Value << ")"; 10866 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10867 Constant->IgnoreParenImpCasts())) { 10868 OS << (BL->getValue() ? "YES" : "NO"); 10869 } else { 10870 OS << Value; 10871 } 10872 10873 if (IsObjCSignedCharBool) { 10874 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10875 S.PDiag(diag::warn_tautological_compare_objc_bool) 10876 << OS.str() << *Result); 10877 return true; 10878 } 10879 10880 // FIXME: We use a somewhat different formatting for the in-range cases and 10881 // cases involving boolean values for historical reasons. We should pick a 10882 // consistent way of presenting these diagnostics. 10883 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10884 10885 S.DiagRuntimeBehavior( 10886 E->getOperatorLoc(), E, 10887 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10888 : diag::warn_tautological_bool_compare) 10889 << OS.str() << classifyConstantValue(Constant) << OtherT 10890 << OtherIsBooleanDespiteType << *Result 10891 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10892 } else { 10893 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10894 ? (HasEnumType(OriginalOther) 10895 ? diag::warn_unsigned_enum_always_true_comparison 10896 : diag::warn_unsigned_always_true_comparison) 10897 : diag::warn_tautological_constant_compare; 10898 10899 S.Diag(E->getOperatorLoc(), Diag) 10900 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10901 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10902 } 10903 10904 return true; 10905 } 10906 10907 /// Analyze the operands of the given comparison. Implements the 10908 /// fallback case from AnalyzeComparison. 10909 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10910 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10911 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10912 } 10913 10914 /// Implements -Wsign-compare. 10915 /// 10916 /// \param E the binary operator to check for warnings 10917 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10918 // The type the comparison is being performed in. 10919 QualType T = E->getLHS()->getType(); 10920 10921 // Only analyze comparison operators where both sides have been converted to 10922 // the same type. 10923 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10924 return AnalyzeImpConvsInComparison(S, E); 10925 10926 // Don't analyze value-dependent comparisons directly. 10927 if (E->isValueDependent()) 10928 return AnalyzeImpConvsInComparison(S, E); 10929 10930 Expr *LHS = E->getLHS(); 10931 Expr *RHS = E->getRHS(); 10932 10933 if (T->isIntegralType(S.Context)) { 10934 llvm::APSInt RHSValue; 10935 llvm::APSInt LHSValue; 10936 10937 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10938 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10939 10940 // We don't care about expressions whose result is a constant. 10941 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10942 return AnalyzeImpConvsInComparison(S, E); 10943 10944 // We only care about expressions where just one side is literal 10945 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10946 // Is the constant on the RHS or LHS? 10947 const bool RhsConstant = IsRHSIntegralLiteral; 10948 Expr *Const = RhsConstant ? RHS : LHS; 10949 Expr *Other = RhsConstant ? LHS : RHS; 10950 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10951 10952 // Check whether an integer constant comparison results in a value 10953 // of 'true' or 'false'. 10954 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10955 return AnalyzeImpConvsInComparison(S, E); 10956 } 10957 } 10958 10959 if (!T->hasUnsignedIntegerRepresentation()) { 10960 // We don't do anything special if this isn't an unsigned integral 10961 // comparison: we're only interested in integral comparisons, and 10962 // signed comparisons only happen in cases we don't care to warn about. 10963 return AnalyzeImpConvsInComparison(S, E); 10964 } 10965 10966 LHS = LHS->IgnoreParenImpCasts(); 10967 RHS = RHS->IgnoreParenImpCasts(); 10968 10969 if (!S.getLangOpts().CPlusPlus) { 10970 // Avoid warning about comparison of integers with different signs when 10971 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10972 // the type of `E`. 10973 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10974 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10975 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10976 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10977 } 10978 10979 // Check to see if one of the (unmodified) operands is of different 10980 // signedness. 10981 Expr *signedOperand, *unsignedOperand; 10982 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10983 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10984 "unsigned comparison between two signed integer expressions?"); 10985 signedOperand = LHS; 10986 unsignedOperand = RHS; 10987 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10988 signedOperand = RHS; 10989 unsignedOperand = LHS; 10990 } else { 10991 return AnalyzeImpConvsInComparison(S, E); 10992 } 10993 10994 // Otherwise, calculate the effective range of the signed operand. 10995 IntRange signedRange = 10996 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10997 10998 // Go ahead and analyze implicit conversions in the operands. Note 10999 // that we skip the implicit conversions on both sides. 11000 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11001 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11002 11003 // If the signed range is non-negative, -Wsign-compare won't fire. 11004 if (signedRange.NonNegative) 11005 return; 11006 11007 // For (in)equality comparisons, if the unsigned operand is a 11008 // constant which cannot collide with a overflowed signed operand, 11009 // then reinterpreting the signed operand as unsigned will not 11010 // change the result of the comparison. 11011 if (E->isEqualityOp()) { 11012 unsigned comparisonWidth = S.Context.getIntWidth(T); 11013 IntRange unsignedRange = 11014 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 11015 11016 // We should never be unable to prove that the unsigned operand is 11017 // non-negative. 11018 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11019 11020 if (unsignedRange.Width < comparisonWidth) 11021 return; 11022 } 11023 11024 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11025 S.PDiag(diag::warn_mixed_sign_comparison) 11026 << LHS->getType() << RHS->getType() 11027 << LHS->getSourceRange() << RHS->getSourceRange()); 11028 } 11029 11030 /// Analyzes an attempt to assign the given value to a bitfield. 11031 /// 11032 /// Returns true if there was something fishy about the attempt. 11033 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11034 SourceLocation InitLoc) { 11035 assert(Bitfield->isBitField()); 11036 if (Bitfield->isInvalidDecl()) 11037 return false; 11038 11039 // White-list bool bitfields. 11040 QualType BitfieldType = Bitfield->getType(); 11041 if (BitfieldType->isBooleanType()) 11042 return false; 11043 11044 if (BitfieldType->isEnumeralType()) { 11045 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11046 // If the underlying enum type was not explicitly specified as an unsigned 11047 // type and the enum contain only positive values, MSVC++ will cause an 11048 // inconsistency by storing this as a signed type. 11049 if (S.getLangOpts().CPlusPlus11 && 11050 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11051 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11052 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11053 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11054 << BitfieldEnumDecl->getNameAsString(); 11055 } 11056 } 11057 11058 if (Bitfield->getType()->isBooleanType()) 11059 return false; 11060 11061 // Ignore value- or type-dependent expressions. 11062 if (Bitfield->getBitWidth()->isValueDependent() || 11063 Bitfield->getBitWidth()->isTypeDependent() || 11064 Init->isValueDependent() || 11065 Init->isTypeDependent()) 11066 return false; 11067 11068 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11069 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11070 11071 Expr::EvalResult Result; 11072 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11073 Expr::SE_AllowSideEffects)) { 11074 // The RHS is not constant. If the RHS has an enum type, make sure the 11075 // bitfield is wide enough to hold all the values of the enum without 11076 // truncation. 11077 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11078 EnumDecl *ED = EnumTy->getDecl(); 11079 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11080 11081 // Enum types are implicitly signed on Windows, so check if there are any 11082 // negative enumerators to see if the enum was intended to be signed or 11083 // not. 11084 bool SignedEnum = ED->getNumNegativeBits() > 0; 11085 11086 // Check for surprising sign changes when assigning enum values to a 11087 // bitfield of different signedness. If the bitfield is signed and we 11088 // have exactly the right number of bits to store this unsigned enum, 11089 // suggest changing the enum to an unsigned type. This typically happens 11090 // on Windows where unfixed enums always use an underlying type of 'int'. 11091 unsigned DiagID = 0; 11092 if (SignedEnum && !SignedBitfield) { 11093 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11094 } else if (SignedBitfield && !SignedEnum && 11095 ED->getNumPositiveBits() == FieldWidth) { 11096 DiagID = diag::warn_signed_bitfield_enum_conversion; 11097 } 11098 11099 if (DiagID) { 11100 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11101 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11102 SourceRange TypeRange = 11103 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11104 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11105 << SignedEnum << TypeRange; 11106 } 11107 11108 // Compute the required bitwidth. If the enum has negative values, we need 11109 // one more bit than the normal number of positive bits to represent the 11110 // sign bit. 11111 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11112 ED->getNumNegativeBits()) 11113 : ED->getNumPositiveBits(); 11114 11115 // Check the bitwidth. 11116 if (BitsNeeded > FieldWidth) { 11117 Expr *WidthExpr = Bitfield->getBitWidth(); 11118 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11119 << Bitfield << ED; 11120 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11121 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11122 } 11123 } 11124 11125 return false; 11126 } 11127 11128 llvm::APSInt Value = Result.Val.getInt(); 11129 11130 unsigned OriginalWidth = Value.getBitWidth(); 11131 11132 if (!Value.isSigned() || Value.isNegative()) 11133 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11134 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11135 OriginalWidth = Value.getMinSignedBits(); 11136 11137 if (OriginalWidth <= FieldWidth) 11138 return false; 11139 11140 // Compute the value which the bitfield will contain. 11141 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11142 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11143 11144 // Check whether the stored value is equal to the original value. 11145 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11146 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11147 return false; 11148 11149 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11150 // therefore don't strictly fit into a signed bitfield of width 1. 11151 if (FieldWidth == 1 && Value == 1) 11152 return false; 11153 11154 std::string PrettyValue = Value.toString(10); 11155 std::string PrettyTrunc = TruncatedValue.toString(10); 11156 11157 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11158 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11159 << Init->getSourceRange(); 11160 11161 return true; 11162 } 11163 11164 /// Analyze the given simple or compound assignment for warning-worthy 11165 /// operations. 11166 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11167 // Just recurse on the LHS. 11168 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11169 11170 // We want to recurse on the RHS as normal unless we're assigning to 11171 // a bitfield. 11172 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11173 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11174 E->getOperatorLoc())) { 11175 // Recurse, ignoring any implicit conversions on the RHS. 11176 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11177 E->getOperatorLoc()); 11178 } 11179 } 11180 11181 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11182 11183 // Diagnose implicitly sequentially-consistent atomic assignment. 11184 if (E->getLHS()->getType()->isAtomicType()) 11185 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11186 } 11187 11188 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11189 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11190 SourceLocation CContext, unsigned diag, 11191 bool pruneControlFlow = false) { 11192 if (pruneControlFlow) { 11193 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11194 S.PDiag(diag) 11195 << SourceType << T << E->getSourceRange() 11196 << SourceRange(CContext)); 11197 return; 11198 } 11199 S.Diag(E->getExprLoc(), diag) 11200 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11201 } 11202 11203 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11204 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11205 SourceLocation CContext, 11206 unsigned diag, bool pruneControlFlow = false) { 11207 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11208 } 11209 11210 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11211 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11212 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11213 } 11214 11215 static void adornObjCBoolConversionDiagWithTernaryFixit( 11216 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11217 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11218 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11219 Ignored = OVE->getSourceExpr(); 11220 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11221 isa<BinaryOperator>(Ignored) || 11222 isa<CXXOperatorCallExpr>(Ignored); 11223 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11224 if (NeedsParens) 11225 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11226 << FixItHint::CreateInsertion(EndLoc, ")"); 11227 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11228 } 11229 11230 /// Diagnose an implicit cast from a floating point value to an integer value. 11231 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11232 SourceLocation CContext) { 11233 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11234 const bool PruneWarnings = S.inTemplateInstantiation(); 11235 11236 Expr *InnerE = E->IgnoreParenImpCasts(); 11237 // We also want to warn on, e.g., "int i = -1.234" 11238 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11239 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11240 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11241 11242 const bool IsLiteral = 11243 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11244 11245 llvm::APFloat Value(0.0); 11246 bool IsConstant = 11247 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11248 if (!IsConstant) { 11249 if (isObjCSignedCharBool(S, T)) { 11250 return adornObjCBoolConversionDiagWithTernaryFixit( 11251 S, E, 11252 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11253 << E->getType()); 11254 } 11255 11256 return DiagnoseImpCast(S, E, T, CContext, 11257 diag::warn_impcast_float_integer, PruneWarnings); 11258 } 11259 11260 bool isExact = false; 11261 11262 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11263 T->hasUnsignedIntegerRepresentation()); 11264 llvm::APFloat::opStatus Result = Value.convertToInteger( 11265 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11266 11267 // FIXME: Force the precision of the source value down so we don't print 11268 // digits which are usually useless (we don't really care here if we 11269 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11270 // would automatically print the shortest representation, but it's a bit 11271 // tricky to implement. 11272 SmallString<16> PrettySourceValue; 11273 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11274 precision = (precision * 59 + 195) / 196; 11275 Value.toString(PrettySourceValue, precision); 11276 11277 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11278 return adornObjCBoolConversionDiagWithTernaryFixit( 11279 S, E, 11280 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11281 << PrettySourceValue); 11282 } 11283 11284 if (Result == llvm::APFloat::opOK && isExact) { 11285 if (IsLiteral) return; 11286 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11287 PruneWarnings); 11288 } 11289 11290 // Conversion of a floating-point value to a non-bool integer where the 11291 // integral part cannot be represented by the integer type is undefined. 11292 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11293 return DiagnoseImpCast( 11294 S, E, T, CContext, 11295 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11296 : diag::warn_impcast_float_to_integer_out_of_range, 11297 PruneWarnings); 11298 11299 unsigned DiagID = 0; 11300 if (IsLiteral) { 11301 // Warn on floating point literal to integer. 11302 DiagID = diag::warn_impcast_literal_float_to_integer; 11303 } else if (IntegerValue == 0) { 11304 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11305 return DiagnoseImpCast(S, E, T, CContext, 11306 diag::warn_impcast_float_integer, PruneWarnings); 11307 } 11308 // Warn on non-zero to zero conversion. 11309 DiagID = diag::warn_impcast_float_to_integer_zero; 11310 } else { 11311 if (IntegerValue.isUnsigned()) { 11312 if (!IntegerValue.isMaxValue()) { 11313 return DiagnoseImpCast(S, E, T, CContext, 11314 diag::warn_impcast_float_integer, PruneWarnings); 11315 } 11316 } else { // IntegerValue.isSigned() 11317 if (!IntegerValue.isMaxSignedValue() && 11318 !IntegerValue.isMinSignedValue()) { 11319 return DiagnoseImpCast(S, E, T, CContext, 11320 diag::warn_impcast_float_integer, PruneWarnings); 11321 } 11322 } 11323 // Warn on evaluatable floating point expression to integer conversion. 11324 DiagID = diag::warn_impcast_float_to_integer; 11325 } 11326 11327 SmallString<16> PrettyTargetValue; 11328 if (IsBool) 11329 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11330 else 11331 IntegerValue.toString(PrettyTargetValue); 11332 11333 if (PruneWarnings) { 11334 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11335 S.PDiag(DiagID) 11336 << E->getType() << T.getUnqualifiedType() 11337 << PrettySourceValue << PrettyTargetValue 11338 << E->getSourceRange() << SourceRange(CContext)); 11339 } else { 11340 S.Diag(E->getExprLoc(), DiagID) 11341 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11342 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11343 } 11344 } 11345 11346 /// Analyze the given compound assignment for the possible losing of 11347 /// floating-point precision. 11348 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11349 assert(isa<CompoundAssignOperator>(E) && 11350 "Must be compound assignment operation"); 11351 // Recurse on the LHS and RHS in here 11352 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11353 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11354 11355 if (E->getLHS()->getType()->isAtomicType()) 11356 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11357 11358 // Now check the outermost expression 11359 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11360 const auto *RBT = cast<CompoundAssignOperator>(E) 11361 ->getComputationResultType() 11362 ->getAs<BuiltinType>(); 11363 11364 // The below checks assume source is floating point. 11365 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11366 11367 // If source is floating point but target is an integer. 11368 if (ResultBT->isInteger()) 11369 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11370 E->getExprLoc(), diag::warn_impcast_float_integer); 11371 11372 if (!ResultBT->isFloatingPoint()) 11373 return; 11374 11375 // If both source and target are floating points, warn about losing precision. 11376 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11377 QualType(ResultBT, 0), QualType(RBT, 0)); 11378 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11379 // warn about dropping FP rank. 11380 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11381 diag::warn_impcast_float_result_precision); 11382 } 11383 11384 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11385 IntRange Range) { 11386 if (!Range.Width) return "0"; 11387 11388 llvm::APSInt ValueInRange = Value; 11389 ValueInRange.setIsSigned(!Range.NonNegative); 11390 ValueInRange = ValueInRange.trunc(Range.Width); 11391 return ValueInRange.toString(10); 11392 } 11393 11394 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11395 if (!isa<ImplicitCastExpr>(Ex)) 11396 return false; 11397 11398 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11399 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11400 const Type *Source = 11401 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11402 if (Target->isDependentType()) 11403 return false; 11404 11405 const BuiltinType *FloatCandidateBT = 11406 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11407 const Type *BoolCandidateType = ToBool ? Target : Source; 11408 11409 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11410 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11411 } 11412 11413 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11414 SourceLocation CC) { 11415 unsigned NumArgs = TheCall->getNumArgs(); 11416 for (unsigned i = 0; i < NumArgs; ++i) { 11417 Expr *CurrA = TheCall->getArg(i); 11418 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11419 continue; 11420 11421 bool IsSwapped = ((i > 0) && 11422 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11423 IsSwapped |= ((i < (NumArgs - 1)) && 11424 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11425 if (IsSwapped) { 11426 // Warn on this floating-point to bool conversion. 11427 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11428 CurrA->getType(), CC, 11429 diag::warn_impcast_floating_point_to_bool); 11430 } 11431 } 11432 } 11433 11434 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11435 SourceLocation CC) { 11436 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11437 E->getExprLoc())) 11438 return; 11439 11440 // Don't warn on functions which have return type nullptr_t. 11441 if (isa<CallExpr>(E)) 11442 return; 11443 11444 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11445 const Expr::NullPointerConstantKind NullKind = 11446 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11447 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11448 return; 11449 11450 // Return if target type is a safe conversion. 11451 if (T->isAnyPointerType() || T->isBlockPointerType() || 11452 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11453 return; 11454 11455 SourceLocation Loc = E->getSourceRange().getBegin(); 11456 11457 // Venture through the macro stacks to get to the source of macro arguments. 11458 // The new location is a better location than the complete location that was 11459 // passed in. 11460 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11461 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11462 11463 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11464 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11465 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11466 Loc, S.SourceMgr, S.getLangOpts()); 11467 if (MacroName == "NULL") 11468 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11469 } 11470 11471 // Only warn if the null and context location are in the same macro expansion. 11472 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11473 return; 11474 11475 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11476 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11477 << FixItHint::CreateReplacement(Loc, 11478 S.getFixItZeroLiteralForType(T, Loc)); 11479 } 11480 11481 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11482 ObjCArrayLiteral *ArrayLiteral); 11483 11484 static void 11485 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11486 ObjCDictionaryLiteral *DictionaryLiteral); 11487 11488 /// Check a single element within a collection literal against the 11489 /// target element type. 11490 static void checkObjCCollectionLiteralElement(Sema &S, 11491 QualType TargetElementType, 11492 Expr *Element, 11493 unsigned ElementKind) { 11494 // Skip a bitcast to 'id' or qualified 'id'. 11495 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11496 if (ICE->getCastKind() == CK_BitCast && 11497 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11498 Element = ICE->getSubExpr(); 11499 } 11500 11501 QualType ElementType = Element->getType(); 11502 ExprResult ElementResult(Element); 11503 if (ElementType->getAs<ObjCObjectPointerType>() && 11504 S.CheckSingleAssignmentConstraints(TargetElementType, 11505 ElementResult, 11506 false, false) 11507 != Sema::Compatible) { 11508 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11509 << ElementType << ElementKind << TargetElementType 11510 << Element->getSourceRange(); 11511 } 11512 11513 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11514 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11515 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11516 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11517 } 11518 11519 /// Check an Objective-C array literal being converted to the given 11520 /// target type. 11521 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11522 ObjCArrayLiteral *ArrayLiteral) { 11523 if (!S.NSArrayDecl) 11524 return; 11525 11526 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11527 if (!TargetObjCPtr) 11528 return; 11529 11530 if (TargetObjCPtr->isUnspecialized() || 11531 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11532 != S.NSArrayDecl->getCanonicalDecl()) 11533 return; 11534 11535 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11536 if (TypeArgs.size() != 1) 11537 return; 11538 11539 QualType TargetElementType = TypeArgs[0]; 11540 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11541 checkObjCCollectionLiteralElement(S, TargetElementType, 11542 ArrayLiteral->getElement(I), 11543 0); 11544 } 11545 } 11546 11547 /// Check an Objective-C dictionary literal being converted to the given 11548 /// target type. 11549 static void 11550 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11551 ObjCDictionaryLiteral *DictionaryLiteral) { 11552 if (!S.NSDictionaryDecl) 11553 return; 11554 11555 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11556 if (!TargetObjCPtr) 11557 return; 11558 11559 if (TargetObjCPtr->isUnspecialized() || 11560 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11561 != S.NSDictionaryDecl->getCanonicalDecl()) 11562 return; 11563 11564 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11565 if (TypeArgs.size() != 2) 11566 return; 11567 11568 QualType TargetKeyType = TypeArgs[0]; 11569 QualType TargetObjectType = TypeArgs[1]; 11570 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11571 auto Element = DictionaryLiteral->getKeyValueElement(I); 11572 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11573 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11574 } 11575 } 11576 11577 // Helper function to filter out cases for constant width constant conversion. 11578 // Don't warn on char array initialization or for non-decimal values. 11579 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11580 SourceLocation CC) { 11581 // If initializing from a constant, and the constant starts with '0', 11582 // then it is a binary, octal, or hexadecimal. Allow these constants 11583 // to fill all the bits, even if there is a sign change. 11584 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11585 const char FirstLiteralCharacter = 11586 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11587 if (FirstLiteralCharacter == '0') 11588 return false; 11589 } 11590 11591 // If the CC location points to a '{', and the type is char, then assume 11592 // assume it is an array initialization. 11593 if (CC.isValid() && T->isCharType()) { 11594 const char FirstContextCharacter = 11595 S.getSourceManager().getCharacterData(CC)[0]; 11596 if (FirstContextCharacter == '{') 11597 return false; 11598 } 11599 11600 return true; 11601 } 11602 11603 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11604 const auto *IL = dyn_cast<IntegerLiteral>(E); 11605 if (!IL) { 11606 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11607 if (UO->getOpcode() == UO_Minus) 11608 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11609 } 11610 } 11611 11612 return IL; 11613 } 11614 11615 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11616 E = E->IgnoreParenImpCasts(); 11617 SourceLocation ExprLoc = E->getExprLoc(); 11618 11619 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11620 BinaryOperator::Opcode Opc = BO->getOpcode(); 11621 Expr::EvalResult Result; 11622 // Do not diagnose unsigned shifts. 11623 if (Opc == BO_Shl) { 11624 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11625 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11626 if (LHS && LHS->getValue() == 0) 11627 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11628 else if (!E->isValueDependent() && LHS && RHS && 11629 RHS->getValue().isNonNegative() && 11630 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11631 S.Diag(ExprLoc, diag::warn_left_shift_always) 11632 << (Result.Val.getInt() != 0); 11633 else if (E->getType()->isSignedIntegerType()) 11634 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11635 } 11636 } 11637 11638 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11639 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11640 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11641 if (!LHS || !RHS) 11642 return; 11643 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11644 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11645 // Do not diagnose common idioms. 11646 return; 11647 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11648 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11649 } 11650 } 11651 11652 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11653 SourceLocation CC, 11654 bool *ICContext = nullptr, 11655 bool IsListInit = false) { 11656 if (E->isTypeDependent() || E->isValueDependent()) return; 11657 11658 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11659 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11660 if (Source == Target) return; 11661 if (Target->isDependentType()) return; 11662 11663 // If the conversion context location is invalid don't complain. We also 11664 // don't want to emit a warning if the issue occurs from the expansion of 11665 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11666 // delay this check as long as possible. Once we detect we are in that 11667 // scenario, we just return. 11668 if (CC.isInvalid()) 11669 return; 11670 11671 if (Source->isAtomicType()) 11672 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11673 11674 // Diagnose implicit casts to bool. 11675 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11676 if (isa<StringLiteral>(E)) 11677 // Warn on string literal to bool. Checks for string literals in logical 11678 // and expressions, for instance, assert(0 && "error here"), are 11679 // prevented by a check in AnalyzeImplicitConversions(). 11680 return DiagnoseImpCast(S, E, T, CC, 11681 diag::warn_impcast_string_literal_to_bool); 11682 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11683 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11684 // This covers the literal expressions that evaluate to Objective-C 11685 // objects. 11686 return DiagnoseImpCast(S, E, T, CC, 11687 diag::warn_impcast_objective_c_literal_to_bool); 11688 } 11689 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11690 // Warn on pointer to bool conversion that is always true. 11691 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11692 SourceRange(CC)); 11693 } 11694 } 11695 11696 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11697 // is a typedef for signed char (macOS), then that constant value has to be 1 11698 // or 0. 11699 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11700 Expr::EvalResult Result; 11701 if (E->EvaluateAsInt(Result, S.getASTContext(), 11702 Expr::SE_AllowSideEffects)) { 11703 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11704 adornObjCBoolConversionDiagWithTernaryFixit( 11705 S, E, 11706 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11707 << Result.Val.getInt().toString(10)); 11708 } 11709 return; 11710 } 11711 } 11712 11713 // Check implicit casts from Objective-C collection literals to specialized 11714 // collection types, e.g., NSArray<NSString *> *. 11715 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11716 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11717 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11718 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11719 11720 // Strip vector types. 11721 if (isa<VectorType>(Source)) { 11722 if (!isa<VectorType>(Target)) { 11723 if (S.SourceMgr.isInSystemMacro(CC)) 11724 return; 11725 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11726 } 11727 11728 // If the vector cast is cast between two vectors of the same size, it is 11729 // a bitcast, not a conversion. 11730 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11731 return; 11732 11733 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11734 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11735 } 11736 if (auto VecTy = dyn_cast<VectorType>(Target)) 11737 Target = VecTy->getElementType().getTypePtr(); 11738 11739 // Strip complex types. 11740 if (isa<ComplexType>(Source)) { 11741 if (!isa<ComplexType>(Target)) { 11742 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11743 return; 11744 11745 return DiagnoseImpCast(S, E, T, CC, 11746 S.getLangOpts().CPlusPlus 11747 ? diag::err_impcast_complex_scalar 11748 : diag::warn_impcast_complex_scalar); 11749 } 11750 11751 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11752 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11753 } 11754 11755 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11756 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11757 11758 // If the source is floating point... 11759 if (SourceBT && SourceBT->isFloatingPoint()) { 11760 // ...and the target is floating point... 11761 if (TargetBT && TargetBT->isFloatingPoint()) { 11762 // ...then warn if we're dropping FP rank. 11763 11764 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11765 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11766 if (Order > 0) { 11767 // Don't warn about float constants that are precisely 11768 // representable in the target type. 11769 Expr::EvalResult result; 11770 if (E->EvaluateAsRValue(result, S.Context)) { 11771 // Value might be a float, a float vector, or a float complex. 11772 if (IsSameFloatAfterCast(result.Val, 11773 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11774 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11775 return; 11776 } 11777 11778 if (S.SourceMgr.isInSystemMacro(CC)) 11779 return; 11780 11781 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11782 } 11783 // ... or possibly if we're increasing rank, too 11784 else if (Order < 0) { 11785 if (S.SourceMgr.isInSystemMacro(CC)) 11786 return; 11787 11788 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11789 } 11790 return; 11791 } 11792 11793 // If the target is integral, always warn. 11794 if (TargetBT && TargetBT->isInteger()) { 11795 if (S.SourceMgr.isInSystemMacro(CC)) 11796 return; 11797 11798 DiagnoseFloatingImpCast(S, E, T, CC); 11799 } 11800 11801 // Detect the case where a call result is converted from floating-point to 11802 // to bool, and the final argument to the call is converted from bool, to 11803 // discover this typo: 11804 // 11805 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11806 // 11807 // FIXME: This is an incredibly special case; is there some more general 11808 // way to detect this class of misplaced-parentheses bug? 11809 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11810 // Check last argument of function call to see if it is an 11811 // implicit cast from a type matching the type the result 11812 // is being cast to. 11813 CallExpr *CEx = cast<CallExpr>(E); 11814 if (unsigned NumArgs = CEx->getNumArgs()) { 11815 Expr *LastA = CEx->getArg(NumArgs - 1); 11816 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11817 if (isa<ImplicitCastExpr>(LastA) && 11818 InnerE->getType()->isBooleanType()) { 11819 // Warn on this floating-point to bool conversion 11820 DiagnoseImpCast(S, E, T, CC, 11821 diag::warn_impcast_floating_point_to_bool); 11822 } 11823 } 11824 } 11825 return; 11826 } 11827 11828 // Valid casts involving fixed point types should be accounted for here. 11829 if (Source->isFixedPointType()) { 11830 if (Target->isUnsaturatedFixedPointType()) { 11831 Expr::EvalResult Result; 11832 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11833 S.isConstantEvaluated())) { 11834 APFixedPoint Value = Result.Val.getFixedPoint(); 11835 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11836 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11837 if (Value > MaxVal || Value < MinVal) { 11838 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11839 S.PDiag(diag::warn_impcast_fixed_point_range) 11840 << Value.toString() << T 11841 << E->getSourceRange() 11842 << clang::SourceRange(CC)); 11843 return; 11844 } 11845 } 11846 } else if (Target->isIntegerType()) { 11847 Expr::EvalResult Result; 11848 if (!S.isConstantEvaluated() && 11849 E->EvaluateAsFixedPoint(Result, S.Context, 11850 Expr::SE_AllowSideEffects)) { 11851 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11852 11853 bool Overflowed; 11854 llvm::APSInt IntResult = FXResult.convertToInt( 11855 S.Context.getIntWidth(T), 11856 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11857 11858 if (Overflowed) { 11859 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11860 S.PDiag(diag::warn_impcast_fixed_point_range) 11861 << FXResult.toString() << T 11862 << E->getSourceRange() 11863 << clang::SourceRange(CC)); 11864 return; 11865 } 11866 } 11867 } 11868 } else if (Target->isUnsaturatedFixedPointType()) { 11869 if (Source->isIntegerType()) { 11870 Expr::EvalResult Result; 11871 if (!S.isConstantEvaluated() && 11872 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11873 llvm::APSInt Value = Result.Val.getInt(); 11874 11875 bool Overflowed; 11876 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11877 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11878 11879 if (Overflowed) { 11880 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11881 S.PDiag(diag::warn_impcast_fixed_point_range) 11882 << Value.toString(/*Radix=*/10) << T 11883 << E->getSourceRange() 11884 << clang::SourceRange(CC)); 11885 return; 11886 } 11887 } 11888 } 11889 } 11890 11891 // If we are casting an integer type to a floating point type without 11892 // initialization-list syntax, we might lose accuracy if the floating 11893 // point type has a narrower significand than the integer type. 11894 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11895 TargetBT->isFloatingType() && !IsListInit) { 11896 // Determine the number of precision bits in the source integer type. 11897 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11898 unsigned int SourcePrecision = SourceRange.Width; 11899 11900 // Determine the number of precision bits in the 11901 // target floating point type. 11902 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11903 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11904 11905 if (SourcePrecision > 0 && TargetPrecision > 0 && 11906 SourcePrecision > TargetPrecision) { 11907 11908 llvm::APSInt SourceInt; 11909 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11910 // If the source integer is a constant, convert it to the target 11911 // floating point type. Issue a warning if the value changes 11912 // during the whole conversion. 11913 llvm::APFloat TargetFloatValue( 11914 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11915 llvm::APFloat::opStatus ConversionStatus = 11916 TargetFloatValue.convertFromAPInt( 11917 SourceInt, SourceBT->isSignedInteger(), 11918 llvm::APFloat::rmNearestTiesToEven); 11919 11920 if (ConversionStatus != llvm::APFloat::opOK) { 11921 std::string PrettySourceValue = SourceInt.toString(10); 11922 SmallString<32> PrettyTargetValue; 11923 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11924 11925 S.DiagRuntimeBehavior( 11926 E->getExprLoc(), E, 11927 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11928 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11929 << E->getSourceRange() << clang::SourceRange(CC)); 11930 } 11931 } else { 11932 // Otherwise, the implicit conversion may lose precision. 11933 DiagnoseImpCast(S, E, T, CC, 11934 diag::warn_impcast_integer_float_precision); 11935 } 11936 } 11937 } 11938 11939 DiagnoseNullConversion(S, E, T, CC); 11940 11941 S.DiscardMisalignedMemberAddress(Target, E); 11942 11943 if (Target->isBooleanType()) 11944 DiagnoseIntInBoolContext(S, E); 11945 11946 if (!Source->isIntegerType() || !Target->isIntegerType()) 11947 return; 11948 11949 // TODO: remove this early return once the false positives for constant->bool 11950 // in templates, macros, etc, are reduced or removed. 11951 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11952 return; 11953 11954 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11955 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11956 return adornObjCBoolConversionDiagWithTernaryFixit( 11957 S, E, 11958 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11959 << E->getType()); 11960 } 11961 11962 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11963 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11964 11965 if (SourceRange.Width > TargetRange.Width) { 11966 // If the source is a constant, use a default-on diagnostic. 11967 // TODO: this should happen for bitfield stores, too. 11968 Expr::EvalResult Result; 11969 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11970 S.isConstantEvaluated())) { 11971 llvm::APSInt Value(32); 11972 Value = Result.Val.getInt(); 11973 11974 if (S.SourceMgr.isInSystemMacro(CC)) 11975 return; 11976 11977 std::string PrettySourceValue = Value.toString(10); 11978 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11979 11980 S.DiagRuntimeBehavior( 11981 E->getExprLoc(), E, 11982 S.PDiag(diag::warn_impcast_integer_precision_constant) 11983 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11984 << E->getSourceRange() << clang::SourceRange(CC)); 11985 return; 11986 } 11987 11988 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11989 if (S.SourceMgr.isInSystemMacro(CC)) 11990 return; 11991 11992 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11993 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11994 /* pruneControlFlow */ true); 11995 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11996 } 11997 11998 if (TargetRange.Width > SourceRange.Width) { 11999 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12000 if (UO->getOpcode() == UO_Minus) 12001 if (Source->isUnsignedIntegerType()) { 12002 if (Target->isUnsignedIntegerType()) 12003 return DiagnoseImpCast(S, E, T, CC, 12004 diag::warn_impcast_high_order_zero_bits); 12005 if (Target->isSignedIntegerType()) 12006 return DiagnoseImpCast(S, E, T, CC, 12007 diag::warn_impcast_nonnegative_result); 12008 } 12009 } 12010 12011 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 12012 SourceRange.NonNegative && Source->isSignedIntegerType()) { 12013 // Warn when doing a signed to signed conversion, warn if the positive 12014 // source value is exactly the width of the target type, which will 12015 // cause a negative value to be stored. 12016 12017 Expr::EvalResult Result; 12018 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12019 !S.SourceMgr.isInSystemMacro(CC)) { 12020 llvm::APSInt Value = Result.Val.getInt(); 12021 if (isSameWidthConstantConversion(S, E, T, CC)) { 12022 std::string PrettySourceValue = Value.toString(10); 12023 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12024 12025 S.DiagRuntimeBehavior( 12026 E->getExprLoc(), E, 12027 S.PDiag(diag::warn_impcast_integer_precision_constant) 12028 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12029 << E->getSourceRange() << clang::SourceRange(CC)); 12030 return; 12031 } 12032 } 12033 12034 // Fall through for non-constants to give a sign conversion warning. 12035 } 12036 12037 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 12038 (!TargetRange.NonNegative && SourceRange.NonNegative && 12039 SourceRange.Width == TargetRange.Width)) { 12040 if (S.SourceMgr.isInSystemMacro(CC)) 12041 return; 12042 12043 unsigned DiagID = diag::warn_impcast_integer_sign; 12044 12045 // Traditionally, gcc has warned about this under -Wsign-compare. 12046 // We also want to warn about it in -Wconversion. 12047 // So if -Wconversion is off, use a completely identical diagnostic 12048 // in the sign-compare group. 12049 // The conditional-checking code will 12050 if (ICContext) { 12051 DiagID = diag::warn_impcast_integer_sign_conditional; 12052 *ICContext = true; 12053 } 12054 12055 return DiagnoseImpCast(S, E, T, CC, DiagID); 12056 } 12057 12058 // Diagnose conversions between different enumeration types. 12059 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12060 // type, to give us better diagnostics. 12061 QualType SourceType = E->getType(); 12062 if (!S.getLangOpts().CPlusPlus) { 12063 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12064 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12065 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12066 SourceType = S.Context.getTypeDeclType(Enum); 12067 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12068 } 12069 } 12070 12071 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12072 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12073 if (SourceEnum->getDecl()->hasNameForLinkage() && 12074 TargetEnum->getDecl()->hasNameForLinkage() && 12075 SourceEnum != TargetEnum) { 12076 if (S.SourceMgr.isInSystemMacro(CC)) 12077 return; 12078 12079 return DiagnoseImpCast(S, E, SourceType, T, CC, 12080 diag::warn_impcast_different_enum_types); 12081 } 12082 } 12083 12084 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 12085 SourceLocation CC, QualType T); 12086 12087 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12088 SourceLocation CC, bool &ICContext) { 12089 E = E->IgnoreParenImpCasts(); 12090 12091 if (isa<ConditionalOperator>(E)) 12092 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 12093 12094 AnalyzeImplicitConversions(S, E, CC); 12095 if (E->getType() != T) 12096 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12097 } 12098 12099 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 12100 SourceLocation CC, QualType T) { 12101 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12102 12103 bool Suspicious = false; 12104 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 12105 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12106 12107 if (T->isBooleanType()) 12108 DiagnoseIntInBoolContext(S, E); 12109 12110 // If -Wconversion would have warned about either of the candidates 12111 // for a signedness conversion to the context type... 12112 if (!Suspicious) return; 12113 12114 // ...but it's currently ignored... 12115 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12116 return; 12117 12118 // ...then check whether it would have warned about either of the 12119 // candidates for a signedness conversion to the condition type. 12120 if (E->getType() == T) return; 12121 12122 Suspicious = false; 12123 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 12124 E->getType(), CC, &Suspicious); 12125 if (!Suspicious) 12126 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12127 E->getType(), CC, &Suspicious); 12128 } 12129 12130 /// Check conversion of given expression to boolean. 12131 /// Input argument E is a logical expression. 12132 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12133 if (S.getLangOpts().Bool) 12134 return; 12135 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12136 return; 12137 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12138 } 12139 12140 /// AnalyzeImplicitConversions - Find and report any interesting 12141 /// implicit conversions in the given expression. There are a couple 12142 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12143 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12144 bool IsListInit/*= false*/) { 12145 QualType T = OrigE->getType(); 12146 Expr *E = OrigE->IgnoreParenImpCasts(); 12147 12148 // Propagate whether we are in a C++ list initialization expression. 12149 // If so, we do not issue warnings for implicit int-float conversion 12150 // precision loss, because C++11 narrowing already handles it. 12151 IsListInit = 12152 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12153 12154 if (E->isTypeDependent() || E->isValueDependent()) 12155 return; 12156 12157 if (const auto *UO = dyn_cast<UnaryOperator>(E)) 12158 if (UO->getOpcode() == UO_Not && 12159 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12160 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12161 << OrigE->getSourceRange() << T->isBooleanType() 12162 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12163 12164 // For conditional operators, we analyze the arguments as if they 12165 // were being fed directly into the output. 12166 if (isa<ConditionalOperator>(E)) { 12167 ConditionalOperator *CO = cast<ConditionalOperator>(E); 12168 CheckConditionalOperator(S, CO, CC, T); 12169 return; 12170 } 12171 12172 // Check implicit argument conversions for function calls. 12173 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 12174 CheckImplicitArgumentConversions(S, Call, CC); 12175 12176 // Go ahead and check any implicit conversions we might have skipped. 12177 // The non-canonical typecheck is just an optimization; 12178 // CheckImplicitConversion will filter out dead implicit conversions. 12179 if (E->getType() != T) 12180 CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit); 12181 12182 // Now continue drilling into this expression. 12183 12184 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12185 // The bound subexpressions in a PseudoObjectExpr are not reachable 12186 // as transitive children. 12187 // FIXME: Use a more uniform representation for this. 12188 for (auto *SE : POE->semantics()) 12189 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12190 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit); 12191 } 12192 12193 // Skip past explicit casts. 12194 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12195 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12196 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12197 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12198 return AnalyzeImplicitConversions(S, E, CC, IsListInit); 12199 } 12200 12201 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12202 // Do a somewhat different check with comparison operators. 12203 if (BO->isComparisonOp()) 12204 return AnalyzeComparison(S, BO); 12205 12206 // And with simple assignments. 12207 if (BO->getOpcode() == BO_Assign) 12208 return AnalyzeAssignment(S, BO); 12209 // And with compound assignments. 12210 if (BO->isAssignmentOp()) 12211 return AnalyzeCompoundAssignment(S, BO); 12212 } 12213 12214 // These break the otherwise-useful invariant below. Fortunately, 12215 // we don't really need to recurse into them, because any internal 12216 // expressions should have been analyzed already when they were 12217 // built into statements. 12218 if (isa<StmtExpr>(E)) return; 12219 12220 // Don't descend into unevaluated contexts. 12221 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12222 12223 // Now just recurse over the expression's children. 12224 CC = E->getExprLoc(); 12225 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12226 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12227 for (Stmt *SubStmt : E->children()) { 12228 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12229 if (!ChildExpr) 12230 continue; 12231 12232 if (IsLogicalAndOperator && 12233 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12234 // Ignore checking string literals that are in logical and operators. 12235 // This is a common pattern for asserts. 12236 continue; 12237 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit); 12238 } 12239 12240 if (BO && BO->isLogicalOp()) { 12241 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12242 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12243 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12244 12245 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12246 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12247 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12248 } 12249 12250 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12251 if (U->getOpcode() == UO_LNot) { 12252 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12253 } else if (U->getOpcode() != UO_AddrOf) { 12254 if (U->getSubExpr()->getType()->isAtomicType()) 12255 S.Diag(U->getSubExpr()->getBeginLoc(), 12256 diag::warn_atomic_implicit_seq_cst); 12257 } 12258 } 12259 } 12260 12261 /// Diagnose integer type and any valid implicit conversion to it. 12262 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12263 // Taking into account implicit conversions, 12264 // allow any integer. 12265 if (!E->getType()->isIntegerType()) { 12266 S.Diag(E->getBeginLoc(), 12267 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12268 return true; 12269 } 12270 // Potentially emit standard warnings for implicit conversions if enabled 12271 // using -Wconversion. 12272 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12273 return false; 12274 } 12275 12276 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12277 // Returns true when emitting a warning about taking the address of a reference. 12278 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12279 const PartialDiagnostic &PD) { 12280 E = E->IgnoreParenImpCasts(); 12281 12282 const FunctionDecl *FD = nullptr; 12283 12284 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12285 if (!DRE->getDecl()->getType()->isReferenceType()) 12286 return false; 12287 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12288 if (!M->getMemberDecl()->getType()->isReferenceType()) 12289 return false; 12290 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12291 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12292 return false; 12293 FD = Call->getDirectCallee(); 12294 } else { 12295 return false; 12296 } 12297 12298 SemaRef.Diag(E->getExprLoc(), PD); 12299 12300 // If possible, point to location of function. 12301 if (FD) { 12302 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12303 } 12304 12305 return true; 12306 } 12307 12308 // Returns true if the SourceLocation is expanded from any macro body. 12309 // Returns false if the SourceLocation is invalid, is from not in a macro 12310 // expansion, or is from expanded from a top-level macro argument. 12311 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12312 if (Loc.isInvalid()) 12313 return false; 12314 12315 while (Loc.isMacroID()) { 12316 if (SM.isMacroBodyExpansion(Loc)) 12317 return true; 12318 Loc = SM.getImmediateMacroCallerLoc(Loc); 12319 } 12320 12321 return false; 12322 } 12323 12324 /// Diagnose pointers that are always non-null. 12325 /// \param E the expression containing the pointer 12326 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12327 /// compared to a null pointer 12328 /// \param IsEqual True when the comparison is equal to a null pointer 12329 /// \param Range Extra SourceRange to highlight in the diagnostic 12330 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12331 Expr::NullPointerConstantKind NullKind, 12332 bool IsEqual, SourceRange Range) { 12333 if (!E) 12334 return; 12335 12336 // Don't warn inside macros. 12337 if (E->getExprLoc().isMacroID()) { 12338 const SourceManager &SM = getSourceManager(); 12339 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12340 IsInAnyMacroBody(SM, Range.getBegin())) 12341 return; 12342 } 12343 E = E->IgnoreImpCasts(); 12344 12345 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12346 12347 if (isa<CXXThisExpr>(E)) { 12348 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12349 : diag::warn_this_bool_conversion; 12350 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12351 return; 12352 } 12353 12354 bool IsAddressOf = false; 12355 12356 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12357 if (UO->getOpcode() != UO_AddrOf) 12358 return; 12359 IsAddressOf = true; 12360 E = UO->getSubExpr(); 12361 } 12362 12363 if (IsAddressOf) { 12364 unsigned DiagID = IsCompare 12365 ? diag::warn_address_of_reference_null_compare 12366 : diag::warn_address_of_reference_bool_conversion; 12367 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12368 << IsEqual; 12369 if (CheckForReference(*this, E, PD)) { 12370 return; 12371 } 12372 } 12373 12374 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12375 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12376 std::string Str; 12377 llvm::raw_string_ostream S(Str); 12378 E->printPretty(S, nullptr, getPrintingPolicy()); 12379 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12380 : diag::warn_cast_nonnull_to_bool; 12381 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12382 << E->getSourceRange() << Range << IsEqual; 12383 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12384 }; 12385 12386 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12387 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12388 if (auto *Callee = Call->getDirectCallee()) { 12389 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12390 ComplainAboutNonnullParamOrCall(A); 12391 return; 12392 } 12393 } 12394 } 12395 12396 // Expect to find a single Decl. Skip anything more complicated. 12397 ValueDecl *D = nullptr; 12398 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12399 D = R->getDecl(); 12400 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12401 D = M->getMemberDecl(); 12402 } 12403 12404 // Weak Decls can be null. 12405 if (!D || D->isWeak()) 12406 return; 12407 12408 // Check for parameter decl with nonnull attribute 12409 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12410 if (getCurFunction() && 12411 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12412 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12413 ComplainAboutNonnullParamOrCall(A); 12414 return; 12415 } 12416 12417 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12418 // Skip function template not specialized yet. 12419 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12420 return; 12421 auto ParamIter = llvm::find(FD->parameters(), PV); 12422 assert(ParamIter != FD->param_end()); 12423 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12424 12425 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12426 if (!NonNull->args_size()) { 12427 ComplainAboutNonnullParamOrCall(NonNull); 12428 return; 12429 } 12430 12431 for (const ParamIdx &ArgNo : NonNull->args()) { 12432 if (ArgNo.getASTIndex() == ParamNo) { 12433 ComplainAboutNonnullParamOrCall(NonNull); 12434 return; 12435 } 12436 } 12437 } 12438 } 12439 } 12440 } 12441 12442 QualType T = D->getType(); 12443 const bool IsArray = T->isArrayType(); 12444 const bool IsFunction = T->isFunctionType(); 12445 12446 // Address of function is used to silence the function warning. 12447 if (IsAddressOf && IsFunction) { 12448 return; 12449 } 12450 12451 // Found nothing. 12452 if (!IsAddressOf && !IsFunction && !IsArray) 12453 return; 12454 12455 // Pretty print the expression for the diagnostic. 12456 std::string Str; 12457 llvm::raw_string_ostream S(Str); 12458 E->printPretty(S, nullptr, getPrintingPolicy()); 12459 12460 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12461 : diag::warn_impcast_pointer_to_bool; 12462 enum { 12463 AddressOf, 12464 FunctionPointer, 12465 ArrayPointer 12466 } DiagType; 12467 if (IsAddressOf) 12468 DiagType = AddressOf; 12469 else if (IsFunction) 12470 DiagType = FunctionPointer; 12471 else if (IsArray) 12472 DiagType = ArrayPointer; 12473 else 12474 llvm_unreachable("Could not determine diagnostic."); 12475 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12476 << Range << IsEqual; 12477 12478 if (!IsFunction) 12479 return; 12480 12481 // Suggest '&' to silence the function warning. 12482 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12483 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12484 12485 // Check to see if '()' fixit should be emitted. 12486 QualType ReturnType; 12487 UnresolvedSet<4> NonTemplateOverloads; 12488 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12489 if (ReturnType.isNull()) 12490 return; 12491 12492 if (IsCompare) { 12493 // There are two cases here. If there is null constant, the only suggest 12494 // for a pointer return type. If the null is 0, then suggest if the return 12495 // type is a pointer or an integer type. 12496 if (!ReturnType->isPointerType()) { 12497 if (NullKind == Expr::NPCK_ZeroExpression || 12498 NullKind == Expr::NPCK_ZeroLiteral) { 12499 if (!ReturnType->isIntegerType()) 12500 return; 12501 } else { 12502 return; 12503 } 12504 } 12505 } else { // !IsCompare 12506 // For function to bool, only suggest if the function pointer has bool 12507 // return type. 12508 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12509 return; 12510 } 12511 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12512 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12513 } 12514 12515 /// Diagnoses "dangerous" implicit conversions within the given 12516 /// expression (which is a full expression). Implements -Wconversion 12517 /// and -Wsign-compare. 12518 /// 12519 /// \param CC the "context" location of the implicit conversion, i.e. 12520 /// the most location of the syntactic entity requiring the implicit 12521 /// conversion 12522 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12523 // Don't diagnose in unevaluated contexts. 12524 if (isUnevaluatedContext()) 12525 return; 12526 12527 // Don't diagnose for value- or type-dependent expressions. 12528 if (E->isTypeDependent() || E->isValueDependent()) 12529 return; 12530 12531 // Check for array bounds violations in cases where the check isn't triggered 12532 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12533 // ArraySubscriptExpr is on the RHS of a variable initialization. 12534 CheckArrayAccess(E); 12535 12536 // This is not the right CC for (e.g.) a variable initialization. 12537 AnalyzeImplicitConversions(*this, E, CC); 12538 } 12539 12540 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12541 /// Input argument E is a logical expression. 12542 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12543 ::CheckBoolLikeConversion(*this, E, CC); 12544 } 12545 12546 /// Diagnose when expression is an integer constant expression and its evaluation 12547 /// results in integer overflow 12548 void Sema::CheckForIntOverflow (Expr *E) { 12549 // Use a work list to deal with nested struct initializers. 12550 SmallVector<Expr *, 2> Exprs(1, E); 12551 12552 do { 12553 Expr *OriginalE = Exprs.pop_back_val(); 12554 Expr *E = OriginalE->IgnoreParenCasts(); 12555 12556 if (isa<BinaryOperator>(E)) { 12557 E->EvaluateForOverflow(Context); 12558 continue; 12559 } 12560 12561 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12562 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12563 else if (isa<ObjCBoxedExpr>(OriginalE)) 12564 E->EvaluateForOverflow(Context); 12565 else if (auto Call = dyn_cast<CallExpr>(E)) 12566 Exprs.append(Call->arg_begin(), Call->arg_end()); 12567 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12568 Exprs.append(Message->arg_begin(), Message->arg_end()); 12569 } while (!Exprs.empty()); 12570 } 12571 12572 namespace { 12573 12574 /// Visitor for expressions which looks for unsequenced operations on the 12575 /// same object. 12576 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12577 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12578 12579 /// A tree of sequenced regions within an expression. Two regions are 12580 /// unsequenced if one is an ancestor or a descendent of the other. When we 12581 /// finish processing an expression with sequencing, such as a comma 12582 /// expression, we fold its tree nodes into its parent, since they are 12583 /// unsequenced with respect to nodes we will visit later. 12584 class SequenceTree { 12585 struct Value { 12586 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12587 unsigned Parent : 31; 12588 unsigned Merged : 1; 12589 }; 12590 SmallVector<Value, 8> Values; 12591 12592 public: 12593 /// A region within an expression which may be sequenced with respect 12594 /// to some other region. 12595 class Seq { 12596 friend class SequenceTree; 12597 12598 unsigned Index; 12599 12600 explicit Seq(unsigned N) : Index(N) {} 12601 12602 public: 12603 Seq() : Index(0) {} 12604 }; 12605 12606 SequenceTree() { Values.push_back(Value(0)); } 12607 Seq root() const { return Seq(0); } 12608 12609 /// Create a new sequence of operations, which is an unsequenced 12610 /// subset of \p Parent. This sequence of operations is sequenced with 12611 /// respect to other children of \p Parent. 12612 Seq allocate(Seq Parent) { 12613 Values.push_back(Value(Parent.Index)); 12614 return Seq(Values.size() - 1); 12615 } 12616 12617 /// Merge a sequence of operations into its parent. 12618 void merge(Seq S) { 12619 Values[S.Index].Merged = true; 12620 } 12621 12622 /// Determine whether two operations are unsequenced. This operation 12623 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12624 /// should have been merged into its parent as appropriate. 12625 bool isUnsequenced(Seq Cur, Seq Old) { 12626 unsigned C = representative(Cur.Index); 12627 unsigned Target = representative(Old.Index); 12628 while (C >= Target) { 12629 if (C == Target) 12630 return true; 12631 C = Values[C].Parent; 12632 } 12633 return false; 12634 } 12635 12636 private: 12637 /// Pick a representative for a sequence. 12638 unsigned representative(unsigned K) { 12639 if (Values[K].Merged) 12640 // Perform path compression as we go. 12641 return Values[K].Parent = representative(Values[K].Parent); 12642 return K; 12643 } 12644 }; 12645 12646 /// An object for which we can track unsequenced uses. 12647 using Object = const NamedDecl *; 12648 12649 /// Different flavors of object usage which we track. We only track the 12650 /// least-sequenced usage of each kind. 12651 enum UsageKind { 12652 /// A read of an object. Multiple unsequenced reads are OK. 12653 UK_Use, 12654 12655 /// A modification of an object which is sequenced before the value 12656 /// computation of the expression, such as ++n in C++. 12657 UK_ModAsValue, 12658 12659 /// A modification of an object which is not sequenced before the value 12660 /// computation of the expression, such as n++. 12661 UK_ModAsSideEffect, 12662 12663 UK_Count = UK_ModAsSideEffect + 1 12664 }; 12665 12666 /// Bundle together a sequencing region and the expression corresponding 12667 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12668 struct Usage { 12669 const Expr *UsageExpr; 12670 SequenceTree::Seq Seq; 12671 12672 Usage() : UsageExpr(nullptr), Seq() {} 12673 }; 12674 12675 struct UsageInfo { 12676 Usage Uses[UK_Count]; 12677 12678 /// Have we issued a diagnostic for this object already? 12679 bool Diagnosed; 12680 12681 UsageInfo() : Uses(), Diagnosed(false) {} 12682 }; 12683 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12684 12685 Sema &SemaRef; 12686 12687 /// Sequenced regions within the expression. 12688 SequenceTree Tree; 12689 12690 /// Declaration modifications and references which we have seen. 12691 UsageInfoMap UsageMap; 12692 12693 /// The region we are currently within. 12694 SequenceTree::Seq Region; 12695 12696 /// Filled in with declarations which were modified as a side-effect 12697 /// (that is, post-increment operations). 12698 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12699 12700 /// Expressions to check later. We defer checking these to reduce 12701 /// stack usage. 12702 SmallVectorImpl<const Expr *> &WorkList; 12703 12704 /// RAII object wrapping the visitation of a sequenced subexpression of an 12705 /// expression. At the end of this process, the side-effects of the evaluation 12706 /// become sequenced with respect to the value computation of the result, so 12707 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12708 /// UK_ModAsValue. 12709 struct SequencedSubexpression { 12710 SequencedSubexpression(SequenceChecker &Self) 12711 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12712 Self.ModAsSideEffect = &ModAsSideEffect; 12713 } 12714 12715 ~SequencedSubexpression() { 12716 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12717 // Add a new usage with usage kind UK_ModAsValue, and then restore 12718 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12719 // the previous one was empty). 12720 UsageInfo &UI = Self.UsageMap[M.first]; 12721 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12722 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12723 SideEffectUsage = M.second; 12724 } 12725 Self.ModAsSideEffect = OldModAsSideEffect; 12726 } 12727 12728 SequenceChecker &Self; 12729 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12730 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12731 }; 12732 12733 /// RAII object wrapping the visitation of a subexpression which we might 12734 /// choose to evaluate as a constant. If any subexpression is evaluated and 12735 /// found to be non-constant, this allows us to suppress the evaluation of 12736 /// the outer expression. 12737 class EvaluationTracker { 12738 public: 12739 EvaluationTracker(SequenceChecker &Self) 12740 : Self(Self), Prev(Self.EvalTracker) { 12741 Self.EvalTracker = this; 12742 } 12743 12744 ~EvaluationTracker() { 12745 Self.EvalTracker = Prev; 12746 if (Prev) 12747 Prev->EvalOK &= EvalOK; 12748 } 12749 12750 bool evaluate(const Expr *E, bool &Result) { 12751 if (!EvalOK || E->isValueDependent()) 12752 return false; 12753 EvalOK = E->EvaluateAsBooleanCondition( 12754 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12755 return EvalOK; 12756 } 12757 12758 private: 12759 SequenceChecker &Self; 12760 EvaluationTracker *Prev; 12761 bool EvalOK = true; 12762 } *EvalTracker = nullptr; 12763 12764 /// Find the object which is produced by the specified expression, 12765 /// if any. 12766 Object getObject(const Expr *E, bool Mod) const { 12767 E = E->IgnoreParenCasts(); 12768 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12769 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12770 return getObject(UO->getSubExpr(), Mod); 12771 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12772 if (BO->getOpcode() == BO_Comma) 12773 return getObject(BO->getRHS(), Mod); 12774 if (Mod && BO->isAssignmentOp()) 12775 return getObject(BO->getLHS(), Mod); 12776 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12777 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12778 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12779 return ME->getMemberDecl(); 12780 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12781 // FIXME: If this is a reference, map through to its value. 12782 return DRE->getDecl(); 12783 return nullptr; 12784 } 12785 12786 /// Note that an object \p O was modified or used by an expression 12787 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12788 /// the object \p O as obtained via the \p UsageMap. 12789 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12790 // Get the old usage for the given object and usage kind. 12791 Usage &U = UI.Uses[UK]; 12792 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12793 // If we have a modification as side effect and are in a sequenced 12794 // subexpression, save the old Usage so that we can restore it later 12795 // in SequencedSubexpression::~SequencedSubexpression. 12796 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12797 ModAsSideEffect->push_back(std::make_pair(O, U)); 12798 // Then record the new usage with the current sequencing region. 12799 U.UsageExpr = UsageExpr; 12800 U.Seq = Region; 12801 } 12802 } 12803 12804 /// Check whether a modification or use of an object \p O in an expression 12805 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12806 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12807 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12808 /// usage and false we are checking for a mod-use unsequenced usage. 12809 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12810 UsageKind OtherKind, bool IsModMod) { 12811 if (UI.Diagnosed) 12812 return; 12813 12814 const Usage &U = UI.Uses[OtherKind]; 12815 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12816 return; 12817 12818 const Expr *Mod = U.UsageExpr; 12819 const Expr *ModOrUse = UsageExpr; 12820 if (OtherKind == UK_Use) 12821 std::swap(Mod, ModOrUse); 12822 12823 SemaRef.DiagRuntimeBehavior( 12824 Mod->getExprLoc(), {Mod, ModOrUse}, 12825 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12826 : diag::warn_unsequenced_mod_use) 12827 << O << SourceRange(ModOrUse->getExprLoc())); 12828 UI.Diagnosed = true; 12829 } 12830 12831 // A note on note{Pre, Post}{Use, Mod}: 12832 // 12833 // (It helps to follow the algorithm with an expression such as 12834 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12835 // operations before C++17 and both are well-defined in C++17). 12836 // 12837 // When visiting a node which uses/modify an object we first call notePreUse 12838 // or notePreMod before visiting its sub-expression(s). At this point the 12839 // children of the current node have not yet been visited and so the eventual 12840 // uses/modifications resulting from the children of the current node have not 12841 // been recorded yet. 12842 // 12843 // We then visit the children of the current node. After that notePostUse or 12844 // notePostMod is called. These will 1) detect an unsequenced modification 12845 // as side effect (as in "k++ + k") and 2) add a new usage with the 12846 // appropriate usage kind. 12847 // 12848 // We also have to be careful that some operation sequences modification as 12849 // side effect as well (for example: || or ,). To account for this we wrap 12850 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12851 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12852 // which record usages which are modifications as side effect, and then 12853 // downgrade them (or more accurately restore the previous usage which was a 12854 // modification as side effect) when exiting the scope of the sequenced 12855 // subexpression. 12856 12857 void notePreUse(Object O, const Expr *UseExpr) { 12858 UsageInfo &UI = UsageMap[O]; 12859 // Uses conflict with other modifications. 12860 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12861 } 12862 12863 void notePostUse(Object O, const Expr *UseExpr) { 12864 UsageInfo &UI = UsageMap[O]; 12865 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12866 /*IsModMod=*/false); 12867 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12868 } 12869 12870 void notePreMod(Object O, const Expr *ModExpr) { 12871 UsageInfo &UI = UsageMap[O]; 12872 // Modifications conflict with other modifications and with uses. 12873 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12874 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12875 } 12876 12877 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12878 UsageInfo &UI = UsageMap[O]; 12879 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12880 /*IsModMod=*/true); 12881 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12882 } 12883 12884 public: 12885 SequenceChecker(Sema &S, const Expr *E, 12886 SmallVectorImpl<const Expr *> &WorkList) 12887 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12888 Visit(E); 12889 // Silence a -Wunused-private-field since WorkList is now unused. 12890 // TODO: Evaluate if it can be used, and if not remove it. 12891 (void)this->WorkList; 12892 } 12893 12894 void VisitStmt(const Stmt *S) { 12895 // Skip all statements which aren't expressions for now. 12896 } 12897 12898 void VisitExpr(const Expr *E) { 12899 // By default, just recurse to evaluated subexpressions. 12900 Base::VisitStmt(E); 12901 } 12902 12903 void VisitCastExpr(const CastExpr *E) { 12904 Object O = Object(); 12905 if (E->getCastKind() == CK_LValueToRValue) 12906 O = getObject(E->getSubExpr(), false); 12907 12908 if (O) 12909 notePreUse(O, E); 12910 VisitExpr(E); 12911 if (O) 12912 notePostUse(O, E); 12913 } 12914 12915 void VisitSequencedExpressions(const Expr *SequencedBefore, 12916 const Expr *SequencedAfter) { 12917 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12918 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12919 SequenceTree::Seq OldRegion = Region; 12920 12921 { 12922 SequencedSubexpression SeqBefore(*this); 12923 Region = BeforeRegion; 12924 Visit(SequencedBefore); 12925 } 12926 12927 Region = AfterRegion; 12928 Visit(SequencedAfter); 12929 12930 Region = OldRegion; 12931 12932 Tree.merge(BeforeRegion); 12933 Tree.merge(AfterRegion); 12934 } 12935 12936 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12937 // C++17 [expr.sub]p1: 12938 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12939 // expression E1 is sequenced before the expression E2. 12940 if (SemaRef.getLangOpts().CPlusPlus17) 12941 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12942 else { 12943 Visit(ASE->getLHS()); 12944 Visit(ASE->getRHS()); 12945 } 12946 } 12947 12948 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12949 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12950 void VisitBinPtrMem(const BinaryOperator *BO) { 12951 // C++17 [expr.mptr.oper]p4: 12952 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12953 // the expression E1 is sequenced before the expression E2. 12954 if (SemaRef.getLangOpts().CPlusPlus17) 12955 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12956 else { 12957 Visit(BO->getLHS()); 12958 Visit(BO->getRHS()); 12959 } 12960 } 12961 12962 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12963 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12964 void VisitBinShlShr(const BinaryOperator *BO) { 12965 // C++17 [expr.shift]p4: 12966 // The expression E1 is sequenced before the expression E2. 12967 if (SemaRef.getLangOpts().CPlusPlus17) 12968 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12969 else { 12970 Visit(BO->getLHS()); 12971 Visit(BO->getRHS()); 12972 } 12973 } 12974 12975 void VisitBinComma(const BinaryOperator *BO) { 12976 // C++11 [expr.comma]p1: 12977 // Every value computation and side effect associated with the left 12978 // expression is sequenced before every value computation and side 12979 // effect associated with the right expression. 12980 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12981 } 12982 12983 void VisitBinAssign(const BinaryOperator *BO) { 12984 SequenceTree::Seq RHSRegion; 12985 SequenceTree::Seq LHSRegion; 12986 if (SemaRef.getLangOpts().CPlusPlus17) { 12987 RHSRegion = Tree.allocate(Region); 12988 LHSRegion = Tree.allocate(Region); 12989 } else { 12990 RHSRegion = Region; 12991 LHSRegion = Region; 12992 } 12993 SequenceTree::Seq OldRegion = Region; 12994 12995 // C++11 [expr.ass]p1: 12996 // [...] the assignment is sequenced after the value computation 12997 // of the right and left operands, [...] 12998 // 12999 // so check it before inspecting the operands and update the 13000 // map afterwards. 13001 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13002 if (O) 13003 notePreMod(O, BO); 13004 13005 if (SemaRef.getLangOpts().CPlusPlus17) { 13006 // C++17 [expr.ass]p1: 13007 // [...] The right operand is sequenced before the left operand. [...] 13008 { 13009 SequencedSubexpression SeqBefore(*this); 13010 Region = RHSRegion; 13011 Visit(BO->getRHS()); 13012 } 13013 13014 Region = LHSRegion; 13015 Visit(BO->getLHS()); 13016 13017 if (O && isa<CompoundAssignOperator>(BO)) 13018 notePostUse(O, BO); 13019 13020 } else { 13021 // C++11 does not specify any sequencing between the LHS and RHS. 13022 Region = LHSRegion; 13023 Visit(BO->getLHS()); 13024 13025 if (O && isa<CompoundAssignOperator>(BO)) 13026 notePostUse(O, BO); 13027 13028 Region = RHSRegion; 13029 Visit(BO->getRHS()); 13030 } 13031 13032 // C++11 [expr.ass]p1: 13033 // the assignment is sequenced [...] before the value computation of the 13034 // assignment expression. 13035 // C11 6.5.16/3 has no such rule. 13036 Region = OldRegion; 13037 if (O) 13038 notePostMod(O, BO, 13039 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13040 : UK_ModAsSideEffect); 13041 if (SemaRef.getLangOpts().CPlusPlus17) { 13042 Tree.merge(RHSRegion); 13043 Tree.merge(LHSRegion); 13044 } 13045 } 13046 13047 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13048 VisitBinAssign(CAO); 13049 } 13050 13051 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13052 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13053 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13054 Object O = getObject(UO->getSubExpr(), true); 13055 if (!O) 13056 return VisitExpr(UO); 13057 13058 notePreMod(O, UO); 13059 Visit(UO->getSubExpr()); 13060 // C++11 [expr.pre.incr]p1: 13061 // the expression ++x is equivalent to x+=1 13062 notePostMod(O, UO, 13063 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13064 : UK_ModAsSideEffect); 13065 } 13066 13067 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13068 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13069 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13070 Object O = getObject(UO->getSubExpr(), true); 13071 if (!O) 13072 return VisitExpr(UO); 13073 13074 notePreMod(O, UO); 13075 Visit(UO->getSubExpr()); 13076 notePostMod(O, UO, UK_ModAsSideEffect); 13077 } 13078 13079 void VisitBinLOr(const BinaryOperator *BO) { 13080 // C++11 [expr.log.or]p2: 13081 // If the second expression is evaluated, every value computation and 13082 // side effect associated with the first expression is sequenced before 13083 // every value computation and side effect associated with the 13084 // second expression. 13085 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13086 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13087 SequenceTree::Seq OldRegion = Region; 13088 13089 EvaluationTracker Eval(*this); 13090 { 13091 SequencedSubexpression Sequenced(*this); 13092 Region = LHSRegion; 13093 Visit(BO->getLHS()); 13094 } 13095 13096 // C++11 [expr.log.or]p1: 13097 // [...] the second operand is not evaluated if the first operand 13098 // evaluates to true. 13099 bool EvalResult = false; 13100 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13101 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13102 if (ShouldVisitRHS) { 13103 Region = RHSRegion; 13104 Visit(BO->getRHS()); 13105 } 13106 13107 Region = OldRegion; 13108 Tree.merge(LHSRegion); 13109 Tree.merge(RHSRegion); 13110 } 13111 13112 void VisitBinLAnd(const BinaryOperator *BO) { 13113 // C++11 [expr.log.and]p2: 13114 // If the second expression is evaluated, every value computation and 13115 // side effect associated with the first expression is sequenced before 13116 // every value computation and side effect associated with the 13117 // second expression. 13118 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13119 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13120 SequenceTree::Seq OldRegion = Region; 13121 13122 EvaluationTracker Eval(*this); 13123 { 13124 SequencedSubexpression Sequenced(*this); 13125 Region = LHSRegion; 13126 Visit(BO->getLHS()); 13127 } 13128 13129 // C++11 [expr.log.and]p1: 13130 // [...] the second operand is not evaluated if the first operand is false. 13131 bool EvalResult = false; 13132 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13133 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13134 if (ShouldVisitRHS) { 13135 Region = RHSRegion; 13136 Visit(BO->getRHS()); 13137 } 13138 13139 Region = OldRegion; 13140 Tree.merge(LHSRegion); 13141 Tree.merge(RHSRegion); 13142 } 13143 13144 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13145 // C++11 [expr.cond]p1: 13146 // [...] Every value computation and side effect associated with the first 13147 // expression is sequenced before every value computation and side effect 13148 // associated with the second or third expression. 13149 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13150 13151 // No sequencing is specified between the true and false expression. 13152 // However since exactly one of both is going to be evaluated we can 13153 // consider them to be sequenced. This is needed to avoid warning on 13154 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13155 // both the true and false expressions because we can't evaluate x. 13156 // This will still allow us to detect an expression like (pre C++17) 13157 // "(x ? y += 1 : y += 2) = y". 13158 // 13159 // We don't wrap the visitation of the true and false expression with 13160 // SequencedSubexpression because we don't want to downgrade modifications 13161 // as side effect in the true and false expressions after the visition 13162 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13163 // not warn between the two "y++", but we should warn between the "y++" 13164 // and the "y". 13165 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13166 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13167 SequenceTree::Seq OldRegion = Region; 13168 13169 EvaluationTracker Eval(*this); 13170 { 13171 SequencedSubexpression Sequenced(*this); 13172 Region = ConditionRegion; 13173 Visit(CO->getCond()); 13174 } 13175 13176 // C++11 [expr.cond]p1: 13177 // [...] The first expression is contextually converted to bool (Clause 4). 13178 // It is evaluated and if it is true, the result of the conditional 13179 // expression is the value of the second expression, otherwise that of the 13180 // third expression. Only one of the second and third expressions is 13181 // evaluated. [...] 13182 bool EvalResult = false; 13183 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13184 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13185 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13186 if (ShouldVisitTrueExpr) { 13187 Region = TrueRegion; 13188 Visit(CO->getTrueExpr()); 13189 } 13190 if (ShouldVisitFalseExpr) { 13191 Region = FalseRegion; 13192 Visit(CO->getFalseExpr()); 13193 } 13194 13195 Region = OldRegion; 13196 Tree.merge(ConditionRegion); 13197 Tree.merge(TrueRegion); 13198 Tree.merge(FalseRegion); 13199 } 13200 13201 void VisitCallExpr(const CallExpr *CE) { 13202 // C++11 [intro.execution]p15: 13203 // When calling a function [...], every value computation and side effect 13204 // associated with any argument expression, or with the postfix expression 13205 // designating the called function, is sequenced before execution of every 13206 // expression or statement in the body of the function [and thus before 13207 // the value computation of its result]. 13208 SequencedSubexpression Sequenced(*this); 13209 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), 13210 [&] { Base::VisitCallExpr(CE); }); 13211 13212 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13213 } 13214 13215 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13216 // This is a call, so all subexpressions are sequenced before the result. 13217 SequencedSubexpression Sequenced(*this); 13218 13219 if (!CCE->isListInitialization()) 13220 return VisitExpr(CCE); 13221 13222 // In C++11, list initializations are sequenced. 13223 SmallVector<SequenceTree::Seq, 32> Elts; 13224 SequenceTree::Seq Parent = Region; 13225 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13226 E = CCE->arg_end(); 13227 I != E; ++I) { 13228 Region = Tree.allocate(Parent); 13229 Elts.push_back(Region); 13230 Visit(*I); 13231 } 13232 13233 // Forget that the initializers are sequenced. 13234 Region = Parent; 13235 for (unsigned I = 0; I < Elts.size(); ++I) 13236 Tree.merge(Elts[I]); 13237 } 13238 13239 void VisitInitListExpr(const InitListExpr *ILE) { 13240 if (!SemaRef.getLangOpts().CPlusPlus11) 13241 return VisitExpr(ILE); 13242 13243 // In C++11, list initializations are sequenced. 13244 SmallVector<SequenceTree::Seq, 32> Elts; 13245 SequenceTree::Seq Parent = Region; 13246 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13247 const Expr *E = ILE->getInit(I); 13248 if (!E) 13249 continue; 13250 Region = Tree.allocate(Parent); 13251 Elts.push_back(Region); 13252 Visit(E); 13253 } 13254 13255 // Forget that the initializers are sequenced. 13256 Region = Parent; 13257 for (unsigned I = 0; I < Elts.size(); ++I) 13258 Tree.merge(Elts[I]); 13259 } 13260 }; 13261 13262 } // namespace 13263 13264 void Sema::CheckUnsequencedOperations(const Expr *E) { 13265 SmallVector<const Expr *, 8> WorkList; 13266 WorkList.push_back(E); 13267 while (!WorkList.empty()) { 13268 const Expr *Item = WorkList.pop_back_val(); 13269 SequenceChecker(*this, Item, WorkList); 13270 } 13271 } 13272 13273 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13274 bool IsConstexpr) { 13275 llvm::SaveAndRestore<bool> ConstantContext( 13276 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13277 CheckImplicitConversions(E, CheckLoc); 13278 if (!E->isInstantiationDependent()) 13279 CheckUnsequencedOperations(E); 13280 if (!IsConstexpr && !E->isValueDependent()) 13281 CheckForIntOverflow(E); 13282 DiagnoseMisalignedMembers(); 13283 } 13284 13285 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13286 FieldDecl *BitField, 13287 Expr *Init) { 13288 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13289 } 13290 13291 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13292 SourceLocation Loc) { 13293 if (!PType->isVariablyModifiedType()) 13294 return; 13295 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13296 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13297 return; 13298 } 13299 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13300 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13301 return; 13302 } 13303 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13304 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13305 return; 13306 } 13307 13308 const ArrayType *AT = S.Context.getAsArrayType(PType); 13309 if (!AT) 13310 return; 13311 13312 if (AT->getSizeModifier() != ArrayType::Star) { 13313 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13314 return; 13315 } 13316 13317 S.Diag(Loc, diag::err_array_star_in_function_definition); 13318 } 13319 13320 /// CheckParmsForFunctionDef - Check that the parameters of the given 13321 /// function are appropriate for the definition of a function. This 13322 /// takes care of any checks that cannot be performed on the 13323 /// declaration itself, e.g., that the types of each of the function 13324 /// parameters are complete. 13325 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13326 bool CheckParameterNames) { 13327 bool HasInvalidParm = false; 13328 for (ParmVarDecl *Param : Parameters) { 13329 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13330 // function declarator that is part of a function definition of 13331 // that function shall not have incomplete type. 13332 // 13333 // This is also C++ [dcl.fct]p6. 13334 if (!Param->isInvalidDecl() && 13335 RequireCompleteType(Param->getLocation(), Param->getType(), 13336 diag::err_typecheck_decl_incomplete_type)) { 13337 Param->setInvalidDecl(); 13338 HasInvalidParm = true; 13339 } 13340 13341 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13342 // declaration of each parameter shall include an identifier. 13343 if (CheckParameterNames && 13344 Param->getIdentifier() == nullptr && 13345 !Param->isImplicit() && 13346 !getLangOpts().CPlusPlus) 13347 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13348 13349 // C99 6.7.5.3p12: 13350 // If the function declarator is not part of a definition of that 13351 // function, parameters may have incomplete type and may use the [*] 13352 // notation in their sequences of declarator specifiers to specify 13353 // variable length array types. 13354 QualType PType = Param->getOriginalType(); 13355 // FIXME: This diagnostic should point the '[*]' if source-location 13356 // information is added for it. 13357 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13358 13359 // If the parameter is a c++ class type and it has to be destructed in the 13360 // callee function, declare the destructor so that it can be called by the 13361 // callee function. Do not perform any direct access check on the dtor here. 13362 if (!Param->isInvalidDecl()) { 13363 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13364 if (!ClassDecl->isInvalidDecl() && 13365 !ClassDecl->hasIrrelevantDestructor() && 13366 !ClassDecl->isDependentContext() && 13367 ClassDecl->isParamDestroyedInCallee()) { 13368 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13369 MarkFunctionReferenced(Param->getLocation(), Destructor); 13370 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13371 } 13372 } 13373 } 13374 13375 // Parameters with the pass_object_size attribute only need to be marked 13376 // constant at function definitions. Because we lack information about 13377 // whether we're on a declaration or definition when we're instantiating the 13378 // attribute, we need to check for constness here. 13379 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13380 if (!Param->getType().isConstQualified()) 13381 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13382 << Attr->getSpelling() << 1; 13383 13384 // Check for parameter names shadowing fields from the class. 13385 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13386 // The owning context for the parameter should be the function, but we 13387 // want to see if this function's declaration context is a record. 13388 DeclContext *DC = Param->getDeclContext(); 13389 if (DC && DC->isFunctionOrMethod()) { 13390 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13391 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13392 RD, /*DeclIsField*/ false); 13393 } 13394 } 13395 } 13396 13397 return HasInvalidParm; 13398 } 13399 13400 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 13401 /// or MemberExpr. 13402 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 13403 ASTContext &Context) { 13404 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 13405 return Context.getDeclAlign(DRE->getDecl()); 13406 13407 if (const auto *ME = dyn_cast<MemberExpr>(E)) 13408 return Context.getDeclAlign(ME->getMemberDecl()); 13409 13410 return TypeAlign; 13411 } 13412 13413 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13414 /// pointer cast increases the alignment requirements. 13415 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13416 // This is actually a lot of work to potentially be doing on every 13417 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13418 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13419 return; 13420 13421 // Ignore dependent types. 13422 if (T->isDependentType() || Op->getType()->isDependentType()) 13423 return; 13424 13425 // Require that the destination be a pointer type. 13426 const PointerType *DestPtr = T->getAs<PointerType>(); 13427 if (!DestPtr) return; 13428 13429 // If the destination has alignment 1, we're done. 13430 QualType DestPointee = DestPtr->getPointeeType(); 13431 if (DestPointee->isIncompleteType()) return; 13432 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13433 if (DestAlign.isOne()) return; 13434 13435 // Require that the source be a pointer type. 13436 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13437 if (!SrcPtr) return; 13438 QualType SrcPointee = SrcPtr->getPointeeType(); 13439 13440 // Whitelist casts from cv void*. We already implicitly 13441 // whitelisted casts to cv void*, since they have alignment 1. 13442 // Also whitelist casts involving incomplete types, which implicitly 13443 // includes 'void'. 13444 if (SrcPointee->isIncompleteType()) return; 13445 13446 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 13447 13448 if (auto *CE = dyn_cast<CastExpr>(Op)) { 13449 if (CE->getCastKind() == CK_ArrayToPointerDecay) 13450 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 13451 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 13452 if (UO->getOpcode() == UO_AddrOf) 13453 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 13454 } 13455 13456 if (SrcAlign >= DestAlign) return; 13457 13458 Diag(TRange.getBegin(), diag::warn_cast_align) 13459 << Op->getType() << T 13460 << static_cast<unsigned>(SrcAlign.getQuantity()) 13461 << static_cast<unsigned>(DestAlign.getQuantity()) 13462 << TRange << Op->getSourceRange(); 13463 } 13464 13465 /// Check whether this array fits the idiom of a size-one tail padded 13466 /// array member of a struct. 13467 /// 13468 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13469 /// commonly used to emulate flexible arrays in C89 code. 13470 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13471 const NamedDecl *ND) { 13472 if (Size != 1 || !ND) return false; 13473 13474 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13475 if (!FD) return false; 13476 13477 // Don't consider sizes resulting from macro expansions or template argument 13478 // substitution to form C89 tail-padded arrays. 13479 13480 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13481 while (TInfo) { 13482 TypeLoc TL = TInfo->getTypeLoc(); 13483 // Look through typedefs. 13484 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13485 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13486 TInfo = TDL->getTypeSourceInfo(); 13487 continue; 13488 } 13489 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13490 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13491 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13492 return false; 13493 } 13494 break; 13495 } 13496 13497 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13498 if (!RD) return false; 13499 if (RD->isUnion()) return false; 13500 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13501 if (!CRD->isStandardLayout()) return false; 13502 } 13503 13504 // See if this is the last field decl in the record. 13505 const Decl *D = FD; 13506 while ((D = D->getNextDeclInContext())) 13507 if (isa<FieldDecl>(D)) 13508 return false; 13509 return true; 13510 } 13511 13512 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13513 const ArraySubscriptExpr *ASE, 13514 bool AllowOnePastEnd, bool IndexNegated) { 13515 // Already diagnosed by the constant evaluator. 13516 if (isConstantEvaluated()) 13517 return; 13518 13519 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13520 if (IndexExpr->isValueDependent()) 13521 return; 13522 13523 const Type *EffectiveType = 13524 BaseExpr->getType()->getPointeeOrArrayElementType(); 13525 BaseExpr = BaseExpr->IgnoreParenCasts(); 13526 const ConstantArrayType *ArrayTy = 13527 Context.getAsConstantArrayType(BaseExpr->getType()); 13528 13529 if (!ArrayTy) 13530 return; 13531 13532 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13533 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13534 return; 13535 13536 Expr::EvalResult Result; 13537 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13538 return; 13539 13540 llvm::APSInt index = Result.Val.getInt(); 13541 if (IndexNegated) 13542 index = -index; 13543 13544 const NamedDecl *ND = nullptr; 13545 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13546 ND = DRE->getDecl(); 13547 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13548 ND = ME->getMemberDecl(); 13549 13550 if (index.isUnsigned() || !index.isNegative()) { 13551 // It is possible that the type of the base expression after 13552 // IgnoreParenCasts is incomplete, even though the type of the base 13553 // expression before IgnoreParenCasts is complete (see PR39746 for an 13554 // example). In this case we have no information about whether the array 13555 // access exceeds the array bounds. However we can still diagnose an array 13556 // access which precedes the array bounds. 13557 if (BaseType->isIncompleteType()) 13558 return; 13559 13560 llvm::APInt size = ArrayTy->getSize(); 13561 if (!size.isStrictlyPositive()) 13562 return; 13563 13564 if (BaseType != EffectiveType) { 13565 // Make sure we're comparing apples to apples when comparing index to size 13566 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13567 uint64_t array_typesize = Context.getTypeSize(BaseType); 13568 // Handle ptrarith_typesize being zero, such as when casting to void* 13569 if (!ptrarith_typesize) ptrarith_typesize = 1; 13570 if (ptrarith_typesize != array_typesize) { 13571 // There's a cast to a different size type involved 13572 uint64_t ratio = array_typesize / ptrarith_typesize; 13573 // TODO: Be smarter about handling cases where array_typesize is not a 13574 // multiple of ptrarith_typesize 13575 if (ptrarith_typesize * ratio == array_typesize) 13576 size *= llvm::APInt(size.getBitWidth(), ratio); 13577 } 13578 } 13579 13580 if (size.getBitWidth() > index.getBitWidth()) 13581 index = index.zext(size.getBitWidth()); 13582 else if (size.getBitWidth() < index.getBitWidth()) 13583 size = size.zext(index.getBitWidth()); 13584 13585 // For array subscripting the index must be less than size, but for pointer 13586 // arithmetic also allow the index (offset) to be equal to size since 13587 // computing the next address after the end of the array is legal and 13588 // commonly done e.g. in C++ iterators and range-based for loops. 13589 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13590 return; 13591 13592 // Also don't warn for arrays of size 1 which are members of some 13593 // structure. These are often used to approximate flexible arrays in C89 13594 // code. 13595 if (IsTailPaddedMemberArray(*this, size, ND)) 13596 return; 13597 13598 // Suppress the warning if the subscript expression (as identified by the 13599 // ']' location) and the index expression are both from macro expansions 13600 // within a system header. 13601 if (ASE) { 13602 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13603 ASE->getRBracketLoc()); 13604 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13605 SourceLocation IndexLoc = 13606 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13607 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13608 return; 13609 } 13610 } 13611 13612 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13613 if (ASE) 13614 DiagID = diag::warn_array_index_exceeds_bounds; 13615 13616 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13617 PDiag(DiagID) << index.toString(10, true) 13618 << size.toString(10, true) 13619 << (unsigned)size.getLimitedValue(~0U) 13620 << IndexExpr->getSourceRange()); 13621 } else { 13622 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13623 if (!ASE) { 13624 DiagID = diag::warn_ptr_arith_precedes_bounds; 13625 if (index.isNegative()) index = -index; 13626 } 13627 13628 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13629 PDiag(DiagID) << index.toString(10, true) 13630 << IndexExpr->getSourceRange()); 13631 } 13632 13633 if (!ND) { 13634 // Try harder to find a NamedDecl to point at in the note. 13635 while (const ArraySubscriptExpr *ASE = 13636 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13637 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13638 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13639 ND = DRE->getDecl(); 13640 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13641 ND = ME->getMemberDecl(); 13642 } 13643 13644 if (ND) 13645 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13646 PDiag(diag::note_array_declared_here) 13647 << ND->getDeclName()); 13648 } 13649 13650 void Sema::CheckArrayAccess(const Expr *expr) { 13651 int AllowOnePastEnd = 0; 13652 while (expr) { 13653 expr = expr->IgnoreParenImpCasts(); 13654 switch (expr->getStmtClass()) { 13655 case Stmt::ArraySubscriptExprClass: { 13656 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13657 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13658 AllowOnePastEnd > 0); 13659 expr = ASE->getBase(); 13660 break; 13661 } 13662 case Stmt::MemberExprClass: { 13663 expr = cast<MemberExpr>(expr)->getBase(); 13664 break; 13665 } 13666 case Stmt::OMPArraySectionExprClass: { 13667 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13668 if (ASE->getLowerBound()) 13669 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13670 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13671 return; 13672 } 13673 case Stmt::UnaryOperatorClass: { 13674 // Only unwrap the * and & unary operators 13675 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13676 expr = UO->getSubExpr(); 13677 switch (UO->getOpcode()) { 13678 case UO_AddrOf: 13679 AllowOnePastEnd++; 13680 break; 13681 case UO_Deref: 13682 AllowOnePastEnd--; 13683 break; 13684 default: 13685 return; 13686 } 13687 break; 13688 } 13689 case Stmt::ConditionalOperatorClass: { 13690 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13691 if (const Expr *lhs = cond->getLHS()) 13692 CheckArrayAccess(lhs); 13693 if (const Expr *rhs = cond->getRHS()) 13694 CheckArrayAccess(rhs); 13695 return; 13696 } 13697 case Stmt::CXXOperatorCallExprClass: { 13698 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13699 for (const auto *Arg : OCE->arguments()) 13700 CheckArrayAccess(Arg); 13701 return; 13702 } 13703 default: 13704 return; 13705 } 13706 } 13707 } 13708 13709 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13710 13711 namespace { 13712 13713 struct RetainCycleOwner { 13714 VarDecl *Variable = nullptr; 13715 SourceRange Range; 13716 SourceLocation Loc; 13717 bool Indirect = false; 13718 13719 RetainCycleOwner() = default; 13720 13721 void setLocsFrom(Expr *e) { 13722 Loc = e->getExprLoc(); 13723 Range = e->getSourceRange(); 13724 } 13725 }; 13726 13727 } // namespace 13728 13729 /// Consider whether capturing the given variable can possibly lead to 13730 /// a retain cycle. 13731 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13732 // In ARC, it's captured strongly iff the variable has __strong 13733 // lifetime. In MRR, it's captured strongly if the variable is 13734 // __block and has an appropriate type. 13735 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13736 return false; 13737 13738 owner.Variable = var; 13739 if (ref) 13740 owner.setLocsFrom(ref); 13741 return true; 13742 } 13743 13744 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13745 while (true) { 13746 e = e->IgnoreParens(); 13747 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13748 switch (cast->getCastKind()) { 13749 case CK_BitCast: 13750 case CK_LValueBitCast: 13751 case CK_LValueToRValue: 13752 case CK_ARCReclaimReturnedObject: 13753 e = cast->getSubExpr(); 13754 continue; 13755 13756 default: 13757 return false; 13758 } 13759 } 13760 13761 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13762 ObjCIvarDecl *ivar = ref->getDecl(); 13763 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13764 return false; 13765 13766 // Try to find a retain cycle in the base. 13767 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13768 return false; 13769 13770 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13771 owner.Indirect = true; 13772 return true; 13773 } 13774 13775 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13776 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13777 if (!var) return false; 13778 return considerVariable(var, ref, owner); 13779 } 13780 13781 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13782 if (member->isArrow()) return false; 13783 13784 // Don't count this as an indirect ownership. 13785 e = member->getBase(); 13786 continue; 13787 } 13788 13789 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13790 // Only pay attention to pseudo-objects on property references. 13791 ObjCPropertyRefExpr *pre 13792 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13793 ->IgnoreParens()); 13794 if (!pre) return false; 13795 if (pre->isImplicitProperty()) return false; 13796 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13797 if (!property->isRetaining() && 13798 !(property->getPropertyIvarDecl() && 13799 property->getPropertyIvarDecl()->getType() 13800 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13801 return false; 13802 13803 owner.Indirect = true; 13804 if (pre->isSuperReceiver()) { 13805 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13806 if (!owner.Variable) 13807 return false; 13808 owner.Loc = pre->getLocation(); 13809 owner.Range = pre->getSourceRange(); 13810 return true; 13811 } 13812 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13813 ->getSourceExpr()); 13814 continue; 13815 } 13816 13817 // Array ivars? 13818 13819 return false; 13820 } 13821 } 13822 13823 namespace { 13824 13825 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13826 ASTContext &Context; 13827 VarDecl *Variable; 13828 Expr *Capturer = nullptr; 13829 bool VarWillBeReased = false; 13830 13831 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13832 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13833 Context(Context), Variable(variable) {} 13834 13835 void VisitDeclRefExpr(DeclRefExpr *ref) { 13836 if (ref->getDecl() == Variable && !Capturer) 13837 Capturer = ref; 13838 } 13839 13840 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13841 if (Capturer) return; 13842 Visit(ref->getBase()); 13843 if (Capturer && ref->isFreeIvar()) 13844 Capturer = ref; 13845 } 13846 13847 void VisitBlockExpr(BlockExpr *block) { 13848 // Look inside nested blocks 13849 if (block->getBlockDecl()->capturesVariable(Variable)) 13850 Visit(block->getBlockDecl()->getBody()); 13851 } 13852 13853 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13854 if (Capturer) return; 13855 if (OVE->getSourceExpr()) 13856 Visit(OVE->getSourceExpr()); 13857 } 13858 13859 void VisitBinaryOperator(BinaryOperator *BinOp) { 13860 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13861 return; 13862 Expr *LHS = BinOp->getLHS(); 13863 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13864 if (DRE->getDecl() != Variable) 13865 return; 13866 if (Expr *RHS = BinOp->getRHS()) { 13867 RHS = RHS->IgnoreParenCasts(); 13868 llvm::APSInt Value; 13869 VarWillBeReased = 13870 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13871 } 13872 } 13873 } 13874 }; 13875 13876 } // namespace 13877 13878 /// Check whether the given argument is a block which captures a 13879 /// variable. 13880 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13881 assert(owner.Variable && owner.Loc.isValid()); 13882 13883 e = e->IgnoreParenCasts(); 13884 13885 // Look through [^{...} copy] and Block_copy(^{...}). 13886 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13887 Selector Cmd = ME->getSelector(); 13888 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13889 e = ME->getInstanceReceiver(); 13890 if (!e) 13891 return nullptr; 13892 e = e->IgnoreParenCasts(); 13893 } 13894 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13895 if (CE->getNumArgs() == 1) { 13896 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13897 if (Fn) { 13898 const IdentifierInfo *FnI = Fn->getIdentifier(); 13899 if (FnI && FnI->isStr("_Block_copy")) { 13900 e = CE->getArg(0)->IgnoreParenCasts(); 13901 } 13902 } 13903 } 13904 } 13905 13906 BlockExpr *block = dyn_cast<BlockExpr>(e); 13907 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13908 return nullptr; 13909 13910 FindCaptureVisitor visitor(S.Context, owner.Variable); 13911 visitor.Visit(block->getBlockDecl()->getBody()); 13912 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13913 } 13914 13915 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13916 RetainCycleOwner &owner) { 13917 assert(capturer); 13918 assert(owner.Variable && owner.Loc.isValid()); 13919 13920 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13921 << owner.Variable << capturer->getSourceRange(); 13922 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13923 << owner.Indirect << owner.Range; 13924 } 13925 13926 /// Check for a keyword selector that starts with the word 'add' or 13927 /// 'set'. 13928 static bool isSetterLikeSelector(Selector sel) { 13929 if (sel.isUnarySelector()) return false; 13930 13931 StringRef str = sel.getNameForSlot(0); 13932 while (!str.empty() && str.front() == '_') str = str.substr(1); 13933 if (str.startswith("set")) 13934 str = str.substr(3); 13935 else if (str.startswith("add")) { 13936 // Specially whitelist 'addOperationWithBlock:'. 13937 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13938 return false; 13939 str = str.substr(3); 13940 } 13941 else 13942 return false; 13943 13944 if (str.empty()) return true; 13945 return !isLowercase(str.front()); 13946 } 13947 13948 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13949 ObjCMessageExpr *Message) { 13950 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13951 Message->getReceiverInterface(), 13952 NSAPI::ClassId_NSMutableArray); 13953 if (!IsMutableArray) { 13954 return None; 13955 } 13956 13957 Selector Sel = Message->getSelector(); 13958 13959 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13960 S.NSAPIObj->getNSArrayMethodKind(Sel); 13961 if (!MKOpt) { 13962 return None; 13963 } 13964 13965 NSAPI::NSArrayMethodKind MK = *MKOpt; 13966 13967 switch (MK) { 13968 case NSAPI::NSMutableArr_addObject: 13969 case NSAPI::NSMutableArr_insertObjectAtIndex: 13970 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13971 return 0; 13972 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13973 return 1; 13974 13975 default: 13976 return None; 13977 } 13978 13979 return None; 13980 } 13981 13982 static 13983 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13984 ObjCMessageExpr *Message) { 13985 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13986 Message->getReceiverInterface(), 13987 NSAPI::ClassId_NSMutableDictionary); 13988 if (!IsMutableDictionary) { 13989 return None; 13990 } 13991 13992 Selector Sel = Message->getSelector(); 13993 13994 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13995 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13996 if (!MKOpt) { 13997 return None; 13998 } 13999 14000 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14001 14002 switch (MK) { 14003 case NSAPI::NSMutableDict_setObjectForKey: 14004 case NSAPI::NSMutableDict_setValueForKey: 14005 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14006 return 0; 14007 14008 default: 14009 return None; 14010 } 14011 14012 return None; 14013 } 14014 14015 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14016 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14017 Message->getReceiverInterface(), 14018 NSAPI::ClassId_NSMutableSet); 14019 14020 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14021 Message->getReceiverInterface(), 14022 NSAPI::ClassId_NSMutableOrderedSet); 14023 if (!IsMutableSet && !IsMutableOrderedSet) { 14024 return None; 14025 } 14026 14027 Selector Sel = Message->getSelector(); 14028 14029 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14030 if (!MKOpt) { 14031 return None; 14032 } 14033 14034 NSAPI::NSSetMethodKind MK = *MKOpt; 14035 14036 switch (MK) { 14037 case NSAPI::NSMutableSet_addObject: 14038 case NSAPI::NSOrderedSet_setObjectAtIndex: 14039 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14040 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14041 return 0; 14042 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14043 return 1; 14044 } 14045 14046 return None; 14047 } 14048 14049 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14050 if (!Message->isInstanceMessage()) { 14051 return; 14052 } 14053 14054 Optional<int> ArgOpt; 14055 14056 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14057 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14058 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14059 return; 14060 } 14061 14062 int ArgIndex = *ArgOpt; 14063 14064 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14065 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14066 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14067 } 14068 14069 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14070 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14071 if (ArgRE->isObjCSelfExpr()) { 14072 Diag(Message->getSourceRange().getBegin(), 14073 diag::warn_objc_circular_container) 14074 << ArgRE->getDecl() << StringRef("'super'"); 14075 } 14076 } 14077 } else { 14078 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14079 14080 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14081 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14082 } 14083 14084 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14085 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14086 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14087 ValueDecl *Decl = ReceiverRE->getDecl(); 14088 Diag(Message->getSourceRange().getBegin(), 14089 diag::warn_objc_circular_container) 14090 << Decl << Decl; 14091 if (!ArgRE->isObjCSelfExpr()) { 14092 Diag(Decl->getLocation(), 14093 diag::note_objc_circular_container_declared_here) 14094 << Decl; 14095 } 14096 } 14097 } 14098 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14099 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14100 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14101 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14102 Diag(Message->getSourceRange().getBegin(), 14103 diag::warn_objc_circular_container) 14104 << Decl << Decl; 14105 Diag(Decl->getLocation(), 14106 diag::note_objc_circular_container_declared_here) 14107 << Decl; 14108 } 14109 } 14110 } 14111 } 14112 } 14113 14114 /// Check a message send to see if it's likely to cause a retain cycle. 14115 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14116 // Only check instance methods whose selector looks like a setter. 14117 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14118 return; 14119 14120 // Try to find a variable that the receiver is strongly owned by. 14121 RetainCycleOwner owner; 14122 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14123 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14124 return; 14125 } else { 14126 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14127 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14128 owner.Loc = msg->getSuperLoc(); 14129 owner.Range = msg->getSuperLoc(); 14130 } 14131 14132 // Check whether the receiver is captured by any of the arguments. 14133 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14134 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14135 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14136 // noescape blocks should not be retained by the method. 14137 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14138 continue; 14139 return diagnoseRetainCycle(*this, capturer, owner); 14140 } 14141 } 14142 } 14143 14144 /// Check a property assign to see if it's likely to cause a retain cycle. 14145 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14146 RetainCycleOwner owner; 14147 if (!findRetainCycleOwner(*this, receiver, owner)) 14148 return; 14149 14150 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14151 diagnoseRetainCycle(*this, capturer, owner); 14152 } 14153 14154 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14155 RetainCycleOwner Owner; 14156 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14157 return; 14158 14159 // Because we don't have an expression for the variable, we have to set the 14160 // location explicitly here. 14161 Owner.Loc = Var->getLocation(); 14162 Owner.Range = Var->getSourceRange(); 14163 14164 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14165 diagnoseRetainCycle(*this, Capturer, Owner); 14166 } 14167 14168 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14169 Expr *RHS, bool isProperty) { 14170 // Check if RHS is an Objective-C object literal, which also can get 14171 // immediately zapped in a weak reference. Note that we explicitly 14172 // allow ObjCStringLiterals, since those are designed to never really die. 14173 RHS = RHS->IgnoreParenImpCasts(); 14174 14175 // This enum needs to match with the 'select' in 14176 // warn_objc_arc_literal_assign (off-by-1). 14177 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14178 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14179 return false; 14180 14181 S.Diag(Loc, diag::warn_arc_literal_assign) 14182 << (unsigned) Kind 14183 << (isProperty ? 0 : 1) 14184 << RHS->getSourceRange(); 14185 14186 return true; 14187 } 14188 14189 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14190 Qualifiers::ObjCLifetime LT, 14191 Expr *RHS, bool isProperty) { 14192 // Strip off any implicit cast added to get to the one ARC-specific. 14193 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14194 if (cast->getCastKind() == CK_ARCConsumeObject) { 14195 S.Diag(Loc, diag::warn_arc_retained_assign) 14196 << (LT == Qualifiers::OCL_ExplicitNone) 14197 << (isProperty ? 0 : 1) 14198 << RHS->getSourceRange(); 14199 return true; 14200 } 14201 RHS = cast->getSubExpr(); 14202 } 14203 14204 if (LT == Qualifiers::OCL_Weak && 14205 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14206 return true; 14207 14208 return false; 14209 } 14210 14211 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14212 QualType LHS, Expr *RHS) { 14213 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14214 14215 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14216 return false; 14217 14218 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14219 return true; 14220 14221 return false; 14222 } 14223 14224 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14225 Expr *LHS, Expr *RHS) { 14226 QualType LHSType; 14227 // PropertyRef on LHS type need be directly obtained from 14228 // its declaration as it has a PseudoType. 14229 ObjCPropertyRefExpr *PRE 14230 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14231 if (PRE && !PRE->isImplicitProperty()) { 14232 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14233 if (PD) 14234 LHSType = PD->getType(); 14235 } 14236 14237 if (LHSType.isNull()) 14238 LHSType = LHS->getType(); 14239 14240 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14241 14242 if (LT == Qualifiers::OCL_Weak) { 14243 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14244 getCurFunction()->markSafeWeakUse(LHS); 14245 } 14246 14247 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14248 return; 14249 14250 // FIXME. Check for other life times. 14251 if (LT != Qualifiers::OCL_None) 14252 return; 14253 14254 if (PRE) { 14255 if (PRE->isImplicitProperty()) 14256 return; 14257 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14258 if (!PD) 14259 return; 14260 14261 unsigned Attributes = PD->getPropertyAttributes(); 14262 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 14263 // when 'assign' attribute was not explicitly specified 14264 // by user, ignore it and rely on property type itself 14265 // for lifetime info. 14266 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14267 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 14268 LHSType->isObjCRetainableType()) 14269 return; 14270 14271 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14272 if (cast->getCastKind() == CK_ARCConsumeObject) { 14273 Diag(Loc, diag::warn_arc_retained_property_assign) 14274 << RHS->getSourceRange(); 14275 return; 14276 } 14277 RHS = cast->getSubExpr(); 14278 } 14279 } 14280 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 14281 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14282 return; 14283 } 14284 } 14285 } 14286 14287 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14288 14289 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14290 SourceLocation StmtLoc, 14291 const NullStmt *Body) { 14292 // Do not warn if the body is a macro that expands to nothing, e.g: 14293 // 14294 // #define CALL(x) 14295 // if (condition) 14296 // CALL(0); 14297 if (Body->hasLeadingEmptyMacro()) 14298 return false; 14299 14300 // Get line numbers of statement and body. 14301 bool StmtLineInvalid; 14302 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14303 &StmtLineInvalid); 14304 if (StmtLineInvalid) 14305 return false; 14306 14307 bool BodyLineInvalid; 14308 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14309 &BodyLineInvalid); 14310 if (BodyLineInvalid) 14311 return false; 14312 14313 // Warn if null statement and body are on the same line. 14314 if (StmtLine != BodyLine) 14315 return false; 14316 14317 return true; 14318 } 14319 14320 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14321 const Stmt *Body, 14322 unsigned DiagID) { 14323 // Since this is a syntactic check, don't emit diagnostic for template 14324 // instantiations, this just adds noise. 14325 if (CurrentInstantiationScope) 14326 return; 14327 14328 // The body should be a null statement. 14329 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14330 if (!NBody) 14331 return; 14332 14333 // Do the usual checks. 14334 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14335 return; 14336 14337 Diag(NBody->getSemiLoc(), DiagID); 14338 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14339 } 14340 14341 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14342 const Stmt *PossibleBody) { 14343 assert(!CurrentInstantiationScope); // Ensured by caller 14344 14345 SourceLocation StmtLoc; 14346 const Stmt *Body; 14347 unsigned DiagID; 14348 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14349 StmtLoc = FS->getRParenLoc(); 14350 Body = FS->getBody(); 14351 DiagID = diag::warn_empty_for_body; 14352 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14353 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14354 Body = WS->getBody(); 14355 DiagID = diag::warn_empty_while_body; 14356 } else 14357 return; // Neither `for' nor `while'. 14358 14359 // The body should be a null statement. 14360 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14361 if (!NBody) 14362 return; 14363 14364 // Skip expensive checks if diagnostic is disabled. 14365 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14366 return; 14367 14368 // Do the usual checks. 14369 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14370 return; 14371 14372 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14373 // noise level low, emit diagnostics only if for/while is followed by a 14374 // CompoundStmt, e.g.: 14375 // for (int i = 0; i < n; i++); 14376 // { 14377 // a(i); 14378 // } 14379 // or if for/while is followed by a statement with more indentation 14380 // than for/while itself: 14381 // for (int i = 0; i < n; i++); 14382 // a(i); 14383 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14384 if (!ProbableTypo) { 14385 bool BodyColInvalid; 14386 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14387 PossibleBody->getBeginLoc(), &BodyColInvalid); 14388 if (BodyColInvalid) 14389 return; 14390 14391 bool StmtColInvalid; 14392 unsigned StmtCol = 14393 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14394 if (StmtColInvalid) 14395 return; 14396 14397 if (BodyCol > StmtCol) 14398 ProbableTypo = true; 14399 } 14400 14401 if (ProbableTypo) { 14402 Diag(NBody->getSemiLoc(), DiagID); 14403 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14404 } 14405 } 14406 14407 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14408 14409 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14410 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14411 SourceLocation OpLoc) { 14412 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14413 return; 14414 14415 if (inTemplateInstantiation()) 14416 return; 14417 14418 // Strip parens and casts away. 14419 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14420 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14421 14422 // Check for a call expression 14423 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14424 if (!CE || CE->getNumArgs() != 1) 14425 return; 14426 14427 // Check for a call to std::move 14428 if (!CE->isCallToStdMove()) 14429 return; 14430 14431 // Get argument from std::move 14432 RHSExpr = CE->getArg(0); 14433 14434 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14435 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14436 14437 // Two DeclRefExpr's, check that the decls are the same. 14438 if (LHSDeclRef && RHSDeclRef) { 14439 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14440 return; 14441 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14442 RHSDeclRef->getDecl()->getCanonicalDecl()) 14443 return; 14444 14445 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14446 << LHSExpr->getSourceRange() 14447 << RHSExpr->getSourceRange(); 14448 return; 14449 } 14450 14451 // Member variables require a different approach to check for self moves. 14452 // MemberExpr's are the same if every nested MemberExpr refers to the same 14453 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14454 // the base Expr's are CXXThisExpr's. 14455 const Expr *LHSBase = LHSExpr; 14456 const Expr *RHSBase = RHSExpr; 14457 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14458 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14459 if (!LHSME || !RHSME) 14460 return; 14461 14462 while (LHSME && RHSME) { 14463 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14464 RHSME->getMemberDecl()->getCanonicalDecl()) 14465 return; 14466 14467 LHSBase = LHSME->getBase(); 14468 RHSBase = RHSME->getBase(); 14469 LHSME = dyn_cast<MemberExpr>(LHSBase); 14470 RHSME = dyn_cast<MemberExpr>(RHSBase); 14471 } 14472 14473 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14474 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14475 if (LHSDeclRef && RHSDeclRef) { 14476 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14477 return; 14478 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14479 RHSDeclRef->getDecl()->getCanonicalDecl()) 14480 return; 14481 14482 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14483 << LHSExpr->getSourceRange() 14484 << RHSExpr->getSourceRange(); 14485 return; 14486 } 14487 14488 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14489 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14490 << LHSExpr->getSourceRange() 14491 << RHSExpr->getSourceRange(); 14492 } 14493 14494 //===--- Layout compatibility ----------------------------------------------// 14495 14496 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14497 14498 /// Check if two enumeration types are layout-compatible. 14499 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14500 // C++11 [dcl.enum] p8: 14501 // Two enumeration types are layout-compatible if they have the same 14502 // underlying type. 14503 return ED1->isComplete() && ED2->isComplete() && 14504 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14505 } 14506 14507 /// Check if two fields are layout-compatible. 14508 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14509 FieldDecl *Field2) { 14510 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14511 return false; 14512 14513 if (Field1->isBitField() != Field2->isBitField()) 14514 return false; 14515 14516 if (Field1->isBitField()) { 14517 // Make sure that the bit-fields are the same length. 14518 unsigned Bits1 = Field1->getBitWidthValue(C); 14519 unsigned Bits2 = Field2->getBitWidthValue(C); 14520 14521 if (Bits1 != Bits2) 14522 return false; 14523 } 14524 14525 return true; 14526 } 14527 14528 /// Check if two standard-layout structs are layout-compatible. 14529 /// (C++11 [class.mem] p17) 14530 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14531 RecordDecl *RD2) { 14532 // If both records are C++ classes, check that base classes match. 14533 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14534 // If one of records is a CXXRecordDecl we are in C++ mode, 14535 // thus the other one is a CXXRecordDecl, too. 14536 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14537 // Check number of base classes. 14538 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14539 return false; 14540 14541 // Check the base classes. 14542 for (CXXRecordDecl::base_class_const_iterator 14543 Base1 = D1CXX->bases_begin(), 14544 BaseEnd1 = D1CXX->bases_end(), 14545 Base2 = D2CXX->bases_begin(); 14546 Base1 != BaseEnd1; 14547 ++Base1, ++Base2) { 14548 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14549 return false; 14550 } 14551 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14552 // If only RD2 is a C++ class, it should have zero base classes. 14553 if (D2CXX->getNumBases() > 0) 14554 return false; 14555 } 14556 14557 // Check the fields. 14558 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14559 Field2End = RD2->field_end(), 14560 Field1 = RD1->field_begin(), 14561 Field1End = RD1->field_end(); 14562 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14563 if (!isLayoutCompatible(C, *Field1, *Field2)) 14564 return false; 14565 } 14566 if (Field1 != Field1End || Field2 != Field2End) 14567 return false; 14568 14569 return true; 14570 } 14571 14572 /// Check if two standard-layout unions are layout-compatible. 14573 /// (C++11 [class.mem] p18) 14574 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14575 RecordDecl *RD2) { 14576 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14577 for (auto *Field2 : RD2->fields()) 14578 UnmatchedFields.insert(Field2); 14579 14580 for (auto *Field1 : RD1->fields()) { 14581 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14582 I = UnmatchedFields.begin(), 14583 E = UnmatchedFields.end(); 14584 14585 for ( ; I != E; ++I) { 14586 if (isLayoutCompatible(C, Field1, *I)) { 14587 bool Result = UnmatchedFields.erase(*I); 14588 (void) Result; 14589 assert(Result); 14590 break; 14591 } 14592 } 14593 if (I == E) 14594 return false; 14595 } 14596 14597 return UnmatchedFields.empty(); 14598 } 14599 14600 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14601 RecordDecl *RD2) { 14602 if (RD1->isUnion() != RD2->isUnion()) 14603 return false; 14604 14605 if (RD1->isUnion()) 14606 return isLayoutCompatibleUnion(C, RD1, RD2); 14607 else 14608 return isLayoutCompatibleStruct(C, RD1, RD2); 14609 } 14610 14611 /// Check if two types are layout-compatible in C++11 sense. 14612 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14613 if (T1.isNull() || T2.isNull()) 14614 return false; 14615 14616 // C++11 [basic.types] p11: 14617 // If two types T1 and T2 are the same type, then T1 and T2 are 14618 // layout-compatible types. 14619 if (C.hasSameType(T1, T2)) 14620 return true; 14621 14622 T1 = T1.getCanonicalType().getUnqualifiedType(); 14623 T2 = T2.getCanonicalType().getUnqualifiedType(); 14624 14625 const Type::TypeClass TC1 = T1->getTypeClass(); 14626 const Type::TypeClass TC2 = T2->getTypeClass(); 14627 14628 if (TC1 != TC2) 14629 return false; 14630 14631 if (TC1 == Type::Enum) { 14632 return isLayoutCompatible(C, 14633 cast<EnumType>(T1)->getDecl(), 14634 cast<EnumType>(T2)->getDecl()); 14635 } else if (TC1 == Type::Record) { 14636 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14637 return false; 14638 14639 return isLayoutCompatible(C, 14640 cast<RecordType>(T1)->getDecl(), 14641 cast<RecordType>(T2)->getDecl()); 14642 } 14643 14644 return false; 14645 } 14646 14647 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14648 14649 /// Given a type tag expression find the type tag itself. 14650 /// 14651 /// \param TypeExpr Type tag expression, as it appears in user's code. 14652 /// 14653 /// \param VD Declaration of an identifier that appears in a type tag. 14654 /// 14655 /// \param MagicValue Type tag magic value. 14656 /// 14657 /// \param isConstantEvaluated wether the evalaution should be performed in 14658 14659 /// constant context. 14660 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14661 const ValueDecl **VD, uint64_t *MagicValue, 14662 bool isConstantEvaluated) { 14663 while(true) { 14664 if (!TypeExpr) 14665 return false; 14666 14667 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14668 14669 switch (TypeExpr->getStmtClass()) { 14670 case Stmt::UnaryOperatorClass: { 14671 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14672 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14673 TypeExpr = UO->getSubExpr(); 14674 continue; 14675 } 14676 return false; 14677 } 14678 14679 case Stmt::DeclRefExprClass: { 14680 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14681 *VD = DRE->getDecl(); 14682 return true; 14683 } 14684 14685 case Stmt::IntegerLiteralClass: { 14686 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14687 llvm::APInt MagicValueAPInt = IL->getValue(); 14688 if (MagicValueAPInt.getActiveBits() <= 64) { 14689 *MagicValue = MagicValueAPInt.getZExtValue(); 14690 return true; 14691 } else 14692 return false; 14693 } 14694 14695 case Stmt::BinaryConditionalOperatorClass: 14696 case Stmt::ConditionalOperatorClass: { 14697 const AbstractConditionalOperator *ACO = 14698 cast<AbstractConditionalOperator>(TypeExpr); 14699 bool Result; 14700 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14701 isConstantEvaluated)) { 14702 if (Result) 14703 TypeExpr = ACO->getTrueExpr(); 14704 else 14705 TypeExpr = ACO->getFalseExpr(); 14706 continue; 14707 } 14708 return false; 14709 } 14710 14711 case Stmt::BinaryOperatorClass: { 14712 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14713 if (BO->getOpcode() == BO_Comma) { 14714 TypeExpr = BO->getRHS(); 14715 continue; 14716 } 14717 return false; 14718 } 14719 14720 default: 14721 return false; 14722 } 14723 } 14724 } 14725 14726 /// Retrieve the C type corresponding to type tag TypeExpr. 14727 /// 14728 /// \param TypeExpr Expression that specifies a type tag. 14729 /// 14730 /// \param MagicValues Registered magic values. 14731 /// 14732 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14733 /// kind. 14734 /// 14735 /// \param TypeInfo Information about the corresponding C type. 14736 /// 14737 /// \param isConstantEvaluated wether the evalaution should be performed in 14738 /// constant context. 14739 /// 14740 /// \returns true if the corresponding C type was found. 14741 static bool GetMatchingCType( 14742 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14743 const ASTContext &Ctx, 14744 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14745 *MagicValues, 14746 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14747 bool isConstantEvaluated) { 14748 FoundWrongKind = false; 14749 14750 // Variable declaration that has type_tag_for_datatype attribute. 14751 const ValueDecl *VD = nullptr; 14752 14753 uint64_t MagicValue; 14754 14755 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14756 return false; 14757 14758 if (VD) { 14759 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14760 if (I->getArgumentKind() != ArgumentKind) { 14761 FoundWrongKind = true; 14762 return false; 14763 } 14764 TypeInfo.Type = I->getMatchingCType(); 14765 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14766 TypeInfo.MustBeNull = I->getMustBeNull(); 14767 return true; 14768 } 14769 return false; 14770 } 14771 14772 if (!MagicValues) 14773 return false; 14774 14775 llvm::DenseMap<Sema::TypeTagMagicValue, 14776 Sema::TypeTagData>::const_iterator I = 14777 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14778 if (I == MagicValues->end()) 14779 return false; 14780 14781 TypeInfo = I->second; 14782 return true; 14783 } 14784 14785 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14786 uint64_t MagicValue, QualType Type, 14787 bool LayoutCompatible, 14788 bool MustBeNull) { 14789 if (!TypeTagForDatatypeMagicValues) 14790 TypeTagForDatatypeMagicValues.reset( 14791 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14792 14793 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14794 (*TypeTagForDatatypeMagicValues)[Magic] = 14795 TypeTagData(Type, LayoutCompatible, MustBeNull); 14796 } 14797 14798 static bool IsSameCharType(QualType T1, QualType T2) { 14799 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14800 if (!BT1) 14801 return false; 14802 14803 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14804 if (!BT2) 14805 return false; 14806 14807 BuiltinType::Kind T1Kind = BT1->getKind(); 14808 BuiltinType::Kind T2Kind = BT2->getKind(); 14809 14810 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14811 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14812 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14813 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14814 } 14815 14816 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14817 const ArrayRef<const Expr *> ExprArgs, 14818 SourceLocation CallSiteLoc) { 14819 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14820 bool IsPointerAttr = Attr->getIsPointer(); 14821 14822 // Retrieve the argument representing the 'type_tag'. 14823 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14824 if (TypeTagIdxAST >= ExprArgs.size()) { 14825 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14826 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14827 return; 14828 } 14829 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14830 bool FoundWrongKind; 14831 TypeTagData TypeInfo; 14832 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14833 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14834 TypeInfo, isConstantEvaluated())) { 14835 if (FoundWrongKind) 14836 Diag(TypeTagExpr->getExprLoc(), 14837 diag::warn_type_tag_for_datatype_wrong_kind) 14838 << TypeTagExpr->getSourceRange(); 14839 return; 14840 } 14841 14842 // Retrieve the argument representing the 'arg_idx'. 14843 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14844 if (ArgumentIdxAST >= ExprArgs.size()) { 14845 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14846 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14847 return; 14848 } 14849 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14850 if (IsPointerAttr) { 14851 // Skip implicit cast of pointer to `void *' (as a function argument). 14852 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14853 if (ICE->getType()->isVoidPointerType() && 14854 ICE->getCastKind() == CK_BitCast) 14855 ArgumentExpr = ICE->getSubExpr(); 14856 } 14857 QualType ArgumentType = ArgumentExpr->getType(); 14858 14859 // Passing a `void*' pointer shouldn't trigger a warning. 14860 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14861 return; 14862 14863 if (TypeInfo.MustBeNull) { 14864 // Type tag with matching void type requires a null pointer. 14865 if (!ArgumentExpr->isNullPointerConstant(Context, 14866 Expr::NPC_ValueDependentIsNotNull)) { 14867 Diag(ArgumentExpr->getExprLoc(), 14868 diag::warn_type_safety_null_pointer_required) 14869 << ArgumentKind->getName() 14870 << ArgumentExpr->getSourceRange() 14871 << TypeTagExpr->getSourceRange(); 14872 } 14873 return; 14874 } 14875 14876 QualType RequiredType = TypeInfo.Type; 14877 if (IsPointerAttr) 14878 RequiredType = Context.getPointerType(RequiredType); 14879 14880 bool mismatch = false; 14881 if (!TypeInfo.LayoutCompatible) { 14882 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14883 14884 // C++11 [basic.fundamental] p1: 14885 // Plain char, signed char, and unsigned char are three distinct types. 14886 // 14887 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14888 // char' depending on the current char signedness mode. 14889 if (mismatch) 14890 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14891 RequiredType->getPointeeType())) || 14892 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14893 mismatch = false; 14894 } else 14895 if (IsPointerAttr) 14896 mismatch = !isLayoutCompatible(Context, 14897 ArgumentType->getPointeeType(), 14898 RequiredType->getPointeeType()); 14899 else 14900 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14901 14902 if (mismatch) 14903 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14904 << ArgumentType << ArgumentKind 14905 << TypeInfo.LayoutCompatible << RequiredType 14906 << ArgumentExpr->getSourceRange() 14907 << TypeTagExpr->getSourceRange(); 14908 } 14909 14910 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14911 CharUnits Alignment) { 14912 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14913 } 14914 14915 void Sema::DiagnoseMisalignedMembers() { 14916 for (MisalignedMember &m : MisalignedMembers) { 14917 const NamedDecl *ND = m.RD; 14918 if (ND->getName().empty()) { 14919 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14920 ND = TD; 14921 } 14922 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14923 << m.MD << ND << m.E->getSourceRange(); 14924 } 14925 MisalignedMembers.clear(); 14926 } 14927 14928 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14929 E = E->IgnoreParens(); 14930 if (!T->isPointerType() && !T->isIntegerType()) 14931 return; 14932 if (isa<UnaryOperator>(E) && 14933 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14934 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14935 if (isa<MemberExpr>(Op)) { 14936 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14937 if (MA != MisalignedMembers.end() && 14938 (T->isIntegerType() || 14939 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14940 Context.getTypeAlignInChars( 14941 T->getPointeeType()) <= MA->Alignment)))) 14942 MisalignedMembers.erase(MA); 14943 } 14944 } 14945 } 14946 14947 void Sema::RefersToMemberWithReducedAlignment( 14948 Expr *E, 14949 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14950 Action) { 14951 const auto *ME = dyn_cast<MemberExpr>(E); 14952 if (!ME) 14953 return; 14954 14955 // No need to check expressions with an __unaligned-qualified type. 14956 if (E->getType().getQualifiers().hasUnaligned()) 14957 return; 14958 14959 // For a chain of MemberExpr like "a.b.c.d" this list 14960 // will keep FieldDecl's like [d, c, b]. 14961 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14962 const MemberExpr *TopME = nullptr; 14963 bool AnyIsPacked = false; 14964 do { 14965 QualType BaseType = ME->getBase()->getType(); 14966 if (BaseType->isDependentType()) 14967 return; 14968 if (ME->isArrow()) 14969 BaseType = BaseType->getPointeeType(); 14970 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14971 if (RD->isInvalidDecl()) 14972 return; 14973 14974 ValueDecl *MD = ME->getMemberDecl(); 14975 auto *FD = dyn_cast<FieldDecl>(MD); 14976 // We do not care about non-data members. 14977 if (!FD || FD->isInvalidDecl()) 14978 return; 14979 14980 AnyIsPacked = 14981 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14982 ReverseMemberChain.push_back(FD); 14983 14984 TopME = ME; 14985 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14986 } while (ME); 14987 assert(TopME && "We did not compute a topmost MemberExpr!"); 14988 14989 // Not the scope of this diagnostic. 14990 if (!AnyIsPacked) 14991 return; 14992 14993 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14994 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14995 // TODO: The innermost base of the member expression may be too complicated. 14996 // For now, just disregard these cases. This is left for future 14997 // improvement. 14998 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14999 return; 15000 15001 // Alignment expected by the whole expression. 15002 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15003 15004 // No need to do anything else with this case. 15005 if (ExpectedAlignment.isOne()) 15006 return; 15007 15008 // Synthesize offset of the whole access. 15009 CharUnits Offset; 15010 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15011 I++) { 15012 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15013 } 15014 15015 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15016 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15017 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15018 15019 // The base expression of the innermost MemberExpr may give 15020 // stronger guarantees than the class containing the member. 15021 if (DRE && !TopME->isArrow()) { 15022 const ValueDecl *VD = DRE->getDecl(); 15023 if (!VD->getType()->isReferenceType()) 15024 CompleteObjectAlignment = 15025 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15026 } 15027 15028 // Check if the synthesized offset fulfills the alignment. 15029 if (Offset % ExpectedAlignment != 0 || 15030 // It may fulfill the offset it but the effective alignment may still be 15031 // lower than the expected expression alignment. 15032 CompleteObjectAlignment < ExpectedAlignment) { 15033 // If this happens, we want to determine a sensible culprit of this. 15034 // Intuitively, watching the chain of member expressions from right to 15035 // left, we start with the required alignment (as required by the field 15036 // type) but some packed attribute in that chain has reduced the alignment. 15037 // It may happen that another packed structure increases it again. But if 15038 // we are here such increase has not been enough. So pointing the first 15039 // FieldDecl that either is packed or else its RecordDecl is, 15040 // seems reasonable. 15041 FieldDecl *FD = nullptr; 15042 CharUnits Alignment; 15043 for (FieldDecl *FDI : ReverseMemberChain) { 15044 if (FDI->hasAttr<PackedAttr>() || 15045 FDI->getParent()->hasAttr<PackedAttr>()) { 15046 FD = FDI; 15047 Alignment = std::min( 15048 Context.getTypeAlignInChars(FD->getType()), 15049 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15050 break; 15051 } 15052 } 15053 assert(FD && "We did not find a packed FieldDecl!"); 15054 Action(E, FD->getParent(), FD, Alignment); 15055 } 15056 } 15057 15058 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15059 using namespace std::placeholders; 15060 15061 RefersToMemberWithReducedAlignment( 15062 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15063 _2, _3, _4)); 15064 } 15065