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 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 205 if (checkArgCount(S, TheCall, 3)) 206 return true; 207 208 // First two arguments should be integers. 209 for (unsigned I = 0; I < 2; ++I) { 210 ExprResult Arg = TheCall->getArg(I); 211 QualType Ty = Arg.get()->getType(); 212 if (!Ty->isIntegerType()) { 213 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 214 << Ty << Arg.get()->getSourceRange(); 215 return true; 216 } 217 InitializedEntity Entity = InitializedEntity::InitializeParameter( 218 S.getASTContext(), Ty, /*consume*/ false); 219 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 220 if (Arg.isInvalid()) 221 return true; 222 TheCall->setArg(I, Arg.get()); 223 } 224 225 // Third argument should be a pointer to a non-const integer. 226 // IRGen correctly handles volatile, restrict, and address spaces, and 227 // the other qualifiers aren't possible. 228 { 229 ExprResult Arg = TheCall->getArg(2); 230 QualType Ty = Arg.get()->getType(); 231 const auto *PtrTy = Ty->getAs<PointerType>(); 232 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 233 !PtrTy->getPointeeType().isConstQualified())) { 234 S.Diag(Arg.get()->getBeginLoc(), 235 diag::err_overflow_builtin_must_be_ptr_int) 236 << Ty << Arg.get()->getSourceRange(); 237 return true; 238 } 239 InitializedEntity Entity = InitializedEntity::InitializeParameter( 240 S.getASTContext(), Ty, /*consume*/ false); 241 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 242 if (Arg.isInvalid()) 243 return true; 244 TheCall->setArg(2, Arg.get()); 245 } 246 return false; 247 } 248 249 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 250 if (checkArgCount(S, BuiltinCall, 2)) 251 return true; 252 253 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 254 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 255 Expr *Call = BuiltinCall->getArg(0); 256 Expr *Chain = BuiltinCall->getArg(1); 257 258 if (Call->getStmtClass() != Stmt::CallExprClass) { 259 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 260 << Call->getSourceRange(); 261 return true; 262 } 263 264 auto CE = cast<CallExpr>(Call); 265 if (CE->getCallee()->getType()->isBlockPointerType()) { 266 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 267 << Call->getSourceRange(); 268 return true; 269 } 270 271 const Decl *TargetDecl = CE->getCalleeDecl(); 272 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 273 if (FD->getBuiltinID()) { 274 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 275 << Call->getSourceRange(); 276 return true; 277 } 278 279 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 280 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 281 << Call->getSourceRange(); 282 return true; 283 } 284 285 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 286 if (ChainResult.isInvalid()) 287 return true; 288 if (!ChainResult.get()->getType()->isPointerType()) { 289 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 290 << Chain->getSourceRange(); 291 return true; 292 } 293 294 QualType ReturnTy = CE->getCallReturnType(S.Context); 295 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 296 QualType BuiltinTy = S.Context.getFunctionType( 297 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 298 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 299 300 Builtin = 301 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 302 303 BuiltinCall->setType(CE->getType()); 304 BuiltinCall->setValueKind(CE->getValueKind()); 305 BuiltinCall->setObjectKind(CE->getObjectKind()); 306 BuiltinCall->setCallee(Builtin); 307 BuiltinCall->setArg(1, ChainResult.get()); 308 309 return false; 310 } 311 312 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 313 /// __builtin_*_chk function, then use the object size argument specified in the 314 /// source. Otherwise, infer the object size using __builtin_object_size. 315 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 316 CallExpr *TheCall) { 317 // FIXME: There are some more useful checks we could be doing here: 318 // - Analyze the format string of sprintf to see how much of buffer is used. 319 // - Evaluate strlen of strcpy arguments, use as object size. 320 321 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 322 isConstantEvaluated()) 323 return; 324 325 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 326 if (!BuiltinID) 327 return; 328 329 unsigned DiagID = 0; 330 bool IsChkVariant = false; 331 unsigned SizeIndex, ObjectIndex; 332 switch (BuiltinID) { 333 default: 334 return; 335 case Builtin::BI__builtin___memcpy_chk: 336 case Builtin::BI__builtin___memmove_chk: 337 case Builtin::BI__builtin___memset_chk: 338 case Builtin::BI__builtin___strlcat_chk: 339 case Builtin::BI__builtin___strlcpy_chk: 340 case Builtin::BI__builtin___strncat_chk: 341 case Builtin::BI__builtin___strncpy_chk: 342 case Builtin::BI__builtin___stpncpy_chk: 343 case Builtin::BI__builtin___memccpy_chk: { 344 DiagID = diag::warn_builtin_chk_overflow; 345 IsChkVariant = true; 346 SizeIndex = TheCall->getNumArgs() - 2; 347 ObjectIndex = TheCall->getNumArgs() - 1; 348 break; 349 } 350 351 case Builtin::BI__builtin___snprintf_chk: 352 case Builtin::BI__builtin___vsnprintf_chk: { 353 DiagID = diag::warn_builtin_chk_overflow; 354 IsChkVariant = true; 355 SizeIndex = 1; 356 ObjectIndex = 3; 357 break; 358 } 359 360 case Builtin::BIstrncat: 361 case Builtin::BI__builtin_strncat: 362 case Builtin::BIstrncpy: 363 case Builtin::BI__builtin_strncpy: 364 case Builtin::BIstpncpy: 365 case Builtin::BI__builtin_stpncpy: { 366 // Whether these functions overflow depends on the runtime strlen of the 367 // string, not just the buffer size, so emitting the "always overflow" 368 // diagnostic isn't quite right. We should still diagnose passing a buffer 369 // size larger than the destination buffer though; this is a runtime abort 370 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 371 DiagID = diag::warn_fortify_source_size_mismatch; 372 SizeIndex = TheCall->getNumArgs() - 1; 373 ObjectIndex = 0; 374 break; 375 } 376 377 case Builtin::BImemcpy: 378 case Builtin::BI__builtin_memcpy: 379 case Builtin::BImemmove: 380 case Builtin::BI__builtin_memmove: 381 case Builtin::BImemset: 382 case Builtin::BI__builtin_memset: { 383 DiagID = diag::warn_fortify_source_overflow; 384 SizeIndex = TheCall->getNumArgs() - 1; 385 ObjectIndex = 0; 386 break; 387 } 388 case Builtin::BIsnprintf: 389 case Builtin::BI__builtin_snprintf: 390 case Builtin::BIvsnprintf: 391 case Builtin::BI__builtin_vsnprintf: { 392 DiagID = diag::warn_fortify_source_size_mismatch; 393 SizeIndex = 1; 394 ObjectIndex = 0; 395 break; 396 } 397 } 398 399 llvm::APSInt ObjectSize; 400 // For __builtin___*_chk, the object size is explicitly provided by the caller 401 // (usually using __builtin_object_size). Use that value to check this call. 402 if (IsChkVariant) { 403 Expr::EvalResult Result; 404 Expr *SizeArg = TheCall->getArg(ObjectIndex); 405 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 406 return; 407 ObjectSize = Result.Val.getInt(); 408 409 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 410 } else { 411 // If the parameter has a pass_object_size attribute, then we should use its 412 // (potentially) more strict checking mode. Otherwise, conservatively assume 413 // type 0. 414 int BOSType = 0; 415 if (const auto *POS = 416 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 417 BOSType = POS->getType(); 418 419 Expr *ObjArg = TheCall->getArg(ObjectIndex); 420 uint64_t Result; 421 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 422 return; 423 // Get the object size in the target's size_t width. 424 const TargetInfo &TI = getASTContext().getTargetInfo(); 425 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 426 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 427 } 428 429 // Evaluate the number of bytes of the object that this call will use. 430 Expr::EvalResult Result; 431 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 432 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 433 return; 434 llvm::APSInt UsedSize = Result.Val.getInt(); 435 436 if (UsedSize.ule(ObjectSize)) 437 return; 438 439 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 440 // Skim off the details of whichever builtin was called to produce a better 441 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 442 if (IsChkVariant) { 443 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 444 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 445 } else if (FunctionName.startswith("__builtin_")) { 446 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 447 } 448 449 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 450 PDiag(DiagID) 451 << FunctionName << ObjectSize.toString(/*Radix=*/10) 452 << UsedSize.toString(/*Radix=*/10)); 453 } 454 455 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 456 Scope::ScopeFlags NeededScopeFlags, 457 unsigned DiagID) { 458 // Scopes aren't available during instantiation. Fortunately, builtin 459 // functions cannot be template args so they cannot be formed through template 460 // instantiation. Therefore checking once during the parse is sufficient. 461 if (SemaRef.inTemplateInstantiation()) 462 return false; 463 464 Scope *S = SemaRef.getCurScope(); 465 while (S && !S->isSEHExceptScope()) 466 S = S->getParent(); 467 if (!S || !(S->getFlags() & NeededScopeFlags)) { 468 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 469 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 470 << DRE->getDecl()->getIdentifier(); 471 return true; 472 } 473 474 return false; 475 } 476 477 static inline bool isBlockPointer(Expr *Arg) { 478 return Arg->getType()->isBlockPointerType(); 479 } 480 481 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 482 /// void*, which is a requirement of device side enqueue. 483 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 484 const BlockPointerType *BPT = 485 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 486 ArrayRef<QualType> Params = 487 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 488 unsigned ArgCounter = 0; 489 bool IllegalParams = false; 490 // Iterate through the block parameters until either one is found that is not 491 // a local void*, or the block is valid. 492 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 493 I != E; ++I, ++ArgCounter) { 494 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 495 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 496 LangAS::opencl_local) { 497 // Get the location of the error. If a block literal has been passed 498 // (BlockExpr) then we can point straight to the offending argument, 499 // else we just point to the variable reference. 500 SourceLocation ErrorLoc; 501 if (isa<BlockExpr>(BlockArg)) { 502 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 503 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 504 } else if (isa<DeclRefExpr>(BlockArg)) { 505 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 506 } 507 S.Diag(ErrorLoc, 508 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 509 IllegalParams = true; 510 } 511 } 512 513 return IllegalParams; 514 } 515 516 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 517 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 518 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 519 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 520 return true; 521 } 522 return false; 523 } 524 525 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 526 if (checkArgCount(S, TheCall, 2)) 527 return true; 528 529 if (checkOpenCLSubgroupExt(S, TheCall)) 530 return true; 531 532 // First argument is an ndrange_t type. 533 Expr *NDRangeArg = TheCall->getArg(0); 534 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 535 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 536 << TheCall->getDirectCallee() << "'ndrange_t'"; 537 return true; 538 } 539 540 Expr *BlockArg = TheCall->getArg(1); 541 if (!isBlockPointer(BlockArg)) { 542 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 543 << TheCall->getDirectCallee() << "block"; 544 return true; 545 } 546 return checkOpenCLBlockArgs(S, BlockArg); 547 } 548 549 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 550 /// get_kernel_work_group_size 551 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 552 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 553 if (checkArgCount(S, TheCall, 1)) 554 return true; 555 556 Expr *BlockArg = TheCall->getArg(0); 557 if (!isBlockPointer(BlockArg)) { 558 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 559 << TheCall->getDirectCallee() << "block"; 560 return true; 561 } 562 return checkOpenCLBlockArgs(S, BlockArg); 563 } 564 565 /// Diagnose integer type and any valid implicit conversion to it. 566 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 567 const QualType &IntType); 568 569 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 570 unsigned Start, unsigned End) { 571 bool IllegalParams = false; 572 for (unsigned I = Start; I <= End; ++I) 573 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 574 S.Context.getSizeType()); 575 return IllegalParams; 576 } 577 578 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 579 /// 'local void*' parameter of passed block. 580 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 581 Expr *BlockArg, 582 unsigned NumNonVarArgs) { 583 const BlockPointerType *BPT = 584 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 585 unsigned NumBlockParams = 586 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 587 unsigned TotalNumArgs = TheCall->getNumArgs(); 588 589 // For each argument passed to the block, a corresponding uint needs to 590 // be passed to describe the size of the local memory. 591 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 592 S.Diag(TheCall->getBeginLoc(), 593 diag::err_opencl_enqueue_kernel_local_size_args); 594 return true; 595 } 596 597 // Check that the sizes of the local memory are specified by integers. 598 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 599 TotalNumArgs - 1); 600 } 601 602 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 603 /// overload formats specified in Table 6.13.17.1. 604 /// int enqueue_kernel(queue_t queue, 605 /// kernel_enqueue_flags_t flags, 606 /// const ndrange_t ndrange, 607 /// void (^block)(void)) 608 /// int enqueue_kernel(queue_t queue, 609 /// kernel_enqueue_flags_t flags, 610 /// const ndrange_t ndrange, 611 /// uint num_events_in_wait_list, 612 /// clk_event_t *event_wait_list, 613 /// clk_event_t *event_ret, 614 /// void (^block)(void)) 615 /// int enqueue_kernel(queue_t queue, 616 /// kernel_enqueue_flags_t flags, 617 /// const ndrange_t ndrange, 618 /// void (^block)(local void*, ...), 619 /// uint size0, ...) 620 /// int enqueue_kernel(queue_t queue, 621 /// kernel_enqueue_flags_t flags, 622 /// const ndrange_t ndrange, 623 /// uint num_events_in_wait_list, 624 /// clk_event_t *event_wait_list, 625 /// clk_event_t *event_ret, 626 /// void (^block)(local void*, ...), 627 /// uint size0, ...) 628 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 629 unsigned NumArgs = TheCall->getNumArgs(); 630 631 if (NumArgs < 4) { 632 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args); 633 return true; 634 } 635 636 Expr *Arg0 = TheCall->getArg(0); 637 Expr *Arg1 = TheCall->getArg(1); 638 Expr *Arg2 = TheCall->getArg(2); 639 Expr *Arg3 = TheCall->getArg(3); 640 641 // First argument always needs to be a queue_t type. 642 if (!Arg0->getType()->isQueueT()) { 643 S.Diag(TheCall->getArg(0)->getBeginLoc(), 644 diag::err_opencl_builtin_expected_type) 645 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 646 return true; 647 } 648 649 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 650 if (!Arg1->getType()->isIntegerType()) { 651 S.Diag(TheCall->getArg(1)->getBeginLoc(), 652 diag::err_opencl_builtin_expected_type) 653 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 654 return true; 655 } 656 657 // Third argument is always an ndrange_t type. 658 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 659 S.Diag(TheCall->getArg(2)->getBeginLoc(), 660 diag::err_opencl_builtin_expected_type) 661 << TheCall->getDirectCallee() << "'ndrange_t'"; 662 return true; 663 } 664 665 // With four arguments, there is only one form that the function could be 666 // called in: no events and no variable arguments. 667 if (NumArgs == 4) { 668 // check that the last argument is the right block type. 669 if (!isBlockPointer(Arg3)) { 670 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 671 << TheCall->getDirectCallee() << "block"; 672 return true; 673 } 674 // we have a block type, check the prototype 675 const BlockPointerType *BPT = 676 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 677 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 678 S.Diag(Arg3->getBeginLoc(), 679 diag::err_opencl_enqueue_kernel_blocks_no_args); 680 return true; 681 } 682 return false; 683 } 684 // we can have block + varargs. 685 if (isBlockPointer(Arg3)) 686 return (checkOpenCLBlockArgs(S, Arg3) || 687 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 688 // last two cases with either exactly 7 args or 7 args and varargs. 689 if (NumArgs >= 7) { 690 // check common block argument. 691 Expr *Arg6 = TheCall->getArg(6); 692 if (!isBlockPointer(Arg6)) { 693 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 694 << TheCall->getDirectCallee() << "block"; 695 return true; 696 } 697 if (checkOpenCLBlockArgs(S, Arg6)) 698 return true; 699 700 // Forth argument has to be any integer type. 701 if (!Arg3->getType()->isIntegerType()) { 702 S.Diag(TheCall->getArg(3)->getBeginLoc(), 703 diag::err_opencl_builtin_expected_type) 704 << TheCall->getDirectCallee() << "integer"; 705 return true; 706 } 707 // check remaining common arguments. 708 Expr *Arg4 = TheCall->getArg(4); 709 Expr *Arg5 = TheCall->getArg(5); 710 711 // Fifth argument is always passed as a pointer to clk_event_t. 712 if (!Arg4->isNullPointerConstant(S.Context, 713 Expr::NPC_ValueDependentIsNotNull) && 714 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 715 S.Diag(TheCall->getArg(4)->getBeginLoc(), 716 diag::err_opencl_builtin_expected_type) 717 << TheCall->getDirectCallee() 718 << S.Context.getPointerType(S.Context.OCLClkEventTy); 719 return true; 720 } 721 722 // Sixth argument is always passed as a pointer to clk_event_t. 723 if (!Arg5->isNullPointerConstant(S.Context, 724 Expr::NPC_ValueDependentIsNotNull) && 725 !(Arg5->getType()->isPointerType() && 726 Arg5->getType()->getPointeeType()->isClkEventT())) { 727 S.Diag(TheCall->getArg(5)->getBeginLoc(), 728 diag::err_opencl_builtin_expected_type) 729 << TheCall->getDirectCallee() 730 << S.Context.getPointerType(S.Context.OCLClkEventTy); 731 return true; 732 } 733 734 if (NumArgs == 7) 735 return false; 736 737 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 738 } 739 740 // None of the specific case has been detected, give generic error 741 S.Diag(TheCall->getBeginLoc(), 742 diag::err_opencl_enqueue_kernel_incorrect_args); 743 return true; 744 } 745 746 /// Returns OpenCL access qual. 747 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 748 return D->getAttr<OpenCLAccessAttr>(); 749 } 750 751 /// Returns true if pipe element type is different from the pointer. 752 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 753 const Expr *Arg0 = Call->getArg(0); 754 // First argument type should always be pipe. 755 if (!Arg0->getType()->isPipeType()) { 756 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 757 << Call->getDirectCallee() << Arg0->getSourceRange(); 758 return true; 759 } 760 OpenCLAccessAttr *AccessQual = 761 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 762 // Validates the access qualifier is compatible with the call. 763 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 764 // read_only and write_only, and assumed to be read_only if no qualifier is 765 // specified. 766 switch (Call->getDirectCallee()->getBuiltinID()) { 767 case Builtin::BIread_pipe: 768 case Builtin::BIreserve_read_pipe: 769 case Builtin::BIcommit_read_pipe: 770 case Builtin::BIwork_group_reserve_read_pipe: 771 case Builtin::BIsub_group_reserve_read_pipe: 772 case Builtin::BIwork_group_commit_read_pipe: 773 case Builtin::BIsub_group_commit_read_pipe: 774 if (!(!AccessQual || AccessQual->isReadOnly())) { 775 S.Diag(Arg0->getBeginLoc(), 776 diag::err_opencl_builtin_pipe_invalid_access_modifier) 777 << "read_only" << Arg0->getSourceRange(); 778 return true; 779 } 780 break; 781 case Builtin::BIwrite_pipe: 782 case Builtin::BIreserve_write_pipe: 783 case Builtin::BIcommit_write_pipe: 784 case Builtin::BIwork_group_reserve_write_pipe: 785 case Builtin::BIsub_group_reserve_write_pipe: 786 case Builtin::BIwork_group_commit_write_pipe: 787 case Builtin::BIsub_group_commit_write_pipe: 788 if (!(AccessQual && AccessQual->isWriteOnly())) { 789 S.Diag(Arg0->getBeginLoc(), 790 diag::err_opencl_builtin_pipe_invalid_access_modifier) 791 << "write_only" << Arg0->getSourceRange(); 792 return true; 793 } 794 break; 795 default: 796 break; 797 } 798 return false; 799 } 800 801 /// Returns true if pipe element type is different from the pointer. 802 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 803 const Expr *Arg0 = Call->getArg(0); 804 const Expr *ArgIdx = Call->getArg(Idx); 805 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 806 const QualType EltTy = PipeTy->getElementType(); 807 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 808 // The Idx argument should be a pointer and the type of the pointer and 809 // the type of pipe element should also be the same. 810 if (!ArgTy || 811 !S.Context.hasSameType( 812 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 813 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 814 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 815 << ArgIdx->getType() << ArgIdx->getSourceRange(); 816 return true; 817 } 818 return false; 819 } 820 821 // Performs semantic analysis for the read/write_pipe call. 822 // \param S Reference to the semantic analyzer. 823 // \param Call A pointer to the builtin call. 824 // \return True if a semantic error has been found, false otherwise. 825 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 826 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 827 // functions have two forms. 828 switch (Call->getNumArgs()) { 829 case 2: 830 if (checkOpenCLPipeArg(S, Call)) 831 return true; 832 // The call with 2 arguments should be 833 // read/write_pipe(pipe T, T*). 834 // Check packet type T. 835 if (checkOpenCLPipePacketType(S, Call, 1)) 836 return true; 837 break; 838 839 case 4: { 840 if (checkOpenCLPipeArg(S, Call)) 841 return true; 842 // The call with 4 arguments should be 843 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 844 // Check reserve_id_t. 845 if (!Call->getArg(1)->getType()->isReserveIDT()) { 846 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 847 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 848 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 849 return true; 850 } 851 852 // Check the index. 853 const Expr *Arg2 = Call->getArg(2); 854 if (!Arg2->getType()->isIntegerType() && 855 !Arg2->getType()->isUnsignedIntegerType()) { 856 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 857 << Call->getDirectCallee() << S.Context.UnsignedIntTy 858 << Arg2->getType() << Arg2->getSourceRange(); 859 return true; 860 } 861 862 // Check packet type T. 863 if (checkOpenCLPipePacketType(S, Call, 3)) 864 return true; 865 } break; 866 default: 867 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 868 << Call->getDirectCallee() << Call->getSourceRange(); 869 return true; 870 } 871 872 return false; 873 } 874 875 // Performs a semantic analysis on the {work_group_/sub_group_ 876 // /_}reserve_{read/write}_pipe 877 // \param S Reference to the semantic analyzer. 878 // \param Call The call to the builtin function to be analyzed. 879 // \return True if a semantic error was found, false otherwise. 880 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 881 if (checkArgCount(S, Call, 2)) 882 return true; 883 884 if (checkOpenCLPipeArg(S, Call)) 885 return true; 886 887 // Check the reserve size. 888 if (!Call->getArg(1)->getType()->isIntegerType() && 889 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 890 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 891 << Call->getDirectCallee() << S.Context.UnsignedIntTy 892 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 893 return true; 894 } 895 896 // Since return type of reserve_read/write_pipe built-in function is 897 // reserve_id_t, which is not defined in the builtin def file , we used int 898 // as return type and need to override the return type of these functions. 899 Call->setType(S.Context.OCLReserveIDTy); 900 901 return false; 902 } 903 904 // Performs a semantic analysis on {work_group_/sub_group_ 905 // /_}commit_{read/write}_pipe 906 // \param S Reference to the semantic analyzer. 907 // \param Call The call to the builtin function to be analyzed. 908 // \return True if a semantic error was found, false otherwise. 909 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 910 if (checkArgCount(S, Call, 2)) 911 return true; 912 913 if (checkOpenCLPipeArg(S, Call)) 914 return true; 915 916 // Check reserve_id_t. 917 if (!Call->getArg(1)->getType()->isReserveIDT()) { 918 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 919 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 920 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 921 return true; 922 } 923 924 return false; 925 } 926 927 // Performs a semantic analysis on the call to built-in Pipe 928 // Query Functions. 929 // \param S Reference to the semantic analyzer. 930 // \param Call The call to the builtin function to be analyzed. 931 // \return True if a semantic error was found, false otherwise. 932 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 933 if (checkArgCount(S, Call, 1)) 934 return true; 935 936 if (!Call->getArg(0)->getType()->isPipeType()) { 937 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 938 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 939 return true; 940 } 941 942 return false; 943 } 944 945 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 946 // Performs semantic analysis for the to_global/local/private call. 947 // \param S Reference to the semantic analyzer. 948 // \param BuiltinID ID of the builtin function. 949 // \param Call A pointer to the builtin call. 950 // \return True if a semantic error has been found, false otherwise. 951 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 952 CallExpr *Call) { 953 if (Call->getNumArgs() != 1) { 954 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 955 << Call->getDirectCallee() << Call->getSourceRange(); 956 return true; 957 } 958 959 auto RT = Call->getArg(0)->getType(); 960 if (!RT->isPointerType() || RT->getPointeeType() 961 .getAddressSpace() == LangAS::opencl_constant) { 962 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 963 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 964 return true; 965 } 966 967 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 968 S.Diag(Call->getArg(0)->getBeginLoc(), 969 diag::warn_opencl_generic_address_space_arg) 970 << Call->getDirectCallee()->getNameInfo().getAsString() 971 << Call->getArg(0)->getSourceRange(); 972 } 973 974 RT = RT->getPointeeType(); 975 auto Qual = RT.getQualifiers(); 976 switch (BuiltinID) { 977 case Builtin::BIto_global: 978 Qual.setAddressSpace(LangAS::opencl_global); 979 break; 980 case Builtin::BIto_local: 981 Qual.setAddressSpace(LangAS::opencl_local); 982 break; 983 case Builtin::BIto_private: 984 Qual.setAddressSpace(LangAS::opencl_private); 985 break; 986 default: 987 llvm_unreachable("Invalid builtin function"); 988 } 989 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 990 RT.getUnqualifiedType(), Qual))); 991 992 return false; 993 } 994 995 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 996 if (checkArgCount(S, TheCall, 1)) 997 return ExprError(); 998 999 // Compute __builtin_launder's parameter type from the argument. 1000 // The parameter type is: 1001 // * The type of the argument if it's not an array or function type, 1002 // Otherwise, 1003 // * The decayed argument type. 1004 QualType ParamTy = [&]() { 1005 QualType ArgTy = TheCall->getArg(0)->getType(); 1006 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1007 return S.Context.getPointerType(Ty->getElementType()); 1008 if (ArgTy->isFunctionType()) { 1009 return S.Context.getPointerType(ArgTy); 1010 } 1011 return ArgTy; 1012 }(); 1013 1014 TheCall->setType(ParamTy); 1015 1016 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1017 if (!ParamTy->isPointerType()) 1018 return 0; 1019 if (ParamTy->isFunctionPointerType()) 1020 return 1; 1021 if (ParamTy->isVoidPointerType()) 1022 return 2; 1023 return llvm::Optional<unsigned>{}; 1024 }(); 1025 if (DiagSelect.hasValue()) { 1026 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1027 << DiagSelect.getValue() << TheCall->getSourceRange(); 1028 return ExprError(); 1029 } 1030 1031 // We either have an incomplete class type, or we have a class template 1032 // whose instantiation has not been forced. Example: 1033 // 1034 // template <class T> struct Foo { T value; }; 1035 // Foo<int> *p = nullptr; 1036 // auto *d = __builtin_launder(p); 1037 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1038 diag::err_incomplete_type)) 1039 return ExprError(); 1040 1041 assert(ParamTy->getPointeeType()->isObjectType() && 1042 "Unhandled non-object pointer case"); 1043 1044 InitializedEntity Entity = 1045 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1046 ExprResult Arg = 1047 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1048 if (Arg.isInvalid()) 1049 return ExprError(); 1050 TheCall->setArg(0, Arg.get()); 1051 1052 return TheCall; 1053 } 1054 1055 // Emit an error and return true if the current architecture is not in the list 1056 // of supported architectures. 1057 static bool 1058 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1059 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1060 llvm::Triple::ArchType CurArch = 1061 S.getASTContext().getTargetInfo().getTriple().getArch(); 1062 if (llvm::is_contained(SupportedArchs, CurArch)) 1063 return false; 1064 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1065 << TheCall->getSourceRange(); 1066 return true; 1067 } 1068 1069 ExprResult 1070 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1071 CallExpr *TheCall) { 1072 ExprResult TheCallResult(TheCall); 1073 1074 // Find out if any arguments are required to be integer constant expressions. 1075 unsigned ICEArguments = 0; 1076 ASTContext::GetBuiltinTypeError Error; 1077 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1078 if (Error != ASTContext::GE_None) 1079 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1080 1081 // If any arguments are required to be ICE's, check and diagnose. 1082 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1083 // Skip arguments not required to be ICE's. 1084 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1085 1086 llvm::APSInt Result; 1087 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1088 return true; 1089 ICEArguments &= ~(1 << ArgNo); 1090 } 1091 1092 switch (BuiltinID) { 1093 case Builtin::BI__builtin___CFStringMakeConstantString: 1094 assert(TheCall->getNumArgs() == 1 && 1095 "Wrong # arguments to builtin CFStringMakeConstantString"); 1096 if (CheckObjCString(TheCall->getArg(0))) 1097 return ExprError(); 1098 break; 1099 case Builtin::BI__builtin_ms_va_start: 1100 case Builtin::BI__builtin_stdarg_start: 1101 case Builtin::BI__builtin_va_start: 1102 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1103 return ExprError(); 1104 break; 1105 case Builtin::BI__va_start: { 1106 switch (Context.getTargetInfo().getTriple().getArch()) { 1107 case llvm::Triple::aarch64: 1108 case llvm::Triple::arm: 1109 case llvm::Triple::thumb: 1110 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1111 return ExprError(); 1112 break; 1113 default: 1114 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1115 return ExprError(); 1116 break; 1117 } 1118 break; 1119 } 1120 1121 // The acquire, release, and no fence variants are ARM and AArch64 only. 1122 case Builtin::BI_interlockedbittestandset_acq: 1123 case Builtin::BI_interlockedbittestandset_rel: 1124 case Builtin::BI_interlockedbittestandset_nf: 1125 case Builtin::BI_interlockedbittestandreset_acq: 1126 case Builtin::BI_interlockedbittestandreset_rel: 1127 case Builtin::BI_interlockedbittestandreset_nf: 1128 if (CheckBuiltinTargetSupport( 1129 *this, BuiltinID, TheCall, 1130 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1131 return ExprError(); 1132 break; 1133 1134 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1135 case Builtin::BI_bittest64: 1136 case Builtin::BI_bittestandcomplement64: 1137 case Builtin::BI_bittestandreset64: 1138 case Builtin::BI_bittestandset64: 1139 case Builtin::BI_interlockedbittestandreset64: 1140 case Builtin::BI_interlockedbittestandset64: 1141 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1142 {llvm::Triple::x86_64, llvm::Triple::arm, 1143 llvm::Triple::thumb, llvm::Triple::aarch64})) 1144 return ExprError(); 1145 break; 1146 1147 case Builtin::BI__builtin_isgreater: 1148 case Builtin::BI__builtin_isgreaterequal: 1149 case Builtin::BI__builtin_isless: 1150 case Builtin::BI__builtin_islessequal: 1151 case Builtin::BI__builtin_islessgreater: 1152 case Builtin::BI__builtin_isunordered: 1153 if (SemaBuiltinUnorderedCompare(TheCall)) 1154 return ExprError(); 1155 break; 1156 case Builtin::BI__builtin_fpclassify: 1157 if (SemaBuiltinFPClassification(TheCall, 6)) 1158 return ExprError(); 1159 break; 1160 case Builtin::BI__builtin_isfinite: 1161 case Builtin::BI__builtin_isinf: 1162 case Builtin::BI__builtin_isinf_sign: 1163 case Builtin::BI__builtin_isnan: 1164 case Builtin::BI__builtin_isnormal: 1165 case Builtin::BI__builtin_signbit: 1166 case Builtin::BI__builtin_signbitf: 1167 case Builtin::BI__builtin_signbitl: 1168 if (SemaBuiltinFPClassification(TheCall, 1)) 1169 return ExprError(); 1170 break; 1171 case Builtin::BI__builtin_shufflevector: 1172 return SemaBuiltinShuffleVector(TheCall); 1173 // TheCall will be freed by the smart pointer here, but that's fine, since 1174 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1175 case Builtin::BI__builtin_prefetch: 1176 if (SemaBuiltinPrefetch(TheCall)) 1177 return ExprError(); 1178 break; 1179 case Builtin::BI__builtin_alloca_with_align: 1180 if (SemaBuiltinAllocaWithAlign(TheCall)) 1181 return ExprError(); 1182 LLVM_FALLTHROUGH; 1183 case Builtin::BI__builtin_alloca: 1184 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1185 << TheCall->getDirectCallee(); 1186 break; 1187 case Builtin::BI__assume: 1188 case Builtin::BI__builtin_assume: 1189 if (SemaBuiltinAssume(TheCall)) 1190 return ExprError(); 1191 break; 1192 case Builtin::BI__builtin_assume_aligned: 1193 if (SemaBuiltinAssumeAligned(TheCall)) 1194 return ExprError(); 1195 break; 1196 case Builtin::BI__builtin_dynamic_object_size: 1197 case Builtin::BI__builtin_object_size: 1198 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1199 return ExprError(); 1200 break; 1201 case Builtin::BI__builtin_longjmp: 1202 if (SemaBuiltinLongjmp(TheCall)) 1203 return ExprError(); 1204 break; 1205 case Builtin::BI__builtin_setjmp: 1206 if (SemaBuiltinSetjmp(TheCall)) 1207 return ExprError(); 1208 break; 1209 case Builtin::BI_setjmp: 1210 case Builtin::BI_setjmpex: 1211 if (checkArgCount(*this, TheCall, 1)) 1212 return true; 1213 break; 1214 case Builtin::BI__builtin_classify_type: 1215 if (checkArgCount(*this, TheCall, 1)) return true; 1216 TheCall->setType(Context.IntTy); 1217 break; 1218 case Builtin::BI__builtin_constant_p: { 1219 if (checkArgCount(*this, TheCall, 1)) return true; 1220 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1221 if (Arg.isInvalid()) return true; 1222 TheCall->setArg(0, Arg.get()); 1223 TheCall->setType(Context.IntTy); 1224 break; 1225 } 1226 case Builtin::BI__builtin_launder: 1227 return SemaBuiltinLaunder(*this, TheCall); 1228 case Builtin::BI__sync_fetch_and_add: 1229 case Builtin::BI__sync_fetch_and_add_1: 1230 case Builtin::BI__sync_fetch_and_add_2: 1231 case Builtin::BI__sync_fetch_and_add_4: 1232 case Builtin::BI__sync_fetch_and_add_8: 1233 case Builtin::BI__sync_fetch_and_add_16: 1234 case Builtin::BI__sync_fetch_and_sub: 1235 case Builtin::BI__sync_fetch_and_sub_1: 1236 case Builtin::BI__sync_fetch_and_sub_2: 1237 case Builtin::BI__sync_fetch_and_sub_4: 1238 case Builtin::BI__sync_fetch_and_sub_8: 1239 case Builtin::BI__sync_fetch_and_sub_16: 1240 case Builtin::BI__sync_fetch_and_or: 1241 case Builtin::BI__sync_fetch_and_or_1: 1242 case Builtin::BI__sync_fetch_and_or_2: 1243 case Builtin::BI__sync_fetch_and_or_4: 1244 case Builtin::BI__sync_fetch_and_or_8: 1245 case Builtin::BI__sync_fetch_and_or_16: 1246 case Builtin::BI__sync_fetch_and_and: 1247 case Builtin::BI__sync_fetch_and_and_1: 1248 case Builtin::BI__sync_fetch_and_and_2: 1249 case Builtin::BI__sync_fetch_and_and_4: 1250 case Builtin::BI__sync_fetch_and_and_8: 1251 case Builtin::BI__sync_fetch_and_and_16: 1252 case Builtin::BI__sync_fetch_and_xor: 1253 case Builtin::BI__sync_fetch_and_xor_1: 1254 case Builtin::BI__sync_fetch_and_xor_2: 1255 case Builtin::BI__sync_fetch_and_xor_4: 1256 case Builtin::BI__sync_fetch_and_xor_8: 1257 case Builtin::BI__sync_fetch_and_xor_16: 1258 case Builtin::BI__sync_fetch_and_nand: 1259 case Builtin::BI__sync_fetch_and_nand_1: 1260 case Builtin::BI__sync_fetch_and_nand_2: 1261 case Builtin::BI__sync_fetch_and_nand_4: 1262 case Builtin::BI__sync_fetch_and_nand_8: 1263 case Builtin::BI__sync_fetch_and_nand_16: 1264 case Builtin::BI__sync_add_and_fetch: 1265 case Builtin::BI__sync_add_and_fetch_1: 1266 case Builtin::BI__sync_add_and_fetch_2: 1267 case Builtin::BI__sync_add_and_fetch_4: 1268 case Builtin::BI__sync_add_and_fetch_8: 1269 case Builtin::BI__sync_add_and_fetch_16: 1270 case Builtin::BI__sync_sub_and_fetch: 1271 case Builtin::BI__sync_sub_and_fetch_1: 1272 case Builtin::BI__sync_sub_and_fetch_2: 1273 case Builtin::BI__sync_sub_and_fetch_4: 1274 case Builtin::BI__sync_sub_and_fetch_8: 1275 case Builtin::BI__sync_sub_and_fetch_16: 1276 case Builtin::BI__sync_and_and_fetch: 1277 case Builtin::BI__sync_and_and_fetch_1: 1278 case Builtin::BI__sync_and_and_fetch_2: 1279 case Builtin::BI__sync_and_and_fetch_4: 1280 case Builtin::BI__sync_and_and_fetch_8: 1281 case Builtin::BI__sync_and_and_fetch_16: 1282 case Builtin::BI__sync_or_and_fetch: 1283 case Builtin::BI__sync_or_and_fetch_1: 1284 case Builtin::BI__sync_or_and_fetch_2: 1285 case Builtin::BI__sync_or_and_fetch_4: 1286 case Builtin::BI__sync_or_and_fetch_8: 1287 case Builtin::BI__sync_or_and_fetch_16: 1288 case Builtin::BI__sync_xor_and_fetch: 1289 case Builtin::BI__sync_xor_and_fetch_1: 1290 case Builtin::BI__sync_xor_and_fetch_2: 1291 case Builtin::BI__sync_xor_and_fetch_4: 1292 case Builtin::BI__sync_xor_and_fetch_8: 1293 case Builtin::BI__sync_xor_and_fetch_16: 1294 case Builtin::BI__sync_nand_and_fetch: 1295 case Builtin::BI__sync_nand_and_fetch_1: 1296 case Builtin::BI__sync_nand_and_fetch_2: 1297 case Builtin::BI__sync_nand_and_fetch_4: 1298 case Builtin::BI__sync_nand_and_fetch_8: 1299 case Builtin::BI__sync_nand_and_fetch_16: 1300 case Builtin::BI__sync_val_compare_and_swap: 1301 case Builtin::BI__sync_val_compare_and_swap_1: 1302 case Builtin::BI__sync_val_compare_and_swap_2: 1303 case Builtin::BI__sync_val_compare_and_swap_4: 1304 case Builtin::BI__sync_val_compare_and_swap_8: 1305 case Builtin::BI__sync_val_compare_and_swap_16: 1306 case Builtin::BI__sync_bool_compare_and_swap: 1307 case Builtin::BI__sync_bool_compare_and_swap_1: 1308 case Builtin::BI__sync_bool_compare_and_swap_2: 1309 case Builtin::BI__sync_bool_compare_and_swap_4: 1310 case Builtin::BI__sync_bool_compare_and_swap_8: 1311 case Builtin::BI__sync_bool_compare_and_swap_16: 1312 case Builtin::BI__sync_lock_test_and_set: 1313 case Builtin::BI__sync_lock_test_and_set_1: 1314 case Builtin::BI__sync_lock_test_and_set_2: 1315 case Builtin::BI__sync_lock_test_and_set_4: 1316 case Builtin::BI__sync_lock_test_and_set_8: 1317 case Builtin::BI__sync_lock_test_and_set_16: 1318 case Builtin::BI__sync_lock_release: 1319 case Builtin::BI__sync_lock_release_1: 1320 case Builtin::BI__sync_lock_release_2: 1321 case Builtin::BI__sync_lock_release_4: 1322 case Builtin::BI__sync_lock_release_8: 1323 case Builtin::BI__sync_lock_release_16: 1324 case Builtin::BI__sync_swap: 1325 case Builtin::BI__sync_swap_1: 1326 case Builtin::BI__sync_swap_2: 1327 case Builtin::BI__sync_swap_4: 1328 case Builtin::BI__sync_swap_8: 1329 case Builtin::BI__sync_swap_16: 1330 return SemaBuiltinAtomicOverloaded(TheCallResult); 1331 case Builtin::BI__sync_synchronize: 1332 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1333 << TheCall->getCallee()->getSourceRange(); 1334 break; 1335 case Builtin::BI__builtin_nontemporal_load: 1336 case Builtin::BI__builtin_nontemporal_store: 1337 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1338 #define BUILTIN(ID, TYPE, ATTRS) 1339 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1340 case Builtin::BI##ID: \ 1341 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1342 #include "clang/Basic/Builtins.def" 1343 case Builtin::BI__annotation: 1344 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1345 return ExprError(); 1346 break; 1347 case Builtin::BI__builtin_annotation: 1348 if (SemaBuiltinAnnotation(*this, TheCall)) 1349 return ExprError(); 1350 break; 1351 case Builtin::BI__builtin_addressof: 1352 if (SemaBuiltinAddressof(*this, TheCall)) 1353 return ExprError(); 1354 break; 1355 case Builtin::BI__builtin_add_overflow: 1356 case Builtin::BI__builtin_sub_overflow: 1357 case Builtin::BI__builtin_mul_overflow: 1358 if (SemaBuiltinOverflow(*this, TheCall)) 1359 return ExprError(); 1360 break; 1361 case Builtin::BI__builtin_operator_new: 1362 case Builtin::BI__builtin_operator_delete: { 1363 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1364 ExprResult Res = 1365 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1366 if (Res.isInvalid()) 1367 CorrectDelayedTyposInExpr(TheCallResult.get()); 1368 return Res; 1369 } 1370 case Builtin::BI__builtin_dump_struct: { 1371 // We first want to ensure we are called with 2 arguments 1372 if (checkArgCount(*this, TheCall, 2)) 1373 return ExprError(); 1374 // Ensure that the first argument is of type 'struct XX *' 1375 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1376 const QualType PtrArgType = PtrArg->getType(); 1377 if (!PtrArgType->isPointerType() || 1378 !PtrArgType->getPointeeType()->isRecordType()) { 1379 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1380 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1381 << "structure pointer"; 1382 return ExprError(); 1383 } 1384 1385 // Ensure that the second argument is of type 'FunctionType' 1386 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1387 const QualType FnPtrArgType = FnPtrArg->getType(); 1388 if (!FnPtrArgType->isPointerType()) { 1389 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1390 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1391 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1392 return ExprError(); 1393 } 1394 1395 const auto *FuncType = 1396 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1397 1398 if (!FuncType) { 1399 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1400 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1401 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1402 return ExprError(); 1403 } 1404 1405 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1406 if (!FT->getNumParams()) { 1407 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1408 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1409 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1410 return ExprError(); 1411 } 1412 QualType PT = FT->getParamType(0); 1413 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1414 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1415 !PT->getPointeeType().isConstQualified()) { 1416 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1417 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1418 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1419 return ExprError(); 1420 } 1421 } 1422 1423 TheCall->setType(Context.IntTy); 1424 break; 1425 } 1426 case Builtin::BI__builtin_preserve_access_index: 1427 if (SemaBuiltinPreserveAI(*this, TheCall)) 1428 return ExprError(); 1429 break; 1430 case Builtin::BI__builtin_call_with_static_chain: 1431 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1432 return ExprError(); 1433 break; 1434 case Builtin::BI__exception_code: 1435 case Builtin::BI_exception_code: 1436 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1437 diag::err_seh___except_block)) 1438 return ExprError(); 1439 break; 1440 case Builtin::BI__exception_info: 1441 case Builtin::BI_exception_info: 1442 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1443 diag::err_seh___except_filter)) 1444 return ExprError(); 1445 break; 1446 case Builtin::BI__GetExceptionInfo: 1447 if (checkArgCount(*this, TheCall, 1)) 1448 return ExprError(); 1449 1450 if (CheckCXXThrowOperand( 1451 TheCall->getBeginLoc(), 1452 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1453 TheCall)) 1454 return ExprError(); 1455 1456 TheCall->setType(Context.VoidPtrTy); 1457 break; 1458 // OpenCL v2.0, s6.13.16 - Pipe functions 1459 case Builtin::BIread_pipe: 1460 case Builtin::BIwrite_pipe: 1461 // Since those two functions are declared with var args, we need a semantic 1462 // check for the argument. 1463 if (SemaBuiltinRWPipe(*this, TheCall)) 1464 return ExprError(); 1465 break; 1466 case Builtin::BIreserve_read_pipe: 1467 case Builtin::BIreserve_write_pipe: 1468 case Builtin::BIwork_group_reserve_read_pipe: 1469 case Builtin::BIwork_group_reserve_write_pipe: 1470 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1471 return ExprError(); 1472 break; 1473 case Builtin::BIsub_group_reserve_read_pipe: 1474 case Builtin::BIsub_group_reserve_write_pipe: 1475 if (checkOpenCLSubgroupExt(*this, TheCall) || 1476 SemaBuiltinReserveRWPipe(*this, TheCall)) 1477 return ExprError(); 1478 break; 1479 case Builtin::BIcommit_read_pipe: 1480 case Builtin::BIcommit_write_pipe: 1481 case Builtin::BIwork_group_commit_read_pipe: 1482 case Builtin::BIwork_group_commit_write_pipe: 1483 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1484 return ExprError(); 1485 break; 1486 case Builtin::BIsub_group_commit_read_pipe: 1487 case Builtin::BIsub_group_commit_write_pipe: 1488 if (checkOpenCLSubgroupExt(*this, TheCall) || 1489 SemaBuiltinCommitRWPipe(*this, TheCall)) 1490 return ExprError(); 1491 break; 1492 case Builtin::BIget_pipe_num_packets: 1493 case Builtin::BIget_pipe_max_packets: 1494 if (SemaBuiltinPipePackets(*this, TheCall)) 1495 return ExprError(); 1496 break; 1497 case Builtin::BIto_global: 1498 case Builtin::BIto_local: 1499 case Builtin::BIto_private: 1500 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1501 return ExprError(); 1502 break; 1503 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1504 case Builtin::BIenqueue_kernel: 1505 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1506 return ExprError(); 1507 break; 1508 case Builtin::BIget_kernel_work_group_size: 1509 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1510 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1511 return ExprError(); 1512 break; 1513 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1514 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1515 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1516 return ExprError(); 1517 break; 1518 case Builtin::BI__builtin_os_log_format: 1519 case Builtin::BI__builtin_os_log_format_buffer_size: 1520 if (SemaBuiltinOSLogFormat(TheCall)) 1521 return ExprError(); 1522 break; 1523 } 1524 1525 // Since the target specific builtins for each arch overlap, only check those 1526 // of the arch we are compiling for. 1527 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1528 switch (Context.getTargetInfo().getTriple().getArch()) { 1529 case llvm::Triple::arm: 1530 case llvm::Triple::armeb: 1531 case llvm::Triple::thumb: 1532 case llvm::Triple::thumbeb: 1533 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1534 return ExprError(); 1535 break; 1536 case llvm::Triple::aarch64: 1537 case llvm::Triple::aarch64_be: 1538 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1539 return ExprError(); 1540 break; 1541 case llvm::Triple::hexagon: 1542 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1543 return ExprError(); 1544 break; 1545 case llvm::Triple::mips: 1546 case llvm::Triple::mipsel: 1547 case llvm::Triple::mips64: 1548 case llvm::Triple::mips64el: 1549 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1550 return ExprError(); 1551 break; 1552 case llvm::Triple::systemz: 1553 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1554 return ExprError(); 1555 break; 1556 case llvm::Triple::x86: 1557 case llvm::Triple::x86_64: 1558 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1559 return ExprError(); 1560 break; 1561 case llvm::Triple::ppc: 1562 case llvm::Triple::ppc64: 1563 case llvm::Triple::ppc64le: 1564 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1565 return ExprError(); 1566 break; 1567 default: 1568 break; 1569 } 1570 } 1571 1572 return TheCallResult; 1573 } 1574 1575 // Get the valid immediate range for the specified NEON type code. 1576 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1577 NeonTypeFlags Type(t); 1578 int IsQuad = ForceQuad ? true : Type.isQuad(); 1579 switch (Type.getEltType()) { 1580 case NeonTypeFlags::Int8: 1581 case NeonTypeFlags::Poly8: 1582 return shift ? 7 : (8 << IsQuad) - 1; 1583 case NeonTypeFlags::Int16: 1584 case NeonTypeFlags::Poly16: 1585 return shift ? 15 : (4 << IsQuad) - 1; 1586 case NeonTypeFlags::Int32: 1587 return shift ? 31 : (2 << IsQuad) - 1; 1588 case NeonTypeFlags::Int64: 1589 case NeonTypeFlags::Poly64: 1590 return shift ? 63 : (1 << IsQuad) - 1; 1591 case NeonTypeFlags::Poly128: 1592 return shift ? 127 : (1 << IsQuad) - 1; 1593 case NeonTypeFlags::Float16: 1594 assert(!shift && "cannot shift float types!"); 1595 return (4 << IsQuad) - 1; 1596 case NeonTypeFlags::Float32: 1597 assert(!shift && "cannot shift float types!"); 1598 return (2 << IsQuad) - 1; 1599 case NeonTypeFlags::Float64: 1600 assert(!shift && "cannot shift float types!"); 1601 return (1 << IsQuad) - 1; 1602 } 1603 llvm_unreachable("Invalid NeonTypeFlag!"); 1604 } 1605 1606 /// getNeonEltType - Return the QualType corresponding to the elements of 1607 /// the vector type specified by the NeonTypeFlags. This is used to check 1608 /// the pointer arguments for Neon load/store intrinsics. 1609 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1610 bool IsPolyUnsigned, bool IsInt64Long) { 1611 switch (Flags.getEltType()) { 1612 case NeonTypeFlags::Int8: 1613 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1614 case NeonTypeFlags::Int16: 1615 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1616 case NeonTypeFlags::Int32: 1617 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1618 case NeonTypeFlags::Int64: 1619 if (IsInt64Long) 1620 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1621 else 1622 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1623 : Context.LongLongTy; 1624 case NeonTypeFlags::Poly8: 1625 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1626 case NeonTypeFlags::Poly16: 1627 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1628 case NeonTypeFlags::Poly64: 1629 if (IsInt64Long) 1630 return Context.UnsignedLongTy; 1631 else 1632 return Context.UnsignedLongLongTy; 1633 case NeonTypeFlags::Poly128: 1634 break; 1635 case NeonTypeFlags::Float16: 1636 return Context.HalfTy; 1637 case NeonTypeFlags::Float32: 1638 return Context.FloatTy; 1639 case NeonTypeFlags::Float64: 1640 return Context.DoubleTy; 1641 } 1642 llvm_unreachable("Invalid NeonTypeFlag!"); 1643 } 1644 1645 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1646 llvm::APSInt Result; 1647 uint64_t mask = 0; 1648 unsigned TV = 0; 1649 int PtrArgNum = -1; 1650 bool HasConstPtr = false; 1651 switch (BuiltinID) { 1652 #define GET_NEON_OVERLOAD_CHECK 1653 #include "clang/Basic/arm_neon.inc" 1654 #include "clang/Basic/arm_fp16.inc" 1655 #undef GET_NEON_OVERLOAD_CHECK 1656 } 1657 1658 // For NEON intrinsics which are overloaded on vector element type, validate 1659 // the immediate which specifies which variant to emit. 1660 unsigned ImmArg = TheCall->getNumArgs()-1; 1661 if (mask) { 1662 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1663 return true; 1664 1665 TV = Result.getLimitedValue(64); 1666 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1667 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1668 << TheCall->getArg(ImmArg)->getSourceRange(); 1669 } 1670 1671 if (PtrArgNum >= 0) { 1672 // Check that pointer arguments have the specified type. 1673 Expr *Arg = TheCall->getArg(PtrArgNum); 1674 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1675 Arg = ICE->getSubExpr(); 1676 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1677 QualType RHSTy = RHS.get()->getType(); 1678 1679 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1680 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1681 Arch == llvm::Triple::aarch64_be; 1682 bool IsInt64Long = 1683 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1684 QualType EltTy = 1685 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1686 if (HasConstPtr) 1687 EltTy = EltTy.withConst(); 1688 QualType LHSTy = Context.getPointerType(EltTy); 1689 AssignConvertType ConvTy; 1690 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1691 if (RHS.isInvalid()) 1692 return true; 1693 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1694 RHS.get(), AA_Assigning)) 1695 return true; 1696 } 1697 1698 // For NEON intrinsics which take an immediate value as part of the 1699 // instruction, range check them here. 1700 unsigned i = 0, l = 0, u = 0; 1701 switch (BuiltinID) { 1702 default: 1703 return false; 1704 #define GET_NEON_IMMEDIATE_CHECK 1705 #include "clang/Basic/arm_neon.inc" 1706 #include "clang/Basic/arm_fp16.inc" 1707 #undef GET_NEON_IMMEDIATE_CHECK 1708 } 1709 1710 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1711 } 1712 1713 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1714 unsigned MaxWidth) { 1715 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1716 BuiltinID == ARM::BI__builtin_arm_ldaex || 1717 BuiltinID == ARM::BI__builtin_arm_strex || 1718 BuiltinID == ARM::BI__builtin_arm_stlex || 1719 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1720 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1721 BuiltinID == AArch64::BI__builtin_arm_strex || 1722 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1723 "unexpected ARM builtin"); 1724 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1725 BuiltinID == ARM::BI__builtin_arm_ldaex || 1726 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1727 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1728 1729 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1730 1731 // Ensure that we have the proper number of arguments. 1732 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1733 return true; 1734 1735 // Inspect the pointer argument of the atomic builtin. This should always be 1736 // a pointer type, whose element is an integral scalar or pointer type. 1737 // Because it is a pointer type, we don't have to worry about any implicit 1738 // casts here. 1739 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1740 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1741 if (PointerArgRes.isInvalid()) 1742 return true; 1743 PointerArg = PointerArgRes.get(); 1744 1745 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1746 if (!pointerType) { 1747 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1748 << PointerArg->getType() << PointerArg->getSourceRange(); 1749 return true; 1750 } 1751 1752 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1753 // task is to insert the appropriate casts into the AST. First work out just 1754 // what the appropriate type is. 1755 QualType ValType = pointerType->getPointeeType(); 1756 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1757 if (IsLdrex) 1758 AddrType.addConst(); 1759 1760 // Issue a warning if the cast is dodgy. 1761 CastKind CastNeeded = CK_NoOp; 1762 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1763 CastNeeded = CK_BitCast; 1764 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1765 << PointerArg->getType() << Context.getPointerType(AddrType) 1766 << AA_Passing << PointerArg->getSourceRange(); 1767 } 1768 1769 // Finally, do the cast and replace the argument with the corrected version. 1770 AddrType = Context.getPointerType(AddrType); 1771 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1772 if (PointerArgRes.isInvalid()) 1773 return true; 1774 PointerArg = PointerArgRes.get(); 1775 1776 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1777 1778 // In general, we allow ints, floats and pointers to be loaded and stored. 1779 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1780 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1781 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1782 << PointerArg->getType() << PointerArg->getSourceRange(); 1783 return true; 1784 } 1785 1786 // But ARM doesn't have instructions to deal with 128-bit versions. 1787 if (Context.getTypeSize(ValType) > MaxWidth) { 1788 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1789 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1790 << PointerArg->getType() << PointerArg->getSourceRange(); 1791 return true; 1792 } 1793 1794 switch (ValType.getObjCLifetime()) { 1795 case Qualifiers::OCL_None: 1796 case Qualifiers::OCL_ExplicitNone: 1797 // okay 1798 break; 1799 1800 case Qualifiers::OCL_Weak: 1801 case Qualifiers::OCL_Strong: 1802 case Qualifiers::OCL_Autoreleasing: 1803 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1804 << ValType << PointerArg->getSourceRange(); 1805 return true; 1806 } 1807 1808 if (IsLdrex) { 1809 TheCall->setType(ValType); 1810 return false; 1811 } 1812 1813 // Initialize the argument to be stored. 1814 ExprResult ValArg = TheCall->getArg(0); 1815 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1816 Context, ValType, /*consume*/ false); 1817 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1818 if (ValArg.isInvalid()) 1819 return true; 1820 TheCall->setArg(0, ValArg.get()); 1821 1822 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1823 // but the custom checker bypasses all default analysis. 1824 TheCall->setType(Context.IntTy); 1825 return false; 1826 } 1827 1828 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1829 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1830 BuiltinID == ARM::BI__builtin_arm_ldaex || 1831 BuiltinID == ARM::BI__builtin_arm_strex || 1832 BuiltinID == ARM::BI__builtin_arm_stlex) { 1833 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1834 } 1835 1836 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1837 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1838 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1839 } 1840 1841 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1842 BuiltinID == ARM::BI__builtin_arm_wsr64) 1843 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1844 1845 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1846 BuiltinID == ARM::BI__builtin_arm_rsrp || 1847 BuiltinID == ARM::BI__builtin_arm_wsr || 1848 BuiltinID == ARM::BI__builtin_arm_wsrp) 1849 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1850 1851 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1852 return true; 1853 1854 // For intrinsics which take an immediate value as part of the instruction, 1855 // range check them here. 1856 // FIXME: VFP Intrinsics should error if VFP not present. 1857 switch (BuiltinID) { 1858 default: return false; 1859 case ARM::BI__builtin_arm_ssat: 1860 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1861 case ARM::BI__builtin_arm_usat: 1862 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1863 case ARM::BI__builtin_arm_ssat16: 1864 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1865 case ARM::BI__builtin_arm_usat16: 1866 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1867 case ARM::BI__builtin_arm_vcvtr_f: 1868 case ARM::BI__builtin_arm_vcvtr_d: 1869 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1870 case ARM::BI__builtin_arm_dmb: 1871 case ARM::BI__builtin_arm_dsb: 1872 case ARM::BI__builtin_arm_isb: 1873 case ARM::BI__builtin_arm_dbg: 1874 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1875 } 1876 } 1877 1878 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1879 CallExpr *TheCall) { 1880 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1881 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1882 BuiltinID == AArch64::BI__builtin_arm_strex || 1883 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1884 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1885 } 1886 1887 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1888 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1889 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1890 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1891 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1892 } 1893 1894 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1895 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1896 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1897 1898 // Memory Tagging Extensions (MTE) Intrinsics 1899 if (BuiltinID == AArch64::BI__builtin_arm_irg || 1900 BuiltinID == AArch64::BI__builtin_arm_addg || 1901 BuiltinID == AArch64::BI__builtin_arm_gmi || 1902 BuiltinID == AArch64::BI__builtin_arm_ldg || 1903 BuiltinID == AArch64::BI__builtin_arm_stg || 1904 BuiltinID == AArch64::BI__builtin_arm_subp) { 1905 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 1906 } 1907 1908 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1909 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1910 BuiltinID == AArch64::BI__builtin_arm_wsr || 1911 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1912 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1913 1914 // Only check the valid encoding range. Any constant in this range would be 1915 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 1916 // an exception for incorrect registers. This matches MSVC behavior. 1917 if (BuiltinID == AArch64::BI_ReadStatusReg || 1918 BuiltinID == AArch64::BI_WriteStatusReg) 1919 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 1920 1921 if (BuiltinID == AArch64::BI__getReg) 1922 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1923 1924 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1925 return true; 1926 1927 // For intrinsics which take an immediate value as part of the instruction, 1928 // range check them here. 1929 unsigned i = 0, l = 0, u = 0; 1930 switch (BuiltinID) { 1931 default: return false; 1932 case AArch64::BI__builtin_arm_dmb: 1933 case AArch64::BI__builtin_arm_dsb: 1934 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1935 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 1936 } 1937 1938 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1939 } 1940 1941 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1942 struct BuiltinAndString { 1943 unsigned BuiltinID; 1944 const char *Str; 1945 }; 1946 1947 static BuiltinAndString ValidCPU[] = { 1948 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" }, 1949 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" }, 1950 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" }, 1951 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" }, 1952 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" }, 1953 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" }, 1954 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" }, 1955 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" }, 1956 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" }, 1957 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" }, 1958 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" }, 1959 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" }, 1960 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" }, 1961 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" }, 1962 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" }, 1963 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" }, 1964 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" }, 1965 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" }, 1966 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" }, 1967 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" }, 1968 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" }, 1969 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" }, 1970 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" }, 1971 }; 1972 1973 static BuiltinAndString ValidHVX[] = { 1974 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" }, 2526 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" }, 2527 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" }, 2528 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" }, 2529 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" }, 2530 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" }, 2531 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" }, 2532 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" }, 2533 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" }, 2534 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" }, 2535 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" }, 2536 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" }, 2537 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" }, 2538 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" }, 2539 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" }, 2540 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" }, 2541 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" }, 2542 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, 2543 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, 2544 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, 2545 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, 2546 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" }, 2547 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" }, 2548 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" }, 2549 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" }, 2550 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" }, 2551 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" }, 2552 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" }, 2553 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" }, 2554 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" }, 2555 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" }, 2556 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" }, 2557 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" }, 2558 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" }, 2559 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" }, 2560 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" }, 2561 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" }, 2562 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" }, 2563 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" }, 2564 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" }, 2565 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" }, 2566 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" }, 2567 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" }, 2568 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" }, 2569 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" }, 2570 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, 2571 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, 2572 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, 2573 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, 2574 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" }, 2575 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" }, 2576 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" }, 2577 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" }, 2578 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" }, 2579 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" }, 2580 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" }, 2581 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" }, 2582 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" }, 2583 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" }, 2584 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" }, 2585 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" }, 2586 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" }, 2587 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" }, 2588 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" }, 2589 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" }, 2590 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" }, 2591 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" }, 2592 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" }, 2593 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" }, 2594 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" }, 2595 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" }, 2596 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" }, 2597 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" }, 2598 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" }, 2599 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" }, 2600 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" }, 2601 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" }, 2602 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" }, 2603 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" }, 2604 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" }, 2605 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" }, 2606 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" }, 2607 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" }, 2608 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" }, 2609 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" }, 2610 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" }, 2611 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" }, 2612 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" }, 2613 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" }, 2614 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" }, 2615 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" }, 2616 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" }, 2617 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" }, 2618 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" }, 2619 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" }, 2620 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" }, 2621 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" }, 2622 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" }, 2623 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" }, 2624 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" }, 2625 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" }, 2626 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" }, 2627 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" }, 2628 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" }, 2629 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" }, 2630 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" }, 2631 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" }, 2632 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" }, 2633 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" }, 2634 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" }, 2635 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" }, 2636 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" }, 2637 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" }, 2638 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" }, 2639 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" }, 2640 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" }, 2641 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" }, 2642 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" }, 2643 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" }, 2644 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" }, 2645 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" }, 2646 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" }, 2647 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" }, 2648 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" }, 2649 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" }, 2650 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" }, 2651 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" }, 2652 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" }, 2653 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" }, 2654 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" }, 2655 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" }, 2656 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" }, 2657 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" }, 2658 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" }, 2659 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" }, 2660 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" }, 2661 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" }, 2662 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" }, 2663 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" }, 2664 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" }, 2665 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" }, 2666 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" }, 2667 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" }, 2668 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" }, 2669 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" }, 2670 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" }, 2671 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" }, 2672 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" }, 2673 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" }, 2674 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" }, 2675 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" }, 2676 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" }, 2677 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" }, 2678 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" }, 2679 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" }, 2680 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" }, 2681 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" }, 2682 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" }, 2683 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" }, 2684 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" }, 2685 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" }, 2686 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" }, 2687 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" }, 2688 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" }, 2689 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" }, 2690 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" }, 2691 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" }, 2692 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" }, 2693 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" }, 2694 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" }, 2695 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" }, 2696 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" }, 2697 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" }, 2698 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" }, 2699 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" }, 2700 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" }, 2701 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" }, 2702 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" }, 2703 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" }, 2704 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" }, 2705 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" }, 2706 }; 2707 2708 // Sort the tables on first execution so we can binary search them. 2709 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { 2710 return LHS.BuiltinID < RHS.BuiltinID; 2711 }; 2712 static const bool SortOnce = 2713 (llvm::sort(ValidCPU, SortCmp), 2714 llvm::sort(ValidHVX, SortCmp), true); 2715 (void)SortOnce; 2716 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { 2717 return BI.BuiltinID < BuiltinID; 2718 }; 2719 2720 const TargetInfo &TI = Context.getTargetInfo(); 2721 2722 const BuiltinAndString *FC = 2723 llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp); 2724 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { 2725 const TargetOptions &Opts = TI.getTargetOpts(); 2726 StringRef CPU = Opts.CPU; 2727 if (!CPU.empty()) { 2728 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2729 CPU.consume_front("hexagon"); 2730 SmallVector<StringRef, 3> CPUs; 2731 StringRef(FC->Str).split(CPUs, ','); 2732 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) 2733 return Diag(TheCall->getBeginLoc(), 2734 diag::err_hexagon_builtin_unsupported_cpu); 2735 } 2736 } 2737 2738 const BuiltinAndString *FH = 2739 llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp); 2740 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { 2741 if (!TI.hasFeature("hvx")) 2742 return Diag(TheCall->getBeginLoc(), 2743 diag::err_hexagon_builtin_requires_hvx); 2744 2745 SmallVector<StringRef, 3> HVXs; 2746 StringRef(FH->Str).split(HVXs, ','); 2747 bool IsValid = llvm::any_of(HVXs, 2748 [&TI] (StringRef V) { 2749 std::string F = "hvx" + V.str(); 2750 return TI.hasFeature(F); 2751 }); 2752 if (!IsValid) 2753 return Diag(TheCall->getBeginLoc(), 2754 diag::err_hexagon_builtin_unsupported_hvx); 2755 } 2756 2757 return false; 2758 } 2759 2760 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2761 struct ArgInfo { 2762 uint8_t OpNum; 2763 bool IsSigned; 2764 uint8_t BitWidth; 2765 uint8_t Align; 2766 }; 2767 struct BuiltinInfo { 2768 unsigned BuiltinID; 2769 ArgInfo Infos[2]; 2770 }; 2771 2772 static BuiltinInfo Infos[] = { 2773 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2774 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2775 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2776 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2777 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2778 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2779 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2780 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2781 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2782 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2783 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2784 2785 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2796 2797 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2849 {{ 1, false, 6, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2857 {{ 1, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2864 { 2, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2866 { 2, false, 6, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2868 { 3, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2870 { 3, false, 6, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2887 {{ 2, false, 4, 0 }, 2888 { 3, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2890 {{ 2, false, 4, 0 }, 2891 { 3, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2893 {{ 2, false, 4, 0 }, 2894 { 3, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2896 {{ 2, false, 4, 0 }, 2897 { 3, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2909 { 2, false, 5, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2911 { 2, false, 6, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2921 {{ 1, false, 4, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2924 {{ 1, false, 4, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2945 {{ 3, false, 1, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2948 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2950 {{ 3, false, 1, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2953 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2955 {{ 3, false, 1, 0 }} }, 2956 }; 2957 2958 // Use a dynamically initialized static to sort the table exactly once on 2959 // first run. 2960 static const bool SortOnce = 2961 (llvm::sort(Infos, 2962 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2963 return LHS.BuiltinID < RHS.BuiltinID; 2964 }), 2965 true); 2966 (void)SortOnce; 2967 2968 const BuiltinInfo *F = llvm::partition_point( 2969 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2970 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2971 return false; 2972 2973 bool Error = false; 2974 2975 for (const ArgInfo &A : F->Infos) { 2976 // Ignore empty ArgInfo elements. 2977 if (A.BitWidth == 0) 2978 continue; 2979 2980 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2981 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2982 if (!A.Align) { 2983 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2984 } else { 2985 unsigned M = 1 << A.Align; 2986 Min *= M; 2987 Max *= M; 2988 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2989 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2990 } 2991 } 2992 return Error; 2993 } 2994 2995 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2996 CallExpr *TheCall) { 2997 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2998 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2999 } 3000 3001 3002 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 3003 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3004 // ordering for DSP is unspecified. MSA is ordered by the data format used 3005 // by the underlying instruction i.e., df/m, df/n and then by size. 3006 // 3007 // FIXME: The size tests here should instead be tablegen'd along with the 3008 // definitions from include/clang/Basic/BuiltinsMips.def. 3009 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3010 // be too. 3011 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3012 unsigned i = 0, l = 0, u = 0, m = 0; 3013 switch (BuiltinID) { 3014 default: return false; 3015 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3016 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3017 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3018 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3019 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3020 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3021 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3022 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3023 // df/m field. 3024 // These intrinsics take an unsigned 3 bit immediate. 3025 case Mips::BI__builtin_msa_bclri_b: 3026 case Mips::BI__builtin_msa_bnegi_b: 3027 case Mips::BI__builtin_msa_bseti_b: 3028 case Mips::BI__builtin_msa_sat_s_b: 3029 case Mips::BI__builtin_msa_sat_u_b: 3030 case Mips::BI__builtin_msa_slli_b: 3031 case Mips::BI__builtin_msa_srai_b: 3032 case Mips::BI__builtin_msa_srari_b: 3033 case Mips::BI__builtin_msa_srli_b: 3034 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3035 case Mips::BI__builtin_msa_binsli_b: 3036 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3037 // These intrinsics take an unsigned 4 bit immediate. 3038 case Mips::BI__builtin_msa_bclri_h: 3039 case Mips::BI__builtin_msa_bnegi_h: 3040 case Mips::BI__builtin_msa_bseti_h: 3041 case Mips::BI__builtin_msa_sat_s_h: 3042 case Mips::BI__builtin_msa_sat_u_h: 3043 case Mips::BI__builtin_msa_slli_h: 3044 case Mips::BI__builtin_msa_srai_h: 3045 case Mips::BI__builtin_msa_srari_h: 3046 case Mips::BI__builtin_msa_srli_h: 3047 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3048 case Mips::BI__builtin_msa_binsli_h: 3049 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3050 // These intrinsics take an unsigned 5 bit immediate. 3051 // The first block of intrinsics actually have an unsigned 5 bit field, 3052 // not a df/n field. 3053 case Mips::BI__builtin_msa_cfcmsa: 3054 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3055 case Mips::BI__builtin_msa_clei_u_b: 3056 case Mips::BI__builtin_msa_clei_u_h: 3057 case Mips::BI__builtin_msa_clei_u_w: 3058 case Mips::BI__builtin_msa_clei_u_d: 3059 case Mips::BI__builtin_msa_clti_u_b: 3060 case Mips::BI__builtin_msa_clti_u_h: 3061 case Mips::BI__builtin_msa_clti_u_w: 3062 case Mips::BI__builtin_msa_clti_u_d: 3063 case Mips::BI__builtin_msa_maxi_u_b: 3064 case Mips::BI__builtin_msa_maxi_u_h: 3065 case Mips::BI__builtin_msa_maxi_u_w: 3066 case Mips::BI__builtin_msa_maxi_u_d: 3067 case Mips::BI__builtin_msa_mini_u_b: 3068 case Mips::BI__builtin_msa_mini_u_h: 3069 case Mips::BI__builtin_msa_mini_u_w: 3070 case Mips::BI__builtin_msa_mini_u_d: 3071 case Mips::BI__builtin_msa_addvi_b: 3072 case Mips::BI__builtin_msa_addvi_h: 3073 case Mips::BI__builtin_msa_addvi_w: 3074 case Mips::BI__builtin_msa_addvi_d: 3075 case Mips::BI__builtin_msa_bclri_w: 3076 case Mips::BI__builtin_msa_bnegi_w: 3077 case Mips::BI__builtin_msa_bseti_w: 3078 case Mips::BI__builtin_msa_sat_s_w: 3079 case Mips::BI__builtin_msa_sat_u_w: 3080 case Mips::BI__builtin_msa_slli_w: 3081 case Mips::BI__builtin_msa_srai_w: 3082 case Mips::BI__builtin_msa_srari_w: 3083 case Mips::BI__builtin_msa_srli_w: 3084 case Mips::BI__builtin_msa_srlri_w: 3085 case Mips::BI__builtin_msa_subvi_b: 3086 case Mips::BI__builtin_msa_subvi_h: 3087 case Mips::BI__builtin_msa_subvi_w: 3088 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3089 case Mips::BI__builtin_msa_binsli_w: 3090 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3091 // These intrinsics take an unsigned 6 bit immediate. 3092 case Mips::BI__builtin_msa_bclri_d: 3093 case Mips::BI__builtin_msa_bnegi_d: 3094 case Mips::BI__builtin_msa_bseti_d: 3095 case Mips::BI__builtin_msa_sat_s_d: 3096 case Mips::BI__builtin_msa_sat_u_d: 3097 case Mips::BI__builtin_msa_slli_d: 3098 case Mips::BI__builtin_msa_srai_d: 3099 case Mips::BI__builtin_msa_srari_d: 3100 case Mips::BI__builtin_msa_srli_d: 3101 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3102 case Mips::BI__builtin_msa_binsli_d: 3103 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3104 // These intrinsics take a signed 5 bit immediate. 3105 case Mips::BI__builtin_msa_ceqi_b: 3106 case Mips::BI__builtin_msa_ceqi_h: 3107 case Mips::BI__builtin_msa_ceqi_w: 3108 case Mips::BI__builtin_msa_ceqi_d: 3109 case Mips::BI__builtin_msa_clti_s_b: 3110 case Mips::BI__builtin_msa_clti_s_h: 3111 case Mips::BI__builtin_msa_clti_s_w: 3112 case Mips::BI__builtin_msa_clti_s_d: 3113 case Mips::BI__builtin_msa_clei_s_b: 3114 case Mips::BI__builtin_msa_clei_s_h: 3115 case Mips::BI__builtin_msa_clei_s_w: 3116 case Mips::BI__builtin_msa_clei_s_d: 3117 case Mips::BI__builtin_msa_maxi_s_b: 3118 case Mips::BI__builtin_msa_maxi_s_h: 3119 case Mips::BI__builtin_msa_maxi_s_w: 3120 case Mips::BI__builtin_msa_maxi_s_d: 3121 case Mips::BI__builtin_msa_mini_s_b: 3122 case Mips::BI__builtin_msa_mini_s_h: 3123 case Mips::BI__builtin_msa_mini_s_w: 3124 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3125 // These intrinsics take an unsigned 8 bit immediate. 3126 case Mips::BI__builtin_msa_andi_b: 3127 case Mips::BI__builtin_msa_nori_b: 3128 case Mips::BI__builtin_msa_ori_b: 3129 case Mips::BI__builtin_msa_shf_b: 3130 case Mips::BI__builtin_msa_shf_h: 3131 case Mips::BI__builtin_msa_shf_w: 3132 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3133 case Mips::BI__builtin_msa_bseli_b: 3134 case Mips::BI__builtin_msa_bmnzi_b: 3135 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3136 // df/n format 3137 // These intrinsics take an unsigned 4 bit immediate. 3138 case Mips::BI__builtin_msa_copy_s_b: 3139 case Mips::BI__builtin_msa_copy_u_b: 3140 case Mips::BI__builtin_msa_insve_b: 3141 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3142 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3143 // These intrinsics take an unsigned 3 bit immediate. 3144 case Mips::BI__builtin_msa_copy_s_h: 3145 case Mips::BI__builtin_msa_copy_u_h: 3146 case Mips::BI__builtin_msa_insve_h: 3147 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3148 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3149 // These intrinsics take an unsigned 2 bit immediate. 3150 case Mips::BI__builtin_msa_copy_s_w: 3151 case Mips::BI__builtin_msa_copy_u_w: 3152 case Mips::BI__builtin_msa_insve_w: 3153 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3154 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3155 // These intrinsics take an unsigned 1 bit immediate. 3156 case Mips::BI__builtin_msa_copy_s_d: 3157 case Mips::BI__builtin_msa_copy_u_d: 3158 case Mips::BI__builtin_msa_insve_d: 3159 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3160 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3161 // Memory offsets and immediate loads. 3162 // These intrinsics take a signed 10 bit immediate. 3163 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3164 case Mips::BI__builtin_msa_ldi_h: 3165 case Mips::BI__builtin_msa_ldi_w: 3166 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3167 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3168 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3169 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3170 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3171 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3172 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3173 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3174 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3175 } 3176 3177 if (!m) 3178 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3179 3180 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3181 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3182 } 3183 3184 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3185 unsigned i = 0, l = 0, u = 0; 3186 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3187 BuiltinID == PPC::BI__builtin_divdeu || 3188 BuiltinID == PPC::BI__builtin_bpermd; 3189 bool IsTarget64Bit = Context.getTargetInfo() 3190 .getTypeWidth(Context 3191 .getTargetInfo() 3192 .getIntPtrType()) == 64; 3193 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3194 BuiltinID == PPC::BI__builtin_divweu || 3195 BuiltinID == PPC::BI__builtin_divde || 3196 BuiltinID == PPC::BI__builtin_divdeu; 3197 3198 if (Is64BitBltin && !IsTarget64Bit) 3199 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3200 << TheCall->getSourceRange(); 3201 3202 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 3203 (BuiltinID == PPC::BI__builtin_bpermd && 3204 !Context.getTargetInfo().hasFeature("bpermd"))) 3205 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3206 << TheCall->getSourceRange(); 3207 3208 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3209 if (!Context.getTargetInfo().hasFeature("vsx")) 3210 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3211 << TheCall->getSourceRange(); 3212 return false; 3213 }; 3214 3215 switch (BuiltinID) { 3216 default: return false; 3217 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3218 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3219 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3220 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3221 case PPC::BI__builtin_tbegin: 3222 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3223 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3224 case PPC::BI__builtin_tabortwc: 3225 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3226 case PPC::BI__builtin_tabortwci: 3227 case PPC::BI__builtin_tabortdci: 3228 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3229 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3230 case PPC::BI__builtin_vsx_xxpermdi: 3231 case PPC::BI__builtin_vsx_xxsldwi: 3232 return SemaBuiltinVSX(TheCall); 3233 case PPC::BI__builtin_unpack_vector_int128: 3234 return SemaVSXCheck(TheCall) || 3235 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3236 case PPC::BI__builtin_pack_vector_int128: 3237 return SemaVSXCheck(TheCall); 3238 } 3239 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3240 } 3241 3242 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3243 CallExpr *TheCall) { 3244 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3245 Expr *Arg = TheCall->getArg(0); 3246 llvm::APSInt AbortCode(32); 3247 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3248 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3249 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3250 << Arg->getSourceRange(); 3251 } 3252 3253 // For intrinsics which take an immediate value as part of the instruction, 3254 // range check them here. 3255 unsigned i = 0, l = 0, u = 0; 3256 switch (BuiltinID) { 3257 default: return false; 3258 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3259 case SystemZ::BI__builtin_s390_verimb: 3260 case SystemZ::BI__builtin_s390_verimh: 3261 case SystemZ::BI__builtin_s390_verimf: 3262 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3263 case SystemZ::BI__builtin_s390_vfaeb: 3264 case SystemZ::BI__builtin_s390_vfaeh: 3265 case SystemZ::BI__builtin_s390_vfaef: 3266 case SystemZ::BI__builtin_s390_vfaebs: 3267 case SystemZ::BI__builtin_s390_vfaehs: 3268 case SystemZ::BI__builtin_s390_vfaefs: 3269 case SystemZ::BI__builtin_s390_vfaezb: 3270 case SystemZ::BI__builtin_s390_vfaezh: 3271 case SystemZ::BI__builtin_s390_vfaezf: 3272 case SystemZ::BI__builtin_s390_vfaezbs: 3273 case SystemZ::BI__builtin_s390_vfaezhs: 3274 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3275 case SystemZ::BI__builtin_s390_vfisb: 3276 case SystemZ::BI__builtin_s390_vfidb: 3277 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3278 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3279 case SystemZ::BI__builtin_s390_vftcisb: 3280 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3281 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3282 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3283 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3284 case SystemZ::BI__builtin_s390_vstrcb: 3285 case SystemZ::BI__builtin_s390_vstrch: 3286 case SystemZ::BI__builtin_s390_vstrcf: 3287 case SystemZ::BI__builtin_s390_vstrczb: 3288 case SystemZ::BI__builtin_s390_vstrczh: 3289 case SystemZ::BI__builtin_s390_vstrczf: 3290 case SystemZ::BI__builtin_s390_vstrcbs: 3291 case SystemZ::BI__builtin_s390_vstrchs: 3292 case SystemZ::BI__builtin_s390_vstrcfs: 3293 case SystemZ::BI__builtin_s390_vstrczbs: 3294 case SystemZ::BI__builtin_s390_vstrczhs: 3295 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3296 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3297 case SystemZ::BI__builtin_s390_vfminsb: 3298 case SystemZ::BI__builtin_s390_vfmaxsb: 3299 case SystemZ::BI__builtin_s390_vfmindb: 3300 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3301 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3302 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3303 } 3304 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3305 } 3306 3307 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3308 /// This checks that the target supports __builtin_cpu_supports and 3309 /// that the string argument is constant and valid. 3310 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3311 Expr *Arg = TheCall->getArg(0); 3312 3313 // Check if the argument is a string literal. 3314 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3315 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3316 << Arg->getSourceRange(); 3317 3318 // Check the contents of the string. 3319 StringRef Feature = 3320 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3321 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3322 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3323 << Arg->getSourceRange(); 3324 return false; 3325 } 3326 3327 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3328 /// This checks that the target supports __builtin_cpu_is and 3329 /// that the string argument is constant and valid. 3330 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3331 Expr *Arg = TheCall->getArg(0); 3332 3333 // Check if the argument is a string literal. 3334 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3335 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3336 << Arg->getSourceRange(); 3337 3338 // Check the contents of the string. 3339 StringRef Feature = 3340 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3341 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3342 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3343 << Arg->getSourceRange(); 3344 return false; 3345 } 3346 3347 // Check if the rounding mode is legal. 3348 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3349 // Indicates if this instruction has rounding control or just SAE. 3350 bool HasRC = false; 3351 3352 unsigned ArgNum = 0; 3353 switch (BuiltinID) { 3354 default: 3355 return false; 3356 case X86::BI__builtin_ia32_vcvttsd2si32: 3357 case X86::BI__builtin_ia32_vcvttsd2si64: 3358 case X86::BI__builtin_ia32_vcvttsd2usi32: 3359 case X86::BI__builtin_ia32_vcvttsd2usi64: 3360 case X86::BI__builtin_ia32_vcvttss2si32: 3361 case X86::BI__builtin_ia32_vcvttss2si64: 3362 case X86::BI__builtin_ia32_vcvttss2usi32: 3363 case X86::BI__builtin_ia32_vcvttss2usi64: 3364 ArgNum = 1; 3365 break; 3366 case X86::BI__builtin_ia32_maxpd512: 3367 case X86::BI__builtin_ia32_maxps512: 3368 case X86::BI__builtin_ia32_minpd512: 3369 case X86::BI__builtin_ia32_minps512: 3370 ArgNum = 2; 3371 break; 3372 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3373 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3374 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3375 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3376 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3377 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3378 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3379 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3380 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3381 case X86::BI__builtin_ia32_exp2pd_mask: 3382 case X86::BI__builtin_ia32_exp2ps_mask: 3383 case X86::BI__builtin_ia32_getexppd512_mask: 3384 case X86::BI__builtin_ia32_getexpps512_mask: 3385 case X86::BI__builtin_ia32_rcp28pd_mask: 3386 case X86::BI__builtin_ia32_rcp28ps_mask: 3387 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3388 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3389 case X86::BI__builtin_ia32_vcomisd: 3390 case X86::BI__builtin_ia32_vcomiss: 3391 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3392 ArgNum = 3; 3393 break; 3394 case X86::BI__builtin_ia32_cmppd512_mask: 3395 case X86::BI__builtin_ia32_cmpps512_mask: 3396 case X86::BI__builtin_ia32_cmpsd_mask: 3397 case X86::BI__builtin_ia32_cmpss_mask: 3398 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3399 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3400 case X86::BI__builtin_ia32_getexpss128_round_mask: 3401 case X86::BI__builtin_ia32_getmantpd512_mask: 3402 case X86::BI__builtin_ia32_getmantps512_mask: 3403 case X86::BI__builtin_ia32_maxsd_round_mask: 3404 case X86::BI__builtin_ia32_maxss_round_mask: 3405 case X86::BI__builtin_ia32_minsd_round_mask: 3406 case X86::BI__builtin_ia32_minss_round_mask: 3407 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3408 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3409 case X86::BI__builtin_ia32_reducepd512_mask: 3410 case X86::BI__builtin_ia32_reduceps512_mask: 3411 case X86::BI__builtin_ia32_rndscalepd_mask: 3412 case X86::BI__builtin_ia32_rndscaleps_mask: 3413 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3414 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3415 ArgNum = 4; 3416 break; 3417 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3418 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3419 case X86::BI__builtin_ia32_fixupimmps512_mask: 3420 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3421 case X86::BI__builtin_ia32_fixupimmsd_mask: 3422 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3423 case X86::BI__builtin_ia32_fixupimmss_mask: 3424 case X86::BI__builtin_ia32_fixupimmss_maskz: 3425 case X86::BI__builtin_ia32_getmantsd_round_mask: 3426 case X86::BI__builtin_ia32_getmantss_round_mask: 3427 case X86::BI__builtin_ia32_rangepd512_mask: 3428 case X86::BI__builtin_ia32_rangeps512_mask: 3429 case X86::BI__builtin_ia32_rangesd128_round_mask: 3430 case X86::BI__builtin_ia32_rangess128_round_mask: 3431 case X86::BI__builtin_ia32_reducesd_mask: 3432 case X86::BI__builtin_ia32_reducess_mask: 3433 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3434 case X86::BI__builtin_ia32_rndscaless_round_mask: 3435 ArgNum = 5; 3436 break; 3437 case X86::BI__builtin_ia32_vcvtsd2si64: 3438 case X86::BI__builtin_ia32_vcvtsd2si32: 3439 case X86::BI__builtin_ia32_vcvtsd2usi32: 3440 case X86::BI__builtin_ia32_vcvtsd2usi64: 3441 case X86::BI__builtin_ia32_vcvtss2si32: 3442 case X86::BI__builtin_ia32_vcvtss2si64: 3443 case X86::BI__builtin_ia32_vcvtss2usi32: 3444 case X86::BI__builtin_ia32_vcvtss2usi64: 3445 case X86::BI__builtin_ia32_sqrtpd512: 3446 case X86::BI__builtin_ia32_sqrtps512: 3447 ArgNum = 1; 3448 HasRC = true; 3449 break; 3450 case X86::BI__builtin_ia32_addpd512: 3451 case X86::BI__builtin_ia32_addps512: 3452 case X86::BI__builtin_ia32_divpd512: 3453 case X86::BI__builtin_ia32_divps512: 3454 case X86::BI__builtin_ia32_mulpd512: 3455 case X86::BI__builtin_ia32_mulps512: 3456 case X86::BI__builtin_ia32_subpd512: 3457 case X86::BI__builtin_ia32_subps512: 3458 case X86::BI__builtin_ia32_cvtsi2sd64: 3459 case X86::BI__builtin_ia32_cvtsi2ss32: 3460 case X86::BI__builtin_ia32_cvtsi2ss64: 3461 case X86::BI__builtin_ia32_cvtusi2sd64: 3462 case X86::BI__builtin_ia32_cvtusi2ss32: 3463 case X86::BI__builtin_ia32_cvtusi2ss64: 3464 ArgNum = 2; 3465 HasRC = true; 3466 break; 3467 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3468 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3469 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3470 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3471 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3472 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3473 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3474 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3475 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3476 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3477 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3478 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3479 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3480 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3481 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3482 ArgNum = 3; 3483 HasRC = true; 3484 break; 3485 case X86::BI__builtin_ia32_addss_round_mask: 3486 case X86::BI__builtin_ia32_addsd_round_mask: 3487 case X86::BI__builtin_ia32_divss_round_mask: 3488 case X86::BI__builtin_ia32_divsd_round_mask: 3489 case X86::BI__builtin_ia32_mulss_round_mask: 3490 case X86::BI__builtin_ia32_mulsd_round_mask: 3491 case X86::BI__builtin_ia32_subss_round_mask: 3492 case X86::BI__builtin_ia32_subsd_round_mask: 3493 case X86::BI__builtin_ia32_scalefpd512_mask: 3494 case X86::BI__builtin_ia32_scalefps512_mask: 3495 case X86::BI__builtin_ia32_scalefsd_round_mask: 3496 case X86::BI__builtin_ia32_scalefss_round_mask: 3497 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3498 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3499 case X86::BI__builtin_ia32_sqrtss_round_mask: 3500 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3501 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3502 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3503 case X86::BI__builtin_ia32_vfmaddss3_mask: 3504 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3505 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3506 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3507 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3508 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3509 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3510 case X86::BI__builtin_ia32_vfmaddps512_mask: 3511 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3512 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3513 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3514 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3515 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3516 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3517 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3518 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3519 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3520 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3521 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3522 ArgNum = 4; 3523 HasRC = true; 3524 break; 3525 } 3526 3527 llvm::APSInt Result; 3528 3529 // We can't check the value of a dependent argument. 3530 Expr *Arg = TheCall->getArg(ArgNum); 3531 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3532 return false; 3533 3534 // Check constant-ness first. 3535 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3536 return true; 3537 3538 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3539 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3540 // combined with ROUND_NO_EXC. 3541 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3542 Result == 8/*ROUND_NO_EXC*/ || 3543 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3544 return false; 3545 3546 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3547 << Arg->getSourceRange(); 3548 } 3549 3550 // Check if the gather/scatter scale is legal. 3551 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3552 CallExpr *TheCall) { 3553 unsigned ArgNum = 0; 3554 switch (BuiltinID) { 3555 default: 3556 return false; 3557 case X86::BI__builtin_ia32_gatherpfdpd: 3558 case X86::BI__builtin_ia32_gatherpfdps: 3559 case X86::BI__builtin_ia32_gatherpfqpd: 3560 case X86::BI__builtin_ia32_gatherpfqps: 3561 case X86::BI__builtin_ia32_scatterpfdpd: 3562 case X86::BI__builtin_ia32_scatterpfdps: 3563 case X86::BI__builtin_ia32_scatterpfqpd: 3564 case X86::BI__builtin_ia32_scatterpfqps: 3565 ArgNum = 3; 3566 break; 3567 case X86::BI__builtin_ia32_gatherd_pd: 3568 case X86::BI__builtin_ia32_gatherd_pd256: 3569 case X86::BI__builtin_ia32_gatherq_pd: 3570 case X86::BI__builtin_ia32_gatherq_pd256: 3571 case X86::BI__builtin_ia32_gatherd_ps: 3572 case X86::BI__builtin_ia32_gatherd_ps256: 3573 case X86::BI__builtin_ia32_gatherq_ps: 3574 case X86::BI__builtin_ia32_gatherq_ps256: 3575 case X86::BI__builtin_ia32_gatherd_q: 3576 case X86::BI__builtin_ia32_gatherd_q256: 3577 case X86::BI__builtin_ia32_gatherq_q: 3578 case X86::BI__builtin_ia32_gatherq_q256: 3579 case X86::BI__builtin_ia32_gatherd_d: 3580 case X86::BI__builtin_ia32_gatherd_d256: 3581 case X86::BI__builtin_ia32_gatherq_d: 3582 case X86::BI__builtin_ia32_gatherq_d256: 3583 case X86::BI__builtin_ia32_gather3div2df: 3584 case X86::BI__builtin_ia32_gather3div2di: 3585 case X86::BI__builtin_ia32_gather3div4df: 3586 case X86::BI__builtin_ia32_gather3div4di: 3587 case X86::BI__builtin_ia32_gather3div4sf: 3588 case X86::BI__builtin_ia32_gather3div4si: 3589 case X86::BI__builtin_ia32_gather3div8sf: 3590 case X86::BI__builtin_ia32_gather3div8si: 3591 case X86::BI__builtin_ia32_gather3siv2df: 3592 case X86::BI__builtin_ia32_gather3siv2di: 3593 case X86::BI__builtin_ia32_gather3siv4df: 3594 case X86::BI__builtin_ia32_gather3siv4di: 3595 case X86::BI__builtin_ia32_gather3siv4sf: 3596 case X86::BI__builtin_ia32_gather3siv4si: 3597 case X86::BI__builtin_ia32_gather3siv8sf: 3598 case X86::BI__builtin_ia32_gather3siv8si: 3599 case X86::BI__builtin_ia32_gathersiv8df: 3600 case X86::BI__builtin_ia32_gathersiv16sf: 3601 case X86::BI__builtin_ia32_gatherdiv8df: 3602 case X86::BI__builtin_ia32_gatherdiv16sf: 3603 case X86::BI__builtin_ia32_gathersiv8di: 3604 case X86::BI__builtin_ia32_gathersiv16si: 3605 case X86::BI__builtin_ia32_gatherdiv8di: 3606 case X86::BI__builtin_ia32_gatherdiv16si: 3607 case X86::BI__builtin_ia32_scatterdiv2df: 3608 case X86::BI__builtin_ia32_scatterdiv2di: 3609 case X86::BI__builtin_ia32_scatterdiv4df: 3610 case X86::BI__builtin_ia32_scatterdiv4di: 3611 case X86::BI__builtin_ia32_scatterdiv4sf: 3612 case X86::BI__builtin_ia32_scatterdiv4si: 3613 case X86::BI__builtin_ia32_scatterdiv8sf: 3614 case X86::BI__builtin_ia32_scatterdiv8si: 3615 case X86::BI__builtin_ia32_scattersiv2df: 3616 case X86::BI__builtin_ia32_scattersiv2di: 3617 case X86::BI__builtin_ia32_scattersiv4df: 3618 case X86::BI__builtin_ia32_scattersiv4di: 3619 case X86::BI__builtin_ia32_scattersiv4sf: 3620 case X86::BI__builtin_ia32_scattersiv4si: 3621 case X86::BI__builtin_ia32_scattersiv8sf: 3622 case X86::BI__builtin_ia32_scattersiv8si: 3623 case X86::BI__builtin_ia32_scattersiv8df: 3624 case X86::BI__builtin_ia32_scattersiv16sf: 3625 case X86::BI__builtin_ia32_scatterdiv8df: 3626 case X86::BI__builtin_ia32_scatterdiv16sf: 3627 case X86::BI__builtin_ia32_scattersiv8di: 3628 case X86::BI__builtin_ia32_scattersiv16si: 3629 case X86::BI__builtin_ia32_scatterdiv8di: 3630 case X86::BI__builtin_ia32_scatterdiv16si: 3631 ArgNum = 4; 3632 break; 3633 } 3634 3635 llvm::APSInt Result; 3636 3637 // We can't check the value of a dependent argument. 3638 Expr *Arg = TheCall->getArg(ArgNum); 3639 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3640 return false; 3641 3642 // Check constant-ness first. 3643 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3644 return true; 3645 3646 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3647 return false; 3648 3649 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3650 << Arg->getSourceRange(); 3651 } 3652 3653 static bool isX86_32Builtin(unsigned BuiltinID) { 3654 // These builtins only work on x86-32 targets. 3655 switch (BuiltinID) { 3656 case X86::BI__builtin_ia32_readeflags_u32: 3657 case X86::BI__builtin_ia32_writeeflags_u32: 3658 return true; 3659 } 3660 3661 return false; 3662 } 3663 3664 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3665 if (BuiltinID == X86::BI__builtin_cpu_supports) 3666 return SemaBuiltinCpuSupports(*this, TheCall); 3667 3668 if (BuiltinID == X86::BI__builtin_cpu_is) 3669 return SemaBuiltinCpuIs(*this, TheCall); 3670 3671 // Check for 32-bit only builtins on a 64-bit target. 3672 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3673 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3674 return Diag(TheCall->getCallee()->getBeginLoc(), 3675 diag::err_32_bit_builtin_64_bit_tgt); 3676 3677 // If the intrinsic has rounding or SAE make sure its valid. 3678 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3679 return true; 3680 3681 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3682 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3683 return true; 3684 3685 // For intrinsics which take an immediate value as part of the instruction, 3686 // range check them here. 3687 int i = 0, l = 0, u = 0; 3688 switch (BuiltinID) { 3689 default: 3690 return false; 3691 case X86::BI__builtin_ia32_vec_ext_v2si: 3692 case X86::BI__builtin_ia32_vec_ext_v2di: 3693 case X86::BI__builtin_ia32_vextractf128_pd256: 3694 case X86::BI__builtin_ia32_vextractf128_ps256: 3695 case X86::BI__builtin_ia32_vextractf128_si256: 3696 case X86::BI__builtin_ia32_extract128i256: 3697 case X86::BI__builtin_ia32_extractf64x4_mask: 3698 case X86::BI__builtin_ia32_extracti64x4_mask: 3699 case X86::BI__builtin_ia32_extractf32x8_mask: 3700 case X86::BI__builtin_ia32_extracti32x8_mask: 3701 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3702 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3703 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3704 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3705 i = 1; l = 0; u = 1; 3706 break; 3707 case X86::BI__builtin_ia32_vec_set_v2di: 3708 case X86::BI__builtin_ia32_vinsertf128_pd256: 3709 case X86::BI__builtin_ia32_vinsertf128_ps256: 3710 case X86::BI__builtin_ia32_vinsertf128_si256: 3711 case X86::BI__builtin_ia32_insert128i256: 3712 case X86::BI__builtin_ia32_insertf32x8: 3713 case X86::BI__builtin_ia32_inserti32x8: 3714 case X86::BI__builtin_ia32_insertf64x4: 3715 case X86::BI__builtin_ia32_inserti64x4: 3716 case X86::BI__builtin_ia32_insertf64x2_256: 3717 case X86::BI__builtin_ia32_inserti64x2_256: 3718 case X86::BI__builtin_ia32_insertf32x4_256: 3719 case X86::BI__builtin_ia32_inserti32x4_256: 3720 i = 2; l = 0; u = 1; 3721 break; 3722 case X86::BI__builtin_ia32_vpermilpd: 3723 case X86::BI__builtin_ia32_vec_ext_v4hi: 3724 case X86::BI__builtin_ia32_vec_ext_v4si: 3725 case X86::BI__builtin_ia32_vec_ext_v4sf: 3726 case X86::BI__builtin_ia32_vec_ext_v4di: 3727 case X86::BI__builtin_ia32_extractf32x4_mask: 3728 case X86::BI__builtin_ia32_extracti32x4_mask: 3729 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3730 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3731 i = 1; l = 0; u = 3; 3732 break; 3733 case X86::BI_mm_prefetch: 3734 case X86::BI__builtin_ia32_vec_ext_v8hi: 3735 case X86::BI__builtin_ia32_vec_ext_v8si: 3736 i = 1; l = 0; u = 7; 3737 break; 3738 case X86::BI__builtin_ia32_sha1rnds4: 3739 case X86::BI__builtin_ia32_blendpd: 3740 case X86::BI__builtin_ia32_shufpd: 3741 case X86::BI__builtin_ia32_vec_set_v4hi: 3742 case X86::BI__builtin_ia32_vec_set_v4si: 3743 case X86::BI__builtin_ia32_vec_set_v4di: 3744 case X86::BI__builtin_ia32_shuf_f32x4_256: 3745 case X86::BI__builtin_ia32_shuf_f64x2_256: 3746 case X86::BI__builtin_ia32_shuf_i32x4_256: 3747 case X86::BI__builtin_ia32_shuf_i64x2_256: 3748 case X86::BI__builtin_ia32_insertf64x2_512: 3749 case X86::BI__builtin_ia32_inserti64x2_512: 3750 case X86::BI__builtin_ia32_insertf32x4: 3751 case X86::BI__builtin_ia32_inserti32x4: 3752 i = 2; l = 0; u = 3; 3753 break; 3754 case X86::BI__builtin_ia32_vpermil2pd: 3755 case X86::BI__builtin_ia32_vpermil2pd256: 3756 case X86::BI__builtin_ia32_vpermil2ps: 3757 case X86::BI__builtin_ia32_vpermil2ps256: 3758 i = 3; l = 0; u = 3; 3759 break; 3760 case X86::BI__builtin_ia32_cmpb128_mask: 3761 case X86::BI__builtin_ia32_cmpw128_mask: 3762 case X86::BI__builtin_ia32_cmpd128_mask: 3763 case X86::BI__builtin_ia32_cmpq128_mask: 3764 case X86::BI__builtin_ia32_cmpb256_mask: 3765 case X86::BI__builtin_ia32_cmpw256_mask: 3766 case X86::BI__builtin_ia32_cmpd256_mask: 3767 case X86::BI__builtin_ia32_cmpq256_mask: 3768 case X86::BI__builtin_ia32_cmpb512_mask: 3769 case X86::BI__builtin_ia32_cmpw512_mask: 3770 case X86::BI__builtin_ia32_cmpd512_mask: 3771 case X86::BI__builtin_ia32_cmpq512_mask: 3772 case X86::BI__builtin_ia32_ucmpb128_mask: 3773 case X86::BI__builtin_ia32_ucmpw128_mask: 3774 case X86::BI__builtin_ia32_ucmpd128_mask: 3775 case X86::BI__builtin_ia32_ucmpq128_mask: 3776 case X86::BI__builtin_ia32_ucmpb256_mask: 3777 case X86::BI__builtin_ia32_ucmpw256_mask: 3778 case X86::BI__builtin_ia32_ucmpd256_mask: 3779 case X86::BI__builtin_ia32_ucmpq256_mask: 3780 case X86::BI__builtin_ia32_ucmpb512_mask: 3781 case X86::BI__builtin_ia32_ucmpw512_mask: 3782 case X86::BI__builtin_ia32_ucmpd512_mask: 3783 case X86::BI__builtin_ia32_ucmpq512_mask: 3784 case X86::BI__builtin_ia32_vpcomub: 3785 case X86::BI__builtin_ia32_vpcomuw: 3786 case X86::BI__builtin_ia32_vpcomud: 3787 case X86::BI__builtin_ia32_vpcomuq: 3788 case X86::BI__builtin_ia32_vpcomb: 3789 case X86::BI__builtin_ia32_vpcomw: 3790 case X86::BI__builtin_ia32_vpcomd: 3791 case X86::BI__builtin_ia32_vpcomq: 3792 case X86::BI__builtin_ia32_vec_set_v8hi: 3793 case X86::BI__builtin_ia32_vec_set_v8si: 3794 i = 2; l = 0; u = 7; 3795 break; 3796 case X86::BI__builtin_ia32_vpermilpd256: 3797 case X86::BI__builtin_ia32_roundps: 3798 case X86::BI__builtin_ia32_roundpd: 3799 case X86::BI__builtin_ia32_roundps256: 3800 case X86::BI__builtin_ia32_roundpd256: 3801 case X86::BI__builtin_ia32_getmantpd128_mask: 3802 case X86::BI__builtin_ia32_getmantpd256_mask: 3803 case X86::BI__builtin_ia32_getmantps128_mask: 3804 case X86::BI__builtin_ia32_getmantps256_mask: 3805 case X86::BI__builtin_ia32_getmantpd512_mask: 3806 case X86::BI__builtin_ia32_getmantps512_mask: 3807 case X86::BI__builtin_ia32_vec_ext_v16qi: 3808 case X86::BI__builtin_ia32_vec_ext_v16hi: 3809 i = 1; l = 0; u = 15; 3810 break; 3811 case X86::BI__builtin_ia32_pblendd128: 3812 case X86::BI__builtin_ia32_blendps: 3813 case X86::BI__builtin_ia32_blendpd256: 3814 case X86::BI__builtin_ia32_shufpd256: 3815 case X86::BI__builtin_ia32_roundss: 3816 case X86::BI__builtin_ia32_roundsd: 3817 case X86::BI__builtin_ia32_rangepd128_mask: 3818 case X86::BI__builtin_ia32_rangepd256_mask: 3819 case X86::BI__builtin_ia32_rangepd512_mask: 3820 case X86::BI__builtin_ia32_rangeps128_mask: 3821 case X86::BI__builtin_ia32_rangeps256_mask: 3822 case X86::BI__builtin_ia32_rangeps512_mask: 3823 case X86::BI__builtin_ia32_getmantsd_round_mask: 3824 case X86::BI__builtin_ia32_getmantss_round_mask: 3825 case X86::BI__builtin_ia32_vec_set_v16qi: 3826 case X86::BI__builtin_ia32_vec_set_v16hi: 3827 i = 2; l = 0; u = 15; 3828 break; 3829 case X86::BI__builtin_ia32_vec_ext_v32qi: 3830 i = 1; l = 0; u = 31; 3831 break; 3832 case X86::BI__builtin_ia32_cmpps: 3833 case X86::BI__builtin_ia32_cmpss: 3834 case X86::BI__builtin_ia32_cmppd: 3835 case X86::BI__builtin_ia32_cmpsd: 3836 case X86::BI__builtin_ia32_cmpps256: 3837 case X86::BI__builtin_ia32_cmppd256: 3838 case X86::BI__builtin_ia32_cmpps128_mask: 3839 case X86::BI__builtin_ia32_cmppd128_mask: 3840 case X86::BI__builtin_ia32_cmpps256_mask: 3841 case X86::BI__builtin_ia32_cmppd256_mask: 3842 case X86::BI__builtin_ia32_cmpps512_mask: 3843 case X86::BI__builtin_ia32_cmppd512_mask: 3844 case X86::BI__builtin_ia32_cmpsd_mask: 3845 case X86::BI__builtin_ia32_cmpss_mask: 3846 case X86::BI__builtin_ia32_vec_set_v32qi: 3847 i = 2; l = 0; u = 31; 3848 break; 3849 case X86::BI__builtin_ia32_permdf256: 3850 case X86::BI__builtin_ia32_permdi256: 3851 case X86::BI__builtin_ia32_permdf512: 3852 case X86::BI__builtin_ia32_permdi512: 3853 case X86::BI__builtin_ia32_vpermilps: 3854 case X86::BI__builtin_ia32_vpermilps256: 3855 case X86::BI__builtin_ia32_vpermilpd512: 3856 case X86::BI__builtin_ia32_vpermilps512: 3857 case X86::BI__builtin_ia32_pshufd: 3858 case X86::BI__builtin_ia32_pshufd256: 3859 case X86::BI__builtin_ia32_pshufd512: 3860 case X86::BI__builtin_ia32_pshufhw: 3861 case X86::BI__builtin_ia32_pshufhw256: 3862 case X86::BI__builtin_ia32_pshufhw512: 3863 case X86::BI__builtin_ia32_pshuflw: 3864 case X86::BI__builtin_ia32_pshuflw256: 3865 case X86::BI__builtin_ia32_pshuflw512: 3866 case X86::BI__builtin_ia32_vcvtps2ph: 3867 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3868 case X86::BI__builtin_ia32_vcvtps2ph256: 3869 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3870 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3871 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3872 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3873 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3874 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3875 case X86::BI__builtin_ia32_rndscaleps_mask: 3876 case X86::BI__builtin_ia32_rndscalepd_mask: 3877 case X86::BI__builtin_ia32_reducepd128_mask: 3878 case X86::BI__builtin_ia32_reducepd256_mask: 3879 case X86::BI__builtin_ia32_reducepd512_mask: 3880 case X86::BI__builtin_ia32_reduceps128_mask: 3881 case X86::BI__builtin_ia32_reduceps256_mask: 3882 case X86::BI__builtin_ia32_reduceps512_mask: 3883 case X86::BI__builtin_ia32_prold512: 3884 case X86::BI__builtin_ia32_prolq512: 3885 case X86::BI__builtin_ia32_prold128: 3886 case X86::BI__builtin_ia32_prold256: 3887 case X86::BI__builtin_ia32_prolq128: 3888 case X86::BI__builtin_ia32_prolq256: 3889 case X86::BI__builtin_ia32_prord512: 3890 case X86::BI__builtin_ia32_prorq512: 3891 case X86::BI__builtin_ia32_prord128: 3892 case X86::BI__builtin_ia32_prord256: 3893 case X86::BI__builtin_ia32_prorq128: 3894 case X86::BI__builtin_ia32_prorq256: 3895 case X86::BI__builtin_ia32_fpclasspd128_mask: 3896 case X86::BI__builtin_ia32_fpclasspd256_mask: 3897 case X86::BI__builtin_ia32_fpclassps128_mask: 3898 case X86::BI__builtin_ia32_fpclassps256_mask: 3899 case X86::BI__builtin_ia32_fpclassps512_mask: 3900 case X86::BI__builtin_ia32_fpclasspd512_mask: 3901 case X86::BI__builtin_ia32_fpclasssd_mask: 3902 case X86::BI__builtin_ia32_fpclassss_mask: 3903 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3904 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3905 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3906 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3907 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3908 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3909 case X86::BI__builtin_ia32_kshiftliqi: 3910 case X86::BI__builtin_ia32_kshiftlihi: 3911 case X86::BI__builtin_ia32_kshiftlisi: 3912 case X86::BI__builtin_ia32_kshiftlidi: 3913 case X86::BI__builtin_ia32_kshiftriqi: 3914 case X86::BI__builtin_ia32_kshiftrihi: 3915 case X86::BI__builtin_ia32_kshiftrisi: 3916 case X86::BI__builtin_ia32_kshiftridi: 3917 i = 1; l = 0; u = 255; 3918 break; 3919 case X86::BI__builtin_ia32_vperm2f128_pd256: 3920 case X86::BI__builtin_ia32_vperm2f128_ps256: 3921 case X86::BI__builtin_ia32_vperm2f128_si256: 3922 case X86::BI__builtin_ia32_permti256: 3923 case X86::BI__builtin_ia32_pblendw128: 3924 case X86::BI__builtin_ia32_pblendw256: 3925 case X86::BI__builtin_ia32_blendps256: 3926 case X86::BI__builtin_ia32_pblendd256: 3927 case X86::BI__builtin_ia32_palignr128: 3928 case X86::BI__builtin_ia32_palignr256: 3929 case X86::BI__builtin_ia32_palignr512: 3930 case X86::BI__builtin_ia32_alignq512: 3931 case X86::BI__builtin_ia32_alignd512: 3932 case X86::BI__builtin_ia32_alignd128: 3933 case X86::BI__builtin_ia32_alignd256: 3934 case X86::BI__builtin_ia32_alignq128: 3935 case X86::BI__builtin_ia32_alignq256: 3936 case X86::BI__builtin_ia32_vcomisd: 3937 case X86::BI__builtin_ia32_vcomiss: 3938 case X86::BI__builtin_ia32_shuf_f32x4: 3939 case X86::BI__builtin_ia32_shuf_f64x2: 3940 case X86::BI__builtin_ia32_shuf_i32x4: 3941 case X86::BI__builtin_ia32_shuf_i64x2: 3942 case X86::BI__builtin_ia32_shufpd512: 3943 case X86::BI__builtin_ia32_shufps: 3944 case X86::BI__builtin_ia32_shufps256: 3945 case X86::BI__builtin_ia32_shufps512: 3946 case X86::BI__builtin_ia32_dbpsadbw128: 3947 case X86::BI__builtin_ia32_dbpsadbw256: 3948 case X86::BI__builtin_ia32_dbpsadbw512: 3949 case X86::BI__builtin_ia32_vpshldd128: 3950 case X86::BI__builtin_ia32_vpshldd256: 3951 case X86::BI__builtin_ia32_vpshldd512: 3952 case X86::BI__builtin_ia32_vpshldq128: 3953 case X86::BI__builtin_ia32_vpshldq256: 3954 case X86::BI__builtin_ia32_vpshldq512: 3955 case X86::BI__builtin_ia32_vpshldw128: 3956 case X86::BI__builtin_ia32_vpshldw256: 3957 case X86::BI__builtin_ia32_vpshldw512: 3958 case X86::BI__builtin_ia32_vpshrdd128: 3959 case X86::BI__builtin_ia32_vpshrdd256: 3960 case X86::BI__builtin_ia32_vpshrdd512: 3961 case X86::BI__builtin_ia32_vpshrdq128: 3962 case X86::BI__builtin_ia32_vpshrdq256: 3963 case X86::BI__builtin_ia32_vpshrdq512: 3964 case X86::BI__builtin_ia32_vpshrdw128: 3965 case X86::BI__builtin_ia32_vpshrdw256: 3966 case X86::BI__builtin_ia32_vpshrdw512: 3967 i = 2; l = 0; u = 255; 3968 break; 3969 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3970 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3971 case X86::BI__builtin_ia32_fixupimmps512_mask: 3972 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3973 case X86::BI__builtin_ia32_fixupimmsd_mask: 3974 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3975 case X86::BI__builtin_ia32_fixupimmss_mask: 3976 case X86::BI__builtin_ia32_fixupimmss_maskz: 3977 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3978 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3979 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3980 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3981 case X86::BI__builtin_ia32_fixupimmps128_mask: 3982 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3983 case X86::BI__builtin_ia32_fixupimmps256_mask: 3984 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3985 case X86::BI__builtin_ia32_pternlogd512_mask: 3986 case X86::BI__builtin_ia32_pternlogd512_maskz: 3987 case X86::BI__builtin_ia32_pternlogq512_mask: 3988 case X86::BI__builtin_ia32_pternlogq512_maskz: 3989 case X86::BI__builtin_ia32_pternlogd128_mask: 3990 case X86::BI__builtin_ia32_pternlogd128_maskz: 3991 case X86::BI__builtin_ia32_pternlogd256_mask: 3992 case X86::BI__builtin_ia32_pternlogd256_maskz: 3993 case X86::BI__builtin_ia32_pternlogq128_mask: 3994 case X86::BI__builtin_ia32_pternlogq128_maskz: 3995 case X86::BI__builtin_ia32_pternlogq256_mask: 3996 case X86::BI__builtin_ia32_pternlogq256_maskz: 3997 i = 3; l = 0; u = 255; 3998 break; 3999 case X86::BI__builtin_ia32_gatherpfdpd: 4000 case X86::BI__builtin_ia32_gatherpfdps: 4001 case X86::BI__builtin_ia32_gatherpfqpd: 4002 case X86::BI__builtin_ia32_gatherpfqps: 4003 case X86::BI__builtin_ia32_scatterpfdpd: 4004 case X86::BI__builtin_ia32_scatterpfdps: 4005 case X86::BI__builtin_ia32_scatterpfqpd: 4006 case X86::BI__builtin_ia32_scatterpfqps: 4007 i = 4; l = 2; u = 3; 4008 break; 4009 case X86::BI__builtin_ia32_reducesd_mask: 4010 case X86::BI__builtin_ia32_reducess_mask: 4011 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4012 case X86::BI__builtin_ia32_rndscaless_round_mask: 4013 i = 4; l = 0; u = 255; 4014 break; 4015 } 4016 4017 // Note that we don't force a hard error on the range check here, allowing 4018 // template-generated or macro-generated dead code to potentially have out-of- 4019 // range values. These need to code generate, but don't need to necessarily 4020 // make any sense. We use a warning that defaults to an error. 4021 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4022 } 4023 4024 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4025 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4026 /// Returns true when the format fits the function and the FormatStringInfo has 4027 /// been populated. 4028 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4029 FormatStringInfo *FSI) { 4030 FSI->HasVAListArg = Format->getFirstArg() == 0; 4031 FSI->FormatIdx = Format->getFormatIdx() - 1; 4032 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4033 4034 // The way the format attribute works in GCC, the implicit this argument 4035 // of member functions is counted. However, it doesn't appear in our own 4036 // lists, so decrement format_idx in that case. 4037 if (IsCXXMember) { 4038 if(FSI->FormatIdx == 0) 4039 return false; 4040 --FSI->FormatIdx; 4041 if (FSI->FirstDataArg != 0) 4042 --FSI->FirstDataArg; 4043 } 4044 return true; 4045 } 4046 4047 /// Checks if a the given expression evaluates to null. 4048 /// 4049 /// Returns true if the value evaluates to null. 4050 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4051 // If the expression has non-null type, it doesn't evaluate to null. 4052 if (auto nullability 4053 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4054 if (*nullability == NullabilityKind::NonNull) 4055 return false; 4056 } 4057 4058 // As a special case, transparent unions initialized with zero are 4059 // considered null for the purposes of the nonnull attribute. 4060 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4061 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4062 if (const CompoundLiteralExpr *CLE = 4063 dyn_cast<CompoundLiteralExpr>(Expr)) 4064 if (const InitListExpr *ILE = 4065 dyn_cast<InitListExpr>(CLE->getInitializer())) 4066 Expr = ILE->getInit(0); 4067 } 4068 4069 bool Result; 4070 return (!Expr->isValueDependent() && 4071 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4072 !Result); 4073 } 4074 4075 static void CheckNonNullArgument(Sema &S, 4076 const Expr *ArgExpr, 4077 SourceLocation CallSiteLoc) { 4078 if (CheckNonNullExpr(S, ArgExpr)) 4079 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4080 S.PDiag(diag::warn_null_arg) 4081 << ArgExpr->getSourceRange()); 4082 } 4083 4084 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4085 FormatStringInfo FSI; 4086 if ((GetFormatStringType(Format) == FST_NSString) && 4087 getFormatStringInfo(Format, false, &FSI)) { 4088 Idx = FSI.FormatIdx; 4089 return true; 4090 } 4091 return false; 4092 } 4093 4094 /// Diagnose use of %s directive in an NSString which is being passed 4095 /// as formatting string to formatting method. 4096 static void 4097 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4098 const NamedDecl *FDecl, 4099 Expr **Args, 4100 unsigned NumArgs) { 4101 unsigned Idx = 0; 4102 bool Format = false; 4103 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4104 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4105 Idx = 2; 4106 Format = true; 4107 } 4108 else 4109 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4110 if (S.GetFormatNSStringIdx(I, Idx)) { 4111 Format = true; 4112 break; 4113 } 4114 } 4115 if (!Format || NumArgs <= Idx) 4116 return; 4117 const Expr *FormatExpr = Args[Idx]; 4118 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4119 FormatExpr = CSCE->getSubExpr(); 4120 const StringLiteral *FormatString; 4121 if (const ObjCStringLiteral *OSL = 4122 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4123 FormatString = OSL->getString(); 4124 else 4125 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4126 if (!FormatString) 4127 return; 4128 if (S.FormatStringHasSArg(FormatString)) { 4129 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4130 << "%s" << 1 << 1; 4131 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4132 << FDecl->getDeclName(); 4133 } 4134 } 4135 4136 /// Determine whether the given type has a non-null nullability annotation. 4137 static bool isNonNullType(ASTContext &ctx, QualType type) { 4138 if (auto nullability = type->getNullability(ctx)) 4139 return *nullability == NullabilityKind::NonNull; 4140 4141 return false; 4142 } 4143 4144 static void CheckNonNullArguments(Sema &S, 4145 const NamedDecl *FDecl, 4146 const FunctionProtoType *Proto, 4147 ArrayRef<const Expr *> Args, 4148 SourceLocation CallSiteLoc) { 4149 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4150 4151 // Already checked by by constant evaluator. 4152 if (S.isConstantEvaluated()) 4153 return; 4154 // Check the attributes attached to the method/function itself. 4155 llvm::SmallBitVector NonNullArgs; 4156 if (FDecl) { 4157 // Handle the nonnull attribute on the function/method declaration itself. 4158 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4159 if (!NonNull->args_size()) { 4160 // Easy case: all pointer arguments are nonnull. 4161 for (const auto *Arg : Args) 4162 if (S.isValidPointerAttrType(Arg->getType())) 4163 CheckNonNullArgument(S, Arg, CallSiteLoc); 4164 return; 4165 } 4166 4167 for (const ParamIdx &Idx : NonNull->args()) { 4168 unsigned IdxAST = Idx.getASTIndex(); 4169 if (IdxAST >= Args.size()) 4170 continue; 4171 if (NonNullArgs.empty()) 4172 NonNullArgs.resize(Args.size()); 4173 NonNullArgs.set(IdxAST); 4174 } 4175 } 4176 } 4177 4178 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4179 // Handle the nonnull attribute on the parameters of the 4180 // function/method. 4181 ArrayRef<ParmVarDecl*> parms; 4182 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4183 parms = FD->parameters(); 4184 else 4185 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4186 4187 unsigned ParamIndex = 0; 4188 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4189 I != E; ++I, ++ParamIndex) { 4190 const ParmVarDecl *PVD = *I; 4191 if (PVD->hasAttr<NonNullAttr>() || 4192 isNonNullType(S.Context, PVD->getType())) { 4193 if (NonNullArgs.empty()) 4194 NonNullArgs.resize(Args.size()); 4195 4196 NonNullArgs.set(ParamIndex); 4197 } 4198 } 4199 } else { 4200 // If we have a non-function, non-method declaration but no 4201 // function prototype, try to dig out the function prototype. 4202 if (!Proto) { 4203 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4204 QualType type = VD->getType().getNonReferenceType(); 4205 if (auto pointerType = type->getAs<PointerType>()) 4206 type = pointerType->getPointeeType(); 4207 else if (auto blockType = type->getAs<BlockPointerType>()) 4208 type = blockType->getPointeeType(); 4209 // FIXME: data member pointers? 4210 4211 // Dig out the function prototype, if there is one. 4212 Proto = type->getAs<FunctionProtoType>(); 4213 } 4214 } 4215 4216 // Fill in non-null argument information from the nullability 4217 // information on the parameter types (if we have them). 4218 if (Proto) { 4219 unsigned Index = 0; 4220 for (auto paramType : Proto->getParamTypes()) { 4221 if (isNonNullType(S.Context, paramType)) { 4222 if (NonNullArgs.empty()) 4223 NonNullArgs.resize(Args.size()); 4224 4225 NonNullArgs.set(Index); 4226 } 4227 4228 ++Index; 4229 } 4230 } 4231 } 4232 4233 // Check for non-null arguments. 4234 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4235 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4236 if (NonNullArgs[ArgIndex]) 4237 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4238 } 4239 } 4240 4241 /// Handles the checks for format strings, non-POD arguments to vararg 4242 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4243 /// attributes. 4244 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4245 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4246 bool IsMemberFunction, SourceLocation Loc, 4247 SourceRange Range, VariadicCallType CallType) { 4248 // FIXME: We should check as much as we can in the template definition. 4249 if (CurContext->isDependentContext()) 4250 return; 4251 4252 // Printf and scanf checking. 4253 llvm::SmallBitVector CheckedVarArgs; 4254 if (FDecl) { 4255 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4256 // Only create vector if there are format attributes. 4257 CheckedVarArgs.resize(Args.size()); 4258 4259 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4260 CheckedVarArgs); 4261 } 4262 } 4263 4264 // Refuse POD arguments that weren't caught by the format string 4265 // checks above. 4266 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4267 if (CallType != VariadicDoesNotApply && 4268 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4269 unsigned NumParams = Proto ? Proto->getNumParams() 4270 : FDecl && isa<FunctionDecl>(FDecl) 4271 ? cast<FunctionDecl>(FDecl)->getNumParams() 4272 : FDecl && isa<ObjCMethodDecl>(FDecl) 4273 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4274 : 0; 4275 4276 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4277 // Args[ArgIdx] can be null in malformed code. 4278 if (const Expr *Arg = Args[ArgIdx]) { 4279 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4280 checkVariadicArgument(Arg, CallType); 4281 } 4282 } 4283 } 4284 4285 if (FDecl || Proto) { 4286 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4287 4288 // Type safety checking. 4289 if (FDecl) { 4290 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4291 CheckArgumentWithTypeTag(I, Args, Loc); 4292 } 4293 } 4294 4295 if (FD) 4296 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4297 } 4298 4299 /// CheckConstructorCall - Check a constructor call for correctness and safety 4300 /// properties not enforced by the C type system. 4301 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4302 ArrayRef<const Expr *> Args, 4303 const FunctionProtoType *Proto, 4304 SourceLocation Loc) { 4305 VariadicCallType CallType = 4306 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4307 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4308 Loc, SourceRange(), CallType); 4309 } 4310 4311 /// CheckFunctionCall - Check a direct function call for various correctness 4312 /// and safety properties not strictly enforced by the C type system. 4313 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4314 const FunctionProtoType *Proto) { 4315 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4316 isa<CXXMethodDecl>(FDecl); 4317 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4318 IsMemberOperatorCall; 4319 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4320 TheCall->getCallee()); 4321 Expr** Args = TheCall->getArgs(); 4322 unsigned NumArgs = TheCall->getNumArgs(); 4323 4324 Expr *ImplicitThis = nullptr; 4325 if (IsMemberOperatorCall) { 4326 // If this is a call to a member operator, hide the first argument 4327 // from checkCall. 4328 // FIXME: Our choice of AST representation here is less than ideal. 4329 ImplicitThis = Args[0]; 4330 ++Args; 4331 --NumArgs; 4332 } else if (IsMemberFunction) 4333 ImplicitThis = 4334 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4335 4336 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4337 IsMemberFunction, TheCall->getRParenLoc(), 4338 TheCall->getCallee()->getSourceRange(), CallType); 4339 4340 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4341 // None of the checks below are needed for functions that don't have 4342 // simple names (e.g., C++ conversion functions). 4343 if (!FnInfo) 4344 return false; 4345 4346 CheckAbsoluteValueFunction(TheCall, FDecl); 4347 CheckMaxUnsignedZero(TheCall, FDecl); 4348 4349 if (getLangOpts().ObjC) 4350 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4351 4352 unsigned CMId = FDecl->getMemoryFunctionKind(); 4353 if (CMId == 0) 4354 return false; 4355 4356 // Handle memory setting and copying functions. 4357 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4358 CheckStrlcpycatArguments(TheCall, FnInfo); 4359 else if (CMId == Builtin::BIstrncat) 4360 CheckStrncatArguments(TheCall, FnInfo); 4361 else 4362 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4363 4364 return false; 4365 } 4366 4367 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4368 ArrayRef<const Expr *> Args) { 4369 VariadicCallType CallType = 4370 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4371 4372 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4373 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4374 CallType); 4375 4376 return false; 4377 } 4378 4379 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4380 const FunctionProtoType *Proto) { 4381 QualType Ty; 4382 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4383 Ty = V->getType().getNonReferenceType(); 4384 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4385 Ty = F->getType().getNonReferenceType(); 4386 else 4387 return false; 4388 4389 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4390 !Ty->isFunctionProtoType()) 4391 return false; 4392 4393 VariadicCallType CallType; 4394 if (!Proto || !Proto->isVariadic()) { 4395 CallType = VariadicDoesNotApply; 4396 } else if (Ty->isBlockPointerType()) { 4397 CallType = VariadicBlock; 4398 } else { // Ty->isFunctionPointerType() 4399 CallType = VariadicFunction; 4400 } 4401 4402 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4403 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4404 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4405 TheCall->getCallee()->getSourceRange(), CallType); 4406 4407 return false; 4408 } 4409 4410 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4411 /// such as function pointers returned from functions. 4412 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4413 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4414 TheCall->getCallee()); 4415 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4416 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4417 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4418 TheCall->getCallee()->getSourceRange(), CallType); 4419 4420 return false; 4421 } 4422 4423 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4424 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4425 return false; 4426 4427 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4428 switch (Op) { 4429 case AtomicExpr::AO__c11_atomic_init: 4430 case AtomicExpr::AO__opencl_atomic_init: 4431 llvm_unreachable("There is no ordering argument for an init"); 4432 4433 case AtomicExpr::AO__c11_atomic_load: 4434 case AtomicExpr::AO__opencl_atomic_load: 4435 case AtomicExpr::AO__atomic_load_n: 4436 case AtomicExpr::AO__atomic_load: 4437 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4438 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4439 4440 case AtomicExpr::AO__c11_atomic_store: 4441 case AtomicExpr::AO__opencl_atomic_store: 4442 case AtomicExpr::AO__atomic_store: 4443 case AtomicExpr::AO__atomic_store_n: 4444 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4445 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4446 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4447 4448 default: 4449 return true; 4450 } 4451 } 4452 4453 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4454 AtomicExpr::AtomicOp Op) { 4455 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4456 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4457 4458 // All the non-OpenCL operations take one of the following forms. 4459 // The OpenCL operations take the __c11 forms with one extra argument for 4460 // synchronization scope. 4461 enum { 4462 // C __c11_atomic_init(A *, C) 4463 Init, 4464 4465 // C __c11_atomic_load(A *, int) 4466 Load, 4467 4468 // void __atomic_load(A *, CP, int) 4469 LoadCopy, 4470 4471 // void __atomic_store(A *, CP, int) 4472 Copy, 4473 4474 // C __c11_atomic_add(A *, M, int) 4475 Arithmetic, 4476 4477 // C __atomic_exchange_n(A *, CP, int) 4478 Xchg, 4479 4480 // void __atomic_exchange(A *, C *, CP, int) 4481 GNUXchg, 4482 4483 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4484 C11CmpXchg, 4485 4486 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4487 GNUCmpXchg 4488 } Form = Init; 4489 4490 const unsigned NumForm = GNUCmpXchg + 1; 4491 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4492 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4493 // where: 4494 // C is an appropriate type, 4495 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4496 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4497 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4498 // the int parameters are for orderings. 4499 4500 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4501 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4502 "need to update code for modified forms"); 4503 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4504 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4505 AtomicExpr::AO__atomic_load, 4506 "need to update code for modified C11 atomics"); 4507 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4508 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4509 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4510 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4511 IsOpenCL; 4512 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4513 Op == AtomicExpr::AO__atomic_store_n || 4514 Op == AtomicExpr::AO__atomic_exchange_n || 4515 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4516 bool IsAddSub = false; 4517 bool IsMinMax = false; 4518 4519 switch (Op) { 4520 case AtomicExpr::AO__c11_atomic_init: 4521 case AtomicExpr::AO__opencl_atomic_init: 4522 Form = Init; 4523 break; 4524 4525 case AtomicExpr::AO__c11_atomic_load: 4526 case AtomicExpr::AO__opencl_atomic_load: 4527 case AtomicExpr::AO__atomic_load_n: 4528 Form = Load; 4529 break; 4530 4531 case AtomicExpr::AO__atomic_load: 4532 Form = LoadCopy; 4533 break; 4534 4535 case AtomicExpr::AO__c11_atomic_store: 4536 case AtomicExpr::AO__opencl_atomic_store: 4537 case AtomicExpr::AO__atomic_store: 4538 case AtomicExpr::AO__atomic_store_n: 4539 Form = Copy; 4540 break; 4541 4542 case AtomicExpr::AO__c11_atomic_fetch_add: 4543 case AtomicExpr::AO__c11_atomic_fetch_sub: 4544 case AtomicExpr::AO__opencl_atomic_fetch_add: 4545 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4546 case AtomicExpr::AO__opencl_atomic_fetch_min: 4547 case AtomicExpr::AO__opencl_atomic_fetch_max: 4548 case AtomicExpr::AO__atomic_fetch_add: 4549 case AtomicExpr::AO__atomic_fetch_sub: 4550 case AtomicExpr::AO__atomic_add_fetch: 4551 case AtomicExpr::AO__atomic_sub_fetch: 4552 IsAddSub = true; 4553 LLVM_FALLTHROUGH; 4554 case AtomicExpr::AO__c11_atomic_fetch_and: 4555 case AtomicExpr::AO__c11_atomic_fetch_or: 4556 case AtomicExpr::AO__c11_atomic_fetch_xor: 4557 case AtomicExpr::AO__opencl_atomic_fetch_and: 4558 case AtomicExpr::AO__opencl_atomic_fetch_or: 4559 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4560 case AtomicExpr::AO__atomic_fetch_and: 4561 case AtomicExpr::AO__atomic_fetch_or: 4562 case AtomicExpr::AO__atomic_fetch_xor: 4563 case AtomicExpr::AO__atomic_fetch_nand: 4564 case AtomicExpr::AO__atomic_and_fetch: 4565 case AtomicExpr::AO__atomic_or_fetch: 4566 case AtomicExpr::AO__atomic_xor_fetch: 4567 case AtomicExpr::AO__atomic_nand_fetch: 4568 Form = Arithmetic; 4569 break; 4570 4571 case AtomicExpr::AO__atomic_fetch_min: 4572 case AtomicExpr::AO__atomic_fetch_max: 4573 IsMinMax = true; 4574 Form = Arithmetic; 4575 break; 4576 4577 case AtomicExpr::AO__c11_atomic_exchange: 4578 case AtomicExpr::AO__opencl_atomic_exchange: 4579 case AtomicExpr::AO__atomic_exchange_n: 4580 Form = Xchg; 4581 break; 4582 4583 case AtomicExpr::AO__atomic_exchange: 4584 Form = GNUXchg; 4585 break; 4586 4587 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4588 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4589 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4590 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4591 Form = C11CmpXchg; 4592 break; 4593 4594 case AtomicExpr::AO__atomic_compare_exchange: 4595 case AtomicExpr::AO__atomic_compare_exchange_n: 4596 Form = GNUCmpXchg; 4597 break; 4598 } 4599 4600 unsigned AdjustedNumArgs = NumArgs[Form]; 4601 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4602 ++AdjustedNumArgs; 4603 // Check we have the right number of arguments. 4604 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4605 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4606 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4607 << TheCall->getCallee()->getSourceRange(); 4608 return ExprError(); 4609 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4610 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4611 diag::err_typecheck_call_too_many_args) 4612 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4613 << TheCall->getCallee()->getSourceRange(); 4614 return ExprError(); 4615 } 4616 4617 // Inspect the first argument of the atomic operation. 4618 Expr *Ptr = TheCall->getArg(0); 4619 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4620 if (ConvertedPtr.isInvalid()) 4621 return ExprError(); 4622 4623 Ptr = ConvertedPtr.get(); 4624 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4625 if (!pointerType) { 4626 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4627 << Ptr->getType() << Ptr->getSourceRange(); 4628 return ExprError(); 4629 } 4630 4631 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4632 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4633 QualType ValType = AtomTy; // 'C' 4634 if (IsC11) { 4635 if (!AtomTy->isAtomicType()) { 4636 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4637 << Ptr->getType() << Ptr->getSourceRange(); 4638 return ExprError(); 4639 } 4640 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4641 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4642 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4643 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4644 << Ptr->getSourceRange(); 4645 return ExprError(); 4646 } 4647 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4648 } else if (Form != Load && Form != LoadCopy) { 4649 if (ValType.isConstQualified()) { 4650 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4651 << Ptr->getType() << Ptr->getSourceRange(); 4652 return ExprError(); 4653 } 4654 } 4655 4656 // For an arithmetic operation, the implied arithmetic must be well-formed. 4657 if (Form == Arithmetic) { 4658 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4659 if (IsAddSub && !ValType->isIntegerType() 4660 && !ValType->isPointerType()) { 4661 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4662 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4663 return ExprError(); 4664 } 4665 if (IsMinMax) { 4666 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4667 if (!BT || (BT->getKind() != BuiltinType::Int && 4668 BT->getKind() != BuiltinType::UInt)) { 4669 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4670 return ExprError(); 4671 } 4672 } 4673 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4674 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4675 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4676 return ExprError(); 4677 } 4678 if (IsC11 && ValType->isPointerType() && 4679 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4680 diag::err_incomplete_type)) { 4681 return ExprError(); 4682 } 4683 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4684 // For __atomic_*_n operations, the value type must be a scalar integral or 4685 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4686 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4687 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4688 return ExprError(); 4689 } 4690 4691 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4692 !AtomTy->isScalarType()) { 4693 // For GNU atomics, require a trivially-copyable type. This is not part of 4694 // the GNU atomics specification, but we enforce it for sanity. 4695 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4696 << Ptr->getType() << Ptr->getSourceRange(); 4697 return ExprError(); 4698 } 4699 4700 switch (ValType.getObjCLifetime()) { 4701 case Qualifiers::OCL_None: 4702 case Qualifiers::OCL_ExplicitNone: 4703 // okay 4704 break; 4705 4706 case Qualifiers::OCL_Weak: 4707 case Qualifiers::OCL_Strong: 4708 case Qualifiers::OCL_Autoreleasing: 4709 // FIXME: Can this happen? By this point, ValType should be known 4710 // to be trivially copyable. 4711 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4712 << ValType << Ptr->getSourceRange(); 4713 return ExprError(); 4714 } 4715 4716 // All atomic operations have an overload which takes a pointer to a volatile 4717 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4718 // into the result or the other operands. Similarly atomic_load takes a 4719 // pointer to a const 'A'. 4720 ValType.removeLocalVolatile(); 4721 ValType.removeLocalConst(); 4722 QualType ResultType = ValType; 4723 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4724 Form == Init) 4725 ResultType = Context.VoidTy; 4726 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4727 ResultType = Context.BoolTy; 4728 4729 // The type of a parameter passed 'by value'. In the GNU atomics, such 4730 // arguments are actually passed as pointers. 4731 QualType ByValType = ValType; // 'CP' 4732 bool IsPassedByAddress = false; 4733 if (!IsC11 && !IsN) { 4734 ByValType = Ptr->getType(); 4735 IsPassedByAddress = true; 4736 } 4737 4738 // The first argument's non-CV pointer type is used to deduce the type of 4739 // subsequent arguments, except for: 4740 // - weak flag (always converted to bool) 4741 // - memory order (always converted to int) 4742 // - scope (always converted to int) 4743 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4744 QualType Ty; 4745 if (i < NumVals[Form] + 1) { 4746 switch (i) { 4747 case 0: 4748 // The first argument is always a pointer. It has a fixed type. 4749 // It is always dereferenced, a nullptr is undefined. 4750 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4751 // Nothing else to do: we already know all we want about this pointer. 4752 continue; 4753 case 1: 4754 // The second argument is the non-atomic operand. For arithmetic, this 4755 // is always passed by value, and for a compare_exchange it is always 4756 // passed by address. For the rest, GNU uses by-address and C11 uses 4757 // by-value. 4758 assert(Form != Load); 4759 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4760 Ty = ValType; 4761 else if (Form == Copy || Form == Xchg) { 4762 if (IsPassedByAddress) 4763 // The value pointer is always dereferenced, a nullptr is undefined. 4764 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4765 Ty = ByValType; 4766 } else if (Form == Arithmetic) 4767 Ty = Context.getPointerDiffType(); 4768 else { 4769 Expr *ValArg = TheCall->getArg(i); 4770 // The value pointer is always dereferenced, a nullptr is undefined. 4771 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4772 LangAS AS = LangAS::Default; 4773 // Keep address space of non-atomic pointer type. 4774 if (const PointerType *PtrTy = 4775 ValArg->getType()->getAs<PointerType>()) { 4776 AS = PtrTy->getPointeeType().getAddressSpace(); 4777 } 4778 Ty = Context.getPointerType( 4779 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4780 } 4781 break; 4782 case 2: 4783 // The third argument to compare_exchange / GNU exchange is the desired 4784 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4785 if (IsPassedByAddress) 4786 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4787 Ty = ByValType; 4788 break; 4789 case 3: 4790 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4791 Ty = Context.BoolTy; 4792 break; 4793 } 4794 } else { 4795 // The order(s) and scope are always converted to int. 4796 Ty = Context.IntTy; 4797 } 4798 4799 InitializedEntity Entity = 4800 InitializedEntity::InitializeParameter(Context, Ty, false); 4801 ExprResult Arg = TheCall->getArg(i); 4802 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4803 if (Arg.isInvalid()) 4804 return true; 4805 TheCall->setArg(i, Arg.get()); 4806 } 4807 4808 // Permute the arguments into a 'consistent' order. 4809 SmallVector<Expr*, 5> SubExprs; 4810 SubExprs.push_back(Ptr); 4811 switch (Form) { 4812 case Init: 4813 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4814 SubExprs.push_back(TheCall->getArg(1)); // Val1 4815 break; 4816 case Load: 4817 SubExprs.push_back(TheCall->getArg(1)); // Order 4818 break; 4819 case LoadCopy: 4820 case Copy: 4821 case Arithmetic: 4822 case Xchg: 4823 SubExprs.push_back(TheCall->getArg(2)); // Order 4824 SubExprs.push_back(TheCall->getArg(1)); // Val1 4825 break; 4826 case GNUXchg: 4827 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4828 SubExprs.push_back(TheCall->getArg(3)); // Order 4829 SubExprs.push_back(TheCall->getArg(1)); // Val1 4830 SubExprs.push_back(TheCall->getArg(2)); // Val2 4831 break; 4832 case C11CmpXchg: 4833 SubExprs.push_back(TheCall->getArg(3)); // Order 4834 SubExprs.push_back(TheCall->getArg(1)); // Val1 4835 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4836 SubExprs.push_back(TheCall->getArg(2)); // Val2 4837 break; 4838 case GNUCmpXchg: 4839 SubExprs.push_back(TheCall->getArg(4)); // Order 4840 SubExprs.push_back(TheCall->getArg(1)); // Val1 4841 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4842 SubExprs.push_back(TheCall->getArg(2)); // Val2 4843 SubExprs.push_back(TheCall->getArg(3)); // Weak 4844 break; 4845 } 4846 4847 if (SubExprs.size() >= 2 && Form != Init) { 4848 llvm::APSInt Result(32); 4849 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4850 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4851 Diag(SubExprs[1]->getBeginLoc(), 4852 diag::warn_atomic_op_has_invalid_memory_order) 4853 << SubExprs[1]->getSourceRange(); 4854 } 4855 4856 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4857 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4858 llvm::APSInt Result(32); 4859 if (Scope->isIntegerConstantExpr(Result, Context) && 4860 !ScopeModel->isValid(Result.getZExtValue())) { 4861 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4862 << Scope->getSourceRange(); 4863 } 4864 SubExprs.push_back(Scope); 4865 } 4866 4867 AtomicExpr *AE = 4868 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4869 ResultType, Op, TheCall->getRParenLoc()); 4870 4871 if ((Op == AtomicExpr::AO__c11_atomic_load || 4872 Op == AtomicExpr::AO__c11_atomic_store || 4873 Op == AtomicExpr::AO__opencl_atomic_load || 4874 Op == AtomicExpr::AO__opencl_atomic_store ) && 4875 Context.AtomicUsesUnsupportedLibcall(AE)) 4876 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4877 << ((Op == AtomicExpr::AO__c11_atomic_load || 4878 Op == AtomicExpr::AO__opencl_atomic_load) 4879 ? 0 4880 : 1); 4881 4882 return AE; 4883 } 4884 4885 /// checkBuiltinArgument - Given a call to a builtin function, perform 4886 /// normal type-checking on the given argument, updating the call in 4887 /// place. This is useful when a builtin function requires custom 4888 /// type-checking for some of its arguments but not necessarily all of 4889 /// them. 4890 /// 4891 /// Returns true on error. 4892 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4893 FunctionDecl *Fn = E->getDirectCallee(); 4894 assert(Fn && "builtin call without direct callee!"); 4895 4896 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4897 InitializedEntity Entity = 4898 InitializedEntity::InitializeParameter(S.Context, Param); 4899 4900 ExprResult Arg = E->getArg(0); 4901 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4902 if (Arg.isInvalid()) 4903 return true; 4904 4905 E->setArg(ArgIndex, Arg.get()); 4906 return false; 4907 } 4908 4909 /// We have a call to a function like __sync_fetch_and_add, which is an 4910 /// overloaded function based on the pointer type of its first argument. 4911 /// The main BuildCallExpr routines have already promoted the types of 4912 /// arguments because all of these calls are prototyped as void(...). 4913 /// 4914 /// This function goes through and does final semantic checking for these 4915 /// builtins, as well as generating any warnings. 4916 ExprResult 4917 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4918 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4919 Expr *Callee = TheCall->getCallee(); 4920 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4921 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4922 4923 // Ensure that we have at least one argument to do type inference from. 4924 if (TheCall->getNumArgs() < 1) { 4925 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4926 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4927 return ExprError(); 4928 } 4929 4930 // Inspect the first argument of the atomic builtin. This should always be 4931 // a pointer type, whose element is an integral scalar or pointer type. 4932 // Because it is a pointer type, we don't have to worry about any implicit 4933 // casts here. 4934 // FIXME: We don't allow floating point scalars as input. 4935 Expr *FirstArg = TheCall->getArg(0); 4936 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4937 if (FirstArgResult.isInvalid()) 4938 return ExprError(); 4939 FirstArg = FirstArgResult.get(); 4940 TheCall->setArg(0, FirstArg); 4941 4942 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4943 if (!pointerType) { 4944 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4945 << FirstArg->getType() << FirstArg->getSourceRange(); 4946 return ExprError(); 4947 } 4948 4949 QualType ValType = pointerType->getPointeeType(); 4950 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4951 !ValType->isBlockPointerType()) { 4952 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4953 << FirstArg->getType() << FirstArg->getSourceRange(); 4954 return ExprError(); 4955 } 4956 4957 if (ValType.isConstQualified()) { 4958 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4959 << FirstArg->getType() << FirstArg->getSourceRange(); 4960 return ExprError(); 4961 } 4962 4963 switch (ValType.getObjCLifetime()) { 4964 case Qualifiers::OCL_None: 4965 case Qualifiers::OCL_ExplicitNone: 4966 // okay 4967 break; 4968 4969 case Qualifiers::OCL_Weak: 4970 case Qualifiers::OCL_Strong: 4971 case Qualifiers::OCL_Autoreleasing: 4972 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4973 << ValType << FirstArg->getSourceRange(); 4974 return ExprError(); 4975 } 4976 4977 // Strip any qualifiers off ValType. 4978 ValType = ValType.getUnqualifiedType(); 4979 4980 // The majority of builtins return a value, but a few have special return 4981 // types, so allow them to override appropriately below. 4982 QualType ResultType = ValType; 4983 4984 // We need to figure out which concrete builtin this maps onto. For example, 4985 // __sync_fetch_and_add with a 2 byte object turns into 4986 // __sync_fetch_and_add_2. 4987 #define BUILTIN_ROW(x) \ 4988 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4989 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4990 4991 static const unsigned BuiltinIndices[][5] = { 4992 BUILTIN_ROW(__sync_fetch_and_add), 4993 BUILTIN_ROW(__sync_fetch_and_sub), 4994 BUILTIN_ROW(__sync_fetch_and_or), 4995 BUILTIN_ROW(__sync_fetch_and_and), 4996 BUILTIN_ROW(__sync_fetch_and_xor), 4997 BUILTIN_ROW(__sync_fetch_and_nand), 4998 4999 BUILTIN_ROW(__sync_add_and_fetch), 5000 BUILTIN_ROW(__sync_sub_and_fetch), 5001 BUILTIN_ROW(__sync_and_and_fetch), 5002 BUILTIN_ROW(__sync_or_and_fetch), 5003 BUILTIN_ROW(__sync_xor_and_fetch), 5004 BUILTIN_ROW(__sync_nand_and_fetch), 5005 5006 BUILTIN_ROW(__sync_val_compare_and_swap), 5007 BUILTIN_ROW(__sync_bool_compare_and_swap), 5008 BUILTIN_ROW(__sync_lock_test_and_set), 5009 BUILTIN_ROW(__sync_lock_release), 5010 BUILTIN_ROW(__sync_swap) 5011 }; 5012 #undef BUILTIN_ROW 5013 5014 // Determine the index of the size. 5015 unsigned SizeIndex; 5016 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5017 case 1: SizeIndex = 0; break; 5018 case 2: SizeIndex = 1; break; 5019 case 4: SizeIndex = 2; break; 5020 case 8: SizeIndex = 3; break; 5021 case 16: SizeIndex = 4; break; 5022 default: 5023 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5024 << FirstArg->getType() << FirstArg->getSourceRange(); 5025 return ExprError(); 5026 } 5027 5028 // Each of these builtins has one pointer argument, followed by some number of 5029 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5030 // that we ignore. Find out which row of BuiltinIndices to read from as well 5031 // as the number of fixed args. 5032 unsigned BuiltinID = FDecl->getBuiltinID(); 5033 unsigned BuiltinIndex, NumFixed = 1; 5034 bool WarnAboutSemanticsChange = false; 5035 switch (BuiltinID) { 5036 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5037 case Builtin::BI__sync_fetch_and_add: 5038 case Builtin::BI__sync_fetch_and_add_1: 5039 case Builtin::BI__sync_fetch_and_add_2: 5040 case Builtin::BI__sync_fetch_and_add_4: 5041 case Builtin::BI__sync_fetch_and_add_8: 5042 case Builtin::BI__sync_fetch_and_add_16: 5043 BuiltinIndex = 0; 5044 break; 5045 5046 case Builtin::BI__sync_fetch_and_sub: 5047 case Builtin::BI__sync_fetch_and_sub_1: 5048 case Builtin::BI__sync_fetch_and_sub_2: 5049 case Builtin::BI__sync_fetch_and_sub_4: 5050 case Builtin::BI__sync_fetch_and_sub_8: 5051 case Builtin::BI__sync_fetch_and_sub_16: 5052 BuiltinIndex = 1; 5053 break; 5054 5055 case Builtin::BI__sync_fetch_and_or: 5056 case Builtin::BI__sync_fetch_and_or_1: 5057 case Builtin::BI__sync_fetch_and_or_2: 5058 case Builtin::BI__sync_fetch_and_or_4: 5059 case Builtin::BI__sync_fetch_and_or_8: 5060 case Builtin::BI__sync_fetch_and_or_16: 5061 BuiltinIndex = 2; 5062 break; 5063 5064 case Builtin::BI__sync_fetch_and_and: 5065 case Builtin::BI__sync_fetch_and_and_1: 5066 case Builtin::BI__sync_fetch_and_and_2: 5067 case Builtin::BI__sync_fetch_and_and_4: 5068 case Builtin::BI__sync_fetch_and_and_8: 5069 case Builtin::BI__sync_fetch_and_and_16: 5070 BuiltinIndex = 3; 5071 break; 5072 5073 case Builtin::BI__sync_fetch_and_xor: 5074 case Builtin::BI__sync_fetch_and_xor_1: 5075 case Builtin::BI__sync_fetch_and_xor_2: 5076 case Builtin::BI__sync_fetch_and_xor_4: 5077 case Builtin::BI__sync_fetch_and_xor_8: 5078 case Builtin::BI__sync_fetch_and_xor_16: 5079 BuiltinIndex = 4; 5080 break; 5081 5082 case Builtin::BI__sync_fetch_and_nand: 5083 case Builtin::BI__sync_fetch_and_nand_1: 5084 case Builtin::BI__sync_fetch_and_nand_2: 5085 case Builtin::BI__sync_fetch_and_nand_4: 5086 case Builtin::BI__sync_fetch_and_nand_8: 5087 case Builtin::BI__sync_fetch_and_nand_16: 5088 BuiltinIndex = 5; 5089 WarnAboutSemanticsChange = true; 5090 break; 5091 5092 case Builtin::BI__sync_add_and_fetch: 5093 case Builtin::BI__sync_add_and_fetch_1: 5094 case Builtin::BI__sync_add_and_fetch_2: 5095 case Builtin::BI__sync_add_and_fetch_4: 5096 case Builtin::BI__sync_add_and_fetch_8: 5097 case Builtin::BI__sync_add_and_fetch_16: 5098 BuiltinIndex = 6; 5099 break; 5100 5101 case Builtin::BI__sync_sub_and_fetch: 5102 case Builtin::BI__sync_sub_and_fetch_1: 5103 case Builtin::BI__sync_sub_and_fetch_2: 5104 case Builtin::BI__sync_sub_and_fetch_4: 5105 case Builtin::BI__sync_sub_and_fetch_8: 5106 case Builtin::BI__sync_sub_and_fetch_16: 5107 BuiltinIndex = 7; 5108 break; 5109 5110 case Builtin::BI__sync_and_and_fetch: 5111 case Builtin::BI__sync_and_and_fetch_1: 5112 case Builtin::BI__sync_and_and_fetch_2: 5113 case Builtin::BI__sync_and_and_fetch_4: 5114 case Builtin::BI__sync_and_and_fetch_8: 5115 case Builtin::BI__sync_and_and_fetch_16: 5116 BuiltinIndex = 8; 5117 break; 5118 5119 case Builtin::BI__sync_or_and_fetch: 5120 case Builtin::BI__sync_or_and_fetch_1: 5121 case Builtin::BI__sync_or_and_fetch_2: 5122 case Builtin::BI__sync_or_and_fetch_4: 5123 case Builtin::BI__sync_or_and_fetch_8: 5124 case Builtin::BI__sync_or_and_fetch_16: 5125 BuiltinIndex = 9; 5126 break; 5127 5128 case Builtin::BI__sync_xor_and_fetch: 5129 case Builtin::BI__sync_xor_and_fetch_1: 5130 case Builtin::BI__sync_xor_and_fetch_2: 5131 case Builtin::BI__sync_xor_and_fetch_4: 5132 case Builtin::BI__sync_xor_and_fetch_8: 5133 case Builtin::BI__sync_xor_and_fetch_16: 5134 BuiltinIndex = 10; 5135 break; 5136 5137 case Builtin::BI__sync_nand_and_fetch: 5138 case Builtin::BI__sync_nand_and_fetch_1: 5139 case Builtin::BI__sync_nand_and_fetch_2: 5140 case Builtin::BI__sync_nand_and_fetch_4: 5141 case Builtin::BI__sync_nand_and_fetch_8: 5142 case Builtin::BI__sync_nand_and_fetch_16: 5143 BuiltinIndex = 11; 5144 WarnAboutSemanticsChange = true; 5145 break; 5146 5147 case Builtin::BI__sync_val_compare_and_swap: 5148 case Builtin::BI__sync_val_compare_and_swap_1: 5149 case Builtin::BI__sync_val_compare_and_swap_2: 5150 case Builtin::BI__sync_val_compare_and_swap_4: 5151 case Builtin::BI__sync_val_compare_and_swap_8: 5152 case Builtin::BI__sync_val_compare_and_swap_16: 5153 BuiltinIndex = 12; 5154 NumFixed = 2; 5155 break; 5156 5157 case Builtin::BI__sync_bool_compare_and_swap: 5158 case Builtin::BI__sync_bool_compare_and_swap_1: 5159 case Builtin::BI__sync_bool_compare_and_swap_2: 5160 case Builtin::BI__sync_bool_compare_and_swap_4: 5161 case Builtin::BI__sync_bool_compare_and_swap_8: 5162 case Builtin::BI__sync_bool_compare_and_swap_16: 5163 BuiltinIndex = 13; 5164 NumFixed = 2; 5165 ResultType = Context.BoolTy; 5166 break; 5167 5168 case Builtin::BI__sync_lock_test_and_set: 5169 case Builtin::BI__sync_lock_test_and_set_1: 5170 case Builtin::BI__sync_lock_test_and_set_2: 5171 case Builtin::BI__sync_lock_test_and_set_4: 5172 case Builtin::BI__sync_lock_test_and_set_8: 5173 case Builtin::BI__sync_lock_test_and_set_16: 5174 BuiltinIndex = 14; 5175 break; 5176 5177 case Builtin::BI__sync_lock_release: 5178 case Builtin::BI__sync_lock_release_1: 5179 case Builtin::BI__sync_lock_release_2: 5180 case Builtin::BI__sync_lock_release_4: 5181 case Builtin::BI__sync_lock_release_8: 5182 case Builtin::BI__sync_lock_release_16: 5183 BuiltinIndex = 15; 5184 NumFixed = 0; 5185 ResultType = Context.VoidTy; 5186 break; 5187 5188 case Builtin::BI__sync_swap: 5189 case Builtin::BI__sync_swap_1: 5190 case Builtin::BI__sync_swap_2: 5191 case Builtin::BI__sync_swap_4: 5192 case Builtin::BI__sync_swap_8: 5193 case Builtin::BI__sync_swap_16: 5194 BuiltinIndex = 16; 5195 break; 5196 } 5197 5198 // Now that we know how many fixed arguments we expect, first check that we 5199 // have at least that many. 5200 if (TheCall->getNumArgs() < 1+NumFixed) { 5201 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5202 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5203 << Callee->getSourceRange(); 5204 return ExprError(); 5205 } 5206 5207 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5208 << Callee->getSourceRange(); 5209 5210 if (WarnAboutSemanticsChange) { 5211 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5212 << Callee->getSourceRange(); 5213 } 5214 5215 // Get the decl for the concrete builtin from this, we can tell what the 5216 // concrete integer type we should convert to is. 5217 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5218 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5219 FunctionDecl *NewBuiltinDecl; 5220 if (NewBuiltinID == BuiltinID) 5221 NewBuiltinDecl = FDecl; 5222 else { 5223 // Perform builtin lookup to avoid redeclaring it. 5224 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5225 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5226 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5227 assert(Res.getFoundDecl()); 5228 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5229 if (!NewBuiltinDecl) 5230 return ExprError(); 5231 } 5232 5233 // The first argument --- the pointer --- has a fixed type; we 5234 // deduce the types of the rest of the arguments accordingly. Walk 5235 // the remaining arguments, converting them to the deduced value type. 5236 for (unsigned i = 0; i != NumFixed; ++i) { 5237 ExprResult Arg = TheCall->getArg(i+1); 5238 5239 // GCC does an implicit conversion to the pointer or integer ValType. This 5240 // can fail in some cases (1i -> int**), check for this error case now. 5241 // Initialize the argument. 5242 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5243 ValType, /*consume*/ false); 5244 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5245 if (Arg.isInvalid()) 5246 return ExprError(); 5247 5248 // Okay, we have something that *can* be converted to the right type. Check 5249 // to see if there is a potentially weird extension going on here. This can 5250 // happen when you do an atomic operation on something like an char* and 5251 // pass in 42. The 42 gets converted to char. This is even more strange 5252 // for things like 45.123 -> char, etc. 5253 // FIXME: Do this check. 5254 TheCall->setArg(i+1, Arg.get()); 5255 } 5256 5257 // Create a new DeclRefExpr to refer to the new decl. 5258 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5259 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5260 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5261 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5262 5263 // Set the callee in the CallExpr. 5264 // FIXME: This loses syntactic information. 5265 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5266 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5267 CK_BuiltinFnToFnPtr); 5268 TheCall->setCallee(PromotedCall.get()); 5269 5270 // Change the result type of the call to match the original value type. This 5271 // is arbitrary, but the codegen for these builtins ins design to handle it 5272 // gracefully. 5273 TheCall->setType(ResultType); 5274 5275 return TheCallResult; 5276 } 5277 5278 /// SemaBuiltinNontemporalOverloaded - We have a call to 5279 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5280 /// overloaded function based on the pointer type of its last argument. 5281 /// 5282 /// This function goes through and does final semantic checking for these 5283 /// builtins. 5284 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5285 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5286 DeclRefExpr *DRE = 5287 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5288 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5289 unsigned BuiltinID = FDecl->getBuiltinID(); 5290 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5291 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5292 "Unexpected nontemporal load/store builtin!"); 5293 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5294 unsigned numArgs = isStore ? 2 : 1; 5295 5296 // Ensure that we have the proper number of arguments. 5297 if (checkArgCount(*this, TheCall, numArgs)) 5298 return ExprError(); 5299 5300 // Inspect the last argument of the nontemporal builtin. This should always 5301 // be a pointer type, from which we imply the type of the memory access. 5302 // Because it is a pointer type, we don't have to worry about any implicit 5303 // casts here. 5304 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5305 ExprResult PointerArgResult = 5306 DefaultFunctionArrayLvalueConversion(PointerArg); 5307 5308 if (PointerArgResult.isInvalid()) 5309 return ExprError(); 5310 PointerArg = PointerArgResult.get(); 5311 TheCall->setArg(numArgs - 1, PointerArg); 5312 5313 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5314 if (!pointerType) { 5315 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5316 << PointerArg->getType() << PointerArg->getSourceRange(); 5317 return ExprError(); 5318 } 5319 5320 QualType ValType = pointerType->getPointeeType(); 5321 5322 // Strip any qualifiers off ValType. 5323 ValType = ValType.getUnqualifiedType(); 5324 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5325 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5326 !ValType->isVectorType()) { 5327 Diag(DRE->getBeginLoc(), 5328 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5329 << PointerArg->getType() << PointerArg->getSourceRange(); 5330 return ExprError(); 5331 } 5332 5333 if (!isStore) { 5334 TheCall->setType(ValType); 5335 return TheCallResult; 5336 } 5337 5338 ExprResult ValArg = TheCall->getArg(0); 5339 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5340 Context, ValType, /*consume*/ false); 5341 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5342 if (ValArg.isInvalid()) 5343 return ExprError(); 5344 5345 TheCall->setArg(0, ValArg.get()); 5346 TheCall->setType(Context.VoidTy); 5347 return TheCallResult; 5348 } 5349 5350 /// CheckObjCString - Checks that the argument to the builtin 5351 /// CFString constructor is correct 5352 /// Note: It might also make sense to do the UTF-16 conversion here (would 5353 /// simplify the backend). 5354 bool Sema::CheckObjCString(Expr *Arg) { 5355 Arg = Arg->IgnoreParenCasts(); 5356 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5357 5358 if (!Literal || !Literal->isAscii()) { 5359 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5360 << Arg->getSourceRange(); 5361 return true; 5362 } 5363 5364 if (Literal->containsNonAsciiOrNull()) { 5365 StringRef String = Literal->getString(); 5366 unsigned NumBytes = String.size(); 5367 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5368 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5369 llvm::UTF16 *ToPtr = &ToBuf[0]; 5370 5371 llvm::ConversionResult Result = 5372 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5373 ToPtr + NumBytes, llvm::strictConversion); 5374 // Check for conversion failure. 5375 if (Result != llvm::conversionOK) 5376 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5377 << Arg->getSourceRange(); 5378 } 5379 return false; 5380 } 5381 5382 /// CheckObjCString - Checks that the format string argument to the os_log() 5383 /// and os_trace() functions is correct, and converts it to const char *. 5384 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5385 Arg = Arg->IgnoreParenCasts(); 5386 auto *Literal = dyn_cast<StringLiteral>(Arg); 5387 if (!Literal) { 5388 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5389 Literal = ObjcLiteral->getString(); 5390 } 5391 } 5392 5393 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5394 return ExprError( 5395 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5396 << Arg->getSourceRange()); 5397 } 5398 5399 ExprResult Result(Literal); 5400 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5401 InitializedEntity Entity = 5402 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5403 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5404 return Result; 5405 } 5406 5407 /// Check that the user is calling the appropriate va_start builtin for the 5408 /// target and calling convention. 5409 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5410 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5411 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5412 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5413 bool IsWindows = TT.isOSWindows(); 5414 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5415 if (IsX64 || IsAArch64) { 5416 CallingConv CC = CC_C; 5417 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5418 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5419 if (IsMSVAStart) { 5420 // Don't allow this in System V ABI functions. 5421 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5422 return S.Diag(Fn->getBeginLoc(), 5423 diag::err_ms_va_start_used_in_sysv_function); 5424 } else { 5425 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5426 // On x64 Windows, don't allow this in System V ABI functions. 5427 // (Yes, that means there's no corresponding way to support variadic 5428 // System V ABI functions on Windows.) 5429 if ((IsWindows && CC == CC_X86_64SysV) || 5430 (!IsWindows && CC == CC_Win64)) 5431 return S.Diag(Fn->getBeginLoc(), 5432 diag::err_va_start_used_in_wrong_abi_function) 5433 << !IsWindows; 5434 } 5435 return false; 5436 } 5437 5438 if (IsMSVAStart) 5439 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5440 return false; 5441 } 5442 5443 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5444 ParmVarDecl **LastParam = nullptr) { 5445 // Determine whether the current function, block, or obj-c method is variadic 5446 // and get its parameter list. 5447 bool IsVariadic = false; 5448 ArrayRef<ParmVarDecl *> Params; 5449 DeclContext *Caller = S.CurContext; 5450 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5451 IsVariadic = Block->isVariadic(); 5452 Params = Block->parameters(); 5453 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5454 IsVariadic = FD->isVariadic(); 5455 Params = FD->parameters(); 5456 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5457 IsVariadic = MD->isVariadic(); 5458 // FIXME: This isn't correct for methods (results in bogus warning). 5459 Params = MD->parameters(); 5460 } else if (isa<CapturedDecl>(Caller)) { 5461 // We don't support va_start in a CapturedDecl. 5462 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5463 return true; 5464 } else { 5465 // This must be some other declcontext that parses exprs. 5466 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5467 return true; 5468 } 5469 5470 if (!IsVariadic) { 5471 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5472 return true; 5473 } 5474 5475 if (LastParam) 5476 *LastParam = Params.empty() ? nullptr : Params.back(); 5477 5478 return false; 5479 } 5480 5481 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5482 /// for validity. Emit an error and return true on failure; return false 5483 /// on success. 5484 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5485 Expr *Fn = TheCall->getCallee(); 5486 5487 if (checkVAStartABI(*this, BuiltinID, Fn)) 5488 return true; 5489 5490 if (TheCall->getNumArgs() > 2) { 5491 Diag(TheCall->getArg(2)->getBeginLoc(), 5492 diag::err_typecheck_call_too_many_args) 5493 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5494 << Fn->getSourceRange() 5495 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5496 (*(TheCall->arg_end() - 1))->getEndLoc()); 5497 return true; 5498 } 5499 5500 if (TheCall->getNumArgs() < 2) { 5501 return Diag(TheCall->getEndLoc(), 5502 diag::err_typecheck_call_too_few_args_at_least) 5503 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5504 } 5505 5506 // Type-check the first argument normally. 5507 if (checkBuiltinArgument(*this, TheCall, 0)) 5508 return true; 5509 5510 // Check that the current function is variadic, and get its last parameter. 5511 ParmVarDecl *LastParam; 5512 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5513 return true; 5514 5515 // Verify that the second argument to the builtin is the last argument of the 5516 // current function or method. 5517 bool SecondArgIsLastNamedArgument = false; 5518 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5519 5520 // These are valid if SecondArgIsLastNamedArgument is false after the next 5521 // block. 5522 QualType Type; 5523 SourceLocation ParamLoc; 5524 bool IsCRegister = false; 5525 5526 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5527 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5528 SecondArgIsLastNamedArgument = PV == LastParam; 5529 5530 Type = PV->getType(); 5531 ParamLoc = PV->getLocation(); 5532 IsCRegister = 5533 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5534 } 5535 } 5536 5537 if (!SecondArgIsLastNamedArgument) 5538 Diag(TheCall->getArg(1)->getBeginLoc(), 5539 diag::warn_second_arg_of_va_start_not_last_named_param); 5540 else if (IsCRegister || Type->isReferenceType() || 5541 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5542 // Promotable integers are UB, but enumerations need a bit of 5543 // extra checking to see what their promotable type actually is. 5544 if (!Type->isPromotableIntegerType()) 5545 return false; 5546 if (!Type->isEnumeralType()) 5547 return true; 5548 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5549 return !(ED && 5550 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5551 }()) { 5552 unsigned Reason = 0; 5553 if (Type->isReferenceType()) Reason = 1; 5554 else if (IsCRegister) Reason = 2; 5555 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5556 Diag(ParamLoc, diag::note_parameter_type) << Type; 5557 } 5558 5559 TheCall->setType(Context.VoidTy); 5560 return false; 5561 } 5562 5563 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5564 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5565 // const char *named_addr); 5566 5567 Expr *Func = Call->getCallee(); 5568 5569 if (Call->getNumArgs() < 3) 5570 return Diag(Call->getEndLoc(), 5571 diag::err_typecheck_call_too_few_args_at_least) 5572 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5573 5574 // Type-check the first argument normally. 5575 if (checkBuiltinArgument(*this, Call, 0)) 5576 return true; 5577 5578 // Check that the current function is variadic. 5579 if (checkVAStartIsInVariadicFunction(*this, Func)) 5580 return true; 5581 5582 // __va_start on Windows does not validate the parameter qualifiers 5583 5584 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5585 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5586 5587 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5588 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5589 5590 const QualType &ConstCharPtrTy = 5591 Context.getPointerType(Context.CharTy.withConst()); 5592 if (!Arg1Ty->isPointerType() || 5593 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5594 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5595 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5596 << 0 /* qualifier difference */ 5597 << 3 /* parameter mismatch */ 5598 << 2 << Arg1->getType() << ConstCharPtrTy; 5599 5600 const QualType SizeTy = Context.getSizeType(); 5601 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5602 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5603 << Arg2->getType() << SizeTy << 1 /* different class */ 5604 << 0 /* qualifier difference */ 5605 << 3 /* parameter mismatch */ 5606 << 3 << Arg2->getType() << SizeTy; 5607 5608 return false; 5609 } 5610 5611 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5612 /// friends. This is declared to take (...), so we have to check everything. 5613 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5614 if (TheCall->getNumArgs() < 2) 5615 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5616 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5617 if (TheCall->getNumArgs() > 2) 5618 return Diag(TheCall->getArg(2)->getBeginLoc(), 5619 diag::err_typecheck_call_too_many_args) 5620 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5621 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5622 (*(TheCall->arg_end() - 1))->getEndLoc()); 5623 5624 ExprResult OrigArg0 = TheCall->getArg(0); 5625 ExprResult OrigArg1 = TheCall->getArg(1); 5626 5627 // Do standard promotions between the two arguments, returning their common 5628 // type. 5629 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5630 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5631 return true; 5632 5633 // Make sure any conversions are pushed back into the call; this is 5634 // type safe since unordered compare builtins are declared as "_Bool 5635 // foo(...)". 5636 TheCall->setArg(0, OrigArg0.get()); 5637 TheCall->setArg(1, OrigArg1.get()); 5638 5639 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5640 return false; 5641 5642 // If the common type isn't a real floating type, then the arguments were 5643 // invalid for this operation. 5644 if (Res.isNull() || !Res->isRealFloatingType()) 5645 return Diag(OrigArg0.get()->getBeginLoc(), 5646 diag::err_typecheck_call_invalid_ordered_compare) 5647 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5648 << SourceRange(OrigArg0.get()->getBeginLoc(), 5649 OrigArg1.get()->getEndLoc()); 5650 5651 return false; 5652 } 5653 5654 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5655 /// __builtin_isnan and friends. This is declared to take (...), so we have 5656 /// to check everything. We expect the last argument to be a floating point 5657 /// value. 5658 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5659 if (TheCall->getNumArgs() < NumArgs) 5660 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5661 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5662 if (TheCall->getNumArgs() > NumArgs) 5663 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5664 diag::err_typecheck_call_too_many_args) 5665 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5666 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5667 (*(TheCall->arg_end() - 1))->getEndLoc()); 5668 5669 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5670 5671 if (OrigArg->isTypeDependent()) 5672 return false; 5673 5674 // This operation requires a non-_Complex floating-point number. 5675 if (!OrigArg->getType()->isRealFloatingType()) 5676 return Diag(OrigArg->getBeginLoc(), 5677 diag::err_typecheck_call_invalid_unary_fp) 5678 << OrigArg->getType() << OrigArg->getSourceRange(); 5679 5680 // If this is an implicit conversion from float -> float, double, or 5681 // long double, remove it. 5682 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5683 // Only remove standard FloatCasts, leaving other casts inplace 5684 if (Cast->getCastKind() == CK_FloatingCast) { 5685 Expr *CastArg = Cast->getSubExpr(); 5686 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5687 assert( 5688 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5689 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5690 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5691 "promotion from float to either float, double, or long double is " 5692 "the only expected cast here"); 5693 Cast->setSubExpr(nullptr); 5694 TheCall->setArg(NumArgs-1, CastArg); 5695 } 5696 } 5697 } 5698 5699 return false; 5700 } 5701 5702 // Customized Sema Checking for VSX builtins that have the following signature: 5703 // vector [...] builtinName(vector [...], vector [...], const int); 5704 // Which takes the same type of vectors (any legal vector type) for the first 5705 // two arguments and takes compile time constant for the third argument. 5706 // Example builtins are : 5707 // vector double vec_xxpermdi(vector double, vector double, int); 5708 // vector short vec_xxsldwi(vector short, vector short, int); 5709 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5710 unsigned ExpectedNumArgs = 3; 5711 if (TheCall->getNumArgs() < ExpectedNumArgs) 5712 return Diag(TheCall->getEndLoc(), 5713 diag::err_typecheck_call_too_few_args_at_least) 5714 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5715 << TheCall->getSourceRange(); 5716 5717 if (TheCall->getNumArgs() > ExpectedNumArgs) 5718 return Diag(TheCall->getEndLoc(), 5719 diag::err_typecheck_call_too_many_args_at_most) 5720 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5721 << TheCall->getSourceRange(); 5722 5723 // Check the third argument is a compile time constant 5724 llvm::APSInt Value; 5725 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5726 return Diag(TheCall->getBeginLoc(), 5727 diag::err_vsx_builtin_nonconstant_argument) 5728 << 3 /* argument index */ << TheCall->getDirectCallee() 5729 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5730 TheCall->getArg(2)->getEndLoc()); 5731 5732 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5733 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5734 5735 // Check the type of argument 1 and argument 2 are vectors. 5736 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5737 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5738 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5739 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5740 << TheCall->getDirectCallee() 5741 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5742 TheCall->getArg(1)->getEndLoc()); 5743 } 5744 5745 // Check the first two arguments are the same type. 5746 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5747 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5748 << TheCall->getDirectCallee() 5749 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5750 TheCall->getArg(1)->getEndLoc()); 5751 } 5752 5753 // When default clang type checking is turned off and the customized type 5754 // checking is used, the returning type of the function must be explicitly 5755 // set. Otherwise it is _Bool by default. 5756 TheCall->setType(Arg1Ty); 5757 5758 return false; 5759 } 5760 5761 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5762 // This is declared to take (...), so we have to check everything. 5763 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5764 if (TheCall->getNumArgs() < 2) 5765 return ExprError(Diag(TheCall->getEndLoc(), 5766 diag::err_typecheck_call_too_few_args_at_least) 5767 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5768 << TheCall->getSourceRange()); 5769 5770 // Determine which of the following types of shufflevector we're checking: 5771 // 1) unary, vector mask: (lhs, mask) 5772 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5773 QualType resType = TheCall->getArg(0)->getType(); 5774 unsigned numElements = 0; 5775 5776 if (!TheCall->getArg(0)->isTypeDependent() && 5777 !TheCall->getArg(1)->isTypeDependent()) { 5778 QualType LHSType = TheCall->getArg(0)->getType(); 5779 QualType RHSType = TheCall->getArg(1)->getType(); 5780 5781 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5782 return ExprError( 5783 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5784 << TheCall->getDirectCallee() 5785 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5786 TheCall->getArg(1)->getEndLoc())); 5787 5788 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5789 unsigned numResElements = TheCall->getNumArgs() - 2; 5790 5791 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5792 // with mask. If so, verify that RHS is an integer vector type with the 5793 // same number of elts as lhs. 5794 if (TheCall->getNumArgs() == 2) { 5795 if (!RHSType->hasIntegerRepresentation() || 5796 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5797 return ExprError(Diag(TheCall->getBeginLoc(), 5798 diag::err_vec_builtin_incompatible_vector) 5799 << TheCall->getDirectCallee() 5800 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5801 TheCall->getArg(1)->getEndLoc())); 5802 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5803 return ExprError(Diag(TheCall->getBeginLoc(), 5804 diag::err_vec_builtin_incompatible_vector) 5805 << TheCall->getDirectCallee() 5806 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5807 TheCall->getArg(1)->getEndLoc())); 5808 } else if (numElements != numResElements) { 5809 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5810 resType = Context.getVectorType(eltType, numResElements, 5811 VectorType::GenericVector); 5812 } 5813 } 5814 5815 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5816 if (TheCall->getArg(i)->isTypeDependent() || 5817 TheCall->getArg(i)->isValueDependent()) 5818 continue; 5819 5820 llvm::APSInt Result(32); 5821 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5822 return ExprError(Diag(TheCall->getBeginLoc(), 5823 diag::err_shufflevector_nonconstant_argument) 5824 << TheCall->getArg(i)->getSourceRange()); 5825 5826 // Allow -1 which will be translated to undef in the IR. 5827 if (Result.isSigned() && Result.isAllOnesValue()) 5828 continue; 5829 5830 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5831 return ExprError(Diag(TheCall->getBeginLoc(), 5832 diag::err_shufflevector_argument_too_large) 5833 << TheCall->getArg(i)->getSourceRange()); 5834 } 5835 5836 SmallVector<Expr*, 32> exprs; 5837 5838 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5839 exprs.push_back(TheCall->getArg(i)); 5840 TheCall->setArg(i, nullptr); 5841 } 5842 5843 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5844 TheCall->getCallee()->getBeginLoc(), 5845 TheCall->getRParenLoc()); 5846 } 5847 5848 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5849 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5850 SourceLocation BuiltinLoc, 5851 SourceLocation RParenLoc) { 5852 ExprValueKind VK = VK_RValue; 5853 ExprObjectKind OK = OK_Ordinary; 5854 QualType DstTy = TInfo->getType(); 5855 QualType SrcTy = E->getType(); 5856 5857 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5858 return ExprError(Diag(BuiltinLoc, 5859 diag::err_convertvector_non_vector) 5860 << E->getSourceRange()); 5861 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5862 return ExprError(Diag(BuiltinLoc, 5863 diag::err_convertvector_non_vector_type)); 5864 5865 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5866 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5867 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5868 if (SrcElts != DstElts) 5869 return ExprError(Diag(BuiltinLoc, 5870 diag::err_convertvector_incompatible_vector) 5871 << E->getSourceRange()); 5872 } 5873 5874 return new (Context) 5875 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5876 } 5877 5878 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5879 // This is declared to take (const void*, ...) and can take two 5880 // optional constant int args. 5881 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5882 unsigned NumArgs = TheCall->getNumArgs(); 5883 5884 if (NumArgs > 3) 5885 return Diag(TheCall->getEndLoc(), 5886 diag::err_typecheck_call_too_many_args_at_most) 5887 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5888 5889 // Argument 0 is checked for us and the remaining arguments must be 5890 // constant integers. 5891 for (unsigned i = 1; i != NumArgs; ++i) 5892 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5893 return true; 5894 5895 return false; 5896 } 5897 5898 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5899 // __assume does not evaluate its arguments, and should warn if its argument 5900 // has side effects. 5901 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5902 Expr *Arg = TheCall->getArg(0); 5903 if (Arg->isInstantiationDependent()) return false; 5904 5905 if (Arg->HasSideEffects(Context)) 5906 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5907 << Arg->getSourceRange() 5908 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5909 5910 return false; 5911 } 5912 5913 /// Handle __builtin_alloca_with_align. This is declared 5914 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5915 /// than 8. 5916 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5917 // The alignment must be a constant integer. 5918 Expr *Arg = TheCall->getArg(1); 5919 5920 // We can't check the value of a dependent argument. 5921 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5922 if (const auto *UE = 5923 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5924 if (UE->getKind() == UETT_AlignOf || 5925 UE->getKind() == UETT_PreferredAlignOf) 5926 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5927 << Arg->getSourceRange(); 5928 5929 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5930 5931 if (!Result.isPowerOf2()) 5932 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5933 << Arg->getSourceRange(); 5934 5935 if (Result < Context.getCharWidth()) 5936 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5937 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5938 5939 if (Result > std::numeric_limits<int32_t>::max()) 5940 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5941 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5942 } 5943 5944 return false; 5945 } 5946 5947 /// Handle __builtin_assume_aligned. This is declared 5948 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5949 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5950 unsigned NumArgs = TheCall->getNumArgs(); 5951 5952 if (NumArgs > 3) 5953 return Diag(TheCall->getEndLoc(), 5954 diag::err_typecheck_call_too_many_args_at_most) 5955 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5956 5957 // The alignment must be a constant integer. 5958 Expr *Arg = TheCall->getArg(1); 5959 5960 // We can't check the value of a dependent argument. 5961 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5962 llvm::APSInt Result; 5963 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5964 return true; 5965 5966 if (!Result.isPowerOf2()) 5967 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5968 << Arg->getSourceRange(); 5969 } 5970 5971 if (NumArgs > 2) { 5972 ExprResult Arg(TheCall->getArg(2)); 5973 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5974 Context.getSizeType(), false); 5975 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5976 if (Arg.isInvalid()) return true; 5977 TheCall->setArg(2, Arg.get()); 5978 } 5979 5980 return false; 5981 } 5982 5983 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5984 unsigned BuiltinID = 5985 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5986 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5987 5988 unsigned NumArgs = TheCall->getNumArgs(); 5989 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5990 if (NumArgs < NumRequiredArgs) { 5991 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5992 << 0 /* function call */ << NumRequiredArgs << NumArgs 5993 << TheCall->getSourceRange(); 5994 } 5995 if (NumArgs >= NumRequiredArgs + 0x100) { 5996 return Diag(TheCall->getEndLoc(), 5997 diag::err_typecheck_call_too_many_args_at_most) 5998 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5999 << TheCall->getSourceRange(); 6000 } 6001 unsigned i = 0; 6002 6003 // For formatting call, check buffer arg. 6004 if (!IsSizeCall) { 6005 ExprResult Arg(TheCall->getArg(i)); 6006 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6007 Context, Context.VoidPtrTy, false); 6008 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6009 if (Arg.isInvalid()) 6010 return true; 6011 TheCall->setArg(i, Arg.get()); 6012 i++; 6013 } 6014 6015 // Check string literal arg. 6016 unsigned FormatIdx = i; 6017 { 6018 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6019 if (Arg.isInvalid()) 6020 return true; 6021 TheCall->setArg(i, Arg.get()); 6022 i++; 6023 } 6024 6025 // Make sure variadic args are scalar. 6026 unsigned FirstDataArg = i; 6027 while (i < NumArgs) { 6028 ExprResult Arg = DefaultVariadicArgumentPromotion( 6029 TheCall->getArg(i), VariadicFunction, nullptr); 6030 if (Arg.isInvalid()) 6031 return true; 6032 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6033 if (ArgSize.getQuantity() >= 0x100) { 6034 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6035 << i << (int)ArgSize.getQuantity() << 0xff 6036 << TheCall->getSourceRange(); 6037 } 6038 TheCall->setArg(i, Arg.get()); 6039 i++; 6040 } 6041 6042 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6043 // call to avoid duplicate diagnostics. 6044 if (!IsSizeCall) { 6045 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6046 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6047 bool Success = CheckFormatArguments( 6048 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6049 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6050 CheckedVarArgs); 6051 if (!Success) 6052 return true; 6053 } 6054 6055 if (IsSizeCall) { 6056 TheCall->setType(Context.getSizeType()); 6057 } else { 6058 TheCall->setType(Context.VoidPtrTy); 6059 } 6060 return false; 6061 } 6062 6063 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6064 /// TheCall is a constant expression. 6065 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6066 llvm::APSInt &Result) { 6067 Expr *Arg = TheCall->getArg(ArgNum); 6068 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6069 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6070 6071 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6072 6073 if (!Arg->isIntegerConstantExpr(Result, Context)) 6074 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6075 << FDecl->getDeclName() << Arg->getSourceRange(); 6076 6077 return false; 6078 } 6079 6080 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6081 /// TheCall is a constant expression in the range [Low, High]. 6082 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6083 int Low, int High, bool RangeIsError) { 6084 if (isConstantEvaluated()) 6085 return false; 6086 llvm::APSInt Result; 6087 6088 // We can't check the value of a dependent argument. 6089 Expr *Arg = TheCall->getArg(ArgNum); 6090 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6091 return false; 6092 6093 // Check constant-ness first. 6094 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6095 return true; 6096 6097 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6098 if (RangeIsError) 6099 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6100 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6101 else 6102 // Defer the warning until we know if the code will be emitted so that 6103 // dead code can ignore this. 6104 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6105 PDiag(diag::warn_argument_invalid_range) 6106 << Result.toString(10) << Low << High 6107 << Arg->getSourceRange()); 6108 } 6109 6110 return false; 6111 } 6112 6113 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6114 /// TheCall is a constant expression is a multiple of Num.. 6115 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6116 unsigned Num) { 6117 llvm::APSInt Result; 6118 6119 // We can't check the value of a dependent argument. 6120 Expr *Arg = TheCall->getArg(ArgNum); 6121 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6122 return false; 6123 6124 // Check constant-ness first. 6125 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6126 return true; 6127 6128 if (Result.getSExtValue() % Num != 0) 6129 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6130 << Num << Arg->getSourceRange(); 6131 6132 return false; 6133 } 6134 6135 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6136 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6137 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6138 if (checkArgCount(*this, TheCall, 2)) 6139 return true; 6140 Expr *Arg0 = TheCall->getArg(0); 6141 Expr *Arg1 = TheCall->getArg(1); 6142 6143 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6144 if (FirstArg.isInvalid()) 6145 return true; 6146 QualType FirstArgType = FirstArg.get()->getType(); 6147 if (!FirstArgType->isAnyPointerType()) 6148 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6149 << "first" << FirstArgType << Arg0->getSourceRange(); 6150 TheCall->setArg(0, FirstArg.get()); 6151 6152 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6153 if (SecArg.isInvalid()) 6154 return true; 6155 QualType SecArgType = SecArg.get()->getType(); 6156 if (!SecArgType->isIntegerType()) 6157 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6158 << "second" << SecArgType << Arg1->getSourceRange(); 6159 6160 // Derive the return type from the pointer argument. 6161 TheCall->setType(FirstArgType); 6162 return false; 6163 } 6164 6165 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6166 if (checkArgCount(*this, TheCall, 2)) 6167 return true; 6168 6169 Expr *Arg0 = TheCall->getArg(0); 6170 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6171 if (FirstArg.isInvalid()) 6172 return true; 6173 QualType FirstArgType = FirstArg.get()->getType(); 6174 if (!FirstArgType->isAnyPointerType()) 6175 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6176 << "first" << FirstArgType << Arg0->getSourceRange(); 6177 TheCall->setArg(0, FirstArg.get()); 6178 6179 // Derive the return type from the pointer argument. 6180 TheCall->setType(FirstArgType); 6181 6182 // Second arg must be an constant in range [0,15] 6183 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6184 } 6185 6186 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6187 if (checkArgCount(*this, TheCall, 2)) 6188 return true; 6189 Expr *Arg0 = TheCall->getArg(0); 6190 Expr *Arg1 = TheCall->getArg(1); 6191 6192 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6193 if (FirstArg.isInvalid()) 6194 return true; 6195 QualType FirstArgType = FirstArg.get()->getType(); 6196 if (!FirstArgType->isAnyPointerType()) 6197 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6198 << "first" << FirstArgType << Arg0->getSourceRange(); 6199 6200 QualType SecArgType = Arg1->getType(); 6201 if (!SecArgType->isIntegerType()) 6202 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6203 << "second" << SecArgType << Arg1->getSourceRange(); 6204 TheCall->setType(Context.IntTy); 6205 return false; 6206 } 6207 6208 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6209 BuiltinID == AArch64::BI__builtin_arm_stg) { 6210 if (checkArgCount(*this, TheCall, 1)) 6211 return true; 6212 Expr *Arg0 = TheCall->getArg(0); 6213 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6214 if (FirstArg.isInvalid()) 6215 return true; 6216 6217 QualType FirstArgType = FirstArg.get()->getType(); 6218 if (!FirstArgType->isAnyPointerType()) 6219 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6220 << "first" << FirstArgType << Arg0->getSourceRange(); 6221 TheCall->setArg(0, FirstArg.get()); 6222 6223 // Derive the return type from the pointer argument. 6224 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6225 TheCall->setType(FirstArgType); 6226 return false; 6227 } 6228 6229 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6230 Expr *ArgA = TheCall->getArg(0); 6231 Expr *ArgB = TheCall->getArg(1); 6232 6233 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6234 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6235 6236 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6237 return true; 6238 6239 QualType ArgTypeA = ArgExprA.get()->getType(); 6240 QualType ArgTypeB = ArgExprB.get()->getType(); 6241 6242 auto isNull = [&] (Expr *E) -> bool { 6243 return E->isNullPointerConstant( 6244 Context, Expr::NPC_ValueDependentIsNotNull); }; 6245 6246 // argument should be either a pointer or null 6247 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6248 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6249 << "first" << ArgTypeA << ArgA->getSourceRange(); 6250 6251 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6252 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6253 << "second" << ArgTypeB << ArgB->getSourceRange(); 6254 6255 // Ensure Pointee types are compatible 6256 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6257 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6258 QualType pointeeA = ArgTypeA->getPointeeType(); 6259 QualType pointeeB = ArgTypeB->getPointeeType(); 6260 if (!Context.typesAreCompatible( 6261 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6262 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6263 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6264 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6265 << ArgB->getSourceRange(); 6266 } 6267 } 6268 6269 // at least one argument should be pointer type 6270 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6271 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6272 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6273 6274 if (isNull(ArgA)) // adopt type of the other pointer 6275 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6276 6277 if (isNull(ArgB)) 6278 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6279 6280 TheCall->setArg(0, ArgExprA.get()); 6281 TheCall->setArg(1, ArgExprB.get()); 6282 TheCall->setType(Context.LongLongTy); 6283 return false; 6284 } 6285 assert(false && "Unhandled ARM MTE intrinsic"); 6286 return true; 6287 } 6288 6289 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6290 /// TheCall is an ARM/AArch64 special register string literal. 6291 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6292 int ArgNum, unsigned ExpectedFieldNum, 6293 bool AllowName) { 6294 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6295 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6296 BuiltinID == ARM::BI__builtin_arm_rsr || 6297 BuiltinID == ARM::BI__builtin_arm_rsrp || 6298 BuiltinID == ARM::BI__builtin_arm_wsr || 6299 BuiltinID == ARM::BI__builtin_arm_wsrp; 6300 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6301 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6302 BuiltinID == AArch64::BI__builtin_arm_rsr || 6303 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6304 BuiltinID == AArch64::BI__builtin_arm_wsr || 6305 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6306 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6307 6308 // We can't check the value of a dependent argument. 6309 Expr *Arg = TheCall->getArg(ArgNum); 6310 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6311 return false; 6312 6313 // Check if the argument is a string literal. 6314 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6315 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6316 << Arg->getSourceRange(); 6317 6318 // Check the type of special register given. 6319 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6320 SmallVector<StringRef, 6> Fields; 6321 Reg.split(Fields, ":"); 6322 6323 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6324 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6325 << Arg->getSourceRange(); 6326 6327 // If the string is the name of a register then we cannot check that it is 6328 // valid here but if the string is of one the forms described in ACLE then we 6329 // can check that the supplied fields are integers and within the valid 6330 // ranges. 6331 if (Fields.size() > 1) { 6332 bool FiveFields = Fields.size() == 5; 6333 6334 bool ValidString = true; 6335 if (IsARMBuiltin) { 6336 ValidString &= Fields[0].startswith_lower("cp") || 6337 Fields[0].startswith_lower("p"); 6338 if (ValidString) 6339 Fields[0] = 6340 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6341 6342 ValidString &= Fields[2].startswith_lower("c"); 6343 if (ValidString) 6344 Fields[2] = Fields[2].drop_front(1); 6345 6346 if (FiveFields) { 6347 ValidString &= Fields[3].startswith_lower("c"); 6348 if (ValidString) 6349 Fields[3] = Fields[3].drop_front(1); 6350 } 6351 } 6352 6353 SmallVector<int, 5> Ranges; 6354 if (FiveFields) 6355 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6356 else 6357 Ranges.append({15, 7, 15}); 6358 6359 for (unsigned i=0; i<Fields.size(); ++i) { 6360 int IntField; 6361 ValidString &= !Fields[i].getAsInteger(10, IntField); 6362 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6363 } 6364 6365 if (!ValidString) 6366 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6367 << Arg->getSourceRange(); 6368 } else if (IsAArch64Builtin && Fields.size() == 1) { 6369 // If the register name is one of those that appear in the condition below 6370 // and the special register builtin being used is one of the write builtins, 6371 // then we require that the argument provided for writing to the register 6372 // is an integer constant expression. This is because it will be lowered to 6373 // an MSR (immediate) instruction, so we need to know the immediate at 6374 // compile time. 6375 if (TheCall->getNumArgs() != 2) 6376 return false; 6377 6378 std::string RegLower = Reg.lower(); 6379 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6380 RegLower != "pan" && RegLower != "uao") 6381 return false; 6382 6383 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6384 } 6385 6386 return false; 6387 } 6388 6389 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6390 /// This checks that the target supports __builtin_longjmp and 6391 /// that val is a constant 1. 6392 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6393 if (!Context.getTargetInfo().hasSjLjLowering()) 6394 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6395 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6396 6397 Expr *Arg = TheCall->getArg(1); 6398 llvm::APSInt Result; 6399 6400 // TODO: This is less than ideal. Overload this to take a value. 6401 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6402 return true; 6403 6404 if (Result != 1) 6405 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6406 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6407 6408 return false; 6409 } 6410 6411 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6412 /// This checks that the target supports __builtin_setjmp. 6413 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6414 if (!Context.getTargetInfo().hasSjLjLowering()) 6415 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6416 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6417 return false; 6418 } 6419 6420 namespace { 6421 6422 class UncoveredArgHandler { 6423 enum { Unknown = -1, AllCovered = -2 }; 6424 6425 signed FirstUncoveredArg = Unknown; 6426 SmallVector<const Expr *, 4> DiagnosticExprs; 6427 6428 public: 6429 UncoveredArgHandler() = default; 6430 6431 bool hasUncoveredArg() const { 6432 return (FirstUncoveredArg >= 0); 6433 } 6434 6435 unsigned getUncoveredArg() const { 6436 assert(hasUncoveredArg() && "no uncovered argument"); 6437 return FirstUncoveredArg; 6438 } 6439 6440 void setAllCovered() { 6441 // A string has been found with all arguments covered, so clear out 6442 // the diagnostics. 6443 DiagnosticExprs.clear(); 6444 FirstUncoveredArg = AllCovered; 6445 } 6446 6447 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6448 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6449 6450 // Don't update if a previous string covers all arguments. 6451 if (FirstUncoveredArg == AllCovered) 6452 return; 6453 6454 // UncoveredArgHandler tracks the highest uncovered argument index 6455 // and with it all the strings that match this index. 6456 if (NewFirstUncoveredArg == FirstUncoveredArg) 6457 DiagnosticExprs.push_back(StrExpr); 6458 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6459 DiagnosticExprs.clear(); 6460 DiagnosticExprs.push_back(StrExpr); 6461 FirstUncoveredArg = NewFirstUncoveredArg; 6462 } 6463 } 6464 6465 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6466 }; 6467 6468 enum StringLiteralCheckType { 6469 SLCT_NotALiteral, 6470 SLCT_UncheckedLiteral, 6471 SLCT_CheckedLiteral 6472 }; 6473 6474 } // namespace 6475 6476 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6477 BinaryOperatorKind BinOpKind, 6478 bool AddendIsRight) { 6479 unsigned BitWidth = Offset.getBitWidth(); 6480 unsigned AddendBitWidth = Addend.getBitWidth(); 6481 // There might be negative interim results. 6482 if (Addend.isUnsigned()) { 6483 Addend = Addend.zext(++AddendBitWidth); 6484 Addend.setIsSigned(true); 6485 } 6486 // Adjust the bit width of the APSInts. 6487 if (AddendBitWidth > BitWidth) { 6488 Offset = Offset.sext(AddendBitWidth); 6489 BitWidth = AddendBitWidth; 6490 } else if (BitWidth > AddendBitWidth) { 6491 Addend = Addend.sext(BitWidth); 6492 } 6493 6494 bool Ov = false; 6495 llvm::APSInt ResOffset = Offset; 6496 if (BinOpKind == BO_Add) 6497 ResOffset = Offset.sadd_ov(Addend, Ov); 6498 else { 6499 assert(AddendIsRight && BinOpKind == BO_Sub && 6500 "operator must be add or sub with addend on the right"); 6501 ResOffset = Offset.ssub_ov(Addend, Ov); 6502 } 6503 6504 // We add an offset to a pointer here so we should support an offset as big as 6505 // possible. 6506 if (Ov) { 6507 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6508 "index (intermediate) result too big"); 6509 Offset = Offset.sext(2 * BitWidth); 6510 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6511 return; 6512 } 6513 6514 Offset = ResOffset; 6515 } 6516 6517 namespace { 6518 6519 // This is a wrapper class around StringLiteral to support offsetted string 6520 // literals as format strings. It takes the offset into account when returning 6521 // the string and its length or the source locations to display notes correctly. 6522 class FormatStringLiteral { 6523 const StringLiteral *FExpr; 6524 int64_t Offset; 6525 6526 public: 6527 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6528 : FExpr(fexpr), Offset(Offset) {} 6529 6530 StringRef getString() const { 6531 return FExpr->getString().drop_front(Offset); 6532 } 6533 6534 unsigned getByteLength() const { 6535 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6536 } 6537 6538 unsigned getLength() const { return FExpr->getLength() - Offset; } 6539 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6540 6541 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6542 6543 QualType getType() const { return FExpr->getType(); } 6544 6545 bool isAscii() const { return FExpr->isAscii(); } 6546 bool isWide() const { return FExpr->isWide(); } 6547 bool isUTF8() const { return FExpr->isUTF8(); } 6548 bool isUTF16() const { return FExpr->isUTF16(); } 6549 bool isUTF32() const { return FExpr->isUTF32(); } 6550 bool isPascal() const { return FExpr->isPascal(); } 6551 6552 SourceLocation getLocationOfByte( 6553 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6554 const TargetInfo &Target, unsigned *StartToken = nullptr, 6555 unsigned *StartTokenByteOffset = nullptr) const { 6556 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6557 StartToken, StartTokenByteOffset); 6558 } 6559 6560 SourceLocation getBeginLoc() const LLVM_READONLY { 6561 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6562 } 6563 6564 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6565 }; 6566 6567 } // namespace 6568 6569 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6570 const Expr *OrigFormatExpr, 6571 ArrayRef<const Expr *> Args, 6572 bool HasVAListArg, unsigned format_idx, 6573 unsigned firstDataArg, 6574 Sema::FormatStringType Type, 6575 bool inFunctionCall, 6576 Sema::VariadicCallType CallType, 6577 llvm::SmallBitVector &CheckedVarArgs, 6578 UncoveredArgHandler &UncoveredArg); 6579 6580 // Determine if an expression is a string literal or constant string. 6581 // If this function returns false on the arguments to a function expecting a 6582 // format string, we will usually need to emit a warning. 6583 // True string literals are then checked by CheckFormatString. 6584 static StringLiteralCheckType 6585 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6586 bool HasVAListArg, unsigned format_idx, 6587 unsigned firstDataArg, Sema::FormatStringType Type, 6588 Sema::VariadicCallType CallType, bool InFunctionCall, 6589 llvm::SmallBitVector &CheckedVarArgs, 6590 UncoveredArgHandler &UncoveredArg, 6591 llvm::APSInt Offset) { 6592 if (S.isConstantEvaluated()) 6593 return SLCT_NotALiteral; 6594 tryAgain: 6595 assert(Offset.isSigned() && "invalid offset"); 6596 6597 if (E->isTypeDependent() || E->isValueDependent()) 6598 return SLCT_NotALiteral; 6599 6600 E = E->IgnoreParenCasts(); 6601 6602 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6603 // Technically -Wformat-nonliteral does not warn about this case. 6604 // The behavior of printf and friends in this case is implementation 6605 // dependent. Ideally if the format string cannot be null then 6606 // it should have a 'nonnull' attribute in the function prototype. 6607 return SLCT_UncheckedLiteral; 6608 6609 switch (E->getStmtClass()) { 6610 case Stmt::BinaryConditionalOperatorClass: 6611 case Stmt::ConditionalOperatorClass: { 6612 // The expression is a literal if both sub-expressions were, and it was 6613 // completely checked only if both sub-expressions were checked. 6614 const AbstractConditionalOperator *C = 6615 cast<AbstractConditionalOperator>(E); 6616 6617 // Determine whether it is necessary to check both sub-expressions, for 6618 // example, because the condition expression is a constant that can be 6619 // evaluated at compile time. 6620 bool CheckLeft = true, CheckRight = true; 6621 6622 bool Cond; 6623 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6624 S.isConstantEvaluated())) { 6625 if (Cond) 6626 CheckRight = false; 6627 else 6628 CheckLeft = false; 6629 } 6630 6631 // We need to maintain the offsets for the right and the left hand side 6632 // separately to check if every possible indexed expression is a valid 6633 // string literal. They might have different offsets for different string 6634 // literals in the end. 6635 StringLiteralCheckType Left; 6636 if (!CheckLeft) 6637 Left = SLCT_UncheckedLiteral; 6638 else { 6639 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6640 HasVAListArg, format_idx, firstDataArg, 6641 Type, CallType, InFunctionCall, 6642 CheckedVarArgs, UncoveredArg, Offset); 6643 if (Left == SLCT_NotALiteral || !CheckRight) { 6644 return Left; 6645 } 6646 } 6647 6648 StringLiteralCheckType Right = 6649 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6650 HasVAListArg, format_idx, firstDataArg, 6651 Type, CallType, InFunctionCall, CheckedVarArgs, 6652 UncoveredArg, Offset); 6653 6654 return (CheckLeft && Left < Right) ? Left : Right; 6655 } 6656 6657 case Stmt::ImplicitCastExprClass: 6658 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6659 goto tryAgain; 6660 6661 case Stmt::OpaqueValueExprClass: 6662 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6663 E = src; 6664 goto tryAgain; 6665 } 6666 return SLCT_NotALiteral; 6667 6668 case Stmt::PredefinedExprClass: 6669 // While __func__, etc., are technically not string literals, they 6670 // cannot contain format specifiers and thus are not a security 6671 // liability. 6672 return SLCT_UncheckedLiteral; 6673 6674 case Stmt::DeclRefExprClass: { 6675 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6676 6677 // As an exception, do not flag errors for variables binding to 6678 // const string literals. 6679 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6680 bool isConstant = false; 6681 QualType T = DR->getType(); 6682 6683 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6684 isConstant = AT->getElementType().isConstant(S.Context); 6685 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6686 isConstant = T.isConstant(S.Context) && 6687 PT->getPointeeType().isConstant(S.Context); 6688 } else if (T->isObjCObjectPointerType()) { 6689 // In ObjC, there is usually no "const ObjectPointer" type, 6690 // so don't check if the pointee type is constant. 6691 isConstant = T.isConstant(S.Context); 6692 } 6693 6694 if (isConstant) { 6695 if (const Expr *Init = VD->getAnyInitializer()) { 6696 // Look through initializers like const char c[] = { "foo" } 6697 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6698 if (InitList->isStringLiteralInit()) 6699 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6700 } 6701 return checkFormatStringExpr(S, Init, Args, 6702 HasVAListArg, format_idx, 6703 firstDataArg, Type, CallType, 6704 /*InFunctionCall*/ false, CheckedVarArgs, 6705 UncoveredArg, Offset); 6706 } 6707 } 6708 6709 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6710 // special check to see if the format string is a function parameter 6711 // of the function calling the printf function. If the function 6712 // has an attribute indicating it is a printf-like function, then we 6713 // should suppress warnings concerning non-literals being used in a call 6714 // to a vprintf function. For example: 6715 // 6716 // void 6717 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6718 // va_list ap; 6719 // va_start(ap, fmt); 6720 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6721 // ... 6722 // } 6723 if (HasVAListArg) { 6724 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6725 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6726 int PVIndex = PV->getFunctionScopeIndex() + 1; 6727 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6728 // adjust for implicit parameter 6729 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6730 if (MD->isInstance()) 6731 ++PVIndex; 6732 // We also check if the formats are compatible. 6733 // We can't pass a 'scanf' string to a 'printf' function. 6734 if (PVIndex == PVFormat->getFormatIdx() && 6735 Type == S.GetFormatStringType(PVFormat)) 6736 return SLCT_UncheckedLiteral; 6737 } 6738 } 6739 } 6740 } 6741 } 6742 6743 return SLCT_NotALiteral; 6744 } 6745 6746 case Stmt::CallExprClass: 6747 case Stmt::CXXMemberCallExprClass: { 6748 const CallExpr *CE = cast<CallExpr>(E); 6749 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6750 bool IsFirst = true; 6751 StringLiteralCheckType CommonResult; 6752 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6753 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6754 StringLiteralCheckType Result = checkFormatStringExpr( 6755 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6756 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6757 if (IsFirst) { 6758 CommonResult = Result; 6759 IsFirst = false; 6760 } 6761 } 6762 if (!IsFirst) 6763 return CommonResult; 6764 6765 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6766 unsigned BuiltinID = FD->getBuiltinID(); 6767 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6768 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6769 const Expr *Arg = CE->getArg(0); 6770 return checkFormatStringExpr(S, Arg, Args, 6771 HasVAListArg, format_idx, 6772 firstDataArg, Type, CallType, 6773 InFunctionCall, CheckedVarArgs, 6774 UncoveredArg, Offset); 6775 } 6776 } 6777 } 6778 6779 return SLCT_NotALiteral; 6780 } 6781 case Stmt::ObjCMessageExprClass: { 6782 const auto *ME = cast<ObjCMessageExpr>(E); 6783 if (const auto *ND = ME->getMethodDecl()) { 6784 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6785 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6786 return checkFormatStringExpr( 6787 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6788 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6789 } 6790 } 6791 6792 return SLCT_NotALiteral; 6793 } 6794 case Stmt::ObjCStringLiteralClass: 6795 case Stmt::StringLiteralClass: { 6796 const StringLiteral *StrE = nullptr; 6797 6798 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6799 StrE = ObjCFExpr->getString(); 6800 else 6801 StrE = cast<StringLiteral>(E); 6802 6803 if (StrE) { 6804 if (Offset.isNegative() || Offset > StrE->getLength()) { 6805 // TODO: It would be better to have an explicit warning for out of 6806 // bounds literals. 6807 return SLCT_NotALiteral; 6808 } 6809 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6810 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6811 firstDataArg, Type, InFunctionCall, CallType, 6812 CheckedVarArgs, UncoveredArg); 6813 return SLCT_CheckedLiteral; 6814 } 6815 6816 return SLCT_NotALiteral; 6817 } 6818 case Stmt::BinaryOperatorClass: { 6819 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6820 6821 // A string literal + an int offset is still a string literal. 6822 if (BinOp->isAdditiveOp()) { 6823 Expr::EvalResult LResult, RResult; 6824 6825 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6826 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6827 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6828 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6829 6830 if (LIsInt != RIsInt) { 6831 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6832 6833 if (LIsInt) { 6834 if (BinOpKind == BO_Add) { 6835 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6836 E = BinOp->getRHS(); 6837 goto tryAgain; 6838 } 6839 } else { 6840 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6841 E = BinOp->getLHS(); 6842 goto tryAgain; 6843 } 6844 } 6845 } 6846 6847 return SLCT_NotALiteral; 6848 } 6849 case Stmt::UnaryOperatorClass: { 6850 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6851 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6852 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6853 Expr::EvalResult IndexResult; 6854 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6855 Expr::SE_NoSideEffects, 6856 S.isConstantEvaluated())) { 6857 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6858 /*RHS is int*/ true); 6859 E = ASE->getBase(); 6860 goto tryAgain; 6861 } 6862 } 6863 6864 return SLCT_NotALiteral; 6865 } 6866 6867 default: 6868 return SLCT_NotALiteral; 6869 } 6870 } 6871 6872 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6873 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6874 .Case("scanf", FST_Scanf) 6875 .Cases("printf", "printf0", FST_Printf) 6876 .Cases("NSString", "CFString", FST_NSString) 6877 .Case("strftime", FST_Strftime) 6878 .Case("strfmon", FST_Strfmon) 6879 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6880 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6881 .Case("os_trace", FST_OSLog) 6882 .Case("os_log", FST_OSLog) 6883 .Default(FST_Unknown); 6884 } 6885 6886 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6887 /// functions) for correct use of format strings. 6888 /// Returns true if a format string has been fully checked. 6889 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6890 ArrayRef<const Expr *> Args, 6891 bool IsCXXMember, 6892 VariadicCallType CallType, 6893 SourceLocation Loc, SourceRange Range, 6894 llvm::SmallBitVector &CheckedVarArgs) { 6895 FormatStringInfo FSI; 6896 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6897 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6898 FSI.FirstDataArg, GetFormatStringType(Format), 6899 CallType, Loc, Range, CheckedVarArgs); 6900 return false; 6901 } 6902 6903 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6904 bool HasVAListArg, unsigned format_idx, 6905 unsigned firstDataArg, FormatStringType Type, 6906 VariadicCallType CallType, 6907 SourceLocation Loc, SourceRange Range, 6908 llvm::SmallBitVector &CheckedVarArgs) { 6909 // CHECK: printf/scanf-like function is called with no format string. 6910 if (format_idx >= Args.size()) { 6911 Diag(Loc, diag::warn_missing_format_string) << Range; 6912 return false; 6913 } 6914 6915 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6916 6917 // CHECK: format string is not a string literal. 6918 // 6919 // Dynamically generated format strings are difficult to 6920 // automatically vet at compile time. Requiring that format strings 6921 // are string literals: (1) permits the checking of format strings by 6922 // the compiler and thereby (2) can practically remove the source of 6923 // many format string exploits. 6924 6925 // Format string can be either ObjC string (e.g. @"%d") or 6926 // C string (e.g. "%d") 6927 // ObjC string uses the same format specifiers as C string, so we can use 6928 // the same format string checking logic for both ObjC and C strings. 6929 UncoveredArgHandler UncoveredArg; 6930 StringLiteralCheckType CT = 6931 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6932 format_idx, firstDataArg, Type, CallType, 6933 /*IsFunctionCall*/ true, CheckedVarArgs, 6934 UncoveredArg, 6935 /*no string offset*/ llvm::APSInt(64, false) = 0); 6936 6937 // Generate a diagnostic where an uncovered argument is detected. 6938 if (UncoveredArg.hasUncoveredArg()) { 6939 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6940 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6941 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6942 } 6943 6944 if (CT != SLCT_NotALiteral) 6945 // Literal format string found, check done! 6946 return CT == SLCT_CheckedLiteral; 6947 6948 // Strftime is particular as it always uses a single 'time' argument, 6949 // so it is safe to pass a non-literal string. 6950 if (Type == FST_Strftime) 6951 return false; 6952 6953 // Do not emit diag when the string param is a macro expansion and the 6954 // format is either NSString or CFString. This is a hack to prevent 6955 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6956 // which are usually used in place of NS and CF string literals. 6957 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6958 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6959 return false; 6960 6961 // If there are no arguments specified, warn with -Wformat-security, otherwise 6962 // warn only with -Wformat-nonliteral. 6963 if (Args.size() == firstDataArg) { 6964 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6965 << OrigFormatExpr->getSourceRange(); 6966 switch (Type) { 6967 default: 6968 break; 6969 case FST_Kprintf: 6970 case FST_FreeBSDKPrintf: 6971 case FST_Printf: 6972 Diag(FormatLoc, diag::note_format_security_fixit) 6973 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6974 break; 6975 case FST_NSString: 6976 Diag(FormatLoc, diag::note_format_security_fixit) 6977 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6978 break; 6979 } 6980 } else { 6981 Diag(FormatLoc, diag::warn_format_nonliteral) 6982 << OrigFormatExpr->getSourceRange(); 6983 } 6984 return false; 6985 } 6986 6987 namespace { 6988 6989 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6990 protected: 6991 Sema &S; 6992 const FormatStringLiteral *FExpr; 6993 const Expr *OrigFormatExpr; 6994 const Sema::FormatStringType FSType; 6995 const unsigned FirstDataArg; 6996 const unsigned NumDataArgs; 6997 const char *Beg; // Start of format string. 6998 const bool HasVAListArg; 6999 ArrayRef<const Expr *> Args; 7000 unsigned FormatIdx; 7001 llvm::SmallBitVector CoveredArgs; 7002 bool usesPositionalArgs = false; 7003 bool atFirstArg = true; 7004 bool inFunctionCall; 7005 Sema::VariadicCallType CallType; 7006 llvm::SmallBitVector &CheckedVarArgs; 7007 UncoveredArgHandler &UncoveredArg; 7008 7009 public: 7010 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7011 const Expr *origFormatExpr, 7012 const Sema::FormatStringType type, unsigned firstDataArg, 7013 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7014 ArrayRef<const Expr *> Args, unsigned formatIdx, 7015 bool inFunctionCall, Sema::VariadicCallType callType, 7016 llvm::SmallBitVector &CheckedVarArgs, 7017 UncoveredArgHandler &UncoveredArg) 7018 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7019 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7020 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7021 inFunctionCall(inFunctionCall), CallType(callType), 7022 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7023 CoveredArgs.resize(numDataArgs); 7024 CoveredArgs.reset(); 7025 } 7026 7027 void DoneProcessing(); 7028 7029 void HandleIncompleteSpecifier(const char *startSpecifier, 7030 unsigned specifierLen) override; 7031 7032 void HandleInvalidLengthModifier( 7033 const analyze_format_string::FormatSpecifier &FS, 7034 const analyze_format_string::ConversionSpecifier &CS, 7035 const char *startSpecifier, unsigned specifierLen, 7036 unsigned DiagID); 7037 7038 void HandleNonStandardLengthModifier( 7039 const analyze_format_string::FormatSpecifier &FS, 7040 const char *startSpecifier, unsigned specifierLen); 7041 7042 void HandleNonStandardConversionSpecifier( 7043 const analyze_format_string::ConversionSpecifier &CS, 7044 const char *startSpecifier, unsigned specifierLen); 7045 7046 void HandlePosition(const char *startPos, unsigned posLen) override; 7047 7048 void HandleInvalidPosition(const char *startSpecifier, 7049 unsigned specifierLen, 7050 analyze_format_string::PositionContext p) override; 7051 7052 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7053 7054 void HandleNullChar(const char *nullCharacter) override; 7055 7056 template <typename Range> 7057 static void 7058 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7059 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7060 bool IsStringLocation, Range StringRange, 7061 ArrayRef<FixItHint> Fixit = None); 7062 7063 protected: 7064 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7065 const char *startSpec, 7066 unsigned specifierLen, 7067 const char *csStart, unsigned csLen); 7068 7069 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7070 const char *startSpec, 7071 unsigned specifierLen); 7072 7073 SourceRange getFormatStringRange(); 7074 CharSourceRange getSpecifierRange(const char *startSpecifier, 7075 unsigned specifierLen); 7076 SourceLocation getLocationOfByte(const char *x); 7077 7078 const Expr *getDataArg(unsigned i) const; 7079 7080 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7081 const analyze_format_string::ConversionSpecifier &CS, 7082 const char *startSpecifier, unsigned specifierLen, 7083 unsigned argIndex); 7084 7085 template <typename Range> 7086 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7087 bool IsStringLocation, Range StringRange, 7088 ArrayRef<FixItHint> Fixit = None); 7089 }; 7090 7091 } // namespace 7092 7093 SourceRange CheckFormatHandler::getFormatStringRange() { 7094 return OrigFormatExpr->getSourceRange(); 7095 } 7096 7097 CharSourceRange CheckFormatHandler:: 7098 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7099 SourceLocation Start = getLocationOfByte(startSpecifier); 7100 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7101 7102 // Advance the end SourceLocation by one due to half-open ranges. 7103 End = End.getLocWithOffset(1); 7104 7105 return CharSourceRange::getCharRange(Start, End); 7106 } 7107 7108 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7109 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7110 S.getLangOpts(), S.Context.getTargetInfo()); 7111 } 7112 7113 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7114 unsigned specifierLen){ 7115 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7116 getLocationOfByte(startSpecifier), 7117 /*IsStringLocation*/true, 7118 getSpecifierRange(startSpecifier, specifierLen)); 7119 } 7120 7121 void CheckFormatHandler::HandleInvalidLengthModifier( 7122 const analyze_format_string::FormatSpecifier &FS, 7123 const analyze_format_string::ConversionSpecifier &CS, 7124 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7125 using namespace analyze_format_string; 7126 7127 const LengthModifier &LM = FS.getLengthModifier(); 7128 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7129 7130 // See if we know how to fix this length modifier. 7131 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7132 if (FixedLM) { 7133 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7134 getLocationOfByte(LM.getStart()), 7135 /*IsStringLocation*/true, 7136 getSpecifierRange(startSpecifier, specifierLen)); 7137 7138 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7139 << FixedLM->toString() 7140 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7141 7142 } else { 7143 FixItHint Hint; 7144 if (DiagID == diag::warn_format_nonsensical_length) 7145 Hint = FixItHint::CreateRemoval(LMRange); 7146 7147 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7148 getLocationOfByte(LM.getStart()), 7149 /*IsStringLocation*/true, 7150 getSpecifierRange(startSpecifier, specifierLen), 7151 Hint); 7152 } 7153 } 7154 7155 void CheckFormatHandler::HandleNonStandardLengthModifier( 7156 const analyze_format_string::FormatSpecifier &FS, 7157 const char *startSpecifier, unsigned specifierLen) { 7158 using namespace analyze_format_string; 7159 7160 const LengthModifier &LM = FS.getLengthModifier(); 7161 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7162 7163 // See if we know how to fix this length modifier. 7164 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7165 if (FixedLM) { 7166 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7167 << LM.toString() << 0, 7168 getLocationOfByte(LM.getStart()), 7169 /*IsStringLocation*/true, 7170 getSpecifierRange(startSpecifier, specifierLen)); 7171 7172 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7173 << FixedLM->toString() 7174 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7175 7176 } else { 7177 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7178 << LM.toString() << 0, 7179 getLocationOfByte(LM.getStart()), 7180 /*IsStringLocation*/true, 7181 getSpecifierRange(startSpecifier, specifierLen)); 7182 } 7183 } 7184 7185 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7186 const analyze_format_string::ConversionSpecifier &CS, 7187 const char *startSpecifier, unsigned specifierLen) { 7188 using namespace analyze_format_string; 7189 7190 // See if we know how to fix this conversion specifier. 7191 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7192 if (FixedCS) { 7193 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7194 << CS.toString() << /*conversion specifier*/1, 7195 getLocationOfByte(CS.getStart()), 7196 /*IsStringLocation*/true, 7197 getSpecifierRange(startSpecifier, specifierLen)); 7198 7199 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7200 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7201 << FixedCS->toString() 7202 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7203 } else { 7204 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7205 << CS.toString() << /*conversion specifier*/1, 7206 getLocationOfByte(CS.getStart()), 7207 /*IsStringLocation*/true, 7208 getSpecifierRange(startSpecifier, specifierLen)); 7209 } 7210 } 7211 7212 void CheckFormatHandler::HandlePosition(const char *startPos, 7213 unsigned posLen) { 7214 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7215 getLocationOfByte(startPos), 7216 /*IsStringLocation*/true, 7217 getSpecifierRange(startPos, posLen)); 7218 } 7219 7220 void 7221 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7222 analyze_format_string::PositionContext p) { 7223 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7224 << (unsigned) p, 7225 getLocationOfByte(startPos), /*IsStringLocation*/true, 7226 getSpecifierRange(startPos, posLen)); 7227 } 7228 7229 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7230 unsigned posLen) { 7231 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7232 getLocationOfByte(startPos), 7233 /*IsStringLocation*/true, 7234 getSpecifierRange(startPos, posLen)); 7235 } 7236 7237 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7238 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7239 // The presence of a null character is likely an error. 7240 EmitFormatDiagnostic( 7241 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7242 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7243 getFormatStringRange()); 7244 } 7245 } 7246 7247 // Note that this may return NULL if there was an error parsing or building 7248 // one of the argument expressions. 7249 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7250 return Args[FirstDataArg + i]; 7251 } 7252 7253 void CheckFormatHandler::DoneProcessing() { 7254 // Does the number of data arguments exceed the number of 7255 // format conversions in the format string? 7256 if (!HasVAListArg) { 7257 // Find any arguments that weren't covered. 7258 CoveredArgs.flip(); 7259 signed notCoveredArg = CoveredArgs.find_first(); 7260 if (notCoveredArg >= 0) { 7261 assert((unsigned)notCoveredArg < NumDataArgs); 7262 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7263 } else { 7264 UncoveredArg.setAllCovered(); 7265 } 7266 } 7267 } 7268 7269 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7270 const Expr *ArgExpr) { 7271 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7272 "Invalid state"); 7273 7274 if (!ArgExpr) 7275 return; 7276 7277 SourceLocation Loc = ArgExpr->getBeginLoc(); 7278 7279 if (S.getSourceManager().isInSystemMacro(Loc)) 7280 return; 7281 7282 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7283 for (auto E : DiagnosticExprs) 7284 PDiag << E->getSourceRange(); 7285 7286 CheckFormatHandler::EmitFormatDiagnostic( 7287 S, IsFunctionCall, DiagnosticExprs[0], 7288 PDiag, Loc, /*IsStringLocation*/false, 7289 DiagnosticExprs[0]->getSourceRange()); 7290 } 7291 7292 bool 7293 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7294 SourceLocation Loc, 7295 const char *startSpec, 7296 unsigned specifierLen, 7297 const char *csStart, 7298 unsigned csLen) { 7299 bool keepGoing = true; 7300 if (argIndex < NumDataArgs) { 7301 // Consider the argument coverered, even though the specifier doesn't 7302 // make sense. 7303 CoveredArgs.set(argIndex); 7304 } 7305 else { 7306 // If argIndex exceeds the number of data arguments we 7307 // don't issue a warning because that is just a cascade of warnings (and 7308 // they may have intended '%%' anyway). We don't want to continue processing 7309 // the format string after this point, however, as we will like just get 7310 // gibberish when trying to match arguments. 7311 keepGoing = false; 7312 } 7313 7314 StringRef Specifier(csStart, csLen); 7315 7316 // If the specifier in non-printable, it could be the first byte of a UTF-8 7317 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7318 // hex value. 7319 std::string CodePointStr; 7320 if (!llvm::sys::locale::isPrint(*csStart)) { 7321 llvm::UTF32 CodePoint; 7322 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7323 const llvm::UTF8 *E = 7324 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7325 llvm::ConversionResult Result = 7326 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7327 7328 if (Result != llvm::conversionOK) { 7329 unsigned char FirstChar = *csStart; 7330 CodePoint = (llvm::UTF32)FirstChar; 7331 } 7332 7333 llvm::raw_string_ostream OS(CodePointStr); 7334 if (CodePoint < 256) 7335 OS << "\\x" << llvm::format("%02x", CodePoint); 7336 else if (CodePoint <= 0xFFFF) 7337 OS << "\\u" << llvm::format("%04x", CodePoint); 7338 else 7339 OS << "\\U" << llvm::format("%08x", CodePoint); 7340 OS.flush(); 7341 Specifier = CodePointStr; 7342 } 7343 7344 EmitFormatDiagnostic( 7345 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7346 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7347 7348 return keepGoing; 7349 } 7350 7351 void 7352 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7353 const char *startSpec, 7354 unsigned specifierLen) { 7355 EmitFormatDiagnostic( 7356 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7357 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7358 } 7359 7360 bool 7361 CheckFormatHandler::CheckNumArgs( 7362 const analyze_format_string::FormatSpecifier &FS, 7363 const analyze_format_string::ConversionSpecifier &CS, 7364 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7365 7366 if (argIndex >= NumDataArgs) { 7367 PartialDiagnostic PDiag = FS.usesPositionalArg() 7368 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7369 << (argIndex+1) << NumDataArgs) 7370 : S.PDiag(diag::warn_printf_insufficient_data_args); 7371 EmitFormatDiagnostic( 7372 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7373 getSpecifierRange(startSpecifier, specifierLen)); 7374 7375 // Since more arguments than conversion tokens are given, by extension 7376 // all arguments are covered, so mark this as so. 7377 UncoveredArg.setAllCovered(); 7378 return false; 7379 } 7380 return true; 7381 } 7382 7383 template<typename Range> 7384 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7385 SourceLocation Loc, 7386 bool IsStringLocation, 7387 Range StringRange, 7388 ArrayRef<FixItHint> FixIt) { 7389 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7390 Loc, IsStringLocation, StringRange, FixIt); 7391 } 7392 7393 /// If the format string is not within the function call, emit a note 7394 /// so that the function call and string are in diagnostic messages. 7395 /// 7396 /// \param InFunctionCall if true, the format string is within the function 7397 /// call and only one diagnostic message will be produced. Otherwise, an 7398 /// extra note will be emitted pointing to location of the format string. 7399 /// 7400 /// \param ArgumentExpr the expression that is passed as the format string 7401 /// argument in the function call. Used for getting locations when two 7402 /// diagnostics are emitted. 7403 /// 7404 /// \param PDiag the callee should already have provided any strings for the 7405 /// diagnostic message. This function only adds locations and fixits 7406 /// to diagnostics. 7407 /// 7408 /// \param Loc primary location for diagnostic. If two diagnostics are 7409 /// required, one will be at Loc and a new SourceLocation will be created for 7410 /// the other one. 7411 /// 7412 /// \param IsStringLocation if true, Loc points to the format string should be 7413 /// used for the note. Otherwise, Loc points to the argument list and will 7414 /// be used with PDiag. 7415 /// 7416 /// \param StringRange some or all of the string to highlight. This is 7417 /// templated so it can accept either a CharSourceRange or a SourceRange. 7418 /// 7419 /// \param FixIt optional fix it hint for the format string. 7420 template <typename Range> 7421 void CheckFormatHandler::EmitFormatDiagnostic( 7422 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7423 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7424 Range StringRange, ArrayRef<FixItHint> FixIt) { 7425 if (InFunctionCall) { 7426 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7427 D << StringRange; 7428 D << FixIt; 7429 } else { 7430 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7431 << ArgumentExpr->getSourceRange(); 7432 7433 const Sema::SemaDiagnosticBuilder &Note = 7434 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7435 diag::note_format_string_defined); 7436 7437 Note << StringRange; 7438 Note << FixIt; 7439 } 7440 } 7441 7442 //===--- CHECK: Printf format string checking ------------------------------===// 7443 7444 namespace { 7445 7446 class CheckPrintfHandler : public CheckFormatHandler { 7447 public: 7448 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7449 const Expr *origFormatExpr, 7450 const Sema::FormatStringType type, unsigned firstDataArg, 7451 unsigned numDataArgs, bool isObjC, const char *beg, 7452 bool hasVAListArg, ArrayRef<const Expr *> Args, 7453 unsigned formatIdx, bool inFunctionCall, 7454 Sema::VariadicCallType CallType, 7455 llvm::SmallBitVector &CheckedVarArgs, 7456 UncoveredArgHandler &UncoveredArg) 7457 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7458 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7459 inFunctionCall, CallType, CheckedVarArgs, 7460 UncoveredArg) {} 7461 7462 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7463 7464 /// Returns true if '%@' specifiers are allowed in the format string. 7465 bool allowsObjCArg() const { 7466 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7467 FSType == Sema::FST_OSTrace; 7468 } 7469 7470 bool HandleInvalidPrintfConversionSpecifier( 7471 const analyze_printf::PrintfSpecifier &FS, 7472 const char *startSpecifier, 7473 unsigned specifierLen) override; 7474 7475 void handleInvalidMaskType(StringRef MaskType) override; 7476 7477 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7478 const char *startSpecifier, 7479 unsigned specifierLen) override; 7480 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7481 const char *StartSpecifier, 7482 unsigned SpecifierLen, 7483 const Expr *E); 7484 7485 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7486 const char *startSpecifier, unsigned specifierLen); 7487 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7488 const analyze_printf::OptionalAmount &Amt, 7489 unsigned type, 7490 const char *startSpecifier, unsigned specifierLen); 7491 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7492 const analyze_printf::OptionalFlag &flag, 7493 const char *startSpecifier, unsigned specifierLen); 7494 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7495 const analyze_printf::OptionalFlag &ignoredFlag, 7496 const analyze_printf::OptionalFlag &flag, 7497 const char *startSpecifier, unsigned specifierLen); 7498 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7499 const Expr *E); 7500 7501 void HandleEmptyObjCModifierFlag(const char *startFlag, 7502 unsigned flagLen) override; 7503 7504 void HandleInvalidObjCModifierFlag(const char *startFlag, 7505 unsigned flagLen) override; 7506 7507 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7508 const char *flagsEnd, 7509 const char *conversionPosition) 7510 override; 7511 }; 7512 7513 } // namespace 7514 7515 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7516 const analyze_printf::PrintfSpecifier &FS, 7517 const char *startSpecifier, 7518 unsigned specifierLen) { 7519 const analyze_printf::PrintfConversionSpecifier &CS = 7520 FS.getConversionSpecifier(); 7521 7522 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7523 getLocationOfByte(CS.getStart()), 7524 startSpecifier, specifierLen, 7525 CS.getStart(), CS.getLength()); 7526 } 7527 7528 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7529 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7530 } 7531 7532 bool CheckPrintfHandler::HandleAmount( 7533 const analyze_format_string::OptionalAmount &Amt, 7534 unsigned k, const char *startSpecifier, 7535 unsigned specifierLen) { 7536 if (Amt.hasDataArgument()) { 7537 if (!HasVAListArg) { 7538 unsigned argIndex = Amt.getArgIndex(); 7539 if (argIndex >= NumDataArgs) { 7540 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7541 << k, 7542 getLocationOfByte(Amt.getStart()), 7543 /*IsStringLocation*/true, 7544 getSpecifierRange(startSpecifier, specifierLen)); 7545 // Don't do any more checking. We will just emit 7546 // spurious errors. 7547 return false; 7548 } 7549 7550 // Type check the data argument. It should be an 'int'. 7551 // Although not in conformance with C99, we also allow the argument to be 7552 // an 'unsigned int' as that is a reasonably safe case. GCC also 7553 // doesn't emit a warning for that case. 7554 CoveredArgs.set(argIndex); 7555 const Expr *Arg = getDataArg(argIndex); 7556 if (!Arg) 7557 return false; 7558 7559 QualType T = Arg->getType(); 7560 7561 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7562 assert(AT.isValid()); 7563 7564 if (!AT.matchesType(S.Context, T)) { 7565 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7566 << k << AT.getRepresentativeTypeName(S.Context) 7567 << T << Arg->getSourceRange(), 7568 getLocationOfByte(Amt.getStart()), 7569 /*IsStringLocation*/true, 7570 getSpecifierRange(startSpecifier, specifierLen)); 7571 // Don't do any more checking. We will just emit 7572 // spurious errors. 7573 return false; 7574 } 7575 } 7576 } 7577 return true; 7578 } 7579 7580 void CheckPrintfHandler::HandleInvalidAmount( 7581 const analyze_printf::PrintfSpecifier &FS, 7582 const analyze_printf::OptionalAmount &Amt, 7583 unsigned type, 7584 const char *startSpecifier, 7585 unsigned specifierLen) { 7586 const analyze_printf::PrintfConversionSpecifier &CS = 7587 FS.getConversionSpecifier(); 7588 7589 FixItHint fixit = 7590 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7591 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7592 Amt.getConstantLength())) 7593 : FixItHint(); 7594 7595 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7596 << type << CS.toString(), 7597 getLocationOfByte(Amt.getStart()), 7598 /*IsStringLocation*/true, 7599 getSpecifierRange(startSpecifier, specifierLen), 7600 fixit); 7601 } 7602 7603 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7604 const analyze_printf::OptionalFlag &flag, 7605 const char *startSpecifier, 7606 unsigned specifierLen) { 7607 // Warn about pointless flag with a fixit removal. 7608 const analyze_printf::PrintfConversionSpecifier &CS = 7609 FS.getConversionSpecifier(); 7610 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7611 << flag.toString() << CS.toString(), 7612 getLocationOfByte(flag.getPosition()), 7613 /*IsStringLocation*/true, 7614 getSpecifierRange(startSpecifier, specifierLen), 7615 FixItHint::CreateRemoval( 7616 getSpecifierRange(flag.getPosition(), 1))); 7617 } 7618 7619 void CheckPrintfHandler::HandleIgnoredFlag( 7620 const analyze_printf::PrintfSpecifier &FS, 7621 const analyze_printf::OptionalFlag &ignoredFlag, 7622 const analyze_printf::OptionalFlag &flag, 7623 const char *startSpecifier, 7624 unsigned specifierLen) { 7625 // Warn about ignored flag with a fixit removal. 7626 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7627 << ignoredFlag.toString() << flag.toString(), 7628 getLocationOfByte(ignoredFlag.getPosition()), 7629 /*IsStringLocation*/true, 7630 getSpecifierRange(startSpecifier, specifierLen), 7631 FixItHint::CreateRemoval( 7632 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7633 } 7634 7635 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7636 unsigned flagLen) { 7637 // Warn about an empty flag. 7638 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7639 getLocationOfByte(startFlag), 7640 /*IsStringLocation*/true, 7641 getSpecifierRange(startFlag, flagLen)); 7642 } 7643 7644 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7645 unsigned flagLen) { 7646 // Warn about an invalid flag. 7647 auto Range = getSpecifierRange(startFlag, flagLen); 7648 StringRef flag(startFlag, flagLen); 7649 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7650 getLocationOfByte(startFlag), 7651 /*IsStringLocation*/true, 7652 Range, FixItHint::CreateRemoval(Range)); 7653 } 7654 7655 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7656 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7657 // Warn about using '[...]' without a '@' conversion. 7658 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7659 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7660 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7661 getLocationOfByte(conversionPosition), 7662 /*IsStringLocation*/true, 7663 Range, FixItHint::CreateRemoval(Range)); 7664 } 7665 7666 // Determines if the specified is a C++ class or struct containing 7667 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7668 // "c_str()"). 7669 template<typename MemberKind> 7670 static llvm::SmallPtrSet<MemberKind*, 1> 7671 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7672 const RecordType *RT = Ty->getAs<RecordType>(); 7673 llvm::SmallPtrSet<MemberKind*, 1> Results; 7674 7675 if (!RT) 7676 return Results; 7677 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7678 if (!RD || !RD->getDefinition()) 7679 return Results; 7680 7681 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7682 Sema::LookupMemberName); 7683 R.suppressDiagnostics(); 7684 7685 // We just need to include all members of the right kind turned up by the 7686 // filter, at this point. 7687 if (S.LookupQualifiedName(R, RT->getDecl())) 7688 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7689 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7690 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7691 Results.insert(FK); 7692 } 7693 return Results; 7694 } 7695 7696 /// Check if we could call '.c_str()' on an object. 7697 /// 7698 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7699 /// allow the call, or if it would be ambiguous). 7700 bool Sema::hasCStrMethod(const Expr *E) { 7701 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7702 7703 MethodSet Results = 7704 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7705 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7706 MI != ME; ++MI) 7707 if ((*MI)->getMinRequiredArguments() == 0) 7708 return true; 7709 return false; 7710 } 7711 7712 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7713 // better diagnostic if so. AT is assumed to be valid. 7714 // Returns true when a c_str() conversion method is found. 7715 bool CheckPrintfHandler::checkForCStrMembers( 7716 const analyze_printf::ArgType &AT, const Expr *E) { 7717 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7718 7719 MethodSet Results = 7720 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7721 7722 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7723 MI != ME; ++MI) { 7724 const CXXMethodDecl *Method = *MI; 7725 if (Method->getMinRequiredArguments() == 0 && 7726 AT.matchesType(S.Context, Method->getReturnType())) { 7727 // FIXME: Suggest parens if the expression needs them. 7728 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7729 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7730 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7731 return true; 7732 } 7733 } 7734 7735 return false; 7736 } 7737 7738 bool 7739 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7740 &FS, 7741 const char *startSpecifier, 7742 unsigned specifierLen) { 7743 using namespace analyze_format_string; 7744 using namespace analyze_printf; 7745 7746 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7747 7748 if (FS.consumesDataArgument()) { 7749 if (atFirstArg) { 7750 atFirstArg = false; 7751 usesPositionalArgs = FS.usesPositionalArg(); 7752 } 7753 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7754 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7755 startSpecifier, specifierLen); 7756 return false; 7757 } 7758 } 7759 7760 // First check if the field width, precision, and conversion specifier 7761 // have matching data arguments. 7762 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7763 startSpecifier, specifierLen)) { 7764 return false; 7765 } 7766 7767 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7768 startSpecifier, specifierLen)) { 7769 return false; 7770 } 7771 7772 if (!CS.consumesDataArgument()) { 7773 // FIXME: Technically specifying a precision or field width here 7774 // makes no sense. Worth issuing a warning at some point. 7775 return true; 7776 } 7777 7778 // Consume the argument. 7779 unsigned argIndex = FS.getArgIndex(); 7780 if (argIndex < NumDataArgs) { 7781 // The check to see if the argIndex is valid will come later. 7782 // We set the bit here because we may exit early from this 7783 // function if we encounter some other error. 7784 CoveredArgs.set(argIndex); 7785 } 7786 7787 // FreeBSD kernel extensions. 7788 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7789 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7790 // We need at least two arguments. 7791 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7792 return false; 7793 7794 // Claim the second argument. 7795 CoveredArgs.set(argIndex + 1); 7796 7797 // Type check the first argument (int for %b, pointer for %D) 7798 const Expr *Ex = getDataArg(argIndex); 7799 const analyze_printf::ArgType &AT = 7800 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7801 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7802 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7803 EmitFormatDiagnostic( 7804 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7805 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7806 << false << Ex->getSourceRange(), 7807 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7808 getSpecifierRange(startSpecifier, specifierLen)); 7809 7810 // Type check the second argument (char * for both %b and %D) 7811 Ex = getDataArg(argIndex + 1); 7812 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7813 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7814 EmitFormatDiagnostic( 7815 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7816 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7817 << false << Ex->getSourceRange(), 7818 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7819 getSpecifierRange(startSpecifier, specifierLen)); 7820 7821 return true; 7822 } 7823 7824 // Check for using an Objective-C specific conversion specifier 7825 // in a non-ObjC literal. 7826 if (!allowsObjCArg() && CS.isObjCArg()) { 7827 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7828 specifierLen); 7829 } 7830 7831 // %P can only be used with os_log. 7832 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7833 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7834 specifierLen); 7835 } 7836 7837 // %n is not allowed with os_log. 7838 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7839 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7840 getLocationOfByte(CS.getStart()), 7841 /*IsStringLocation*/ false, 7842 getSpecifierRange(startSpecifier, specifierLen)); 7843 7844 return true; 7845 } 7846 7847 // Only scalars are allowed for os_trace. 7848 if (FSType == Sema::FST_OSTrace && 7849 (CS.getKind() == ConversionSpecifier::PArg || 7850 CS.getKind() == ConversionSpecifier::sArg || 7851 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7852 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7853 specifierLen); 7854 } 7855 7856 // Check for use of public/private annotation outside of os_log(). 7857 if (FSType != Sema::FST_OSLog) { 7858 if (FS.isPublic().isSet()) { 7859 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7860 << "public", 7861 getLocationOfByte(FS.isPublic().getPosition()), 7862 /*IsStringLocation*/ false, 7863 getSpecifierRange(startSpecifier, specifierLen)); 7864 } 7865 if (FS.isPrivate().isSet()) { 7866 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7867 << "private", 7868 getLocationOfByte(FS.isPrivate().getPosition()), 7869 /*IsStringLocation*/ false, 7870 getSpecifierRange(startSpecifier, specifierLen)); 7871 } 7872 } 7873 7874 // Check for invalid use of field width 7875 if (!FS.hasValidFieldWidth()) { 7876 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7877 startSpecifier, specifierLen); 7878 } 7879 7880 // Check for invalid use of precision 7881 if (!FS.hasValidPrecision()) { 7882 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7883 startSpecifier, specifierLen); 7884 } 7885 7886 // Precision is mandatory for %P specifier. 7887 if (CS.getKind() == ConversionSpecifier::PArg && 7888 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7889 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7890 getLocationOfByte(startSpecifier), 7891 /*IsStringLocation*/ false, 7892 getSpecifierRange(startSpecifier, specifierLen)); 7893 } 7894 7895 // Check each flag does not conflict with any other component. 7896 if (!FS.hasValidThousandsGroupingPrefix()) 7897 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7898 if (!FS.hasValidLeadingZeros()) 7899 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7900 if (!FS.hasValidPlusPrefix()) 7901 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7902 if (!FS.hasValidSpacePrefix()) 7903 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7904 if (!FS.hasValidAlternativeForm()) 7905 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7906 if (!FS.hasValidLeftJustified()) 7907 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7908 7909 // Check that flags are not ignored by another flag 7910 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7911 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7912 startSpecifier, specifierLen); 7913 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7914 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7915 startSpecifier, specifierLen); 7916 7917 // Check the length modifier is valid with the given conversion specifier. 7918 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 7919 S.getLangOpts())) 7920 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7921 diag::warn_format_nonsensical_length); 7922 else if (!FS.hasStandardLengthModifier()) 7923 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7924 else if (!FS.hasStandardLengthConversionCombination()) 7925 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7926 diag::warn_format_non_standard_conversion_spec); 7927 7928 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7929 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7930 7931 // The remaining checks depend on the data arguments. 7932 if (HasVAListArg) 7933 return true; 7934 7935 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7936 return false; 7937 7938 const Expr *Arg = getDataArg(argIndex); 7939 if (!Arg) 7940 return true; 7941 7942 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7943 } 7944 7945 static bool requiresParensToAddCast(const Expr *E) { 7946 // FIXME: We should have a general way to reason about operator 7947 // precedence and whether parens are actually needed here. 7948 // Take care of a few common cases where they aren't. 7949 const Expr *Inside = E->IgnoreImpCasts(); 7950 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7951 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7952 7953 switch (Inside->getStmtClass()) { 7954 case Stmt::ArraySubscriptExprClass: 7955 case Stmt::CallExprClass: 7956 case Stmt::CharacterLiteralClass: 7957 case Stmt::CXXBoolLiteralExprClass: 7958 case Stmt::DeclRefExprClass: 7959 case Stmt::FloatingLiteralClass: 7960 case Stmt::IntegerLiteralClass: 7961 case Stmt::MemberExprClass: 7962 case Stmt::ObjCArrayLiteralClass: 7963 case Stmt::ObjCBoolLiteralExprClass: 7964 case Stmt::ObjCBoxedExprClass: 7965 case Stmt::ObjCDictionaryLiteralClass: 7966 case Stmt::ObjCEncodeExprClass: 7967 case Stmt::ObjCIvarRefExprClass: 7968 case Stmt::ObjCMessageExprClass: 7969 case Stmt::ObjCPropertyRefExprClass: 7970 case Stmt::ObjCStringLiteralClass: 7971 case Stmt::ObjCSubscriptRefExprClass: 7972 case Stmt::ParenExprClass: 7973 case Stmt::StringLiteralClass: 7974 case Stmt::UnaryOperatorClass: 7975 return false; 7976 default: 7977 return true; 7978 } 7979 } 7980 7981 static std::pair<QualType, StringRef> 7982 shouldNotPrintDirectly(const ASTContext &Context, 7983 QualType IntendedTy, 7984 const Expr *E) { 7985 // Use a 'while' to peel off layers of typedefs. 7986 QualType TyTy = IntendedTy; 7987 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7988 StringRef Name = UserTy->getDecl()->getName(); 7989 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7990 .Case("CFIndex", Context.getNSIntegerType()) 7991 .Case("NSInteger", Context.getNSIntegerType()) 7992 .Case("NSUInteger", Context.getNSUIntegerType()) 7993 .Case("SInt32", Context.IntTy) 7994 .Case("UInt32", Context.UnsignedIntTy) 7995 .Default(QualType()); 7996 7997 if (!CastTy.isNull()) 7998 return std::make_pair(CastTy, Name); 7999 8000 TyTy = UserTy->desugar(); 8001 } 8002 8003 // Strip parens if necessary. 8004 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8005 return shouldNotPrintDirectly(Context, 8006 PE->getSubExpr()->getType(), 8007 PE->getSubExpr()); 8008 8009 // If this is a conditional expression, then its result type is constructed 8010 // via usual arithmetic conversions and thus there might be no necessary 8011 // typedef sugar there. Recurse to operands to check for NSInteger & 8012 // Co. usage condition. 8013 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8014 QualType TrueTy, FalseTy; 8015 StringRef TrueName, FalseName; 8016 8017 std::tie(TrueTy, TrueName) = 8018 shouldNotPrintDirectly(Context, 8019 CO->getTrueExpr()->getType(), 8020 CO->getTrueExpr()); 8021 std::tie(FalseTy, FalseName) = 8022 shouldNotPrintDirectly(Context, 8023 CO->getFalseExpr()->getType(), 8024 CO->getFalseExpr()); 8025 8026 if (TrueTy == FalseTy) 8027 return std::make_pair(TrueTy, TrueName); 8028 else if (TrueTy.isNull()) 8029 return std::make_pair(FalseTy, FalseName); 8030 else if (FalseTy.isNull()) 8031 return std::make_pair(TrueTy, TrueName); 8032 } 8033 8034 return std::make_pair(QualType(), StringRef()); 8035 } 8036 8037 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8038 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8039 /// type do not count. 8040 static bool 8041 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8042 QualType From = ICE->getSubExpr()->getType(); 8043 QualType To = ICE->getType(); 8044 // It's an integer promotion if the destination type is the promoted 8045 // source type. 8046 if (ICE->getCastKind() == CK_IntegralCast && 8047 From->isPromotableIntegerType() && 8048 S.Context.getPromotedIntegerType(From) == To) 8049 return true; 8050 // Look through vector types, since we do default argument promotion for 8051 // those in OpenCL. 8052 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8053 From = VecTy->getElementType(); 8054 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8055 To = VecTy->getElementType(); 8056 // It's a floating promotion if the source type is a lower rank. 8057 return ICE->getCastKind() == CK_FloatingCast && 8058 S.Context.getFloatingTypeOrder(From, To) < 0; 8059 } 8060 8061 bool 8062 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8063 const char *StartSpecifier, 8064 unsigned SpecifierLen, 8065 const Expr *E) { 8066 using namespace analyze_format_string; 8067 using namespace analyze_printf; 8068 8069 // Now type check the data expression that matches the 8070 // format specifier. 8071 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8072 if (!AT.isValid()) 8073 return true; 8074 8075 QualType ExprTy = E->getType(); 8076 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8077 ExprTy = TET->getUnderlyingExpr()->getType(); 8078 } 8079 8080 const analyze_printf::ArgType::MatchKind Match = 8081 AT.matchesType(S.Context, ExprTy); 8082 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 8083 if (Match == analyze_printf::ArgType::Match) 8084 return true; 8085 8086 // Look through argument promotions for our error message's reported type. 8087 // This includes the integral and floating promotions, but excludes array 8088 // and function pointer decay (seeing that an argument intended to be a 8089 // string has type 'char [6]' is probably more confusing than 'char *') and 8090 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8091 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8092 if (isArithmeticArgumentPromotion(S, ICE)) { 8093 E = ICE->getSubExpr(); 8094 ExprTy = E->getType(); 8095 8096 // Check if we didn't match because of an implicit cast from a 'char' 8097 // or 'short' to an 'int'. This is done because printf is a varargs 8098 // function. 8099 if (ICE->getType() == S.Context.IntTy || 8100 ICE->getType() == S.Context.UnsignedIntTy) { 8101 // All further checking is done on the subexpression. 8102 if (AT.matchesType(S.Context, ExprTy)) 8103 return true; 8104 } 8105 } 8106 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8107 // Special case for 'a', which has type 'int' in C. 8108 // Note, however, that we do /not/ want to treat multibyte constants like 8109 // 'MooV' as characters! This form is deprecated but still exists. 8110 if (ExprTy == S.Context.IntTy) 8111 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8112 ExprTy = S.Context.CharTy; 8113 } 8114 8115 // Look through enums to their underlying type. 8116 bool IsEnum = false; 8117 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8118 ExprTy = EnumTy->getDecl()->getIntegerType(); 8119 IsEnum = true; 8120 } 8121 8122 // %C in an Objective-C context prints a unichar, not a wchar_t. 8123 // If the argument is an integer of some kind, believe the %C and suggest 8124 // a cast instead of changing the conversion specifier. 8125 QualType IntendedTy = ExprTy; 8126 if (isObjCContext() && 8127 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8128 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8129 !ExprTy->isCharType()) { 8130 // 'unichar' is defined as a typedef of unsigned short, but we should 8131 // prefer using the typedef if it is visible. 8132 IntendedTy = S.Context.UnsignedShortTy; 8133 8134 // While we are here, check if the value is an IntegerLiteral that happens 8135 // to be within the valid range. 8136 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8137 const llvm::APInt &V = IL->getValue(); 8138 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8139 return true; 8140 } 8141 8142 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8143 Sema::LookupOrdinaryName); 8144 if (S.LookupName(Result, S.getCurScope())) { 8145 NamedDecl *ND = Result.getFoundDecl(); 8146 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8147 if (TD->getUnderlyingType() == IntendedTy) 8148 IntendedTy = S.Context.getTypedefType(TD); 8149 } 8150 } 8151 } 8152 8153 // Special-case some of Darwin's platform-independence types by suggesting 8154 // casts to primitive types that are known to be large enough. 8155 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8156 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8157 QualType CastTy; 8158 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8159 if (!CastTy.isNull()) { 8160 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8161 // (long in ASTContext). Only complain to pedants. 8162 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8163 (AT.isSizeT() || AT.isPtrdiffT()) && 8164 AT.matchesType(S.Context, CastTy)) 8165 Pedantic = true; 8166 IntendedTy = CastTy; 8167 ShouldNotPrintDirectly = true; 8168 } 8169 } 8170 8171 // We may be able to offer a FixItHint if it is a supported type. 8172 PrintfSpecifier fixedFS = FS; 8173 bool Success = 8174 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8175 8176 if (Success) { 8177 // Get the fix string from the fixed format specifier 8178 SmallString<16> buf; 8179 llvm::raw_svector_ostream os(buf); 8180 fixedFS.toString(os); 8181 8182 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8183 8184 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8185 unsigned Diag = 8186 Pedantic 8187 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8188 : diag::warn_format_conversion_argument_type_mismatch; 8189 // In this case, the specifier is wrong and should be changed to match 8190 // the argument. 8191 EmitFormatDiagnostic(S.PDiag(Diag) 8192 << AT.getRepresentativeTypeName(S.Context) 8193 << IntendedTy << IsEnum << E->getSourceRange(), 8194 E->getBeginLoc(), 8195 /*IsStringLocation*/ false, SpecRange, 8196 FixItHint::CreateReplacement(SpecRange, os.str())); 8197 } else { 8198 // The canonical type for formatting this value is different from the 8199 // actual type of the expression. (This occurs, for example, with Darwin's 8200 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8201 // should be printed as 'long' for 64-bit compatibility.) 8202 // Rather than emitting a normal format/argument mismatch, we want to 8203 // add a cast to the recommended type (and correct the format string 8204 // if necessary). 8205 SmallString<16> CastBuf; 8206 llvm::raw_svector_ostream CastFix(CastBuf); 8207 CastFix << "("; 8208 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8209 CastFix << ")"; 8210 8211 SmallVector<FixItHint,4> Hints; 8212 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8213 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8214 8215 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8216 // If there's already a cast present, just replace it. 8217 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8218 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8219 8220 } else if (!requiresParensToAddCast(E)) { 8221 // If the expression has high enough precedence, 8222 // just write the C-style cast. 8223 Hints.push_back( 8224 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8225 } else { 8226 // Otherwise, add parens around the expression as well as the cast. 8227 CastFix << "("; 8228 Hints.push_back( 8229 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8230 8231 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8232 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8233 } 8234 8235 if (ShouldNotPrintDirectly) { 8236 // The expression has a type that should not be printed directly. 8237 // We extract the name from the typedef because we don't want to show 8238 // the underlying type in the diagnostic. 8239 StringRef Name; 8240 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8241 Name = TypedefTy->getDecl()->getName(); 8242 else 8243 Name = CastTyName; 8244 unsigned Diag = Pedantic 8245 ? diag::warn_format_argument_needs_cast_pedantic 8246 : diag::warn_format_argument_needs_cast; 8247 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8248 << E->getSourceRange(), 8249 E->getBeginLoc(), /*IsStringLocation=*/false, 8250 SpecRange, Hints); 8251 } else { 8252 // In this case, the expression could be printed using a different 8253 // specifier, but we've decided that the specifier is probably correct 8254 // and we should cast instead. Just use the normal warning message. 8255 EmitFormatDiagnostic( 8256 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8257 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8258 << E->getSourceRange(), 8259 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8260 } 8261 } 8262 } else { 8263 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8264 SpecifierLen); 8265 // Since the warning for passing non-POD types to variadic functions 8266 // was deferred until now, we emit a warning for non-POD 8267 // arguments here. 8268 switch (S.isValidVarArgType(ExprTy)) { 8269 case Sema::VAK_Valid: 8270 case Sema::VAK_ValidInCXX11: { 8271 unsigned Diag = 8272 Pedantic 8273 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8274 : diag::warn_format_conversion_argument_type_mismatch; 8275 8276 EmitFormatDiagnostic( 8277 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8278 << IsEnum << CSR << E->getSourceRange(), 8279 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8280 break; 8281 } 8282 case Sema::VAK_Undefined: 8283 case Sema::VAK_MSVCUndefined: 8284 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8285 << S.getLangOpts().CPlusPlus11 << ExprTy 8286 << CallType 8287 << AT.getRepresentativeTypeName(S.Context) << CSR 8288 << E->getSourceRange(), 8289 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8290 checkForCStrMembers(AT, E); 8291 break; 8292 8293 case Sema::VAK_Invalid: 8294 if (ExprTy->isObjCObjectType()) 8295 EmitFormatDiagnostic( 8296 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8297 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8298 << AT.getRepresentativeTypeName(S.Context) << CSR 8299 << E->getSourceRange(), 8300 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8301 else 8302 // FIXME: If this is an initializer list, suggest removing the braces 8303 // or inserting a cast to the target type. 8304 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8305 << isa<InitListExpr>(E) << ExprTy << CallType 8306 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8307 break; 8308 } 8309 8310 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8311 "format string specifier index out of range"); 8312 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8313 } 8314 8315 return true; 8316 } 8317 8318 //===--- CHECK: Scanf format string checking ------------------------------===// 8319 8320 namespace { 8321 8322 class CheckScanfHandler : public CheckFormatHandler { 8323 public: 8324 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8325 const Expr *origFormatExpr, Sema::FormatStringType type, 8326 unsigned firstDataArg, unsigned numDataArgs, 8327 const char *beg, bool hasVAListArg, 8328 ArrayRef<const Expr *> Args, unsigned formatIdx, 8329 bool inFunctionCall, Sema::VariadicCallType CallType, 8330 llvm::SmallBitVector &CheckedVarArgs, 8331 UncoveredArgHandler &UncoveredArg) 8332 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8333 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8334 inFunctionCall, CallType, CheckedVarArgs, 8335 UncoveredArg) {} 8336 8337 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8338 const char *startSpecifier, 8339 unsigned specifierLen) override; 8340 8341 bool HandleInvalidScanfConversionSpecifier( 8342 const analyze_scanf::ScanfSpecifier &FS, 8343 const char *startSpecifier, 8344 unsigned specifierLen) override; 8345 8346 void HandleIncompleteScanList(const char *start, const char *end) override; 8347 }; 8348 8349 } // namespace 8350 8351 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8352 const char *end) { 8353 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8354 getLocationOfByte(end), /*IsStringLocation*/true, 8355 getSpecifierRange(start, end - start)); 8356 } 8357 8358 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8359 const analyze_scanf::ScanfSpecifier &FS, 8360 const char *startSpecifier, 8361 unsigned specifierLen) { 8362 const analyze_scanf::ScanfConversionSpecifier &CS = 8363 FS.getConversionSpecifier(); 8364 8365 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8366 getLocationOfByte(CS.getStart()), 8367 startSpecifier, specifierLen, 8368 CS.getStart(), CS.getLength()); 8369 } 8370 8371 bool CheckScanfHandler::HandleScanfSpecifier( 8372 const analyze_scanf::ScanfSpecifier &FS, 8373 const char *startSpecifier, 8374 unsigned specifierLen) { 8375 using namespace analyze_scanf; 8376 using namespace analyze_format_string; 8377 8378 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8379 8380 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8381 // be used to decide if we are using positional arguments consistently. 8382 if (FS.consumesDataArgument()) { 8383 if (atFirstArg) { 8384 atFirstArg = false; 8385 usesPositionalArgs = FS.usesPositionalArg(); 8386 } 8387 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8388 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8389 startSpecifier, specifierLen); 8390 return false; 8391 } 8392 } 8393 8394 // Check if the field with is non-zero. 8395 const OptionalAmount &Amt = FS.getFieldWidth(); 8396 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8397 if (Amt.getConstantAmount() == 0) { 8398 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8399 Amt.getConstantLength()); 8400 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8401 getLocationOfByte(Amt.getStart()), 8402 /*IsStringLocation*/true, R, 8403 FixItHint::CreateRemoval(R)); 8404 } 8405 } 8406 8407 if (!FS.consumesDataArgument()) { 8408 // FIXME: Technically specifying a precision or field width here 8409 // makes no sense. Worth issuing a warning at some point. 8410 return true; 8411 } 8412 8413 // Consume the argument. 8414 unsigned argIndex = FS.getArgIndex(); 8415 if (argIndex < NumDataArgs) { 8416 // The check to see if the argIndex is valid will come later. 8417 // We set the bit here because we may exit early from this 8418 // function if we encounter some other error. 8419 CoveredArgs.set(argIndex); 8420 } 8421 8422 // Check the length modifier is valid with the given conversion specifier. 8423 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8424 S.getLangOpts())) 8425 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8426 diag::warn_format_nonsensical_length); 8427 else if (!FS.hasStandardLengthModifier()) 8428 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8429 else if (!FS.hasStandardLengthConversionCombination()) 8430 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8431 diag::warn_format_non_standard_conversion_spec); 8432 8433 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8434 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8435 8436 // The remaining checks depend on the data arguments. 8437 if (HasVAListArg) 8438 return true; 8439 8440 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8441 return false; 8442 8443 // Check that the argument type matches the format specifier. 8444 const Expr *Ex = getDataArg(argIndex); 8445 if (!Ex) 8446 return true; 8447 8448 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8449 8450 if (!AT.isValid()) { 8451 return true; 8452 } 8453 8454 analyze_format_string::ArgType::MatchKind Match = 8455 AT.matchesType(S.Context, Ex->getType()); 8456 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8457 if (Match == analyze_format_string::ArgType::Match) 8458 return true; 8459 8460 ScanfSpecifier fixedFS = FS; 8461 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8462 S.getLangOpts(), S.Context); 8463 8464 unsigned Diag = 8465 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8466 : diag::warn_format_conversion_argument_type_mismatch; 8467 8468 if (Success) { 8469 // Get the fix string from the fixed format specifier. 8470 SmallString<128> buf; 8471 llvm::raw_svector_ostream os(buf); 8472 fixedFS.toString(os); 8473 8474 EmitFormatDiagnostic( 8475 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8476 << Ex->getType() << false << Ex->getSourceRange(), 8477 Ex->getBeginLoc(), 8478 /*IsStringLocation*/ false, 8479 getSpecifierRange(startSpecifier, specifierLen), 8480 FixItHint::CreateReplacement( 8481 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8482 } else { 8483 EmitFormatDiagnostic(S.PDiag(Diag) 8484 << AT.getRepresentativeTypeName(S.Context) 8485 << Ex->getType() << false << Ex->getSourceRange(), 8486 Ex->getBeginLoc(), 8487 /*IsStringLocation*/ false, 8488 getSpecifierRange(startSpecifier, specifierLen)); 8489 } 8490 8491 return true; 8492 } 8493 8494 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8495 const Expr *OrigFormatExpr, 8496 ArrayRef<const Expr *> Args, 8497 bool HasVAListArg, unsigned format_idx, 8498 unsigned firstDataArg, 8499 Sema::FormatStringType Type, 8500 bool inFunctionCall, 8501 Sema::VariadicCallType CallType, 8502 llvm::SmallBitVector &CheckedVarArgs, 8503 UncoveredArgHandler &UncoveredArg) { 8504 // CHECK: is the format string a wide literal? 8505 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8506 CheckFormatHandler::EmitFormatDiagnostic( 8507 S, inFunctionCall, Args[format_idx], 8508 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8509 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8510 return; 8511 } 8512 8513 // Str - The format string. NOTE: this is NOT null-terminated! 8514 StringRef StrRef = FExpr->getString(); 8515 const char *Str = StrRef.data(); 8516 // Account for cases where the string literal is truncated in a declaration. 8517 const ConstantArrayType *T = 8518 S.Context.getAsConstantArrayType(FExpr->getType()); 8519 assert(T && "String literal not of constant array type!"); 8520 size_t TypeSize = T->getSize().getZExtValue(); 8521 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8522 const unsigned numDataArgs = Args.size() - firstDataArg; 8523 8524 // Emit a warning if the string literal is truncated and does not contain an 8525 // embedded null character. 8526 if (TypeSize <= StrRef.size() && 8527 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8528 CheckFormatHandler::EmitFormatDiagnostic( 8529 S, inFunctionCall, Args[format_idx], 8530 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8531 FExpr->getBeginLoc(), 8532 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8533 return; 8534 } 8535 8536 // CHECK: empty format string? 8537 if (StrLen == 0 && numDataArgs > 0) { 8538 CheckFormatHandler::EmitFormatDiagnostic( 8539 S, inFunctionCall, Args[format_idx], 8540 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8541 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8542 return; 8543 } 8544 8545 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8546 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8547 Type == Sema::FST_OSTrace) { 8548 CheckPrintfHandler H( 8549 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8550 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8551 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8552 CheckedVarArgs, UncoveredArg); 8553 8554 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8555 S.getLangOpts(), 8556 S.Context.getTargetInfo(), 8557 Type == Sema::FST_FreeBSDKPrintf)) 8558 H.DoneProcessing(); 8559 } else if (Type == Sema::FST_Scanf) { 8560 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8561 numDataArgs, Str, HasVAListArg, Args, format_idx, 8562 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8563 8564 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8565 S.getLangOpts(), 8566 S.Context.getTargetInfo())) 8567 H.DoneProcessing(); 8568 } // TODO: handle other formats 8569 } 8570 8571 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8572 // Str - The format string. NOTE: this is NOT null-terminated! 8573 StringRef StrRef = FExpr->getString(); 8574 const char *Str = StrRef.data(); 8575 // Account for cases where the string literal is truncated in a declaration. 8576 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8577 assert(T && "String literal not of constant array type!"); 8578 size_t TypeSize = T->getSize().getZExtValue(); 8579 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8580 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8581 getLangOpts(), 8582 Context.getTargetInfo()); 8583 } 8584 8585 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8586 8587 // Returns the related absolute value function that is larger, of 0 if one 8588 // does not exist. 8589 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8590 switch (AbsFunction) { 8591 default: 8592 return 0; 8593 8594 case Builtin::BI__builtin_abs: 8595 return Builtin::BI__builtin_labs; 8596 case Builtin::BI__builtin_labs: 8597 return Builtin::BI__builtin_llabs; 8598 case Builtin::BI__builtin_llabs: 8599 return 0; 8600 8601 case Builtin::BI__builtin_fabsf: 8602 return Builtin::BI__builtin_fabs; 8603 case Builtin::BI__builtin_fabs: 8604 return Builtin::BI__builtin_fabsl; 8605 case Builtin::BI__builtin_fabsl: 8606 return 0; 8607 8608 case Builtin::BI__builtin_cabsf: 8609 return Builtin::BI__builtin_cabs; 8610 case Builtin::BI__builtin_cabs: 8611 return Builtin::BI__builtin_cabsl; 8612 case Builtin::BI__builtin_cabsl: 8613 return 0; 8614 8615 case Builtin::BIabs: 8616 return Builtin::BIlabs; 8617 case Builtin::BIlabs: 8618 return Builtin::BIllabs; 8619 case Builtin::BIllabs: 8620 return 0; 8621 8622 case Builtin::BIfabsf: 8623 return Builtin::BIfabs; 8624 case Builtin::BIfabs: 8625 return Builtin::BIfabsl; 8626 case Builtin::BIfabsl: 8627 return 0; 8628 8629 case Builtin::BIcabsf: 8630 return Builtin::BIcabs; 8631 case Builtin::BIcabs: 8632 return Builtin::BIcabsl; 8633 case Builtin::BIcabsl: 8634 return 0; 8635 } 8636 } 8637 8638 // Returns the argument type of the absolute value function. 8639 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8640 unsigned AbsType) { 8641 if (AbsType == 0) 8642 return QualType(); 8643 8644 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8645 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8646 if (Error != ASTContext::GE_None) 8647 return QualType(); 8648 8649 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8650 if (!FT) 8651 return QualType(); 8652 8653 if (FT->getNumParams() != 1) 8654 return QualType(); 8655 8656 return FT->getParamType(0); 8657 } 8658 8659 // Returns the best absolute value function, or zero, based on type and 8660 // current absolute value function. 8661 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8662 unsigned AbsFunctionKind) { 8663 unsigned BestKind = 0; 8664 uint64_t ArgSize = Context.getTypeSize(ArgType); 8665 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8666 Kind = getLargerAbsoluteValueFunction(Kind)) { 8667 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8668 if (Context.getTypeSize(ParamType) >= ArgSize) { 8669 if (BestKind == 0) 8670 BestKind = Kind; 8671 else if (Context.hasSameType(ParamType, ArgType)) { 8672 BestKind = Kind; 8673 break; 8674 } 8675 } 8676 } 8677 return BestKind; 8678 } 8679 8680 enum AbsoluteValueKind { 8681 AVK_Integer, 8682 AVK_Floating, 8683 AVK_Complex 8684 }; 8685 8686 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8687 if (T->isIntegralOrEnumerationType()) 8688 return AVK_Integer; 8689 if (T->isRealFloatingType()) 8690 return AVK_Floating; 8691 if (T->isAnyComplexType()) 8692 return AVK_Complex; 8693 8694 llvm_unreachable("Type not integer, floating, or complex"); 8695 } 8696 8697 // Changes the absolute value function to a different type. Preserves whether 8698 // the function is a builtin. 8699 static unsigned changeAbsFunction(unsigned AbsKind, 8700 AbsoluteValueKind ValueKind) { 8701 switch (ValueKind) { 8702 case AVK_Integer: 8703 switch (AbsKind) { 8704 default: 8705 return 0; 8706 case Builtin::BI__builtin_fabsf: 8707 case Builtin::BI__builtin_fabs: 8708 case Builtin::BI__builtin_fabsl: 8709 case Builtin::BI__builtin_cabsf: 8710 case Builtin::BI__builtin_cabs: 8711 case Builtin::BI__builtin_cabsl: 8712 return Builtin::BI__builtin_abs; 8713 case Builtin::BIfabsf: 8714 case Builtin::BIfabs: 8715 case Builtin::BIfabsl: 8716 case Builtin::BIcabsf: 8717 case Builtin::BIcabs: 8718 case Builtin::BIcabsl: 8719 return Builtin::BIabs; 8720 } 8721 case AVK_Floating: 8722 switch (AbsKind) { 8723 default: 8724 return 0; 8725 case Builtin::BI__builtin_abs: 8726 case Builtin::BI__builtin_labs: 8727 case Builtin::BI__builtin_llabs: 8728 case Builtin::BI__builtin_cabsf: 8729 case Builtin::BI__builtin_cabs: 8730 case Builtin::BI__builtin_cabsl: 8731 return Builtin::BI__builtin_fabsf; 8732 case Builtin::BIabs: 8733 case Builtin::BIlabs: 8734 case Builtin::BIllabs: 8735 case Builtin::BIcabsf: 8736 case Builtin::BIcabs: 8737 case Builtin::BIcabsl: 8738 return Builtin::BIfabsf; 8739 } 8740 case AVK_Complex: 8741 switch (AbsKind) { 8742 default: 8743 return 0; 8744 case Builtin::BI__builtin_abs: 8745 case Builtin::BI__builtin_labs: 8746 case Builtin::BI__builtin_llabs: 8747 case Builtin::BI__builtin_fabsf: 8748 case Builtin::BI__builtin_fabs: 8749 case Builtin::BI__builtin_fabsl: 8750 return Builtin::BI__builtin_cabsf; 8751 case Builtin::BIabs: 8752 case Builtin::BIlabs: 8753 case Builtin::BIllabs: 8754 case Builtin::BIfabsf: 8755 case Builtin::BIfabs: 8756 case Builtin::BIfabsl: 8757 return Builtin::BIcabsf; 8758 } 8759 } 8760 llvm_unreachable("Unable to convert function"); 8761 } 8762 8763 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8764 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8765 if (!FnInfo) 8766 return 0; 8767 8768 switch (FDecl->getBuiltinID()) { 8769 default: 8770 return 0; 8771 case Builtin::BI__builtin_abs: 8772 case Builtin::BI__builtin_fabs: 8773 case Builtin::BI__builtin_fabsf: 8774 case Builtin::BI__builtin_fabsl: 8775 case Builtin::BI__builtin_labs: 8776 case Builtin::BI__builtin_llabs: 8777 case Builtin::BI__builtin_cabs: 8778 case Builtin::BI__builtin_cabsf: 8779 case Builtin::BI__builtin_cabsl: 8780 case Builtin::BIabs: 8781 case Builtin::BIlabs: 8782 case Builtin::BIllabs: 8783 case Builtin::BIfabs: 8784 case Builtin::BIfabsf: 8785 case Builtin::BIfabsl: 8786 case Builtin::BIcabs: 8787 case Builtin::BIcabsf: 8788 case Builtin::BIcabsl: 8789 return FDecl->getBuiltinID(); 8790 } 8791 llvm_unreachable("Unknown Builtin type"); 8792 } 8793 8794 // If the replacement is valid, emit a note with replacement function. 8795 // Additionally, suggest including the proper header if not already included. 8796 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8797 unsigned AbsKind, QualType ArgType) { 8798 bool EmitHeaderHint = true; 8799 const char *HeaderName = nullptr; 8800 const char *FunctionName = nullptr; 8801 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8802 FunctionName = "std::abs"; 8803 if (ArgType->isIntegralOrEnumerationType()) { 8804 HeaderName = "cstdlib"; 8805 } else if (ArgType->isRealFloatingType()) { 8806 HeaderName = "cmath"; 8807 } else { 8808 llvm_unreachable("Invalid Type"); 8809 } 8810 8811 // Lookup all std::abs 8812 if (NamespaceDecl *Std = S.getStdNamespace()) { 8813 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8814 R.suppressDiagnostics(); 8815 S.LookupQualifiedName(R, Std); 8816 8817 for (const auto *I : R) { 8818 const FunctionDecl *FDecl = nullptr; 8819 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8820 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8821 } else { 8822 FDecl = dyn_cast<FunctionDecl>(I); 8823 } 8824 if (!FDecl) 8825 continue; 8826 8827 // Found std::abs(), check that they are the right ones. 8828 if (FDecl->getNumParams() != 1) 8829 continue; 8830 8831 // Check that the parameter type can handle the argument. 8832 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8833 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8834 S.Context.getTypeSize(ArgType) <= 8835 S.Context.getTypeSize(ParamType)) { 8836 // Found a function, don't need the header hint. 8837 EmitHeaderHint = false; 8838 break; 8839 } 8840 } 8841 } 8842 } else { 8843 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8844 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8845 8846 if (HeaderName) { 8847 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8848 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8849 R.suppressDiagnostics(); 8850 S.LookupName(R, S.getCurScope()); 8851 8852 if (R.isSingleResult()) { 8853 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8854 if (FD && FD->getBuiltinID() == AbsKind) { 8855 EmitHeaderHint = false; 8856 } else { 8857 return; 8858 } 8859 } else if (!R.empty()) { 8860 return; 8861 } 8862 } 8863 } 8864 8865 S.Diag(Loc, diag::note_replace_abs_function) 8866 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8867 8868 if (!HeaderName) 8869 return; 8870 8871 if (!EmitHeaderHint) 8872 return; 8873 8874 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8875 << FunctionName; 8876 } 8877 8878 template <std::size_t StrLen> 8879 static bool IsStdFunction(const FunctionDecl *FDecl, 8880 const char (&Str)[StrLen]) { 8881 if (!FDecl) 8882 return false; 8883 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8884 return false; 8885 if (!FDecl->isInStdNamespace()) 8886 return false; 8887 8888 return true; 8889 } 8890 8891 // Warn when using the wrong abs() function. 8892 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8893 const FunctionDecl *FDecl) { 8894 if (Call->getNumArgs() != 1) 8895 return; 8896 8897 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8898 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8899 if (AbsKind == 0 && !IsStdAbs) 8900 return; 8901 8902 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8903 QualType ParamType = Call->getArg(0)->getType(); 8904 8905 // Unsigned types cannot be negative. Suggest removing the absolute value 8906 // function call. 8907 if (ArgType->isUnsignedIntegerType()) { 8908 const char *FunctionName = 8909 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8910 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8911 Diag(Call->getExprLoc(), diag::note_remove_abs) 8912 << FunctionName 8913 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8914 return; 8915 } 8916 8917 // Taking the absolute value of a pointer is very suspicious, they probably 8918 // wanted to index into an array, dereference a pointer, call a function, etc. 8919 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8920 unsigned DiagType = 0; 8921 if (ArgType->isFunctionType()) 8922 DiagType = 1; 8923 else if (ArgType->isArrayType()) 8924 DiagType = 2; 8925 8926 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8927 return; 8928 } 8929 8930 // std::abs has overloads which prevent most of the absolute value problems 8931 // from occurring. 8932 if (IsStdAbs) 8933 return; 8934 8935 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8936 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8937 8938 // The argument and parameter are the same kind. Check if they are the right 8939 // size. 8940 if (ArgValueKind == ParamValueKind) { 8941 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8942 return; 8943 8944 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8945 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8946 << FDecl << ArgType << ParamType; 8947 8948 if (NewAbsKind == 0) 8949 return; 8950 8951 emitReplacement(*this, Call->getExprLoc(), 8952 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8953 return; 8954 } 8955 8956 // ArgValueKind != ParamValueKind 8957 // The wrong type of absolute value function was used. Attempt to find the 8958 // proper one. 8959 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8960 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8961 if (NewAbsKind == 0) 8962 return; 8963 8964 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8965 << FDecl << ParamValueKind << ArgValueKind; 8966 8967 emitReplacement(*this, Call->getExprLoc(), 8968 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8969 } 8970 8971 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8972 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8973 const FunctionDecl *FDecl) { 8974 if (!Call || !FDecl) return; 8975 8976 // Ignore template specializations and macros. 8977 if (inTemplateInstantiation()) return; 8978 if (Call->getExprLoc().isMacroID()) return; 8979 8980 // Only care about the one template argument, two function parameter std::max 8981 if (Call->getNumArgs() != 2) return; 8982 if (!IsStdFunction(FDecl, "max")) return; 8983 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8984 if (!ArgList) return; 8985 if (ArgList->size() != 1) return; 8986 8987 // Check that template type argument is unsigned integer. 8988 const auto& TA = ArgList->get(0); 8989 if (TA.getKind() != TemplateArgument::Type) return; 8990 QualType ArgType = TA.getAsType(); 8991 if (!ArgType->isUnsignedIntegerType()) return; 8992 8993 // See if either argument is a literal zero. 8994 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8995 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8996 if (!MTE) return false; 8997 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8998 if (!Num) return false; 8999 if (Num->getValue() != 0) return false; 9000 return true; 9001 }; 9002 9003 const Expr *FirstArg = Call->getArg(0); 9004 const Expr *SecondArg = Call->getArg(1); 9005 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9006 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9007 9008 // Only warn when exactly one argument is zero. 9009 if (IsFirstArgZero == IsSecondArgZero) return; 9010 9011 SourceRange FirstRange = FirstArg->getSourceRange(); 9012 SourceRange SecondRange = SecondArg->getSourceRange(); 9013 9014 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9015 9016 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9017 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9018 9019 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9020 SourceRange RemovalRange; 9021 if (IsFirstArgZero) { 9022 RemovalRange = SourceRange(FirstRange.getBegin(), 9023 SecondRange.getBegin().getLocWithOffset(-1)); 9024 } else { 9025 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9026 SecondRange.getEnd()); 9027 } 9028 9029 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9030 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9031 << FixItHint::CreateRemoval(RemovalRange); 9032 } 9033 9034 //===--- CHECK: Standard memory functions ---------------------------------===// 9035 9036 /// Takes the expression passed to the size_t parameter of functions 9037 /// such as memcmp, strncat, etc and warns if it's a comparison. 9038 /// 9039 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9040 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9041 IdentifierInfo *FnName, 9042 SourceLocation FnLoc, 9043 SourceLocation RParenLoc) { 9044 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9045 if (!Size) 9046 return false; 9047 9048 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9049 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9050 return false; 9051 9052 SourceRange SizeRange = Size->getSourceRange(); 9053 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9054 << SizeRange << FnName; 9055 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9056 << FnName 9057 << FixItHint::CreateInsertion( 9058 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9059 << FixItHint::CreateRemoval(RParenLoc); 9060 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9061 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9062 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9063 ")"); 9064 9065 return true; 9066 } 9067 9068 /// Determine whether the given type is or contains a dynamic class type 9069 /// (e.g., whether it has a vtable). 9070 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9071 bool &IsContained) { 9072 // Look through array types while ignoring qualifiers. 9073 const Type *Ty = T->getBaseElementTypeUnsafe(); 9074 IsContained = false; 9075 9076 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9077 RD = RD ? RD->getDefinition() : nullptr; 9078 if (!RD || RD->isInvalidDecl()) 9079 return nullptr; 9080 9081 if (RD->isDynamicClass()) 9082 return RD; 9083 9084 // Check all the fields. If any bases were dynamic, the class is dynamic. 9085 // It's impossible for a class to transitively contain itself by value, so 9086 // infinite recursion is impossible. 9087 for (auto *FD : RD->fields()) { 9088 bool SubContained; 9089 if (const CXXRecordDecl *ContainedRD = 9090 getContainedDynamicClass(FD->getType(), SubContained)) { 9091 IsContained = true; 9092 return ContainedRD; 9093 } 9094 } 9095 9096 return nullptr; 9097 } 9098 9099 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9100 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9101 if (Unary->getKind() == UETT_SizeOf) 9102 return Unary; 9103 return nullptr; 9104 } 9105 9106 /// If E is a sizeof expression, returns its argument expression, 9107 /// otherwise returns NULL. 9108 static const Expr *getSizeOfExprArg(const Expr *E) { 9109 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9110 if (!SizeOf->isArgumentType()) 9111 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9112 return nullptr; 9113 } 9114 9115 /// If E is a sizeof expression, returns its argument type. 9116 static QualType getSizeOfArgType(const Expr *E) { 9117 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9118 return SizeOf->getTypeOfArgument(); 9119 return QualType(); 9120 } 9121 9122 namespace { 9123 9124 struct SearchNonTrivialToInitializeField 9125 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9126 using Super = 9127 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9128 9129 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9130 9131 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9132 SourceLocation SL) { 9133 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9134 asDerived().visitArray(PDIK, AT, SL); 9135 return; 9136 } 9137 9138 Super::visitWithKind(PDIK, FT, SL); 9139 } 9140 9141 void visitARCStrong(QualType FT, SourceLocation SL) { 9142 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9143 } 9144 void visitARCWeak(QualType FT, SourceLocation SL) { 9145 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9146 } 9147 void visitStruct(QualType FT, SourceLocation SL) { 9148 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9149 visit(FD->getType(), FD->getLocation()); 9150 } 9151 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9152 const ArrayType *AT, SourceLocation SL) { 9153 visit(getContext().getBaseElementType(AT), SL); 9154 } 9155 void visitTrivial(QualType FT, SourceLocation SL) {} 9156 9157 static void diag(QualType RT, const Expr *E, Sema &S) { 9158 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9159 } 9160 9161 ASTContext &getContext() { return S.getASTContext(); } 9162 9163 const Expr *E; 9164 Sema &S; 9165 }; 9166 9167 struct SearchNonTrivialToCopyField 9168 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9169 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9170 9171 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9172 9173 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9174 SourceLocation SL) { 9175 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9176 asDerived().visitArray(PCK, AT, SL); 9177 return; 9178 } 9179 9180 Super::visitWithKind(PCK, FT, SL); 9181 } 9182 9183 void visitARCStrong(QualType FT, SourceLocation SL) { 9184 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9185 } 9186 void visitARCWeak(QualType FT, SourceLocation SL) { 9187 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9188 } 9189 void visitStruct(QualType FT, SourceLocation SL) { 9190 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9191 visit(FD->getType(), FD->getLocation()); 9192 } 9193 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9194 SourceLocation SL) { 9195 visit(getContext().getBaseElementType(AT), SL); 9196 } 9197 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9198 SourceLocation SL) {} 9199 void visitTrivial(QualType FT, SourceLocation SL) {} 9200 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9201 9202 static void diag(QualType RT, const Expr *E, Sema &S) { 9203 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9204 } 9205 9206 ASTContext &getContext() { return S.getASTContext(); } 9207 9208 const Expr *E; 9209 Sema &S; 9210 }; 9211 9212 } 9213 9214 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9215 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9216 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9217 9218 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9219 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9220 return false; 9221 9222 return doesExprLikelyComputeSize(BO->getLHS()) || 9223 doesExprLikelyComputeSize(BO->getRHS()); 9224 } 9225 9226 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9227 } 9228 9229 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9230 /// 9231 /// \code 9232 /// #define MACRO 0 9233 /// foo(MACRO); 9234 /// foo(0); 9235 /// \endcode 9236 /// 9237 /// This should return true for the first call to foo, but not for the second 9238 /// (regardless of whether foo is a macro or function). 9239 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9240 SourceLocation CallLoc, 9241 SourceLocation ArgLoc) { 9242 if (!CallLoc.isMacroID()) 9243 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9244 9245 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9246 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9247 } 9248 9249 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9250 /// last two arguments transposed. 9251 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9252 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9253 return; 9254 9255 const Expr *SizeArg = 9256 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9257 9258 auto isLiteralZero = [](const Expr *E) { 9259 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9260 }; 9261 9262 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9263 SourceLocation CallLoc = Call->getRParenLoc(); 9264 SourceManager &SM = S.getSourceManager(); 9265 if (isLiteralZero(SizeArg) && 9266 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9267 9268 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9269 9270 // Some platforms #define bzero to __builtin_memset. See if this is the 9271 // case, and if so, emit a better diagnostic. 9272 if (BId == Builtin::BIbzero || 9273 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9274 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9275 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9276 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9277 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9278 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9279 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9280 } 9281 return; 9282 } 9283 9284 // If the second argument to a memset is a sizeof expression and the third 9285 // isn't, this is also likely an error. This should catch 9286 // 'memset(buf, sizeof(buf), 0xff)'. 9287 if (BId == Builtin::BImemset && 9288 doesExprLikelyComputeSize(Call->getArg(1)) && 9289 !doesExprLikelyComputeSize(Call->getArg(2))) { 9290 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9291 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9292 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9293 return; 9294 } 9295 } 9296 9297 /// Check for dangerous or invalid arguments to memset(). 9298 /// 9299 /// This issues warnings on known problematic, dangerous or unspecified 9300 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9301 /// function calls. 9302 /// 9303 /// \param Call The call expression to diagnose. 9304 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9305 unsigned BId, 9306 IdentifierInfo *FnName) { 9307 assert(BId != 0); 9308 9309 // It is possible to have a non-standard definition of memset. Validate 9310 // we have enough arguments, and if not, abort further checking. 9311 unsigned ExpectedNumArgs = 9312 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9313 if (Call->getNumArgs() < ExpectedNumArgs) 9314 return; 9315 9316 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9317 BId == Builtin::BIstrndup ? 1 : 2); 9318 unsigned LenArg = 9319 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9320 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9321 9322 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9323 Call->getBeginLoc(), Call->getRParenLoc())) 9324 return; 9325 9326 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9327 CheckMemaccessSize(*this, BId, Call); 9328 9329 // We have special checking when the length is a sizeof expression. 9330 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9331 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9332 llvm::FoldingSetNodeID SizeOfArgID; 9333 9334 // Although widely used, 'bzero' is not a standard function. Be more strict 9335 // with the argument types before allowing diagnostics and only allow the 9336 // form bzero(ptr, sizeof(...)). 9337 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9338 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9339 return; 9340 9341 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9342 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9343 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9344 9345 QualType DestTy = Dest->getType(); 9346 QualType PointeeTy; 9347 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9348 PointeeTy = DestPtrTy->getPointeeType(); 9349 9350 // Never warn about void type pointers. This can be used to suppress 9351 // false positives. 9352 if (PointeeTy->isVoidType()) 9353 continue; 9354 9355 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9356 // actually comparing the expressions for equality. Because computing the 9357 // expression IDs can be expensive, we only do this if the diagnostic is 9358 // enabled. 9359 if (SizeOfArg && 9360 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9361 SizeOfArg->getExprLoc())) { 9362 // We only compute IDs for expressions if the warning is enabled, and 9363 // cache the sizeof arg's ID. 9364 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9365 SizeOfArg->Profile(SizeOfArgID, Context, true); 9366 llvm::FoldingSetNodeID DestID; 9367 Dest->Profile(DestID, Context, true); 9368 if (DestID == SizeOfArgID) { 9369 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9370 // over sizeof(src) as well. 9371 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9372 StringRef ReadableName = FnName->getName(); 9373 9374 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9375 if (UnaryOp->getOpcode() == UO_AddrOf) 9376 ActionIdx = 1; // If its an address-of operator, just remove it. 9377 if (!PointeeTy->isIncompleteType() && 9378 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9379 ActionIdx = 2; // If the pointee's size is sizeof(char), 9380 // suggest an explicit length. 9381 9382 // If the function is defined as a builtin macro, do not show macro 9383 // expansion. 9384 SourceLocation SL = SizeOfArg->getExprLoc(); 9385 SourceRange DSR = Dest->getSourceRange(); 9386 SourceRange SSR = SizeOfArg->getSourceRange(); 9387 SourceManager &SM = getSourceManager(); 9388 9389 if (SM.isMacroArgExpansion(SL)) { 9390 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9391 SL = SM.getSpellingLoc(SL); 9392 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9393 SM.getSpellingLoc(DSR.getEnd())); 9394 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9395 SM.getSpellingLoc(SSR.getEnd())); 9396 } 9397 9398 DiagRuntimeBehavior(SL, SizeOfArg, 9399 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9400 << ReadableName 9401 << PointeeTy 9402 << DestTy 9403 << DSR 9404 << SSR); 9405 DiagRuntimeBehavior(SL, SizeOfArg, 9406 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9407 << ActionIdx 9408 << SSR); 9409 9410 break; 9411 } 9412 } 9413 9414 // Also check for cases where the sizeof argument is the exact same 9415 // type as the memory argument, and where it points to a user-defined 9416 // record type. 9417 if (SizeOfArgTy != QualType()) { 9418 if (PointeeTy->isRecordType() && 9419 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9420 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9421 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9422 << FnName << SizeOfArgTy << ArgIdx 9423 << PointeeTy << Dest->getSourceRange() 9424 << LenExpr->getSourceRange()); 9425 break; 9426 } 9427 } 9428 } else if (DestTy->isArrayType()) { 9429 PointeeTy = DestTy; 9430 } 9431 9432 if (PointeeTy == QualType()) 9433 continue; 9434 9435 // Always complain about dynamic classes. 9436 bool IsContained; 9437 if (const CXXRecordDecl *ContainedRD = 9438 getContainedDynamicClass(PointeeTy, IsContained)) { 9439 9440 unsigned OperationType = 0; 9441 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9442 // "overwritten" if we're warning about the destination for any call 9443 // but memcmp; otherwise a verb appropriate to the call. 9444 if (ArgIdx != 0 || IsCmp) { 9445 if (BId == Builtin::BImemcpy) 9446 OperationType = 1; 9447 else if(BId == Builtin::BImemmove) 9448 OperationType = 2; 9449 else if (IsCmp) 9450 OperationType = 3; 9451 } 9452 9453 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9454 PDiag(diag::warn_dyn_class_memaccess) 9455 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9456 << IsContained << ContainedRD << OperationType 9457 << Call->getCallee()->getSourceRange()); 9458 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9459 BId != Builtin::BImemset) 9460 DiagRuntimeBehavior( 9461 Dest->getExprLoc(), Dest, 9462 PDiag(diag::warn_arc_object_memaccess) 9463 << ArgIdx << FnName << PointeeTy 9464 << Call->getCallee()->getSourceRange()); 9465 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9466 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9467 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9468 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9469 PDiag(diag::warn_cstruct_memaccess) 9470 << ArgIdx << FnName << PointeeTy << 0); 9471 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9472 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9473 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9474 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9475 PDiag(diag::warn_cstruct_memaccess) 9476 << ArgIdx << FnName << PointeeTy << 1); 9477 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9478 } else { 9479 continue; 9480 } 9481 } else 9482 continue; 9483 9484 DiagRuntimeBehavior( 9485 Dest->getExprLoc(), Dest, 9486 PDiag(diag::note_bad_memaccess_silence) 9487 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9488 break; 9489 } 9490 } 9491 9492 // A little helper routine: ignore addition and subtraction of integer literals. 9493 // This intentionally does not ignore all integer constant expressions because 9494 // we don't want to remove sizeof(). 9495 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9496 Ex = Ex->IgnoreParenCasts(); 9497 9498 while (true) { 9499 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9500 if (!BO || !BO->isAdditiveOp()) 9501 break; 9502 9503 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9504 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9505 9506 if (isa<IntegerLiteral>(RHS)) 9507 Ex = LHS; 9508 else if (isa<IntegerLiteral>(LHS)) 9509 Ex = RHS; 9510 else 9511 break; 9512 } 9513 9514 return Ex; 9515 } 9516 9517 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9518 ASTContext &Context) { 9519 // Only handle constant-sized or VLAs, but not flexible members. 9520 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9521 // Only issue the FIXIT for arrays of size > 1. 9522 if (CAT->getSize().getSExtValue() <= 1) 9523 return false; 9524 } else if (!Ty->isVariableArrayType()) { 9525 return false; 9526 } 9527 return true; 9528 } 9529 9530 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9531 // be the size of the source, instead of the destination. 9532 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9533 IdentifierInfo *FnName) { 9534 9535 // Don't crash if the user has the wrong number of arguments 9536 unsigned NumArgs = Call->getNumArgs(); 9537 if ((NumArgs != 3) && (NumArgs != 4)) 9538 return; 9539 9540 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9541 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9542 const Expr *CompareWithSrc = nullptr; 9543 9544 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9545 Call->getBeginLoc(), Call->getRParenLoc())) 9546 return; 9547 9548 // Look for 'strlcpy(dst, x, sizeof(x))' 9549 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9550 CompareWithSrc = Ex; 9551 else { 9552 // Look for 'strlcpy(dst, x, strlen(x))' 9553 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9554 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9555 SizeCall->getNumArgs() == 1) 9556 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9557 } 9558 } 9559 9560 if (!CompareWithSrc) 9561 return; 9562 9563 // Determine if the argument to sizeof/strlen is equal to the source 9564 // argument. In principle there's all kinds of things you could do 9565 // here, for instance creating an == expression and evaluating it with 9566 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9567 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9568 if (!SrcArgDRE) 9569 return; 9570 9571 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9572 if (!CompareWithSrcDRE || 9573 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9574 return; 9575 9576 const Expr *OriginalSizeArg = Call->getArg(2); 9577 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9578 << OriginalSizeArg->getSourceRange() << FnName; 9579 9580 // Output a FIXIT hint if the destination is an array (rather than a 9581 // pointer to an array). This could be enhanced to handle some 9582 // pointers if we know the actual size, like if DstArg is 'array+2' 9583 // we could say 'sizeof(array)-2'. 9584 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9585 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9586 return; 9587 9588 SmallString<128> sizeString; 9589 llvm::raw_svector_ostream OS(sizeString); 9590 OS << "sizeof("; 9591 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9592 OS << ")"; 9593 9594 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9595 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9596 OS.str()); 9597 } 9598 9599 /// Check if two expressions refer to the same declaration. 9600 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9601 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9602 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9603 return D1->getDecl() == D2->getDecl(); 9604 return false; 9605 } 9606 9607 static const Expr *getStrlenExprArg(const Expr *E) { 9608 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9609 const FunctionDecl *FD = CE->getDirectCallee(); 9610 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9611 return nullptr; 9612 return CE->getArg(0)->IgnoreParenCasts(); 9613 } 9614 return nullptr; 9615 } 9616 9617 // Warn on anti-patterns as the 'size' argument to strncat. 9618 // The correct size argument should look like following: 9619 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9620 void Sema::CheckStrncatArguments(const CallExpr *CE, 9621 IdentifierInfo *FnName) { 9622 // Don't crash if the user has the wrong number of arguments. 9623 if (CE->getNumArgs() < 3) 9624 return; 9625 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9626 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9627 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9628 9629 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9630 CE->getRParenLoc())) 9631 return; 9632 9633 // Identify common expressions, which are wrongly used as the size argument 9634 // to strncat and may lead to buffer overflows. 9635 unsigned PatternType = 0; 9636 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9637 // - sizeof(dst) 9638 if (referToTheSameDecl(SizeOfArg, DstArg)) 9639 PatternType = 1; 9640 // - sizeof(src) 9641 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9642 PatternType = 2; 9643 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9644 if (BE->getOpcode() == BO_Sub) { 9645 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9646 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9647 // - sizeof(dst) - strlen(dst) 9648 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9649 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9650 PatternType = 1; 9651 // - sizeof(src) - (anything) 9652 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9653 PatternType = 2; 9654 } 9655 } 9656 9657 if (PatternType == 0) 9658 return; 9659 9660 // Generate the diagnostic. 9661 SourceLocation SL = LenArg->getBeginLoc(); 9662 SourceRange SR = LenArg->getSourceRange(); 9663 SourceManager &SM = getSourceManager(); 9664 9665 // If the function is defined as a builtin macro, do not show macro expansion. 9666 if (SM.isMacroArgExpansion(SL)) { 9667 SL = SM.getSpellingLoc(SL); 9668 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9669 SM.getSpellingLoc(SR.getEnd())); 9670 } 9671 9672 // Check if the destination is an array (rather than a pointer to an array). 9673 QualType DstTy = DstArg->getType(); 9674 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9675 Context); 9676 if (!isKnownSizeArray) { 9677 if (PatternType == 1) 9678 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9679 else 9680 Diag(SL, diag::warn_strncat_src_size) << SR; 9681 return; 9682 } 9683 9684 if (PatternType == 1) 9685 Diag(SL, diag::warn_strncat_large_size) << SR; 9686 else 9687 Diag(SL, diag::warn_strncat_src_size) << SR; 9688 9689 SmallString<128> sizeString; 9690 llvm::raw_svector_ostream OS(sizeString); 9691 OS << "sizeof("; 9692 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9693 OS << ") - "; 9694 OS << "strlen("; 9695 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9696 OS << ") - 1"; 9697 9698 Diag(SL, diag::note_strncat_wrong_size) 9699 << FixItHint::CreateReplacement(SR, OS.str()); 9700 } 9701 9702 void 9703 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9704 SourceLocation ReturnLoc, 9705 bool isObjCMethod, 9706 const AttrVec *Attrs, 9707 const FunctionDecl *FD) { 9708 // Check if the return value is null but should not be. 9709 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9710 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9711 CheckNonNullExpr(*this, RetValExp)) 9712 Diag(ReturnLoc, diag::warn_null_ret) 9713 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9714 9715 // C++11 [basic.stc.dynamic.allocation]p4: 9716 // If an allocation function declared with a non-throwing 9717 // exception-specification fails to allocate storage, it shall return 9718 // a null pointer. Any other allocation function that fails to allocate 9719 // storage shall indicate failure only by throwing an exception [...] 9720 if (FD) { 9721 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9722 if (Op == OO_New || Op == OO_Array_New) { 9723 const FunctionProtoType *Proto 9724 = FD->getType()->castAs<FunctionProtoType>(); 9725 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9726 CheckNonNullExpr(*this, RetValExp)) 9727 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9728 << FD << getLangOpts().CPlusPlus11; 9729 } 9730 } 9731 } 9732 9733 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9734 9735 /// Check for comparisons of floating point operands using != and ==. 9736 /// Issue a warning if these are no self-comparisons, as they are not likely 9737 /// to do what the programmer intended. 9738 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9739 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9740 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9741 9742 // Special case: check for x == x (which is OK). 9743 // Do not emit warnings for such cases. 9744 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9745 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9746 if (DRL->getDecl() == DRR->getDecl()) 9747 return; 9748 9749 // Special case: check for comparisons against literals that can be exactly 9750 // represented by APFloat. In such cases, do not emit a warning. This 9751 // is a heuristic: often comparison against such literals are used to 9752 // detect if a value in a variable has not changed. This clearly can 9753 // lead to false negatives. 9754 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9755 if (FLL->isExact()) 9756 return; 9757 } else 9758 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9759 if (FLR->isExact()) 9760 return; 9761 9762 // Check for comparisons with builtin types. 9763 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9764 if (CL->getBuiltinCallee()) 9765 return; 9766 9767 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9768 if (CR->getBuiltinCallee()) 9769 return; 9770 9771 // Emit the diagnostic. 9772 Diag(Loc, diag::warn_floatingpoint_eq) 9773 << LHS->getSourceRange() << RHS->getSourceRange(); 9774 } 9775 9776 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9777 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9778 9779 namespace { 9780 9781 /// Structure recording the 'active' range of an integer-valued 9782 /// expression. 9783 struct IntRange { 9784 /// The number of bits active in the int. 9785 unsigned Width; 9786 9787 /// True if the int is known not to have negative values. 9788 bool NonNegative; 9789 9790 IntRange(unsigned Width, bool NonNegative) 9791 : Width(Width), NonNegative(NonNegative) {} 9792 9793 /// Returns the range of the bool type. 9794 static IntRange forBoolType() { 9795 return IntRange(1, true); 9796 } 9797 9798 /// Returns the range of an opaque value of the given integral type. 9799 static IntRange forValueOfType(ASTContext &C, QualType T) { 9800 return forValueOfCanonicalType(C, 9801 T->getCanonicalTypeInternal().getTypePtr()); 9802 } 9803 9804 /// Returns the range of an opaque value of a canonical integral type. 9805 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9806 assert(T->isCanonicalUnqualified()); 9807 9808 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9809 T = VT->getElementType().getTypePtr(); 9810 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9811 T = CT->getElementType().getTypePtr(); 9812 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9813 T = AT->getValueType().getTypePtr(); 9814 9815 if (!C.getLangOpts().CPlusPlus) { 9816 // For enum types in C code, use the underlying datatype. 9817 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9818 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9819 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9820 // For enum types in C++, use the known bit width of the enumerators. 9821 EnumDecl *Enum = ET->getDecl(); 9822 // In C++11, enums can have a fixed underlying type. Use this type to 9823 // compute the range. 9824 if (Enum->isFixed()) { 9825 return IntRange(C.getIntWidth(QualType(T, 0)), 9826 !ET->isSignedIntegerOrEnumerationType()); 9827 } 9828 9829 unsigned NumPositive = Enum->getNumPositiveBits(); 9830 unsigned NumNegative = Enum->getNumNegativeBits(); 9831 9832 if (NumNegative == 0) 9833 return IntRange(NumPositive, true/*NonNegative*/); 9834 else 9835 return IntRange(std::max(NumPositive + 1, NumNegative), 9836 false/*NonNegative*/); 9837 } 9838 9839 const BuiltinType *BT = cast<BuiltinType>(T); 9840 assert(BT->isInteger()); 9841 9842 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9843 } 9844 9845 /// Returns the "target" range of a canonical integral type, i.e. 9846 /// the range of values expressible in the type. 9847 /// 9848 /// This matches forValueOfCanonicalType except that enums have the 9849 /// full range of their type, not the range of their enumerators. 9850 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9851 assert(T->isCanonicalUnqualified()); 9852 9853 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9854 T = VT->getElementType().getTypePtr(); 9855 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9856 T = CT->getElementType().getTypePtr(); 9857 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9858 T = AT->getValueType().getTypePtr(); 9859 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9860 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9861 9862 const BuiltinType *BT = cast<BuiltinType>(T); 9863 assert(BT->isInteger()); 9864 9865 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9866 } 9867 9868 /// Returns the supremum of two ranges: i.e. their conservative merge. 9869 static IntRange join(IntRange L, IntRange R) { 9870 return IntRange(std::max(L.Width, R.Width), 9871 L.NonNegative && R.NonNegative); 9872 } 9873 9874 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9875 static IntRange meet(IntRange L, IntRange R) { 9876 return IntRange(std::min(L.Width, R.Width), 9877 L.NonNegative || R.NonNegative); 9878 } 9879 }; 9880 9881 } // namespace 9882 9883 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9884 unsigned MaxWidth) { 9885 if (value.isSigned() && value.isNegative()) 9886 return IntRange(value.getMinSignedBits(), false); 9887 9888 if (value.getBitWidth() > MaxWidth) 9889 value = value.trunc(MaxWidth); 9890 9891 // isNonNegative() just checks the sign bit without considering 9892 // signedness. 9893 return IntRange(value.getActiveBits(), true); 9894 } 9895 9896 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9897 unsigned MaxWidth) { 9898 if (result.isInt()) 9899 return GetValueRange(C, result.getInt(), MaxWidth); 9900 9901 if (result.isVector()) { 9902 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9903 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9904 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9905 R = IntRange::join(R, El); 9906 } 9907 return R; 9908 } 9909 9910 if (result.isComplexInt()) { 9911 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9912 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9913 return IntRange::join(R, I); 9914 } 9915 9916 // This can happen with lossless casts to intptr_t of "based" lvalues. 9917 // Assume it might use arbitrary bits. 9918 // FIXME: The only reason we need to pass the type in here is to get 9919 // the sign right on this one case. It would be nice if APValue 9920 // preserved this. 9921 assert(result.isLValue() || result.isAddrLabelDiff()); 9922 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9923 } 9924 9925 static QualType GetExprType(const Expr *E) { 9926 QualType Ty = E->getType(); 9927 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9928 Ty = AtomicRHS->getValueType(); 9929 return Ty; 9930 } 9931 9932 /// Pseudo-evaluate the given integer expression, estimating the 9933 /// range of values it might take. 9934 /// 9935 /// \param MaxWidth - the width to which the value will be truncated 9936 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 9937 bool InConstantContext) { 9938 E = E->IgnoreParens(); 9939 9940 // Try a full evaluation first. 9941 Expr::EvalResult result; 9942 if (E->EvaluateAsRValue(result, C, InConstantContext)) 9943 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9944 9945 // I think we only want to look through implicit casts here; if the 9946 // user has an explicit widening cast, we should treat the value as 9947 // being of the new, wider type. 9948 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9949 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9950 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 9951 9952 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9953 9954 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9955 CE->getCastKind() == CK_BooleanToSignedIntegral; 9956 9957 // Assume that non-integer casts can span the full range of the type. 9958 if (!isIntegerCast) 9959 return OutputTypeRange; 9960 9961 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 9962 std::min(MaxWidth, OutputTypeRange.Width), 9963 InConstantContext); 9964 9965 // Bail out if the subexpr's range is as wide as the cast type. 9966 if (SubRange.Width >= OutputTypeRange.Width) 9967 return OutputTypeRange; 9968 9969 // Otherwise, we take the smaller width, and we're non-negative if 9970 // either the output type or the subexpr is. 9971 return IntRange(SubRange.Width, 9972 SubRange.NonNegative || OutputTypeRange.NonNegative); 9973 } 9974 9975 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9976 // If we can fold the condition, just take that operand. 9977 bool CondResult; 9978 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9979 return GetExprRange(C, 9980 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 9981 MaxWidth, InConstantContext); 9982 9983 // Otherwise, conservatively merge. 9984 IntRange L = 9985 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 9986 IntRange R = 9987 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 9988 return IntRange::join(L, R); 9989 } 9990 9991 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9992 switch (BO->getOpcode()) { 9993 case BO_Cmp: 9994 llvm_unreachable("builtin <=> should have class type"); 9995 9996 // Boolean-valued operations are single-bit and positive. 9997 case BO_LAnd: 9998 case BO_LOr: 9999 case BO_LT: 10000 case BO_GT: 10001 case BO_LE: 10002 case BO_GE: 10003 case BO_EQ: 10004 case BO_NE: 10005 return IntRange::forBoolType(); 10006 10007 // The type of the assignments is the type of the LHS, so the RHS 10008 // is not necessarily the same type. 10009 case BO_MulAssign: 10010 case BO_DivAssign: 10011 case BO_RemAssign: 10012 case BO_AddAssign: 10013 case BO_SubAssign: 10014 case BO_XorAssign: 10015 case BO_OrAssign: 10016 // TODO: bitfields? 10017 return IntRange::forValueOfType(C, GetExprType(E)); 10018 10019 // Simple assignments just pass through the RHS, which will have 10020 // been coerced to the LHS type. 10021 case BO_Assign: 10022 // TODO: bitfields? 10023 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10024 10025 // Operations with opaque sources are black-listed. 10026 case BO_PtrMemD: 10027 case BO_PtrMemI: 10028 return IntRange::forValueOfType(C, GetExprType(E)); 10029 10030 // Bitwise-and uses the *infinum* of the two source ranges. 10031 case BO_And: 10032 case BO_AndAssign: 10033 return IntRange::meet( 10034 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10035 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10036 10037 // Left shift gets black-listed based on a judgement call. 10038 case BO_Shl: 10039 // ...except that we want to treat '1 << (blah)' as logically 10040 // positive. It's an important idiom. 10041 if (IntegerLiteral *I 10042 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10043 if (I->getValue() == 1) { 10044 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10045 return IntRange(R.Width, /*NonNegative*/ true); 10046 } 10047 } 10048 LLVM_FALLTHROUGH; 10049 10050 case BO_ShlAssign: 10051 return IntRange::forValueOfType(C, GetExprType(E)); 10052 10053 // Right shift by a constant can narrow its left argument. 10054 case BO_Shr: 10055 case BO_ShrAssign: { 10056 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10057 10058 // If the shift amount is a positive constant, drop the width by 10059 // that much. 10060 llvm::APSInt shift; 10061 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10062 shift.isNonNegative()) { 10063 unsigned zext = shift.getZExtValue(); 10064 if (zext >= L.Width) 10065 L.Width = (L.NonNegative ? 0 : 1); 10066 else 10067 L.Width -= zext; 10068 } 10069 10070 return L; 10071 } 10072 10073 // Comma acts as its right operand. 10074 case BO_Comma: 10075 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10076 10077 // Black-list pointer subtractions. 10078 case BO_Sub: 10079 if (BO->getLHS()->getType()->isPointerType()) 10080 return IntRange::forValueOfType(C, GetExprType(E)); 10081 break; 10082 10083 // The width of a division result is mostly determined by the size 10084 // of the LHS. 10085 case BO_Div: { 10086 // Don't 'pre-truncate' the operands. 10087 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10088 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10089 10090 // If the divisor is constant, use that. 10091 llvm::APSInt divisor; 10092 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10093 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10094 if (log2 >= L.Width) 10095 L.Width = (L.NonNegative ? 0 : 1); 10096 else 10097 L.Width = std::min(L.Width - log2, MaxWidth); 10098 return L; 10099 } 10100 10101 // Otherwise, just use the LHS's width. 10102 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10103 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10104 } 10105 10106 // The result of a remainder can't be larger than the result of 10107 // either side. 10108 case BO_Rem: { 10109 // Don't 'pre-truncate' the operands. 10110 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10111 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10112 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10113 10114 IntRange meet = IntRange::meet(L, R); 10115 meet.Width = std::min(meet.Width, MaxWidth); 10116 return meet; 10117 } 10118 10119 // The default behavior is okay for these. 10120 case BO_Mul: 10121 case BO_Add: 10122 case BO_Xor: 10123 case BO_Or: 10124 break; 10125 } 10126 10127 // The default case is to treat the operation as if it were closed 10128 // on the narrowest type that encompasses both operands. 10129 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10130 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10131 return IntRange::join(L, R); 10132 } 10133 10134 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10135 switch (UO->getOpcode()) { 10136 // Boolean-valued operations are white-listed. 10137 case UO_LNot: 10138 return IntRange::forBoolType(); 10139 10140 // Operations with opaque sources are black-listed. 10141 case UO_Deref: 10142 case UO_AddrOf: // should be impossible 10143 return IntRange::forValueOfType(C, GetExprType(E)); 10144 10145 default: 10146 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10147 } 10148 } 10149 10150 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10151 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10152 10153 if (const auto *BitField = E->getSourceBitField()) 10154 return IntRange(BitField->getBitWidthValue(C), 10155 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10156 10157 return IntRange::forValueOfType(C, GetExprType(E)); 10158 } 10159 10160 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10161 bool InConstantContext) { 10162 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10163 } 10164 10165 /// Checks whether the given value, which currently has the given 10166 /// source semantics, has the same value when coerced through the 10167 /// target semantics. 10168 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10169 const llvm::fltSemantics &Src, 10170 const llvm::fltSemantics &Tgt) { 10171 llvm::APFloat truncated = value; 10172 10173 bool ignored; 10174 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10175 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10176 10177 return truncated.bitwiseIsEqual(value); 10178 } 10179 10180 /// Checks whether the given value, which currently has the given 10181 /// source semantics, has the same value when coerced through the 10182 /// target semantics. 10183 /// 10184 /// The value might be a vector of floats (or a complex number). 10185 static bool IsSameFloatAfterCast(const APValue &value, 10186 const llvm::fltSemantics &Src, 10187 const llvm::fltSemantics &Tgt) { 10188 if (value.isFloat()) 10189 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10190 10191 if (value.isVector()) { 10192 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10193 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10194 return false; 10195 return true; 10196 } 10197 10198 assert(value.isComplexFloat()); 10199 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10200 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10201 } 10202 10203 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10204 bool IsListInit = false); 10205 10206 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10207 // Suppress cases where we are comparing against an enum constant. 10208 if (const DeclRefExpr *DR = 10209 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10210 if (isa<EnumConstantDecl>(DR->getDecl())) 10211 return true; 10212 10213 // Suppress cases where the value is expanded from a macro, unless that macro 10214 // is how a language represents a boolean literal. This is the case in both C 10215 // and Objective-C. 10216 SourceLocation BeginLoc = E->getBeginLoc(); 10217 if (BeginLoc.isMacroID()) { 10218 StringRef MacroName = Lexer::getImmediateMacroName( 10219 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10220 return MacroName != "YES" && MacroName != "NO" && 10221 MacroName != "true" && MacroName != "false"; 10222 } 10223 10224 return false; 10225 } 10226 10227 static bool isKnownToHaveUnsignedValue(Expr *E) { 10228 return E->getType()->isIntegerType() && 10229 (!E->getType()->isSignedIntegerType() || 10230 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10231 } 10232 10233 namespace { 10234 /// The promoted range of values of a type. In general this has the 10235 /// following structure: 10236 /// 10237 /// |-----------| . . . |-----------| 10238 /// ^ ^ ^ ^ 10239 /// Min HoleMin HoleMax Max 10240 /// 10241 /// ... where there is only a hole if a signed type is promoted to unsigned 10242 /// (in which case Min and Max are the smallest and largest representable 10243 /// values). 10244 struct PromotedRange { 10245 // Min, or HoleMax if there is a hole. 10246 llvm::APSInt PromotedMin; 10247 // Max, or HoleMin if there is a hole. 10248 llvm::APSInt PromotedMax; 10249 10250 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10251 if (R.Width == 0) 10252 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10253 else if (R.Width >= BitWidth && !Unsigned) { 10254 // Promotion made the type *narrower*. This happens when promoting 10255 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10256 // Treat all values of 'signed int' as being in range for now. 10257 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10258 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10259 } else { 10260 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10261 .extOrTrunc(BitWidth); 10262 PromotedMin.setIsUnsigned(Unsigned); 10263 10264 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10265 .extOrTrunc(BitWidth); 10266 PromotedMax.setIsUnsigned(Unsigned); 10267 } 10268 } 10269 10270 // Determine whether this range is contiguous (has no hole). 10271 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10272 10273 // Where a constant value is within the range. 10274 enum ComparisonResult { 10275 LT = 0x1, 10276 LE = 0x2, 10277 GT = 0x4, 10278 GE = 0x8, 10279 EQ = 0x10, 10280 NE = 0x20, 10281 InRangeFlag = 0x40, 10282 10283 Less = LE | LT | NE, 10284 Min = LE | InRangeFlag, 10285 InRange = InRangeFlag, 10286 Max = GE | InRangeFlag, 10287 Greater = GE | GT | NE, 10288 10289 OnlyValue = LE | GE | EQ | InRangeFlag, 10290 InHole = NE 10291 }; 10292 10293 ComparisonResult compare(const llvm::APSInt &Value) const { 10294 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10295 Value.isUnsigned() == PromotedMin.isUnsigned()); 10296 if (!isContiguous()) { 10297 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10298 if (Value.isMinValue()) return Min; 10299 if (Value.isMaxValue()) return Max; 10300 if (Value >= PromotedMin) return InRange; 10301 if (Value <= PromotedMax) return InRange; 10302 return InHole; 10303 } 10304 10305 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10306 case -1: return Less; 10307 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10308 case 1: 10309 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10310 case -1: return InRange; 10311 case 0: return Max; 10312 case 1: return Greater; 10313 } 10314 } 10315 10316 llvm_unreachable("impossible compare result"); 10317 } 10318 10319 static llvm::Optional<StringRef> 10320 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10321 if (Op == BO_Cmp) { 10322 ComparisonResult LTFlag = LT, GTFlag = GT; 10323 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10324 10325 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10326 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10327 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10328 return llvm::None; 10329 } 10330 10331 ComparisonResult TrueFlag, FalseFlag; 10332 if (Op == BO_EQ) { 10333 TrueFlag = EQ; 10334 FalseFlag = NE; 10335 } else if (Op == BO_NE) { 10336 TrueFlag = NE; 10337 FalseFlag = EQ; 10338 } else { 10339 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10340 TrueFlag = LT; 10341 FalseFlag = GE; 10342 } else { 10343 TrueFlag = GT; 10344 FalseFlag = LE; 10345 } 10346 if (Op == BO_GE || Op == BO_LE) 10347 std::swap(TrueFlag, FalseFlag); 10348 } 10349 if (R & TrueFlag) 10350 return StringRef("true"); 10351 if (R & FalseFlag) 10352 return StringRef("false"); 10353 return llvm::None; 10354 } 10355 }; 10356 } 10357 10358 static bool HasEnumType(Expr *E) { 10359 // Strip off implicit integral promotions. 10360 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10361 if (ICE->getCastKind() != CK_IntegralCast && 10362 ICE->getCastKind() != CK_NoOp) 10363 break; 10364 E = ICE->getSubExpr(); 10365 } 10366 10367 return E->getType()->isEnumeralType(); 10368 } 10369 10370 static int classifyConstantValue(Expr *Constant) { 10371 // The values of this enumeration are used in the diagnostics 10372 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10373 enum ConstantValueKind { 10374 Miscellaneous = 0, 10375 LiteralTrue, 10376 LiteralFalse 10377 }; 10378 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10379 return BL->getValue() ? ConstantValueKind::LiteralTrue 10380 : ConstantValueKind::LiteralFalse; 10381 return ConstantValueKind::Miscellaneous; 10382 } 10383 10384 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10385 Expr *Constant, Expr *Other, 10386 const llvm::APSInt &Value, 10387 bool RhsConstant) { 10388 if (S.inTemplateInstantiation()) 10389 return false; 10390 10391 Expr *OriginalOther = Other; 10392 10393 Constant = Constant->IgnoreParenImpCasts(); 10394 Other = Other->IgnoreParenImpCasts(); 10395 10396 // Suppress warnings on tautological comparisons between values of the same 10397 // enumeration type. There are only two ways we could warn on this: 10398 // - If the constant is outside the range of representable values of 10399 // the enumeration. In such a case, we should warn about the cast 10400 // to enumeration type, not about the comparison. 10401 // - If the constant is the maximum / minimum in-range value. For an 10402 // enumeratin type, such comparisons can be meaningful and useful. 10403 if (Constant->getType()->isEnumeralType() && 10404 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10405 return false; 10406 10407 // TODO: Investigate using GetExprRange() to get tighter bounds 10408 // on the bit ranges. 10409 QualType OtherT = Other->getType(); 10410 if (const auto *AT = OtherT->getAs<AtomicType>()) 10411 OtherT = AT->getValueType(); 10412 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10413 10414 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10415 // (Namely, macOS). 10416 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10417 S.NSAPIObj->isObjCBOOLType(OtherT) && 10418 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10419 10420 // Whether we're treating Other as being a bool because of the form of 10421 // expression despite it having another type (typically 'int' in C). 10422 bool OtherIsBooleanDespiteType = 10423 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10424 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10425 OtherRange = IntRange::forBoolType(); 10426 10427 // Determine the promoted range of the other type and see if a comparison of 10428 // the constant against that range is tautological. 10429 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10430 Value.isUnsigned()); 10431 auto Cmp = OtherPromotedRange.compare(Value); 10432 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10433 if (!Result) 10434 return false; 10435 10436 // Suppress the diagnostic for an in-range comparison if the constant comes 10437 // from a macro or enumerator. We don't want to diagnose 10438 // 10439 // some_long_value <= INT_MAX 10440 // 10441 // when sizeof(int) == sizeof(long). 10442 bool InRange = Cmp & PromotedRange::InRangeFlag; 10443 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10444 return false; 10445 10446 // If this is a comparison to an enum constant, include that 10447 // constant in the diagnostic. 10448 const EnumConstantDecl *ED = nullptr; 10449 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10450 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10451 10452 // Should be enough for uint128 (39 decimal digits) 10453 SmallString<64> PrettySourceValue; 10454 llvm::raw_svector_ostream OS(PrettySourceValue); 10455 if (ED) { 10456 OS << '\'' << *ED << "' (" << Value << ")"; 10457 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10458 Constant->IgnoreParenImpCasts())) { 10459 OS << (BL->getValue() ? "YES" : "NO"); 10460 } else { 10461 OS << Value; 10462 } 10463 10464 if (IsObjCSignedCharBool) { 10465 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10466 S.PDiag(diag::warn_tautological_compare_objc_bool) 10467 << OS.str() << *Result); 10468 return true; 10469 } 10470 10471 // FIXME: We use a somewhat different formatting for the in-range cases and 10472 // cases involving boolean values for historical reasons. We should pick a 10473 // consistent way of presenting these diagnostics. 10474 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10475 10476 S.DiagRuntimeBehavior( 10477 E->getOperatorLoc(), E, 10478 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10479 : diag::warn_tautological_bool_compare) 10480 << OS.str() << classifyConstantValue(Constant) << OtherT 10481 << OtherIsBooleanDespiteType << *Result 10482 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10483 } else { 10484 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10485 ? (HasEnumType(OriginalOther) 10486 ? diag::warn_unsigned_enum_always_true_comparison 10487 : diag::warn_unsigned_always_true_comparison) 10488 : diag::warn_tautological_constant_compare; 10489 10490 S.Diag(E->getOperatorLoc(), Diag) 10491 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10492 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10493 } 10494 10495 return true; 10496 } 10497 10498 /// Analyze the operands of the given comparison. Implements the 10499 /// fallback case from AnalyzeComparison. 10500 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10501 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10502 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10503 } 10504 10505 /// Implements -Wsign-compare. 10506 /// 10507 /// \param E the binary operator to check for warnings 10508 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10509 // The type the comparison is being performed in. 10510 QualType T = E->getLHS()->getType(); 10511 10512 // Only analyze comparison operators where both sides have been converted to 10513 // the same type. 10514 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10515 return AnalyzeImpConvsInComparison(S, E); 10516 10517 // Don't analyze value-dependent comparisons directly. 10518 if (E->isValueDependent()) 10519 return AnalyzeImpConvsInComparison(S, E); 10520 10521 Expr *LHS = E->getLHS(); 10522 Expr *RHS = E->getRHS(); 10523 10524 if (T->isIntegralType(S.Context)) { 10525 llvm::APSInt RHSValue; 10526 llvm::APSInt LHSValue; 10527 10528 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10529 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10530 10531 // We don't care about expressions whose result is a constant. 10532 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10533 return AnalyzeImpConvsInComparison(S, E); 10534 10535 // We only care about expressions where just one side is literal 10536 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10537 // Is the constant on the RHS or LHS? 10538 const bool RhsConstant = IsRHSIntegralLiteral; 10539 Expr *Const = RhsConstant ? RHS : LHS; 10540 Expr *Other = RhsConstant ? LHS : RHS; 10541 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10542 10543 // Check whether an integer constant comparison results in a value 10544 // of 'true' or 'false'. 10545 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10546 return AnalyzeImpConvsInComparison(S, E); 10547 } 10548 } 10549 10550 if (!T->hasUnsignedIntegerRepresentation()) { 10551 // We don't do anything special if this isn't an unsigned integral 10552 // comparison: we're only interested in integral comparisons, and 10553 // signed comparisons only happen in cases we don't care to warn about. 10554 return AnalyzeImpConvsInComparison(S, E); 10555 } 10556 10557 LHS = LHS->IgnoreParenImpCasts(); 10558 RHS = RHS->IgnoreParenImpCasts(); 10559 10560 if (!S.getLangOpts().CPlusPlus) { 10561 // Avoid warning about comparison of integers with different signs when 10562 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10563 // the type of `E`. 10564 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10565 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10566 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10567 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10568 } 10569 10570 // Check to see if one of the (unmodified) operands is of different 10571 // signedness. 10572 Expr *signedOperand, *unsignedOperand; 10573 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10574 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10575 "unsigned comparison between two signed integer expressions?"); 10576 signedOperand = LHS; 10577 unsignedOperand = RHS; 10578 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10579 signedOperand = RHS; 10580 unsignedOperand = LHS; 10581 } else { 10582 return AnalyzeImpConvsInComparison(S, E); 10583 } 10584 10585 // Otherwise, calculate the effective range of the signed operand. 10586 IntRange signedRange = 10587 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10588 10589 // Go ahead and analyze implicit conversions in the operands. Note 10590 // that we skip the implicit conversions on both sides. 10591 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10592 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10593 10594 // If the signed range is non-negative, -Wsign-compare won't fire. 10595 if (signedRange.NonNegative) 10596 return; 10597 10598 // For (in)equality comparisons, if the unsigned operand is a 10599 // constant which cannot collide with a overflowed signed operand, 10600 // then reinterpreting the signed operand as unsigned will not 10601 // change the result of the comparison. 10602 if (E->isEqualityOp()) { 10603 unsigned comparisonWidth = S.Context.getIntWidth(T); 10604 IntRange unsignedRange = 10605 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10606 10607 // We should never be unable to prove that the unsigned operand is 10608 // non-negative. 10609 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10610 10611 if (unsignedRange.Width < comparisonWidth) 10612 return; 10613 } 10614 10615 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10616 S.PDiag(diag::warn_mixed_sign_comparison) 10617 << LHS->getType() << RHS->getType() 10618 << LHS->getSourceRange() << RHS->getSourceRange()); 10619 } 10620 10621 /// Analyzes an attempt to assign the given value to a bitfield. 10622 /// 10623 /// Returns true if there was something fishy about the attempt. 10624 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10625 SourceLocation InitLoc) { 10626 assert(Bitfield->isBitField()); 10627 if (Bitfield->isInvalidDecl()) 10628 return false; 10629 10630 // White-list bool bitfields. 10631 QualType BitfieldType = Bitfield->getType(); 10632 if (BitfieldType->isBooleanType()) 10633 return false; 10634 10635 if (BitfieldType->isEnumeralType()) { 10636 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10637 // If the underlying enum type was not explicitly specified as an unsigned 10638 // type and the enum contain only positive values, MSVC++ will cause an 10639 // inconsistency by storing this as a signed type. 10640 if (S.getLangOpts().CPlusPlus11 && 10641 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10642 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10643 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10644 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10645 << BitfieldEnumDecl->getNameAsString(); 10646 } 10647 } 10648 10649 if (Bitfield->getType()->isBooleanType()) 10650 return false; 10651 10652 // Ignore value- or type-dependent expressions. 10653 if (Bitfield->getBitWidth()->isValueDependent() || 10654 Bitfield->getBitWidth()->isTypeDependent() || 10655 Init->isValueDependent() || 10656 Init->isTypeDependent()) 10657 return false; 10658 10659 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10660 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10661 10662 Expr::EvalResult Result; 10663 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10664 Expr::SE_AllowSideEffects)) { 10665 // The RHS is not constant. If the RHS has an enum type, make sure the 10666 // bitfield is wide enough to hold all the values of the enum without 10667 // truncation. 10668 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10669 EnumDecl *ED = EnumTy->getDecl(); 10670 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10671 10672 // Enum types are implicitly signed on Windows, so check if there are any 10673 // negative enumerators to see if the enum was intended to be signed or 10674 // not. 10675 bool SignedEnum = ED->getNumNegativeBits() > 0; 10676 10677 // Check for surprising sign changes when assigning enum values to a 10678 // bitfield of different signedness. If the bitfield is signed and we 10679 // have exactly the right number of bits to store this unsigned enum, 10680 // suggest changing the enum to an unsigned type. This typically happens 10681 // on Windows where unfixed enums always use an underlying type of 'int'. 10682 unsigned DiagID = 0; 10683 if (SignedEnum && !SignedBitfield) { 10684 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10685 } else if (SignedBitfield && !SignedEnum && 10686 ED->getNumPositiveBits() == FieldWidth) { 10687 DiagID = diag::warn_signed_bitfield_enum_conversion; 10688 } 10689 10690 if (DiagID) { 10691 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10692 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10693 SourceRange TypeRange = 10694 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10695 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10696 << SignedEnum << TypeRange; 10697 } 10698 10699 // Compute the required bitwidth. If the enum has negative values, we need 10700 // one more bit than the normal number of positive bits to represent the 10701 // sign bit. 10702 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10703 ED->getNumNegativeBits()) 10704 : ED->getNumPositiveBits(); 10705 10706 // Check the bitwidth. 10707 if (BitsNeeded > FieldWidth) { 10708 Expr *WidthExpr = Bitfield->getBitWidth(); 10709 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10710 << Bitfield << ED; 10711 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10712 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10713 } 10714 } 10715 10716 return false; 10717 } 10718 10719 llvm::APSInt Value = Result.Val.getInt(); 10720 10721 unsigned OriginalWidth = Value.getBitWidth(); 10722 10723 if (!Value.isSigned() || Value.isNegative()) 10724 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10725 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10726 OriginalWidth = Value.getMinSignedBits(); 10727 10728 if (OriginalWidth <= FieldWidth) 10729 return false; 10730 10731 // Compute the value which the bitfield will contain. 10732 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10733 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10734 10735 // Check whether the stored value is equal to the original value. 10736 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10737 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10738 return false; 10739 10740 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10741 // therefore don't strictly fit into a signed bitfield of width 1. 10742 if (FieldWidth == 1 && Value == 1) 10743 return false; 10744 10745 std::string PrettyValue = Value.toString(10); 10746 std::string PrettyTrunc = TruncatedValue.toString(10); 10747 10748 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10749 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10750 << Init->getSourceRange(); 10751 10752 return true; 10753 } 10754 10755 /// Analyze the given simple or compound assignment for warning-worthy 10756 /// operations. 10757 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10758 // Just recurse on the LHS. 10759 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10760 10761 // We want to recurse on the RHS as normal unless we're assigning to 10762 // a bitfield. 10763 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10764 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10765 E->getOperatorLoc())) { 10766 // Recurse, ignoring any implicit conversions on the RHS. 10767 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10768 E->getOperatorLoc()); 10769 } 10770 } 10771 10772 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10773 10774 // Diagnose implicitly sequentially-consistent atomic assignment. 10775 if (E->getLHS()->getType()->isAtomicType()) 10776 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10777 } 10778 10779 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10780 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10781 SourceLocation CContext, unsigned diag, 10782 bool pruneControlFlow = false) { 10783 if (pruneControlFlow) { 10784 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10785 S.PDiag(diag) 10786 << SourceType << T << E->getSourceRange() 10787 << SourceRange(CContext)); 10788 return; 10789 } 10790 S.Diag(E->getExprLoc(), diag) 10791 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10792 } 10793 10794 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10795 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10796 SourceLocation CContext, 10797 unsigned diag, bool pruneControlFlow = false) { 10798 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10799 } 10800 10801 /// Diagnose an implicit cast from a floating point value to an integer value. 10802 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10803 SourceLocation CContext) { 10804 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10805 const bool PruneWarnings = S.inTemplateInstantiation(); 10806 10807 Expr *InnerE = E->IgnoreParenImpCasts(); 10808 // We also want to warn on, e.g., "int i = -1.234" 10809 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10810 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10811 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10812 10813 const bool IsLiteral = 10814 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10815 10816 llvm::APFloat Value(0.0); 10817 bool IsConstant = 10818 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10819 if (!IsConstant) { 10820 return DiagnoseImpCast(S, E, T, CContext, 10821 diag::warn_impcast_float_integer, PruneWarnings); 10822 } 10823 10824 bool isExact = false; 10825 10826 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10827 T->hasUnsignedIntegerRepresentation()); 10828 llvm::APFloat::opStatus Result = Value.convertToInteger( 10829 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10830 10831 if (Result == llvm::APFloat::opOK && isExact) { 10832 if (IsLiteral) return; 10833 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10834 PruneWarnings); 10835 } 10836 10837 // Conversion of a floating-point value to a non-bool integer where the 10838 // integral part cannot be represented by the integer type is undefined. 10839 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10840 return DiagnoseImpCast( 10841 S, E, T, CContext, 10842 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10843 : diag::warn_impcast_float_to_integer_out_of_range, 10844 PruneWarnings); 10845 10846 unsigned DiagID = 0; 10847 if (IsLiteral) { 10848 // Warn on floating point literal to integer. 10849 DiagID = diag::warn_impcast_literal_float_to_integer; 10850 } else if (IntegerValue == 0) { 10851 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10852 return DiagnoseImpCast(S, E, T, CContext, 10853 diag::warn_impcast_float_integer, PruneWarnings); 10854 } 10855 // Warn on non-zero to zero conversion. 10856 DiagID = diag::warn_impcast_float_to_integer_zero; 10857 } else { 10858 if (IntegerValue.isUnsigned()) { 10859 if (!IntegerValue.isMaxValue()) { 10860 return DiagnoseImpCast(S, E, T, CContext, 10861 diag::warn_impcast_float_integer, PruneWarnings); 10862 } 10863 } else { // IntegerValue.isSigned() 10864 if (!IntegerValue.isMaxSignedValue() && 10865 !IntegerValue.isMinSignedValue()) { 10866 return DiagnoseImpCast(S, E, T, CContext, 10867 diag::warn_impcast_float_integer, PruneWarnings); 10868 } 10869 } 10870 // Warn on evaluatable floating point expression to integer conversion. 10871 DiagID = diag::warn_impcast_float_to_integer; 10872 } 10873 10874 // FIXME: Force the precision of the source value down so we don't print 10875 // digits which are usually useless (we don't really care here if we 10876 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10877 // would automatically print the shortest representation, but it's a bit 10878 // tricky to implement. 10879 SmallString<16> PrettySourceValue; 10880 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10881 precision = (precision * 59 + 195) / 196; 10882 Value.toString(PrettySourceValue, precision); 10883 10884 SmallString<16> PrettyTargetValue; 10885 if (IsBool) 10886 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10887 else 10888 IntegerValue.toString(PrettyTargetValue); 10889 10890 if (PruneWarnings) { 10891 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10892 S.PDiag(DiagID) 10893 << E->getType() << T.getUnqualifiedType() 10894 << PrettySourceValue << PrettyTargetValue 10895 << E->getSourceRange() << SourceRange(CContext)); 10896 } else { 10897 S.Diag(E->getExprLoc(), DiagID) 10898 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10899 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10900 } 10901 } 10902 10903 /// Analyze the given compound assignment for the possible losing of 10904 /// floating-point precision. 10905 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10906 assert(isa<CompoundAssignOperator>(E) && 10907 "Must be compound assignment operation"); 10908 // Recurse on the LHS and RHS in here 10909 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10910 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10911 10912 if (E->getLHS()->getType()->isAtomicType()) 10913 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10914 10915 // Now check the outermost expression 10916 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10917 const auto *RBT = cast<CompoundAssignOperator>(E) 10918 ->getComputationResultType() 10919 ->getAs<BuiltinType>(); 10920 10921 // The below checks assume source is floating point. 10922 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10923 10924 // If source is floating point but target is an integer. 10925 if (ResultBT->isInteger()) 10926 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 10927 E->getExprLoc(), diag::warn_impcast_float_integer); 10928 10929 if (!ResultBT->isFloatingPoint()) 10930 return; 10931 10932 // If both source and target are floating points, warn about losing precision. 10933 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 10934 QualType(ResultBT, 0), QualType(RBT, 0)); 10935 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10936 // warn about dropping FP rank. 10937 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10938 diag::warn_impcast_float_result_precision); 10939 } 10940 10941 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10942 IntRange Range) { 10943 if (!Range.Width) return "0"; 10944 10945 llvm::APSInt ValueInRange = Value; 10946 ValueInRange.setIsSigned(!Range.NonNegative); 10947 ValueInRange = ValueInRange.trunc(Range.Width); 10948 return ValueInRange.toString(10); 10949 } 10950 10951 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10952 if (!isa<ImplicitCastExpr>(Ex)) 10953 return false; 10954 10955 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10956 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10957 const Type *Source = 10958 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10959 if (Target->isDependentType()) 10960 return false; 10961 10962 const BuiltinType *FloatCandidateBT = 10963 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10964 const Type *BoolCandidateType = ToBool ? Target : Source; 10965 10966 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10967 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10968 } 10969 10970 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10971 SourceLocation CC) { 10972 unsigned NumArgs = TheCall->getNumArgs(); 10973 for (unsigned i = 0; i < NumArgs; ++i) { 10974 Expr *CurrA = TheCall->getArg(i); 10975 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10976 continue; 10977 10978 bool IsSwapped = ((i > 0) && 10979 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10980 IsSwapped |= ((i < (NumArgs - 1)) && 10981 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10982 if (IsSwapped) { 10983 // Warn on this floating-point to bool conversion. 10984 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10985 CurrA->getType(), CC, 10986 diag::warn_impcast_floating_point_to_bool); 10987 } 10988 } 10989 } 10990 10991 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10992 SourceLocation CC) { 10993 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10994 E->getExprLoc())) 10995 return; 10996 10997 // Don't warn on functions which have return type nullptr_t. 10998 if (isa<CallExpr>(E)) 10999 return; 11000 11001 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11002 const Expr::NullPointerConstantKind NullKind = 11003 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11004 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11005 return; 11006 11007 // Return if target type is a safe conversion. 11008 if (T->isAnyPointerType() || T->isBlockPointerType() || 11009 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11010 return; 11011 11012 SourceLocation Loc = E->getSourceRange().getBegin(); 11013 11014 // Venture through the macro stacks to get to the source of macro arguments. 11015 // The new location is a better location than the complete location that was 11016 // passed in. 11017 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11018 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11019 11020 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11021 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11022 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11023 Loc, S.SourceMgr, S.getLangOpts()); 11024 if (MacroName == "NULL") 11025 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11026 } 11027 11028 // Only warn if the null and context location are in the same macro expansion. 11029 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11030 return; 11031 11032 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11033 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11034 << FixItHint::CreateReplacement(Loc, 11035 S.getFixItZeroLiteralForType(T, Loc)); 11036 } 11037 11038 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11039 ObjCArrayLiteral *ArrayLiteral); 11040 11041 static void 11042 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11043 ObjCDictionaryLiteral *DictionaryLiteral); 11044 11045 /// Check a single element within a collection literal against the 11046 /// target element type. 11047 static void checkObjCCollectionLiteralElement(Sema &S, 11048 QualType TargetElementType, 11049 Expr *Element, 11050 unsigned ElementKind) { 11051 // Skip a bitcast to 'id' or qualified 'id'. 11052 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11053 if (ICE->getCastKind() == CK_BitCast && 11054 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11055 Element = ICE->getSubExpr(); 11056 } 11057 11058 QualType ElementType = Element->getType(); 11059 ExprResult ElementResult(Element); 11060 if (ElementType->getAs<ObjCObjectPointerType>() && 11061 S.CheckSingleAssignmentConstraints(TargetElementType, 11062 ElementResult, 11063 false, false) 11064 != Sema::Compatible) { 11065 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11066 << ElementType << ElementKind << TargetElementType 11067 << Element->getSourceRange(); 11068 } 11069 11070 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11071 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11072 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11073 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11074 } 11075 11076 /// Check an Objective-C array literal being converted to the given 11077 /// target type. 11078 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11079 ObjCArrayLiteral *ArrayLiteral) { 11080 if (!S.NSArrayDecl) 11081 return; 11082 11083 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11084 if (!TargetObjCPtr) 11085 return; 11086 11087 if (TargetObjCPtr->isUnspecialized() || 11088 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11089 != S.NSArrayDecl->getCanonicalDecl()) 11090 return; 11091 11092 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11093 if (TypeArgs.size() != 1) 11094 return; 11095 11096 QualType TargetElementType = TypeArgs[0]; 11097 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11098 checkObjCCollectionLiteralElement(S, TargetElementType, 11099 ArrayLiteral->getElement(I), 11100 0); 11101 } 11102 } 11103 11104 /// Check an Objective-C dictionary literal being converted to the given 11105 /// target type. 11106 static void 11107 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11108 ObjCDictionaryLiteral *DictionaryLiteral) { 11109 if (!S.NSDictionaryDecl) 11110 return; 11111 11112 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11113 if (!TargetObjCPtr) 11114 return; 11115 11116 if (TargetObjCPtr->isUnspecialized() || 11117 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11118 != S.NSDictionaryDecl->getCanonicalDecl()) 11119 return; 11120 11121 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11122 if (TypeArgs.size() != 2) 11123 return; 11124 11125 QualType TargetKeyType = TypeArgs[0]; 11126 QualType TargetObjectType = TypeArgs[1]; 11127 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11128 auto Element = DictionaryLiteral->getKeyValueElement(I); 11129 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11130 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11131 } 11132 } 11133 11134 // Helper function to filter out cases for constant width constant conversion. 11135 // Don't warn on char array initialization or for non-decimal values. 11136 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11137 SourceLocation CC) { 11138 // If initializing from a constant, and the constant starts with '0', 11139 // then it is a binary, octal, or hexadecimal. Allow these constants 11140 // to fill all the bits, even if there is a sign change. 11141 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11142 const char FirstLiteralCharacter = 11143 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11144 if (FirstLiteralCharacter == '0') 11145 return false; 11146 } 11147 11148 // If the CC location points to a '{', and the type is char, then assume 11149 // assume it is an array initialization. 11150 if (CC.isValid() && T->isCharType()) { 11151 const char FirstContextCharacter = 11152 S.getSourceManager().getCharacterData(CC)[0]; 11153 if (FirstContextCharacter == '{') 11154 return false; 11155 } 11156 11157 return true; 11158 } 11159 11160 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11161 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11162 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11163 } 11164 11165 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11166 SourceLocation CC, 11167 bool *ICContext = nullptr, 11168 bool IsListInit = false) { 11169 if (E->isTypeDependent() || E->isValueDependent()) return; 11170 11171 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11172 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11173 if (Source == Target) return; 11174 if (Target->isDependentType()) return; 11175 11176 // If the conversion context location is invalid don't complain. We also 11177 // don't want to emit a warning if the issue occurs from the expansion of 11178 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11179 // delay this check as long as possible. Once we detect we are in that 11180 // scenario, we just return. 11181 if (CC.isInvalid()) 11182 return; 11183 11184 if (Source->isAtomicType()) 11185 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11186 11187 // Diagnose implicit casts to bool. 11188 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11189 if (isa<StringLiteral>(E)) 11190 // Warn on string literal to bool. Checks for string literals in logical 11191 // and expressions, for instance, assert(0 && "error here"), are 11192 // prevented by a check in AnalyzeImplicitConversions(). 11193 return DiagnoseImpCast(S, E, T, CC, 11194 diag::warn_impcast_string_literal_to_bool); 11195 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11196 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11197 // This covers the literal expressions that evaluate to Objective-C 11198 // objects. 11199 return DiagnoseImpCast(S, E, T, CC, 11200 diag::warn_impcast_objective_c_literal_to_bool); 11201 } 11202 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11203 // Warn on pointer to bool conversion that is always true. 11204 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11205 SourceRange(CC)); 11206 } 11207 } 11208 11209 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11210 // is a typedef for signed char (macOS), then that constant value has to be 1 11211 // or 0. 11212 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11213 Expr::EvalResult Result; 11214 if (E->EvaluateAsInt(Result, S.getASTContext(), 11215 Expr::SE_AllowSideEffects) && 11216 Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11217 auto Builder = S.Diag(CC, diag::warn_impcast_constant_int_to_objc_bool) 11218 << Result.Val.getInt().toString(10); 11219 Expr *Ignored = E->IgnoreImplicit(); 11220 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11221 isa<BinaryOperator>(Ignored) || 11222 isa<CXXOperatorCallExpr>(Ignored); 11223 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 11224 if (NeedsParens) 11225 Builder << FixItHint::CreateInsertion(E->getBeginLoc(), "(") 11226 << FixItHint::CreateInsertion(EndLoc, ")"); 11227 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11228 return; 11229 } 11230 } 11231 11232 // Check implicit casts from Objective-C collection literals to specialized 11233 // collection types, e.g., NSArray<NSString *> *. 11234 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11235 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11236 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11237 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11238 11239 // Strip vector types. 11240 if (isa<VectorType>(Source)) { 11241 if (!isa<VectorType>(Target)) { 11242 if (S.SourceMgr.isInSystemMacro(CC)) 11243 return; 11244 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11245 } 11246 11247 // If the vector cast is cast between two vectors of the same size, it is 11248 // a bitcast, not a conversion. 11249 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11250 return; 11251 11252 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11253 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11254 } 11255 if (auto VecTy = dyn_cast<VectorType>(Target)) 11256 Target = VecTy->getElementType().getTypePtr(); 11257 11258 // Strip complex types. 11259 if (isa<ComplexType>(Source)) { 11260 if (!isa<ComplexType>(Target)) { 11261 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11262 return; 11263 11264 return DiagnoseImpCast(S, E, T, CC, 11265 S.getLangOpts().CPlusPlus 11266 ? diag::err_impcast_complex_scalar 11267 : diag::warn_impcast_complex_scalar); 11268 } 11269 11270 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11271 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11272 } 11273 11274 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11275 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11276 11277 // If the source is floating point... 11278 if (SourceBT && SourceBT->isFloatingPoint()) { 11279 // ...and the target is floating point... 11280 if (TargetBT && TargetBT->isFloatingPoint()) { 11281 // ...then warn if we're dropping FP rank. 11282 11283 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11284 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11285 if (Order > 0) { 11286 // Don't warn about float constants that are precisely 11287 // representable in the target type. 11288 Expr::EvalResult result; 11289 if (E->EvaluateAsRValue(result, S.Context)) { 11290 // Value might be a float, a float vector, or a float complex. 11291 if (IsSameFloatAfterCast(result.Val, 11292 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11293 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11294 return; 11295 } 11296 11297 if (S.SourceMgr.isInSystemMacro(CC)) 11298 return; 11299 11300 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11301 } 11302 // ... or possibly if we're increasing rank, too 11303 else if (Order < 0) { 11304 if (S.SourceMgr.isInSystemMacro(CC)) 11305 return; 11306 11307 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11308 } 11309 return; 11310 } 11311 11312 // If the target is integral, always warn. 11313 if (TargetBT && TargetBT->isInteger()) { 11314 if (S.SourceMgr.isInSystemMacro(CC)) 11315 return; 11316 11317 DiagnoseFloatingImpCast(S, E, T, CC); 11318 } 11319 11320 // Detect the case where a call result is converted from floating-point to 11321 // to bool, and the final argument to the call is converted from bool, to 11322 // discover this typo: 11323 // 11324 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11325 // 11326 // FIXME: This is an incredibly special case; is there some more general 11327 // way to detect this class of misplaced-parentheses bug? 11328 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11329 // Check last argument of function call to see if it is an 11330 // implicit cast from a type matching the type the result 11331 // is being cast to. 11332 CallExpr *CEx = cast<CallExpr>(E); 11333 if (unsigned NumArgs = CEx->getNumArgs()) { 11334 Expr *LastA = CEx->getArg(NumArgs - 1); 11335 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11336 if (isa<ImplicitCastExpr>(LastA) && 11337 InnerE->getType()->isBooleanType()) { 11338 // Warn on this floating-point to bool conversion 11339 DiagnoseImpCast(S, E, T, CC, 11340 diag::warn_impcast_floating_point_to_bool); 11341 } 11342 } 11343 } 11344 return; 11345 } 11346 11347 // Valid casts involving fixed point types should be accounted for here. 11348 if (Source->isFixedPointType()) { 11349 if (Target->isUnsaturatedFixedPointType()) { 11350 Expr::EvalResult Result; 11351 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11352 S.isConstantEvaluated())) { 11353 APFixedPoint Value = Result.Val.getFixedPoint(); 11354 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11355 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11356 if (Value > MaxVal || Value < MinVal) { 11357 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11358 S.PDiag(diag::warn_impcast_fixed_point_range) 11359 << Value.toString() << T 11360 << E->getSourceRange() 11361 << clang::SourceRange(CC)); 11362 return; 11363 } 11364 } 11365 } else if (Target->isIntegerType()) { 11366 Expr::EvalResult Result; 11367 if (!S.isConstantEvaluated() && 11368 E->EvaluateAsFixedPoint(Result, S.Context, 11369 Expr::SE_AllowSideEffects)) { 11370 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11371 11372 bool Overflowed; 11373 llvm::APSInt IntResult = FXResult.convertToInt( 11374 S.Context.getIntWidth(T), 11375 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11376 11377 if (Overflowed) { 11378 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11379 S.PDiag(diag::warn_impcast_fixed_point_range) 11380 << FXResult.toString() << T 11381 << E->getSourceRange() 11382 << clang::SourceRange(CC)); 11383 return; 11384 } 11385 } 11386 } 11387 } else if (Target->isUnsaturatedFixedPointType()) { 11388 if (Source->isIntegerType()) { 11389 Expr::EvalResult Result; 11390 if (!S.isConstantEvaluated() && 11391 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11392 llvm::APSInt Value = Result.Val.getInt(); 11393 11394 bool Overflowed; 11395 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11396 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11397 11398 if (Overflowed) { 11399 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11400 S.PDiag(diag::warn_impcast_fixed_point_range) 11401 << Value.toString(/*Radix=*/10) << T 11402 << E->getSourceRange() 11403 << clang::SourceRange(CC)); 11404 return; 11405 } 11406 } 11407 } 11408 } 11409 11410 // If we are casting an integer type to a floating point type without 11411 // initialization-list syntax, we might lose accuracy if the floating 11412 // point type has a narrower significand than the integer type. 11413 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11414 TargetBT->isFloatingType() && !IsListInit) { 11415 // Determine the number of precision bits in the source integer type. 11416 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11417 unsigned int SourcePrecision = SourceRange.Width; 11418 11419 // Determine the number of precision bits in the 11420 // target floating point type. 11421 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11422 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11423 11424 if (SourcePrecision > 0 && TargetPrecision > 0 && 11425 SourcePrecision > TargetPrecision) { 11426 11427 llvm::APSInt SourceInt; 11428 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11429 // If the source integer is a constant, convert it to the target 11430 // floating point type. Issue a warning if the value changes 11431 // during the whole conversion. 11432 llvm::APFloat TargetFloatValue( 11433 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11434 llvm::APFloat::opStatus ConversionStatus = 11435 TargetFloatValue.convertFromAPInt( 11436 SourceInt, SourceBT->isSignedInteger(), 11437 llvm::APFloat::rmNearestTiesToEven); 11438 11439 if (ConversionStatus != llvm::APFloat::opOK) { 11440 std::string PrettySourceValue = SourceInt.toString(10); 11441 SmallString<32> PrettyTargetValue; 11442 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11443 11444 S.DiagRuntimeBehavior( 11445 E->getExprLoc(), E, 11446 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11447 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11448 << E->getSourceRange() << clang::SourceRange(CC)); 11449 } 11450 } else { 11451 // Otherwise, the implicit conversion may lose precision. 11452 DiagnoseImpCast(S, E, T, CC, 11453 diag::warn_impcast_integer_float_precision); 11454 } 11455 } 11456 } 11457 11458 DiagnoseNullConversion(S, E, T, CC); 11459 11460 S.DiscardMisalignedMemberAddress(Target, E); 11461 11462 if (!Source->isIntegerType() || !Target->isIntegerType()) 11463 return; 11464 11465 // TODO: remove this early return once the false positives for constant->bool 11466 // in templates, macros, etc, are reduced or removed. 11467 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11468 return; 11469 11470 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11471 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11472 11473 if (SourceRange.Width > TargetRange.Width) { 11474 // If the source is a constant, use a default-on diagnostic. 11475 // TODO: this should happen for bitfield stores, too. 11476 Expr::EvalResult Result; 11477 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11478 S.isConstantEvaluated())) { 11479 llvm::APSInt Value(32); 11480 Value = Result.Val.getInt(); 11481 11482 if (S.SourceMgr.isInSystemMacro(CC)) 11483 return; 11484 11485 std::string PrettySourceValue = Value.toString(10); 11486 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11487 11488 S.DiagRuntimeBehavior( 11489 E->getExprLoc(), E, 11490 S.PDiag(diag::warn_impcast_integer_precision_constant) 11491 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11492 << E->getSourceRange() << clang::SourceRange(CC)); 11493 return; 11494 } 11495 11496 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11497 if (S.SourceMgr.isInSystemMacro(CC)) 11498 return; 11499 11500 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11501 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11502 /* pruneControlFlow */ true); 11503 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11504 } 11505 11506 if (TargetRange.Width > SourceRange.Width) { 11507 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11508 if (UO->getOpcode() == UO_Minus) 11509 if (Source->isUnsignedIntegerType()) { 11510 if (Target->isUnsignedIntegerType()) 11511 return DiagnoseImpCast(S, E, T, CC, 11512 diag::warn_impcast_high_order_zero_bits); 11513 if (Target->isSignedIntegerType()) 11514 return DiagnoseImpCast(S, E, T, CC, 11515 diag::warn_impcast_nonnegative_result); 11516 } 11517 } 11518 11519 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11520 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11521 // Warn when doing a signed to signed conversion, warn if the positive 11522 // source value is exactly the width of the target type, which will 11523 // cause a negative value to be stored. 11524 11525 Expr::EvalResult Result; 11526 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11527 !S.SourceMgr.isInSystemMacro(CC)) { 11528 llvm::APSInt Value = Result.Val.getInt(); 11529 if (isSameWidthConstantConversion(S, E, T, CC)) { 11530 std::string PrettySourceValue = Value.toString(10); 11531 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11532 11533 S.DiagRuntimeBehavior( 11534 E->getExprLoc(), E, 11535 S.PDiag(diag::warn_impcast_integer_precision_constant) 11536 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11537 << E->getSourceRange() << clang::SourceRange(CC)); 11538 return; 11539 } 11540 } 11541 11542 // Fall through for non-constants to give a sign conversion warning. 11543 } 11544 11545 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11546 (!TargetRange.NonNegative && SourceRange.NonNegative && 11547 SourceRange.Width == TargetRange.Width)) { 11548 if (S.SourceMgr.isInSystemMacro(CC)) 11549 return; 11550 11551 unsigned DiagID = diag::warn_impcast_integer_sign; 11552 11553 // Traditionally, gcc has warned about this under -Wsign-compare. 11554 // We also want to warn about it in -Wconversion. 11555 // So if -Wconversion is off, use a completely identical diagnostic 11556 // in the sign-compare group. 11557 // The conditional-checking code will 11558 if (ICContext) { 11559 DiagID = diag::warn_impcast_integer_sign_conditional; 11560 *ICContext = true; 11561 } 11562 11563 return DiagnoseImpCast(S, E, T, CC, DiagID); 11564 } 11565 11566 // Diagnose conversions between different enumeration types. 11567 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11568 // type, to give us better diagnostics. 11569 QualType SourceType = E->getType(); 11570 if (!S.getLangOpts().CPlusPlus) { 11571 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11572 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11573 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11574 SourceType = S.Context.getTypeDeclType(Enum); 11575 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11576 } 11577 } 11578 11579 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11580 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11581 if (SourceEnum->getDecl()->hasNameForLinkage() && 11582 TargetEnum->getDecl()->hasNameForLinkage() && 11583 SourceEnum != TargetEnum) { 11584 if (S.SourceMgr.isInSystemMacro(CC)) 11585 return; 11586 11587 return DiagnoseImpCast(S, E, SourceType, T, CC, 11588 diag::warn_impcast_different_enum_types); 11589 } 11590 } 11591 11592 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11593 SourceLocation CC, QualType T); 11594 11595 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11596 SourceLocation CC, bool &ICContext) { 11597 E = E->IgnoreParenImpCasts(); 11598 11599 if (isa<ConditionalOperator>(E)) 11600 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11601 11602 AnalyzeImplicitConversions(S, E, CC); 11603 if (E->getType() != T) 11604 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11605 } 11606 11607 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11608 SourceLocation CC, QualType T) { 11609 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11610 11611 bool Suspicious = false; 11612 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11613 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11614 11615 // If -Wconversion would have warned about either of the candidates 11616 // for a signedness conversion to the context type... 11617 if (!Suspicious) return; 11618 11619 // ...but it's currently ignored... 11620 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11621 return; 11622 11623 // ...then check whether it would have warned about either of the 11624 // candidates for a signedness conversion to the condition type. 11625 if (E->getType() == T) return; 11626 11627 Suspicious = false; 11628 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11629 E->getType(), CC, &Suspicious); 11630 if (!Suspicious) 11631 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11632 E->getType(), CC, &Suspicious); 11633 } 11634 11635 /// Check conversion of given expression to boolean. 11636 /// Input argument E is a logical expression. 11637 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11638 if (S.getLangOpts().Bool) 11639 return; 11640 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11641 return; 11642 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11643 } 11644 11645 /// AnalyzeImplicitConversions - Find and report any interesting 11646 /// implicit conversions in the given expression. There are a couple 11647 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11648 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 11649 bool IsListInit/*= false*/) { 11650 QualType T = OrigE->getType(); 11651 Expr *E = OrigE->IgnoreParenImpCasts(); 11652 11653 // Propagate whether we are in a C++ list initialization expression. 11654 // If so, we do not issue warnings for implicit int-float conversion 11655 // precision loss, because C++11 narrowing already handles it. 11656 IsListInit = 11657 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11658 11659 if (E->isTypeDependent() || E->isValueDependent()) 11660 return; 11661 11662 // For conditional operators, we analyze the arguments as if they 11663 // were being fed directly into the output. 11664 if (isa<ConditionalOperator>(E)) { 11665 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11666 CheckConditionalOperator(S, CO, CC, T); 11667 return; 11668 } 11669 11670 // Check implicit argument conversions for function calls. 11671 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11672 CheckImplicitArgumentConversions(S, Call, CC); 11673 11674 // Go ahead and check any implicit conversions we might have skipped. 11675 // The non-canonical typecheck is just an optimization; 11676 // CheckImplicitConversion will filter out dead implicit conversions. 11677 if (E->getType() != T) 11678 CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit); 11679 11680 // Now continue drilling into this expression. 11681 11682 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11683 // The bound subexpressions in a PseudoObjectExpr are not reachable 11684 // as transitive children. 11685 // FIXME: Use a more uniform representation for this. 11686 for (auto *SE : POE->semantics()) 11687 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11688 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit); 11689 } 11690 11691 // Skip past explicit casts. 11692 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11693 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11694 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11695 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11696 return AnalyzeImplicitConversions(S, E, CC, IsListInit); 11697 } 11698 11699 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11700 // Do a somewhat different check with comparison operators. 11701 if (BO->isComparisonOp()) 11702 return AnalyzeComparison(S, BO); 11703 11704 // And with simple assignments. 11705 if (BO->getOpcode() == BO_Assign) 11706 return AnalyzeAssignment(S, BO); 11707 // And with compound assignments. 11708 if (BO->isAssignmentOp()) 11709 return AnalyzeCompoundAssignment(S, BO); 11710 } 11711 11712 // These break the otherwise-useful invariant below. Fortunately, 11713 // we don't really need to recurse into them, because any internal 11714 // expressions should have been analyzed already when they were 11715 // built into statements. 11716 if (isa<StmtExpr>(E)) return; 11717 11718 // Don't descend into unevaluated contexts. 11719 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11720 11721 // Now just recurse over the expression's children. 11722 CC = E->getExprLoc(); 11723 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11724 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11725 for (Stmt *SubStmt : E->children()) { 11726 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11727 if (!ChildExpr) 11728 continue; 11729 11730 if (IsLogicalAndOperator && 11731 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11732 // Ignore checking string literals that are in logical and operators. 11733 // This is a common pattern for asserts. 11734 continue; 11735 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit); 11736 } 11737 11738 if (BO && BO->isLogicalOp()) { 11739 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11740 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11741 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11742 11743 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11744 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11745 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11746 } 11747 11748 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11749 if (U->getOpcode() == UO_LNot) { 11750 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11751 } else if (U->getOpcode() != UO_AddrOf) { 11752 if (U->getSubExpr()->getType()->isAtomicType()) 11753 S.Diag(U->getSubExpr()->getBeginLoc(), 11754 diag::warn_atomic_implicit_seq_cst); 11755 } 11756 } 11757 } 11758 11759 /// Diagnose integer type and any valid implicit conversion to it. 11760 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11761 // Taking into account implicit conversions, 11762 // allow any integer. 11763 if (!E->getType()->isIntegerType()) { 11764 S.Diag(E->getBeginLoc(), 11765 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11766 return true; 11767 } 11768 // Potentially emit standard warnings for implicit conversions if enabled 11769 // using -Wconversion. 11770 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11771 return false; 11772 } 11773 11774 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11775 // Returns true when emitting a warning about taking the address of a reference. 11776 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11777 const PartialDiagnostic &PD) { 11778 E = E->IgnoreParenImpCasts(); 11779 11780 const FunctionDecl *FD = nullptr; 11781 11782 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11783 if (!DRE->getDecl()->getType()->isReferenceType()) 11784 return false; 11785 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11786 if (!M->getMemberDecl()->getType()->isReferenceType()) 11787 return false; 11788 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11789 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11790 return false; 11791 FD = Call->getDirectCallee(); 11792 } else { 11793 return false; 11794 } 11795 11796 SemaRef.Diag(E->getExprLoc(), PD); 11797 11798 // If possible, point to location of function. 11799 if (FD) { 11800 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11801 } 11802 11803 return true; 11804 } 11805 11806 // Returns true if the SourceLocation is expanded from any macro body. 11807 // Returns false if the SourceLocation is invalid, is from not in a macro 11808 // expansion, or is from expanded from a top-level macro argument. 11809 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11810 if (Loc.isInvalid()) 11811 return false; 11812 11813 while (Loc.isMacroID()) { 11814 if (SM.isMacroBodyExpansion(Loc)) 11815 return true; 11816 Loc = SM.getImmediateMacroCallerLoc(Loc); 11817 } 11818 11819 return false; 11820 } 11821 11822 /// Diagnose pointers that are always non-null. 11823 /// \param E the expression containing the pointer 11824 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11825 /// compared to a null pointer 11826 /// \param IsEqual True when the comparison is equal to a null pointer 11827 /// \param Range Extra SourceRange to highlight in the diagnostic 11828 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11829 Expr::NullPointerConstantKind NullKind, 11830 bool IsEqual, SourceRange Range) { 11831 if (!E) 11832 return; 11833 11834 // Don't warn inside macros. 11835 if (E->getExprLoc().isMacroID()) { 11836 const SourceManager &SM = getSourceManager(); 11837 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11838 IsInAnyMacroBody(SM, Range.getBegin())) 11839 return; 11840 } 11841 E = E->IgnoreImpCasts(); 11842 11843 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11844 11845 if (isa<CXXThisExpr>(E)) { 11846 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11847 : diag::warn_this_bool_conversion; 11848 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11849 return; 11850 } 11851 11852 bool IsAddressOf = false; 11853 11854 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11855 if (UO->getOpcode() != UO_AddrOf) 11856 return; 11857 IsAddressOf = true; 11858 E = UO->getSubExpr(); 11859 } 11860 11861 if (IsAddressOf) { 11862 unsigned DiagID = IsCompare 11863 ? diag::warn_address_of_reference_null_compare 11864 : diag::warn_address_of_reference_bool_conversion; 11865 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11866 << IsEqual; 11867 if (CheckForReference(*this, E, PD)) { 11868 return; 11869 } 11870 } 11871 11872 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11873 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11874 std::string Str; 11875 llvm::raw_string_ostream S(Str); 11876 E->printPretty(S, nullptr, getPrintingPolicy()); 11877 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11878 : diag::warn_cast_nonnull_to_bool; 11879 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11880 << E->getSourceRange() << Range << IsEqual; 11881 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11882 }; 11883 11884 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11885 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11886 if (auto *Callee = Call->getDirectCallee()) { 11887 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11888 ComplainAboutNonnullParamOrCall(A); 11889 return; 11890 } 11891 } 11892 } 11893 11894 // Expect to find a single Decl. Skip anything more complicated. 11895 ValueDecl *D = nullptr; 11896 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11897 D = R->getDecl(); 11898 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11899 D = M->getMemberDecl(); 11900 } 11901 11902 // Weak Decls can be null. 11903 if (!D || D->isWeak()) 11904 return; 11905 11906 // Check for parameter decl with nonnull attribute 11907 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11908 if (getCurFunction() && 11909 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11910 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11911 ComplainAboutNonnullParamOrCall(A); 11912 return; 11913 } 11914 11915 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11916 // Skip function template not specialized yet. 11917 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11918 return; 11919 auto ParamIter = llvm::find(FD->parameters(), PV); 11920 assert(ParamIter != FD->param_end()); 11921 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11922 11923 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11924 if (!NonNull->args_size()) { 11925 ComplainAboutNonnullParamOrCall(NonNull); 11926 return; 11927 } 11928 11929 for (const ParamIdx &ArgNo : NonNull->args()) { 11930 if (ArgNo.getASTIndex() == ParamNo) { 11931 ComplainAboutNonnullParamOrCall(NonNull); 11932 return; 11933 } 11934 } 11935 } 11936 } 11937 } 11938 } 11939 11940 QualType T = D->getType(); 11941 const bool IsArray = T->isArrayType(); 11942 const bool IsFunction = T->isFunctionType(); 11943 11944 // Address of function is used to silence the function warning. 11945 if (IsAddressOf && IsFunction) { 11946 return; 11947 } 11948 11949 // Found nothing. 11950 if (!IsAddressOf && !IsFunction && !IsArray) 11951 return; 11952 11953 // Pretty print the expression for the diagnostic. 11954 std::string Str; 11955 llvm::raw_string_ostream S(Str); 11956 E->printPretty(S, nullptr, getPrintingPolicy()); 11957 11958 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11959 : diag::warn_impcast_pointer_to_bool; 11960 enum { 11961 AddressOf, 11962 FunctionPointer, 11963 ArrayPointer 11964 } DiagType; 11965 if (IsAddressOf) 11966 DiagType = AddressOf; 11967 else if (IsFunction) 11968 DiagType = FunctionPointer; 11969 else if (IsArray) 11970 DiagType = ArrayPointer; 11971 else 11972 llvm_unreachable("Could not determine diagnostic."); 11973 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11974 << Range << IsEqual; 11975 11976 if (!IsFunction) 11977 return; 11978 11979 // Suggest '&' to silence the function warning. 11980 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11981 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11982 11983 // Check to see if '()' fixit should be emitted. 11984 QualType ReturnType; 11985 UnresolvedSet<4> NonTemplateOverloads; 11986 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11987 if (ReturnType.isNull()) 11988 return; 11989 11990 if (IsCompare) { 11991 // There are two cases here. If there is null constant, the only suggest 11992 // for a pointer return type. If the null is 0, then suggest if the return 11993 // type is a pointer or an integer type. 11994 if (!ReturnType->isPointerType()) { 11995 if (NullKind == Expr::NPCK_ZeroExpression || 11996 NullKind == Expr::NPCK_ZeroLiteral) { 11997 if (!ReturnType->isIntegerType()) 11998 return; 11999 } else { 12000 return; 12001 } 12002 } 12003 } else { // !IsCompare 12004 // For function to bool, only suggest if the function pointer has bool 12005 // return type. 12006 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12007 return; 12008 } 12009 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12010 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12011 } 12012 12013 /// Diagnoses "dangerous" implicit conversions within the given 12014 /// expression (which is a full expression). Implements -Wconversion 12015 /// and -Wsign-compare. 12016 /// 12017 /// \param CC the "context" location of the implicit conversion, i.e. 12018 /// the most location of the syntactic entity requiring the implicit 12019 /// conversion 12020 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12021 // Don't diagnose in unevaluated contexts. 12022 if (isUnevaluatedContext()) 12023 return; 12024 12025 // Don't diagnose for value- or type-dependent expressions. 12026 if (E->isTypeDependent() || E->isValueDependent()) 12027 return; 12028 12029 // Check for array bounds violations in cases where the check isn't triggered 12030 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12031 // ArraySubscriptExpr is on the RHS of a variable initialization. 12032 CheckArrayAccess(E); 12033 12034 // This is not the right CC for (e.g.) a variable initialization. 12035 AnalyzeImplicitConversions(*this, E, CC); 12036 } 12037 12038 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12039 /// Input argument E is a logical expression. 12040 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12041 ::CheckBoolLikeConversion(*this, E, CC); 12042 } 12043 12044 /// Diagnose when expression is an integer constant expression and its evaluation 12045 /// results in integer overflow 12046 void Sema::CheckForIntOverflow (Expr *E) { 12047 // Use a work list to deal with nested struct initializers. 12048 SmallVector<Expr *, 2> Exprs(1, E); 12049 12050 do { 12051 Expr *OriginalE = Exprs.pop_back_val(); 12052 Expr *E = OriginalE->IgnoreParenCasts(); 12053 12054 if (isa<BinaryOperator>(E)) { 12055 E->EvaluateForOverflow(Context); 12056 continue; 12057 } 12058 12059 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12060 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12061 else if (isa<ObjCBoxedExpr>(OriginalE)) 12062 E->EvaluateForOverflow(Context); 12063 else if (auto Call = dyn_cast<CallExpr>(E)) 12064 Exprs.append(Call->arg_begin(), Call->arg_end()); 12065 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12066 Exprs.append(Message->arg_begin(), Message->arg_end()); 12067 } while (!Exprs.empty()); 12068 } 12069 12070 namespace { 12071 12072 /// Visitor for expressions which looks for unsequenced operations on the 12073 /// same object. 12074 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 12075 using Base = EvaluatedExprVisitor<SequenceChecker>; 12076 12077 /// A tree of sequenced regions within an expression. Two regions are 12078 /// unsequenced if one is an ancestor or a descendent of the other. When we 12079 /// finish processing an expression with sequencing, such as a comma 12080 /// expression, we fold its tree nodes into its parent, since they are 12081 /// unsequenced with respect to nodes we will visit later. 12082 class SequenceTree { 12083 struct Value { 12084 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12085 unsigned Parent : 31; 12086 unsigned Merged : 1; 12087 }; 12088 SmallVector<Value, 8> Values; 12089 12090 public: 12091 /// A region within an expression which may be sequenced with respect 12092 /// to some other region. 12093 class Seq { 12094 friend class SequenceTree; 12095 12096 unsigned Index; 12097 12098 explicit Seq(unsigned N) : Index(N) {} 12099 12100 public: 12101 Seq() : Index(0) {} 12102 }; 12103 12104 SequenceTree() { Values.push_back(Value(0)); } 12105 Seq root() const { return Seq(0); } 12106 12107 /// Create a new sequence of operations, which is an unsequenced 12108 /// subset of \p Parent. This sequence of operations is sequenced with 12109 /// respect to other children of \p Parent. 12110 Seq allocate(Seq Parent) { 12111 Values.push_back(Value(Parent.Index)); 12112 return Seq(Values.size() - 1); 12113 } 12114 12115 /// Merge a sequence of operations into its parent. 12116 void merge(Seq S) { 12117 Values[S.Index].Merged = true; 12118 } 12119 12120 /// Determine whether two operations are unsequenced. This operation 12121 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12122 /// should have been merged into its parent as appropriate. 12123 bool isUnsequenced(Seq Cur, Seq Old) { 12124 unsigned C = representative(Cur.Index); 12125 unsigned Target = representative(Old.Index); 12126 while (C >= Target) { 12127 if (C == Target) 12128 return true; 12129 C = Values[C].Parent; 12130 } 12131 return false; 12132 } 12133 12134 private: 12135 /// Pick a representative for a sequence. 12136 unsigned representative(unsigned K) { 12137 if (Values[K].Merged) 12138 // Perform path compression as we go. 12139 return Values[K].Parent = representative(Values[K].Parent); 12140 return K; 12141 } 12142 }; 12143 12144 /// An object for which we can track unsequenced uses. 12145 using Object = NamedDecl *; 12146 12147 /// Different flavors of object usage which we track. We only track the 12148 /// least-sequenced usage of each kind. 12149 enum UsageKind { 12150 /// A read of an object. Multiple unsequenced reads are OK. 12151 UK_Use, 12152 12153 /// A modification of an object which is sequenced before the value 12154 /// computation of the expression, such as ++n in C++. 12155 UK_ModAsValue, 12156 12157 /// A modification of an object which is not sequenced before the value 12158 /// computation of the expression, such as n++. 12159 UK_ModAsSideEffect, 12160 12161 UK_Count = UK_ModAsSideEffect + 1 12162 }; 12163 12164 struct Usage { 12165 Expr *Use; 12166 SequenceTree::Seq Seq; 12167 12168 Usage() : Use(nullptr), Seq() {} 12169 }; 12170 12171 struct UsageInfo { 12172 Usage Uses[UK_Count]; 12173 12174 /// Have we issued a diagnostic for this variable already? 12175 bool Diagnosed; 12176 12177 UsageInfo() : Uses(), Diagnosed(false) {} 12178 }; 12179 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12180 12181 Sema &SemaRef; 12182 12183 /// Sequenced regions within the expression. 12184 SequenceTree Tree; 12185 12186 /// Declaration modifications and references which we have seen. 12187 UsageInfoMap UsageMap; 12188 12189 /// The region we are currently within. 12190 SequenceTree::Seq Region; 12191 12192 /// Filled in with declarations which were modified as a side-effect 12193 /// (that is, post-increment operations). 12194 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12195 12196 /// Expressions to check later. We defer checking these to reduce 12197 /// stack usage. 12198 SmallVectorImpl<Expr *> &WorkList; 12199 12200 /// RAII object wrapping the visitation of a sequenced subexpression of an 12201 /// expression. At the end of this process, the side-effects of the evaluation 12202 /// become sequenced with respect to the value computation of the result, so 12203 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12204 /// UK_ModAsValue. 12205 struct SequencedSubexpression { 12206 SequencedSubexpression(SequenceChecker &Self) 12207 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12208 Self.ModAsSideEffect = &ModAsSideEffect; 12209 } 12210 12211 ~SequencedSubexpression() { 12212 for (auto &M : llvm::reverse(ModAsSideEffect)) { 12213 UsageInfo &U = Self.UsageMap[M.first]; 12214 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 12215 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 12216 SideEffectUsage = M.second; 12217 } 12218 Self.ModAsSideEffect = OldModAsSideEffect; 12219 } 12220 12221 SequenceChecker &Self; 12222 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12223 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12224 }; 12225 12226 /// RAII object wrapping the visitation of a subexpression which we might 12227 /// choose to evaluate as a constant. If any subexpression is evaluated and 12228 /// found to be non-constant, this allows us to suppress the evaluation of 12229 /// the outer expression. 12230 class EvaluationTracker { 12231 public: 12232 EvaluationTracker(SequenceChecker &Self) 12233 : Self(Self), Prev(Self.EvalTracker) { 12234 Self.EvalTracker = this; 12235 } 12236 12237 ~EvaluationTracker() { 12238 Self.EvalTracker = Prev; 12239 if (Prev) 12240 Prev->EvalOK &= EvalOK; 12241 } 12242 12243 bool evaluate(const Expr *E, bool &Result) { 12244 if (!EvalOK || E->isValueDependent()) 12245 return false; 12246 EvalOK = E->EvaluateAsBooleanCondition( 12247 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12248 return EvalOK; 12249 } 12250 12251 private: 12252 SequenceChecker &Self; 12253 EvaluationTracker *Prev; 12254 bool EvalOK = true; 12255 } *EvalTracker = nullptr; 12256 12257 /// Find the object which is produced by the specified expression, 12258 /// if any. 12259 Object getObject(Expr *E, bool Mod) const { 12260 E = E->IgnoreParenCasts(); 12261 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12262 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12263 return getObject(UO->getSubExpr(), Mod); 12264 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12265 if (BO->getOpcode() == BO_Comma) 12266 return getObject(BO->getRHS(), Mod); 12267 if (Mod && BO->isAssignmentOp()) 12268 return getObject(BO->getLHS(), Mod); 12269 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12270 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12271 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12272 return ME->getMemberDecl(); 12273 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12274 // FIXME: If this is a reference, map through to its value. 12275 return DRE->getDecl(); 12276 return nullptr; 12277 } 12278 12279 /// Note that an object was modified or used by an expression. 12280 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 12281 Usage &U = UI.Uses[UK]; 12282 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 12283 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12284 ModAsSideEffect->push_back(std::make_pair(O, U)); 12285 U.Use = Ref; 12286 U.Seq = Region; 12287 } 12288 } 12289 12290 /// Check whether a modification or use conflicts with a prior usage. 12291 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 12292 bool IsModMod) { 12293 if (UI.Diagnosed) 12294 return; 12295 12296 const Usage &U = UI.Uses[OtherKind]; 12297 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 12298 return; 12299 12300 Expr *Mod = U.Use; 12301 Expr *ModOrUse = Ref; 12302 if (OtherKind == UK_Use) 12303 std::swap(Mod, ModOrUse); 12304 12305 SemaRef.DiagRuntimeBehavior( 12306 Mod->getExprLoc(), {Mod, ModOrUse}, 12307 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12308 : diag::warn_unsequenced_mod_use) 12309 << O << SourceRange(ModOrUse->getExprLoc())); 12310 UI.Diagnosed = true; 12311 } 12312 12313 void notePreUse(Object O, Expr *Use) { 12314 UsageInfo &U = UsageMap[O]; 12315 // Uses conflict with other modifications. 12316 checkUsage(O, U, Use, UK_ModAsValue, false); 12317 } 12318 12319 void notePostUse(Object O, Expr *Use) { 12320 UsageInfo &U = UsageMap[O]; 12321 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 12322 addUsage(U, O, Use, UK_Use); 12323 } 12324 12325 void notePreMod(Object O, Expr *Mod) { 12326 UsageInfo &U = UsageMap[O]; 12327 // Modifications conflict with other modifications and with uses. 12328 checkUsage(O, U, Mod, UK_ModAsValue, true); 12329 checkUsage(O, U, Mod, UK_Use, false); 12330 } 12331 12332 void notePostMod(Object O, Expr *Use, UsageKind UK) { 12333 UsageInfo &U = UsageMap[O]; 12334 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 12335 addUsage(U, O, Use, UK); 12336 } 12337 12338 public: 12339 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 12340 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12341 Visit(E); 12342 } 12343 12344 void VisitStmt(Stmt *S) { 12345 // Skip all statements which aren't expressions for now. 12346 } 12347 12348 void VisitExpr(Expr *E) { 12349 // By default, just recurse to evaluated subexpressions. 12350 Base::VisitStmt(E); 12351 } 12352 12353 void VisitCastExpr(CastExpr *E) { 12354 Object O = Object(); 12355 if (E->getCastKind() == CK_LValueToRValue) 12356 O = getObject(E->getSubExpr(), false); 12357 12358 if (O) 12359 notePreUse(O, E); 12360 VisitExpr(E); 12361 if (O) 12362 notePostUse(O, E); 12363 } 12364 12365 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) { 12366 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12367 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12368 SequenceTree::Seq OldRegion = Region; 12369 12370 { 12371 SequencedSubexpression SeqBefore(*this); 12372 Region = BeforeRegion; 12373 Visit(SequencedBefore); 12374 } 12375 12376 Region = AfterRegion; 12377 Visit(SequencedAfter); 12378 12379 Region = OldRegion; 12380 12381 Tree.merge(BeforeRegion); 12382 Tree.merge(AfterRegion); 12383 } 12384 12385 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) { 12386 // C++17 [expr.sub]p1: 12387 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12388 // expression E1 is sequenced before the expression E2. 12389 if (SemaRef.getLangOpts().CPlusPlus17) 12390 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12391 else 12392 Base::VisitStmt(ASE); 12393 } 12394 12395 void VisitBinComma(BinaryOperator *BO) { 12396 // C++11 [expr.comma]p1: 12397 // Every value computation and side effect associated with the left 12398 // expression is sequenced before every value computation and side 12399 // effect associated with the right expression. 12400 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12401 } 12402 12403 void VisitBinAssign(BinaryOperator *BO) { 12404 // The modification is sequenced after the value computation of the LHS 12405 // and RHS, so check it before inspecting the operands and update the 12406 // map afterwards. 12407 Object O = getObject(BO->getLHS(), true); 12408 if (!O) 12409 return VisitExpr(BO); 12410 12411 notePreMod(O, BO); 12412 12413 // C++11 [expr.ass]p7: 12414 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 12415 // only once. 12416 // 12417 // Therefore, for a compound assignment operator, O is considered used 12418 // everywhere except within the evaluation of E1 itself. 12419 if (isa<CompoundAssignOperator>(BO)) 12420 notePreUse(O, BO); 12421 12422 Visit(BO->getLHS()); 12423 12424 if (isa<CompoundAssignOperator>(BO)) 12425 notePostUse(O, BO); 12426 12427 Visit(BO->getRHS()); 12428 12429 // C++11 [expr.ass]p1: 12430 // the assignment is sequenced [...] before the value computation of the 12431 // assignment expression. 12432 // C11 6.5.16/3 has no such rule. 12433 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12434 : UK_ModAsSideEffect); 12435 } 12436 12437 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 12438 VisitBinAssign(CAO); 12439 } 12440 12441 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12442 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12443 void VisitUnaryPreIncDec(UnaryOperator *UO) { 12444 Object O = getObject(UO->getSubExpr(), true); 12445 if (!O) 12446 return VisitExpr(UO); 12447 12448 notePreMod(O, UO); 12449 Visit(UO->getSubExpr()); 12450 // C++11 [expr.pre.incr]p1: 12451 // the expression ++x is equivalent to x+=1 12452 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12453 : UK_ModAsSideEffect); 12454 } 12455 12456 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12457 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12458 void VisitUnaryPostIncDec(UnaryOperator *UO) { 12459 Object O = getObject(UO->getSubExpr(), true); 12460 if (!O) 12461 return VisitExpr(UO); 12462 12463 notePreMod(O, UO); 12464 Visit(UO->getSubExpr()); 12465 notePostMod(O, UO, UK_ModAsSideEffect); 12466 } 12467 12468 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 12469 void VisitBinLOr(BinaryOperator *BO) { 12470 // The side-effects of the LHS of an '&&' are sequenced before the 12471 // value computation of the RHS, and hence before the value computation 12472 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 12473 // as if they were unconditionally sequenced. 12474 EvaluationTracker Eval(*this); 12475 { 12476 SequencedSubexpression Sequenced(*this); 12477 Visit(BO->getLHS()); 12478 } 12479 12480 bool Result; 12481 if (Eval.evaluate(BO->getLHS(), Result)) { 12482 if (!Result) 12483 Visit(BO->getRHS()); 12484 } else { 12485 // Check for unsequenced operations in the RHS, treating it as an 12486 // entirely separate evaluation. 12487 // 12488 // FIXME: If there are operations in the RHS which are unsequenced 12489 // with respect to operations outside the RHS, and those operations 12490 // are unconditionally evaluated, diagnose them. 12491 WorkList.push_back(BO->getRHS()); 12492 } 12493 } 12494 void VisitBinLAnd(BinaryOperator *BO) { 12495 EvaluationTracker Eval(*this); 12496 { 12497 SequencedSubexpression Sequenced(*this); 12498 Visit(BO->getLHS()); 12499 } 12500 12501 bool Result; 12502 if (Eval.evaluate(BO->getLHS(), Result)) { 12503 if (Result) 12504 Visit(BO->getRHS()); 12505 } else { 12506 WorkList.push_back(BO->getRHS()); 12507 } 12508 } 12509 12510 // Only visit the condition, unless we can be sure which subexpression will 12511 // be chosen. 12512 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 12513 EvaluationTracker Eval(*this); 12514 { 12515 SequencedSubexpression Sequenced(*this); 12516 Visit(CO->getCond()); 12517 } 12518 12519 bool Result; 12520 if (Eval.evaluate(CO->getCond(), Result)) 12521 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 12522 else { 12523 WorkList.push_back(CO->getTrueExpr()); 12524 WorkList.push_back(CO->getFalseExpr()); 12525 } 12526 } 12527 12528 void VisitCallExpr(CallExpr *CE) { 12529 // C++11 [intro.execution]p15: 12530 // When calling a function [...], every value computation and side effect 12531 // associated with any argument expression, or with the postfix expression 12532 // designating the called function, is sequenced before execution of every 12533 // expression or statement in the body of the function [and thus before 12534 // the value computation of its result]. 12535 SequencedSubexpression Sequenced(*this); 12536 Base::VisitCallExpr(CE); 12537 12538 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12539 } 12540 12541 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 12542 // This is a call, so all subexpressions are sequenced before the result. 12543 SequencedSubexpression Sequenced(*this); 12544 12545 if (!CCE->isListInitialization()) 12546 return VisitExpr(CCE); 12547 12548 // In C++11, list initializations are sequenced. 12549 SmallVector<SequenceTree::Seq, 32> Elts; 12550 SequenceTree::Seq Parent = Region; 12551 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 12552 E = CCE->arg_end(); 12553 I != E; ++I) { 12554 Region = Tree.allocate(Parent); 12555 Elts.push_back(Region); 12556 Visit(*I); 12557 } 12558 12559 // Forget that the initializers are sequenced. 12560 Region = Parent; 12561 for (unsigned I = 0; I < Elts.size(); ++I) 12562 Tree.merge(Elts[I]); 12563 } 12564 12565 void VisitInitListExpr(InitListExpr *ILE) { 12566 if (!SemaRef.getLangOpts().CPlusPlus11) 12567 return VisitExpr(ILE); 12568 12569 // In C++11, list initializations are sequenced. 12570 SmallVector<SequenceTree::Seq, 32> Elts; 12571 SequenceTree::Seq Parent = Region; 12572 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12573 Expr *E = ILE->getInit(I); 12574 if (!E) continue; 12575 Region = Tree.allocate(Parent); 12576 Elts.push_back(Region); 12577 Visit(E); 12578 } 12579 12580 // Forget that the initializers are sequenced. 12581 Region = Parent; 12582 for (unsigned I = 0; I < Elts.size(); ++I) 12583 Tree.merge(Elts[I]); 12584 } 12585 }; 12586 12587 } // namespace 12588 12589 void Sema::CheckUnsequencedOperations(Expr *E) { 12590 SmallVector<Expr *, 8> WorkList; 12591 WorkList.push_back(E); 12592 while (!WorkList.empty()) { 12593 Expr *Item = WorkList.pop_back_val(); 12594 SequenceChecker(*this, Item, WorkList); 12595 } 12596 } 12597 12598 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12599 bool IsConstexpr) { 12600 llvm::SaveAndRestore<bool> ConstantContext( 12601 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 12602 CheckImplicitConversions(E, CheckLoc); 12603 if (!E->isInstantiationDependent()) 12604 CheckUnsequencedOperations(E); 12605 if (!IsConstexpr && !E->isValueDependent()) 12606 CheckForIntOverflow(E); 12607 DiagnoseMisalignedMembers(); 12608 } 12609 12610 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12611 FieldDecl *BitField, 12612 Expr *Init) { 12613 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12614 } 12615 12616 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12617 SourceLocation Loc) { 12618 if (!PType->isVariablyModifiedType()) 12619 return; 12620 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12621 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12622 return; 12623 } 12624 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12625 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12626 return; 12627 } 12628 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12629 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12630 return; 12631 } 12632 12633 const ArrayType *AT = S.Context.getAsArrayType(PType); 12634 if (!AT) 12635 return; 12636 12637 if (AT->getSizeModifier() != ArrayType::Star) { 12638 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12639 return; 12640 } 12641 12642 S.Diag(Loc, diag::err_array_star_in_function_definition); 12643 } 12644 12645 /// CheckParmsForFunctionDef - Check that the parameters of the given 12646 /// function are appropriate for the definition of a function. This 12647 /// takes care of any checks that cannot be performed on the 12648 /// declaration itself, e.g., that the types of each of the function 12649 /// parameters are complete. 12650 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12651 bool CheckParameterNames) { 12652 bool HasInvalidParm = false; 12653 for (ParmVarDecl *Param : Parameters) { 12654 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12655 // function declarator that is part of a function definition of 12656 // that function shall not have incomplete type. 12657 // 12658 // This is also C++ [dcl.fct]p6. 12659 if (!Param->isInvalidDecl() && 12660 RequireCompleteType(Param->getLocation(), Param->getType(), 12661 diag::err_typecheck_decl_incomplete_type)) { 12662 Param->setInvalidDecl(); 12663 HasInvalidParm = true; 12664 } 12665 12666 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12667 // declaration of each parameter shall include an identifier. 12668 if (CheckParameterNames && 12669 Param->getIdentifier() == nullptr && 12670 !Param->isImplicit() && 12671 !getLangOpts().CPlusPlus) 12672 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12673 12674 // C99 6.7.5.3p12: 12675 // If the function declarator is not part of a definition of that 12676 // function, parameters may have incomplete type and may use the [*] 12677 // notation in their sequences of declarator specifiers to specify 12678 // variable length array types. 12679 QualType PType = Param->getOriginalType(); 12680 // FIXME: This diagnostic should point the '[*]' if source-location 12681 // information is added for it. 12682 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12683 12684 // If the parameter is a c++ class type and it has to be destructed in the 12685 // callee function, declare the destructor so that it can be called by the 12686 // callee function. Do not perform any direct access check on the dtor here. 12687 if (!Param->isInvalidDecl()) { 12688 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12689 if (!ClassDecl->isInvalidDecl() && 12690 !ClassDecl->hasIrrelevantDestructor() && 12691 !ClassDecl->isDependentContext() && 12692 ClassDecl->isParamDestroyedInCallee()) { 12693 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12694 MarkFunctionReferenced(Param->getLocation(), Destructor); 12695 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12696 } 12697 } 12698 } 12699 12700 // Parameters with the pass_object_size attribute only need to be marked 12701 // constant at function definitions. Because we lack information about 12702 // whether we're on a declaration or definition when we're instantiating the 12703 // attribute, we need to check for constness here. 12704 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12705 if (!Param->getType().isConstQualified()) 12706 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12707 << Attr->getSpelling() << 1; 12708 12709 // Check for parameter names shadowing fields from the class. 12710 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 12711 // The owning context for the parameter should be the function, but we 12712 // want to see if this function's declaration context is a record. 12713 DeclContext *DC = Param->getDeclContext(); 12714 if (DC && DC->isFunctionOrMethod()) { 12715 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 12716 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 12717 RD, /*DeclIsField*/ false); 12718 } 12719 } 12720 } 12721 12722 return HasInvalidParm; 12723 } 12724 12725 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12726 /// or MemberExpr. 12727 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12728 ASTContext &Context) { 12729 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12730 return Context.getDeclAlign(DRE->getDecl()); 12731 12732 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12733 return Context.getDeclAlign(ME->getMemberDecl()); 12734 12735 return TypeAlign; 12736 } 12737 12738 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12739 /// pointer cast increases the alignment requirements. 12740 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12741 // This is actually a lot of work to potentially be doing on every 12742 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12743 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12744 return; 12745 12746 // Ignore dependent types. 12747 if (T->isDependentType() || Op->getType()->isDependentType()) 12748 return; 12749 12750 // Require that the destination be a pointer type. 12751 const PointerType *DestPtr = T->getAs<PointerType>(); 12752 if (!DestPtr) return; 12753 12754 // If the destination has alignment 1, we're done. 12755 QualType DestPointee = DestPtr->getPointeeType(); 12756 if (DestPointee->isIncompleteType()) return; 12757 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12758 if (DestAlign.isOne()) return; 12759 12760 // Require that the source be a pointer type. 12761 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12762 if (!SrcPtr) return; 12763 QualType SrcPointee = SrcPtr->getPointeeType(); 12764 12765 // Whitelist casts from cv void*. We already implicitly 12766 // whitelisted casts to cv void*, since they have alignment 1. 12767 // Also whitelist casts involving incomplete types, which implicitly 12768 // includes 'void'. 12769 if (SrcPointee->isIncompleteType()) return; 12770 12771 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12772 12773 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12774 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12775 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12776 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12777 if (UO->getOpcode() == UO_AddrOf) 12778 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12779 } 12780 12781 if (SrcAlign >= DestAlign) return; 12782 12783 Diag(TRange.getBegin(), diag::warn_cast_align) 12784 << Op->getType() << T 12785 << static_cast<unsigned>(SrcAlign.getQuantity()) 12786 << static_cast<unsigned>(DestAlign.getQuantity()) 12787 << TRange << Op->getSourceRange(); 12788 } 12789 12790 /// Check whether this array fits the idiom of a size-one tail padded 12791 /// array member of a struct. 12792 /// 12793 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12794 /// commonly used to emulate flexible arrays in C89 code. 12795 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12796 const NamedDecl *ND) { 12797 if (Size != 1 || !ND) return false; 12798 12799 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12800 if (!FD) return false; 12801 12802 // Don't consider sizes resulting from macro expansions or template argument 12803 // substitution to form C89 tail-padded arrays. 12804 12805 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12806 while (TInfo) { 12807 TypeLoc TL = TInfo->getTypeLoc(); 12808 // Look through typedefs. 12809 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12810 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12811 TInfo = TDL->getTypeSourceInfo(); 12812 continue; 12813 } 12814 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12815 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12816 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12817 return false; 12818 } 12819 break; 12820 } 12821 12822 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12823 if (!RD) return false; 12824 if (RD->isUnion()) return false; 12825 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12826 if (!CRD->isStandardLayout()) return false; 12827 } 12828 12829 // See if this is the last field decl in the record. 12830 const Decl *D = FD; 12831 while ((D = D->getNextDeclInContext())) 12832 if (isa<FieldDecl>(D)) 12833 return false; 12834 return true; 12835 } 12836 12837 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12838 const ArraySubscriptExpr *ASE, 12839 bool AllowOnePastEnd, bool IndexNegated) { 12840 // Already diagnosed by the constant evaluator. 12841 if (isConstantEvaluated()) 12842 return; 12843 12844 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12845 if (IndexExpr->isValueDependent()) 12846 return; 12847 12848 const Type *EffectiveType = 12849 BaseExpr->getType()->getPointeeOrArrayElementType(); 12850 BaseExpr = BaseExpr->IgnoreParenCasts(); 12851 const ConstantArrayType *ArrayTy = 12852 Context.getAsConstantArrayType(BaseExpr->getType()); 12853 12854 if (!ArrayTy) 12855 return; 12856 12857 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 12858 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 12859 return; 12860 12861 Expr::EvalResult Result; 12862 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 12863 return; 12864 12865 llvm::APSInt index = Result.Val.getInt(); 12866 if (IndexNegated) 12867 index = -index; 12868 12869 const NamedDecl *ND = nullptr; 12870 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12871 ND = DRE->getDecl(); 12872 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12873 ND = ME->getMemberDecl(); 12874 12875 if (index.isUnsigned() || !index.isNegative()) { 12876 // It is possible that the type of the base expression after 12877 // IgnoreParenCasts is incomplete, even though the type of the base 12878 // expression before IgnoreParenCasts is complete (see PR39746 for an 12879 // example). In this case we have no information about whether the array 12880 // access exceeds the array bounds. However we can still diagnose an array 12881 // access which precedes the array bounds. 12882 if (BaseType->isIncompleteType()) 12883 return; 12884 12885 llvm::APInt size = ArrayTy->getSize(); 12886 if (!size.isStrictlyPositive()) 12887 return; 12888 12889 if (BaseType != EffectiveType) { 12890 // Make sure we're comparing apples to apples when comparing index to size 12891 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12892 uint64_t array_typesize = Context.getTypeSize(BaseType); 12893 // Handle ptrarith_typesize being zero, such as when casting to void* 12894 if (!ptrarith_typesize) ptrarith_typesize = 1; 12895 if (ptrarith_typesize != array_typesize) { 12896 // There's a cast to a different size type involved 12897 uint64_t ratio = array_typesize / ptrarith_typesize; 12898 // TODO: Be smarter about handling cases where array_typesize is not a 12899 // multiple of ptrarith_typesize 12900 if (ptrarith_typesize * ratio == array_typesize) 12901 size *= llvm::APInt(size.getBitWidth(), ratio); 12902 } 12903 } 12904 12905 if (size.getBitWidth() > index.getBitWidth()) 12906 index = index.zext(size.getBitWidth()); 12907 else if (size.getBitWidth() < index.getBitWidth()) 12908 size = size.zext(index.getBitWidth()); 12909 12910 // For array subscripting the index must be less than size, but for pointer 12911 // arithmetic also allow the index (offset) to be equal to size since 12912 // computing the next address after the end of the array is legal and 12913 // commonly done e.g. in C++ iterators and range-based for loops. 12914 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12915 return; 12916 12917 // Also don't warn for arrays of size 1 which are members of some 12918 // structure. These are often used to approximate flexible arrays in C89 12919 // code. 12920 if (IsTailPaddedMemberArray(*this, size, ND)) 12921 return; 12922 12923 // Suppress the warning if the subscript expression (as identified by the 12924 // ']' location) and the index expression are both from macro expansions 12925 // within a system header. 12926 if (ASE) { 12927 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12928 ASE->getRBracketLoc()); 12929 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12930 SourceLocation IndexLoc = 12931 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12932 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12933 return; 12934 } 12935 } 12936 12937 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12938 if (ASE) 12939 DiagID = diag::warn_array_index_exceeds_bounds; 12940 12941 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12942 PDiag(DiagID) << index.toString(10, true) 12943 << size.toString(10, true) 12944 << (unsigned)size.getLimitedValue(~0U) 12945 << IndexExpr->getSourceRange()); 12946 } else { 12947 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12948 if (!ASE) { 12949 DiagID = diag::warn_ptr_arith_precedes_bounds; 12950 if (index.isNegative()) index = -index; 12951 } 12952 12953 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12954 PDiag(DiagID) << index.toString(10, true) 12955 << IndexExpr->getSourceRange()); 12956 } 12957 12958 if (!ND) { 12959 // Try harder to find a NamedDecl to point at in the note. 12960 while (const ArraySubscriptExpr *ASE = 12961 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12962 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12963 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12964 ND = DRE->getDecl(); 12965 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12966 ND = ME->getMemberDecl(); 12967 } 12968 12969 if (ND) 12970 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12971 PDiag(diag::note_array_index_out_of_bounds) 12972 << ND->getDeclName()); 12973 } 12974 12975 void Sema::CheckArrayAccess(const Expr *expr) { 12976 int AllowOnePastEnd = 0; 12977 while (expr) { 12978 expr = expr->IgnoreParenImpCasts(); 12979 switch (expr->getStmtClass()) { 12980 case Stmt::ArraySubscriptExprClass: { 12981 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12982 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12983 AllowOnePastEnd > 0); 12984 expr = ASE->getBase(); 12985 break; 12986 } 12987 case Stmt::MemberExprClass: { 12988 expr = cast<MemberExpr>(expr)->getBase(); 12989 break; 12990 } 12991 case Stmt::OMPArraySectionExprClass: { 12992 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12993 if (ASE->getLowerBound()) 12994 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12995 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12996 return; 12997 } 12998 case Stmt::UnaryOperatorClass: { 12999 // Only unwrap the * and & unary operators 13000 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13001 expr = UO->getSubExpr(); 13002 switch (UO->getOpcode()) { 13003 case UO_AddrOf: 13004 AllowOnePastEnd++; 13005 break; 13006 case UO_Deref: 13007 AllowOnePastEnd--; 13008 break; 13009 default: 13010 return; 13011 } 13012 break; 13013 } 13014 case Stmt::ConditionalOperatorClass: { 13015 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13016 if (const Expr *lhs = cond->getLHS()) 13017 CheckArrayAccess(lhs); 13018 if (const Expr *rhs = cond->getRHS()) 13019 CheckArrayAccess(rhs); 13020 return; 13021 } 13022 case Stmt::CXXOperatorCallExprClass: { 13023 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13024 for (const auto *Arg : OCE->arguments()) 13025 CheckArrayAccess(Arg); 13026 return; 13027 } 13028 default: 13029 return; 13030 } 13031 } 13032 } 13033 13034 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13035 13036 namespace { 13037 13038 struct RetainCycleOwner { 13039 VarDecl *Variable = nullptr; 13040 SourceRange Range; 13041 SourceLocation Loc; 13042 bool Indirect = false; 13043 13044 RetainCycleOwner() = default; 13045 13046 void setLocsFrom(Expr *e) { 13047 Loc = e->getExprLoc(); 13048 Range = e->getSourceRange(); 13049 } 13050 }; 13051 13052 } // namespace 13053 13054 /// Consider whether capturing the given variable can possibly lead to 13055 /// a retain cycle. 13056 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13057 // In ARC, it's captured strongly iff the variable has __strong 13058 // lifetime. In MRR, it's captured strongly if the variable is 13059 // __block and has an appropriate type. 13060 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13061 return false; 13062 13063 owner.Variable = var; 13064 if (ref) 13065 owner.setLocsFrom(ref); 13066 return true; 13067 } 13068 13069 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13070 while (true) { 13071 e = e->IgnoreParens(); 13072 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13073 switch (cast->getCastKind()) { 13074 case CK_BitCast: 13075 case CK_LValueBitCast: 13076 case CK_LValueToRValue: 13077 case CK_ARCReclaimReturnedObject: 13078 e = cast->getSubExpr(); 13079 continue; 13080 13081 default: 13082 return false; 13083 } 13084 } 13085 13086 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13087 ObjCIvarDecl *ivar = ref->getDecl(); 13088 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13089 return false; 13090 13091 // Try to find a retain cycle in the base. 13092 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13093 return false; 13094 13095 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13096 owner.Indirect = true; 13097 return true; 13098 } 13099 13100 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13101 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13102 if (!var) return false; 13103 return considerVariable(var, ref, owner); 13104 } 13105 13106 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13107 if (member->isArrow()) return false; 13108 13109 // Don't count this as an indirect ownership. 13110 e = member->getBase(); 13111 continue; 13112 } 13113 13114 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13115 // Only pay attention to pseudo-objects on property references. 13116 ObjCPropertyRefExpr *pre 13117 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13118 ->IgnoreParens()); 13119 if (!pre) return false; 13120 if (pre->isImplicitProperty()) return false; 13121 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13122 if (!property->isRetaining() && 13123 !(property->getPropertyIvarDecl() && 13124 property->getPropertyIvarDecl()->getType() 13125 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13126 return false; 13127 13128 owner.Indirect = true; 13129 if (pre->isSuperReceiver()) { 13130 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13131 if (!owner.Variable) 13132 return false; 13133 owner.Loc = pre->getLocation(); 13134 owner.Range = pre->getSourceRange(); 13135 return true; 13136 } 13137 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13138 ->getSourceExpr()); 13139 continue; 13140 } 13141 13142 // Array ivars? 13143 13144 return false; 13145 } 13146 } 13147 13148 namespace { 13149 13150 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13151 ASTContext &Context; 13152 VarDecl *Variable; 13153 Expr *Capturer = nullptr; 13154 bool VarWillBeReased = false; 13155 13156 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13157 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13158 Context(Context), Variable(variable) {} 13159 13160 void VisitDeclRefExpr(DeclRefExpr *ref) { 13161 if (ref->getDecl() == Variable && !Capturer) 13162 Capturer = ref; 13163 } 13164 13165 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13166 if (Capturer) return; 13167 Visit(ref->getBase()); 13168 if (Capturer && ref->isFreeIvar()) 13169 Capturer = ref; 13170 } 13171 13172 void VisitBlockExpr(BlockExpr *block) { 13173 // Look inside nested blocks 13174 if (block->getBlockDecl()->capturesVariable(Variable)) 13175 Visit(block->getBlockDecl()->getBody()); 13176 } 13177 13178 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13179 if (Capturer) return; 13180 if (OVE->getSourceExpr()) 13181 Visit(OVE->getSourceExpr()); 13182 } 13183 13184 void VisitBinaryOperator(BinaryOperator *BinOp) { 13185 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13186 return; 13187 Expr *LHS = BinOp->getLHS(); 13188 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13189 if (DRE->getDecl() != Variable) 13190 return; 13191 if (Expr *RHS = BinOp->getRHS()) { 13192 RHS = RHS->IgnoreParenCasts(); 13193 llvm::APSInt Value; 13194 VarWillBeReased = 13195 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13196 } 13197 } 13198 } 13199 }; 13200 13201 } // namespace 13202 13203 /// Check whether the given argument is a block which captures a 13204 /// variable. 13205 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13206 assert(owner.Variable && owner.Loc.isValid()); 13207 13208 e = e->IgnoreParenCasts(); 13209 13210 // Look through [^{...} copy] and Block_copy(^{...}). 13211 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13212 Selector Cmd = ME->getSelector(); 13213 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13214 e = ME->getInstanceReceiver(); 13215 if (!e) 13216 return nullptr; 13217 e = e->IgnoreParenCasts(); 13218 } 13219 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13220 if (CE->getNumArgs() == 1) { 13221 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13222 if (Fn) { 13223 const IdentifierInfo *FnI = Fn->getIdentifier(); 13224 if (FnI && FnI->isStr("_Block_copy")) { 13225 e = CE->getArg(0)->IgnoreParenCasts(); 13226 } 13227 } 13228 } 13229 } 13230 13231 BlockExpr *block = dyn_cast<BlockExpr>(e); 13232 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13233 return nullptr; 13234 13235 FindCaptureVisitor visitor(S.Context, owner.Variable); 13236 visitor.Visit(block->getBlockDecl()->getBody()); 13237 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13238 } 13239 13240 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13241 RetainCycleOwner &owner) { 13242 assert(capturer); 13243 assert(owner.Variable && owner.Loc.isValid()); 13244 13245 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13246 << owner.Variable << capturer->getSourceRange(); 13247 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13248 << owner.Indirect << owner.Range; 13249 } 13250 13251 /// Check for a keyword selector that starts with the word 'add' or 13252 /// 'set'. 13253 static bool isSetterLikeSelector(Selector sel) { 13254 if (sel.isUnarySelector()) return false; 13255 13256 StringRef str = sel.getNameForSlot(0); 13257 while (!str.empty() && str.front() == '_') str = str.substr(1); 13258 if (str.startswith("set")) 13259 str = str.substr(3); 13260 else if (str.startswith("add")) { 13261 // Specially whitelist 'addOperationWithBlock:'. 13262 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13263 return false; 13264 str = str.substr(3); 13265 } 13266 else 13267 return false; 13268 13269 if (str.empty()) return true; 13270 return !isLowercase(str.front()); 13271 } 13272 13273 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13274 ObjCMessageExpr *Message) { 13275 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13276 Message->getReceiverInterface(), 13277 NSAPI::ClassId_NSMutableArray); 13278 if (!IsMutableArray) { 13279 return None; 13280 } 13281 13282 Selector Sel = Message->getSelector(); 13283 13284 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13285 S.NSAPIObj->getNSArrayMethodKind(Sel); 13286 if (!MKOpt) { 13287 return None; 13288 } 13289 13290 NSAPI::NSArrayMethodKind MK = *MKOpt; 13291 13292 switch (MK) { 13293 case NSAPI::NSMutableArr_addObject: 13294 case NSAPI::NSMutableArr_insertObjectAtIndex: 13295 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13296 return 0; 13297 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13298 return 1; 13299 13300 default: 13301 return None; 13302 } 13303 13304 return None; 13305 } 13306 13307 static 13308 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13309 ObjCMessageExpr *Message) { 13310 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13311 Message->getReceiverInterface(), 13312 NSAPI::ClassId_NSMutableDictionary); 13313 if (!IsMutableDictionary) { 13314 return None; 13315 } 13316 13317 Selector Sel = Message->getSelector(); 13318 13319 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13320 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13321 if (!MKOpt) { 13322 return None; 13323 } 13324 13325 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13326 13327 switch (MK) { 13328 case NSAPI::NSMutableDict_setObjectForKey: 13329 case NSAPI::NSMutableDict_setValueForKey: 13330 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13331 return 0; 13332 13333 default: 13334 return None; 13335 } 13336 13337 return None; 13338 } 13339 13340 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13341 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13342 Message->getReceiverInterface(), 13343 NSAPI::ClassId_NSMutableSet); 13344 13345 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13346 Message->getReceiverInterface(), 13347 NSAPI::ClassId_NSMutableOrderedSet); 13348 if (!IsMutableSet && !IsMutableOrderedSet) { 13349 return None; 13350 } 13351 13352 Selector Sel = Message->getSelector(); 13353 13354 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13355 if (!MKOpt) { 13356 return None; 13357 } 13358 13359 NSAPI::NSSetMethodKind MK = *MKOpt; 13360 13361 switch (MK) { 13362 case NSAPI::NSMutableSet_addObject: 13363 case NSAPI::NSOrderedSet_setObjectAtIndex: 13364 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13365 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13366 return 0; 13367 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13368 return 1; 13369 } 13370 13371 return None; 13372 } 13373 13374 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13375 if (!Message->isInstanceMessage()) { 13376 return; 13377 } 13378 13379 Optional<int> ArgOpt; 13380 13381 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13382 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13383 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13384 return; 13385 } 13386 13387 int ArgIndex = *ArgOpt; 13388 13389 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13390 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13391 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13392 } 13393 13394 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13395 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13396 if (ArgRE->isObjCSelfExpr()) { 13397 Diag(Message->getSourceRange().getBegin(), 13398 diag::warn_objc_circular_container) 13399 << ArgRE->getDecl() << StringRef("'super'"); 13400 } 13401 } 13402 } else { 13403 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13404 13405 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13406 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13407 } 13408 13409 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13410 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13411 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13412 ValueDecl *Decl = ReceiverRE->getDecl(); 13413 Diag(Message->getSourceRange().getBegin(), 13414 diag::warn_objc_circular_container) 13415 << Decl << Decl; 13416 if (!ArgRE->isObjCSelfExpr()) { 13417 Diag(Decl->getLocation(), 13418 diag::note_objc_circular_container_declared_here) 13419 << Decl; 13420 } 13421 } 13422 } 13423 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13424 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13425 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13426 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13427 Diag(Message->getSourceRange().getBegin(), 13428 diag::warn_objc_circular_container) 13429 << Decl << Decl; 13430 Diag(Decl->getLocation(), 13431 diag::note_objc_circular_container_declared_here) 13432 << Decl; 13433 } 13434 } 13435 } 13436 } 13437 } 13438 13439 /// Check a message send to see if it's likely to cause a retain cycle. 13440 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13441 // Only check instance methods whose selector looks like a setter. 13442 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13443 return; 13444 13445 // Try to find a variable that the receiver is strongly owned by. 13446 RetainCycleOwner owner; 13447 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13448 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13449 return; 13450 } else { 13451 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13452 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13453 owner.Loc = msg->getSuperLoc(); 13454 owner.Range = msg->getSuperLoc(); 13455 } 13456 13457 // Check whether the receiver is captured by any of the arguments. 13458 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13459 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13460 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13461 // noescape blocks should not be retained by the method. 13462 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13463 continue; 13464 return diagnoseRetainCycle(*this, capturer, owner); 13465 } 13466 } 13467 } 13468 13469 /// Check a property assign to see if it's likely to cause a retain cycle. 13470 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13471 RetainCycleOwner owner; 13472 if (!findRetainCycleOwner(*this, receiver, owner)) 13473 return; 13474 13475 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13476 diagnoseRetainCycle(*this, capturer, owner); 13477 } 13478 13479 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13480 RetainCycleOwner Owner; 13481 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13482 return; 13483 13484 // Because we don't have an expression for the variable, we have to set the 13485 // location explicitly here. 13486 Owner.Loc = Var->getLocation(); 13487 Owner.Range = Var->getSourceRange(); 13488 13489 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13490 diagnoseRetainCycle(*this, Capturer, Owner); 13491 } 13492 13493 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13494 Expr *RHS, bool isProperty) { 13495 // Check if RHS is an Objective-C object literal, which also can get 13496 // immediately zapped in a weak reference. Note that we explicitly 13497 // allow ObjCStringLiterals, since those are designed to never really die. 13498 RHS = RHS->IgnoreParenImpCasts(); 13499 13500 // This enum needs to match with the 'select' in 13501 // warn_objc_arc_literal_assign (off-by-1). 13502 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13503 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13504 return false; 13505 13506 S.Diag(Loc, diag::warn_arc_literal_assign) 13507 << (unsigned) Kind 13508 << (isProperty ? 0 : 1) 13509 << RHS->getSourceRange(); 13510 13511 return true; 13512 } 13513 13514 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13515 Qualifiers::ObjCLifetime LT, 13516 Expr *RHS, bool isProperty) { 13517 // Strip off any implicit cast added to get to the one ARC-specific. 13518 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13519 if (cast->getCastKind() == CK_ARCConsumeObject) { 13520 S.Diag(Loc, diag::warn_arc_retained_assign) 13521 << (LT == Qualifiers::OCL_ExplicitNone) 13522 << (isProperty ? 0 : 1) 13523 << RHS->getSourceRange(); 13524 return true; 13525 } 13526 RHS = cast->getSubExpr(); 13527 } 13528 13529 if (LT == Qualifiers::OCL_Weak && 13530 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13531 return true; 13532 13533 return false; 13534 } 13535 13536 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13537 QualType LHS, Expr *RHS) { 13538 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13539 13540 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13541 return false; 13542 13543 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13544 return true; 13545 13546 return false; 13547 } 13548 13549 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13550 Expr *LHS, Expr *RHS) { 13551 QualType LHSType; 13552 // PropertyRef on LHS type need be directly obtained from 13553 // its declaration as it has a PseudoType. 13554 ObjCPropertyRefExpr *PRE 13555 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13556 if (PRE && !PRE->isImplicitProperty()) { 13557 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13558 if (PD) 13559 LHSType = PD->getType(); 13560 } 13561 13562 if (LHSType.isNull()) 13563 LHSType = LHS->getType(); 13564 13565 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13566 13567 if (LT == Qualifiers::OCL_Weak) { 13568 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13569 getCurFunction()->markSafeWeakUse(LHS); 13570 } 13571 13572 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13573 return; 13574 13575 // FIXME. Check for other life times. 13576 if (LT != Qualifiers::OCL_None) 13577 return; 13578 13579 if (PRE) { 13580 if (PRE->isImplicitProperty()) 13581 return; 13582 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13583 if (!PD) 13584 return; 13585 13586 unsigned Attributes = PD->getPropertyAttributes(); 13587 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13588 // when 'assign' attribute was not explicitly specified 13589 // by user, ignore it and rely on property type itself 13590 // for lifetime info. 13591 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13592 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13593 LHSType->isObjCRetainableType()) 13594 return; 13595 13596 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13597 if (cast->getCastKind() == CK_ARCConsumeObject) { 13598 Diag(Loc, diag::warn_arc_retained_property_assign) 13599 << RHS->getSourceRange(); 13600 return; 13601 } 13602 RHS = cast->getSubExpr(); 13603 } 13604 } 13605 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13606 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13607 return; 13608 } 13609 } 13610 } 13611 13612 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13613 13614 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13615 SourceLocation StmtLoc, 13616 const NullStmt *Body) { 13617 // Do not warn if the body is a macro that expands to nothing, e.g: 13618 // 13619 // #define CALL(x) 13620 // if (condition) 13621 // CALL(0); 13622 if (Body->hasLeadingEmptyMacro()) 13623 return false; 13624 13625 // Get line numbers of statement and body. 13626 bool StmtLineInvalid; 13627 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13628 &StmtLineInvalid); 13629 if (StmtLineInvalid) 13630 return false; 13631 13632 bool BodyLineInvalid; 13633 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13634 &BodyLineInvalid); 13635 if (BodyLineInvalid) 13636 return false; 13637 13638 // Warn if null statement and body are on the same line. 13639 if (StmtLine != BodyLine) 13640 return false; 13641 13642 return true; 13643 } 13644 13645 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13646 const Stmt *Body, 13647 unsigned DiagID) { 13648 // Since this is a syntactic check, don't emit diagnostic for template 13649 // instantiations, this just adds noise. 13650 if (CurrentInstantiationScope) 13651 return; 13652 13653 // The body should be a null statement. 13654 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13655 if (!NBody) 13656 return; 13657 13658 // Do the usual checks. 13659 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13660 return; 13661 13662 Diag(NBody->getSemiLoc(), DiagID); 13663 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13664 } 13665 13666 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13667 const Stmt *PossibleBody) { 13668 assert(!CurrentInstantiationScope); // Ensured by caller 13669 13670 SourceLocation StmtLoc; 13671 const Stmt *Body; 13672 unsigned DiagID; 13673 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13674 StmtLoc = FS->getRParenLoc(); 13675 Body = FS->getBody(); 13676 DiagID = diag::warn_empty_for_body; 13677 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13678 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13679 Body = WS->getBody(); 13680 DiagID = diag::warn_empty_while_body; 13681 } else 13682 return; // Neither `for' nor `while'. 13683 13684 // The body should be a null statement. 13685 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13686 if (!NBody) 13687 return; 13688 13689 // Skip expensive checks if diagnostic is disabled. 13690 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13691 return; 13692 13693 // Do the usual checks. 13694 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13695 return; 13696 13697 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13698 // noise level low, emit diagnostics only if for/while is followed by a 13699 // CompoundStmt, e.g.: 13700 // for (int i = 0; i < n; i++); 13701 // { 13702 // a(i); 13703 // } 13704 // or if for/while is followed by a statement with more indentation 13705 // than for/while itself: 13706 // for (int i = 0; i < n; i++); 13707 // a(i); 13708 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13709 if (!ProbableTypo) { 13710 bool BodyColInvalid; 13711 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13712 PossibleBody->getBeginLoc(), &BodyColInvalid); 13713 if (BodyColInvalid) 13714 return; 13715 13716 bool StmtColInvalid; 13717 unsigned StmtCol = 13718 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13719 if (StmtColInvalid) 13720 return; 13721 13722 if (BodyCol > StmtCol) 13723 ProbableTypo = true; 13724 } 13725 13726 if (ProbableTypo) { 13727 Diag(NBody->getSemiLoc(), DiagID); 13728 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13729 } 13730 } 13731 13732 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13733 13734 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13735 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13736 SourceLocation OpLoc) { 13737 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13738 return; 13739 13740 if (inTemplateInstantiation()) 13741 return; 13742 13743 // Strip parens and casts away. 13744 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13745 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13746 13747 // Check for a call expression 13748 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13749 if (!CE || CE->getNumArgs() != 1) 13750 return; 13751 13752 // Check for a call to std::move 13753 if (!CE->isCallToStdMove()) 13754 return; 13755 13756 // Get argument from std::move 13757 RHSExpr = CE->getArg(0); 13758 13759 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13760 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13761 13762 // Two DeclRefExpr's, check that the decls are the same. 13763 if (LHSDeclRef && RHSDeclRef) { 13764 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13765 return; 13766 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13767 RHSDeclRef->getDecl()->getCanonicalDecl()) 13768 return; 13769 13770 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13771 << LHSExpr->getSourceRange() 13772 << RHSExpr->getSourceRange(); 13773 return; 13774 } 13775 13776 // Member variables require a different approach to check for self moves. 13777 // MemberExpr's are the same if every nested MemberExpr refers to the same 13778 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13779 // the base Expr's are CXXThisExpr's. 13780 const Expr *LHSBase = LHSExpr; 13781 const Expr *RHSBase = RHSExpr; 13782 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13783 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13784 if (!LHSME || !RHSME) 13785 return; 13786 13787 while (LHSME && RHSME) { 13788 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13789 RHSME->getMemberDecl()->getCanonicalDecl()) 13790 return; 13791 13792 LHSBase = LHSME->getBase(); 13793 RHSBase = RHSME->getBase(); 13794 LHSME = dyn_cast<MemberExpr>(LHSBase); 13795 RHSME = dyn_cast<MemberExpr>(RHSBase); 13796 } 13797 13798 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13799 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13800 if (LHSDeclRef && RHSDeclRef) { 13801 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13802 return; 13803 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13804 RHSDeclRef->getDecl()->getCanonicalDecl()) 13805 return; 13806 13807 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13808 << LHSExpr->getSourceRange() 13809 << RHSExpr->getSourceRange(); 13810 return; 13811 } 13812 13813 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13814 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13815 << LHSExpr->getSourceRange() 13816 << RHSExpr->getSourceRange(); 13817 } 13818 13819 //===--- Layout compatibility ----------------------------------------------// 13820 13821 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13822 13823 /// Check if two enumeration types are layout-compatible. 13824 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13825 // C++11 [dcl.enum] p8: 13826 // Two enumeration types are layout-compatible if they have the same 13827 // underlying type. 13828 return ED1->isComplete() && ED2->isComplete() && 13829 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13830 } 13831 13832 /// Check if two fields are layout-compatible. 13833 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13834 FieldDecl *Field2) { 13835 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13836 return false; 13837 13838 if (Field1->isBitField() != Field2->isBitField()) 13839 return false; 13840 13841 if (Field1->isBitField()) { 13842 // Make sure that the bit-fields are the same length. 13843 unsigned Bits1 = Field1->getBitWidthValue(C); 13844 unsigned Bits2 = Field2->getBitWidthValue(C); 13845 13846 if (Bits1 != Bits2) 13847 return false; 13848 } 13849 13850 return true; 13851 } 13852 13853 /// Check if two standard-layout structs are layout-compatible. 13854 /// (C++11 [class.mem] p17) 13855 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13856 RecordDecl *RD2) { 13857 // If both records are C++ classes, check that base classes match. 13858 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13859 // If one of records is a CXXRecordDecl we are in C++ mode, 13860 // thus the other one is a CXXRecordDecl, too. 13861 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13862 // Check number of base classes. 13863 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13864 return false; 13865 13866 // Check the base classes. 13867 for (CXXRecordDecl::base_class_const_iterator 13868 Base1 = D1CXX->bases_begin(), 13869 BaseEnd1 = D1CXX->bases_end(), 13870 Base2 = D2CXX->bases_begin(); 13871 Base1 != BaseEnd1; 13872 ++Base1, ++Base2) { 13873 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13874 return false; 13875 } 13876 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13877 // If only RD2 is a C++ class, it should have zero base classes. 13878 if (D2CXX->getNumBases() > 0) 13879 return false; 13880 } 13881 13882 // Check the fields. 13883 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13884 Field2End = RD2->field_end(), 13885 Field1 = RD1->field_begin(), 13886 Field1End = RD1->field_end(); 13887 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13888 if (!isLayoutCompatible(C, *Field1, *Field2)) 13889 return false; 13890 } 13891 if (Field1 != Field1End || Field2 != Field2End) 13892 return false; 13893 13894 return true; 13895 } 13896 13897 /// Check if two standard-layout unions are layout-compatible. 13898 /// (C++11 [class.mem] p18) 13899 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13900 RecordDecl *RD2) { 13901 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13902 for (auto *Field2 : RD2->fields()) 13903 UnmatchedFields.insert(Field2); 13904 13905 for (auto *Field1 : RD1->fields()) { 13906 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13907 I = UnmatchedFields.begin(), 13908 E = UnmatchedFields.end(); 13909 13910 for ( ; I != E; ++I) { 13911 if (isLayoutCompatible(C, Field1, *I)) { 13912 bool Result = UnmatchedFields.erase(*I); 13913 (void) Result; 13914 assert(Result); 13915 break; 13916 } 13917 } 13918 if (I == E) 13919 return false; 13920 } 13921 13922 return UnmatchedFields.empty(); 13923 } 13924 13925 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13926 RecordDecl *RD2) { 13927 if (RD1->isUnion() != RD2->isUnion()) 13928 return false; 13929 13930 if (RD1->isUnion()) 13931 return isLayoutCompatibleUnion(C, RD1, RD2); 13932 else 13933 return isLayoutCompatibleStruct(C, RD1, RD2); 13934 } 13935 13936 /// Check if two types are layout-compatible in C++11 sense. 13937 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13938 if (T1.isNull() || T2.isNull()) 13939 return false; 13940 13941 // C++11 [basic.types] p11: 13942 // If two types T1 and T2 are the same type, then T1 and T2 are 13943 // layout-compatible types. 13944 if (C.hasSameType(T1, T2)) 13945 return true; 13946 13947 T1 = T1.getCanonicalType().getUnqualifiedType(); 13948 T2 = T2.getCanonicalType().getUnqualifiedType(); 13949 13950 const Type::TypeClass TC1 = T1->getTypeClass(); 13951 const Type::TypeClass TC2 = T2->getTypeClass(); 13952 13953 if (TC1 != TC2) 13954 return false; 13955 13956 if (TC1 == Type::Enum) { 13957 return isLayoutCompatible(C, 13958 cast<EnumType>(T1)->getDecl(), 13959 cast<EnumType>(T2)->getDecl()); 13960 } else if (TC1 == Type::Record) { 13961 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13962 return false; 13963 13964 return isLayoutCompatible(C, 13965 cast<RecordType>(T1)->getDecl(), 13966 cast<RecordType>(T2)->getDecl()); 13967 } 13968 13969 return false; 13970 } 13971 13972 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13973 13974 /// Given a type tag expression find the type tag itself. 13975 /// 13976 /// \param TypeExpr Type tag expression, as it appears in user's code. 13977 /// 13978 /// \param VD Declaration of an identifier that appears in a type tag. 13979 /// 13980 /// \param MagicValue Type tag magic value. 13981 /// 13982 /// \param isConstantEvaluated wether the evalaution should be performed in 13983 13984 /// constant context. 13985 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13986 const ValueDecl **VD, uint64_t *MagicValue, 13987 bool isConstantEvaluated) { 13988 while(true) { 13989 if (!TypeExpr) 13990 return false; 13991 13992 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13993 13994 switch (TypeExpr->getStmtClass()) { 13995 case Stmt::UnaryOperatorClass: { 13996 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13997 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13998 TypeExpr = UO->getSubExpr(); 13999 continue; 14000 } 14001 return false; 14002 } 14003 14004 case Stmt::DeclRefExprClass: { 14005 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14006 *VD = DRE->getDecl(); 14007 return true; 14008 } 14009 14010 case Stmt::IntegerLiteralClass: { 14011 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14012 llvm::APInt MagicValueAPInt = IL->getValue(); 14013 if (MagicValueAPInt.getActiveBits() <= 64) { 14014 *MagicValue = MagicValueAPInt.getZExtValue(); 14015 return true; 14016 } else 14017 return false; 14018 } 14019 14020 case Stmt::BinaryConditionalOperatorClass: 14021 case Stmt::ConditionalOperatorClass: { 14022 const AbstractConditionalOperator *ACO = 14023 cast<AbstractConditionalOperator>(TypeExpr); 14024 bool Result; 14025 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14026 isConstantEvaluated)) { 14027 if (Result) 14028 TypeExpr = ACO->getTrueExpr(); 14029 else 14030 TypeExpr = ACO->getFalseExpr(); 14031 continue; 14032 } 14033 return false; 14034 } 14035 14036 case Stmt::BinaryOperatorClass: { 14037 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14038 if (BO->getOpcode() == BO_Comma) { 14039 TypeExpr = BO->getRHS(); 14040 continue; 14041 } 14042 return false; 14043 } 14044 14045 default: 14046 return false; 14047 } 14048 } 14049 } 14050 14051 /// Retrieve the C type corresponding to type tag TypeExpr. 14052 /// 14053 /// \param TypeExpr Expression that specifies a type tag. 14054 /// 14055 /// \param MagicValues Registered magic values. 14056 /// 14057 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14058 /// kind. 14059 /// 14060 /// \param TypeInfo Information about the corresponding C type. 14061 /// 14062 /// \param isConstantEvaluated wether the evalaution should be performed in 14063 /// constant context. 14064 /// 14065 /// \returns true if the corresponding C type was found. 14066 static bool GetMatchingCType( 14067 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14068 const ASTContext &Ctx, 14069 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14070 *MagicValues, 14071 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14072 bool isConstantEvaluated) { 14073 FoundWrongKind = false; 14074 14075 // Variable declaration that has type_tag_for_datatype attribute. 14076 const ValueDecl *VD = nullptr; 14077 14078 uint64_t MagicValue; 14079 14080 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14081 return false; 14082 14083 if (VD) { 14084 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14085 if (I->getArgumentKind() != ArgumentKind) { 14086 FoundWrongKind = true; 14087 return false; 14088 } 14089 TypeInfo.Type = I->getMatchingCType(); 14090 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14091 TypeInfo.MustBeNull = I->getMustBeNull(); 14092 return true; 14093 } 14094 return false; 14095 } 14096 14097 if (!MagicValues) 14098 return false; 14099 14100 llvm::DenseMap<Sema::TypeTagMagicValue, 14101 Sema::TypeTagData>::const_iterator I = 14102 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14103 if (I == MagicValues->end()) 14104 return false; 14105 14106 TypeInfo = I->second; 14107 return true; 14108 } 14109 14110 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14111 uint64_t MagicValue, QualType Type, 14112 bool LayoutCompatible, 14113 bool MustBeNull) { 14114 if (!TypeTagForDatatypeMagicValues) 14115 TypeTagForDatatypeMagicValues.reset( 14116 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14117 14118 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14119 (*TypeTagForDatatypeMagicValues)[Magic] = 14120 TypeTagData(Type, LayoutCompatible, MustBeNull); 14121 } 14122 14123 static bool IsSameCharType(QualType T1, QualType T2) { 14124 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14125 if (!BT1) 14126 return false; 14127 14128 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14129 if (!BT2) 14130 return false; 14131 14132 BuiltinType::Kind T1Kind = BT1->getKind(); 14133 BuiltinType::Kind T2Kind = BT2->getKind(); 14134 14135 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14136 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14137 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14138 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14139 } 14140 14141 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14142 const ArrayRef<const Expr *> ExprArgs, 14143 SourceLocation CallSiteLoc) { 14144 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14145 bool IsPointerAttr = Attr->getIsPointer(); 14146 14147 // Retrieve the argument representing the 'type_tag'. 14148 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14149 if (TypeTagIdxAST >= ExprArgs.size()) { 14150 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14151 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14152 return; 14153 } 14154 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14155 bool FoundWrongKind; 14156 TypeTagData TypeInfo; 14157 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14158 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14159 TypeInfo, isConstantEvaluated())) { 14160 if (FoundWrongKind) 14161 Diag(TypeTagExpr->getExprLoc(), 14162 diag::warn_type_tag_for_datatype_wrong_kind) 14163 << TypeTagExpr->getSourceRange(); 14164 return; 14165 } 14166 14167 // Retrieve the argument representing the 'arg_idx'. 14168 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14169 if (ArgumentIdxAST >= ExprArgs.size()) { 14170 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14171 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14172 return; 14173 } 14174 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14175 if (IsPointerAttr) { 14176 // Skip implicit cast of pointer to `void *' (as a function argument). 14177 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14178 if (ICE->getType()->isVoidPointerType() && 14179 ICE->getCastKind() == CK_BitCast) 14180 ArgumentExpr = ICE->getSubExpr(); 14181 } 14182 QualType ArgumentType = ArgumentExpr->getType(); 14183 14184 // Passing a `void*' pointer shouldn't trigger a warning. 14185 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14186 return; 14187 14188 if (TypeInfo.MustBeNull) { 14189 // Type tag with matching void type requires a null pointer. 14190 if (!ArgumentExpr->isNullPointerConstant(Context, 14191 Expr::NPC_ValueDependentIsNotNull)) { 14192 Diag(ArgumentExpr->getExprLoc(), 14193 diag::warn_type_safety_null_pointer_required) 14194 << ArgumentKind->getName() 14195 << ArgumentExpr->getSourceRange() 14196 << TypeTagExpr->getSourceRange(); 14197 } 14198 return; 14199 } 14200 14201 QualType RequiredType = TypeInfo.Type; 14202 if (IsPointerAttr) 14203 RequiredType = Context.getPointerType(RequiredType); 14204 14205 bool mismatch = false; 14206 if (!TypeInfo.LayoutCompatible) { 14207 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14208 14209 // C++11 [basic.fundamental] p1: 14210 // Plain char, signed char, and unsigned char are three distinct types. 14211 // 14212 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14213 // char' depending on the current char signedness mode. 14214 if (mismatch) 14215 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14216 RequiredType->getPointeeType())) || 14217 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14218 mismatch = false; 14219 } else 14220 if (IsPointerAttr) 14221 mismatch = !isLayoutCompatible(Context, 14222 ArgumentType->getPointeeType(), 14223 RequiredType->getPointeeType()); 14224 else 14225 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14226 14227 if (mismatch) 14228 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14229 << ArgumentType << ArgumentKind 14230 << TypeInfo.LayoutCompatible << RequiredType 14231 << ArgumentExpr->getSourceRange() 14232 << TypeTagExpr->getSourceRange(); 14233 } 14234 14235 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14236 CharUnits Alignment) { 14237 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14238 } 14239 14240 void Sema::DiagnoseMisalignedMembers() { 14241 for (MisalignedMember &m : MisalignedMembers) { 14242 const NamedDecl *ND = m.RD; 14243 if (ND->getName().empty()) { 14244 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14245 ND = TD; 14246 } 14247 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14248 << m.MD << ND << m.E->getSourceRange(); 14249 } 14250 MisalignedMembers.clear(); 14251 } 14252 14253 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14254 E = E->IgnoreParens(); 14255 if (!T->isPointerType() && !T->isIntegerType()) 14256 return; 14257 if (isa<UnaryOperator>(E) && 14258 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14259 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14260 if (isa<MemberExpr>(Op)) { 14261 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14262 if (MA != MisalignedMembers.end() && 14263 (T->isIntegerType() || 14264 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14265 Context.getTypeAlignInChars( 14266 T->getPointeeType()) <= MA->Alignment)))) 14267 MisalignedMembers.erase(MA); 14268 } 14269 } 14270 } 14271 14272 void Sema::RefersToMemberWithReducedAlignment( 14273 Expr *E, 14274 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14275 Action) { 14276 const auto *ME = dyn_cast<MemberExpr>(E); 14277 if (!ME) 14278 return; 14279 14280 // No need to check expressions with an __unaligned-qualified type. 14281 if (E->getType().getQualifiers().hasUnaligned()) 14282 return; 14283 14284 // For a chain of MemberExpr like "a.b.c.d" this list 14285 // will keep FieldDecl's like [d, c, b]. 14286 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14287 const MemberExpr *TopME = nullptr; 14288 bool AnyIsPacked = false; 14289 do { 14290 QualType BaseType = ME->getBase()->getType(); 14291 if (ME->isArrow()) 14292 BaseType = BaseType->getPointeeType(); 14293 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 14294 if (RD->isInvalidDecl()) 14295 return; 14296 14297 ValueDecl *MD = ME->getMemberDecl(); 14298 auto *FD = dyn_cast<FieldDecl>(MD); 14299 // We do not care about non-data members. 14300 if (!FD || FD->isInvalidDecl()) 14301 return; 14302 14303 AnyIsPacked = 14304 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14305 ReverseMemberChain.push_back(FD); 14306 14307 TopME = ME; 14308 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14309 } while (ME); 14310 assert(TopME && "We did not compute a topmost MemberExpr!"); 14311 14312 // Not the scope of this diagnostic. 14313 if (!AnyIsPacked) 14314 return; 14315 14316 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14317 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14318 // TODO: The innermost base of the member expression may be too complicated. 14319 // For now, just disregard these cases. This is left for future 14320 // improvement. 14321 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14322 return; 14323 14324 // Alignment expected by the whole expression. 14325 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14326 14327 // No need to do anything else with this case. 14328 if (ExpectedAlignment.isOne()) 14329 return; 14330 14331 // Synthesize offset of the whole access. 14332 CharUnits Offset; 14333 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14334 I++) { 14335 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14336 } 14337 14338 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14339 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14340 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14341 14342 // The base expression of the innermost MemberExpr may give 14343 // stronger guarantees than the class containing the member. 14344 if (DRE && !TopME->isArrow()) { 14345 const ValueDecl *VD = DRE->getDecl(); 14346 if (!VD->getType()->isReferenceType()) 14347 CompleteObjectAlignment = 14348 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14349 } 14350 14351 // Check if the synthesized offset fulfills the alignment. 14352 if (Offset % ExpectedAlignment != 0 || 14353 // It may fulfill the offset it but the effective alignment may still be 14354 // lower than the expected expression alignment. 14355 CompleteObjectAlignment < ExpectedAlignment) { 14356 // If this happens, we want to determine a sensible culprit of this. 14357 // Intuitively, watching the chain of member expressions from right to 14358 // left, we start with the required alignment (as required by the field 14359 // type) but some packed attribute in that chain has reduced the alignment. 14360 // It may happen that another packed structure increases it again. But if 14361 // we are here such increase has not been enough. So pointing the first 14362 // FieldDecl that either is packed or else its RecordDecl is, 14363 // seems reasonable. 14364 FieldDecl *FD = nullptr; 14365 CharUnits Alignment; 14366 for (FieldDecl *FDI : ReverseMemberChain) { 14367 if (FDI->hasAttr<PackedAttr>() || 14368 FDI->getParent()->hasAttr<PackedAttr>()) { 14369 FD = FDI; 14370 Alignment = std::min( 14371 Context.getTypeAlignInChars(FD->getType()), 14372 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14373 break; 14374 } 14375 } 14376 assert(FD && "We did not find a packed FieldDecl!"); 14377 Action(E, FD->getParent(), FD, Alignment); 14378 } 14379 } 14380 14381 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14382 using namespace std::placeholders; 14383 14384 RefersToMemberWithReducedAlignment( 14385 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14386 _2, _3, _4)); 14387 } 14388