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()->castAs<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()->castAs<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(), 633 diag::err_typecheck_call_too_few_args_at_least) 634 << 0 << 4 << NumArgs; 635 return true; 636 } 637 638 Expr *Arg0 = TheCall->getArg(0); 639 Expr *Arg1 = TheCall->getArg(1); 640 Expr *Arg2 = TheCall->getArg(2); 641 Expr *Arg3 = TheCall->getArg(3); 642 643 // First argument always needs to be a queue_t type. 644 if (!Arg0->getType()->isQueueT()) { 645 S.Diag(TheCall->getArg(0)->getBeginLoc(), 646 diag::err_opencl_builtin_expected_type) 647 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 648 return true; 649 } 650 651 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 652 if (!Arg1->getType()->isIntegerType()) { 653 S.Diag(TheCall->getArg(1)->getBeginLoc(), 654 diag::err_opencl_builtin_expected_type) 655 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 656 return true; 657 } 658 659 // Third argument is always an ndrange_t type. 660 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 661 S.Diag(TheCall->getArg(2)->getBeginLoc(), 662 diag::err_opencl_builtin_expected_type) 663 << TheCall->getDirectCallee() << "'ndrange_t'"; 664 return true; 665 } 666 667 // With four arguments, there is only one form that the function could be 668 // called in: no events and no variable arguments. 669 if (NumArgs == 4) { 670 // check that the last argument is the right block type. 671 if (!isBlockPointer(Arg3)) { 672 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 673 << TheCall->getDirectCallee() << "block"; 674 return true; 675 } 676 // we have a block type, check the prototype 677 const BlockPointerType *BPT = 678 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 679 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 680 S.Diag(Arg3->getBeginLoc(), 681 diag::err_opencl_enqueue_kernel_blocks_no_args); 682 return true; 683 } 684 return false; 685 } 686 // we can have block + varargs. 687 if (isBlockPointer(Arg3)) 688 return (checkOpenCLBlockArgs(S, Arg3) || 689 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 690 // last two cases with either exactly 7 args or 7 args and varargs. 691 if (NumArgs >= 7) { 692 // check common block argument. 693 Expr *Arg6 = TheCall->getArg(6); 694 if (!isBlockPointer(Arg6)) { 695 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 696 << TheCall->getDirectCallee() << "block"; 697 return true; 698 } 699 if (checkOpenCLBlockArgs(S, Arg6)) 700 return true; 701 702 // Forth argument has to be any integer type. 703 if (!Arg3->getType()->isIntegerType()) { 704 S.Diag(TheCall->getArg(3)->getBeginLoc(), 705 diag::err_opencl_builtin_expected_type) 706 << TheCall->getDirectCallee() << "integer"; 707 return true; 708 } 709 // check remaining common arguments. 710 Expr *Arg4 = TheCall->getArg(4); 711 Expr *Arg5 = TheCall->getArg(5); 712 713 // Fifth argument is always passed as a pointer to clk_event_t. 714 if (!Arg4->isNullPointerConstant(S.Context, 715 Expr::NPC_ValueDependentIsNotNull) && 716 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 717 S.Diag(TheCall->getArg(4)->getBeginLoc(), 718 diag::err_opencl_builtin_expected_type) 719 << TheCall->getDirectCallee() 720 << S.Context.getPointerType(S.Context.OCLClkEventTy); 721 return true; 722 } 723 724 // Sixth argument is always passed as a pointer to clk_event_t. 725 if (!Arg5->isNullPointerConstant(S.Context, 726 Expr::NPC_ValueDependentIsNotNull) && 727 !(Arg5->getType()->isPointerType() && 728 Arg5->getType()->getPointeeType()->isClkEventT())) { 729 S.Diag(TheCall->getArg(5)->getBeginLoc(), 730 diag::err_opencl_builtin_expected_type) 731 << TheCall->getDirectCallee() 732 << S.Context.getPointerType(S.Context.OCLClkEventTy); 733 return true; 734 } 735 736 if (NumArgs == 7) 737 return false; 738 739 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 740 } 741 742 // None of the specific case has been detected, give generic error 743 S.Diag(TheCall->getBeginLoc(), 744 diag::err_opencl_enqueue_kernel_incorrect_args); 745 return true; 746 } 747 748 /// Returns OpenCL access qual. 749 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 750 return D->getAttr<OpenCLAccessAttr>(); 751 } 752 753 /// Returns true if pipe element type is different from the pointer. 754 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 755 const Expr *Arg0 = Call->getArg(0); 756 // First argument type should always be pipe. 757 if (!Arg0->getType()->isPipeType()) { 758 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 759 << Call->getDirectCallee() << Arg0->getSourceRange(); 760 return true; 761 } 762 OpenCLAccessAttr *AccessQual = 763 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 764 // Validates the access qualifier is compatible with the call. 765 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 766 // read_only and write_only, and assumed to be read_only if no qualifier is 767 // specified. 768 switch (Call->getDirectCallee()->getBuiltinID()) { 769 case Builtin::BIread_pipe: 770 case Builtin::BIreserve_read_pipe: 771 case Builtin::BIcommit_read_pipe: 772 case Builtin::BIwork_group_reserve_read_pipe: 773 case Builtin::BIsub_group_reserve_read_pipe: 774 case Builtin::BIwork_group_commit_read_pipe: 775 case Builtin::BIsub_group_commit_read_pipe: 776 if (!(!AccessQual || AccessQual->isReadOnly())) { 777 S.Diag(Arg0->getBeginLoc(), 778 diag::err_opencl_builtin_pipe_invalid_access_modifier) 779 << "read_only" << Arg0->getSourceRange(); 780 return true; 781 } 782 break; 783 case Builtin::BIwrite_pipe: 784 case Builtin::BIreserve_write_pipe: 785 case Builtin::BIcommit_write_pipe: 786 case Builtin::BIwork_group_reserve_write_pipe: 787 case Builtin::BIsub_group_reserve_write_pipe: 788 case Builtin::BIwork_group_commit_write_pipe: 789 case Builtin::BIsub_group_commit_write_pipe: 790 if (!(AccessQual && AccessQual->isWriteOnly())) { 791 S.Diag(Arg0->getBeginLoc(), 792 diag::err_opencl_builtin_pipe_invalid_access_modifier) 793 << "write_only" << Arg0->getSourceRange(); 794 return true; 795 } 796 break; 797 default: 798 break; 799 } 800 return false; 801 } 802 803 /// Returns true if pipe element type is different from the pointer. 804 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 805 const Expr *Arg0 = Call->getArg(0); 806 const Expr *ArgIdx = Call->getArg(Idx); 807 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 808 const QualType EltTy = PipeTy->getElementType(); 809 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 810 // The Idx argument should be a pointer and the type of the pointer and 811 // the type of pipe element should also be the same. 812 if (!ArgTy || 813 !S.Context.hasSameType( 814 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 815 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 816 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 817 << ArgIdx->getType() << ArgIdx->getSourceRange(); 818 return true; 819 } 820 return false; 821 } 822 823 // Performs semantic analysis for the read/write_pipe call. 824 // \param S Reference to the semantic analyzer. 825 // \param Call A pointer to the builtin call. 826 // \return True if a semantic error has been found, false otherwise. 827 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 828 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 829 // functions have two forms. 830 switch (Call->getNumArgs()) { 831 case 2: 832 if (checkOpenCLPipeArg(S, Call)) 833 return true; 834 // The call with 2 arguments should be 835 // read/write_pipe(pipe T, T*). 836 // Check packet type T. 837 if (checkOpenCLPipePacketType(S, Call, 1)) 838 return true; 839 break; 840 841 case 4: { 842 if (checkOpenCLPipeArg(S, Call)) 843 return true; 844 // The call with 4 arguments should be 845 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 846 // Check reserve_id_t. 847 if (!Call->getArg(1)->getType()->isReserveIDT()) { 848 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 849 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 850 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 851 return true; 852 } 853 854 // Check the index. 855 const Expr *Arg2 = Call->getArg(2); 856 if (!Arg2->getType()->isIntegerType() && 857 !Arg2->getType()->isUnsignedIntegerType()) { 858 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 859 << Call->getDirectCallee() << S.Context.UnsignedIntTy 860 << Arg2->getType() << Arg2->getSourceRange(); 861 return true; 862 } 863 864 // Check packet type T. 865 if (checkOpenCLPipePacketType(S, Call, 3)) 866 return true; 867 } break; 868 default: 869 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 870 << Call->getDirectCallee() << Call->getSourceRange(); 871 return true; 872 } 873 874 return false; 875 } 876 877 // Performs a semantic analysis on the {work_group_/sub_group_ 878 // /_}reserve_{read/write}_pipe 879 // \param S Reference to the semantic analyzer. 880 // \param Call The call to the builtin function to be analyzed. 881 // \return True if a semantic error was found, false otherwise. 882 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 883 if (checkArgCount(S, Call, 2)) 884 return true; 885 886 if (checkOpenCLPipeArg(S, Call)) 887 return true; 888 889 // Check the reserve size. 890 if (!Call->getArg(1)->getType()->isIntegerType() && 891 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 892 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 893 << Call->getDirectCallee() << S.Context.UnsignedIntTy 894 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 895 return true; 896 } 897 898 // Since return type of reserve_read/write_pipe built-in function is 899 // reserve_id_t, which is not defined in the builtin def file , we used int 900 // as return type and need to override the return type of these functions. 901 Call->setType(S.Context.OCLReserveIDTy); 902 903 return false; 904 } 905 906 // Performs a semantic analysis on {work_group_/sub_group_ 907 // /_}commit_{read/write}_pipe 908 // \param S Reference to the semantic analyzer. 909 // \param Call The call to the builtin function to be analyzed. 910 // \return True if a semantic error was found, false otherwise. 911 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 912 if (checkArgCount(S, Call, 2)) 913 return true; 914 915 if (checkOpenCLPipeArg(S, Call)) 916 return true; 917 918 // Check reserve_id_t. 919 if (!Call->getArg(1)->getType()->isReserveIDT()) { 920 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 921 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 922 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 923 return true; 924 } 925 926 return false; 927 } 928 929 // Performs a semantic analysis on the call to built-in Pipe 930 // Query Functions. 931 // \param S Reference to the semantic analyzer. 932 // \param Call The call to the builtin function to be analyzed. 933 // \return True if a semantic error was found, false otherwise. 934 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 935 if (checkArgCount(S, Call, 1)) 936 return true; 937 938 if (!Call->getArg(0)->getType()->isPipeType()) { 939 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 940 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 941 return true; 942 } 943 944 return false; 945 } 946 947 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 948 // Performs semantic analysis for the to_global/local/private call. 949 // \param S Reference to the semantic analyzer. 950 // \param BuiltinID ID of the builtin function. 951 // \param Call A pointer to the builtin call. 952 // \return True if a semantic error has been found, false otherwise. 953 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 954 CallExpr *Call) { 955 if (Call->getNumArgs() != 1) { 956 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 957 << Call->getDirectCallee() << Call->getSourceRange(); 958 return true; 959 } 960 961 auto RT = Call->getArg(0)->getType(); 962 if (!RT->isPointerType() || RT->getPointeeType() 963 .getAddressSpace() == LangAS::opencl_constant) { 964 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 965 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 966 return true; 967 } 968 969 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 970 S.Diag(Call->getArg(0)->getBeginLoc(), 971 diag::warn_opencl_generic_address_space_arg) 972 << Call->getDirectCallee()->getNameInfo().getAsString() 973 << Call->getArg(0)->getSourceRange(); 974 } 975 976 RT = RT->getPointeeType(); 977 auto Qual = RT.getQualifiers(); 978 switch (BuiltinID) { 979 case Builtin::BIto_global: 980 Qual.setAddressSpace(LangAS::opencl_global); 981 break; 982 case Builtin::BIto_local: 983 Qual.setAddressSpace(LangAS::opencl_local); 984 break; 985 case Builtin::BIto_private: 986 Qual.setAddressSpace(LangAS::opencl_private); 987 break; 988 default: 989 llvm_unreachable("Invalid builtin function"); 990 } 991 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 992 RT.getUnqualifiedType(), Qual))); 993 994 return false; 995 } 996 997 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 998 if (checkArgCount(S, TheCall, 1)) 999 return ExprError(); 1000 1001 // Compute __builtin_launder's parameter type from the argument. 1002 // The parameter type is: 1003 // * The type of the argument if it's not an array or function type, 1004 // Otherwise, 1005 // * The decayed argument type. 1006 QualType ParamTy = [&]() { 1007 QualType ArgTy = TheCall->getArg(0)->getType(); 1008 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1009 return S.Context.getPointerType(Ty->getElementType()); 1010 if (ArgTy->isFunctionType()) { 1011 return S.Context.getPointerType(ArgTy); 1012 } 1013 return ArgTy; 1014 }(); 1015 1016 TheCall->setType(ParamTy); 1017 1018 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1019 if (!ParamTy->isPointerType()) 1020 return 0; 1021 if (ParamTy->isFunctionPointerType()) 1022 return 1; 1023 if (ParamTy->isVoidPointerType()) 1024 return 2; 1025 return llvm::Optional<unsigned>{}; 1026 }(); 1027 if (DiagSelect.hasValue()) { 1028 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1029 << DiagSelect.getValue() << TheCall->getSourceRange(); 1030 return ExprError(); 1031 } 1032 1033 // We either have an incomplete class type, or we have a class template 1034 // whose instantiation has not been forced. Example: 1035 // 1036 // template <class T> struct Foo { T value; }; 1037 // Foo<int> *p = nullptr; 1038 // auto *d = __builtin_launder(p); 1039 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1040 diag::err_incomplete_type)) 1041 return ExprError(); 1042 1043 assert(ParamTy->getPointeeType()->isObjectType() && 1044 "Unhandled non-object pointer case"); 1045 1046 InitializedEntity Entity = 1047 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1048 ExprResult Arg = 1049 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1050 if (Arg.isInvalid()) 1051 return ExprError(); 1052 TheCall->setArg(0, Arg.get()); 1053 1054 return TheCall; 1055 } 1056 1057 // Emit an error and return true if the current architecture is not in the list 1058 // of supported architectures. 1059 static bool 1060 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1061 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1062 llvm::Triple::ArchType CurArch = 1063 S.getASTContext().getTargetInfo().getTriple().getArch(); 1064 if (llvm::is_contained(SupportedArchs, CurArch)) 1065 return false; 1066 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1067 << TheCall->getSourceRange(); 1068 return true; 1069 } 1070 1071 ExprResult 1072 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1073 CallExpr *TheCall) { 1074 ExprResult TheCallResult(TheCall); 1075 1076 // Find out if any arguments are required to be integer constant expressions. 1077 unsigned ICEArguments = 0; 1078 ASTContext::GetBuiltinTypeError Error; 1079 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1080 if (Error != ASTContext::GE_None) 1081 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1082 1083 // If any arguments are required to be ICE's, check and diagnose. 1084 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1085 // Skip arguments not required to be ICE's. 1086 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1087 1088 llvm::APSInt Result; 1089 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1090 return true; 1091 ICEArguments &= ~(1 << ArgNo); 1092 } 1093 1094 switch (BuiltinID) { 1095 case Builtin::BI__builtin___CFStringMakeConstantString: 1096 assert(TheCall->getNumArgs() == 1 && 1097 "Wrong # arguments to builtin CFStringMakeConstantString"); 1098 if (CheckObjCString(TheCall->getArg(0))) 1099 return ExprError(); 1100 break; 1101 case Builtin::BI__builtin_ms_va_start: 1102 case Builtin::BI__builtin_stdarg_start: 1103 case Builtin::BI__builtin_va_start: 1104 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1105 return ExprError(); 1106 break; 1107 case Builtin::BI__va_start: { 1108 switch (Context.getTargetInfo().getTriple().getArch()) { 1109 case llvm::Triple::aarch64: 1110 case llvm::Triple::arm: 1111 case llvm::Triple::thumb: 1112 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1113 return ExprError(); 1114 break; 1115 default: 1116 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1117 return ExprError(); 1118 break; 1119 } 1120 break; 1121 } 1122 1123 // The acquire, release, and no fence variants are ARM and AArch64 only. 1124 case Builtin::BI_interlockedbittestandset_acq: 1125 case Builtin::BI_interlockedbittestandset_rel: 1126 case Builtin::BI_interlockedbittestandset_nf: 1127 case Builtin::BI_interlockedbittestandreset_acq: 1128 case Builtin::BI_interlockedbittestandreset_rel: 1129 case Builtin::BI_interlockedbittestandreset_nf: 1130 if (CheckBuiltinTargetSupport( 1131 *this, BuiltinID, TheCall, 1132 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1133 return ExprError(); 1134 break; 1135 1136 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1137 case Builtin::BI_bittest64: 1138 case Builtin::BI_bittestandcomplement64: 1139 case Builtin::BI_bittestandreset64: 1140 case Builtin::BI_bittestandset64: 1141 case Builtin::BI_interlockedbittestandreset64: 1142 case Builtin::BI_interlockedbittestandset64: 1143 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1144 {llvm::Triple::x86_64, llvm::Triple::arm, 1145 llvm::Triple::thumb, llvm::Triple::aarch64})) 1146 return ExprError(); 1147 break; 1148 1149 case Builtin::BI__builtin_isgreater: 1150 case Builtin::BI__builtin_isgreaterequal: 1151 case Builtin::BI__builtin_isless: 1152 case Builtin::BI__builtin_islessequal: 1153 case Builtin::BI__builtin_islessgreater: 1154 case Builtin::BI__builtin_isunordered: 1155 if (SemaBuiltinUnorderedCompare(TheCall)) 1156 return ExprError(); 1157 break; 1158 case Builtin::BI__builtin_fpclassify: 1159 if (SemaBuiltinFPClassification(TheCall, 6)) 1160 return ExprError(); 1161 break; 1162 case Builtin::BI__builtin_isfinite: 1163 case Builtin::BI__builtin_isinf: 1164 case Builtin::BI__builtin_isinf_sign: 1165 case Builtin::BI__builtin_isnan: 1166 case Builtin::BI__builtin_isnormal: 1167 case Builtin::BI__builtin_signbit: 1168 case Builtin::BI__builtin_signbitf: 1169 case Builtin::BI__builtin_signbitl: 1170 if (SemaBuiltinFPClassification(TheCall, 1)) 1171 return ExprError(); 1172 break; 1173 case Builtin::BI__builtin_shufflevector: 1174 return SemaBuiltinShuffleVector(TheCall); 1175 // TheCall will be freed by the smart pointer here, but that's fine, since 1176 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1177 case Builtin::BI__builtin_prefetch: 1178 if (SemaBuiltinPrefetch(TheCall)) 1179 return ExprError(); 1180 break; 1181 case Builtin::BI__builtin_alloca_with_align: 1182 if (SemaBuiltinAllocaWithAlign(TheCall)) 1183 return ExprError(); 1184 LLVM_FALLTHROUGH; 1185 case Builtin::BI__builtin_alloca: 1186 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1187 << TheCall->getDirectCallee(); 1188 break; 1189 case Builtin::BI__assume: 1190 case Builtin::BI__builtin_assume: 1191 if (SemaBuiltinAssume(TheCall)) 1192 return ExprError(); 1193 break; 1194 case Builtin::BI__builtin_assume_aligned: 1195 if (SemaBuiltinAssumeAligned(TheCall)) 1196 return ExprError(); 1197 break; 1198 case Builtin::BI__builtin_dynamic_object_size: 1199 case Builtin::BI__builtin_object_size: 1200 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1201 return ExprError(); 1202 break; 1203 case Builtin::BI__builtin_longjmp: 1204 if (SemaBuiltinLongjmp(TheCall)) 1205 return ExprError(); 1206 break; 1207 case Builtin::BI__builtin_setjmp: 1208 if (SemaBuiltinSetjmp(TheCall)) 1209 return ExprError(); 1210 break; 1211 case Builtin::BI_setjmp: 1212 case Builtin::BI_setjmpex: 1213 if (checkArgCount(*this, TheCall, 1)) 1214 return true; 1215 break; 1216 case Builtin::BI__builtin_classify_type: 1217 if (checkArgCount(*this, TheCall, 1)) return true; 1218 TheCall->setType(Context.IntTy); 1219 break; 1220 case Builtin::BI__builtin_constant_p: { 1221 if (checkArgCount(*this, TheCall, 1)) return true; 1222 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1223 if (Arg.isInvalid()) return true; 1224 TheCall->setArg(0, Arg.get()); 1225 TheCall->setType(Context.IntTy); 1226 break; 1227 } 1228 case Builtin::BI__builtin_launder: 1229 return SemaBuiltinLaunder(*this, TheCall); 1230 case Builtin::BI__sync_fetch_and_add: 1231 case Builtin::BI__sync_fetch_and_add_1: 1232 case Builtin::BI__sync_fetch_and_add_2: 1233 case Builtin::BI__sync_fetch_and_add_4: 1234 case Builtin::BI__sync_fetch_and_add_8: 1235 case Builtin::BI__sync_fetch_and_add_16: 1236 case Builtin::BI__sync_fetch_and_sub: 1237 case Builtin::BI__sync_fetch_and_sub_1: 1238 case Builtin::BI__sync_fetch_and_sub_2: 1239 case Builtin::BI__sync_fetch_and_sub_4: 1240 case Builtin::BI__sync_fetch_and_sub_8: 1241 case Builtin::BI__sync_fetch_and_sub_16: 1242 case Builtin::BI__sync_fetch_and_or: 1243 case Builtin::BI__sync_fetch_and_or_1: 1244 case Builtin::BI__sync_fetch_and_or_2: 1245 case Builtin::BI__sync_fetch_and_or_4: 1246 case Builtin::BI__sync_fetch_and_or_8: 1247 case Builtin::BI__sync_fetch_and_or_16: 1248 case Builtin::BI__sync_fetch_and_and: 1249 case Builtin::BI__sync_fetch_and_and_1: 1250 case Builtin::BI__sync_fetch_and_and_2: 1251 case Builtin::BI__sync_fetch_and_and_4: 1252 case Builtin::BI__sync_fetch_and_and_8: 1253 case Builtin::BI__sync_fetch_and_and_16: 1254 case Builtin::BI__sync_fetch_and_xor: 1255 case Builtin::BI__sync_fetch_and_xor_1: 1256 case Builtin::BI__sync_fetch_and_xor_2: 1257 case Builtin::BI__sync_fetch_and_xor_4: 1258 case Builtin::BI__sync_fetch_and_xor_8: 1259 case Builtin::BI__sync_fetch_and_xor_16: 1260 case Builtin::BI__sync_fetch_and_nand: 1261 case Builtin::BI__sync_fetch_and_nand_1: 1262 case Builtin::BI__sync_fetch_and_nand_2: 1263 case Builtin::BI__sync_fetch_and_nand_4: 1264 case Builtin::BI__sync_fetch_and_nand_8: 1265 case Builtin::BI__sync_fetch_and_nand_16: 1266 case Builtin::BI__sync_add_and_fetch: 1267 case Builtin::BI__sync_add_and_fetch_1: 1268 case Builtin::BI__sync_add_and_fetch_2: 1269 case Builtin::BI__sync_add_and_fetch_4: 1270 case Builtin::BI__sync_add_and_fetch_8: 1271 case Builtin::BI__sync_add_and_fetch_16: 1272 case Builtin::BI__sync_sub_and_fetch: 1273 case Builtin::BI__sync_sub_and_fetch_1: 1274 case Builtin::BI__sync_sub_and_fetch_2: 1275 case Builtin::BI__sync_sub_and_fetch_4: 1276 case Builtin::BI__sync_sub_and_fetch_8: 1277 case Builtin::BI__sync_sub_and_fetch_16: 1278 case Builtin::BI__sync_and_and_fetch: 1279 case Builtin::BI__sync_and_and_fetch_1: 1280 case Builtin::BI__sync_and_and_fetch_2: 1281 case Builtin::BI__sync_and_and_fetch_4: 1282 case Builtin::BI__sync_and_and_fetch_8: 1283 case Builtin::BI__sync_and_and_fetch_16: 1284 case Builtin::BI__sync_or_and_fetch: 1285 case Builtin::BI__sync_or_and_fetch_1: 1286 case Builtin::BI__sync_or_and_fetch_2: 1287 case Builtin::BI__sync_or_and_fetch_4: 1288 case Builtin::BI__sync_or_and_fetch_8: 1289 case Builtin::BI__sync_or_and_fetch_16: 1290 case Builtin::BI__sync_xor_and_fetch: 1291 case Builtin::BI__sync_xor_and_fetch_1: 1292 case Builtin::BI__sync_xor_and_fetch_2: 1293 case Builtin::BI__sync_xor_and_fetch_4: 1294 case Builtin::BI__sync_xor_and_fetch_8: 1295 case Builtin::BI__sync_xor_and_fetch_16: 1296 case Builtin::BI__sync_nand_and_fetch: 1297 case Builtin::BI__sync_nand_and_fetch_1: 1298 case Builtin::BI__sync_nand_and_fetch_2: 1299 case Builtin::BI__sync_nand_and_fetch_4: 1300 case Builtin::BI__sync_nand_and_fetch_8: 1301 case Builtin::BI__sync_nand_and_fetch_16: 1302 case Builtin::BI__sync_val_compare_and_swap: 1303 case Builtin::BI__sync_val_compare_and_swap_1: 1304 case Builtin::BI__sync_val_compare_and_swap_2: 1305 case Builtin::BI__sync_val_compare_and_swap_4: 1306 case Builtin::BI__sync_val_compare_and_swap_8: 1307 case Builtin::BI__sync_val_compare_and_swap_16: 1308 case Builtin::BI__sync_bool_compare_and_swap: 1309 case Builtin::BI__sync_bool_compare_and_swap_1: 1310 case Builtin::BI__sync_bool_compare_and_swap_2: 1311 case Builtin::BI__sync_bool_compare_and_swap_4: 1312 case Builtin::BI__sync_bool_compare_and_swap_8: 1313 case Builtin::BI__sync_bool_compare_and_swap_16: 1314 case Builtin::BI__sync_lock_test_and_set: 1315 case Builtin::BI__sync_lock_test_and_set_1: 1316 case Builtin::BI__sync_lock_test_and_set_2: 1317 case Builtin::BI__sync_lock_test_and_set_4: 1318 case Builtin::BI__sync_lock_test_and_set_8: 1319 case Builtin::BI__sync_lock_test_and_set_16: 1320 case Builtin::BI__sync_lock_release: 1321 case Builtin::BI__sync_lock_release_1: 1322 case Builtin::BI__sync_lock_release_2: 1323 case Builtin::BI__sync_lock_release_4: 1324 case Builtin::BI__sync_lock_release_8: 1325 case Builtin::BI__sync_lock_release_16: 1326 case Builtin::BI__sync_swap: 1327 case Builtin::BI__sync_swap_1: 1328 case Builtin::BI__sync_swap_2: 1329 case Builtin::BI__sync_swap_4: 1330 case Builtin::BI__sync_swap_8: 1331 case Builtin::BI__sync_swap_16: 1332 return SemaBuiltinAtomicOverloaded(TheCallResult); 1333 case Builtin::BI__sync_synchronize: 1334 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1335 << TheCall->getCallee()->getSourceRange(); 1336 break; 1337 case Builtin::BI__builtin_nontemporal_load: 1338 case Builtin::BI__builtin_nontemporal_store: 1339 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1340 #define BUILTIN(ID, TYPE, ATTRS) 1341 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1342 case Builtin::BI##ID: \ 1343 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1344 #include "clang/Basic/Builtins.def" 1345 case Builtin::BI__annotation: 1346 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1347 return ExprError(); 1348 break; 1349 case Builtin::BI__builtin_annotation: 1350 if (SemaBuiltinAnnotation(*this, TheCall)) 1351 return ExprError(); 1352 break; 1353 case Builtin::BI__builtin_addressof: 1354 if (SemaBuiltinAddressof(*this, TheCall)) 1355 return ExprError(); 1356 break; 1357 case Builtin::BI__builtin_add_overflow: 1358 case Builtin::BI__builtin_sub_overflow: 1359 case Builtin::BI__builtin_mul_overflow: 1360 if (SemaBuiltinOverflow(*this, TheCall)) 1361 return ExprError(); 1362 break; 1363 case Builtin::BI__builtin_operator_new: 1364 case Builtin::BI__builtin_operator_delete: { 1365 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1366 ExprResult Res = 1367 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1368 if (Res.isInvalid()) 1369 CorrectDelayedTyposInExpr(TheCallResult.get()); 1370 return Res; 1371 } 1372 case Builtin::BI__builtin_dump_struct: { 1373 // We first want to ensure we are called with 2 arguments 1374 if (checkArgCount(*this, TheCall, 2)) 1375 return ExprError(); 1376 // Ensure that the first argument is of type 'struct XX *' 1377 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1378 const QualType PtrArgType = PtrArg->getType(); 1379 if (!PtrArgType->isPointerType() || 1380 !PtrArgType->getPointeeType()->isRecordType()) { 1381 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1382 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1383 << "structure pointer"; 1384 return ExprError(); 1385 } 1386 1387 // Ensure that the second argument is of type 'FunctionType' 1388 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1389 const QualType FnPtrArgType = FnPtrArg->getType(); 1390 if (!FnPtrArgType->isPointerType()) { 1391 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1392 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1393 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1394 return ExprError(); 1395 } 1396 1397 const auto *FuncType = 1398 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1399 1400 if (!FuncType) { 1401 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1402 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1403 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1404 return ExprError(); 1405 } 1406 1407 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1408 if (!FT->getNumParams()) { 1409 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1410 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1411 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1412 return ExprError(); 1413 } 1414 QualType PT = FT->getParamType(0); 1415 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1416 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1417 !PT->getPointeeType().isConstQualified()) { 1418 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1419 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1420 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1421 return ExprError(); 1422 } 1423 } 1424 1425 TheCall->setType(Context.IntTy); 1426 break; 1427 } 1428 case Builtin::BI__builtin_preserve_access_index: 1429 if (SemaBuiltinPreserveAI(*this, TheCall)) 1430 return ExprError(); 1431 break; 1432 case Builtin::BI__builtin_call_with_static_chain: 1433 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1434 return ExprError(); 1435 break; 1436 case Builtin::BI__exception_code: 1437 case Builtin::BI_exception_code: 1438 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1439 diag::err_seh___except_block)) 1440 return ExprError(); 1441 break; 1442 case Builtin::BI__exception_info: 1443 case Builtin::BI_exception_info: 1444 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1445 diag::err_seh___except_filter)) 1446 return ExprError(); 1447 break; 1448 case Builtin::BI__GetExceptionInfo: 1449 if (checkArgCount(*this, TheCall, 1)) 1450 return ExprError(); 1451 1452 if (CheckCXXThrowOperand( 1453 TheCall->getBeginLoc(), 1454 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1455 TheCall)) 1456 return ExprError(); 1457 1458 TheCall->setType(Context.VoidPtrTy); 1459 break; 1460 // OpenCL v2.0, s6.13.16 - Pipe functions 1461 case Builtin::BIread_pipe: 1462 case Builtin::BIwrite_pipe: 1463 // Since those two functions are declared with var args, we need a semantic 1464 // check for the argument. 1465 if (SemaBuiltinRWPipe(*this, TheCall)) 1466 return ExprError(); 1467 break; 1468 case Builtin::BIreserve_read_pipe: 1469 case Builtin::BIreserve_write_pipe: 1470 case Builtin::BIwork_group_reserve_read_pipe: 1471 case Builtin::BIwork_group_reserve_write_pipe: 1472 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1473 return ExprError(); 1474 break; 1475 case Builtin::BIsub_group_reserve_read_pipe: 1476 case Builtin::BIsub_group_reserve_write_pipe: 1477 if (checkOpenCLSubgroupExt(*this, TheCall) || 1478 SemaBuiltinReserveRWPipe(*this, TheCall)) 1479 return ExprError(); 1480 break; 1481 case Builtin::BIcommit_read_pipe: 1482 case Builtin::BIcommit_write_pipe: 1483 case Builtin::BIwork_group_commit_read_pipe: 1484 case Builtin::BIwork_group_commit_write_pipe: 1485 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1486 return ExprError(); 1487 break; 1488 case Builtin::BIsub_group_commit_read_pipe: 1489 case Builtin::BIsub_group_commit_write_pipe: 1490 if (checkOpenCLSubgroupExt(*this, TheCall) || 1491 SemaBuiltinCommitRWPipe(*this, TheCall)) 1492 return ExprError(); 1493 break; 1494 case Builtin::BIget_pipe_num_packets: 1495 case Builtin::BIget_pipe_max_packets: 1496 if (SemaBuiltinPipePackets(*this, TheCall)) 1497 return ExprError(); 1498 break; 1499 case Builtin::BIto_global: 1500 case Builtin::BIto_local: 1501 case Builtin::BIto_private: 1502 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1503 return ExprError(); 1504 break; 1505 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1506 case Builtin::BIenqueue_kernel: 1507 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1508 return ExprError(); 1509 break; 1510 case Builtin::BIget_kernel_work_group_size: 1511 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1512 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1513 return ExprError(); 1514 break; 1515 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1516 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1517 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1518 return ExprError(); 1519 break; 1520 case Builtin::BI__builtin_os_log_format: 1521 case Builtin::BI__builtin_os_log_format_buffer_size: 1522 if (SemaBuiltinOSLogFormat(TheCall)) 1523 return ExprError(); 1524 break; 1525 } 1526 1527 // Since the target specific builtins for each arch overlap, only check those 1528 // of the arch we are compiling for. 1529 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1530 switch (Context.getTargetInfo().getTriple().getArch()) { 1531 case llvm::Triple::arm: 1532 case llvm::Triple::armeb: 1533 case llvm::Triple::thumb: 1534 case llvm::Triple::thumbeb: 1535 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1536 return ExprError(); 1537 break; 1538 case llvm::Triple::aarch64: 1539 case llvm::Triple::aarch64_32: 1540 case llvm::Triple::aarch64_be: 1541 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1542 return ExprError(); 1543 break; 1544 case llvm::Triple::bpfeb: 1545 case llvm::Triple::bpfel: 1546 if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall)) 1547 return ExprError(); 1548 break; 1549 case llvm::Triple::hexagon: 1550 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1551 return ExprError(); 1552 break; 1553 case llvm::Triple::mips: 1554 case llvm::Triple::mipsel: 1555 case llvm::Triple::mips64: 1556 case llvm::Triple::mips64el: 1557 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1558 return ExprError(); 1559 break; 1560 case llvm::Triple::systemz: 1561 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1562 return ExprError(); 1563 break; 1564 case llvm::Triple::x86: 1565 case llvm::Triple::x86_64: 1566 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1567 return ExprError(); 1568 break; 1569 case llvm::Triple::ppc: 1570 case llvm::Triple::ppc64: 1571 case llvm::Triple::ppc64le: 1572 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1573 return ExprError(); 1574 break; 1575 default: 1576 break; 1577 } 1578 } 1579 1580 return TheCallResult; 1581 } 1582 1583 // Get the valid immediate range for the specified NEON type code. 1584 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1585 NeonTypeFlags Type(t); 1586 int IsQuad = ForceQuad ? true : Type.isQuad(); 1587 switch (Type.getEltType()) { 1588 case NeonTypeFlags::Int8: 1589 case NeonTypeFlags::Poly8: 1590 return shift ? 7 : (8 << IsQuad) - 1; 1591 case NeonTypeFlags::Int16: 1592 case NeonTypeFlags::Poly16: 1593 return shift ? 15 : (4 << IsQuad) - 1; 1594 case NeonTypeFlags::Int32: 1595 return shift ? 31 : (2 << IsQuad) - 1; 1596 case NeonTypeFlags::Int64: 1597 case NeonTypeFlags::Poly64: 1598 return shift ? 63 : (1 << IsQuad) - 1; 1599 case NeonTypeFlags::Poly128: 1600 return shift ? 127 : (1 << IsQuad) - 1; 1601 case NeonTypeFlags::Float16: 1602 assert(!shift && "cannot shift float types!"); 1603 return (4 << IsQuad) - 1; 1604 case NeonTypeFlags::Float32: 1605 assert(!shift && "cannot shift float types!"); 1606 return (2 << IsQuad) - 1; 1607 case NeonTypeFlags::Float64: 1608 assert(!shift && "cannot shift float types!"); 1609 return (1 << IsQuad) - 1; 1610 } 1611 llvm_unreachable("Invalid NeonTypeFlag!"); 1612 } 1613 1614 /// getNeonEltType - Return the QualType corresponding to the elements of 1615 /// the vector type specified by the NeonTypeFlags. This is used to check 1616 /// the pointer arguments for Neon load/store intrinsics. 1617 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1618 bool IsPolyUnsigned, bool IsInt64Long) { 1619 switch (Flags.getEltType()) { 1620 case NeonTypeFlags::Int8: 1621 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1622 case NeonTypeFlags::Int16: 1623 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1624 case NeonTypeFlags::Int32: 1625 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1626 case NeonTypeFlags::Int64: 1627 if (IsInt64Long) 1628 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1629 else 1630 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1631 : Context.LongLongTy; 1632 case NeonTypeFlags::Poly8: 1633 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1634 case NeonTypeFlags::Poly16: 1635 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1636 case NeonTypeFlags::Poly64: 1637 if (IsInt64Long) 1638 return Context.UnsignedLongTy; 1639 else 1640 return Context.UnsignedLongLongTy; 1641 case NeonTypeFlags::Poly128: 1642 break; 1643 case NeonTypeFlags::Float16: 1644 return Context.HalfTy; 1645 case NeonTypeFlags::Float32: 1646 return Context.FloatTy; 1647 case NeonTypeFlags::Float64: 1648 return Context.DoubleTy; 1649 } 1650 llvm_unreachable("Invalid NeonTypeFlag!"); 1651 } 1652 1653 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1654 llvm::APSInt Result; 1655 uint64_t mask = 0; 1656 unsigned TV = 0; 1657 int PtrArgNum = -1; 1658 bool HasConstPtr = false; 1659 switch (BuiltinID) { 1660 #define GET_NEON_OVERLOAD_CHECK 1661 #include "clang/Basic/arm_neon.inc" 1662 #include "clang/Basic/arm_fp16.inc" 1663 #undef GET_NEON_OVERLOAD_CHECK 1664 } 1665 1666 // For NEON intrinsics which are overloaded on vector element type, validate 1667 // the immediate which specifies which variant to emit. 1668 unsigned ImmArg = TheCall->getNumArgs()-1; 1669 if (mask) { 1670 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1671 return true; 1672 1673 TV = Result.getLimitedValue(64); 1674 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1675 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1676 << TheCall->getArg(ImmArg)->getSourceRange(); 1677 } 1678 1679 if (PtrArgNum >= 0) { 1680 // Check that pointer arguments have the specified type. 1681 Expr *Arg = TheCall->getArg(PtrArgNum); 1682 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1683 Arg = ICE->getSubExpr(); 1684 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1685 QualType RHSTy = RHS.get()->getType(); 1686 1687 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1688 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1689 Arch == llvm::Triple::aarch64_32 || 1690 Arch == llvm::Triple::aarch64_be; 1691 bool IsInt64Long = 1692 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1693 QualType EltTy = 1694 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1695 if (HasConstPtr) 1696 EltTy = EltTy.withConst(); 1697 QualType LHSTy = Context.getPointerType(EltTy); 1698 AssignConvertType ConvTy; 1699 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1700 if (RHS.isInvalid()) 1701 return true; 1702 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1703 RHS.get(), AA_Assigning)) 1704 return true; 1705 } 1706 1707 // For NEON intrinsics which take an immediate value as part of the 1708 // instruction, range check them here. 1709 unsigned i = 0, l = 0, u = 0; 1710 switch (BuiltinID) { 1711 default: 1712 return false; 1713 #define GET_NEON_IMMEDIATE_CHECK 1714 #include "clang/Basic/arm_neon.inc" 1715 #include "clang/Basic/arm_fp16.inc" 1716 #undef GET_NEON_IMMEDIATE_CHECK 1717 } 1718 1719 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1720 } 1721 1722 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1723 switch (BuiltinID) { 1724 default: 1725 return false; 1726 #include "clang/Basic/arm_mve_builtin_sema.inc" 1727 } 1728 } 1729 1730 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1731 unsigned MaxWidth) { 1732 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1733 BuiltinID == ARM::BI__builtin_arm_ldaex || 1734 BuiltinID == ARM::BI__builtin_arm_strex || 1735 BuiltinID == ARM::BI__builtin_arm_stlex || 1736 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1737 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1738 BuiltinID == AArch64::BI__builtin_arm_strex || 1739 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1740 "unexpected ARM builtin"); 1741 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1742 BuiltinID == ARM::BI__builtin_arm_ldaex || 1743 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1744 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1745 1746 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1747 1748 // Ensure that we have the proper number of arguments. 1749 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1750 return true; 1751 1752 // Inspect the pointer argument of the atomic builtin. This should always be 1753 // a pointer type, whose element is an integral scalar or pointer type. 1754 // Because it is a pointer type, we don't have to worry about any implicit 1755 // casts here. 1756 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1757 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1758 if (PointerArgRes.isInvalid()) 1759 return true; 1760 PointerArg = PointerArgRes.get(); 1761 1762 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1763 if (!pointerType) { 1764 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1765 << PointerArg->getType() << PointerArg->getSourceRange(); 1766 return true; 1767 } 1768 1769 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1770 // task is to insert the appropriate casts into the AST. First work out just 1771 // what the appropriate type is. 1772 QualType ValType = pointerType->getPointeeType(); 1773 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1774 if (IsLdrex) 1775 AddrType.addConst(); 1776 1777 // Issue a warning if the cast is dodgy. 1778 CastKind CastNeeded = CK_NoOp; 1779 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1780 CastNeeded = CK_BitCast; 1781 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1782 << PointerArg->getType() << Context.getPointerType(AddrType) 1783 << AA_Passing << PointerArg->getSourceRange(); 1784 } 1785 1786 // Finally, do the cast and replace the argument with the corrected version. 1787 AddrType = Context.getPointerType(AddrType); 1788 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1789 if (PointerArgRes.isInvalid()) 1790 return true; 1791 PointerArg = PointerArgRes.get(); 1792 1793 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1794 1795 // In general, we allow ints, floats and pointers to be loaded and stored. 1796 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1797 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1798 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1799 << PointerArg->getType() << PointerArg->getSourceRange(); 1800 return true; 1801 } 1802 1803 // But ARM doesn't have instructions to deal with 128-bit versions. 1804 if (Context.getTypeSize(ValType) > MaxWidth) { 1805 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1806 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1807 << PointerArg->getType() << PointerArg->getSourceRange(); 1808 return true; 1809 } 1810 1811 switch (ValType.getObjCLifetime()) { 1812 case Qualifiers::OCL_None: 1813 case Qualifiers::OCL_ExplicitNone: 1814 // okay 1815 break; 1816 1817 case Qualifiers::OCL_Weak: 1818 case Qualifiers::OCL_Strong: 1819 case Qualifiers::OCL_Autoreleasing: 1820 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1821 << ValType << PointerArg->getSourceRange(); 1822 return true; 1823 } 1824 1825 if (IsLdrex) { 1826 TheCall->setType(ValType); 1827 return false; 1828 } 1829 1830 // Initialize the argument to be stored. 1831 ExprResult ValArg = TheCall->getArg(0); 1832 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1833 Context, ValType, /*consume*/ false); 1834 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1835 if (ValArg.isInvalid()) 1836 return true; 1837 TheCall->setArg(0, ValArg.get()); 1838 1839 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1840 // but the custom checker bypasses all default analysis. 1841 TheCall->setType(Context.IntTy); 1842 return false; 1843 } 1844 1845 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1846 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1847 BuiltinID == ARM::BI__builtin_arm_ldaex || 1848 BuiltinID == ARM::BI__builtin_arm_strex || 1849 BuiltinID == ARM::BI__builtin_arm_stlex) { 1850 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1851 } 1852 1853 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1854 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1855 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1856 } 1857 1858 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1859 BuiltinID == ARM::BI__builtin_arm_wsr64) 1860 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1861 1862 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1863 BuiltinID == ARM::BI__builtin_arm_rsrp || 1864 BuiltinID == ARM::BI__builtin_arm_wsr || 1865 BuiltinID == ARM::BI__builtin_arm_wsrp) 1866 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1867 1868 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1869 return true; 1870 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 1871 return true; 1872 1873 // For intrinsics which take an immediate value as part of the instruction, 1874 // range check them here. 1875 // FIXME: VFP Intrinsics should error if VFP not present. 1876 switch (BuiltinID) { 1877 default: return false; 1878 case ARM::BI__builtin_arm_ssat: 1879 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1880 case ARM::BI__builtin_arm_usat: 1881 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1882 case ARM::BI__builtin_arm_ssat16: 1883 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1884 case ARM::BI__builtin_arm_usat16: 1885 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1886 case ARM::BI__builtin_arm_vcvtr_f: 1887 case ARM::BI__builtin_arm_vcvtr_d: 1888 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1889 case ARM::BI__builtin_arm_dmb: 1890 case ARM::BI__builtin_arm_dsb: 1891 case ARM::BI__builtin_arm_isb: 1892 case ARM::BI__builtin_arm_dbg: 1893 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1894 } 1895 } 1896 1897 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1898 CallExpr *TheCall) { 1899 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1900 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1901 BuiltinID == AArch64::BI__builtin_arm_strex || 1902 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1903 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1904 } 1905 1906 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1907 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1908 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1909 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1910 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1911 } 1912 1913 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1914 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1915 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1916 1917 // Memory Tagging Extensions (MTE) Intrinsics 1918 if (BuiltinID == AArch64::BI__builtin_arm_irg || 1919 BuiltinID == AArch64::BI__builtin_arm_addg || 1920 BuiltinID == AArch64::BI__builtin_arm_gmi || 1921 BuiltinID == AArch64::BI__builtin_arm_ldg || 1922 BuiltinID == AArch64::BI__builtin_arm_stg || 1923 BuiltinID == AArch64::BI__builtin_arm_subp) { 1924 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 1925 } 1926 1927 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1928 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1929 BuiltinID == AArch64::BI__builtin_arm_wsr || 1930 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1931 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1932 1933 // Only check the valid encoding range. Any constant in this range would be 1934 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 1935 // an exception for incorrect registers. This matches MSVC behavior. 1936 if (BuiltinID == AArch64::BI_ReadStatusReg || 1937 BuiltinID == AArch64::BI_WriteStatusReg) 1938 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 1939 1940 if (BuiltinID == AArch64::BI__getReg) 1941 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1942 1943 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1944 return true; 1945 1946 // For intrinsics which take an immediate value as part of the instruction, 1947 // range check them here. 1948 unsigned i = 0, l = 0, u = 0; 1949 switch (BuiltinID) { 1950 default: return false; 1951 case AArch64::BI__builtin_arm_dmb: 1952 case AArch64::BI__builtin_arm_dsb: 1953 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1954 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 1955 } 1956 1957 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1958 } 1959 1960 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 1961 CallExpr *TheCall) { 1962 assert(BuiltinID == BPF::BI__builtin_preserve_field_info && 1963 "unexpected ARM builtin"); 1964 1965 if (checkArgCount(*this, TheCall, 2)) 1966 return true; 1967 1968 // The first argument needs to be a record field access. 1969 // If it is an array element access, we delay decision 1970 // to BPF backend to check whether the access is a 1971 // field access or not. 1972 Expr *Arg = TheCall->getArg(0); 1973 if (Arg->getType()->getAsPlaceholderType() || 1974 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 1975 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 1976 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 1977 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 1978 << 1 << Arg->getSourceRange(); 1979 return true; 1980 } 1981 1982 // The second argument needs to be a constant int 1983 llvm::APSInt Value; 1984 if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) { 1985 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 1986 << 2 << Arg->getSourceRange(); 1987 return true; 1988 } 1989 1990 TheCall->setType(Context.UnsignedIntTy); 1991 return false; 1992 } 1993 1994 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1995 struct BuiltinAndString { 1996 unsigned BuiltinID; 1997 const char *Str; 1998 }; 1999 2000 static BuiltinAndString ValidCPU[] = { 2001 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" }, 2002 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" }, 2003 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" }, 2004 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" }, 2005 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" }, 2006 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" }, 2007 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" }, 2008 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" }, 2009 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" }, 2010 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" }, 2011 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" }, 2012 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" }, 2013 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" }, 2014 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" }, 2015 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" }, 2016 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" }, 2017 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" }, 2018 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" }, 2019 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" }, 2020 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" }, 2021 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" }, 2022 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" }, 2023 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" }, 2024 }; 2025 2026 static BuiltinAndString ValidHVX[] = { 2027 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" }, 2526 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" }, 2527 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" }, 2528 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" }, 2529 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" }, 2530 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" }, 2531 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" }, 2532 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" }, 2533 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" }, 2534 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" }, 2535 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" }, 2536 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" }, 2537 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" }, 2538 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" }, 2539 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" }, 2540 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" }, 2541 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" }, 2542 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" }, 2543 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" }, 2544 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" }, 2545 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" }, 2546 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" }, 2547 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" }, 2548 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" }, 2549 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" }, 2550 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" }, 2551 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" }, 2552 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" }, 2553 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" }, 2554 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" }, 2555 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" }, 2556 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" }, 2557 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" }, 2558 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" }, 2559 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" }, 2560 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" }, 2561 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" }, 2562 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" }, 2563 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" }, 2564 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" }, 2565 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" }, 2566 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" }, 2567 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" }, 2568 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" }, 2569 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" }, 2570 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" }, 2571 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" }, 2572 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" }, 2573 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" }, 2574 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" }, 2575 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" }, 2576 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" }, 2577 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" }, 2578 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" }, 2579 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" }, 2580 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" }, 2581 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" }, 2582 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" }, 2583 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" }, 2584 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" }, 2585 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" }, 2586 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" }, 2587 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" }, 2588 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" }, 2589 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" }, 2590 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" }, 2591 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" }, 2592 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" }, 2593 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" }, 2594 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" }, 2595 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, 2596 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, 2597 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, 2598 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, 2599 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" }, 2600 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" }, 2601 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" }, 2602 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" }, 2603 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" }, 2604 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" }, 2605 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" }, 2606 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" }, 2607 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" }, 2608 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" }, 2609 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" }, 2610 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" }, 2611 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" }, 2612 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" }, 2613 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" }, 2614 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" }, 2615 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" }, 2616 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" }, 2617 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" }, 2618 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" }, 2619 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" }, 2620 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" }, 2621 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" }, 2622 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" }, 2623 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, 2624 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, 2625 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, 2626 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, 2627 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" }, 2628 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" }, 2629 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" }, 2630 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" }, 2631 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" }, 2632 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" }, 2633 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" }, 2634 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" }, 2635 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" }, 2636 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" }, 2637 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" }, 2638 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" }, 2639 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" }, 2640 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" }, 2641 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" }, 2642 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" }, 2643 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" }, 2644 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" }, 2645 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" }, 2646 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" }, 2647 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" }, 2648 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" }, 2649 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" }, 2650 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" }, 2651 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" }, 2652 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" }, 2653 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" }, 2654 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" }, 2655 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" }, 2656 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" }, 2657 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" }, 2658 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" }, 2659 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" }, 2660 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" }, 2661 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" }, 2662 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" }, 2663 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" }, 2664 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" }, 2665 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" }, 2666 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" }, 2667 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" }, 2668 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" }, 2669 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" }, 2670 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" }, 2671 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" }, 2672 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" }, 2673 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" }, 2674 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" }, 2675 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" }, 2676 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" }, 2677 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" }, 2678 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" }, 2679 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" }, 2680 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" }, 2681 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" }, 2682 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" }, 2683 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" }, 2684 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" }, 2685 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" }, 2686 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" }, 2687 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" }, 2688 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" }, 2689 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" }, 2690 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" }, 2691 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" }, 2692 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" }, 2693 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" }, 2694 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" }, 2695 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" }, 2696 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" }, 2697 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" }, 2698 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" }, 2699 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" }, 2700 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" }, 2701 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" }, 2702 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" }, 2703 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" }, 2704 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" }, 2705 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" }, 2706 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" }, 2707 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" }, 2708 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" }, 2709 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" }, 2710 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" }, 2711 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" }, 2712 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" }, 2713 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" }, 2714 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" }, 2715 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" }, 2716 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" }, 2717 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" }, 2718 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" }, 2719 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" }, 2720 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" }, 2721 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" }, 2722 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" }, 2723 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" }, 2724 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" }, 2725 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" }, 2726 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" }, 2727 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" }, 2728 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" }, 2729 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" }, 2730 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" }, 2731 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" }, 2732 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" }, 2733 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" }, 2734 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" }, 2735 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" }, 2736 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" }, 2737 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" }, 2738 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" }, 2739 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" }, 2740 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" }, 2741 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" }, 2742 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" }, 2743 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" }, 2744 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" }, 2745 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" }, 2746 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" }, 2747 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" }, 2748 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" }, 2749 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" }, 2750 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" }, 2751 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" }, 2752 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" }, 2753 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" }, 2754 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" }, 2755 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" }, 2756 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" }, 2757 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" }, 2758 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" }, 2759 }; 2760 2761 // Sort the tables on first execution so we can binary search them. 2762 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { 2763 return LHS.BuiltinID < RHS.BuiltinID; 2764 }; 2765 static const bool SortOnce = 2766 (llvm::sort(ValidCPU, SortCmp), 2767 llvm::sort(ValidHVX, SortCmp), true); 2768 (void)SortOnce; 2769 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { 2770 return BI.BuiltinID < BuiltinID; 2771 }; 2772 2773 const TargetInfo &TI = Context.getTargetInfo(); 2774 2775 const BuiltinAndString *FC = 2776 llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp); 2777 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { 2778 const TargetOptions &Opts = TI.getTargetOpts(); 2779 StringRef CPU = Opts.CPU; 2780 if (!CPU.empty()) { 2781 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2782 CPU.consume_front("hexagon"); 2783 SmallVector<StringRef, 3> CPUs; 2784 StringRef(FC->Str).split(CPUs, ','); 2785 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) 2786 return Diag(TheCall->getBeginLoc(), 2787 diag::err_hexagon_builtin_unsupported_cpu); 2788 } 2789 } 2790 2791 const BuiltinAndString *FH = 2792 llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp); 2793 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { 2794 if (!TI.hasFeature("hvx")) 2795 return Diag(TheCall->getBeginLoc(), 2796 diag::err_hexagon_builtin_requires_hvx); 2797 2798 SmallVector<StringRef, 3> HVXs; 2799 StringRef(FH->Str).split(HVXs, ','); 2800 bool IsValid = llvm::any_of(HVXs, 2801 [&TI] (StringRef V) { 2802 std::string F = "hvx" + V.str(); 2803 return TI.hasFeature(F); 2804 }); 2805 if (!IsValid) 2806 return Diag(TheCall->getBeginLoc(), 2807 diag::err_hexagon_builtin_unsupported_hvx); 2808 } 2809 2810 return false; 2811 } 2812 2813 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2814 struct ArgInfo { 2815 uint8_t OpNum; 2816 bool IsSigned; 2817 uint8_t BitWidth; 2818 uint8_t Align; 2819 }; 2820 struct BuiltinInfo { 2821 unsigned BuiltinID; 2822 ArgInfo Infos[2]; 2823 }; 2824 2825 static BuiltinInfo Infos[] = { 2826 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2827 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2828 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2829 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2830 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2831 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2832 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2833 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2834 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2835 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2836 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2837 2838 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2849 2850 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2902 {{ 1, false, 6, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2910 {{ 1, false, 5, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2917 { 2, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2919 { 2, false, 6, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2921 { 3, false, 5, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2923 { 3, false, 6, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2940 {{ 2, false, 4, 0 }, 2941 { 3, false, 5, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2943 {{ 2, false, 4, 0 }, 2944 { 3, false, 5, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2946 {{ 2, false, 4, 0 }, 2947 { 3, false, 5, 0 }} }, 2948 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2949 {{ 2, false, 4, 0 }, 2950 { 3, false, 5, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2953 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2955 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2956 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2957 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2958 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2959 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2960 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2961 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2962 { 2, false, 5, 0 }} }, 2963 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2964 { 2, false, 6, 0 }} }, 2965 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2966 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2967 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2968 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2969 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2970 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2971 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2972 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2973 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2974 {{ 1, false, 4, 0 }} }, 2975 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2976 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2977 {{ 1, false, 4, 0 }} }, 2978 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2979 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2980 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2981 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2982 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2983 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2984 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2985 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2986 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2987 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2988 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2989 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2990 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2991 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2992 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2993 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2994 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2995 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2996 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2997 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2998 {{ 3, false, 1, 0 }} }, 2999 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 3000 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 3001 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 3002 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 3003 {{ 3, false, 1, 0 }} }, 3004 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 3005 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 3006 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 3007 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 3008 {{ 3, false, 1, 0 }} }, 3009 }; 3010 3011 // Use a dynamically initialized static to sort the table exactly once on 3012 // first run. 3013 static const bool SortOnce = 3014 (llvm::sort(Infos, 3015 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 3016 return LHS.BuiltinID < RHS.BuiltinID; 3017 }), 3018 true); 3019 (void)SortOnce; 3020 3021 const BuiltinInfo *F = llvm::partition_point( 3022 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 3023 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 3024 return false; 3025 3026 bool Error = false; 3027 3028 for (const ArgInfo &A : F->Infos) { 3029 // Ignore empty ArgInfo elements. 3030 if (A.BitWidth == 0) 3031 continue; 3032 3033 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 3034 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 3035 if (!A.Align) { 3036 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3037 } else { 3038 unsigned M = 1 << A.Align; 3039 Min *= M; 3040 Max *= M; 3041 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 3042 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 3043 } 3044 } 3045 return Error; 3046 } 3047 3048 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3049 CallExpr *TheCall) { 3050 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 3051 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3052 } 3053 3054 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3055 return CheckMipsBuiltinCpu(BuiltinID, TheCall) || 3056 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3057 } 3058 3059 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 3060 const TargetInfo &TI = Context.getTargetInfo(); 3061 3062 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3063 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3064 if (!TI.hasFeature("dsp")) 3065 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3066 } 3067 3068 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3069 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3070 if (!TI.hasFeature("dspr2")) 3071 return Diag(TheCall->getBeginLoc(), 3072 diag::err_mips_builtin_requires_dspr2); 3073 } 3074 3075 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3076 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3077 if (!TI.hasFeature("msa")) 3078 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3079 } 3080 3081 return false; 3082 } 3083 3084 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3085 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3086 // ordering for DSP is unspecified. MSA is ordered by the data format used 3087 // by the underlying instruction i.e., df/m, df/n and then by size. 3088 // 3089 // FIXME: The size tests here should instead be tablegen'd along with the 3090 // definitions from include/clang/Basic/BuiltinsMips.def. 3091 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3092 // be too. 3093 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3094 unsigned i = 0, l = 0, u = 0, m = 0; 3095 switch (BuiltinID) { 3096 default: return false; 3097 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3098 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3099 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3100 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3101 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3102 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3103 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3104 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3105 // df/m field. 3106 // These intrinsics take an unsigned 3 bit immediate. 3107 case Mips::BI__builtin_msa_bclri_b: 3108 case Mips::BI__builtin_msa_bnegi_b: 3109 case Mips::BI__builtin_msa_bseti_b: 3110 case Mips::BI__builtin_msa_sat_s_b: 3111 case Mips::BI__builtin_msa_sat_u_b: 3112 case Mips::BI__builtin_msa_slli_b: 3113 case Mips::BI__builtin_msa_srai_b: 3114 case Mips::BI__builtin_msa_srari_b: 3115 case Mips::BI__builtin_msa_srli_b: 3116 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3117 case Mips::BI__builtin_msa_binsli_b: 3118 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3119 // These intrinsics take an unsigned 4 bit immediate. 3120 case Mips::BI__builtin_msa_bclri_h: 3121 case Mips::BI__builtin_msa_bnegi_h: 3122 case Mips::BI__builtin_msa_bseti_h: 3123 case Mips::BI__builtin_msa_sat_s_h: 3124 case Mips::BI__builtin_msa_sat_u_h: 3125 case Mips::BI__builtin_msa_slli_h: 3126 case Mips::BI__builtin_msa_srai_h: 3127 case Mips::BI__builtin_msa_srari_h: 3128 case Mips::BI__builtin_msa_srli_h: 3129 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3130 case Mips::BI__builtin_msa_binsli_h: 3131 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3132 // These intrinsics take an unsigned 5 bit immediate. 3133 // The first block of intrinsics actually have an unsigned 5 bit field, 3134 // not a df/n field. 3135 case Mips::BI__builtin_msa_cfcmsa: 3136 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3137 case Mips::BI__builtin_msa_clei_u_b: 3138 case Mips::BI__builtin_msa_clei_u_h: 3139 case Mips::BI__builtin_msa_clei_u_w: 3140 case Mips::BI__builtin_msa_clei_u_d: 3141 case Mips::BI__builtin_msa_clti_u_b: 3142 case Mips::BI__builtin_msa_clti_u_h: 3143 case Mips::BI__builtin_msa_clti_u_w: 3144 case Mips::BI__builtin_msa_clti_u_d: 3145 case Mips::BI__builtin_msa_maxi_u_b: 3146 case Mips::BI__builtin_msa_maxi_u_h: 3147 case Mips::BI__builtin_msa_maxi_u_w: 3148 case Mips::BI__builtin_msa_maxi_u_d: 3149 case Mips::BI__builtin_msa_mini_u_b: 3150 case Mips::BI__builtin_msa_mini_u_h: 3151 case Mips::BI__builtin_msa_mini_u_w: 3152 case Mips::BI__builtin_msa_mini_u_d: 3153 case Mips::BI__builtin_msa_addvi_b: 3154 case Mips::BI__builtin_msa_addvi_h: 3155 case Mips::BI__builtin_msa_addvi_w: 3156 case Mips::BI__builtin_msa_addvi_d: 3157 case Mips::BI__builtin_msa_bclri_w: 3158 case Mips::BI__builtin_msa_bnegi_w: 3159 case Mips::BI__builtin_msa_bseti_w: 3160 case Mips::BI__builtin_msa_sat_s_w: 3161 case Mips::BI__builtin_msa_sat_u_w: 3162 case Mips::BI__builtin_msa_slli_w: 3163 case Mips::BI__builtin_msa_srai_w: 3164 case Mips::BI__builtin_msa_srari_w: 3165 case Mips::BI__builtin_msa_srli_w: 3166 case Mips::BI__builtin_msa_srlri_w: 3167 case Mips::BI__builtin_msa_subvi_b: 3168 case Mips::BI__builtin_msa_subvi_h: 3169 case Mips::BI__builtin_msa_subvi_w: 3170 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3171 case Mips::BI__builtin_msa_binsli_w: 3172 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3173 // These intrinsics take an unsigned 6 bit immediate. 3174 case Mips::BI__builtin_msa_bclri_d: 3175 case Mips::BI__builtin_msa_bnegi_d: 3176 case Mips::BI__builtin_msa_bseti_d: 3177 case Mips::BI__builtin_msa_sat_s_d: 3178 case Mips::BI__builtin_msa_sat_u_d: 3179 case Mips::BI__builtin_msa_slli_d: 3180 case Mips::BI__builtin_msa_srai_d: 3181 case Mips::BI__builtin_msa_srari_d: 3182 case Mips::BI__builtin_msa_srli_d: 3183 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3184 case Mips::BI__builtin_msa_binsli_d: 3185 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3186 // These intrinsics take a signed 5 bit immediate. 3187 case Mips::BI__builtin_msa_ceqi_b: 3188 case Mips::BI__builtin_msa_ceqi_h: 3189 case Mips::BI__builtin_msa_ceqi_w: 3190 case Mips::BI__builtin_msa_ceqi_d: 3191 case Mips::BI__builtin_msa_clti_s_b: 3192 case Mips::BI__builtin_msa_clti_s_h: 3193 case Mips::BI__builtin_msa_clti_s_w: 3194 case Mips::BI__builtin_msa_clti_s_d: 3195 case Mips::BI__builtin_msa_clei_s_b: 3196 case Mips::BI__builtin_msa_clei_s_h: 3197 case Mips::BI__builtin_msa_clei_s_w: 3198 case Mips::BI__builtin_msa_clei_s_d: 3199 case Mips::BI__builtin_msa_maxi_s_b: 3200 case Mips::BI__builtin_msa_maxi_s_h: 3201 case Mips::BI__builtin_msa_maxi_s_w: 3202 case Mips::BI__builtin_msa_maxi_s_d: 3203 case Mips::BI__builtin_msa_mini_s_b: 3204 case Mips::BI__builtin_msa_mini_s_h: 3205 case Mips::BI__builtin_msa_mini_s_w: 3206 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3207 // These intrinsics take an unsigned 8 bit immediate. 3208 case Mips::BI__builtin_msa_andi_b: 3209 case Mips::BI__builtin_msa_nori_b: 3210 case Mips::BI__builtin_msa_ori_b: 3211 case Mips::BI__builtin_msa_shf_b: 3212 case Mips::BI__builtin_msa_shf_h: 3213 case Mips::BI__builtin_msa_shf_w: 3214 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3215 case Mips::BI__builtin_msa_bseli_b: 3216 case Mips::BI__builtin_msa_bmnzi_b: 3217 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3218 // df/n format 3219 // These intrinsics take an unsigned 4 bit immediate. 3220 case Mips::BI__builtin_msa_copy_s_b: 3221 case Mips::BI__builtin_msa_copy_u_b: 3222 case Mips::BI__builtin_msa_insve_b: 3223 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3224 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3225 // These intrinsics take an unsigned 3 bit immediate. 3226 case Mips::BI__builtin_msa_copy_s_h: 3227 case Mips::BI__builtin_msa_copy_u_h: 3228 case Mips::BI__builtin_msa_insve_h: 3229 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3230 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3231 // These intrinsics take an unsigned 2 bit immediate. 3232 case Mips::BI__builtin_msa_copy_s_w: 3233 case Mips::BI__builtin_msa_copy_u_w: 3234 case Mips::BI__builtin_msa_insve_w: 3235 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3236 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3237 // These intrinsics take an unsigned 1 bit immediate. 3238 case Mips::BI__builtin_msa_copy_s_d: 3239 case Mips::BI__builtin_msa_copy_u_d: 3240 case Mips::BI__builtin_msa_insve_d: 3241 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3242 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3243 // Memory offsets and immediate loads. 3244 // These intrinsics take a signed 10 bit immediate. 3245 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3246 case Mips::BI__builtin_msa_ldi_h: 3247 case Mips::BI__builtin_msa_ldi_w: 3248 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3249 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3250 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3251 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3252 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3253 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3254 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3255 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3256 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3257 } 3258 3259 if (!m) 3260 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3261 3262 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3263 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3264 } 3265 3266 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3267 unsigned i = 0, l = 0, u = 0; 3268 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3269 BuiltinID == PPC::BI__builtin_divdeu || 3270 BuiltinID == PPC::BI__builtin_bpermd; 3271 bool IsTarget64Bit = Context.getTargetInfo() 3272 .getTypeWidth(Context 3273 .getTargetInfo() 3274 .getIntPtrType()) == 64; 3275 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3276 BuiltinID == PPC::BI__builtin_divweu || 3277 BuiltinID == PPC::BI__builtin_divde || 3278 BuiltinID == PPC::BI__builtin_divdeu; 3279 3280 if (Is64BitBltin && !IsTarget64Bit) 3281 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3282 << TheCall->getSourceRange(); 3283 3284 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 3285 (BuiltinID == PPC::BI__builtin_bpermd && 3286 !Context.getTargetInfo().hasFeature("bpermd"))) 3287 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3288 << TheCall->getSourceRange(); 3289 3290 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3291 if (!Context.getTargetInfo().hasFeature("vsx")) 3292 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3293 << TheCall->getSourceRange(); 3294 return false; 3295 }; 3296 3297 switch (BuiltinID) { 3298 default: return false; 3299 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3300 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3301 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3302 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3303 case PPC::BI__builtin_altivec_dss: 3304 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3305 case PPC::BI__builtin_tbegin: 3306 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3307 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3308 case PPC::BI__builtin_tabortwc: 3309 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3310 case PPC::BI__builtin_tabortwci: 3311 case PPC::BI__builtin_tabortdci: 3312 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3313 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3314 case PPC::BI__builtin_altivec_dst: 3315 case PPC::BI__builtin_altivec_dstt: 3316 case PPC::BI__builtin_altivec_dstst: 3317 case PPC::BI__builtin_altivec_dststt: 3318 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3319 case PPC::BI__builtin_vsx_xxpermdi: 3320 case PPC::BI__builtin_vsx_xxsldwi: 3321 return SemaBuiltinVSX(TheCall); 3322 case PPC::BI__builtin_unpack_vector_int128: 3323 return SemaVSXCheck(TheCall) || 3324 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3325 case PPC::BI__builtin_pack_vector_int128: 3326 return SemaVSXCheck(TheCall); 3327 } 3328 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3329 } 3330 3331 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3332 CallExpr *TheCall) { 3333 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3334 Expr *Arg = TheCall->getArg(0); 3335 llvm::APSInt AbortCode(32); 3336 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3337 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3338 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3339 << Arg->getSourceRange(); 3340 } 3341 3342 // For intrinsics which take an immediate value as part of the instruction, 3343 // range check them here. 3344 unsigned i = 0, l = 0, u = 0; 3345 switch (BuiltinID) { 3346 default: return false; 3347 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3348 case SystemZ::BI__builtin_s390_verimb: 3349 case SystemZ::BI__builtin_s390_verimh: 3350 case SystemZ::BI__builtin_s390_verimf: 3351 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3352 case SystemZ::BI__builtin_s390_vfaeb: 3353 case SystemZ::BI__builtin_s390_vfaeh: 3354 case SystemZ::BI__builtin_s390_vfaef: 3355 case SystemZ::BI__builtin_s390_vfaebs: 3356 case SystemZ::BI__builtin_s390_vfaehs: 3357 case SystemZ::BI__builtin_s390_vfaefs: 3358 case SystemZ::BI__builtin_s390_vfaezb: 3359 case SystemZ::BI__builtin_s390_vfaezh: 3360 case SystemZ::BI__builtin_s390_vfaezf: 3361 case SystemZ::BI__builtin_s390_vfaezbs: 3362 case SystemZ::BI__builtin_s390_vfaezhs: 3363 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3364 case SystemZ::BI__builtin_s390_vfisb: 3365 case SystemZ::BI__builtin_s390_vfidb: 3366 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3367 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3368 case SystemZ::BI__builtin_s390_vftcisb: 3369 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3370 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3371 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3372 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3373 case SystemZ::BI__builtin_s390_vstrcb: 3374 case SystemZ::BI__builtin_s390_vstrch: 3375 case SystemZ::BI__builtin_s390_vstrcf: 3376 case SystemZ::BI__builtin_s390_vstrczb: 3377 case SystemZ::BI__builtin_s390_vstrczh: 3378 case SystemZ::BI__builtin_s390_vstrczf: 3379 case SystemZ::BI__builtin_s390_vstrcbs: 3380 case SystemZ::BI__builtin_s390_vstrchs: 3381 case SystemZ::BI__builtin_s390_vstrcfs: 3382 case SystemZ::BI__builtin_s390_vstrczbs: 3383 case SystemZ::BI__builtin_s390_vstrczhs: 3384 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3385 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3386 case SystemZ::BI__builtin_s390_vfminsb: 3387 case SystemZ::BI__builtin_s390_vfmaxsb: 3388 case SystemZ::BI__builtin_s390_vfmindb: 3389 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3390 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3391 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3392 } 3393 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3394 } 3395 3396 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3397 /// This checks that the target supports __builtin_cpu_supports and 3398 /// that the string argument is constant and valid. 3399 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3400 Expr *Arg = TheCall->getArg(0); 3401 3402 // Check if the argument is a string literal. 3403 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3404 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3405 << Arg->getSourceRange(); 3406 3407 // Check the contents of the string. 3408 StringRef Feature = 3409 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3410 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3411 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3412 << Arg->getSourceRange(); 3413 return false; 3414 } 3415 3416 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3417 /// This checks that the target supports __builtin_cpu_is and 3418 /// that the string argument is constant and valid. 3419 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3420 Expr *Arg = TheCall->getArg(0); 3421 3422 // Check if the argument is a string literal. 3423 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3424 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3425 << Arg->getSourceRange(); 3426 3427 // Check the contents of the string. 3428 StringRef Feature = 3429 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3430 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3431 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3432 << Arg->getSourceRange(); 3433 return false; 3434 } 3435 3436 // Check if the rounding mode is legal. 3437 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3438 // Indicates if this instruction has rounding control or just SAE. 3439 bool HasRC = false; 3440 3441 unsigned ArgNum = 0; 3442 switch (BuiltinID) { 3443 default: 3444 return false; 3445 case X86::BI__builtin_ia32_vcvttsd2si32: 3446 case X86::BI__builtin_ia32_vcvttsd2si64: 3447 case X86::BI__builtin_ia32_vcvttsd2usi32: 3448 case X86::BI__builtin_ia32_vcvttsd2usi64: 3449 case X86::BI__builtin_ia32_vcvttss2si32: 3450 case X86::BI__builtin_ia32_vcvttss2si64: 3451 case X86::BI__builtin_ia32_vcvttss2usi32: 3452 case X86::BI__builtin_ia32_vcvttss2usi64: 3453 ArgNum = 1; 3454 break; 3455 case X86::BI__builtin_ia32_maxpd512: 3456 case X86::BI__builtin_ia32_maxps512: 3457 case X86::BI__builtin_ia32_minpd512: 3458 case X86::BI__builtin_ia32_minps512: 3459 ArgNum = 2; 3460 break; 3461 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3462 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3463 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3464 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3465 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3466 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3467 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3468 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3469 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3470 case X86::BI__builtin_ia32_exp2pd_mask: 3471 case X86::BI__builtin_ia32_exp2ps_mask: 3472 case X86::BI__builtin_ia32_getexppd512_mask: 3473 case X86::BI__builtin_ia32_getexpps512_mask: 3474 case X86::BI__builtin_ia32_rcp28pd_mask: 3475 case X86::BI__builtin_ia32_rcp28ps_mask: 3476 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3477 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3478 case X86::BI__builtin_ia32_vcomisd: 3479 case X86::BI__builtin_ia32_vcomiss: 3480 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3481 ArgNum = 3; 3482 break; 3483 case X86::BI__builtin_ia32_cmppd512_mask: 3484 case X86::BI__builtin_ia32_cmpps512_mask: 3485 case X86::BI__builtin_ia32_cmpsd_mask: 3486 case X86::BI__builtin_ia32_cmpss_mask: 3487 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3488 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3489 case X86::BI__builtin_ia32_getexpss128_round_mask: 3490 case X86::BI__builtin_ia32_getmantpd512_mask: 3491 case X86::BI__builtin_ia32_getmantps512_mask: 3492 case X86::BI__builtin_ia32_maxsd_round_mask: 3493 case X86::BI__builtin_ia32_maxss_round_mask: 3494 case X86::BI__builtin_ia32_minsd_round_mask: 3495 case X86::BI__builtin_ia32_minss_round_mask: 3496 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3497 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3498 case X86::BI__builtin_ia32_reducepd512_mask: 3499 case X86::BI__builtin_ia32_reduceps512_mask: 3500 case X86::BI__builtin_ia32_rndscalepd_mask: 3501 case X86::BI__builtin_ia32_rndscaleps_mask: 3502 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3503 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3504 ArgNum = 4; 3505 break; 3506 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3507 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3508 case X86::BI__builtin_ia32_fixupimmps512_mask: 3509 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3510 case X86::BI__builtin_ia32_fixupimmsd_mask: 3511 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3512 case X86::BI__builtin_ia32_fixupimmss_mask: 3513 case X86::BI__builtin_ia32_fixupimmss_maskz: 3514 case X86::BI__builtin_ia32_getmantsd_round_mask: 3515 case X86::BI__builtin_ia32_getmantss_round_mask: 3516 case X86::BI__builtin_ia32_rangepd512_mask: 3517 case X86::BI__builtin_ia32_rangeps512_mask: 3518 case X86::BI__builtin_ia32_rangesd128_round_mask: 3519 case X86::BI__builtin_ia32_rangess128_round_mask: 3520 case X86::BI__builtin_ia32_reducesd_mask: 3521 case X86::BI__builtin_ia32_reducess_mask: 3522 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3523 case X86::BI__builtin_ia32_rndscaless_round_mask: 3524 ArgNum = 5; 3525 break; 3526 case X86::BI__builtin_ia32_vcvtsd2si64: 3527 case X86::BI__builtin_ia32_vcvtsd2si32: 3528 case X86::BI__builtin_ia32_vcvtsd2usi32: 3529 case X86::BI__builtin_ia32_vcvtsd2usi64: 3530 case X86::BI__builtin_ia32_vcvtss2si32: 3531 case X86::BI__builtin_ia32_vcvtss2si64: 3532 case X86::BI__builtin_ia32_vcvtss2usi32: 3533 case X86::BI__builtin_ia32_vcvtss2usi64: 3534 case X86::BI__builtin_ia32_sqrtpd512: 3535 case X86::BI__builtin_ia32_sqrtps512: 3536 ArgNum = 1; 3537 HasRC = true; 3538 break; 3539 case X86::BI__builtin_ia32_addpd512: 3540 case X86::BI__builtin_ia32_addps512: 3541 case X86::BI__builtin_ia32_divpd512: 3542 case X86::BI__builtin_ia32_divps512: 3543 case X86::BI__builtin_ia32_mulpd512: 3544 case X86::BI__builtin_ia32_mulps512: 3545 case X86::BI__builtin_ia32_subpd512: 3546 case X86::BI__builtin_ia32_subps512: 3547 case X86::BI__builtin_ia32_cvtsi2sd64: 3548 case X86::BI__builtin_ia32_cvtsi2ss32: 3549 case X86::BI__builtin_ia32_cvtsi2ss64: 3550 case X86::BI__builtin_ia32_cvtusi2sd64: 3551 case X86::BI__builtin_ia32_cvtusi2ss32: 3552 case X86::BI__builtin_ia32_cvtusi2ss64: 3553 ArgNum = 2; 3554 HasRC = true; 3555 break; 3556 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3557 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3558 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3559 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3560 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3561 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3562 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3563 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3564 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3565 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3566 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3567 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3568 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3569 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3570 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3571 ArgNum = 3; 3572 HasRC = true; 3573 break; 3574 case X86::BI__builtin_ia32_addss_round_mask: 3575 case X86::BI__builtin_ia32_addsd_round_mask: 3576 case X86::BI__builtin_ia32_divss_round_mask: 3577 case X86::BI__builtin_ia32_divsd_round_mask: 3578 case X86::BI__builtin_ia32_mulss_round_mask: 3579 case X86::BI__builtin_ia32_mulsd_round_mask: 3580 case X86::BI__builtin_ia32_subss_round_mask: 3581 case X86::BI__builtin_ia32_subsd_round_mask: 3582 case X86::BI__builtin_ia32_scalefpd512_mask: 3583 case X86::BI__builtin_ia32_scalefps512_mask: 3584 case X86::BI__builtin_ia32_scalefsd_round_mask: 3585 case X86::BI__builtin_ia32_scalefss_round_mask: 3586 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3587 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3588 case X86::BI__builtin_ia32_sqrtss_round_mask: 3589 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3590 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3591 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3592 case X86::BI__builtin_ia32_vfmaddss3_mask: 3593 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3594 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3595 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3596 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3597 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3598 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3599 case X86::BI__builtin_ia32_vfmaddps512_mask: 3600 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3601 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3602 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3603 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3604 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3605 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3606 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3607 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3608 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3609 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3610 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3611 ArgNum = 4; 3612 HasRC = true; 3613 break; 3614 } 3615 3616 llvm::APSInt Result; 3617 3618 // We can't check the value of a dependent argument. 3619 Expr *Arg = TheCall->getArg(ArgNum); 3620 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3621 return false; 3622 3623 // Check constant-ness first. 3624 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3625 return true; 3626 3627 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3628 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3629 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3630 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3631 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3632 Result == 8/*ROUND_NO_EXC*/ || 3633 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3634 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3635 return false; 3636 3637 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3638 << Arg->getSourceRange(); 3639 } 3640 3641 // Check if the gather/scatter scale is legal. 3642 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3643 CallExpr *TheCall) { 3644 unsigned ArgNum = 0; 3645 switch (BuiltinID) { 3646 default: 3647 return false; 3648 case X86::BI__builtin_ia32_gatherpfdpd: 3649 case X86::BI__builtin_ia32_gatherpfdps: 3650 case X86::BI__builtin_ia32_gatherpfqpd: 3651 case X86::BI__builtin_ia32_gatherpfqps: 3652 case X86::BI__builtin_ia32_scatterpfdpd: 3653 case X86::BI__builtin_ia32_scatterpfdps: 3654 case X86::BI__builtin_ia32_scatterpfqpd: 3655 case X86::BI__builtin_ia32_scatterpfqps: 3656 ArgNum = 3; 3657 break; 3658 case X86::BI__builtin_ia32_gatherd_pd: 3659 case X86::BI__builtin_ia32_gatherd_pd256: 3660 case X86::BI__builtin_ia32_gatherq_pd: 3661 case X86::BI__builtin_ia32_gatherq_pd256: 3662 case X86::BI__builtin_ia32_gatherd_ps: 3663 case X86::BI__builtin_ia32_gatherd_ps256: 3664 case X86::BI__builtin_ia32_gatherq_ps: 3665 case X86::BI__builtin_ia32_gatherq_ps256: 3666 case X86::BI__builtin_ia32_gatherd_q: 3667 case X86::BI__builtin_ia32_gatherd_q256: 3668 case X86::BI__builtin_ia32_gatherq_q: 3669 case X86::BI__builtin_ia32_gatherq_q256: 3670 case X86::BI__builtin_ia32_gatherd_d: 3671 case X86::BI__builtin_ia32_gatherd_d256: 3672 case X86::BI__builtin_ia32_gatherq_d: 3673 case X86::BI__builtin_ia32_gatherq_d256: 3674 case X86::BI__builtin_ia32_gather3div2df: 3675 case X86::BI__builtin_ia32_gather3div2di: 3676 case X86::BI__builtin_ia32_gather3div4df: 3677 case X86::BI__builtin_ia32_gather3div4di: 3678 case X86::BI__builtin_ia32_gather3div4sf: 3679 case X86::BI__builtin_ia32_gather3div4si: 3680 case X86::BI__builtin_ia32_gather3div8sf: 3681 case X86::BI__builtin_ia32_gather3div8si: 3682 case X86::BI__builtin_ia32_gather3siv2df: 3683 case X86::BI__builtin_ia32_gather3siv2di: 3684 case X86::BI__builtin_ia32_gather3siv4df: 3685 case X86::BI__builtin_ia32_gather3siv4di: 3686 case X86::BI__builtin_ia32_gather3siv4sf: 3687 case X86::BI__builtin_ia32_gather3siv4si: 3688 case X86::BI__builtin_ia32_gather3siv8sf: 3689 case X86::BI__builtin_ia32_gather3siv8si: 3690 case X86::BI__builtin_ia32_gathersiv8df: 3691 case X86::BI__builtin_ia32_gathersiv16sf: 3692 case X86::BI__builtin_ia32_gatherdiv8df: 3693 case X86::BI__builtin_ia32_gatherdiv16sf: 3694 case X86::BI__builtin_ia32_gathersiv8di: 3695 case X86::BI__builtin_ia32_gathersiv16si: 3696 case X86::BI__builtin_ia32_gatherdiv8di: 3697 case X86::BI__builtin_ia32_gatherdiv16si: 3698 case X86::BI__builtin_ia32_scatterdiv2df: 3699 case X86::BI__builtin_ia32_scatterdiv2di: 3700 case X86::BI__builtin_ia32_scatterdiv4df: 3701 case X86::BI__builtin_ia32_scatterdiv4di: 3702 case X86::BI__builtin_ia32_scatterdiv4sf: 3703 case X86::BI__builtin_ia32_scatterdiv4si: 3704 case X86::BI__builtin_ia32_scatterdiv8sf: 3705 case X86::BI__builtin_ia32_scatterdiv8si: 3706 case X86::BI__builtin_ia32_scattersiv2df: 3707 case X86::BI__builtin_ia32_scattersiv2di: 3708 case X86::BI__builtin_ia32_scattersiv4df: 3709 case X86::BI__builtin_ia32_scattersiv4di: 3710 case X86::BI__builtin_ia32_scattersiv4sf: 3711 case X86::BI__builtin_ia32_scattersiv4si: 3712 case X86::BI__builtin_ia32_scattersiv8sf: 3713 case X86::BI__builtin_ia32_scattersiv8si: 3714 case X86::BI__builtin_ia32_scattersiv8df: 3715 case X86::BI__builtin_ia32_scattersiv16sf: 3716 case X86::BI__builtin_ia32_scatterdiv8df: 3717 case X86::BI__builtin_ia32_scatterdiv16sf: 3718 case X86::BI__builtin_ia32_scattersiv8di: 3719 case X86::BI__builtin_ia32_scattersiv16si: 3720 case X86::BI__builtin_ia32_scatterdiv8di: 3721 case X86::BI__builtin_ia32_scatterdiv16si: 3722 ArgNum = 4; 3723 break; 3724 } 3725 3726 llvm::APSInt Result; 3727 3728 // We can't check the value of a dependent argument. 3729 Expr *Arg = TheCall->getArg(ArgNum); 3730 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3731 return false; 3732 3733 // Check constant-ness first. 3734 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3735 return true; 3736 3737 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3738 return false; 3739 3740 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3741 << Arg->getSourceRange(); 3742 } 3743 3744 static bool isX86_32Builtin(unsigned BuiltinID) { 3745 // These builtins only work on x86-32 targets. 3746 switch (BuiltinID) { 3747 case X86::BI__builtin_ia32_readeflags_u32: 3748 case X86::BI__builtin_ia32_writeeflags_u32: 3749 return true; 3750 } 3751 3752 return false; 3753 } 3754 3755 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3756 if (BuiltinID == X86::BI__builtin_cpu_supports) 3757 return SemaBuiltinCpuSupports(*this, TheCall); 3758 3759 if (BuiltinID == X86::BI__builtin_cpu_is) 3760 return SemaBuiltinCpuIs(*this, TheCall); 3761 3762 // Check for 32-bit only builtins on a 64-bit target. 3763 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3764 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3765 return Diag(TheCall->getCallee()->getBeginLoc(), 3766 diag::err_32_bit_builtin_64_bit_tgt); 3767 3768 // If the intrinsic has rounding or SAE make sure its valid. 3769 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3770 return true; 3771 3772 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3773 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3774 return true; 3775 3776 // For intrinsics which take an immediate value as part of the instruction, 3777 // range check them here. 3778 int i = 0, l = 0, u = 0; 3779 switch (BuiltinID) { 3780 default: 3781 return false; 3782 case X86::BI__builtin_ia32_vec_ext_v2si: 3783 case X86::BI__builtin_ia32_vec_ext_v2di: 3784 case X86::BI__builtin_ia32_vextractf128_pd256: 3785 case X86::BI__builtin_ia32_vextractf128_ps256: 3786 case X86::BI__builtin_ia32_vextractf128_si256: 3787 case X86::BI__builtin_ia32_extract128i256: 3788 case X86::BI__builtin_ia32_extractf64x4_mask: 3789 case X86::BI__builtin_ia32_extracti64x4_mask: 3790 case X86::BI__builtin_ia32_extractf32x8_mask: 3791 case X86::BI__builtin_ia32_extracti32x8_mask: 3792 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3793 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3794 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3795 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3796 i = 1; l = 0; u = 1; 3797 break; 3798 case X86::BI__builtin_ia32_vec_set_v2di: 3799 case X86::BI__builtin_ia32_vinsertf128_pd256: 3800 case X86::BI__builtin_ia32_vinsertf128_ps256: 3801 case X86::BI__builtin_ia32_vinsertf128_si256: 3802 case X86::BI__builtin_ia32_insert128i256: 3803 case X86::BI__builtin_ia32_insertf32x8: 3804 case X86::BI__builtin_ia32_inserti32x8: 3805 case X86::BI__builtin_ia32_insertf64x4: 3806 case X86::BI__builtin_ia32_inserti64x4: 3807 case X86::BI__builtin_ia32_insertf64x2_256: 3808 case X86::BI__builtin_ia32_inserti64x2_256: 3809 case X86::BI__builtin_ia32_insertf32x4_256: 3810 case X86::BI__builtin_ia32_inserti32x4_256: 3811 i = 2; l = 0; u = 1; 3812 break; 3813 case X86::BI__builtin_ia32_vpermilpd: 3814 case X86::BI__builtin_ia32_vec_ext_v4hi: 3815 case X86::BI__builtin_ia32_vec_ext_v4si: 3816 case X86::BI__builtin_ia32_vec_ext_v4sf: 3817 case X86::BI__builtin_ia32_vec_ext_v4di: 3818 case X86::BI__builtin_ia32_extractf32x4_mask: 3819 case X86::BI__builtin_ia32_extracti32x4_mask: 3820 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3821 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3822 i = 1; l = 0; u = 3; 3823 break; 3824 case X86::BI_mm_prefetch: 3825 case X86::BI__builtin_ia32_vec_ext_v8hi: 3826 case X86::BI__builtin_ia32_vec_ext_v8si: 3827 i = 1; l = 0; u = 7; 3828 break; 3829 case X86::BI__builtin_ia32_sha1rnds4: 3830 case X86::BI__builtin_ia32_blendpd: 3831 case X86::BI__builtin_ia32_shufpd: 3832 case X86::BI__builtin_ia32_vec_set_v4hi: 3833 case X86::BI__builtin_ia32_vec_set_v4si: 3834 case X86::BI__builtin_ia32_vec_set_v4di: 3835 case X86::BI__builtin_ia32_shuf_f32x4_256: 3836 case X86::BI__builtin_ia32_shuf_f64x2_256: 3837 case X86::BI__builtin_ia32_shuf_i32x4_256: 3838 case X86::BI__builtin_ia32_shuf_i64x2_256: 3839 case X86::BI__builtin_ia32_insertf64x2_512: 3840 case X86::BI__builtin_ia32_inserti64x2_512: 3841 case X86::BI__builtin_ia32_insertf32x4: 3842 case X86::BI__builtin_ia32_inserti32x4: 3843 i = 2; l = 0; u = 3; 3844 break; 3845 case X86::BI__builtin_ia32_vpermil2pd: 3846 case X86::BI__builtin_ia32_vpermil2pd256: 3847 case X86::BI__builtin_ia32_vpermil2ps: 3848 case X86::BI__builtin_ia32_vpermil2ps256: 3849 i = 3; l = 0; u = 3; 3850 break; 3851 case X86::BI__builtin_ia32_cmpb128_mask: 3852 case X86::BI__builtin_ia32_cmpw128_mask: 3853 case X86::BI__builtin_ia32_cmpd128_mask: 3854 case X86::BI__builtin_ia32_cmpq128_mask: 3855 case X86::BI__builtin_ia32_cmpb256_mask: 3856 case X86::BI__builtin_ia32_cmpw256_mask: 3857 case X86::BI__builtin_ia32_cmpd256_mask: 3858 case X86::BI__builtin_ia32_cmpq256_mask: 3859 case X86::BI__builtin_ia32_cmpb512_mask: 3860 case X86::BI__builtin_ia32_cmpw512_mask: 3861 case X86::BI__builtin_ia32_cmpd512_mask: 3862 case X86::BI__builtin_ia32_cmpq512_mask: 3863 case X86::BI__builtin_ia32_ucmpb128_mask: 3864 case X86::BI__builtin_ia32_ucmpw128_mask: 3865 case X86::BI__builtin_ia32_ucmpd128_mask: 3866 case X86::BI__builtin_ia32_ucmpq128_mask: 3867 case X86::BI__builtin_ia32_ucmpb256_mask: 3868 case X86::BI__builtin_ia32_ucmpw256_mask: 3869 case X86::BI__builtin_ia32_ucmpd256_mask: 3870 case X86::BI__builtin_ia32_ucmpq256_mask: 3871 case X86::BI__builtin_ia32_ucmpb512_mask: 3872 case X86::BI__builtin_ia32_ucmpw512_mask: 3873 case X86::BI__builtin_ia32_ucmpd512_mask: 3874 case X86::BI__builtin_ia32_ucmpq512_mask: 3875 case X86::BI__builtin_ia32_vpcomub: 3876 case X86::BI__builtin_ia32_vpcomuw: 3877 case X86::BI__builtin_ia32_vpcomud: 3878 case X86::BI__builtin_ia32_vpcomuq: 3879 case X86::BI__builtin_ia32_vpcomb: 3880 case X86::BI__builtin_ia32_vpcomw: 3881 case X86::BI__builtin_ia32_vpcomd: 3882 case X86::BI__builtin_ia32_vpcomq: 3883 case X86::BI__builtin_ia32_vec_set_v8hi: 3884 case X86::BI__builtin_ia32_vec_set_v8si: 3885 i = 2; l = 0; u = 7; 3886 break; 3887 case X86::BI__builtin_ia32_vpermilpd256: 3888 case X86::BI__builtin_ia32_roundps: 3889 case X86::BI__builtin_ia32_roundpd: 3890 case X86::BI__builtin_ia32_roundps256: 3891 case X86::BI__builtin_ia32_roundpd256: 3892 case X86::BI__builtin_ia32_getmantpd128_mask: 3893 case X86::BI__builtin_ia32_getmantpd256_mask: 3894 case X86::BI__builtin_ia32_getmantps128_mask: 3895 case X86::BI__builtin_ia32_getmantps256_mask: 3896 case X86::BI__builtin_ia32_getmantpd512_mask: 3897 case X86::BI__builtin_ia32_getmantps512_mask: 3898 case X86::BI__builtin_ia32_vec_ext_v16qi: 3899 case X86::BI__builtin_ia32_vec_ext_v16hi: 3900 i = 1; l = 0; u = 15; 3901 break; 3902 case X86::BI__builtin_ia32_pblendd128: 3903 case X86::BI__builtin_ia32_blendps: 3904 case X86::BI__builtin_ia32_blendpd256: 3905 case X86::BI__builtin_ia32_shufpd256: 3906 case X86::BI__builtin_ia32_roundss: 3907 case X86::BI__builtin_ia32_roundsd: 3908 case X86::BI__builtin_ia32_rangepd128_mask: 3909 case X86::BI__builtin_ia32_rangepd256_mask: 3910 case X86::BI__builtin_ia32_rangepd512_mask: 3911 case X86::BI__builtin_ia32_rangeps128_mask: 3912 case X86::BI__builtin_ia32_rangeps256_mask: 3913 case X86::BI__builtin_ia32_rangeps512_mask: 3914 case X86::BI__builtin_ia32_getmantsd_round_mask: 3915 case X86::BI__builtin_ia32_getmantss_round_mask: 3916 case X86::BI__builtin_ia32_vec_set_v16qi: 3917 case X86::BI__builtin_ia32_vec_set_v16hi: 3918 i = 2; l = 0; u = 15; 3919 break; 3920 case X86::BI__builtin_ia32_vec_ext_v32qi: 3921 i = 1; l = 0; u = 31; 3922 break; 3923 case X86::BI__builtin_ia32_cmpps: 3924 case X86::BI__builtin_ia32_cmpss: 3925 case X86::BI__builtin_ia32_cmppd: 3926 case X86::BI__builtin_ia32_cmpsd: 3927 case X86::BI__builtin_ia32_cmpps256: 3928 case X86::BI__builtin_ia32_cmppd256: 3929 case X86::BI__builtin_ia32_cmpps128_mask: 3930 case X86::BI__builtin_ia32_cmppd128_mask: 3931 case X86::BI__builtin_ia32_cmpps256_mask: 3932 case X86::BI__builtin_ia32_cmppd256_mask: 3933 case X86::BI__builtin_ia32_cmpps512_mask: 3934 case X86::BI__builtin_ia32_cmppd512_mask: 3935 case X86::BI__builtin_ia32_cmpsd_mask: 3936 case X86::BI__builtin_ia32_cmpss_mask: 3937 case X86::BI__builtin_ia32_vec_set_v32qi: 3938 i = 2; l = 0; u = 31; 3939 break; 3940 case X86::BI__builtin_ia32_permdf256: 3941 case X86::BI__builtin_ia32_permdi256: 3942 case X86::BI__builtin_ia32_permdf512: 3943 case X86::BI__builtin_ia32_permdi512: 3944 case X86::BI__builtin_ia32_vpermilps: 3945 case X86::BI__builtin_ia32_vpermilps256: 3946 case X86::BI__builtin_ia32_vpermilpd512: 3947 case X86::BI__builtin_ia32_vpermilps512: 3948 case X86::BI__builtin_ia32_pshufd: 3949 case X86::BI__builtin_ia32_pshufd256: 3950 case X86::BI__builtin_ia32_pshufd512: 3951 case X86::BI__builtin_ia32_pshufhw: 3952 case X86::BI__builtin_ia32_pshufhw256: 3953 case X86::BI__builtin_ia32_pshufhw512: 3954 case X86::BI__builtin_ia32_pshuflw: 3955 case X86::BI__builtin_ia32_pshuflw256: 3956 case X86::BI__builtin_ia32_pshuflw512: 3957 case X86::BI__builtin_ia32_vcvtps2ph: 3958 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3959 case X86::BI__builtin_ia32_vcvtps2ph256: 3960 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3961 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3962 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3963 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3964 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3965 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3966 case X86::BI__builtin_ia32_rndscaleps_mask: 3967 case X86::BI__builtin_ia32_rndscalepd_mask: 3968 case X86::BI__builtin_ia32_reducepd128_mask: 3969 case X86::BI__builtin_ia32_reducepd256_mask: 3970 case X86::BI__builtin_ia32_reducepd512_mask: 3971 case X86::BI__builtin_ia32_reduceps128_mask: 3972 case X86::BI__builtin_ia32_reduceps256_mask: 3973 case X86::BI__builtin_ia32_reduceps512_mask: 3974 case X86::BI__builtin_ia32_prold512: 3975 case X86::BI__builtin_ia32_prolq512: 3976 case X86::BI__builtin_ia32_prold128: 3977 case X86::BI__builtin_ia32_prold256: 3978 case X86::BI__builtin_ia32_prolq128: 3979 case X86::BI__builtin_ia32_prolq256: 3980 case X86::BI__builtin_ia32_prord512: 3981 case X86::BI__builtin_ia32_prorq512: 3982 case X86::BI__builtin_ia32_prord128: 3983 case X86::BI__builtin_ia32_prord256: 3984 case X86::BI__builtin_ia32_prorq128: 3985 case X86::BI__builtin_ia32_prorq256: 3986 case X86::BI__builtin_ia32_fpclasspd128_mask: 3987 case X86::BI__builtin_ia32_fpclasspd256_mask: 3988 case X86::BI__builtin_ia32_fpclassps128_mask: 3989 case X86::BI__builtin_ia32_fpclassps256_mask: 3990 case X86::BI__builtin_ia32_fpclassps512_mask: 3991 case X86::BI__builtin_ia32_fpclasspd512_mask: 3992 case X86::BI__builtin_ia32_fpclasssd_mask: 3993 case X86::BI__builtin_ia32_fpclassss_mask: 3994 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3995 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3996 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3997 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3998 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3999 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4000 case X86::BI__builtin_ia32_kshiftliqi: 4001 case X86::BI__builtin_ia32_kshiftlihi: 4002 case X86::BI__builtin_ia32_kshiftlisi: 4003 case X86::BI__builtin_ia32_kshiftlidi: 4004 case X86::BI__builtin_ia32_kshiftriqi: 4005 case X86::BI__builtin_ia32_kshiftrihi: 4006 case X86::BI__builtin_ia32_kshiftrisi: 4007 case X86::BI__builtin_ia32_kshiftridi: 4008 i = 1; l = 0; u = 255; 4009 break; 4010 case X86::BI__builtin_ia32_vperm2f128_pd256: 4011 case X86::BI__builtin_ia32_vperm2f128_ps256: 4012 case X86::BI__builtin_ia32_vperm2f128_si256: 4013 case X86::BI__builtin_ia32_permti256: 4014 case X86::BI__builtin_ia32_pblendw128: 4015 case X86::BI__builtin_ia32_pblendw256: 4016 case X86::BI__builtin_ia32_blendps256: 4017 case X86::BI__builtin_ia32_pblendd256: 4018 case X86::BI__builtin_ia32_palignr128: 4019 case X86::BI__builtin_ia32_palignr256: 4020 case X86::BI__builtin_ia32_palignr512: 4021 case X86::BI__builtin_ia32_alignq512: 4022 case X86::BI__builtin_ia32_alignd512: 4023 case X86::BI__builtin_ia32_alignd128: 4024 case X86::BI__builtin_ia32_alignd256: 4025 case X86::BI__builtin_ia32_alignq128: 4026 case X86::BI__builtin_ia32_alignq256: 4027 case X86::BI__builtin_ia32_vcomisd: 4028 case X86::BI__builtin_ia32_vcomiss: 4029 case X86::BI__builtin_ia32_shuf_f32x4: 4030 case X86::BI__builtin_ia32_shuf_f64x2: 4031 case X86::BI__builtin_ia32_shuf_i32x4: 4032 case X86::BI__builtin_ia32_shuf_i64x2: 4033 case X86::BI__builtin_ia32_shufpd512: 4034 case X86::BI__builtin_ia32_shufps: 4035 case X86::BI__builtin_ia32_shufps256: 4036 case X86::BI__builtin_ia32_shufps512: 4037 case X86::BI__builtin_ia32_dbpsadbw128: 4038 case X86::BI__builtin_ia32_dbpsadbw256: 4039 case X86::BI__builtin_ia32_dbpsadbw512: 4040 case X86::BI__builtin_ia32_vpshldd128: 4041 case X86::BI__builtin_ia32_vpshldd256: 4042 case X86::BI__builtin_ia32_vpshldd512: 4043 case X86::BI__builtin_ia32_vpshldq128: 4044 case X86::BI__builtin_ia32_vpshldq256: 4045 case X86::BI__builtin_ia32_vpshldq512: 4046 case X86::BI__builtin_ia32_vpshldw128: 4047 case X86::BI__builtin_ia32_vpshldw256: 4048 case X86::BI__builtin_ia32_vpshldw512: 4049 case X86::BI__builtin_ia32_vpshrdd128: 4050 case X86::BI__builtin_ia32_vpshrdd256: 4051 case X86::BI__builtin_ia32_vpshrdd512: 4052 case X86::BI__builtin_ia32_vpshrdq128: 4053 case X86::BI__builtin_ia32_vpshrdq256: 4054 case X86::BI__builtin_ia32_vpshrdq512: 4055 case X86::BI__builtin_ia32_vpshrdw128: 4056 case X86::BI__builtin_ia32_vpshrdw256: 4057 case X86::BI__builtin_ia32_vpshrdw512: 4058 i = 2; l = 0; u = 255; 4059 break; 4060 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4061 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4062 case X86::BI__builtin_ia32_fixupimmps512_mask: 4063 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4064 case X86::BI__builtin_ia32_fixupimmsd_mask: 4065 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4066 case X86::BI__builtin_ia32_fixupimmss_mask: 4067 case X86::BI__builtin_ia32_fixupimmss_maskz: 4068 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4069 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4070 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4071 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4072 case X86::BI__builtin_ia32_fixupimmps128_mask: 4073 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4074 case X86::BI__builtin_ia32_fixupimmps256_mask: 4075 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4076 case X86::BI__builtin_ia32_pternlogd512_mask: 4077 case X86::BI__builtin_ia32_pternlogd512_maskz: 4078 case X86::BI__builtin_ia32_pternlogq512_mask: 4079 case X86::BI__builtin_ia32_pternlogq512_maskz: 4080 case X86::BI__builtin_ia32_pternlogd128_mask: 4081 case X86::BI__builtin_ia32_pternlogd128_maskz: 4082 case X86::BI__builtin_ia32_pternlogd256_mask: 4083 case X86::BI__builtin_ia32_pternlogd256_maskz: 4084 case X86::BI__builtin_ia32_pternlogq128_mask: 4085 case X86::BI__builtin_ia32_pternlogq128_maskz: 4086 case X86::BI__builtin_ia32_pternlogq256_mask: 4087 case X86::BI__builtin_ia32_pternlogq256_maskz: 4088 i = 3; l = 0; u = 255; 4089 break; 4090 case X86::BI__builtin_ia32_gatherpfdpd: 4091 case X86::BI__builtin_ia32_gatherpfdps: 4092 case X86::BI__builtin_ia32_gatherpfqpd: 4093 case X86::BI__builtin_ia32_gatherpfqps: 4094 case X86::BI__builtin_ia32_scatterpfdpd: 4095 case X86::BI__builtin_ia32_scatterpfdps: 4096 case X86::BI__builtin_ia32_scatterpfqpd: 4097 case X86::BI__builtin_ia32_scatterpfqps: 4098 i = 4; l = 2; u = 3; 4099 break; 4100 case X86::BI__builtin_ia32_reducesd_mask: 4101 case X86::BI__builtin_ia32_reducess_mask: 4102 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4103 case X86::BI__builtin_ia32_rndscaless_round_mask: 4104 i = 4; l = 0; u = 255; 4105 break; 4106 } 4107 4108 // Note that we don't force a hard error on the range check here, allowing 4109 // template-generated or macro-generated dead code to potentially have out-of- 4110 // range values. These need to code generate, but don't need to necessarily 4111 // make any sense. We use a warning that defaults to an error. 4112 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4113 } 4114 4115 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4116 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4117 /// Returns true when the format fits the function and the FormatStringInfo has 4118 /// been populated. 4119 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4120 FormatStringInfo *FSI) { 4121 FSI->HasVAListArg = Format->getFirstArg() == 0; 4122 FSI->FormatIdx = Format->getFormatIdx() - 1; 4123 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4124 4125 // The way the format attribute works in GCC, the implicit this argument 4126 // of member functions is counted. However, it doesn't appear in our own 4127 // lists, so decrement format_idx in that case. 4128 if (IsCXXMember) { 4129 if(FSI->FormatIdx == 0) 4130 return false; 4131 --FSI->FormatIdx; 4132 if (FSI->FirstDataArg != 0) 4133 --FSI->FirstDataArg; 4134 } 4135 return true; 4136 } 4137 4138 /// Checks if a the given expression evaluates to null. 4139 /// 4140 /// Returns true if the value evaluates to null. 4141 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4142 // If the expression has non-null type, it doesn't evaluate to null. 4143 if (auto nullability 4144 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4145 if (*nullability == NullabilityKind::NonNull) 4146 return false; 4147 } 4148 4149 // As a special case, transparent unions initialized with zero are 4150 // considered null for the purposes of the nonnull attribute. 4151 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4152 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4153 if (const CompoundLiteralExpr *CLE = 4154 dyn_cast<CompoundLiteralExpr>(Expr)) 4155 if (const InitListExpr *ILE = 4156 dyn_cast<InitListExpr>(CLE->getInitializer())) 4157 Expr = ILE->getInit(0); 4158 } 4159 4160 bool Result; 4161 return (!Expr->isValueDependent() && 4162 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4163 !Result); 4164 } 4165 4166 static void CheckNonNullArgument(Sema &S, 4167 const Expr *ArgExpr, 4168 SourceLocation CallSiteLoc) { 4169 if (CheckNonNullExpr(S, ArgExpr)) 4170 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4171 S.PDiag(diag::warn_null_arg) 4172 << ArgExpr->getSourceRange()); 4173 } 4174 4175 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4176 FormatStringInfo FSI; 4177 if ((GetFormatStringType(Format) == FST_NSString) && 4178 getFormatStringInfo(Format, false, &FSI)) { 4179 Idx = FSI.FormatIdx; 4180 return true; 4181 } 4182 return false; 4183 } 4184 4185 /// Diagnose use of %s directive in an NSString which is being passed 4186 /// as formatting string to formatting method. 4187 static void 4188 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4189 const NamedDecl *FDecl, 4190 Expr **Args, 4191 unsigned NumArgs) { 4192 unsigned Idx = 0; 4193 bool Format = false; 4194 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4195 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4196 Idx = 2; 4197 Format = true; 4198 } 4199 else 4200 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4201 if (S.GetFormatNSStringIdx(I, Idx)) { 4202 Format = true; 4203 break; 4204 } 4205 } 4206 if (!Format || NumArgs <= Idx) 4207 return; 4208 const Expr *FormatExpr = Args[Idx]; 4209 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4210 FormatExpr = CSCE->getSubExpr(); 4211 const StringLiteral *FormatString; 4212 if (const ObjCStringLiteral *OSL = 4213 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4214 FormatString = OSL->getString(); 4215 else 4216 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4217 if (!FormatString) 4218 return; 4219 if (S.FormatStringHasSArg(FormatString)) { 4220 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4221 << "%s" << 1 << 1; 4222 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4223 << FDecl->getDeclName(); 4224 } 4225 } 4226 4227 /// Determine whether the given type has a non-null nullability annotation. 4228 static bool isNonNullType(ASTContext &ctx, QualType type) { 4229 if (auto nullability = type->getNullability(ctx)) 4230 return *nullability == NullabilityKind::NonNull; 4231 4232 return false; 4233 } 4234 4235 static void CheckNonNullArguments(Sema &S, 4236 const NamedDecl *FDecl, 4237 const FunctionProtoType *Proto, 4238 ArrayRef<const Expr *> Args, 4239 SourceLocation CallSiteLoc) { 4240 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4241 4242 // Already checked by by constant evaluator. 4243 if (S.isConstantEvaluated()) 4244 return; 4245 // Check the attributes attached to the method/function itself. 4246 llvm::SmallBitVector NonNullArgs; 4247 if (FDecl) { 4248 // Handle the nonnull attribute on the function/method declaration itself. 4249 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4250 if (!NonNull->args_size()) { 4251 // Easy case: all pointer arguments are nonnull. 4252 for (const auto *Arg : Args) 4253 if (S.isValidPointerAttrType(Arg->getType())) 4254 CheckNonNullArgument(S, Arg, CallSiteLoc); 4255 return; 4256 } 4257 4258 for (const ParamIdx &Idx : NonNull->args()) { 4259 unsigned IdxAST = Idx.getASTIndex(); 4260 if (IdxAST >= Args.size()) 4261 continue; 4262 if (NonNullArgs.empty()) 4263 NonNullArgs.resize(Args.size()); 4264 NonNullArgs.set(IdxAST); 4265 } 4266 } 4267 } 4268 4269 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4270 // Handle the nonnull attribute on the parameters of the 4271 // function/method. 4272 ArrayRef<ParmVarDecl*> parms; 4273 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4274 parms = FD->parameters(); 4275 else 4276 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4277 4278 unsigned ParamIndex = 0; 4279 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4280 I != E; ++I, ++ParamIndex) { 4281 const ParmVarDecl *PVD = *I; 4282 if (PVD->hasAttr<NonNullAttr>() || 4283 isNonNullType(S.Context, PVD->getType())) { 4284 if (NonNullArgs.empty()) 4285 NonNullArgs.resize(Args.size()); 4286 4287 NonNullArgs.set(ParamIndex); 4288 } 4289 } 4290 } else { 4291 // If we have a non-function, non-method declaration but no 4292 // function prototype, try to dig out the function prototype. 4293 if (!Proto) { 4294 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4295 QualType type = VD->getType().getNonReferenceType(); 4296 if (auto pointerType = type->getAs<PointerType>()) 4297 type = pointerType->getPointeeType(); 4298 else if (auto blockType = type->getAs<BlockPointerType>()) 4299 type = blockType->getPointeeType(); 4300 // FIXME: data member pointers? 4301 4302 // Dig out the function prototype, if there is one. 4303 Proto = type->getAs<FunctionProtoType>(); 4304 } 4305 } 4306 4307 // Fill in non-null argument information from the nullability 4308 // information on the parameter types (if we have them). 4309 if (Proto) { 4310 unsigned Index = 0; 4311 for (auto paramType : Proto->getParamTypes()) { 4312 if (isNonNullType(S.Context, paramType)) { 4313 if (NonNullArgs.empty()) 4314 NonNullArgs.resize(Args.size()); 4315 4316 NonNullArgs.set(Index); 4317 } 4318 4319 ++Index; 4320 } 4321 } 4322 } 4323 4324 // Check for non-null arguments. 4325 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4326 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4327 if (NonNullArgs[ArgIndex]) 4328 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4329 } 4330 } 4331 4332 /// Handles the checks for format strings, non-POD arguments to vararg 4333 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4334 /// attributes. 4335 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4336 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4337 bool IsMemberFunction, SourceLocation Loc, 4338 SourceRange Range, VariadicCallType CallType) { 4339 // FIXME: We should check as much as we can in the template definition. 4340 if (CurContext->isDependentContext()) 4341 return; 4342 4343 // Printf and scanf checking. 4344 llvm::SmallBitVector CheckedVarArgs; 4345 if (FDecl) { 4346 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4347 // Only create vector if there are format attributes. 4348 CheckedVarArgs.resize(Args.size()); 4349 4350 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4351 CheckedVarArgs); 4352 } 4353 } 4354 4355 // Refuse POD arguments that weren't caught by the format string 4356 // checks above. 4357 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4358 if (CallType != VariadicDoesNotApply && 4359 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4360 unsigned NumParams = Proto ? Proto->getNumParams() 4361 : FDecl && isa<FunctionDecl>(FDecl) 4362 ? cast<FunctionDecl>(FDecl)->getNumParams() 4363 : FDecl && isa<ObjCMethodDecl>(FDecl) 4364 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4365 : 0; 4366 4367 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4368 // Args[ArgIdx] can be null in malformed code. 4369 if (const Expr *Arg = Args[ArgIdx]) { 4370 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4371 checkVariadicArgument(Arg, CallType); 4372 } 4373 } 4374 } 4375 4376 if (FDecl || Proto) { 4377 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4378 4379 // Type safety checking. 4380 if (FDecl) { 4381 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4382 CheckArgumentWithTypeTag(I, Args, Loc); 4383 } 4384 } 4385 4386 if (FD) 4387 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4388 } 4389 4390 /// CheckConstructorCall - Check a constructor call for correctness and safety 4391 /// properties not enforced by the C type system. 4392 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4393 ArrayRef<const Expr *> Args, 4394 const FunctionProtoType *Proto, 4395 SourceLocation Loc) { 4396 VariadicCallType CallType = 4397 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4398 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4399 Loc, SourceRange(), CallType); 4400 } 4401 4402 /// CheckFunctionCall - Check a direct function call for various correctness 4403 /// and safety properties not strictly enforced by the C type system. 4404 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4405 const FunctionProtoType *Proto) { 4406 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4407 isa<CXXMethodDecl>(FDecl); 4408 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4409 IsMemberOperatorCall; 4410 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4411 TheCall->getCallee()); 4412 Expr** Args = TheCall->getArgs(); 4413 unsigned NumArgs = TheCall->getNumArgs(); 4414 4415 Expr *ImplicitThis = nullptr; 4416 if (IsMemberOperatorCall) { 4417 // If this is a call to a member operator, hide the first argument 4418 // from checkCall. 4419 // FIXME: Our choice of AST representation here is less than ideal. 4420 ImplicitThis = Args[0]; 4421 ++Args; 4422 --NumArgs; 4423 } else if (IsMemberFunction) 4424 ImplicitThis = 4425 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4426 4427 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4428 IsMemberFunction, TheCall->getRParenLoc(), 4429 TheCall->getCallee()->getSourceRange(), CallType); 4430 4431 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4432 // None of the checks below are needed for functions that don't have 4433 // simple names (e.g., C++ conversion functions). 4434 if (!FnInfo) 4435 return false; 4436 4437 CheckAbsoluteValueFunction(TheCall, FDecl); 4438 CheckMaxUnsignedZero(TheCall, FDecl); 4439 4440 if (getLangOpts().ObjC) 4441 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4442 4443 unsigned CMId = FDecl->getMemoryFunctionKind(); 4444 if (CMId == 0) 4445 return false; 4446 4447 // Handle memory setting and copying functions. 4448 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4449 CheckStrlcpycatArguments(TheCall, FnInfo); 4450 else if (CMId == Builtin::BIstrncat) 4451 CheckStrncatArguments(TheCall, FnInfo); 4452 else 4453 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4454 4455 return false; 4456 } 4457 4458 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4459 ArrayRef<const Expr *> Args) { 4460 VariadicCallType CallType = 4461 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4462 4463 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4464 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4465 CallType); 4466 4467 return false; 4468 } 4469 4470 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4471 const FunctionProtoType *Proto) { 4472 QualType Ty; 4473 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4474 Ty = V->getType().getNonReferenceType(); 4475 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4476 Ty = F->getType().getNonReferenceType(); 4477 else 4478 return false; 4479 4480 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4481 !Ty->isFunctionProtoType()) 4482 return false; 4483 4484 VariadicCallType CallType; 4485 if (!Proto || !Proto->isVariadic()) { 4486 CallType = VariadicDoesNotApply; 4487 } else if (Ty->isBlockPointerType()) { 4488 CallType = VariadicBlock; 4489 } else { // Ty->isFunctionPointerType() 4490 CallType = VariadicFunction; 4491 } 4492 4493 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4494 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4495 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4496 TheCall->getCallee()->getSourceRange(), CallType); 4497 4498 return false; 4499 } 4500 4501 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4502 /// such as function pointers returned from functions. 4503 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4504 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4505 TheCall->getCallee()); 4506 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4507 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4508 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4509 TheCall->getCallee()->getSourceRange(), CallType); 4510 4511 return false; 4512 } 4513 4514 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4515 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4516 return false; 4517 4518 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4519 switch (Op) { 4520 case AtomicExpr::AO__c11_atomic_init: 4521 case AtomicExpr::AO__opencl_atomic_init: 4522 llvm_unreachable("There is no ordering argument for an init"); 4523 4524 case AtomicExpr::AO__c11_atomic_load: 4525 case AtomicExpr::AO__opencl_atomic_load: 4526 case AtomicExpr::AO__atomic_load_n: 4527 case AtomicExpr::AO__atomic_load: 4528 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4529 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4530 4531 case AtomicExpr::AO__c11_atomic_store: 4532 case AtomicExpr::AO__opencl_atomic_store: 4533 case AtomicExpr::AO__atomic_store: 4534 case AtomicExpr::AO__atomic_store_n: 4535 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4536 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4537 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4538 4539 default: 4540 return true; 4541 } 4542 } 4543 4544 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4545 AtomicExpr::AtomicOp Op) { 4546 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4547 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4548 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4549 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4550 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4551 Op); 4552 } 4553 4554 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4555 SourceLocation RParenLoc, MultiExprArg Args, 4556 AtomicExpr::AtomicOp Op, 4557 AtomicArgumentOrder ArgOrder) { 4558 // All the non-OpenCL operations take one of the following forms. 4559 // The OpenCL operations take the __c11 forms with one extra argument for 4560 // synchronization scope. 4561 enum { 4562 // C __c11_atomic_init(A *, C) 4563 Init, 4564 4565 // C __c11_atomic_load(A *, int) 4566 Load, 4567 4568 // void __atomic_load(A *, CP, int) 4569 LoadCopy, 4570 4571 // void __atomic_store(A *, CP, int) 4572 Copy, 4573 4574 // C __c11_atomic_add(A *, M, int) 4575 Arithmetic, 4576 4577 // C __atomic_exchange_n(A *, CP, int) 4578 Xchg, 4579 4580 // void __atomic_exchange(A *, C *, CP, int) 4581 GNUXchg, 4582 4583 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4584 C11CmpXchg, 4585 4586 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4587 GNUCmpXchg 4588 } Form = Init; 4589 4590 const unsigned NumForm = GNUCmpXchg + 1; 4591 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4592 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4593 // where: 4594 // C is an appropriate type, 4595 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4596 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4597 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4598 // the int parameters are for orderings. 4599 4600 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4601 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4602 "need to update code for modified forms"); 4603 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4604 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4605 AtomicExpr::AO__atomic_load, 4606 "need to update code for modified C11 atomics"); 4607 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4608 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4609 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4610 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4611 IsOpenCL; 4612 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4613 Op == AtomicExpr::AO__atomic_store_n || 4614 Op == AtomicExpr::AO__atomic_exchange_n || 4615 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4616 bool IsAddSub = false; 4617 4618 switch (Op) { 4619 case AtomicExpr::AO__c11_atomic_init: 4620 case AtomicExpr::AO__opencl_atomic_init: 4621 Form = Init; 4622 break; 4623 4624 case AtomicExpr::AO__c11_atomic_load: 4625 case AtomicExpr::AO__opencl_atomic_load: 4626 case AtomicExpr::AO__atomic_load_n: 4627 Form = Load; 4628 break; 4629 4630 case AtomicExpr::AO__atomic_load: 4631 Form = LoadCopy; 4632 break; 4633 4634 case AtomicExpr::AO__c11_atomic_store: 4635 case AtomicExpr::AO__opencl_atomic_store: 4636 case AtomicExpr::AO__atomic_store: 4637 case AtomicExpr::AO__atomic_store_n: 4638 Form = Copy; 4639 break; 4640 4641 case AtomicExpr::AO__c11_atomic_fetch_add: 4642 case AtomicExpr::AO__c11_atomic_fetch_sub: 4643 case AtomicExpr::AO__opencl_atomic_fetch_add: 4644 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4645 case AtomicExpr::AO__opencl_atomic_fetch_min: 4646 case AtomicExpr::AO__opencl_atomic_fetch_max: 4647 case AtomicExpr::AO__atomic_fetch_add: 4648 case AtomicExpr::AO__atomic_fetch_sub: 4649 case AtomicExpr::AO__atomic_add_fetch: 4650 case AtomicExpr::AO__atomic_sub_fetch: 4651 IsAddSub = true; 4652 LLVM_FALLTHROUGH; 4653 case AtomicExpr::AO__c11_atomic_fetch_and: 4654 case AtomicExpr::AO__c11_atomic_fetch_or: 4655 case AtomicExpr::AO__c11_atomic_fetch_xor: 4656 case AtomicExpr::AO__opencl_atomic_fetch_and: 4657 case AtomicExpr::AO__opencl_atomic_fetch_or: 4658 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4659 case AtomicExpr::AO__atomic_fetch_and: 4660 case AtomicExpr::AO__atomic_fetch_or: 4661 case AtomicExpr::AO__atomic_fetch_xor: 4662 case AtomicExpr::AO__atomic_fetch_nand: 4663 case AtomicExpr::AO__atomic_and_fetch: 4664 case AtomicExpr::AO__atomic_or_fetch: 4665 case AtomicExpr::AO__atomic_xor_fetch: 4666 case AtomicExpr::AO__atomic_nand_fetch: 4667 case AtomicExpr::AO__c11_atomic_fetch_min: 4668 case AtomicExpr::AO__c11_atomic_fetch_max: 4669 case AtomicExpr::AO__atomic_min_fetch: 4670 case AtomicExpr::AO__atomic_max_fetch: 4671 case AtomicExpr::AO__atomic_fetch_min: 4672 case AtomicExpr::AO__atomic_fetch_max: 4673 Form = Arithmetic; 4674 break; 4675 4676 case AtomicExpr::AO__c11_atomic_exchange: 4677 case AtomicExpr::AO__opencl_atomic_exchange: 4678 case AtomicExpr::AO__atomic_exchange_n: 4679 Form = Xchg; 4680 break; 4681 4682 case AtomicExpr::AO__atomic_exchange: 4683 Form = GNUXchg; 4684 break; 4685 4686 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4687 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4688 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4689 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4690 Form = C11CmpXchg; 4691 break; 4692 4693 case AtomicExpr::AO__atomic_compare_exchange: 4694 case AtomicExpr::AO__atomic_compare_exchange_n: 4695 Form = GNUCmpXchg; 4696 break; 4697 } 4698 4699 unsigned AdjustedNumArgs = NumArgs[Form]; 4700 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4701 ++AdjustedNumArgs; 4702 // Check we have the right number of arguments. 4703 if (Args.size() < AdjustedNumArgs) { 4704 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4705 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4706 << ExprRange; 4707 return ExprError(); 4708 } else if (Args.size() > AdjustedNumArgs) { 4709 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4710 diag::err_typecheck_call_too_many_args) 4711 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4712 << ExprRange; 4713 return ExprError(); 4714 } 4715 4716 // Inspect the first argument of the atomic operation. 4717 Expr *Ptr = Args[0]; 4718 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4719 if (ConvertedPtr.isInvalid()) 4720 return ExprError(); 4721 4722 Ptr = ConvertedPtr.get(); 4723 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4724 if (!pointerType) { 4725 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4726 << Ptr->getType() << Ptr->getSourceRange(); 4727 return ExprError(); 4728 } 4729 4730 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4731 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4732 QualType ValType = AtomTy; // 'C' 4733 if (IsC11) { 4734 if (!AtomTy->isAtomicType()) { 4735 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4736 << Ptr->getType() << Ptr->getSourceRange(); 4737 return ExprError(); 4738 } 4739 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4740 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4741 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4742 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4743 << Ptr->getSourceRange(); 4744 return ExprError(); 4745 } 4746 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4747 } else if (Form != Load && Form != LoadCopy) { 4748 if (ValType.isConstQualified()) { 4749 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4750 << Ptr->getType() << Ptr->getSourceRange(); 4751 return ExprError(); 4752 } 4753 } 4754 4755 // For an arithmetic operation, the implied arithmetic must be well-formed. 4756 if (Form == Arithmetic) { 4757 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4758 if (IsAddSub && !ValType->isIntegerType() 4759 && !ValType->isPointerType()) { 4760 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4761 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4762 return ExprError(); 4763 } 4764 if (!IsAddSub && !ValType->isIntegerType()) { 4765 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4766 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4767 return ExprError(); 4768 } 4769 if (IsC11 && ValType->isPointerType() && 4770 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4771 diag::err_incomplete_type)) { 4772 return ExprError(); 4773 } 4774 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4775 // For __atomic_*_n operations, the value type must be a scalar integral or 4776 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4777 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4778 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4779 return ExprError(); 4780 } 4781 4782 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4783 !AtomTy->isScalarType()) { 4784 // For GNU atomics, require a trivially-copyable type. This is not part of 4785 // the GNU atomics specification, but we enforce it for sanity. 4786 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4787 << Ptr->getType() << Ptr->getSourceRange(); 4788 return ExprError(); 4789 } 4790 4791 switch (ValType.getObjCLifetime()) { 4792 case Qualifiers::OCL_None: 4793 case Qualifiers::OCL_ExplicitNone: 4794 // okay 4795 break; 4796 4797 case Qualifiers::OCL_Weak: 4798 case Qualifiers::OCL_Strong: 4799 case Qualifiers::OCL_Autoreleasing: 4800 // FIXME: Can this happen? By this point, ValType should be known 4801 // to be trivially copyable. 4802 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4803 << ValType << Ptr->getSourceRange(); 4804 return ExprError(); 4805 } 4806 4807 // All atomic operations have an overload which takes a pointer to a volatile 4808 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4809 // into the result or the other operands. Similarly atomic_load takes a 4810 // pointer to a const 'A'. 4811 ValType.removeLocalVolatile(); 4812 ValType.removeLocalConst(); 4813 QualType ResultType = ValType; 4814 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4815 Form == Init) 4816 ResultType = Context.VoidTy; 4817 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4818 ResultType = Context.BoolTy; 4819 4820 // The type of a parameter passed 'by value'. In the GNU atomics, such 4821 // arguments are actually passed as pointers. 4822 QualType ByValType = ValType; // 'CP' 4823 bool IsPassedByAddress = false; 4824 if (!IsC11 && !IsN) { 4825 ByValType = Ptr->getType(); 4826 IsPassedByAddress = true; 4827 } 4828 4829 SmallVector<Expr *, 5> APIOrderedArgs; 4830 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4831 APIOrderedArgs.push_back(Args[0]); 4832 switch (Form) { 4833 case Init: 4834 case Load: 4835 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4836 break; 4837 case LoadCopy: 4838 case Copy: 4839 case Arithmetic: 4840 case Xchg: 4841 APIOrderedArgs.push_back(Args[2]); // Val1 4842 APIOrderedArgs.push_back(Args[1]); // Order 4843 break; 4844 case GNUXchg: 4845 APIOrderedArgs.push_back(Args[2]); // Val1 4846 APIOrderedArgs.push_back(Args[3]); // Val2 4847 APIOrderedArgs.push_back(Args[1]); // Order 4848 break; 4849 case C11CmpXchg: 4850 APIOrderedArgs.push_back(Args[2]); // Val1 4851 APIOrderedArgs.push_back(Args[4]); // Val2 4852 APIOrderedArgs.push_back(Args[1]); // Order 4853 APIOrderedArgs.push_back(Args[3]); // OrderFail 4854 break; 4855 case GNUCmpXchg: 4856 APIOrderedArgs.push_back(Args[2]); // Val1 4857 APIOrderedArgs.push_back(Args[4]); // Val2 4858 APIOrderedArgs.push_back(Args[5]); // Weak 4859 APIOrderedArgs.push_back(Args[1]); // Order 4860 APIOrderedArgs.push_back(Args[3]); // OrderFail 4861 break; 4862 } 4863 } else 4864 APIOrderedArgs.append(Args.begin(), Args.end()); 4865 4866 // The first argument's non-CV pointer type is used to deduce the type of 4867 // subsequent arguments, except for: 4868 // - weak flag (always converted to bool) 4869 // - memory order (always converted to int) 4870 // - scope (always converted to int) 4871 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4872 QualType Ty; 4873 if (i < NumVals[Form] + 1) { 4874 switch (i) { 4875 case 0: 4876 // The first argument is always a pointer. It has a fixed type. 4877 // It is always dereferenced, a nullptr is undefined. 4878 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4879 // Nothing else to do: we already know all we want about this pointer. 4880 continue; 4881 case 1: 4882 // The second argument is the non-atomic operand. For arithmetic, this 4883 // is always passed by value, and for a compare_exchange it is always 4884 // passed by address. For the rest, GNU uses by-address and C11 uses 4885 // by-value. 4886 assert(Form != Load); 4887 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4888 Ty = ValType; 4889 else if (Form == Copy || Form == Xchg) { 4890 if (IsPassedByAddress) { 4891 // The value pointer is always dereferenced, a nullptr is undefined. 4892 CheckNonNullArgument(*this, APIOrderedArgs[i], 4893 ExprRange.getBegin()); 4894 } 4895 Ty = ByValType; 4896 } else if (Form == Arithmetic) 4897 Ty = Context.getPointerDiffType(); 4898 else { 4899 Expr *ValArg = APIOrderedArgs[i]; 4900 // The value pointer is always dereferenced, a nullptr is undefined. 4901 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4902 LangAS AS = LangAS::Default; 4903 // Keep address space of non-atomic pointer type. 4904 if (const PointerType *PtrTy = 4905 ValArg->getType()->getAs<PointerType>()) { 4906 AS = PtrTy->getPointeeType().getAddressSpace(); 4907 } 4908 Ty = Context.getPointerType( 4909 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4910 } 4911 break; 4912 case 2: 4913 // The third argument to compare_exchange / GNU exchange is the desired 4914 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4915 if (IsPassedByAddress) 4916 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4917 Ty = ByValType; 4918 break; 4919 case 3: 4920 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4921 Ty = Context.BoolTy; 4922 break; 4923 } 4924 } else { 4925 // The order(s) and scope are always converted to int. 4926 Ty = Context.IntTy; 4927 } 4928 4929 InitializedEntity Entity = 4930 InitializedEntity::InitializeParameter(Context, Ty, false); 4931 ExprResult Arg = APIOrderedArgs[i]; 4932 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4933 if (Arg.isInvalid()) 4934 return true; 4935 APIOrderedArgs[i] = Arg.get(); 4936 } 4937 4938 // Permute the arguments into a 'consistent' order. 4939 SmallVector<Expr*, 5> SubExprs; 4940 SubExprs.push_back(Ptr); 4941 switch (Form) { 4942 case Init: 4943 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4944 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4945 break; 4946 case Load: 4947 SubExprs.push_back(APIOrderedArgs[1]); // Order 4948 break; 4949 case LoadCopy: 4950 case Copy: 4951 case Arithmetic: 4952 case Xchg: 4953 SubExprs.push_back(APIOrderedArgs[2]); // Order 4954 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4955 break; 4956 case GNUXchg: 4957 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4958 SubExprs.push_back(APIOrderedArgs[3]); // Order 4959 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4960 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4961 break; 4962 case C11CmpXchg: 4963 SubExprs.push_back(APIOrderedArgs[3]); // Order 4964 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4965 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4966 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4967 break; 4968 case GNUCmpXchg: 4969 SubExprs.push_back(APIOrderedArgs[4]); // Order 4970 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4971 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4972 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4973 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4974 break; 4975 } 4976 4977 if (SubExprs.size() >= 2 && Form != Init) { 4978 llvm::APSInt Result(32); 4979 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4980 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4981 Diag(SubExprs[1]->getBeginLoc(), 4982 diag::warn_atomic_op_has_invalid_memory_order) 4983 << SubExprs[1]->getSourceRange(); 4984 } 4985 4986 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4987 auto *Scope = Args[Args.size() - 1]; 4988 llvm::APSInt Result(32); 4989 if (Scope->isIntegerConstantExpr(Result, Context) && 4990 !ScopeModel->isValid(Result.getZExtValue())) { 4991 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4992 << Scope->getSourceRange(); 4993 } 4994 SubExprs.push_back(Scope); 4995 } 4996 4997 AtomicExpr *AE = new (Context) 4998 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4999 5000 if ((Op == AtomicExpr::AO__c11_atomic_load || 5001 Op == AtomicExpr::AO__c11_atomic_store || 5002 Op == AtomicExpr::AO__opencl_atomic_load || 5003 Op == AtomicExpr::AO__opencl_atomic_store ) && 5004 Context.AtomicUsesUnsupportedLibcall(AE)) 5005 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5006 << ((Op == AtomicExpr::AO__c11_atomic_load || 5007 Op == AtomicExpr::AO__opencl_atomic_load) 5008 ? 0 5009 : 1); 5010 5011 return AE; 5012 } 5013 5014 /// checkBuiltinArgument - Given a call to a builtin function, perform 5015 /// normal type-checking on the given argument, updating the call in 5016 /// place. This is useful when a builtin function requires custom 5017 /// type-checking for some of its arguments but not necessarily all of 5018 /// them. 5019 /// 5020 /// Returns true on error. 5021 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5022 FunctionDecl *Fn = E->getDirectCallee(); 5023 assert(Fn && "builtin call without direct callee!"); 5024 5025 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5026 InitializedEntity Entity = 5027 InitializedEntity::InitializeParameter(S.Context, Param); 5028 5029 ExprResult Arg = E->getArg(0); 5030 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5031 if (Arg.isInvalid()) 5032 return true; 5033 5034 E->setArg(ArgIndex, Arg.get()); 5035 return false; 5036 } 5037 5038 /// We have a call to a function like __sync_fetch_and_add, which is an 5039 /// overloaded function based on the pointer type of its first argument. 5040 /// The main BuildCallExpr routines have already promoted the types of 5041 /// arguments because all of these calls are prototyped as void(...). 5042 /// 5043 /// This function goes through and does final semantic checking for these 5044 /// builtins, as well as generating any warnings. 5045 ExprResult 5046 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5047 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5048 Expr *Callee = TheCall->getCallee(); 5049 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5050 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5051 5052 // Ensure that we have at least one argument to do type inference from. 5053 if (TheCall->getNumArgs() < 1) { 5054 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5055 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5056 return ExprError(); 5057 } 5058 5059 // Inspect the first argument of the atomic builtin. This should always be 5060 // a pointer type, whose element is an integral scalar or pointer type. 5061 // Because it is a pointer type, we don't have to worry about any implicit 5062 // casts here. 5063 // FIXME: We don't allow floating point scalars as input. 5064 Expr *FirstArg = TheCall->getArg(0); 5065 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5066 if (FirstArgResult.isInvalid()) 5067 return ExprError(); 5068 FirstArg = FirstArgResult.get(); 5069 TheCall->setArg(0, FirstArg); 5070 5071 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5072 if (!pointerType) { 5073 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5074 << FirstArg->getType() << FirstArg->getSourceRange(); 5075 return ExprError(); 5076 } 5077 5078 QualType ValType = pointerType->getPointeeType(); 5079 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5080 !ValType->isBlockPointerType()) { 5081 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5082 << FirstArg->getType() << FirstArg->getSourceRange(); 5083 return ExprError(); 5084 } 5085 5086 if (ValType.isConstQualified()) { 5087 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5088 << FirstArg->getType() << FirstArg->getSourceRange(); 5089 return ExprError(); 5090 } 5091 5092 switch (ValType.getObjCLifetime()) { 5093 case Qualifiers::OCL_None: 5094 case Qualifiers::OCL_ExplicitNone: 5095 // okay 5096 break; 5097 5098 case Qualifiers::OCL_Weak: 5099 case Qualifiers::OCL_Strong: 5100 case Qualifiers::OCL_Autoreleasing: 5101 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5102 << ValType << FirstArg->getSourceRange(); 5103 return ExprError(); 5104 } 5105 5106 // Strip any qualifiers off ValType. 5107 ValType = ValType.getUnqualifiedType(); 5108 5109 // The majority of builtins return a value, but a few have special return 5110 // types, so allow them to override appropriately below. 5111 QualType ResultType = ValType; 5112 5113 // We need to figure out which concrete builtin this maps onto. For example, 5114 // __sync_fetch_and_add with a 2 byte object turns into 5115 // __sync_fetch_and_add_2. 5116 #define BUILTIN_ROW(x) \ 5117 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5118 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5119 5120 static const unsigned BuiltinIndices[][5] = { 5121 BUILTIN_ROW(__sync_fetch_and_add), 5122 BUILTIN_ROW(__sync_fetch_and_sub), 5123 BUILTIN_ROW(__sync_fetch_and_or), 5124 BUILTIN_ROW(__sync_fetch_and_and), 5125 BUILTIN_ROW(__sync_fetch_and_xor), 5126 BUILTIN_ROW(__sync_fetch_and_nand), 5127 5128 BUILTIN_ROW(__sync_add_and_fetch), 5129 BUILTIN_ROW(__sync_sub_and_fetch), 5130 BUILTIN_ROW(__sync_and_and_fetch), 5131 BUILTIN_ROW(__sync_or_and_fetch), 5132 BUILTIN_ROW(__sync_xor_and_fetch), 5133 BUILTIN_ROW(__sync_nand_and_fetch), 5134 5135 BUILTIN_ROW(__sync_val_compare_and_swap), 5136 BUILTIN_ROW(__sync_bool_compare_and_swap), 5137 BUILTIN_ROW(__sync_lock_test_and_set), 5138 BUILTIN_ROW(__sync_lock_release), 5139 BUILTIN_ROW(__sync_swap) 5140 }; 5141 #undef BUILTIN_ROW 5142 5143 // Determine the index of the size. 5144 unsigned SizeIndex; 5145 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5146 case 1: SizeIndex = 0; break; 5147 case 2: SizeIndex = 1; break; 5148 case 4: SizeIndex = 2; break; 5149 case 8: SizeIndex = 3; break; 5150 case 16: SizeIndex = 4; break; 5151 default: 5152 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5153 << FirstArg->getType() << FirstArg->getSourceRange(); 5154 return ExprError(); 5155 } 5156 5157 // Each of these builtins has one pointer argument, followed by some number of 5158 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5159 // that we ignore. Find out which row of BuiltinIndices to read from as well 5160 // as the number of fixed args. 5161 unsigned BuiltinID = FDecl->getBuiltinID(); 5162 unsigned BuiltinIndex, NumFixed = 1; 5163 bool WarnAboutSemanticsChange = false; 5164 switch (BuiltinID) { 5165 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5166 case Builtin::BI__sync_fetch_and_add: 5167 case Builtin::BI__sync_fetch_and_add_1: 5168 case Builtin::BI__sync_fetch_and_add_2: 5169 case Builtin::BI__sync_fetch_and_add_4: 5170 case Builtin::BI__sync_fetch_and_add_8: 5171 case Builtin::BI__sync_fetch_and_add_16: 5172 BuiltinIndex = 0; 5173 break; 5174 5175 case Builtin::BI__sync_fetch_and_sub: 5176 case Builtin::BI__sync_fetch_and_sub_1: 5177 case Builtin::BI__sync_fetch_and_sub_2: 5178 case Builtin::BI__sync_fetch_and_sub_4: 5179 case Builtin::BI__sync_fetch_and_sub_8: 5180 case Builtin::BI__sync_fetch_and_sub_16: 5181 BuiltinIndex = 1; 5182 break; 5183 5184 case Builtin::BI__sync_fetch_and_or: 5185 case Builtin::BI__sync_fetch_and_or_1: 5186 case Builtin::BI__sync_fetch_and_or_2: 5187 case Builtin::BI__sync_fetch_and_or_4: 5188 case Builtin::BI__sync_fetch_and_or_8: 5189 case Builtin::BI__sync_fetch_and_or_16: 5190 BuiltinIndex = 2; 5191 break; 5192 5193 case Builtin::BI__sync_fetch_and_and: 5194 case Builtin::BI__sync_fetch_and_and_1: 5195 case Builtin::BI__sync_fetch_and_and_2: 5196 case Builtin::BI__sync_fetch_and_and_4: 5197 case Builtin::BI__sync_fetch_and_and_8: 5198 case Builtin::BI__sync_fetch_and_and_16: 5199 BuiltinIndex = 3; 5200 break; 5201 5202 case Builtin::BI__sync_fetch_and_xor: 5203 case Builtin::BI__sync_fetch_and_xor_1: 5204 case Builtin::BI__sync_fetch_and_xor_2: 5205 case Builtin::BI__sync_fetch_and_xor_4: 5206 case Builtin::BI__sync_fetch_and_xor_8: 5207 case Builtin::BI__sync_fetch_and_xor_16: 5208 BuiltinIndex = 4; 5209 break; 5210 5211 case Builtin::BI__sync_fetch_and_nand: 5212 case Builtin::BI__sync_fetch_and_nand_1: 5213 case Builtin::BI__sync_fetch_and_nand_2: 5214 case Builtin::BI__sync_fetch_and_nand_4: 5215 case Builtin::BI__sync_fetch_and_nand_8: 5216 case Builtin::BI__sync_fetch_and_nand_16: 5217 BuiltinIndex = 5; 5218 WarnAboutSemanticsChange = true; 5219 break; 5220 5221 case Builtin::BI__sync_add_and_fetch: 5222 case Builtin::BI__sync_add_and_fetch_1: 5223 case Builtin::BI__sync_add_and_fetch_2: 5224 case Builtin::BI__sync_add_and_fetch_4: 5225 case Builtin::BI__sync_add_and_fetch_8: 5226 case Builtin::BI__sync_add_and_fetch_16: 5227 BuiltinIndex = 6; 5228 break; 5229 5230 case Builtin::BI__sync_sub_and_fetch: 5231 case Builtin::BI__sync_sub_and_fetch_1: 5232 case Builtin::BI__sync_sub_and_fetch_2: 5233 case Builtin::BI__sync_sub_and_fetch_4: 5234 case Builtin::BI__sync_sub_and_fetch_8: 5235 case Builtin::BI__sync_sub_and_fetch_16: 5236 BuiltinIndex = 7; 5237 break; 5238 5239 case Builtin::BI__sync_and_and_fetch: 5240 case Builtin::BI__sync_and_and_fetch_1: 5241 case Builtin::BI__sync_and_and_fetch_2: 5242 case Builtin::BI__sync_and_and_fetch_4: 5243 case Builtin::BI__sync_and_and_fetch_8: 5244 case Builtin::BI__sync_and_and_fetch_16: 5245 BuiltinIndex = 8; 5246 break; 5247 5248 case Builtin::BI__sync_or_and_fetch: 5249 case Builtin::BI__sync_or_and_fetch_1: 5250 case Builtin::BI__sync_or_and_fetch_2: 5251 case Builtin::BI__sync_or_and_fetch_4: 5252 case Builtin::BI__sync_or_and_fetch_8: 5253 case Builtin::BI__sync_or_and_fetch_16: 5254 BuiltinIndex = 9; 5255 break; 5256 5257 case Builtin::BI__sync_xor_and_fetch: 5258 case Builtin::BI__sync_xor_and_fetch_1: 5259 case Builtin::BI__sync_xor_and_fetch_2: 5260 case Builtin::BI__sync_xor_and_fetch_4: 5261 case Builtin::BI__sync_xor_and_fetch_8: 5262 case Builtin::BI__sync_xor_and_fetch_16: 5263 BuiltinIndex = 10; 5264 break; 5265 5266 case Builtin::BI__sync_nand_and_fetch: 5267 case Builtin::BI__sync_nand_and_fetch_1: 5268 case Builtin::BI__sync_nand_and_fetch_2: 5269 case Builtin::BI__sync_nand_and_fetch_4: 5270 case Builtin::BI__sync_nand_and_fetch_8: 5271 case Builtin::BI__sync_nand_and_fetch_16: 5272 BuiltinIndex = 11; 5273 WarnAboutSemanticsChange = true; 5274 break; 5275 5276 case Builtin::BI__sync_val_compare_and_swap: 5277 case Builtin::BI__sync_val_compare_and_swap_1: 5278 case Builtin::BI__sync_val_compare_and_swap_2: 5279 case Builtin::BI__sync_val_compare_and_swap_4: 5280 case Builtin::BI__sync_val_compare_and_swap_8: 5281 case Builtin::BI__sync_val_compare_and_swap_16: 5282 BuiltinIndex = 12; 5283 NumFixed = 2; 5284 break; 5285 5286 case Builtin::BI__sync_bool_compare_and_swap: 5287 case Builtin::BI__sync_bool_compare_and_swap_1: 5288 case Builtin::BI__sync_bool_compare_and_swap_2: 5289 case Builtin::BI__sync_bool_compare_and_swap_4: 5290 case Builtin::BI__sync_bool_compare_and_swap_8: 5291 case Builtin::BI__sync_bool_compare_and_swap_16: 5292 BuiltinIndex = 13; 5293 NumFixed = 2; 5294 ResultType = Context.BoolTy; 5295 break; 5296 5297 case Builtin::BI__sync_lock_test_and_set: 5298 case Builtin::BI__sync_lock_test_and_set_1: 5299 case Builtin::BI__sync_lock_test_and_set_2: 5300 case Builtin::BI__sync_lock_test_and_set_4: 5301 case Builtin::BI__sync_lock_test_and_set_8: 5302 case Builtin::BI__sync_lock_test_and_set_16: 5303 BuiltinIndex = 14; 5304 break; 5305 5306 case Builtin::BI__sync_lock_release: 5307 case Builtin::BI__sync_lock_release_1: 5308 case Builtin::BI__sync_lock_release_2: 5309 case Builtin::BI__sync_lock_release_4: 5310 case Builtin::BI__sync_lock_release_8: 5311 case Builtin::BI__sync_lock_release_16: 5312 BuiltinIndex = 15; 5313 NumFixed = 0; 5314 ResultType = Context.VoidTy; 5315 break; 5316 5317 case Builtin::BI__sync_swap: 5318 case Builtin::BI__sync_swap_1: 5319 case Builtin::BI__sync_swap_2: 5320 case Builtin::BI__sync_swap_4: 5321 case Builtin::BI__sync_swap_8: 5322 case Builtin::BI__sync_swap_16: 5323 BuiltinIndex = 16; 5324 break; 5325 } 5326 5327 // Now that we know how many fixed arguments we expect, first check that we 5328 // have at least that many. 5329 if (TheCall->getNumArgs() < 1+NumFixed) { 5330 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5331 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5332 << Callee->getSourceRange(); 5333 return ExprError(); 5334 } 5335 5336 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5337 << Callee->getSourceRange(); 5338 5339 if (WarnAboutSemanticsChange) { 5340 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5341 << Callee->getSourceRange(); 5342 } 5343 5344 // Get the decl for the concrete builtin from this, we can tell what the 5345 // concrete integer type we should convert to is. 5346 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5347 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5348 FunctionDecl *NewBuiltinDecl; 5349 if (NewBuiltinID == BuiltinID) 5350 NewBuiltinDecl = FDecl; 5351 else { 5352 // Perform builtin lookup to avoid redeclaring it. 5353 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5354 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5355 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5356 assert(Res.getFoundDecl()); 5357 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5358 if (!NewBuiltinDecl) 5359 return ExprError(); 5360 } 5361 5362 // The first argument --- the pointer --- has a fixed type; we 5363 // deduce the types of the rest of the arguments accordingly. Walk 5364 // the remaining arguments, converting them to the deduced value type. 5365 for (unsigned i = 0; i != NumFixed; ++i) { 5366 ExprResult Arg = TheCall->getArg(i+1); 5367 5368 // GCC does an implicit conversion to the pointer or integer ValType. This 5369 // can fail in some cases (1i -> int**), check for this error case now. 5370 // Initialize the argument. 5371 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5372 ValType, /*consume*/ false); 5373 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5374 if (Arg.isInvalid()) 5375 return ExprError(); 5376 5377 // Okay, we have something that *can* be converted to the right type. Check 5378 // to see if there is a potentially weird extension going on here. This can 5379 // happen when you do an atomic operation on something like an char* and 5380 // pass in 42. The 42 gets converted to char. This is even more strange 5381 // for things like 45.123 -> char, etc. 5382 // FIXME: Do this check. 5383 TheCall->setArg(i+1, Arg.get()); 5384 } 5385 5386 // Create a new DeclRefExpr to refer to the new decl. 5387 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5388 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5389 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5390 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5391 5392 // Set the callee in the CallExpr. 5393 // FIXME: This loses syntactic information. 5394 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5395 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5396 CK_BuiltinFnToFnPtr); 5397 TheCall->setCallee(PromotedCall.get()); 5398 5399 // Change the result type of the call to match the original value type. This 5400 // is arbitrary, but the codegen for these builtins ins design to handle it 5401 // gracefully. 5402 TheCall->setType(ResultType); 5403 5404 return TheCallResult; 5405 } 5406 5407 /// SemaBuiltinNontemporalOverloaded - We have a call to 5408 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5409 /// overloaded function based on the pointer type of its last argument. 5410 /// 5411 /// This function goes through and does final semantic checking for these 5412 /// builtins. 5413 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5414 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5415 DeclRefExpr *DRE = 5416 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5417 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5418 unsigned BuiltinID = FDecl->getBuiltinID(); 5419 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5420 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5421 "Unexpected nontemporal load/store builtin!"); 5422 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5423 unsigned numArgs = isStore ? 2 : 1; 5424 5425 // Ensure that we have the proper number of arguments. 5426 if (checkArgCount(*this, TheCall, numArgs)) 5427 return ExprError(); 5428 5429 // Inspect the last argument of the nontemporal builtin. This should always 5430 // be a pointer type, from which we imply the type of the memory access. 5431 // Because it is a pointer type, we don't have to worry about any implicit 5432 // casts here. 5433 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5434 ExprResult PointerArgResult = 5435 DefaultFunctionArrayLvalueConversion(PointerArg); 5436 5437 if (PointerArgResult.isInvalid()) 5438 return ExprError(); 5439 PointerArg = PointerArgResult.get(); 5440 TheCall->setArg(numArgs - 1, PointerArg); 5441 5442 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5443 if (!pointerType) { 5444 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5445 << PointerArg->getType() << PointerArg->getSourceRange(); 5446 return ExprError(); 5447 } 5448 5449 QualType ValType = pointerType->getPointeeType(); 5450 5451 // Strip any qualifiers off ValType. 5452 ValType = ValType.getUnqualifiedType(); 5453 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5454 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5455 !ValType->isVectorType()) { 5456 Diag(DRE->getBeginLoc(), 5457 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5458 << PointerArg->getType() << PointerArg->getSourceRange(); 5459 return ExprError(); 5460 } 5461 5462 if (!isStore) { 5463 TheCall->setType(ValType); 5464 return TheCallResult; 5465 } 5466 5467 ExprResult ValArg = TheCall->getArg(0); 5468 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5469 Context, ValType, /*consume*/ false); 5470 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5471 if (ValArg.isInvalid()) 5472 return ExprError(); 5473 5474 TheCall->setArg(0, ValArg.get()); 5475 TheCall->setType(Context.VoidTy); 5476 return TheCallResult; 5477 } 5478 5479 /// CheckObjCString - Checks that the argument to the builtin 5480 /// CFString constructor is correct 5481 /// Note: It might also make sense to do the UTF-16 conversion here (would 5482 /// simplify the backend). 5483 bool Sema::CheckObjCString(Expr *Arg) { 5484 Arg = Arg->IgnoreParenCasts(); 5485 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5486 5487 if (!Literal || !Literal->isAscii()) { 5488 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5489 << Arg->getSourceRange(); 5490 return true; 5491 } 5492 5493 if (Literal->containsNonAsciiOrNull()) { 5494 StringRef String = Literal->getString(); 5495 unsigned NumBytes = String.size(); 5496 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5497 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5498 llvm::UTF16 *ToPtr = &ToBuf[0]; 5499 5500 llvm::ConversionResult Result = 5501 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5502 ToPtr + NumBytes, llvm::strictConversion); 5503 // Check for conversion failure. 5504 if (Result != llvm::conversionOK) 5505 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5506 << Arg->getSourceRange(); 5507 } 5508 return false; 5509 } 5510 5511 /// CheckObjCString - Checks that the format string argument to the os_log() 5512 /// and os_trace() functions is correct, and converts it to const char *. 5513 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5514 Arg = Arg->IgnoreParenCasts(); 5515 auto *Literal = dyn_cast<StringLiteral>(Arg); 5516 if (!Literal) { 5517 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5518 Literal = ObjcLiteral->getString(); 5519 } 5520 } 5521 5522 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5523 return ExprError( 5524 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5525 << Arg->getSourceRange()); 5526 } 5527 5528 ExprResult Result(Literal); 5529 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5530 InitializedEntity Entity = 5531 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5532 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5533 return Result; 5534 } 5535 5536 /// Check that the user is calling the appropriate va_start builtin for the 5537 /// target and calling convention. 5538 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5539 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5540 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5541 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5542 TT.getArch() == llvm::Triple::aarch64_32); 5543 bool IsWindows = TT.isOSWindows(); 5544 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5545 if (IsX64 || IsAArch64) { 5546 CallingConv CC = CC_C; 5547 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5548 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5549 if (IsMSVAStart) { 5550 // Don't allow this in System V ABI functions. 5551 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5552 return S.Diag(Fn->getBeginLoc(), 5553 diag::err_ms_va_start_used_in_sysv_function); 5554 } else { 5555 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5556 // On x64 Windows, don't allow this in System V ABI functions. 5557 // (Yes, that means there's no corresponding way to support variadic 5558 // System V ABI functions on Windows.) 5559 if ((IsWindows && CC == CC_X86_64SysV) || 5560 (!IsWindows && CC == CC_Win64)) 5561 return S.Diag(Fn->getBeginLoc(), 5562 diag::err_va_start_used_in_wrong_abi_function) 5563 << !IsWindows; 5564 } 5565 return false; 5566 } 5567 5568 if (IsMSVAStart) 5569 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5570 return false; 5571 } 5572 5573 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5574 ParmVarDecl **LastParam = nullptr) { 5575 // Determine whether the current function, block, or obj-c method is variadic 5576 // and get its parameter list. 5577 bool IsVariadic = false; 5578 ArrayRef<ParmVarDecl *> Params; 5579 DeclContext *Caller = S.CurContext; 5580 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5581 IsVariadic = Block->isVariadic(); 5582 Params = Block->parameters(); 5583 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5584 IsVariadic = FD->isVariadic(); 5585 Params = FD->parameters(); 5586 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5587 IsVariadic = MD->isVariadic(); 5588 // FIXME: This isn't correct for methods (results in bogus warning). 5589 Params = MD->parameters(); 5590 } else if (isa<CapturedDecl>(Caller)) { 5591 // We don't support va_start in a CapturedDecl. 5592 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5593 return true; 5594 } else { 5595 // This must be some other declcontext that parses exprs. 5596 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5597 return true; 5598 } 5599 5600 if (!IsVariadic) { 5601 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5602 return true; 5603 } 5604 5605 if (LastParam) 5606 *LastParam = Params.empty() ? nullptr : Params.back(); 5607 5608 return false; 5609 } 5610 5611 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5612 /// for validity. Emit an error and return true on failure; return false 5613 /// on success. 5614 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5615 Expr *Fn = TheCall->getCallee(); 5616 5617 if (checkVAStartABI(*this, BuiltinID, Fn)) 5618 return true; 5619 5620 if (TheCall->getNumArgs() > 2) { 5621 Diag(TheCall->getArg(2)->getBeginLoc(), 5622 diag::err_typecheck_call_too_many_args) 5623 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5624 << Fn->getSourceRange() 5625 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5626 (*(TheCall->arg_end() - 1))->getEndLoc()); 5627 return true; 5628 } 5629 5630 if (TheCall->getNumArgs() < 2) { 5631 return Diag(TheCall->getEndLoc(), 5632 diag::err_typecheck_call_too_few_args_at_least) 5633 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5634 } 5635 5636 // Type-check the first argument normally. 5637 if (checkBuiltinArgument(*this, TheCall, 0)) 5638 return true; 5639 5640 // Check that the current function is variadic, and get its last parameter. 5641 ParmVarDecl *LastParam; 5642 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5643 return true; 5644 5645 // Verify that the second argument to the builtin is the last argument of the 5646 // current function or method. 5647 bool SecondArgIsLastNamedArgument = false; 5648 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5649 5650 // These are valid if SecondArgIsLastNamedArgument is false after the next 5651 // block. 5652 QualType Type; 5653 SourceLocation ParamLoc; 5654 bool IsCRegister = false; 5655 5656 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5657 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5658 SecondArgIsLastNamedArgument = PV == LastParam; 5659 5660 Type = PV->getType(); 5661 ParamLoc = PV->getLocation(); 5662 IsCRegister = 5663 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5664 } 5665 } 5666 5667 if (!SecondArgIsLastNamedArgument) 5668 Diag(TheCall->getArg(1)->getBeginLoc(), 5669 diag::warn_second_arg_of_va_start_not_last_named_param); 5670 else if (IsCRegister || Type->isReferenceType() || 5671 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5672 // Promotable integers are UB, but enumerations need a bit of 5673 // extra checking to see what their promotable type actually is. 5674 if (!Type->isPromotableIntegerType()) 5675 return false; 5676 if (!Type->isEnumeralType()) 5677 return true; 5678 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5679 return !(ED && 5680 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5681 }()) { 5682 unsigned Reason = 0; 5683 if (Type->isReferenceType()) Reason = 1; 5684 else if (IsCRegister) Reason = 2; 5685 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5686 Diag(ParamLoc, diag::note_parameter_type) << Type; 5687 } 5688 5689 TheCall->setType(Context.VoidTy); 5690 return false; 5691 } 5692 5693 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5694 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5695 // const char *named_addr); 5696 5697 Expr *Func = Call->getCallee(); 5698 5699 if (Call->getNumArgs() < 3) 5700 return Diag(Call->getEndLoc(), 5701 diag::err_typecheck_call_too_few_args_at_least) 5702 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5703 5704 // Type-check the first argument normally. 5705 if (checkBuiltinArgument(*this, Call, 0)) 5706 return true; 5707 5708 // Check that the current function is variadic. 5709 if (checkVAStartIsInVariadicFunction(*this, Func)) 5710 return true; 5711 5712 // __va_start on Windows does not validate the parameter qualifiers 5713 5714 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5715 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5716 5717 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5718 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5719 5720 const QualType &ConstCharPtrTy = 5721 Context.getPointerType(Context.CharTy.withConst()); 5722 if (!Arg1Ty->isPointerType() || 5723 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5724 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5725 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5726 << 0 /* qualifier difference */ 5727 << 3 /* parameter mismatch */ 5728 << 2 << Arg1->getType() << ConstCharPtrTy; 5729 5730 const QualType SizeTy = Context.getSizeType(); 5731 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5732 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5733 << Arg2->getType() << SizeTy << 1 /* different class */ 5734 << 0 /* qualifier difference */ 5735 << 3 /* parameter mismatch */ 5736 << 3 << Arg2->getType() << SizeTy; 5737 5738 return false; 5739 } 5740 5741 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5742 /// friends. This is declared to take (...), so we have to check everything. 5743 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5744 if (TheCall->getNumArgs() < 2) 5745 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5746 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5747 if (TheCall->getNumArgs() > 2) 5748 return Diag(TheCall->getArg(2)->getBeginLoc(), 5749 diag::err_typecheck_call_too_many_args) 5750 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5751 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5752 (*(TheCall->arg_end() - 1))->getEndLoc()); 5753 5754 ExprResult OrigArg0 = TheCall->getArg(0); 5755 ExprResult OrigArg1 = TheCall->getArg(1); 5756 5757 // Do standard promotions between the two arguments, returning their common 5758 // type. 5759 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5760 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5761 return true; 5762 5763 // Make sure any conversions are pushed back into the call; this is 5764 // type safe since unordered compare builtins are declared as "_Bool 5765 // foo(...)". 5766 TheCall->setArg(0, OrigArg0.get()); 5767 TheCall->setArg(1, OrigArg1.get()); 5768 5769 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5770 return false; 5771 5772 // If the common type isn't a real floating type, then the arguments were 5773 // invalid for this operation. 5774 if (Res.isNull() || !Res->isRealFloatingType()) 5775 return Diag(OrigArg0.get()->getBeginLoc(), 5776 diag::err_typecheck_call_invalid_ordered_compare) 5777 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5778 << SourceRange(OrigArg0.get()->getBeginLoc(), 5779 OrigArg1.get()->getEndLoc()); 5780 5781 return false; 5782 } 5783 5784 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5785 /// __builtin_isnan and friends. This is declared to take (...), so we have 5786 /// to check everything. We expect the last argument to be a floating point 5787 /// value. 5788 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5789 if (TheCall->getNumArgs() < NumArgs) 5790 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5791 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5792 if (TheCall->getNumArgs() > NumArgs) 5793 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5794 diag::err_typecheck_call_too_many_args) 5795 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5796 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5797 (*(TheCall->arg_end() - 1))->getEndLoc()); 5798 5799 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5800 5801 if (OrigArg->isTypeDependent()) 5802 return false; 5803 5804 // This operation requires a non-_Complex floating-point number. 5805 if (!OrigArg->getType()->isRealFloatingType()) 5806 return Diag(OrigArg->getBeginLoc(), 5807 diag::err_typecheck_call_invalid_unary_fp) 5808 << OrigArg->getType() << OrigArg->getSourceRange(); 5809 5810 // If this is an implicit conversion from float -> float, double, or 5811 // long double, or half -> half, float, double, or long double, remove it. 5812 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5813 // Only remove standard FloatCasts, leaving other casts inplace 5814 if (Cast->getCastKind() == CK_FloatingCast) { 5815 bool IgnoreCast = false; 5816 Expr *CastArg = Cast->getSubExpr(); 5817 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5818 assert( 5819 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5820 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5821 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5822 "promotion from float to either float, double, or long double is " 5823 "the only expected cast here"); 5824 IgnoreCast = true; 5825 } else if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Half) && 5826 !Context.getTargetInfo().useFP16ConversionIntrinsics()) { 5827 assert( 5828 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5829 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5830 Cast->getType()->isSpecificBuiltinType(BuiltinType::Half) || 5831 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5832 "promotion from half to either half, float, double, or long double " 5833 "is the only expected cast here"); 5834 IgnoreCast = true; 5835 } 5836 5837 if (IgnoreCast) { 5838 Cast->setSubExpr(nullptr); 5839 TheCall->setArg(NumArgs-1, CastArg); 5840 } 5841 } 5842 } 5843 5844 return false; 5845 } 5846 5847 // Customized Sema Checking for VSX builtins that have the following signature: 5848 // vector [...] builtinName(vector [...], vector [...], const int); 5849 // Which takes the same type of vectors (any legal vector type) for the first 5850 // two arguments and takes compile time constant for the third argument. 5851 // Example builtins are : 5852 // vector double vec_xxpermdi(vector double, vector double, int); 5853 // vector short vec_xxsldwi(vector short, vector short, int); 5854 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5855 unsigned ExpectedNumArgs = 3; 5856 if (TheCall->getNumArgs() < ExpectedNumArgs) 5857 return Diag(TheCall->getEndLoc(), 5858 diag::err_typecheck_call_too_few_args_at_least) 5859 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5860 << TheCall->getSourceRange(); 5861 5862 if (TheCall->getNumArgs() > ExpectedNumArgs) 5863 return Diag(TheCall->getEndLoc(), 5864 diag::err_typecheck_call_too_many_args_at_most) 5865 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5866 << TheCall->getSourceRange(); 5867 5868 // Check the third argument is a compile time constant 5869 llvm::APSInt Value; 5870 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5871 return Diag(TheCall->getBeginLoc(), 5872 diag::err_vsx_builtin_nonconstant_argument) 5873 << 3 /* argument index */ << TheCall->getDirectCallee() 5874 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5875 TheCall->getArg(2)->getEndLoc()); 5876 5877 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5878 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5879 5880 // Check the type of argument 1 and argument 2 are vectors. 5881 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5882 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5883 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5884 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5885 << TheCall->getDirectCallee() 5886 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5887 TheCall->getArg(1)->getEndLoc()); 5888 } 5889 5890 // Check the first two arguments are the same type. 5891 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5892 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5893 << TheCall->getDirectCallee() 5894 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5895 TheCall->getArg(1)->getEndLoc()); 5896 } 5897 5898 // When default clang type checking is turned off and the customized type 5899 // checking is used, the returning type of the function must be explicitly 5900 // set. Otherwise it is _Bool by default. 5901 TheCall->setType(Arg1Ty); 5902 5903 return false; 5904 } 5905 5906 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5907 // This is declared to take (...), so we have to check everything. 5908 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5909 if (TheCall->getNumArgs() < 2) 5910 return ExprError(Diag(TheCall->getEndLoc(), 5911 diag::err_typecheck_call_too_few_args_at_least) 5912 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5913 << TheCall->getSourceRange()); 5914 5915 // Determine which of the following types of shufflevector we're checking: 5916 // 1) unary, vector mask: (lhs, mask) 5917 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5918 QualType resType = TheCall->getArg(0)->getType(); 5919 unsigned numElements = 0; 5920 5921 if (!TheCall->getArg(0)->isTypeDependent() && 5922 !TheCall->getArg(1)->isTypeDependent()) { 5923 QualType LHSType = TheCall->getArg(0)->getType(); 5924 QualType RHSType = TheCall->getArg(1)->getType(); 5925 5926 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5927 return ExprError( 5928 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5929 << TheCall->getDirectCallee() 5930 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5931 TheCall->getArg(1)->getEndLoc())); 5932 5933 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5934 unsigned numResElements = TheCall->getNumArgs() - 2; 5935 5936 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5937 // with mask. If so, verify that RHS is an integer vector type with the 5938 // same number of elts as lhs. 5939 if (TheCall->getNumArgs() == 2) { 5940 if (!RHSType->hasIntegerRepresentation() || 5941 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5942 return ExprError(Diag(TheCall->getBeginLoc(), 5943 diag::err_vec_builtin_incompatible_vector) 5944 << TheCall->getDirectCallee() 5945 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5946 TheCall->getArg(1)->getEndLoc())); 5947 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5948 return ExprError(Diag(TheCall->getBeginLoc(), 5949 diag::err_vec_builtin_incompatible_vector) 5950 << TheCall->getDirectCallee() 5951 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5952 TheCall->getArg(1)->getEndLoc())); 5953 } else if (numElements != numResElements) { 5954 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5955 resType = Context.getVectorType(eltType, numResElements, 5956 VectorType::GenericVector); 5957 } 5958 } 5959 5960 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5961 if (TheCall->getArg(i)->isTypeDependent() || 5962 TheCall->getArg(i)->isValueDependent()) 5963 continue; 5964 5965 llvm::APSInt Result(32); 5966 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5967 return ExprError(Diag(TheCall->getBeginLoc(), 5968 diag::err_shufflevector_nonconstant_argument) 5969 << TheCall->getArg(i)->getSourceRange()); 5970 5971 // Allow -1 which will be translated to undef in the IR. 5972 if (Result.isSigned() && Result.isAllOnesValue()) 5973 continue; 5974 5975 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5976 return ExprError(Diag(TheCall->getBeginLoc(), 5977 diag::err_shufflevector_argument_too_large) 5978 << TheCall->getArg(i)->getSourceRange()); 5979 } 5980 5981 SmallVector<Expr*, 32> exprs; 5982 5983 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5984 exprs.push_back(TheCall->getArg(i)); 5985 TheCall->setArg(i, nullptr); 5986 } 5987 5988 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5989 TheCall->getCallee()->getBeginLoc(), 5990 TheCall->getRParenLoc()); 5991 } 5992 5993 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5994 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5995 SourceLocation BuiltinLoc, 5996 SourceLocation RParenLoc) { 5997 ExprValueKind VK = VK_RValue; 5998 ExprObjectKind OK = OK_Ordinary; 5999 QualType DstTy = TInfo->getType(); 6000 QualType SrcTy = E->getType(); 6001 6002 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6003 return ExprError(Diag(BuiltinLoc, 6004 diag::err_convertvector_non_vector) 6005 << E->getSourceRange()); 6006 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6007 return ExprError(Diag(BuiltinLoc, 6008 diag::err_convertvector_non_vector_type)); 6009 6010 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6011 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6012 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6013 if (SrcElts != DstElts) 6014 return ExprError(Diag(BuiltinLoc, 6015 diag::err_convertvector_incompatible_vector) 6016 << E->getSourceRange()); 6017 } 6018 6019 return new (Context) 6020 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6021 } 6022 6023 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6024 // This is declared to take (const void*, ...) and can take two 6025 // optional constant int args. 6026 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6027 unsigned NumArgs = TheCall->getNumArgs(); 6028 6029 if (NumArgs > 3) 6030 return Diag(TheCall->getEndLoc(), 6031 diag::err_typecheck_call_too_many_args_at_most) 6032 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6033 6034 // Argument 0 is checked for us and the remaining arguments must be 6035 // constant integers. 6036 for (unsigned i = 1; i != NumArgs; ++i) 6037 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6038 return true; 6039 6040 return false; 6041 } 6042 6043 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6044 // __assume does not evaluate its arguments, and should warn if its argument 6045 // has side effects. 6046 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6047 Expr *Arg = TheCall->getArg(0); 6048 if (Arg->isInstantiationDependent()) return false; 6049 6050 if (Arg->HasSideEffects(Context)) 6051 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6052 << Arg->getSourceRange() 6053 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6054 6055 return false; 6056 } 6057 6058 /// Handle __builtin_alloca_with_align. This is declared 6059 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6060 /// than 8. 6061 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6062 // The alignment must be a constant integer. 6063 Expr *Arg = TheCall->getArg(1); 6064 6065 // We can't check the value of a dependent argument. 6066 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6067 if (const auto *UE = 6068 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6069 if (UE->getKind() == UETT_AlignOf || 6070 UE->getKind() == UETT_PreferredAlignOf) 6071 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6072 << Arg->getSourceRange(); 6073 6074 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6075 6076 if (!Result.isPowerOf2()) 6077 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6078 << Arg->getSourceRange(); 6079 6080 if (Result < Context.getCharWidth()) 6081 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6082 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6083 6084 if (Result > std::numeric_limits<int32_t>::max()) 6085 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6086 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6087 } 6088 6089 return false; 6090 } 6091 6092 /// Handle __builtin_assume_aligned. This is declared 6093 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6094 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6095 unsigned NumArgs = TheCall->getNumArgs(); 6096 6097 if (NumArgs > 3) 6098 return Diag(TheCall->getEndLoc(), 6099 diag::err_typecheck_call_too_many_args_at_most) 6100 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6101 6102 // The alignment must be a constant integer. 6103 Expr *Arg = TheCall->getArg(1); 6104 6105 // We can't check the value of a dependent argument. 6106 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6107 llvm::APSInt Result; 6108 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6109 return true; 6110 6111 if (!Result.isPowerOf2()) 6112 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6113 << Arg->getSourceRange(); 6114 6115 // Alignment calculations can wrap around if it's greater than 2**29. 6116 unsigned MaximumAlignment = 536870912; 6117 if (Result > MaximumAlignment) 6118 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6119 << Arg->getSourceRange() << MaximumAlignment; 6120 } 6121 6122 if (NumArgs > 2) { 6123 ExprResult Arg(TheCall->getArg(2)); 6124 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6125 Context.getSizeType(), false); 6126 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6127 if (Arg.isInvalid()) return true; 6128 TheCall->setArg(2, Arg.get()); 6129 } 6130 6131 return false; 6132 } 6133 6134 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6135 unsigned BuiltinID = 6136 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6137 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6138 6139 unsigned NumArgs = TheCall->getNumArgs(); 6140 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6141 if (NumArgs < NumRequiredArgs) { 6142 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6143 << 0 /* function call */ << NumRequiredArgs << NumArgs 6144 << TheCall->getSourceRange(); 6145 } 6146 if (NumArgs >= NumRequiredArgs + 0x100) { 6147 return Diag(TheCall->getEndLoc(), 6148 diag::err_typecheck_call_too_many_args_at_most) 6149 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6150 << TheCall->getSourceRange(); 6151 } 6152 unsigned i = 0; 6153 6154 // For formatting call, check buffer arg. 6155 if (!IsSizeCall) { 6156 ExprResult Arg(TheCall->getArg(i)); 6157 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6158 Context, Context.VoidPtrTy, false); 6159 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6160 if (Arg.isInvalid()) 6161 return true; 6162 TheCall->setArg(i, Arg.get()); 6163 i++; 6164 } 6165 6166 // Check string literal arg. 6167 unsigned FormatIdx = i; 6168 { 6169 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6170 if (Arg.isInvalid()) 6171 return true; 6172 TheCall->setArg(i, Arg.get()); 6173 i++; 6174 } 6175 6176 // Make sure variadic args are scalar. 6177 unsigned FirstDataArg = i; 6178 while (i < NumArgs) { 6179 ExprResult Arg = DefaultVariadicArgumentPromotion( 6180 TheCall->getArg(i), VariadicFunction, nullptr); 6181 if (Arg.isInvalid()) 6182 return true; 6183 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6184 if (ArgSize.getQuantity() >= 0x100) { 6185 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6186 << i << (int)ArgSize.getQuantity() << 0xff 6187 << TheCall->getSourceRange(); 6188 } 6189 TheCall->setArg(i, Arg.get()); 6190 i++; 6191 } 6192 6193 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6194 // call to avoid duplicate diagnostics. 6195 if (!IsSizeCall) { 6196 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6197 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6198 bool Success = CheckFormatArguments( 6199 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6200 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6201 CheckedVarArgs); 6202 if (!Success) 6203 return true; 6204 } 6205 6206 if (IsSizeCall) { 6207 TheCall->setType(Context.getSizeType()); 6208 } else { 6209 TheCall->setType(Context.VoidPtrTy); 6210 } 6211 return false; 6212 } 6213 6214 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6215 /// TheCall is a constant expression. 6216 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6217 llvm::APSInt &Result) { 6218 Expr *Arg = TheCall->getArg(ArgNum); 6219 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6220 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6221 6222 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6223 6224 if (!Arg->isIntegerConstantExpr(Result, Context)) 6225 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6226 << FDecl->getDeclName() << Arg->getSourceRange(); 6227 6228 return false; 6229 } 6230 6231 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6232 /// TheCall is a constant expression in the range [Low, High]. 6233 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6234 int Low, int High, bool RangeIsError) { 6235 if (isConstantEvaluated()) 6236 return false; 6237 llvm::APSInt Result; 6238 6239 // We can't check the value of a dependent argument. 6240 Expr *Arg = TheCall->getArg(ArgNum); 6241 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6242 return false; 6243 6244 // Check constant-ness first. 6245 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6246 return true; 6247 6248 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6249 if (RangeIsError) 6250 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6251 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6252 else 6253 // Defer the warning until we know if the code will be emitted so that 6254 // dead code can ignore this. 6255 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6256 PDiag(diag::warn_argument_invalid_range) 6257 << Result.toString(10) << Low << High 6258 << Arg->getSourceRange()); 6259 } 6260 6261 return false; 6262 } 6263 6264 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6265 /// TheCall is a constant expression is a multiple of Num.. 6266 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6267 unsigned Num) { 6268 llvm::APSInt Result; 6269 6270 // We can't check the value of a dependent argument. 6271 Expr *Arg = TheCall->getArg(ArgNum); 6272 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6273 return false; 6274 6275 // Check constant-ness first. 6276 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6277 return true; 6278 6279 if (Result.getSExtValue() % Num != 0) 6280 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6281 << Num << Arg->getSourceRange(); 6282 6283 return false; 6284 } 6285 6286 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6287 /// constant expression representing a power of 2. 6288 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6289 llvm::APSInt Result; 6290 6291 // We can't check the value of a dependent argument. 6292 Expr *Arg = TheCall->getArg(ArgNum); 6293 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6294 return false; 6295 6296 // Check constant-ness first. 6297 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6298 return true; 6299 6300 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6301 // and only if x is a power of 2. 6302 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6303 return false; 6304 6305 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6306 << Arg->getSourceRange(); 6307 } 6308 6309 static bool IsShiftedByte(llvm::APSInt Value) { 6310 if (Value.isNegative()) 6311 return false; 6312 6313 // Check if it's a shifted byte, by shifting it down 6314 while (true) { 6315 // If the value fits in the bottom byte, the check passes. 6316 if (Value < 0x100) 6317 return true; 6318 6319 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6320 // fails. 6321 if ((Value & 0xFF) != 0) 6322 return false; 6323 6324 // If the bottom 8 bits are all 0, but something above that is nonzero, 6325 // then shifting the value right by 8 bits won't affect whether it's a 6326 // shifted byte or not. So do that, and go round again. 6327 Value >>= 8; 6328 } 6329 } 6330 6331 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6332 /// a constant expression representing an arbitrary byte value shifted left by 6333 /// a multiple of 8 bits. 6334 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum) { 6335 llvm::APSInt Result; 6336 6337 // We can't check the value of a dependent argument. 6338 Expr *Arg = TheCall->getArg(ArgNum); 6339 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6340 return false; 6341 6342 // Check constant-ness first. 6343 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6344 return true; 6345 6346 if (IsShiftedByte(Result)) 6347 return false; 6348 6349 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6350 << Arg->getSourceRange(); 6351 } 6352 6353 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6354 /// TheCall is a constant expression representing either a shifted byte value, 6355 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6356 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6357 /// Arm MVE intrinsics. 6358 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6359 int ArgNum) { 6360 llvm::APSInt Result; 6361 6362 // We can't check the value of a dependent argument. 6363 Expr *Arg = TheCall->getArg(ArgNum); 6364 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6365 return false; 6366 6367 // Check constant-ness first. 6368 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6369 return true; 6370 6371 // Check to see if it's in either of the required forms. 6372 if (IsShiftedByte(Result) || 6373 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6374 return false; 6375 6376 return Diag(TheCall->getBeginLoc(), 6377 diag::err_argument_not_shifted_byte_or_xxff) 6378 << Arg->getSourceRange(); 6379 } 6380 6381 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6382 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6383 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6384 if (checkArgCount(*this, TheCall, 2)) 6385 return true; 6386 Expr *Arg0 = TheCall->getArg(0); 6387 Expr *Arg1 = TheCall->getArg(1); 6388 6389 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6390 if (FirstArg.isInvalid()) 6391 return true; 6392 QualType FirstArgType = FirstArg.get()->getType(); 6393 if (!FirstArgType->isAnyPointerType()) 6394 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6395 << "first" << FirstArgType << Arg0->getSourceRange(); 6396 TheCall->setArg(0, FirstArg.get()); 6397 6398 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6399 if (SecArg.isInvalid()) 6400 return true; 6401 QualType SecArgType = SecArg.get()->getType(); 6402 if (!SecArgType->isIntegerType()) 6403 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6404 << "second" << SecArgType << Arg1->getSourceRange(); 6405 6406 // Derive the return type from the pointer argument. 6407 TheCall->setType(FirstArgType); 6408 return false; 6409 } 6410 6411 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6412 if (checkArgCount(*this, TheCall, 2)) 6413 return true; 6414 6415 Expr *Arg0 = TheCall->getArg(0); 6416 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6417 if (FirstArg.isInvalid()) 6418 return true; 6419 QualType FirstArgType = FirstArg.get()->getType(); 6420 if (!FirstArgType->isAnyPointerType()) 6421 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6422 << "first" << FirstArgType << Arg0->getSourceRange(); 6423 TheCall->setArg(0, FirstArg.get()); 6424 6425 // Derive the return type from the pointer argument. 6426 TheCall->setType(FirstArgType); 6427 6428 // Second arg must be an constant in range [0,15] 6429 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6430 } 6431 6432 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6433 if (checkArgCount(*this, TheCall, 2)) 6434 return true; 6435 Expr *Arg0 = TheCall->getArg(0); 6436 Expr *Arg1 = TheCall->getArg(1); 6437 6438 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6439 if (FirstArg.isInvalid()) 6440 return true; 6441 QualType FirstArgType = FirstArg.get()->getType(); 6442 if (!FirstArgType->isAnyPointerType()) 6443 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6444 << "first" << FirstArgType << Arg0->getSourceRange(); 6445 6446 QualType SecArgType = Arg1->getType(); 6447 if (!SecArgType->isIntegerType()) 6448 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6449 << "second" << SecArgType << Arg1->getSourceRange(); 6450 TheCall->setType(Context.IntTy); 6451 return false; 6452 } 6453 6454 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6455 BuiltinID == AArch64::BI__builtin_arm_stg) { 6456 if (checkArgCount(*this, TheCall, 1)) 6457 return true; 6458 Expr *Arg0 = TheCall->getArg(0); 6459 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6460 if (FirstArg.isInvalid()) 6461 return true; 6462 6463 QualType FirstArgType = FirstArg.get()->getType(); 6464 if (!FirstArgType->isAnyPointerType()) 6465 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6466 << "first" << FirstArgType << Arg0->getSourceRange(); 6467 TheCall->setArg(0, FirstArg.get()); 6468 6469 // Derive the return type from the pointer argument. 6470 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6471 TheCall->setType(FirstArgType); 6472 return false; 6473 } 6474 6475 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6476 Expr *ArgA = TheCall->getArg(0); 6477 Expr *ArgB = TheCall->getArg(1); 6478 6479 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6480 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6481 6482 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6483 return true; 6484 6485 QualType ArgTypeA = ArgExprA.get()->getType(); 6486 QualType ArgTypeB = ArgExprB.get()->getType(); 6487 6488 auto isNull = [&] (Expr *E) -> bool { 6489 return E->isNullPointerConstant( 6490 Context, Expr::NPC_ValueDependentIsNotNull); }; 6491 6492 // argument should be either a pointer or null 6493 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6494 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6495 << "first" << ArgTypeA << ArgA->getSourceRange(); 6496 6497 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6498 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6499 << "second" << ArgTypeB << ArgB->getSourceRange(); 6500 6501 // Ensure Pointee types are compatible 6502 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6503 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6504 QualType pointeeA = ArgTypeA->getPointeeType(); 6505 QualType pointeeB = ArgTypeB->getPointeeType(); 6506 if (!Context.typesAreCompatible( 6507 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6508 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6509 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6510 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6511 << ArgB->getSourceRange(); 6512 } 6513 } 6514 6515 // at least one argument should be pointer type 6516 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6517 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6518 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6519 6520 if (isNull(ArgA)) // adopt type of the other pointer 6521 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6522 6523 if (isNull(ArgB)) 6524 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6525 6526 TheCall->setArg(0, ArgExprA.get()); 6527 TheCall->setArg(1, ArgExprB.get()); 6528 TheCall->setType(Context.LongLongTy); 6529 return false; 6530 } 6531 assert(false && "Unhandled ARM MTE intrinsic"); 6532 return true; 6533 } 6534 6535 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6536 /// TheCall is an ARM/AArch64 special register string literal. 6537 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6538 int ArgNum, unsigned ExpectedFieldNum, 6539 bool AllowName) { 6540 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6541 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6542 BuiltinID == ARM::BI__builtin_arm_rsr || 6543 BuiltinID == ARM::BI__builtin_arm_rsrp || 6544 BuiltinID == ARM::BI__builtin_arm_wsr || 6545 BuiltinID == ARM::BI__builtin_arm_wsrp; 6546 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6547 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6548 BuiltinID == AArch64::BI__builtin_arm_rsr || 6549 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6550 BuiltinID == AArch64::BI__builtin_arm_wsr || 6551 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6552 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6553 6554 // We can't check the value of a dependent argument. 6555 Expr *Arg = TheCall->getArg(ArgNum); 6556 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6557 return false; 6558 6559 // Check if the argument is a string literal. 6560 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6561 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6562 << Arg->getSourceRange(); 6563 6564 // Check the type of special register given. 6565 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6566 SmallVector<StringRef, 6> Fields; 6567 Reg.split(Fields, ":"); 6568 6569 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6570 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6571 << Arg->getSourceRange(); 6572 6573 // If the string is the name of a register then we cannot check that it is 6574 // valid here but if the string is of one the forms described in ACLE then we 6575 // can check that the supplied fields are integers and within the valid 6576 // ranges. 6577 if (Fields.size() > 1) { 6578 bool FiveFields = Fields.size() == 5; 6579 6580 bool ValidString = true; 6581 if (IsARMBuiltin) { 6582 ValidString &= Fields[0].startswith_lower("cp") || 6583 Fields[0].startswith_lower("p"); 6584 if (ValidString) 6585 Fields[0] = 6586 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6587 6588 ValidString &= Fields[2].startswith_lower("c"); 6589 if (ValidString) 6590 Fields[2] = Fields[2].drop_front(1); 6591 6592 if (FiveFields) { 6593 ValidString &= Fields[3].startswith_lower("c"); 6594 if (ValidString) 6595 Fields[3] = Fields[3].drop_front(1); 6596 } 6597 } 6598 6599 SmallVector<int, 5> Ranges; 6600 if (FiveFields) 6601 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6602 else 6603 Ranges.append({15, 7, 15}); 6604 6605 for (unsigned i=0; i<Fields.size(); ++i) { 6606 int IntField; 6607 ValidString &= !Fields[i].getAsInteger(10, IntField); 6608 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6609 } 6610 6611 if (!ValidString) 6612 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6613 << Arg->getSourceRange(); 6614 } else if (IsAArch64Builtin && Fields.size() == 1) { 6615 // If the register name is one of those that appear in the condition below 6616 // and the special register builtin being used is one of the write builtins, 6617 // then we require that the argument provided for writing to the register 6618 // is an integer constant expression. This is because it will be lowered to 6619 // an MSR (immediate) instruction, so we need to know the immediate at 6620 // compile time. 6621 if (TheCall->getNumArgs() != 2) 6622 return false; 6623 6624 std::string RegLower = Reg.lower(); 6625 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6626 RegLower != "pan" && RegLower != "uao") 6627 return false; 6628 6629 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6630 } 6631 6632 return false; 6633 } 6634 6635 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6636 /// This checks that the target supports __builtin_longjmp and 6637 /// that val is a constant 1. 6638 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6639 if (!Context.getTargetInfo().hasSjLjLowering()) 6640 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6641 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6642 6643 Expr *Arg = TheCall->getArg(1); 6644 llvm::APSInt Result; 6645 6646 // TODO: This is less than ideal. Overload this to take a value. 6647 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6648 return true; 6649 6650 if (Result != 1) 6651 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6652 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6653 6654 return false; 6655 } 6656 6657 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6658 /// This checks that the target supports __builtin_setjmp. 6659 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6660 if (!Context.getTargetInfo().hasSjLjLowering()) 6661 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6662 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6663 return false; 6664 } 6665 6666 namespace { 6667 6668 class UncoveredArgHandler { 6669 enum { Unknown = -1, AllCovered = -2 }; 6670 6671 signed FirstUncoveredArg = Unknown; 6672 SmallVector<const Expr *, 4> DiagnosticExprs; 6673 6674 public: 6675 UncoveredArgHandler() = default; 6676 6677 bool hasUncoveredArg() const { 6678 return (FirstUncoveredArg >= 0); 6679 } 6680 6681 unsigned getUncoveredArg() const { 6682 assert(hasUncoveredArg() && "no uncovered argument"); 6683 return FirstUncoveredArg; 6684 } 6685 6686 void setAllCovered() { 6687 // A string has been found with all arguments covered, so clear out 6688 // the diagnostics. 6689 DiagnosticExprs.clear(); 6690 FirstUncoveredArg = AllCovered; 6691 } 6692 6693 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6694 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6695 6696 // Don't update if a previous string covers all arguments. 6697 if (FirstUncoveredArg == AllCovered) 6698 return; 6699 6700 // UncoveredArgHandler tracks the highest uncovered argument index 6701 // and with it all the strings that match this index. 6702 if (NewFirstUncoveredArg == FirstUncoveredArg) 6703 DiagnosticExprs.push_back(StrExpr); 6704 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6705 DiagnosticExprs.clear(); 6706 DiagnosticExprs.push_back(StrExpr); 6707 FirstUncoveredArg = NewFirstUncoveredArg; 6708 } 6709 } 6710 6711 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6712 }; 6713 6714 enum StringLiteralCheckType { 6715 SLCT_NotALiteral, 6716 SLCT_UncheckedLiteral, 6717 SLCT_CheckedLiteral 6718 }; 6719 6720 } // namespace 6721 6722 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6723 BinaryOperatorKind BinOpKind, 6724 bool AddendIsRight) { 6725 unsigned BitWidth = Offset.getBitWidth(); 6726 unsigned AddendBitWidth = Addend.getBitWidth(); 6727 // There might be negative interim results. 6728 if (Addend.isUnsigned()) { 6729 Addend = Addend.zext(++AddendBitWidth); 6730 Addend.setIsSigned(true); 6731 } 6732 // Adjust the bit width of the APSInts. 6733 if (AddendBitWidth > BitWidth) { 6734 Offset = Offset.sext(AddendBitWidth); 6735 BitWidth = AddendBitWidth; 6736 } else if (BitWidth > AddendBitWidth) { 6737 Addend = Addend.sext(BitWidth); 6738 } 6739 6740 bool Ov = false; 6741 llvm::APSInt ResOffset = Offset; 6742 if (BinOpKind == BO_Add) 6743 ResOffset = Offset.sadd_ov(Addend, Ov); 6744 else { 6745 assert(AddendIsRight && BinOpKind == BO_Sub && 6746 "operator must be add or sub with addend on the right"); 6747 ResOffset = Offset.ssub_ov(Addend, Ov); 6748 } 6749 6750 // We add an offset to a pointer here so we should support an offset as big as 6751 // possible. 6752 if (Ov) { 6753 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6754 "index (intermediate) result too big"); 6755 Offset = Offset.sext(2 * BitWidth); 6756 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6757 return; 6758 } 6759 6760 Offset = ResOffset; 6761 } 6762 6763 namespace { 6764 6765 // This is a wrapper class around StringLiteral to support offsetted string 6766 // literals as format strings. It takes the offset into account when returning 6767 // the string and its length or the source locations to display notes correctly. 6768 class FormatStringLiteral { 6769 const StringLiteral *FExpr; 6770 int64_t Offset; 6771 6772 public: 6773 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6774 : FExpr(fexpr), Offset(Offset) {} 6775 6776 StringRef getString() const { 6777 return FExpr->getString().drop_front(Offset); 6778 } 6779 6780 unsigned getByteLength() const { 6781 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6782 } 6783 6784 unsigned getLength() const { return FExpr->getLength() - Offset; } 6785 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6786 6787 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6788 6789 QualType getType() const { return FExpr->getType(); } 6790 6791 bool isAscii() const { return FExpr->isAscii(); } 6792 bool isWide() const { return FExpr->isWide(); } 6793 bool isUTF8() const { return FExpr->isUTF8(); } 6794 bool isUTF16() const { return FExpr->isUTF16(); } 6795 bool isUTF32() const { return FExpr->isUTF32(); } 6796 bool isPascal() const { return FExpr->isPascal(); } 6797 6798 SourceLocation getLocationOfByte( 6799 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6800 const TargetInfo &Target, unsigned *StartToken = nullptr, 6801 unsigned *StartTokenByteOffset = nullptr) const { 6802 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6803 StartToken, StartTokenByteOffset); 6804 } 6805 6806 SourceLocation getBeginLoc() const LLVM_READONLY { 6807 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6808 } 6809 6810 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6811 }; 6812 6813 } // namespace 6814 6815 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6816 const Expr *OrigFormatExpr, 6817 ArrayRef<const Expr *> Args, 6818 bool HasVAListArg, unsigned format_idx, 6819 unsigned firstDataArg, 6820 Sema::FormatStringType Type, 6821 bool inFunctionCall, 6822 Sema::VariadicCallType CallType, 6823 llvm::SmallBitVector &CheckedVarArgs, 6824 UncoveredArgHandler &UncoveredArg, 6825 bool IgnoreStringsWithoutSpecifiers); 6826 6827 // Determine if an expression is a string literal or constant string. 6828 // If this function returns false on the arguments to a function expecting a 6829 // format string, we will usually need to emit a warning. 6830 // True string literals are then checked by CheckFormatString. 6831 static StringLiteralCheckType 6832 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6833 bool HasVAListArg, unsigned format_idx, 6834 unsigned firstDataArg, Sema::FormatStringType Type, 6835 Sema::VariadicCallType CallType, bool InFunctionCall, 6836 llvm::SmallBitVector &CheckedVarArgs, 6837 UncoveredArgHandler &UncoveredArg, 6838 llvm::APSInt Offset, 6839 bool IgnoreStringsWithoutSpecifiers = false) { 6840 if (S.isConstantEvaluated()) 6841 return SLCT_NotALiteral; 6842 tryAgain: 6843 assert(Offset.isSigned() && "invalid offset"); 6844 6845 if (E->isTypeDependent() || E->isValueDependent()) 6846 return SLCT_NotALiteral; 6847 6848 E = E->IgnoreParenCasts(); 6849 6850 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6851 // Technically -Wformat-nonliteral does not warn about this case. 6852 // The behavior of printf and friends in this case is implementation 6853 // dependent. Ideally if the format string cannot be null then 6854 // it should have a 'nonnull' attribute in the function prototype. 6855 return SLCT_UncheckedLiteral; 6856 6857 switch (E->getStmtClass()) { 6858 case Stmt::BinaryConditionalOperatorClass: 6859 case Stmt::ConditionalOperatorClass: { 6860 // The expression is a literal if both sub-expressions were, and it was 6861 // completely checked only if both sub-expressions were checked. 6862 const AbstractConditionalOperator *C = 6863 cast<AbstractConditionalOperator>(E); 6864 6865 // Determine whether it is necessary to check both sub-expressions, for 6866 // example, because the condition expression is a constant that can be 6867 // evaluated at compile time. 6868 bool CheckLeft = true, CheckRight = true; 6869 6870 bool Cond; 6871 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6872 S.isConstantEvaluated())) { 6873 if (Cond) 6874 CheckRight = false; 6875 else 6876 CheckLeft = false; 6877 } 6878 6879 // We need to maintain the offsets for the right and the left hand side 6880 // separately to check if every possible indexed expression is a valid 6881 // string literal. They might have different offsets for different string 6882 // literals in the end. 6883 StringLiteralCheckType Left; 6884 if (!CheckLeft) 6885 Left = SLCT_UncheckedLiteral; 6886 else { 6887 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6888 HasVAListArg, format_idx, firstDataArg, 6889 Type, CallType, InFunctionCall, 6890 CheckedVarArgs, UncoveredArg, Offset, 6891 IgnoreStringsWithoutSpecifiers); 6892 if (Left == SLCT_NotALiteral || !CheckRight) { 6893 return Left; 6894 } 6895 } 6896 6897 StringLiteralCheckType Right = checkFormatStringExpr( 6898 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6899 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6900 IgnoreStringsWithoutSpecifiers); 6901 6902 return (CheckLeft && Left < Right) ? Left : Right; 6903 } 6904 6905 case Stmt::ImplicitCastExprClass: 6906 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6907 goto tryAgain; 6908 6909 case Stmt::OpaqueValueExprClass: 6910 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6911 E = src; 6912 goto tryAgain; 6913 } 6914 return SLCT_NotALiteral; 6915 6916 case Stmt::PredefinedExprClass: 6917 // While __func__, etc., are technically not string literals, they 6918 // cannot contain format specifiers and thus are not a security 6919 // liability. 6920 return SLCT_UncheckedLiteral; 6921 6922 case Stmt::DeclRefExprClass: { 6923 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6924 6925 // As an exception, do not flag errors for variables binding to 6926 // const string literals. 6927 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6928 bool isConstant = false; 6929 QualType T = DR->getType(); 6930 6931 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6932 isConstant = AT->getElementType().isConstant(S.Context); 6933 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6934 isConstant = T.isConstant(S.Context) && 6935 PT->getPointeeType().isConstant(S.Context); 6936 } else if (T->isObjCObjectPointerType()) { 6937 // In ObjC, there is usually no "const ObjectPointer" type, 6938 // so don't check if the pointee type is constant. 6939 isConstant = T.isConstant(S.Context); 6940 } 6941 6942 if (isConstant) { 6943 if (const Expr *Init = VD->getAnyInitializer()) { 6944 // Look through initializers like const char c[] = { "foo" } 6945 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6946 if (InitList->isStringLiteralInit()) 6947 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6948 } 6949 return checkFormatStringExpr(S, Init, Args, 6950 HasVAListArg, format_idx, 6951 firstDataArg, Type, CallType, 6952 /*InFunctionCall*/ false, CheckedVarArgs, 6953 UncoveredArg, Offset); 6954 } 6955 } 6956 6957 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6958 // special check to see if the format string is a function parameter 6959 // of the function calling the printf function. If the function 6960 // has an attribute indicating it is a printf-like function, then we 6961 // should suppress warnings concerning non-literals being used in a call 6962 // to a vprintf function. For example: 6963 // 6964 // void 6965 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6966 // va_list ap; 6967 // va_start(ap, fmt); 6968 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6969 // ... 6970 // } 6971 if (HasVAListArg) { 6972 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6973 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6974 int PVIndex = PV->getFunctionScopeIndex() + 1; 6975 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6976 // adjust for implicit parameter 6977 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6978 if (MD->isInstance()) 6979 ++PVIndex; 6980 // We also check if the formats are compatible. 6981 // We can't pass a 'scanf' string to a 'printf' function. 6982 if (PVIndex == PVFormat->getFormatIdx() && 6983 Type == S.GetFormatStringType(PVFormat)) 6984 return SLCT_UncheckedLiteral; 6985 } 6986 } 6987 } 6988 } 6989 } 6990 6991 return SLCT_NotALiteral; 6992 } 6993 6994 case Stmt::CallExprClass: 6995 case Stmt::CXXMemberCallExprClass: { 6996 const CallExpr *CE = cast<CallExpr>(E); 6997 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6998 bool IsFirst = true; 6999 StringLiteralCheckType CommonResult; 7000 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7001 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7002 StringLiteralCheckType Result = checkFormatStringExpr( 7003 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7004 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7005 IgnoreStringsWithoutSpecifiers); 7006 if (IsFirst) { 7007 CommonResult = Result; 7008 IsFirst = false; 7009 } 7010 } 7011 if (!IsFirst) 7012 return CommonResult; 7013 7014 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7015 unsigned BuiltinID = FD->getBuiltinID(); 7016 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7017 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7018 const Expr *Arg = CE->getArg(0); 7019 return checkFormatStringExpr(S, Arg, Args, 7020 HasVAListArg, format_idx, 7021 firstDataArg, Type, CallType, 7022 InFunctionCall, CheckedVarArgs, 7023 UncoveredArg, Offset, 7024 IgnoreStringsWithoutSpecifiers); 7025 } 7026 } 7027 } 7028 7029 return SLCT_NotALiteral; 7030 } 7031 case Stmt::ObjCMessageExprClass: { 7032 const auto *ME = cast<ObjCMessageExpr>(E); 7033 if (const auto *MD = ME->getMethodDecl()) { 7034 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7035 // As a special case heuristic, if we're using the method -[NSBundle 7036 // localizedStringForKey:value:table:], ignore any key strings that lack 7037 // format specifiers. The idea is that if the key doesn't have any 7038 // format specifiers then its probably just a key to map to the 7039 // localized strings. If it does have format specifiers though, then its 7040 // likely that the text of the key is the format string in the 7041 // programmer's language, and should be checked. 7042 const ObjCInterfaceDecl *IFace; 7043 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7044 IFace->getIdentifier()->isStr("NSBundle") && 7045 MD->getSelector().isKeywordSelector( 7046 {"localizedStringForKey", "value", "table"})) { 7047 IgnoreStringsWithoutSpecifiers = true; 7048 } 7049 7050 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7051 return checkFormatStringExpr( 7052 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7053 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7054 IgnoreStringsWithoutSpecifiers); 7055 } 7056 } 7057 7058 return SLCT_NotALiteral; 7059 } 7060 case Stmt::ObjCStringLiteralClass: 7061 case Stmt::StringLiteralClass: { 7062 const StringLiteral *StrE = nullptr; 7063 7064 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7065 StrE = ObjCFExpr->getString(); 7066 else 7067 StrE = cast<StringLiteral>(E); 7068 7069 if (StrE) { 7070 if (Offset.isNegative() || Offset > StrE->getLength()) { 7071 // TODO: It would be better to have an explicit warning for out of 7072 // bounds literals. 7073 return SLCT_NotALiteral; 7074 } 7075 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7076 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7077 firstDataArg, Type, InFunctionCall, CallType, 7078 CheckedVarArgs, UncoveredArg, 7079 IgnoreStringsWithoutSpecifiers); 7080 return SLCT_CheckedLiteral; 7081 } 7082 7083 return SLCT_NotALiteral; 7084 } 7085 case Stmt::BinaryOperatorClass: { 7086 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7087 7088 // A string literal + an int offset is still a string literal. 7089 if (BinOp->isAdditiveOp()) { 7090 Expr::EvalResult LResult, RResult; 7091 7092 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7093 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7094 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7095 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7096 7097 if (LIsInt != RIsInt) { 7098 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7099 7100 if (LIsInt) { 7101 if (BinOpKind == BO_Add) { 7102 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7103 E = BinOp->getRHS(); 7104 goto tryAgain; 7105 } 7106 } else { 7107 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7108 E = BinOp->getLHS(); 7109 goto tryAgain; 7110 } 7111 } 7112 } 7113 7114 return SLCT_NotALiteral; 7115 } 7116 case Stmt::UnaryOperatorClass: { 7117 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7118 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7119 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7120 Expr::EvalResult IndexResult; 7121 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7122 Expr::SE_NoSideEffects, 7123 S.isConstantEvaluated())) { 7124 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7125 /*RHS is int*/ true); 7126 E = ASE->getBase(); 7127 goto tryAgain; 7128 } 7129 } 7130 7131 return SLCT_NotALiteral; 7132 } 7133 7134 default: 7135 return SLCT_NotALiteral; 7136 } 7137 } 7138 7139 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7140 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7141 .Case("scanf", FST_Scanf) 7142 .Cases("printf", "printf0", FST_Printf) 7143 .Cases("NSString", "CFString", FST_NSString) 7144 .Case("strftime", FST_Strftime) 7145 .Case("strfmon", FST_Strfmon) 7146 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7147 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7148 .Case("os_trace", FST_OSLog) 7149 .Case("os_log", FST_OSLog) 7150 .Default(FST_Unknown); 7151 } 7152 7153 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7154 /// functions) for correct use of format strings. 7155 /// Returns true if a format string has been fully checked. 7156 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7157 ArrayRef<const Expr *> Args, 7158 bool IsCXXMember, 7159 VariadicCallType CallType, 7160 SourceLocation Loc, SourceRange Range, 7161 llvm::SmallBitVector &CheckedVarArgs) { 7162 FormatStringInfo FSI; 7163 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7164 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7165 FSI.FirstDataArg, GetFormatStringType(Format), 7166 CallType, Loc, Range, CheckedVarArgs); 7167 return false; 7168 } 7169 7170 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7171 bool HasVAListArg, unsigned format_idx, 7172 unsigned firstDataArg, FormatStringType Type, 7173 VariadicCallType CallType, 7174 SourceLocation Loc, SourceRange Range, 7175 llvm::SmallBitVector &CheckedVarArgs) { 7176 // CHECK: printf/scanf-like function is called with no format string. 7177 if (format_idx >= Args.size()) { 7178 Diag(Loc, diag::warn_missing_format_string) << Range; 7179 return false; 7180 } 7181 7182 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7183 7184 // CHECK: format string is not a string literal. 7185 // 7186 // Dynamically generated format strings are difficult to 7187 // automatically vet at compile time. Requiring that format strings 7188 // are string literals: (1) permits the checking of format strings by 7189 // the compiler and thereby (2) can practically remove the source of 7190 // many format string exploits. 7191 7192 // Format string can be either ObjC string (e.g. @"%d") or 7193 // C string (e.g. "%d") 7194 // ObjC string uses the same format specifiers as C string, so we can use 7195 // the same format string checking logic for both ObjC and C strings. 7196 UncoveredArgHandler UncoveredArg; 7197 StringLiteralCheckType CT = 7198 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7199 format_idx, firstDataArg, Type, CallType, 7200 /*IsFunctionCall*/ true, CheckedVarArgs, 7201 UncoveredArg, 7202 /*no string offset*/ llvm::APSInt(64, false) = 0); 7203 7204 // Generate a diagnostic where an uncovered argument is detected. 7205 if (UncoveredArg.hasUncoveredArg()) { 7206 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7207 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7208 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7209 } 7210 7211 if (CT != SLCT_NotALiteral) 7212 // Literal format string found, check done! 7213 return CT == SLCT_CheckedLiteral; 7214 7215 // Strftime is particular as it always uses a single 'time' argument, 7216 // so it is safe to pass a non-literal string. 7217 if (Type == FST_Strftime) 7218 return false; 7219 7220 // Do not emit diag when the string param is a macro expansion and the 7221 // format is either NSString or CFString. This is a hack to prevent 7222 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7223 // which are usually used in place of NS and CF string literals. 7224 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7225 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7226 return false; 7227 7228 // If there are no arguments specified, warn with -Wformat-security, otherwise 7229 // warn only with -Wformat-nonliteral. 7230 if (Args.size() == firstDataArg) { 7231 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7232 << OrigFormatExpr->getSourceRange(); 7233 switch (Type) { 7234 default: 7235 break; 7236 case FST_Kprintf: 7237 case FST_FreeBSDKPrintf: 7238 case FST_Printf: 7239 Diag(FormatLoc, diag::note_format_security_fixit) 7240 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7241 break; 7242 case FST_NSString: 7243 Diag(FormatLoc, diag::note_format_security_fixit) 7244 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7245 break; 7246 } 7247 } else { 7248 Diag(FormatLoc, diag::warn_format_nonliteral) 7249 << OrigFormatExpr->getSourceRange(); 7250 } 7251 return false; 7252 } 7253 7254 namespace { 7255 7256 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7257 protected: 7258 Sema &S; 7259 const FormatStringLiteral *FExpr; 7260 const Expr *OrigFormatExpr; 7261 const Sema::FormatStringType FSType; 7262 const unsigned FirstDataArg; 7263 const unsigned NumDataArgs; 7264 const char *Beg; // Start of format string. 7265 const bool HasVAListArg; 7266 ArrayRef<const Expr *> Args; 7267 unsigned FormatIdx; 7268 llvm::SmallBitVector CoveredArgs; 7269 bool usesPositionalArgs = false; 7270 bool atFirstArg = true; 7271 bool inFunctionCall; 7272 Sema::VariadicCallType CallType; 7273 llvm::SmallBitVector &CheckedVarArgs; 7274 UncoveredArgHandler &UncoveredArg; 7275 7276 public: 7277 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7278 const Expr *origFormatExpr, 7279 const Sema::FormatStringType type, unsigned firstDataArg, 7280 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7281 ArrayRef<const Expr *> Args, unsigned formatIdx, 7282 bool inFunctionCall, Sema::VariadicCallType callType, 7283 llvm::SmallBitVector &CheckedVarArgs, 7284 UncoveredArgHandler &UncoveredArg) 7285 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7286 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7287 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7288 inFunctionCall(inFunctionCall), CallType(callType), 7289 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7290 CoveredArgs.resize(numDataArgs); 7291 CoveredArgs.reset(); 7292 } 7293 7294 void DoneProcessing(); 7295 7296 void HandleIncompleteSpecifier(const char *startSpecifier, 7297 unsigned specifierLen) override; 7298 7299 void HandleInvalidLengthModifier( 7300 const analyze_format_string::FormatSpecifier &FS, 7301 const analyze_format_string::ConversionSpecifier &CS, 7302 const char *startSpecifier, unsigned specifierLen, 7303 unsigned DiagID); 7304 7305 void HandleNonStandardLengthModifier( 7306 const analyze_format_string::FormatSpecifier &FS, 7307 const char *startSpecifier, unsigned specifierLen); 7308 7309 void HandleNonStandardConversionSpecifier( 7310 const analyze_format_string::ConversionSpecifier &CS, 7311 const char *startSpecifier, unsigned specifierLen); 7312 7313 void HandlePosition(const char *startPos, unsigned posLen) override; 7314 7315 void HandleInvalidPosition(const char *startSpecifier, 7316 unsigned specifierLen, 7317 analyze_format_string::PositionContext p) override; 7318 7319 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7320 7321 void HandleNullChar(const char *nullCharacter) override; 7322 7323 template <typename Range> 7324 static void 7325 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7326 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7327 bool IsStringLocation, Range StringRange, 7328 ArrayRef<FixItHint> Fixit = None); 7329 7330 protected: 7331 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7332 const char *startSpec, 7333 unsigned specifierLen, 7334 const char *csStart, unsigned csLen); 7335 7336 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7337 const char *startSpec, 7338 unsigned specifierLen); 7339 7340 SourceRange getFormatStringRange(); 7341 CharSourceRange getSpecifierRange(const char *startSpecifier, 7342 unsigned specifierLen); 7343 SourceLocation getLocationOfByte(const char *x); 7344 7345 const Expr *getDataArg(unsigned i) const; 7346 7347 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7348 const analyze_format_string::ConversionSpecifier &CS, 7349 const char *startSpecifier, unsigned specifierLen, 7350 unsigned argIndex); 7351 7352 template <typename Range> 7353 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7354 bool IsStringLocation, Range StringRange, 7355 ArrayRef<FixItHint> Fixit = None); 7356 }; 7357 7358 } // namespace 7359 7360 SourceRange CheckFormatHandler::getFormatStringRange() { 7361 return OrigFormatExpr->getSourceRange(); 7362 } 7363 7364 CharSourceRange CheckFormatHandler:: 7365 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7366 SourceLocation Start = getLocationOfByte(startSpecifier); 7367 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7368 7369 // Advance the end SourceLocation by one due to half-open ranges. 7370 End = End.getLocWithOffset(1); 7371 7372 return CharSourceRange::getCharRange(Start, End); 7373 } 7374 7375 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7376 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7377 S.getLangOpts(), S.Context.getTargetInfo()); 7378 } 7379 7380 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7381 unsigned specifierLen){ 7382 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7383 getLocationOfByte(startSpecifier), 7384 /*IsStringLocation*/true, 7385 getSpecifierRange(startSpecifier, specifierLen)); 7386 } 7387 7388 void CheckFormatHandler::HandleInvalidLengthModifier( 7389 const analyze_format_string::FormatSpecifier &FS, 7390 const analyze_format_string::ConversionSpecifier &CS, 7391 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7392 using namespace analyze_format_string; 7393 7394 const LengthModifier &LM = FS.getLengthModifier(); 7395 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7396 7397 // See if we know how to fix this length modifier. 7398 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7399 if (FixedLM) { 7400 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7401 getLocationOfByte(LM.getStart()), 7402 /*IsStringLocation*/true, 7403 getSpecifierRange(startSpecifier, specifierLen)); 7404 7405 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7406 << FixedLM->toString() 7407 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7408 7409 } else { 7410 FixItHint Hint; 7411 if (DiagID == diag::warn_format_nonsensical_length) 7412 Hint = FixItHint::CreateRemoval(LMRange); 7413 7414 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7415 getLocationOfByte(LM.getStart()), 7416 /*IsStringLocation*/true, 7417 getSpecifierRange(startSpecifier, specifierLen), 7418 Hint); 7419 } 7420 } 7421 7422 void CheckFormatHandler::HandleNonStandardLengthModifier( 7423 const analyze_format_string::FormatSpecifier &FS, 7424 const char *startSpecifier, unsigned specifierLen) { 7425 using namespace analyze_format_string; 7426 7427 const LengthModifier &LM = FS.getLengthModifier(); 7428 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7429 7430 // See if we know how to fix this length modifier. 7431 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7432 if (FixedLM) { 7433 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7434 << LM.toString() << 0, 7435 getLocationOfByte(LM.getStart()), 7436 /*IsStringLocation*/true, 7437 getSpecifierRange(startSpecifier, specifierLen)); 7438 7439 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7440 << FixedLM->toString() 7441 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7442 7443 } else { 7444 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7445 << LM.toString() << 0, 7446 getLocationOfByte(LM.getStart()), 7447 /*IsStringLocation*/true, 7448 getSpecifierRange(startSpecifier, specifierLen)); 7449 } 7450 } 7451 7452 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7453 const analyze_format_string::ConversionSpecifier &CS, 7454 const char *startSpecifier, unsigned specifierLen) { 7455 using namespace analyze_format_string; 7456 7457 // See if we know how to fix this conversion specifier. 7458 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7459 if (FixedCS) { 7460 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7461 << CS.toString() << /*conversion specifier*/1, 7462 getLocationOfByte(CS.getStart()), 7463 /*IsStringLocation*/true, 7464 getSpecifierRange(startSpecifier, specifierLen)); 7465 7466 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7467 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7468 << FixedCS->toString() 7469 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7470 } else { 7471 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7472 << CS.toString() << /*conversion specifier*/1, 7473 getLocationOfByte(CS.getStart()), 7474 /*IsStringLocation*/true, 7475 getSpecifierRange(startSpecifier, specifierLen)); 7476 } 7477 } 7478 7479 void CheckFormatHandler::HandlePosition(const char *startPos, 7480 unsigned posLen) { 7481 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7482 getLocationOfByte(startPos), 7483 /*IsStringLocation*/true, 7484 getSpecifierRange(startPos, posLen)); 7485 } 7486 7487 void 7488 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7489 analyze_format_string::PositionContext p) { 7490 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7491 << (unsigned) p, 7492 getLocationOfByte(startPos), /*IsStringLocation*/true, 7493 getSpecifierRange(startPos, posLen)); 7494 } 7495 7496 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7497 unsigned posLen) { 7498 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7499 getLocationOfByte(startPos), 7500 /*IsStringLocation*/true, 7501 getSpecifierRange(startPos, posLen)); 7502 } 7503 7504 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7505 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7506 // The presence of a null character is likely an error. 7507 EmitFormatDiagnostic( 7508 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7509 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7510 getFormatStringRange()); 7511 } 7512 } 7513 7514 // Note that this may return NULL if there was an error parsing or building 7515 // one of the argument expressions. 7516 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7517 return Args[FirstDataArg + i]; 7518 } 7519 7520 void CheckFormatHandler::DoneProcessing() { 7521 // Does the number of data arguments exceed the number of 7522 // format conversions in the format string? 7523 if (!HasVAListArg) { 7524 // Find any arguments that weren't covered. 7525 CoveredArgs.flip(); 7526 signed notCoveredArg = CoveredArgs.find_first(); 7527 if (notCoveredArg >= 0) { 7528 assert((unsigned)notCoveredArg < NumDataArgs); 7529 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7530 } else { 7531 UncoveredArg.setAllCovered(); 7532 } 7533 } 7534 } 7535 7536 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7537 const Expr *ArgExpr) { 7538 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7539 "Invalid state"); 7540 7541 if (!ArgExpr) 7542 return; 7543 7544 SourceLocation Loc = ArgExpr->getBeginLoc(); 7545 7546 if (S.getSourceManager().isInSystemMacro(Loc)) 7547 return; 7548 7549 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7550 for (auto E : DiagnosticExprs) 7551 PDiag << E->getSourceRange(); 7552 7553 CheckFormatHandler::EmitFormatDiagnostic( 7554 S, IsFunctionCall, DiagnosticExprs[0], 7555 PDiag, Loc, /*IsStringLocation*/false, 7556 DiagnosticExprs[0]->getSourceRange()); 7557 } 7558 7559 bool 7560 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7561 SourceLocation Loc, 7562 const char *startSpec, 7563 unsigned specifierLen, 7564 const char *csStart, 7565 unsigned csLen) { 7566 bool keepGoing = true; 7567 if (argIndex < NumDataArgs) { 7568 // Consider the argument coverered, even though the specifier doesn't 7569 // make sense. 7570 CoveredArgs.set(argIndex); 7571 } 7572 else { 7573 // If argIndex exceeds the number of data arguments we 7574 // don't issue a warning because that is just a cascade of warnings (and 7575 // they may have intended '%%' anyway). We don't want to continue processing 7576 // the format string after this point, however, as we will like just get 7577 // gibberish when trying to match arguments. 7578 keepGoing = false; 7579 } 7580 7581 StringRef Specifier(csStart, csLen); 7582 7583 // If the specifier in non-printable, it could be the first byte of a UTF-8 7584 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7585 // hex value. 7586 std::string CodePointStr; 7587 if (!llvm::sys::locale::isPrint(*csStart)) { 7588 llvm::UTF32 CodePoint; 7589 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7590 const llvm::UTF8 *E = 7591 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7592 llvm::ConversionResult Result = 7593 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7594 7595 if (Result != llvm::conversionOK) { 7596 unsigned char FirstChar = *csStart; 7597 CodePoint = (llvm::UTF32)FirstChar; 7598 } 7599 7600 llvm::raw_string_ostream OS(CodePointStr); 7601 if (CodePoint < 256) 7602 OS << "\\x" << llvm::format("%02x", CodePoint); 7603 else if (CodePoint <= 0xFFFF) 7604 OS << "\\u" << llvm::format("%04x", CodePoint); 7605 else 7606 OS << "\\U" << llvm::format("%08x", CodePoint); 7607 OS.flush(); 7608 Specifier = CodePointStr; 7609 } 7610 7611 EmitFormatDiagnostic( 7612 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7613 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7614 7615 return keepGoing; 7616 } 7617 7618 void 7619 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7620 const char *startSpec, 7621 unsigned specifierLen) { 7622 EmitFormatDiagnostic( 7623 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7624 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7625 } 7626 7627 bool 7628 CheckFormatHandler::CheckNumArgs( 7629 const analyze_format_string::FormatSpecifier &FS, 7630 const analyze_format_string::ConversionSpecifier &CS, 7631 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7632 7633 if (argIndex >= NumDataArgs) { 7634 PartialDiagnostic PDiag = FS.usesPositionalArg() 7635 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7636 << (argIndex+1) << NumDataArgs) 7637 : S.PDiag(diag::warn_printf_insufficient_data_args); 7638 EmitFormatDiagnostic( 7639 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7640 getSpecifierRange(startSpecifier, specifierLen)); 7641 7642 // Since more arguments than conversion tokens are given, by extension 7643 // all arguments are covered, so mark this as so. 7644 UncoveredArg.setAllCovered(); 7645 return false; 7646 } 7647 return true; 7648 } 7649 7650 template<typename Range> 7651 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7652 SourceLocation Loc, 7653 bool IsStringLocation, 7654 Range StringRange, 7655 ArrayRef<FixItHint> FixIt) { 7656 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7657 Loc, IsStringLocation, StringRange, FixIt); 7658 } 7659 7660 /// If the format string is not within the function call, emit a note 7661 /// so that the function call and string are in diagnostic messages. 7662 /// 7663 /// \param InFunctionCall if true, the format string is within the function 7664 /// call and only one diagnostic message will be produced. Otherwise, an 7665 /// extra note will be emitted pointing to location of the format string. 7666 /// 7667 /// \param ArgumentExpr the expression that is passed as the format string 7668 /// argument in the function call. Used for getting locations when two 7669 /// diagnostics are emitted. 7670 /// 7671 /// \param PDiag the callee should already have provided any strings for the 7672 /// diagnostic message. This function only adds locations and fixits 7673 /// to diagnostics. 7674 /// 7675 /// \param Loc primary location for diagnostic. If two diagnostics are 7676 /// required, one will be at Loc and a new SourceLocation will be created for 7677 /// the other one. 7678 /// 7679 /// \param IsStringLocation if true, Loc points to the format string should be 7680 /// used for the note. Otherwise, Loc points to the argument list and will 7681 /// be used with PDiag. 7682 /// 7683 /// \param StringRange some or all of the string to highlight. This is 7684 /// templated so it can accept either a CharSourceRange or a SourceRange. 7685 /// 7686 /// \param FixIt optional fix it hint for the format string. 7687 template <typename Range> 7688 void CheckFormatHandler::EmitFormatDiagnostic( 7689 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7690 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7691 Range StringRange, ArrayRef<FixItHint> FixIt) { 7692 if (InFunctionCall) { 7693 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7694 D << StringRange; 7695 D << FixIt; 7696 } else { 7697 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7698 << ArgumentExpr->getSourceRange(); 7699 7700 const Sema::SemaDiagnosticBuilder &Note = 7701 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7702 diag::note_format_string_defined); 7703 7704 Note << StringRange; 7705 Note << FixIt; 7706 } 7707 } 7708 7709 //===--- CHECK: Printf format string checking ------------------------------===// 7710 7711 namespace { 7712 7713 class CheckPrintfHandler : public CheckFormatHandler { 7714 public: 7715 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7716 const Expr *origFormatExpr, 7717 const Sema::FormatStringType type, unsigned firstDataArg, 7718 unsigned numDataArgs, bool isObjC, const char *beg, 7719 bool hasVAListArg, ArrayRef<const Expr *> Args, 7720 unsigned formatIdx, bool inFunctionCall, 7721 Sema::VariadicCallType CallType, 7722 llvm::SmallBitVector &CheckedVarArgs, 7723 UncoveredArgHandler &UncoveredArg) 7724 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7725 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7726 inFunctionCall, CallType, CheckedVarArgs, 7727 UncoveredArg) {} 7728 7729 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7730 7731 /// Returns true if '%@' specifiers are allowed in the format string. 7732 bool allowsObjCArg() const { 7733 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7734 FSType == Sema::FST_OSTrace; 7735 } 7736 7737 bool HandleInvalidPrintfConversionSpecifier( 7738 const analyze_printf::PrintfSpecifier &FS, 7739 const char *startSpecifier, 7740 unsigned specifierLen) override; 7741 7742 void handleInvalidMaskType(StringRef MaskType) override; 7743 7744 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7745 const char *startSpecifier, 7746 unsigned specifierLen) override; 7747 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7748 const char *StartSpecifier, 7749 unsigned SpecifierLen, 7750 const Expr *E); 7751 7752 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7753 const char *startSpecifier, unsigned specifierLen); 7754 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7755 const analyze_printf::OptionalAmount &Amt, 7756 unsigned type, 7757 const char *startSpecifier, unsigned specifierLen); 7758 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7759 const analyze_printf::OptionalFlag &flag, 7760 const char *startSpecifier, unsigned specifierLen); 7761 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7762 const analyze_printf::OptionalFlag &ignoredFlag, 7763 const analyze_printf::OptionalFlag &flag, 7764 const char *startSpecifier, unsigned specifierLen); 7765 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7766 const Expr *E); 7767 7768 void HandleEmptyObjCModifierFlag(const char *startFlag, 7769 unsigned flagLen) override; 7770 7771 void HandleInvalidObjCModifierFlag(const char *startFlag, 7772 unsigned flagLen) override; 7773 7774 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7775 const char *flagsEnd, 7776 const char *conversionPosition) 7777 override; 7778 }; 7779 7780 } // namespace 7781 7782 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7783 const analyze_printf::PrintfSpecifier &FS, 7784 const char *startSpecifier, 7785 unsigned specifierLen) { 7786 const analyze_printf::PrintfConversionSpecifier &CS = 7787 FS.getConversionSpecifier(); 7788 7789 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7790 getLocationOfByte(CS.getStart()), 7791 startSpecifier, specifierLen, 7792 CS.getStart(), CS.getLength()); 7793 } 7794 7795 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7796 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7797 } 7798 7799 bool CheckPrintfHandler::HandleAmount( 7800 const analyze_format_string::OptionalAmount &Amt, 7801 unsigned k, const char *startSpecifier, 7802 unsigned specifierLen) { 7803 if (Amt.hasDataArgument()) { 7804 if (!HasVAListArg) { 7805 unsigned argIndex = Amt.getArgIndex(); 7806 if (argIndex >= NumDataArgs) { 7807 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7808 << k, 7809 getLocationOfByte(Amt.getStart()), 7810 /*IsStringLocation*/true, 7811 getSpecifierRange(startSpecifier, specifierLen)); 7812 // Don't do any more checking. We will just emit 7813 // spurious errors. 7814 return false; 7815 } 7816 7817 // Type check the data argument. It should be an 'int'. 7818 // Although not in conformance with C99, we also allow the argument to be 7819 // an 'unsigned int' as that is a reasonably safe case. GCC also 7820 // doesn't emit a warning for that case. 7821 CoveredArgs.set(argIndex); 7822 const Expr *Arg = getDataArg(argIndex); 7823 if (!Arg) 7824 return false; 7825 7826 QualType T = Arg->getType(); 7827 7828 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7829 assert(AT.isValid()); 7830 7831 if (!AT.matchesType(S.Context, T)) { 7832 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7833 << k << AT.getRepresentativeTypeName(S.Context) 7834 << T << Arg->getSourceRange(), 7835 getLocationOfByte(Amt.getStart()), 7836 /*IsStringLocation*/true, 7837 getSpecifierRange(startSpecifier, specifierLen)); 7838 // Don't do any more checking. We will just emit 7839 // spurious errors. 7840 return false; 7841 } 7842 } 7843 } 7844 return true; 7845 } 7846 7847 void CheckPrintfHandler::HandleInvalidAmount( 7848 const analyze_printf::PrintfSpecifier &FS, 7849 const analyze_printf::OptionalAmount &Amt, 7850 unsigned type, 7851 const char *startSpecifier, 7852 unsigned specifierLen) { 7853 const analyze_printf::PrintfConversionSpecifier &CS = 7854 FS.getConversionSpecifier(); 7855 7856 FixItHint fixit = 7857 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7858 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7859 Amt.getConstantLength())) 7860 : FixItHint(); 7861 7862 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7863 << type << CS.toString(), 7864 getLocationOfByte(Amt.getStart()), 7865 /*IsStringLocation*/true, 7866 getSpecifierRange(startSpecifier, specifierLen), 7867 fixit); 7868 } 7869 7870 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7871 const analyze_printf::OptionalFlag &flag, 7872 const char *startSpecifier, 7873 unsigned specifierLen) { 7874 // Warn about pointless flag with a fixit removal. 7875 const analyze_printf::PrintfConversionSpecifier &CS = 7876 FS.getConversionSpecifier(); 7877 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7878 << flag.toString() << CS.toString(), 7879 getLocationOfByte(flag.getPosition()), 7880 /*IsStringLocation*/true, 7881 getSpecifierRange(startSpecifier, specifierLen), 7882 FixItHint::CreateRemoval( 7883 getSpecifierRange(flag.getPosition(), 1))); 7884 } 7885 7886 void CheckPrintfHandler::HandleIgnoredFlag( 7887 const analyze_printf::PrintfSpecifier &FS, 7888 const analyze_printf::OptionalFlag &ignoredFlag, 7889 const analyze_printf::OptionalFlag &flag, 7890 const char *startSpecifier, 7891 unsigned specifierLen) { 7892 // Warn about ignored flag with a fixit removal. 7893 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7894 << ignoredFlag.toString() << flag.toString(), 7895 getLocationOfByte(ignoredFlag.getPosition()), 7896 /*IsStringLocation*/true, 7897 getSpecifierRange(startSpecifier, specifierLen), 7898 FixItHint::CreateRemoval( 7899 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7900 } 7901 7902 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7903 unsigned flagLen) { 7904 // Warn about an empty flag. 7905 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7906 getLocationOfByte(startFlag), 7907 /*IsStringLocation*/true, 7908 getSpecifierRange(startFlag, flagLen)); 7909 } 7910 7911 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7912 unsigned flagLen) { 7913 // Warn about an invalid flag. 7914 auto Range = getSpecifierRange(startFlag, flagLen); 7915 StringRef flag(startFlag, flagLen); 7916 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7917 getLocationOfByte(startFlag), 7918 /*IsStringLocation*/true, 7919 Range, FixItHint::CreateRemoval(Range)); 7920 } 7921 7922 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7923 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7924 // Warn about using '[...]' without a '@' conversion. 7925 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7926 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7927 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7928 getLocationOfByte(conversionPosition), 7929 /*IsStringLocation*/true, 7930 Range, FixItHint::CreateRemoval(Range)); 7931 } 7932 7933 // Determines if the specified is a C++ class or struct containing 7934 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7935 // "c_str()"). 7936 template<typename MemberKind> 7937 static llvm::SmallPtrSet<MemberKind*, 1> 7938 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7939 const RecordType *RT = Ty->getAs<RecordType>(); 7940 llvm::SmallPtrSet<MemberKind*, 1> Results; 7941 7942 if (!RT) 7943 return Results; 7944 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7945 if (!RD || !RD->getDefinition()) 7946 return Results; 7947 7948 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7949 Sema::LookupMemberName); 7950 R.suppressDiagnostics(); 7951 7952 // We just need to include all members of the right kind turned up by the 7953 // filter, at this point. 7954 if (S.LookupQualifiedName(R, RT->getDecl())) 7955 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7956 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7957 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7958 Results.insert(FK); 7959 } 7960 return Results; 7961 } 7962 7963 /// Check if we could call '.c_str()' on an object. 7964 /// 7965 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7966 /// allow the call, or if it would be ambiguous). 7967 bool Sema::hasCStrMethod(const Expr *E) { 7968 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7969 7970 MethodSet Results = 7971 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7972 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7973 MI != ME; ++MI) 7974 if ((*MI)->getMinRequiredArguments() == 0) 7975 return true; 7976 return false; 7977 } 7978 7979 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7980 // better diagnostic if so. AT is assumed to be valid. 7981 // Returns true when a c_str() conversion method is found. 7982 bool CheckPrintfHandler::checkForCStrMembers( 7983 const analyze_printf::ArgType &AT, const Expr *E) { 7984 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7985 7986 MethodSet Results = 7987 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7988 7989 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7990 MI != ME; ++MI) { 7991 const CXXMethodDecl *Method = *MI; 7992 if (Method->getMinRequiredArguments() == 0 && 7993 AT.matchesType(S.Context, Method->getReturnType())) { 7994 // FIXME: Suggest parens if the expression needs them. 7995 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7996 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7997 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7998 return true; 7999 } 8000 } 8001 8002 return false; 8003 } 8004 8005 bool 8006 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8007 &FS, 8008 const char *startSpecifier, 8009 unsigned specifierLen) { 8010 using namespace analyze_format_string; 8011 using namespace analyze_printf; 8012 8013 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8014 8015 if (FS.consumesDataArgument()) { 8016 if (atFirstArg) { 8017 atFirstArg = false; 8018 usesPositionalArgs = FS.usesPositionalArg(); 8019 } 8020 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8021 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8022 startSpecifier, specifierLen); 8023 return false; 8024 } 8025 } 8026 8027 // First check if the field width, precision, and conversion specifier 8028 // have matching data arguments. 8029 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8030 startSpecifier, specifierLen)) { 8031 return false; 8032 } 8033 8034 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8035 startSpecifier, specifierLen)) { 8036 return false; 8037 } 8038 8039 if (!CS.consumesDataArgument()) { 8040 // FIXME: Technically specifying a precision or field width here 8041 // makes no sense. Worth issuing a warning at some point. 8042 return true; 8043 } 8044 8045 // Consume the argument. 8046 unsigned argIndex = FS.getArgIndex(); 8047 if (argIndex < NumDataArgs) { 8048 // The check to see if the argIndex is valid will come later. 8049 // We set the bit here because we may exit early from this 8050 // function if we encounter some other error. 8051 CoveredArgs.set(argIndex); 8052 } 8053 8054 // FreeBSD kernel extensions. 8055 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8056 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8057 // We need at least two arguments. 8058 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8059 return false; 8060 8061 // Claim the second argument. 8062 CoveredArgs.set(argIndex + 1); 8063 8064 // Type check the first argument (int for %b, pointer for %D) 8065 const Expr *Ex = getDataArg(argIndex); 8066 const analyze_printf::ArgType &AT = 8067 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8068 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8069 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8070 EmitFormatDiagnostic( 8071 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8072 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8073 << false << Ex->getSourceRange(), 8074 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8075 getSpecifierRange(startSpecifier, specifierLen)); 8076 8077 // Type check the second argument (char * for both %b and %D) 8078 Ex = getDataArg(argIndex + 1); 8079 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8080 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8081 EmitFormatDiagnostic( 8082 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8083 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8084 << false << Ex->getSourceRange(), 8085 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8086 getSpecifierRange(startSpecifier, specifierLen)); 8087 8088 return true; 8089 } 8090 8091 // Check for using an Objective-C specific conversion specifier 8092 // in a non-ObjC literal. 8093 if (!allowsObjCArg() && CS.isObjCArg()) { 8094 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8095 specifierLen); 8096 } 8097 8098 // %P can only be used with os_log. 8099 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8100 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8101 specifierLen); 8102 } 8103 8104 // %n is not allowed with os_log. 8105 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8106 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8107 getLocationOfByte(CS.getStart()), 8108 /*IsStringLocation*/ false, 8109 getSpecifierRange(startSpecifier, specifierLen)); 8110 8111 return true; 8112 } 8113 8114 // Only scalars are allowed for os_trace. 8115 if (FSType == Sema::FST_OSTrace && 8116 (CS.getKind() == ConversionSpecifier::PArg || 8117 CS.getKind() == ConversionSpecifier::sArg || 8118 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8119 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8120 specifierLen); 8121 } 8122 8123 // Check for use of public/private annotation outside of os_log(). 8124 if (FSType != Sema::FST_OSLog) { 8125 if (FS.isPublic().isSet()) { 8126 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8127 << "public", 8128 getLocationOfByte(FS.isPublic().getPosition()), 8129 /*IsStringLocation*/ false, 8130 getSpecifierRange(startSpecifier, specifierLen)); 8131 } 8132 if (FS.isPrivate().isSet()) { 8133 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8134 << "private", 8135 getLocationOfByte(FS.isPrivate().getPosition()), 8136 /*IsStringLocation*/ false, 8137 getSpecifierRange(startSpecifier, specifierLen)); 8138 } 8139 } 8140 8141 // Check for invalid use of field width 8142 if (!FS.hasValidFieldWidth()) { 8143 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8144 startSpecifier, specifierLen); 8145 } 8146 8147 // Check for invalid use of precision 8148 if (!FS.hasValidPrecision()) { 8149 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8150 startSpecifier, specifierLen); 8151 } 8152 8153 // Precision is mandatory for %P specifier. 8154 if (CS.getKind() == ConversionSpecifier::PArg && 8155 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8156 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8157 getLocationOfByte(startSpecifier), 8158 /*IsStringLocation*/ false, 8159 getSpecifierRange(startSpecifier, specifierLen)); 8160 } 8161 8162 // Check each flag does not conflict with any other component. 8163 if (!FS.hasValidThousandsGroupingPrefix()) 8164 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8165 if (!FS.hasValidLeadingZeros()) 8166 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8167 if (!FS.hasValidPlusPrefix()) 8168 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8169 if (!FS.hasValidSpacePrefix()) 8170 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8171 if (!FS.hasValidAlternativeForm()) 8172 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8173 if (!FS.hasValidLeftJustified()) 8174 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8175 8176 // Check that flags are not ignored by another flag 8177 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8178 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8179 startSpecifier, specifierLen); 8180 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8181 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8182 startSpecifier, specifierLen); 8183 8184 // Check the length modifier is valid with the given conversion specifier. 8185 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8186 S.getLangOpts())) 8187 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8188 diag::warn_format_nonsensical_length); 8189 else if (!FS.hasStandardLengthModifier()) 8190 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8191 else if (!FS.hasStandardLengthConversionCombination()) 8192 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8193 diag::warn_format_non_standard_conversion_spec); 8194 8195 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8196 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8197 8198 // The remaining checks depend on the data arguments. 8199 if (HasVAListArg) 8200 return true; 8201 8202 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8203 return false; 8204 8205 const Expr *Arg = getDataArg(argIndex); 8206 if (!Arg) 8207 return true; 8208 8209 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8210 } 8211 8212 static bool requiresParensToAddCast(const Expr *E) { 8213 // FIXME: We should have a general way to reason about operator 8214 // precedence and whether parens are actually needed here. 8215 // Take care of a few common cases where they aren't. 8216 const Expr *Inside = E->IgnoreImpCasts(); 8217 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8218 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8219 8220 switch (Inside->getStmtClass()) { 8221 case Stmt::ArraySubscriptExprClass: 8222 case Stmt::CallExprClass: 8223 case Stmt::CharacterLiteralClass: 8224 case Stmt::CXXBoolLiteralExprClass: 8225 case Stmt::DeclRefExprClass: 8226 case Stmt::FloatingLiteralClass: 8227 case Stmt::IntegerLiteralClass: 8228 case Stmt::MemberExprClass: 8229 case Stmt::ObjCArrayLiteralClass: 8230 case Stmt::ObjCBoolLiteralExprClass: 8231 case Stmt::ObjCBoxedExprClass: 8232 case Stmt::ObjCDictionaryLiteralClass: 8233 case Stmt::ObjCEncodeExprClass: 8234 case Stmt::ObjCIvarRefExprClass: 8235 case Stmt::ObjCMessageExprClass: 8236 case Stmt::ObjCPropertyRefExprClass: 8237 case Stmt::ObjCStringLiteralClass: 8238 case Stmt::ObjCSubscriptRefExprClass: 8239 case Stmt::ParenExprClass: 8240 case Stmt::StringLiteralClass: 8241 case Stmt::UnaryOperatorClass: 8242 return false; 8243 default: 8244 return true; 8245 } 8246 } 8247 8248 static std::pair<QualType, StringRef> 8249 shouldNotPrintDirectly(const ASTContext &Context, 8250 QualType IntendedTy, 8251 const Expr *E) { 8252 // Use a 'while' to peel off layers of typedefs. 8253 QualType TyTy = IntendedTy; 8254 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8255 StringRef Name = UserTy->getDecl()->getName(); 8256 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8257 .Case("CFIndex", Context.getNSIntegerType()) 8258 .Case("NSInteger", Context.getNSIntegerType()) 8259 .Case("NSUInteger", Context.getNSUIntegerType()) 8260 .Case("SInt32", Context.IntTy) 8261 .Case("UInt32", Context.UnsignedIntTy) 8262 .Default(QualType()); 8263 8264 if (!CastTy.isNull()) 8265 return std::make_pair(CastTy, Name); 8266 8267 TyTy = UserTy->desugar(); 8268 } 8269 8270 // Strip parens if necessary. 8271 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8272 return shouldNotPrintDirectly(Context, 8273 PE->getSubExpr()->getType(), 8274 PE->getSubExpr()); 8275 8276 // If this is a conditional expression, then its result type is constructed 8277 // via usual arithmetic conversions and thus there might be no necessary 8278 // typedef sugar there. Recurse to operands to check for NSInteger & 8279 // Co. usage condition. 8280 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8281 QualType TrueTy, FalseTy; 8282 StringRef TrueName, FalseName; 8283 8284 std::tie(TrueTy, TrueName) = 8285 shouldNotPrintDirectly(Context, 8286 CO->getTrueExpr()->getType(), 8287 CO->getTrueExpr()); 8288 std::tie(FalseTy, FalseName) = 8289 shouldNotPrintDirectly(Context, 8290 CO->getFalseExpr()->getType(), 8291 CO->getFalseExpr()); 8292 8293 if (TrueTy == FalseTy) 8294 return std::make_pair(TrueTy, TrueName); 8295 else if (TrueTy.isNull()) 8296 return std::make_pair(FalseTy, FalseName); 8297 else if (FalseTy.isNull()) 8298 return std::make_pair(TrueTy, TrueName); 8299 } 8300 8301 return std::make_pair(QualType(), StringRef()); 8302 } 8303 8304 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8305 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8306 /// type do not count. 8307 static bool 8308 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8309 QualType From = ICE->getSubExpr()->getType(); 8310 QualType To = ICE->getType(); 8311 // It's an integer promotion if the destination type is the promoted 8312 // source type. 8313 if (ICE->getCastKind() == CK_IntegralCast && 8314 From->isPromotableIntegerType() && 8315 S.Context.getPromotedIntegerType(From) == To) 8316 return true; 8317 // Look through vector types, since we do default argument promotion for 8318 // those in OpenCL. 8319 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8320 From = VecTy->getElementType(); 8321 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8322 To = VecTy->getElementType(); 8323 // It's a floating promotion if the source type is a lower rank. 8324 return ICE->getCastKind() == CK_FloatingCast && 8325 S.Context.getFloatingTypeOrder(From, To) < 0; 8326 } 8327 8328 bool 8329 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8330 const char *StartSpecifier, 8331 unsigned SpecifierLen, 8332 const Expr *E) { 8333 using namespace analyze_format_string; 8334 using namespace analyze_printf; 8335 8336 // Now type check the data expression that matches the 8337 // format specifier. 8338 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8339 if (!AT.isValid()) 8340 return true; 8341 8342 QualType ExprTy = E->getType(); 8343 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8344 ExprTy = TET->getUnderlyingExpr()->getType(); 8345 } 8346 8347 // Diagnose attempts to print a boolean value as a character. Unlike other 8348 // -Wformat diagnostics, this is fine from a type perspective, but it still 8349 // doesn't make sense. 8350 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8351 E->isKnownToHaveBooleanValue()) { 8352 const CharSourceRange &CSR = 8353 getSpecifierRange(StartSpecifier, SpecifierLen); 8354 SmallString<4> FSString; 8355 llvm::raw_svector_ostream os(FSString); 8356 FS.toString(os); 8357 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8358 << FSString, 8359 E->getExprLoc(), false, CSR); 8360 return true; 8361 } 8362 8363 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8364 if (Match == analyze_printf::ArgType::Match) 8365 return true; 8366 8367 // Look through argument promotions for our error message's reported type. 8368 // This includes the integral and floating promotions, but excludes array 8369 // and function pointer decay (seeing that an argument intended to be a 8370 // string has type 'char [6]' is probably more confusing than 'char *') and 8371 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8372 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8373 if (isArithmeticArgumentPromotion(S, ICE)) { 8374 E = ICE->getSubExpr(); 8375 ExprTy = E->getType(); 8376 8377 // Check if we didn't match because of an implicit cast from a 'char' 8378 // or 'short' to an 'int'. This is done because printf is a varargs 8379 // function. 8380 if (ICE->getType() == S.Context.IntTy || 8381 ICE->getType() == S.Context.UnsignedIntTy) { 8382 // All further checking is done on the subexpression 8383 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8384 AT.matchesType(S.Context, ExprTy); 8385 if (ImplicitMatch == analyze_printf::ArgType::Match) 8386 return true; 8387 if (ImplicitMatch == ArgType::NoMatchPedantic || 8388 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8389 Match = ImplicitMatch; 8390 } 8391 } 8392 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8393 // Special case for 'a', which has type 'int' in C. 8394 // Note, however, that we do /not/ want to treat multibyte constants like 8395 // 'MooV' as characters! This form is deprecated but still exists. 8396 if (ExprTy == S.Context.IntTy) 8397 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8398 ExprTy = S.Context.CharTy; 8399 } 8400 8401 // Look through enums to their underlying type. 8402 bool IsEnum = false; 8403 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8404 ExprTy = EnumTy->getDecl()->getIntegerType(); 8405 IsEnum = true; 8406 } 8407 8408 // %C in an Objective-C context prints a unichar, not a wchar_t. 8409 // If the argument is an integer of some kind, believe the %C and suggest 8410 // a cast instead of changing the conversion specifier. 8411 QualType IntendedTy = ExprTy; 8412 if (isObjCContext() && 8413 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8414 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8415 !ExprTy->isCharType()) { 8416 // 'unichar' is defined as a typedef of unsigned short, but we should 8417 // prefer using the typedef if it is visible. 8418 IntendedTy = S.Context.UnsignedShortTy; 8419 8420 // While we are here, check if the value is an IntegerLiteral that happens 8421 // to be within the valid range. 8422 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8423 const llvm::APInt &V = IL->getValue(); 8424 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8425 return true; 8426 } 8427 8428 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8429 Sema::LookupOrdinaryName); 8430 if (S.LookupName(Result, S.getCurScope())) { 8431 NamedDecl *ND = Result.getFoundDecl(); 8432 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8433 if (TD->getUnderlyingType() == IntendedTy) 8434 IntendedTy = S.Context.getTypedefType(TD); 8435 } 8436 } 8437 } 8438 8439 // Special-case some of Darwin's platform-independence types by suggesting 8440 // casts to primitive types that are known to be large enough. 8441 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8442 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8443 QualType CastTy; 8444 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8445 if (!CastTy.isNull()) { 8446 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8447 // (long in ASTContext). Only complain to pedants. 8448 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8449 (AT.isSizeT() || AT.isPtrdiffT()) && 8450 AT.matchesType(S.Context, CastTy)) 8451 Match = ArgType::NoMatchPedantic; 8452 IntendedTy = CastTy; 8453 ShouldNotPrintDirectly = true; 8454 } 8455 } 8456 8457 // We may be able to offer a FixItHint if it is a supported type. 8458 PrintfSpecifier fixedFS = FS; 8459 bool Success = 8460 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8461 8462 if (Success) { 8463 // Get the fix string from the fixed format specifier 8464 SmallString<16> buf; 8465 llvm::raw_svector_ostream os(buf); 8466 fixedFS.toString(os); 8467 8468 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8469 8470 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8471 unsigned Diag; 8472 switch (Match) { 8473 case ArgType::Match: llvm_unreachable("expected non-matching"); 8474 case ArgType::NoMatchPedantic: 8475 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8476 break; 8477 case ArgType::NoMatchTypeConfusion: 8478 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8479 break; 8480 case ArgType::NoMatch: 8481 Diag = diag::warn_format_conversion_argument_type_mismatch; 8482 break; 8483 } 8484 8485 // In this case, the specifier is wrong and should be changed to match 8486 // the argument. 8487 EmitFormatDiagnostic(S.PDiag(Diag) 8488 << AT.getRepresentativeTypeName(S.Context) 8489 << IntendedTy << IsEnum << E->getSourceRange(), 8490 E->getBeginLoc(), 8491 /*IsStringLocation*/ false, SpecRange, 8492 FixItHint::CreateReplacement(SpecRange, os.str())); 8493 } else { 8494 // The canonical type for formatting this value is different from the 8495 // actual type of the expression. (This occurs, for example, with Darwin's 8496 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8497 // should be printed as 'long' for 64-bit compatibility.) 8498 // Rather than emitting a normal format/argument mismatch, we want to 8499 // add a cast to the recommended type (and correct the format string 8500 // if necessary). 8501 SmallString<16> CastBuf; 8502 llvm::raw_svector_ostream CastFix(CastBuf); 8503 CastFix << "("; 8504 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8505 CastFix << ")"; 8506 8507 SmallVector<FixItHint,4> Hints; 8508 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8509 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8510 8511 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8512 // If there's already a cast present, just replace it. 8513 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8514 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8515 8516 } else if (!requiresParensToAddCast(E)) { 8517 // If the expression has high enough precedence, 8518 // just write the C-style cast. 8519 Hints.push_back( 8520 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8521 } else { 8522 // Otherwise, add parens around the expression as well as the cast. 8523 CastFix << "("; 8524 Hints.push_back( 8525 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8526 8527 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8528 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8529 } 8530 8531 if (ShouldNotPrintDirectly) { 8532 // The expression has a type that should not be printed directly. 8533 // We extract the name from the typedef because we don't want to show 8534 // the underlying type in the diagnostic. 8535 StringRef Name; 8536 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8537 Name = TypedefTy->getDecl()->getName(); 8538 else 8539 Name = CastTyName; 8540 unsigned Diag = Match == ArgType::NoMatchPedantic 8541 ? diag::warn_format_argument_needs_cast_pedantic 8542 : diag::warn_format_argument_needs_cast; 8543 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8544 << E->getSourceRange(), 8545 E->getBeginLoc(), /*IsStringLocation=*/false, 8546 SpecRange, Hints); 8547 } else { 8548 // In this case, the expression could be printed using a different 8549 // specifier, but we've decided that the specifier is probably correct 8550 // and we should cast instead. Just use the normal warning message. 8551 EmitFormatDiagnostic( 8552 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8553 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8554 << E->getSourceRange(), 8555 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8556 } 8557 } 8558 } else { 8559 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8560 SpecifierLen); 8561 // Since the warning for passing non-POD types to variadic functions 8562 // was deferred until now, we emit a warning for non-POD 8563 // arguments here. 8564 switch (S.isValidVarArgType(ExprTy)) { 8565 case Sema::VAK_Valid: 8566 case Sema::VAK_ValidInCXX11: { 8567 unsigned Diag; 8568 switch (Match) { 8569 case ArgType::Match: llvm_unreachable("expected non-matching"); 8570 case ArgType::NoMatchPedantic: 8571 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8572 break; 8573 case ArgType::NoMatchTypeConfusion: 8574 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8575 break; 8576 case ArgType::NoMatch: 8577 Diag = diag::warn_format_conversion_argument_type_mismatch; 8578 break; 8579 } 8580 8581 EmitFormatDiagnostic( 8582 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8583 << IsEnum << CSR << E->getSourceRange(), 8584 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8585 break; 8586 } 8587 case Sema::VAK_Undefined: 8588 case Sema::VAK_MSVCUndefined: 8589 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8590 << S.getLangOpts().CPlusPlus11 << ExprTy 8591 << CallType 8592 << AT.getRepresentativeTypeName(S.Context) << CSR 8593 << E->getSourceRange(), 8594 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8595 checkForCStrMembers(AT, E); 8596 break; 8597 8598 case Sema::VAK_Invalid: 8599 if (ExprTy->isObjCObjectType()) 8600 EmitFormatDiagnostic( 8601 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8602 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8603 << AT.getRepresentativeTypeName(S.Context) << CSR 8604 << E->getSourceRange(), 8605 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8606 else 8607 // FIXME: If this is an initializer list, suggest removing the braces 8608 // or inserting a cast to the target type. 8609 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8610 << isa<InitListExpr>(E) << ExprTy << CallType 8611 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8612 break; 8613 } 8614 8615 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8616 "format string specifier index out of range"); 8617 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8618 } 8619 8620 return true; 8621 } 8622 8623 //===--- CHECK: Scanf format string checking ------------------------------===// 8624 8625 namespace { 8626 8627 class CheckScanfHandler : public CheckFormatHandler { 8628 public: 8629 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8630 const Expr *origFormatExpr, Sema::FormatStringType type, 8631 unsigned firstDataArg, unsigned numDataArgs, 8632 const char *beg, bool hasVAListArg, 8633 ArrayRef<const Expr *> Args, unsigned formatIdx, 8634 bool inFunctionCall, Sema::VariadicCallType CallType, 8635 llvm::SmallBitVector &CheckedVarArgs, 8636 UncoveredArgHandler &UncoveredArg) 8637 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8638 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8639 inFunctionCall, CallType, CheckedVarArgs, 8640 UncoveredArg) {} 8641 8642 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8643 const char *startSpecifier, 8644 unsigned specifierLen) override; 8645 8646 bool HandleInvalidScanfConversionSpecifier( 8647 const analyze_scanf::ScanfSpecifier &FS, 8648 const char *startSpecifier, 8649 unsigned specifierLen) override; 8650 8651 void HandleIncompleteScanList(const char *start, const char *end) override; 8652 }; 8653 8654 } // namespace 8655 8656 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8657 const char *end) { 8658 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8659 getLocationOfByte(end), /*IsStringLocation*/true, 8660 getSpecifierRange(start, end - start)); 8661 } 8662 8663 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8664 const analyze_scanf::ScanfSpecifier &FS, 8665 const char *startSpecifier, 8666 unsigned specifierLen) { 8667 const analyze_scanf::ScanfConversionSpecifier &CS = 8668 FS.getConversionSpecifier(); 8669 8670 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8671 getLocationOfByte(CS.getStart()), 8672 startSpecifier, specifierLen, 8673 CS.getStart(), CS.getLength()); 8674 } 8675 8676 bool CheckScanfHandler::HandleScanfSpecifier( 8677 const analyze_scanf::ScanfSpecifier &FS, 8678 const char *startSpecifier, 8679 unsigned specifierLen) { 8680 using namespace analyze_scanf; 8681 using namespace analyze_format_string; 8682 8683 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8684 8685 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8686 // be used to decide if we are using positional arguments consistently. 8687 if (FS.consumesDataArgument()) { 8688 if (atFirstArg) { 8689 atFirstArg = false; 8690 usesPositionalArgs = FS.usesPositionalArg(); 8691 } 8692 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8693 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8694 startSpecifier, specifierLen); 8695 return false; 8696 } 8697 } 8698 8699 // Check if the field with is non-zero. 8700 const OptionalAmount &Amt = FS.getFieldWidth(); 8701 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8702 if (Amt.getConstantAmount() == 0) { 8703 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8704 Amt.getConstantLength()); 8705 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8706 getLocationOfByte(Amt.getStart()), 8707 /*IsStringLocation*/true, R, 8708 FixItHint::CreateRemoval(R)); 8709 } 8710 } 8711 8712 if (!FS.consumesDataArgument()) { 8713 // FIXME: Technically specifying a precision or field width here 8714 // makes no sense. Worth issuing a warning at some point. 8715 return true; 8716 } 8717 8718 // Consume the argument. 8719 unsigned argIndex = FS.getArgIndex(); 8720 if (argIndex < NumDataArgs) { 8721 // The check to see if the argIndex is valid will come later. 8722 // We set the bit here because we may exit early from this 8723 // function if we encounter some other error. 8724 CoveredArgs.set(argIndex); 8725 } 8726 8727 // Check the length modifier is valid with the given conversion specifier. 8728 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8729 S.getLangOpts())) 8730 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8731 diag::warn_format_nonsensical_length); 8732 else if (!FS.hasStandardLengthModifier()) 8733 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8734 else if (!FS.hasStandardLengthConversionCombination()) 8735 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8736 diag::warn_format_non_standard_conversion_spec); 8737 8738 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8739 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8740 8741 // The remaining checks depend on the data arguments. 8742 if (HasVAListArg) 8743 return true; 8744 8745 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8746 return false; 8747 8748 // Check that the argument type matches the format specifier. 8749 const Expr *Ex = getDataArg(argIndex); 8750 if (!Ex) 8751 return true; 8752 8753 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8754 8755 if (!AT.isValid()) { 8756 return true; 8757 } 8758 8759 analyze_format_string::ArgType::MatchKind Match = 8760 AT.matchesType(S.Context, Ex->getType()); 8761 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8762 if (Match == analyze_format_string::ArgType::Match) 8763 return true; 8764 8765 ScanfSpecifier fixedFS = FS; 8766 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8767 S.getLangOpts(), S.Context); 8768 8769 unsigned Diag = 8770 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8771 : diag::warn_format_conversion_argument_type_mismatch; 8772 8773 if (Success) { 8774 // Get the fix string from the fixed format specifier. 8775 SmallString<128> buf; 8776 llvm::raw_svector_ostream os(buf); 8777 fixedFS.toString(os); 8778 8779 EmitFormatDiagnostic( 8780 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8781 << Ex->getType() << false << Ex->getSourceRange(), 8782 Ex->getBeginLoc(), 8783 /*IsStringLocation*/ false, 8784 getSpecifierRange(startSpecifier, specifierLen), 8785 FixItHint::CreateReplacement( 8786 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8787 } else { 8788 EmitFormatDiagnostic(S.PDiag(Diag) 8789 << AT.getRepresentativeTypeName(S.Context) 8790 << Ex->getType() << false << Ex->getSourceRange(), 8791 Ex->getBeginLoc(), 8792 /*IsStringLocation*/ false, 8793 getSpecifierRange(startSpecifier, specifierLen)); 8794 } 8795 8796 return true; 8797 } 8798 8799 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8800 const Expr *OrigFormatExpr, 8801 ArrayRef<const Expr *> Args, 8802 bool HasVAListArg, unsigned format_idx, 8803 unsigned firstDataArg, 8804 Sema::FormatStringType Type, 8805 bool inFunctionCall, 8806 Sema::VariadicCallType CallType, 8807 llvm::SmallBitVector &CheckedVarArgs, 8808 UncoveredArgHandler &UncoveredArg, 8809 bool IgnoreStringsWithoutSpecifiers) { 8810 // CHECK: is the format string a wide literal? 8811 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8812 CheckFormatHandler::EmitFormatDiagnostic( 8813 S, inFunctionCall, Args[format_idx], 8814 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8815 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8816 return; 8817 } 8818 8819 // Str - The format string. NOTE: this is NOT null-terminated! 8820 StringRef StrRef = FExpr->getString(); 8821 const char *Str = StrRef.data(); 8822 // Account for cases where the string literal is truncated in a declaration. 8823 const ConstantArrayType *T = 8824 S.Context.getAsConstantArrayType(FExpr->getType()); 8825 assert(T && "String literal not of constant array type!"); 8826 size_t TypeSize = T->getSize().getZExtValue(); 8827 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8828 const unsigned numDataArgs = Args.size() - firstDataArg; 8829 8830 if (IgnoreStringsWithoutSpecifiers && 8831 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8832 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8833 return; 8834 8835 // Emit a warning if the string literal is truncated and does not contain an 8836 // embedded null character. 8837 if (TypeSize <= StrRef.size() && 8838 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8839 CheckFormatHandler::EmitFormatDiagnostic( 8840 S, inFunctionCall, Args[format_idx], 8841 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8842 FExpr->getBeginLoc(), 8843 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8844 return; 8845 } 8846 8847 // CHECK: empty format string? 8848 if (StrLen == 0 && numDataArgs > 0) { 8849 CheckFormatHandler::EmitFormatDiagnostic( 8850 S, inFunctionCall, Args[format_idx], 8851 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8852 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8853 return; 8854 } 8855 8856 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8857 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8858 Type == Sema::FST_OSTrace) { 8859 CheckPrintfHandler H( 8860 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8861 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8862 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8863 CheckedVarArgs, UncoveredArg); 8864 8865 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8866 S.getLangOpts(), 8867 S.Context.getTargetInfo(), 8868 Type == Sema::FST_FreeBSDKPrintf)) 8869 H.DoneProcessing(); 8870 } else if (Type == Sema::FST_Scanf) { 8871 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8872 numDataArgs, Str, HasVAListArg, Args, format_idx, 8873 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8874 8875 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8876 S.getLangOpts(), 8877 S.Context.getTargetInfo())) 8878 H.DoneProcessing(); 8879 } // TODO: handle other formats 8880 } 8881 8882 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8883 // Str - The format string. NOTE: this is NOT null-terminated! 8884 StringRef StrRef = FExpr->getString(); 8885 const char *Str = StrRef.data(); 8886 // Account for cases where the string literal is truncated in a declaration. 8887 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8888 assert(T && "String literal not of constant array type!"); 8889 size_t TypeSize = T->getSize().getZExtValue(); 8890 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8891 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8892 getLangOpts(), 8893 Context.getTargetInfo()); 8894 } 8895 8896 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8897 8898 // Returns the related absolute value function that is larger, of 0 if one 8899 // does not exist. 8900 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8901 switch (AbsFunction) { 8902 default: 8903 return 0; 8904 8905 case Builtin::BI__builtin_abs: 8906 return Builtin::BI__builtin_labs; 8907 case Builtin::BI__builtin_labs: 8908 return Builtin::BI__builtin_llabs; 8909 case Builtin::BI__builtin_llabs: 8910 return 0; 8911 8912 case Builtin::BI__builtin_fabsf: 8913 return Builtin::BI__builtin_fabs; 8914 case Builtin::BI__builtin_fabs: 8915 return Builtin::BI__builtin_fabsl; 8916 case Builtin::BI__builtin_fabsl: 8917 return 0; 8918 8919 case Builtin::BI__builtin_cabsf: 8920 return Builtin::BI__builtin_cabs; 8921 case Builtin::BI__builtin_cabs: 8922 return Builtin::BI__builtin_cabsl; 8923 case Builtin::BI__builtin_cabsl: 8924 return 0; 8925 8926 case Builtin::BIabs: 8927 return Builtin::BIlabs; 8928 case Builtin::BIlabs: 8929 return Builtin::BIllabs; 8930 case Builtin::BIllabs: 8931 return 0; 8932 8933 case Builtin::BIfabsf: 8934 return Builtin::BIfabs; 8935 case Builtin::BIfabs: 8936 return Builtin::BIfabsl; 8937 case Builtin::BIfabsl: 8938 return 0; 8939 8940 case Builtin::BIcabsf: 8941 return Builtin::BIcabs; 8942 case Builtin::BIcabs: 8943 return Builtin::BIcabsl; 8944 case Builtin::BIcabsl: 8945 return 0; 8946 } 8947 } 8948 8949 // Returns the argument type of the absolute value function. 8950 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8951 unsigned AbsType) { 8952 if (AbsType == 0) 8953 return QualType(); 8954 8955 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8956 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8957 if (Error != ASTContext::GE_None) 8958 return QualType(); 8959 8960 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8961 if (!FT) 8962 return QualType(); 8963 8964 if (FT->getNumParams() != 1) 8965 return QualType(); 8966 8967 return FT->getParamType(0); 8968 } 8969 8970 // Returns the best absolute value function, or zero, based on type and 8971 // current absolute value function. 8972 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8973 unsigned AbsFunctionKind) { 8974 unsigned BestKind = 0; 8975 uint64_t ArgSize = Context.getTypeSize(ArgType); 8976 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8977 Kind = getLargerAbsoluteValueFunction(Kind)) { 8978 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8979 if (Context.getTypeSize(ParamType) >= ArgSize) { 8980 if (BestKind == 0) 8981 BestKind = Kind; 8982 else if (Context.hasSameType(ParamType, ArgType)) { 8983 BestKind = Kind; 8984 break; 8985 } 8986 } 8987 } 8988 return BestKind; 8989 } 8990 8991 enum AbsoluteValueKind { 8992 AVK_Integer, 8993 AVK_Floating, 8994 AVK_Complex 8995 }; 8996 8997 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8998 if (T->isIntegralOrEnumerationType()) 8999 return AVK_Integer; 9000 if (T->isRealFloatingType()) 9001 return AVK_Floating; 9002 if (T->isAnyComplexType()) 9003 return AVK_Complex; 9004 9005 llvm_unreachable("Type not integer, floating, or complex"); 9006 } 9007 9008 // Changes the absolute value function to a different type. Preserves whether 9009 // the function is a builtin. 9010 static unsigned changeAbsFunction(unsigned AbsKind, 9011 AbsoluteValueKind ValueKind) { 9012 switch (ValueKind) { 9013 case AVK_Integer: 9014 switch (AbsKind) { 9015 default: 9016 return 0; 9017 case Builtin::BI__builtin_fabsf: 9018 case Builtin::BI__builtin_fabs: 9019 case Builtin::BI__builtin_fabsl: 9020 case Builtin::BI__builtin_cabsf: 9021 case Builtin::BI__builtin_cabs: 9022 case Builtin::BI__builtin_cabsl: 9023 return Builtin::BI__builtin_abs; 9024 case Builtin::BIfabsf: 9025 case Builtin::BIfabs: 9026 case Builtin::BIfabsl: 9027 case Builtin::BIcabsf: 9028 case Builtin::BIcabs: 9029 case Builtin::BIcabsl: 9030 return Builtin::BIabs; 9031 } 9032 case AVK_Floating: 9033 switch (AbsKind) { 9034 default: 9035 return 0; 9036 case Builtin::BI__builtin_abs: 9037 case Builtin::BI__builtin_labs: 9038 case Builtin::BI__builtin_llabs: 9039 case Builtin::BI__builtin_cabsf: 9040 case Builtin::BI__builtin_cabs: 9041 case Builtin::BI__builtin_cabsl: 9042 return Builtin::BI__builtin_fabsf; 9043 case Builtin::BIabs: 9044 case Builtin::BIlabs: 9045 case Builtin::BIllabs: 9046 case Builtin::BIcabsf: 9047 case Builtin::BIcabs: 9048 case Builtin::BIcabsl: 9049 return Builtin::BIfabsf; 9050 } 9051 case AVK_Complex: 9052 switch (AbsKind) { 9053 default: 9054 return 0; 9055 case Builtin::BI__builtin_abs: 9056 case Builtin::BI__builtin_labs: 9057 case Builtin::BI__builtin_llabs: 9058 case Builtin::BI__builtin_fabsf: 9059 case Builtin::BI__builtin_fabs: 9060 case Builtin::BI__builtin_fabsl: 9061 return Builtin::BI__builtin_cabsf; 9062 case Builtin::BIabs: 9063 case Builtin::BIlabs: 9064 case Builtin::BIllabs: 9065 case Builtin::BIfabsf: 9066 case Builtin::BIfabs: 9067 case Builtin::BIfabsl: 9068 return Builtin::BIcabsf; 9069 } 9070 } 9071 llvm_unreachable("Unable to convert function"); 9072 } 9073 9074 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9075 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9076 if (!FnInfo) 9077 return 0; 9078 9079 switch (FDecl->getBuiltinID()) { 9080 default: 9081 return 0; 9082 case Builtin::BI__builtin_abs: 9083 case Builtin::BI__builtin_fabs: 9084 case Builtin::BI__builtin_fabsf: 9085 case Builtin::BI__builtin_fabsl: 9086 case Builtin::BI__builtin_labs: 9087 case Builtin::BI__builtin_llabs: 9088 case Builtin::BI__builtin_cabs: 9089 case Builtin::BI__builtin_cabsf: 9090 case Builtin::BI__builtin_cabsl: 9091 case Builtin::BIabs: 9092 case Builtin::BIlabs: 9093 case Builtin::BIllabs: 9094 case Builtin::BIfabs: 9095 case Builtin::BIfabsf: 9096 case Builtin::BIfabsl: 9097 case Builtin::BIcabs: 9098 case Builtin::BIcabsf: 9099 case Builtin::BIcabsl: 9100 return FDecl->getBuiltinID(); 9101 } 9102 llvm_unreachable("Unknown Builtin type"); 9103 } 9104 9105 // If the replacement is valid, emit a note with replacement function. 9106 // Additionally, suggest including the proper header if not already included. 9107 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9108 unsigned AbsKind, QualType ArgType) { 9109 bool EmitHeaderHint = true; 9110 const char *HeaderName = nullptr; 9111 const char *FunctionName = nullptr; 9112 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9113 FunctionName = "std::abs"; 9114 if (ArgType->isIntegralOrEnumerationType()) { 9115 HeaderName = "cstdlib"; 9116 } else if (ArgType->isRealFloatingType()) { 9117 HeaderName = "cmath"; 9118 } else { 9119 llvm_unreachable("Invalid Type"); 9120 } 9121 9122 // Lookup all std::abs 9123 if (NamespaceDecl *Std = S.getStdNamespace()) { 9124 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9125 R.suppressDiagnostics(); 9126 S.LookupQualifiedName(R, Std); 9127 9128 for (const auto *I : R) { 9129 const FunctionDecl *FDecl = nullptr; 9130 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9131 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9132 } else { 9133 FDecl = dyn_cast<FunctionDecl>(I); 9134 } 9135 if (!FDecl) 9136 continue; 9137 9138 // Found std::abs(), check that they are the right ones. 9139 if (FDecl->getNumParams() != 1) 9140 continue; 9141 9142 // Check that the parameter type can handle the argument. 9143 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9144 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9145 S.Context.getTypeSize(ArgType) <= 9146 S.Context.getTypeSize(ParamType)) { 9147 // Found a function, don't need the header hint. 9148 EmitHeaderHint = false; 9149 break; 9150 } 9151 } 9152 } 9153 } else { 9154 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9155 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9156 9157 if (HeaderName) { 9158 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9159 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9160 R.suppressDiagnostics(); 9161 S.LookupName(R, S.getCurScope()); 9162 9163 if (R.isSingleResult()) { 9164 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9165 if (FD && FD->getBuiltinID() == AbsKind) { 9166 EmitHeaderHint = false; 9167 } else { 9168 return; 9169 } 9170 } else if (!R.empty()) { 9171 return; 9172 } 9173 } 9174 } 9175 9176 S.Diag(Loc, diag::note_replace_abs_function) 9177 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9178 9179 if (!HeaderName) 9180 return; 9181 9182 if (!EmitHeaderHint) 9183 return; 9184 9185 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9186 << FunctionName; 9187 } 9188 9189 template <std::size_t StrLen> 9190 static bool IsStdFunction(const FunctionDecl *FDecl, 9191 const char (&Str)[StrLen]) { 9192 if (!FDecl) 9193 return false; 9194 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9195 return false; 9196 if (!FDecl->isInStdNamespace()) 9197 return false; 9198 9199 return true; 9200 } 9201 9202 // Warn when using the wrong abs() function. 9203 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9204 const FunctionDecl *FDecl) { 9205 if (Call->getNumArgs() != 1) 9206 return; 9207 9208 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9209 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9210 if (AbsKind == 0 && !IsStdAbs) 9211 return; 9212 9213 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9214 QualType ParamType = Call->getArg(0)->getType(); 9215 9216 // Unsigned types cannot be negative. Suggest removing the absolute value 9217 // function call. 9218 if (ArgType->isUnsignedIntegerType()) { 9219 const char *FunctionName = 9220 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9221 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9222 Diag(Call->getExprLoc(), diag::note_remove_abs) 9223 << FunctionName 9224 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9225 return; 9226 } 9227 9228 // Taking the absolute value of a pointer is very suspicious, they probably 9229 // wanted to index into an array, dereference a pointer, call a function, etc. 9230 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9231 unsigned DiagType = 0; 9232 if (ArgType->isFunctionType()) 9233 DiagType = 1; 9234 else if (ArgType->isArrayType()) 9235 DiagType = 2; 9236 9237 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9238 return; 9239 } 9240 9241 // std::abs has overloads which prevent most of the absolute value problems 9242 // from occurring. 9243 if (IsStdAbs) 9244 return; 9245 9246 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9247 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9248 9249 // The argument and parameter are the same kind. Check if they are the right 9250 // size. 9251 if (ArgValueKind == ParamValueKind) { 9252 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9253 return; 9254 9255 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9256 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9257 << FDecl << ArgType << ParamType; 9258 9259 if (NewAbsKind == 0) 9260 return; 9261 9262 emitReplacement(*this, Call->getExprLoc(), 9263 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9264 return; 9265 } 9266 9267 // ArgValueKind != ParamValueKind 9268 // The wrong type of absolute value function was used. Attempt to find the 9269 // proper one. 9270 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9271 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9272 if (NewAbsKind == 0) 9273 return; 9274 9275 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9276 << FDecl << ParamValueKind << ArgValueKind; 9277 9278 emitReplacement(*this, Call->getExprLoc(), 9279 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9280 } 9281 9282 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9283 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9284 const FunctionDecl *FDecl) { 9285 if (!Call || !FDecl) return; 9286 9287 // Ignore template specializations and macros. 9288 if (inTemplateInstantiation()) return; 9289 if (Call->getExprLoc().isMacroID()) return; 9290 9291 // Only care about the one template argument, two function parameter std::max 9292 if (Call->getNumArgs() != 2) return; 9293 if (!IsStdFunction(FDecl, "max")) return; 9294 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9295 if (!ArgList) return; 9296 if (ArgList->size() != 1) return; 9297 9298 // Check that template type argument is unsigned integer. 9299 const auto& TA = ArgList->get(0); 9300 if (TA.getKind() != TemplateArgument::Type) return; 9301 QualType ArgType = TA.getAsType(); 9302 if (!ArgType->isUnsignedIntegerType()) return; 9303 9304 // See if either argument is a literal zero. 9305 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9306 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9307 if (!MTE) return false; 9308 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9309 if (!Num) return false; 9310 if (Num->getValue() != 0) return false; 9311 return true; 9312 }; 9313 9314 const Expr *FirstArg = Call->getArg(0); 9315 const Expr *SecondArg = Call->getArg(1); 9316 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9317 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9318 9319 // Only warn when exactly one argument is zero. 9320 if (IsFirstArgZero == IsSecondArgZero) return; 9321 9322 SourceRange FirstRange = FirstArg->getSourceRange(); 9323 SourceRange SecondRange = SecondArg->getSourceRange(); 9324 9325 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9326 9327 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9328 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9329 9330 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9331 SourceRange RemovalRange; 9332 if (IsFirstArgZero) { 9333 RemovalRange = SourceRange(FirstRange.getBegin(), 9334 SecondRange.getBegin().getLocWithOffset(-1)); 9335 } else { 9336 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9337 SecondRange.getEnd()); 9338 } 9339 9340 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9341 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9342 << FixItHint::CreateRemoval(RemovalRange); 9343 } 9344 9345 //===--- CHECK: Standard memory functions ---------------------------------===// 9346 9347 /// Takes the expression passed to the size_t parameter of functions 9348 /// such as memcmp, strncat, etc and warns if it's a comparison. 9349 /// 9350 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9351 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9352 IdentifierInfo *FnName, 9353 SourceLocation FnLoc, 9354 SourceLocation RParenLoc) { 9355 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9356 if (!Size) 9357 return false; 9358 9359 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9360 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9361 return false; 9362 9363 SourceRange SizeRange = Size->getSourceRange(); 9364 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9365 << SizeRange << FnName; 9366 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9367 << FnName 9368 << FixItHint::CreateInsertion( 9369 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9370 << FixItHint::CreateRemoval(RParenLoc); 9371 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9372 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9373 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9374 ")"); 9375 9376 return true; 9377 } 9378 9379 /// Determine whether the given type is or contains a dynamic class type 9380 /// (e.g., whether it has a vtable). 9381 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9382 bool &IsContained) { 9383 // Look through array types while ignoring qualifiers. 9384 const Type *Ty = T->getBaseElementTypeUnsafe(); 9385 IsContained = false; 9386 9387 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9388 RD = RD ? RD->getDefinition() : nullptr; 9389 if (!RD || RD->isInvalidDecl()) 9390 return nullptr; 9391 9392 if (RD->isDynamicClass()) 9393 return RD; 9394 9395 // Check all the fields. If any bases were dynamic, the class is dynamic. 9396 // It's impossible for a class to transitively contain itself by value, so 9397 // infinite recursion is impossible. 9398 for (auto *FD : RD->fields()) { 9399 bool SubContained; 9400 if (const CXXRecordDecl *ContainedRD = 9401 getContainedDynamicClass(FD->getType(), SubContained)) { 9402 IsContained = true; 9403 return ContainedRD; 9404 } 9405 } 9406 9407 return nullptr; 9408 } 9409 9410 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9411 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9412 if (Unary->getKind() == UETT_SizeOf) 9413 return Unary; 9414 return nullptr; 9415 } 9416 9417 /// If E is a sizeof expression, returns its argument expression, 9418 /// otherwise returns NULL. 9419 static const Expr *getSizeOfExprArg(const Expr *E) { 9420 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9421 if (!SizeOf->isArgumentType()) 9422 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9423 return nullptr; 9424 } 9425 9426 /// If E is a sizeof expression, returns its argument type. 9427 static QualType getSizeOfArgType(const Expr *E) { 9428 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9429 return SizeOf->getTypeOfArgument(); 9430 return QualType(); 9431 } 9432 9433 namespace { 9434 9435 struct SearchNonTrivialToInitializeField 9436 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9437 using Super = 9438 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9439 9440 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9441 9442 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9443 SourceLocation SL) { 9444 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9445 asDerived().visitArray(PDIK, AT, SL); 9446 return; 9447 } 9448 9449 Super::visitWithKind(PDIK, FT, SL); 9450 } 9451 9452 void visitARCStrong(QualType FT, SourceLocation SL) { 9453 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9454 } 9455 void visitARCWeak(QualType FT, SourceLocation SL) { 9456 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9457 } 9458 void visitStruct(QualType FT, SourceLocation SL) { 9459 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9460 visit(FD->getType(), FD->getLocation()); 9461 } 9462 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9463 const ArrayType *AT, SourceLocation SL) { 9464 visit(getContext().getBaseElementType(AT), SL); 9465 } 9466 void visitTrivial(QualType FT, SourceLocation SL) {} 9467 9468 static void diag(QualType RT, const Expr *E, Sema &S) { 9469 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9470 } 9471 9472 ASTContext &getContext() { return S.getASTContext(); } 9473 9474 const Expr *E; 9475 Sema &S; 9476 }; 9477 9478 struct SearchNonTrivialToCopyField 9479 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9480 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9481 9482 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9483 9484 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9485 SourceLocation SL) { 9486 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9487 asDerived().visitArray(PCK, AT, SL); 9488 return; 9489 } 9490 9491 Super::visitWithKind(PCK, FT, SL); 9492 } 9493 9494 void visitARCStrong(QualType FT, SourceLocation SL) { 9495 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9496 } 9497 void visitARCWeak(QualType FT, SourceLocation SL) { 9498 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9499 } 9500 void visitStruct(QualType FT, SourceLocation SL) { 9501 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9502 visit(FD->getType(), FD->getLocation()); 9503 } 9504 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9505 SourceLocation SL) { 9506 visit(getContext().getBaseElementType(AT), SL); 9507 } 9508 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9509 SourceLocation SL) {} 9510 void visitTrivial(QualType FT, SourceLocation SL) {} 9511 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9512 9513 static void diag(QualType RT, const Expr *E, Sema &S) { 9514 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9515 } 9516 9517 ASTContext &getContext() { return S.getASTContext(); } 9518 9519 const Expr *E; 9520 Sema &S; 9521 }; 9522 9523 } 9524 9525 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9526 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9527 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9528 9529 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9530 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9531 return false; 9532 9533 return doesExprLikelyComputeSize(BO->getLHS()) || 9534 doesExprLikelyComputeSize(BO->getRHS()); 9535 } 9536 9537 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9538 } 9539 9540 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9541 /// 9542 /// \code 9543 /// #define MACRO 0 9544 /// foo(MACRO); 9545 /// foo(0); 9546 /// \endcode 9547 /// 9548 /// This should return true for the first call to foo, but not for the second 9549 /// (regardless of whether foo is a macro or function). 9550 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9551 SourceLocation CallLoc, 9552 SourceLocation ArgLoc) { 9553 if (!CallLoc.isMacroID()) 9554 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9555 9556 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9557 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9558 } 9559 9560 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9561 /// last two arguments transposed. 9562 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9563 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9564 return; 9565 9566 const Expr *SizeArg = 9567 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9568 9569 auto isLiteralZero = [](const Expr *E) { 9570 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9571 }; 9572 9573 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9574 SourceLocation CallLoc = Call->getRParenLoc(); 9575 SourceManager &SM = S.getSourceManager(); 9576 if (isLiteralZero(SizeArg) && 9577 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9578 9579 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9580 9581 // Some platforms #define bzero to __builtin_memset. See if this is the 9582 // case, and if so, emit a better diagnostic. 9583 if (BId == Builtin::BIbzero || 9584 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9585 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9586 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9587 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9588 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9589 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9590 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9591 } 9592 return; 9593 } 9594 9595 // If the second argument to a memset is a sizeof expression and the third 9596 // isn't, this is also likely an error. This should catch 9597 // 'memset(buf, sizeof(buf), 0xff)'. 9598 if (BId == Builtin::BImemset && 9599 doesExprLikelyComputeSize(Call->getArg(1)) && 9600 !doesExprLikelyComputeSize(Call->getArg(2))) { 9601 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9602 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9603 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9604 return; 9605 } 9606 } 9607 9608 /// Check for dangerous or invalid arguments to memset(). 9609 /// 9610 /// This issues warnings on known problematic, dangerous or unspecified 9611 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9612 /// function calls. 9613 /// 9614 /// \param Call The call expression to diagnose. 9615 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9616 unsigned BId, 9617 IdentifierInfo *FnName) { 9618 assert(BId != 0); 9619 9620 // It is possible to have a non-standard definition of memset. Validate 9621 // we have enough arguments, and if not, abort further checking. 9622 unsigned ExpectedNumArgs = 9623 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9624 if (Call->getNumArgs() < ExpectedNumArgs) 9625 return; 9626 9627 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9628 BId == Builtin::BIstrndup ? 1 : 2); 9629 unsigned LenArg = 9630 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9631 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9632 9633 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9634 Call->getBeginLoc(), Call->getRParenLoc())) 9635 return; 9636 9637 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9638 CheckMemaccessSize(*this, BId, Call); 9639 9640 // We have special checking when the length is a sizeof expression. 9641 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9642 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9643 llvm::FoldingSetNodeID SizeOfArgID; 9644 9645 // Although widely used, 'bzero' is not a standard function. Be more strict 9646 // with the argument types before allowing diagnostics and only allow the 9647 // form bzero(ptr, sizeof(...)). 9648 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9649 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9650 return; 9651 9652 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9653 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9654 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9655 9656 QualType DestTy = Dest->getType(); 9657 QualType PointeeTy; 9658 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9659 PointeeTy = DestPtrTy->getPointeeType(); 9660 9661 // Never warn about void type pointers. This can be used to suppress 9662 // false positives. 9663 if (PointeeTy->isVoidType()) 9664 continue; 9665 9666 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9667 // actually comparing the expressions for equality. Because computing the 9668 // expression IDs can be expensive, we only do this if the diagnostic is 9669 // enabled. 9670 if (SizeOfArg && 9671 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9672 SizeOfArg->getExprLoc())) { 9673 // We only compute IDs for expressions if the warning is enabled, and 9674 // cache the sizeof arg's ID. 9675 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9676 SizeOfArg->Profile(SizeOfArgID, Context, true); 9677 llvm::FoldingSetNodeID DestID; 9678 Dest->Profile(DestID, Context, true); 9679 if (DestID == SizeOfArgID) { 9680 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9681 // over sizeof(src) as well. 9682 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9683 StringRef ReadableName = FnName->getName(); 9684 9685 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9686 if (UnaryOp->getOpcode() == UO_AddrOf) 9687 ActionIdx = 1; // If its an address-of operator, just remove it. 9688 if (!PointeeTy->isIncompleteType() && 9689 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9690 ActionIdx = 2; // If the pointee's size is sizeof(char), 9691 // suggest an explicit length. 9692 9693 // If the function is defined as a builtin macro, do not show macro 9694 // expansion. 9695 SourceLocation SL = SizeOfArg->getExprLoc(); 9696 SourceRange DSR = Dest->getSourceRange(); 9697 SourceRange SSR = SizeOfArg->getSourceRange(); 9698 SourceManager &SM = getSourceManager(); 9699 9700 if (SM.isMacroArgExpansion(SL)) { 9701 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9702 SL = SM.getSpellingLoc(SL); 9703 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9704 SM.getSpellingLoc(DSR.getEnd())); 9705 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9706 SM.getSpellingLoc(SSR.getEnd())); 9707 } 9708 9709 DiagRuntimeBehavior(SL, SizeOfArg, 9710 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9711 << ReadableName 9712 << PointeeTy 9713 << DestTy 9714 << DSR 9715 << SSR); 9716 DiagRuntimeBehavior(SL, SizeOfArg, 9717 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9718 << ActionIdx 9719 << SSR); 9720 9721 break; 9722 } 9723 } 9724 9725 // Also check for cases where the sizeof argument is the exact same 9726 // type as the memory argument, and where it points to a user-defined 9727 // record type. 9728 if (SizeOfArgTy != QualType()) { 9729 if (PointeeTy->isRecordType() && 9730 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9731 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9732 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9733 << FnName << SizeOfArgTy << ArgIdx 9734 << PointeeTy << Dest->getSourceRange() 9735 << LenExpr->getSourceRange()); 9736 break; 9737 } 9738 } 9739 } else if (DestTy->isArrayType()) { 9740 PointeeTy = DestTy; 9741 } 9742 9743 if (PointeeTy == QualType()) 9744 continue; 9745 9746 // Always complain about dynamic classes. 9747 bool IsContained; 9748 if (const CXXRecordDecl *ContainedRD = 9749 getContainedDynamicClass(PointeeTy, IsContained)) { 9750 9751 unsigned OperationType = 0; 9752 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9753 // "overwritten" if we're warning about the destination for any call 9754 // but memcmp; otherwise a verb appropriate to the call. 9755 if (ArgIdx != 0 || IsCmp) { 9756 if (BId == Builtin::BImemcpy) 9757 OperationType = 1; 9758 else if(BId == Builtin::BImemmove) 9759 OperationType = 2; 9760 else if (IsCmp) 9761 OperationType = 3; 9762 } 9763 9764 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9765 PDiag(diag::warn_dyn_class_memaccess) 9766 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9767 << IsContained << ContainedRD << OperationType 9768 << Call->getCallee()->getSourceRange()); 9769 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9770 BId != Builtin::BImemset) 9771 DiagRuntimeBehavior( 9772 Dest->getExprLoc(), Dest, 9773 PDiag(diag::warn_arc_object_memaccess) 9774 << ArgIdx << FnName << PointeeTy 9775 << Call->getCallee()->getSourceRange()); 9776 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9777 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9778 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9779 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9780 PDiag(diag::warn_cstruct_memaccess) 9781 << ArgIdx << FnName << PointeeTy << 0); 9782 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9783 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9784 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9785 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9786 PDiag(diag::warn_cstruct_memaccess) 9787 << ArgIdx << FnName << PointeeTy << 1); 9788 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9789 } else { 9790 continue; 9791 } 9792 } else 9793 continue; 9794 9795 DiagRuntimeBehavior( 9796 Dest->getExprLoc(), Dest, 9797 PDiag(diag::note_bad_memaccess_silence) 9798 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9799 break; 9800 } 9801 } 9802 9803 // A little helper routine: ignore addition and subtraction of integer literals. 9804 // This intentionally does not ignore all integer constant expressions because 9805 // we don't want to remove sizeof(). 9806 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9807 Ex = Ex->IgnoreParenCasts(); 9808 9809 while (true) { 9810 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9811 if (!BO || !BO->isAdditiveOp()) 9812 break; 9813 9814 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9815 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9816 9817 if (isa<IntegerLiteral>(RHS)) 9818 Ex = LHS; 9819 else if (isa<IntegerLiteral>(LHS)) 9820 Ex = RHS; 9821 else 9822 break; 9823 } 9824 9825 return Ex; 9826 } 9827 9828 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9829 ASTContext &Context) { 9830 // Only handle constant-sized or VLAs, but not flexible members. 9831 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9832 // Only issue the FIXIT for arrays of size > 1. 9833 if (CAT->getSize().getSExtValue() <= 1) 9834 return false; 9835 } else if (!Ty->isVariableArrayType()) { 9836 return false; 9837 } 9838 return true; 9839 } 9840 9841 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9842 // be the size of the source, instead of the destination. 9843 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9844 IdentifierInfo *FnName) { 9845 9846 // Don't crash if the user has the wrong number of arguments 9847 unsigned NumArgs = Call->getNumArgs(); 9848 if ((NumArgs != 3) && (NumArgs != 4)) 9849 return; 9850 9851 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9852 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9853 const Expr *CompareWithSrc = nullptr; 9854 9855 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9856 Call->getBeginLoc(), Call->getRParenLoc())) 9857 return; 9858 9859 // Look for 'strlcpy(dst, x, sizeof(x))' 9860 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9861 CompareWithSrc = Ex; 9862 else { 9863 // Look for 'strlcpy(dst, x, strlen(x))' 9864 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9865 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9866 SizeCall->getNumArgs() == 1) 9867 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9868 } 9869 } 9870 9871 if (!CompareWithSrc) 9872 return; 9873 9874 // Determine if the argument to sizeof/strlen is equal to the source 9875 // argument. In principle there's all kinds of things you could do 9876 // here, for instance creating an == expression and evaluating it with 9877 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9878 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9879 if (!SrcArgDRE) 9880 return; 9881 9882 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9883 if (!CompareWithSrcDRE || 9884 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9885 return; 9886 9887 const Expr *OriginalSizeArg = Call->getArg(2); 9888 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9889 << OriginalSizeArg->getSourceRange() << FnName; 9890 9891 // Output a FIXIT hint if the destination is an array (rather than a 9892 // pointer to an array). This could be enhanced to handle some 9893 // pointers if we know the actual size, like if DstArg is 'array+2' 9894 // we could say 'sizeof(array)-2'. 9895 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9896 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9897 return; 9898 9899 SmallString<128> sizeString; 9900 llvm::raw_svector_ostream OS(sizeString); 9901 OS << "sizeof("; 9902 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9903 OS << ")"; 9904 9905 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9906 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9907 OS.str()); 9908 } 9909 9910 /// Check if two expressions refer to the same declaration. 9911 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9912 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9913 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9914 return D1->getDecl() == D2->getDecl(); 9915 return false; 9916 } 9917 9918 static const Expr *getStrlenExprArg(const Expr *E) { 9919 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9920 const FunctionDecl *FD = CE->getDirectCallee(); 9921 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9922 return nullptr; 9923 return CE->getArg(0)->IgnoreParenCasts(); 9924 } 9925 return nullptr; 9926 } 9927 9928 // Warn on anti-patterns as the 'size' argument to strncat. 9929 // The correct size argument should look like following: 9930 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9931 void Sema::CheckStrncatArguments(const CallExpr *CE, 9932 IdentifierInfo *FnName) { 9933 // Don't crash if the user has the wrong number of arguments. 9934 if (CE->getNumArgs() < 3) 9935 return; 9936 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9937 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9938 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9939 9940 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9941 CE->getRParenLoc())) 9942 return; 9943 9944 // Identify common expressions, which are wrongly used as the size argument 9945 // to strncat and may lead to buffer overflows. 9946 unsigned PatternType = 0; 9947 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9948 // - sizeof(dst) 9949 if (referToTheSameDecl(SizeOfArg, DstArg)) 9950 PatternType = 1; 9951 // - sizeof(src) 9952 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9953 PatternType = 2; 9954 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9955 if (BE->getOpcode() == BO_Sub) { 9956 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9957 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9958 // - sizeof(dst) - strlen(dst) 9959 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9960 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9961 PatternType = 1; 9962 // - sizeof(src) - (anything) 9963 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9964 PatternType = 2; 9965 } 9966 } 9967 9968 if (PatternType == 0) 9969 return; 9970 9971 // Generate the diagnostic. 9972 SourceLocation SL = LenArg->getBeginLoc(); 9973 SourceRange SR = LenArg->getSourceRange(); 9974 SourceManager &SM = getSourceManager(); 9975 9976 // If the function is defined as a builtin macro, do not show macro expansion. 9977 if (SM.isMacroArgExpansion(SL)) { 9978 SL = SM.getSpellingLoc(SL); 9979 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9980 SM.getSpellingLoc(SR.getEnd())); 9981 } 9982 9983 // Check if the destination is an array (rather than a pointer to an array). 9984 QualType DstTy = DstArg->getType(); 9985 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9986 Context); 9987 if (!isKnownSizeArray) { 9988 if (PatternType == 1) 9989 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9990 else 9991 Diag(SL, diag::warn_strncat_src_size) << SR; 9992 return; 9993 } 9994 9995 if (PatternType == 1) 9996 Diag(SL, diag::warn_strncat_large_size) << SR; 9997 else 9998 Diag(SL, diag::warn_strncat_src_size) << SR; 9999 10000 SmallString<128> sizeString; 10001 llvm::raw_svector_ostream OS(sizeString); 10002 OS << "sizeof("; 10003 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10004 OS << ") - "; 10005 OS << "strlen("; 10006 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10007 OS << ") - 1"; 10008 10009 Diag(SL, diag::note_strncat_wrong_size) 10010 << FixItHint::CreateReplacement(SR, OS.str()); 10011 } 10012 10013 void 10014 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10015 SourceLocation ReturnLoc, 10016 bool isObjCMethod, 10017 const AttrVec *Attrs, 10018 const FunctionDecl *FD) { 10019 // Check if the return value is null but should not be. 10020 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10021 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10022 CheckNonNullExpr(*this, RetValExp)) 10023 Diag(ReturnLoc, diag::warn_null_ret) 10024 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10025 10026 // C++11 [basic.stc.dynamic.allocation]p4: 10027 // If an allocation function declared with a non-throwing 10028 // exception-specification fails to allocate storage, it shall return 10029 // a null pointer. Any other allocation function that fails to allocate 10030 // storage shall indicate failure only by throwing an exception [...] 10031 if (FD) { 10032 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10033 if (Op == OO_New || Op == OO_Array_New) { 10034 const FunctionProtoType *Proto 10035 = FD->getType()->castAs<FunctionProtoType>(); 10036 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10037 CheckNonNullExpr(*this, RetValExp)) 10038 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10039 << FD << getLangOpts().CPlusPlus11; 10040 } 10041 } 10042 } 10043 10044 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10045 10046 /// Check for comparisons of floating point operands using != and ==. 10047 /// Issue a warning if these are no self-comparisons, as they are not likely 10048 /// to do what the programmer intended. 10049 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10050 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10051 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10052 10053 // Special case: check for x == x (which is OK). 10054 // Do not emit warnings for such cases. 10055 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10056 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10057 if (DRL->getDecl() == DRR->getDecl()) 10058 return; 10059 10060 // Special case: check for comparisons against literals that can be exactly 10061 // represented by APFloat. In such cases, do not emit a warning. This 10062 // is a heuristic: often comparison against such literals are used to 10063 // detect if a value in a variable has not changed. This clearly can 10064 // lead to false negatives. 10065 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10066 if (FLL->isExact()) 10067 return; 10068 } else 10069 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10070 if (FLR->isExact()) 10071 return; 10072 10073 // Check for comparisons with builtin types. 10074 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10075 if (CL->getBuiltinCallee()) 10076 return; 10077 10078 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10079 if (CR->getBuiltinCallee()) 10080 return; 10081 10082 // Emit the diagnostic. 10083 Diag(Loc, diag::warn_floatingpoint_eq) 10084 << LHS->getSourceRange() << RHS->getSourceRange(); 10085 } 10086 10087 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10088 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10089 10090 namespace { 10091 10092 /// Structure recording the 'active' range of an integer-valued 10093 /// expression. 10094 struct IntRange { 10095 /// The number of bits active in the int. 10096 unsigned Width; 10097 10098 /// True if the int is known not to have negative values. 10099 bool NonNegative; 10100 10101 IntRange(unsigned Width, bool NonNegative) 10102 : Width(Width), NonNegative(NonNegative) {} 10103 10104 /// Returns the range of the bool type. 10105 static IntRange forBoolType() { 10106 return IntRange(1, true); 10107 } 10108 10109 /// Returns the range of an opaque value of the given integral type. 10110 static IntRange forValueOfType(ASTContext &C, QualType T) { 10111 return forValueOfCanonicalType(C, 10112 T->getCanonicalTypeInternal().getTypePtr()); 10113 } 10114 10115 /// Returns the range of an opaque value of a canonical integral type. 10116 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10117 assert(T->isCanonicalUnqualified()); 10118 10119 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10120 T = VT->getElementType().getTypePtr(); 10121 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10122 T = CT->getElementType().getTypePtr(); 10123 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10124 T = AT->getValueType().getTypePtr(); 10125 10126 if (!C.getLangOpts().CPlusPlus) { 10127 // For enum types in C code, use the underlying datatype. 10128 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10129 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10130 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10131 // For enum types in C++, use the known bit width of the enumerators. 10132 EnumDecl *Enum = ET->getDecl(); 10133 // In C++11, enums can have a fixed underlying type. Use this type to 10134 // compute the range. 10135 if (Enum->isFixed()) { 10136 return IntRange(C.getIntWidth(QualType(T, 0)), 10137 !ET->isSignedIntegerOrEnumerationType()); 10138 } 10139 10140 unsigned NumPositive = Enum->getNumPositiveBits(); 10141 unsigned NumNegative = Enum->getNumNegativeBits(); 10142 10143 if (NumNegative == 0) 10144 return IntRange(NumPositive, true/*NonNegative*/); 10145 else 10146 return IntRange(std::max(NumPositive + 1, NumNegative), 10147 false/*NonNegative*/); 10148 } 10149 10150 const BuiltinType *BT = cast<BuiltinType>(T); 10151 assert(BT->isInteger()); 10152 10153 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10154 } 10155 10156 /// Returns the "target" range of a canonical integral type, i.e. 10157 /// the range of values expressible in the type. 10158 /// 10159 /// This matches forValueOfCanonicalType except that enums have the 10160 /// full range of their type, not the range of their enumerators. 10161 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10162 assert(T->isCanonicalUnqualified()); 10163 10164 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10165 T = VT->getElementType().getTypePtr(); 10166 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10167 T = CT->getElementType().getTypePtr(); 10168 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10169 T = AT->getValueType().getTypePtr(); 10170 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10171 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10172 10173 const BuiltinType *BT = cast<BuiltinType>(T); 10174 assert(BT->isInteger()); 10175 10176 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10177 } 10178 10179 /// Returns the supremum of two ranges: i.e. their conservative merge. 10180 static IntRange join(IntRange L, IntRange R) { 10181 return IntRange(std::max(L.Width, R.Width), 10182 L.NonNegative && R.NonNegative); 10183 } 10184 10185 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10186 static IntRange meet(IntRange L, IntRange R) { 10187 return IntRange(std::min(L.Width, R.Width), 10188 L.NonNegative || R.NonNegative); 10189 } 10190 }; 10191 10192 } // namespace 10193 10194 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10195 unsigned MaxWidth) { 10196 if (value.isSigned() && value.isNegative()) 10197 return IntRange(value.getMinSignedBits(), false); 10198 10199 if (value.getBitWidth() > MaxWidth) 10200 value = value.trunc(MaxWidth); 10201 10202 // isNonNegative() just checks the sign bit without considering 10203 // signedness. 10204 return IntRange(value.getActiveBits(), true); 10205 } 10206 10207 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10208 unsigned MaxWidth) { 10209 if (result.isInt()) 10210 return GetValueRange(C, result.getInt(), MaxWidth); 10211 10212 if (result.isVector()) { 10213 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10214 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10215 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10216 R = IntRange::join(R, El); 10217 } 10218 return R; 10219 } 10220 10221 if (result.isComplexInt()) { 10222 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10223 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10224 return IntRange::join(R, I); 10225 } 10226 10227 // This can happen with lossless casts to intptr_t of "based" lvalues. 10228 // Assume it might use arbitrary bits. 10229 // FIXME: The only reason we need to pass the type in here is to get 10230 // the sign right on this one case. It would be nice if APValue 10231 // preserved this. 10232 assert(result.isLValue() || result.isAddrLabelDiff()); 10233 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10234 } 10235 10236 static QualType GetExprType(const Expr *E) { 10237 QualType Ty = E->getType(); 10238 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10239 Ty = AtomicRHS->getValueType(); 10240 return Ty; 10241 } 10242 10243 /// Pseudo-evaluate the given integer expression, estimating the 10244 /// range of values it might take. 10245 /// 10246 /// \param MaxWidth - the width to which the value will be truncated 10247 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10248 bool InConstantContext) { 10249 E = E->IgnoreParens(); 10250 10251 // Try a full evaluation first. 10252 Expr::EvalResult result; 10253 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10254 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10255 10256 // I think we only want to look through implicit casts here; if the 10257 // user has an explicit widening cast, we should treat the value as 10258 // being of the new, wider type. 10259 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10260 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10261 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10262 10263 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10264 10265 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10266 CE->getCastKind() == CK_BooleanToSignedIntegral; 10267 10268 // Assume that non-integer casts can span the full range of the type. 10269 if (!isIntegerCast) 10270 return OutputTypeRange; 10271 10272 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10273 std::min(MaxWidth, OutputTypeRange.Width), 10274 InConstantContext); 10275 10276 // Bail out if the subexpr's range is as wide as the cast type. 10277 if (SubRange.Width >= OutputTypeRange.Width) 10278 return OutputTypeRange; 10279 10280 // Otherwise, we take the smaller width, and we're non-negative if 10281 // either the output type or the subexpr is. 10282 return IntRange(SubRange.Width, 10283 SubRange.NonNegative || OutputTypeRange.NonNegative); 10284 } 10285 10286 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10287 // If we can fold the condition, just take that operand. 10288 bool CondResult; 10289 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10290 return GetExprRange(C, 10291 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10292 MaxWidth, InConstantContext); 10293 10294 // Otherwise, conservatively merge. 10295 IntRange L = 10296 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10297 IntRange R = 10298 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10299 return IntRange::join(L, R); 10300 } 10301 10302 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10303 switch (BO->getOpcode()) { 10304 case BO_Cmp: 10305 llvm_unreachable("builtin <=> should have class type"); 10306 10307 // Boolean-valued operations are single-bit and positive. 10308 case BO_LAnd: 10309 case BO_LOr: 10310 case BO_LT: 10311 case BO_GT: 10312 case BO_LE: 10313 case BO_GE: 10314 case BO_EQ: 10315 case BO_NE: 10316 return IntRange::forBoolType(); 10317 10318 // The type of the assignments is the type of the LHS, so the RHS 10319 // is not necessarily the same type. 10320 case BO_MulAssign: 10321 case BO_DivAssign: 10322 case BO_RemAssign: 10323 case BO_AddAssign: 10324 case BO_SubAssign: 10325 case BO_XorAssign: 10326 case BO_OrAssign: 10327 // TODO: bitfields? 10328 return IntRange::forValueOfType(C, GetExprType(E)); 10329 10330 // Simple assignments just pass through the RHS, which will have 10331 // been coerced to the LHS type. 10332 case BO_Assign: 10333 // TODO: bitfields? 10334 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10335 10336 // Operations with opaque sources are black-listed. 10337 case BO_PtrMemD: 10338 case BO_PtrMemI: 10339 return IntRange::forValueOfType(C, GetExprType(E)); 10340 10341 // Bitwise-and uses the *infinum* of the two source ranges. 10342 case BO_And: 10343 case BO_AndAssign: 10344 return IntRange::meet( 10345 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10346 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10347 10348 // Left shift gets black-listed based on a judgement call. 10349 case BO_Shl: 10350 // ...except that we want to treat '1 << (blah)' as logically 10351 // positive. It's an important idiom. 10352 if (IntegerLiteral *I 10353 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10354 if (I->getValue() == 1) { 10355 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10356 return IntRange(R.Width, /*NonNegative*/ true); 10357 } 10358 } 10359 LLVM_FALLTHROUGH; 10360 10361 case BO_ShlAssign: 10362 return IntRange::forValueOfType(C, GetExprType(E)); 10363 10364 // Right shift by a constant can narrow its left argument. 10365 case BO_Shr: 10366 case BO_ShrAssign: { 10367 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10368 10369 // If the shift amount is a positive constant, drop the width by 10370 // that much. 10371 llvm::APSInt shift; 10372 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10373 shift.isNonNegative()) { 10374 unsigned zext = shift.getZExtValue(); 10375 if (zext >= L.Width) 10376 L.Width = (L.NonNegative ? 0 : 1); 10377 else 10378 L.Width -= zext; 10379 } 10380 10381 return L; 10382 } 10383 10384 // Comma acts as its right operand. 10385 case BO_Comma: 10386 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10387 10388 // Black-list pointer subtractions. 10389 case BO_Sub: 10390 if (BO->getLHS()->getType()->isPointerType()) 10391 return IntRange::forValueOfType(C, GetExprType(E)); 10392 break; 10393 10394 // The width of a division result is mostly determined by the size 10395 // of the LHS. 10396 case BO_Div: { 10397 // Don't 'pre-truncate' the operands. 10398 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10399 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10400 10401 // If the divisor is constant, use that. 10402 llvm::APSInt divisor; 10403 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10404 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10405 if (log2 >= L.Width) 10406 L.Width = (L.NonNegative ? 0 : 1); 10407 else 10408 L.Width = std::min(L.Width - log2, MaxWidth); 10409 return L; 10410 } 10411 10412 // Otherwise, just use the LHS's width. 10413 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10414 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10415 } 10416 10417 // The result of a remainder can't be larger than the result of 10418 // either side. 10419 case BO_Rem: { 10420 // Don't 'pre-truncate' the operands. 10421 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10422 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10423 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10424 10425 IntRange meet = IntRange::meet(L, R); 10426 meet.Width = std::min(meet.Width, MaxWidth); 10427 return meet; 10428 } 10429 10430 // The default behavior is okay for these. 10431 case BO_Mul: 10432 case BO_Add: 10433 case BO_Xor: 10434 case BO_Or: 10435 break; 10436 } 10437 10438 // The default case is to treat the operation as if it were closed 10439 // on the narrowest type that encompasses both operands. 10440 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10441 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10442 return IntRange::join(L, R); 10443 } 10444 10445 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10446 switch (UO->getOpcode()) { 10447 // Boolean-valued operations are white-listed. 10448 case UO_LNot: 10449 return IntRange::forBoolType(); 10450 10451 // Operations with opaque sources are black-listed. 10452 case UO_Deref: 10453 case UO_AddrOf: // should be impossible 10454 return IntRange::forValueOfType(C, GetExprType(E)); 10455 10456 default: 10457 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10458 } 10459 } 10460 10461 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10462 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10463 10464 if (const auto *BitField = E->getSourceBitField()) 10465 return IntRange(BitField->getBitWidthValue(C), 10466 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10467 10468 return IntRange::forValueOfType(C, GetExprType(E)); 10469 } 10470 10471 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10472 bool InConstantContext) { 10473 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10474 } 10475 10476 /// Checks whether the given value, which currently has the given 10477 /// source semantics, has the same value when coerced through the 10478 /// target semantics. 10479 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10480 const llvm::fltSemantics &Src, 10481 const llvm::fltSemantics &Tgt) { 10482 llvm::APFloat truncated = value; 10483 10484 bool ignored; 10485 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10486 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10487 10488 return truncated.bitwiseIsEqual(value); 10489 } 10490 10491 /// Checks whether the given value, which currently has the given 10492 /// source semantics, has the same value when coerced through the 10493 /// target semantics. 10494 /// 10495 /// The value might be a vector of floats (or a complex number). 10496 static bool IsSameFloatAfterCast(const APValue &value, 10497 const llvm::fltSemantics &Src, 10498 const llvm::fltSemantics &Tgt) { 10499 if (value.isFloat()) 10500 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10501 10502 if (value.isVector()) { 10503 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10504 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10505 return false; 10506 return true; 10507 } 10508 10509 assert(value.isComplexFloat()); 10510 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10511 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10512 } 10513 10514 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10515 bool IsListInit = false); 10516 10517 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10518 // Suppress cases where we are comparing against an enum constant. 10519 if (const DeclRefExpr *DR = 10520 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10521 if (isa<EnumConstantDecl>(DR->getDecl())) 10522 return true; 10523 10524 // Suppress cases where the value is expanded from a macro, unless that macro 10525 // is how a language represents a boolean literal. This is the case in both C 10526 // and Objective-C. 10527 SourceLocation BeginLoc = E->getBeginLoc(); 10528 if (BeginLoc.isMacroID()) { 10529 StringRef MacroName = Lexer::getImmediateMacroName( 10530 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10531 return MacroName != "YES" && MacroName != "NO" && 10532 MacroName != "true" && MacroName != "false"; 10533 } 10534 10535 return false; 10536 } 10537 10538 static bool isKnownToHaveUnsignedValue(Expr *E) { 10539 return E->getType()->isIntegerType() && 10540 (!E->getType()->isSignedIntegerType() || 10541 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10542 } 10543 10544 namespace { 10545 /// The promoted range of values of a type. In general this has the 10546 /// following structure: 10547 /// 10548 /// |-----------| . . . |-----------| 10549 /// ^ ^ ^ ^ 10550 /// Min HoleMin HoleMax Max 10551 /// 10552 /// ... where there is only a hole if a signed type is promoted to unsigned 10553 /// (in which case Min and Max are the smallest and largest representable 10554 /// values). 10555 struct PromotedRange { 10556 // Min, or HoleMax if there is a hole. 10557 llvm::APSInt PromotedMin; 10558 // Max, or HoleMin if there is a hole. 10559 llvm::APSInt PromotedMax; 10560 10561 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10562 if (R.Width == 0) 10563 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10564 else if (R.Width >= BitWidth && !Unsigned) { 10565 // Promotion made the type *narrower*. This happens when promoting 10566 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10567 // Treat all values of 'signed int' as being in range for now. 10568 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10569 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10570 } else { 10571 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10572 .extOrTrunc(BitWidth); 10573 PromotedMin.setIsUnsigned(Unsigned); 10574 10575 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10576 .extOrTrunc(BitWidth); 10577 PromotedMax.setIsUnsigned(Unsigned); 10578 } 10579 } 10580 10581 // Determine whether this range is contiguous (has no hole). 10582 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10583 10584 // Where a constant value is within the range. 10585 enum ComparisonResult { 10586 LT = 0x1, 10587 LE = 0x2, 10588 GT = 0x4, 10589 GE = 0x8, 10590 EQ = 0x10, 10591 NE = 0x20, 10592 InRangeFlag = 0x40, 10593 10594 Less = LE | LT | NE, 10595 Min = LE | InRangeFlag, 10596 InRange = InRangeFlag, 10597 Max = GE | InRangeFlag, 10598 Greater = GE | GT | NE, 10599 10600 OnlyValue = LE | GE | EQ | InRangeFlag, 10601 InHole = NE 10602 }; 10603 10604 ComparisonResult compare(const llvm::APSInt &Value) const { 10605 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10606 Value.isUnsigned() == PromotedMin.isUnsigned()); 10607 if (!isContiguous()) { 10608 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10609 if (Value.isMinValue()) return Min; 10610 if (Value.isMaxValue()) return Max; 10611 if (Value >= PromotedMin) return InRange; 10612 if (Value <= PromotedMax) return InRange; 10613 return InHole; 10614 } 10615 10616 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10617 case -1: return Less; 10618 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10619 case 1: 10620 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10621 case -1: return InRange; 10622 case 0: return Max; 10623 case 1: return Greater; 10624 } 10625 } 10626 10627 llvm_unreachable("impossible compare result"); 10628 } 10629 10630 static llvm::Optional<StringRef> 10631 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10632 if (Op == BO_Cmp) { 10633 ComparisonResult LTFlag = LT, GTFlag = GT; 10634 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10635 10636 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10637 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10638 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10639 return llvm::None; 10640 } 10641 10642 ComparisonResult TrueFlag, FalseFlag; 10643 if (Op == BO_EQ) { 10644 TrueFlag = EQ; 10645 FalseFlag = NE; 10646 } else if (Op == BO_NE) { 10647 TrueFlag = NE; 10648 FalseFlag = EQ; 10649 } else { 10650 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10651 TrueFlag = LT; 10652 FalseFlag = GE; 10653 } else { 10654 TrueFlag = GT; 10655 FalseFlag = LE; 10656 } 10657 if (Op == BO_GE || Op == BO_LE) 10658 std::swap(TrueFlag, FalseFlag); 10659 } 10660 if (R & TrueFlag) 10661 return StringRef("true"); 10662 if (R & FalseFlag) 10663 return StringRef("false"); 10664 return llvm::None; 10665 } 10666 }; 10667 } 10668 10669 static bool HasEnumType(Expr *E) { 10670 // Strip off implicit integral promotions. 10671 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10672 if (ICE->getCastKind() != CK_IntegralCast && 10673 ICE->getCastKind() != CK_NoOp) 10674 break; 10675 E = ICE->getSubExpr(); 10676 } 10677 10678 return E->getType()->isEnumeralType(); 10679 } 10680 10681 static int classifyConstantValue(Expr *Constant) { 10682 // The values of this enumeration are used in the diagnostics 10683 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10684 enum ConstantValueKind { 10685 Miscellaneous = 0, 10686 LiteralTrue, 10687 LiteralFalse 10688 }; 10689 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10690 return BL->getValue() ? ConstantValueKind::LiteralTrue 10691 : ConstantValueKind::LiteralFalse; 10692 return ConstantValueKind::Miscellaneous; 10693 } 10694 10695 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10696 Expr *Constant, Expr *Other, 10697 const llvm::APSInt &Value, 10698 bool RhsConstant) { 10699 if (S.inTemplateInstantiation()) 10700 return false; 10701 10702 Expr *OriginalOther = Other; 10703 10704 Constant = Constant->IgnoreParenImpCasts(); 10705 Other = Other->IgnoreParenImpCasts(); 10706 10707 // Suppress warnings on tautological comparisons between values of the same 10708 // enumeration type. There are only two ways we could warn on this: 10709 // - If the constant is outside the range of representable values of 10710 // the enumeration. In such a case, we should warn about the cast 10711 // to enumeration type, not about the comparison. 10712 // - If the constant is the maximum / minimum in-range value. For an 10713 // enumeratin type, such comparisons can be meaningful and useful. 10714 if (Constant->getType()->isEnumeralType() && 10715 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10716 return false; 10717 10718 // TODO: Investigate using GetExprRange() to get tighter bounds 10719 // on the bit ranges. 10720 QualType OtherT = Other->getType(); 10721 if (const auto *AT = OtherT->getAs<AtomicType>()) 10722 OtherT = AT->getValueType(); 10723 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10724 10725 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10726 // (Namely, macOS). 10727 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10728 S.NSAPIObj->isObjCBOOLType(OtherT) && 10729 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10730 10731 // Whether we're treating Other as being a bool because of the form of 10732 // expression despite it having another type (typically 'int' in C). 10733 bool OtherIsBooleanDespiteType = 10734 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10735 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10736 OtherRange = IntRange::forBoolType(); 10737 10738 // Determine the promoted range of the other type and see if a comparison of 10739 // the constant against that range is tautological. 10740 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10741 Value.isUnsigned()); 10742 auto Cmp = OtherPromotedRange.compare(Value); 10743 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10744 if (!Result) 10745 return false; 10746 10747 // Suppress the diagnostic for an in-range comparison if the constant comes 10748 // from a macro or enumerator. We don't want to diagnose 10749 // 10750 // some_long_value <= INT_MAX 10751 // 10752 // when sizeof(int) == sizeof(long). 10753 bool InRange = Cmp & PromotedRange::InRangeFlag; 10754 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10755 return false; 10756 10757 // If this is a comparison to an enum constant, include that 10758 // constant in the diagnostic. 10759 const EnumConstantDecl *ED = nullptr; 10760 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10761 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10762 10763 // Should be enough for uint128 (39 decimal digits) 10764 SmallString<64> PrettySourceValue; 10765 llvm::raw_svector_ostream OS(PrettySourceValue); 10766 if (ED) { 10767 OS << '\'' << *ED << "' (" << Value << ")"; 10768 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10769 Constant->IgnoreParenImpCasts())) { 10770 OS << (BL->getValue() ? "YES" : "NO"); 10771 } else { 10772 OS << Value; 10773 } 10774 10775 if (IsObjCSignedCharBool) { 10776 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10777 S.PDiag(diag::warn_tautological_compare_objc_bool) 10778 << OS.str() << *Result); 10779 return true; 10780 } 10781 10782 // FIXME: We use a somewhat different formatting for the in-range cases and 10783 // cases involving boolean values for historical reasons. We should pick a 10784 // consistent way of presenting these diagnostics. 10785 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10786 10787 S.DiagRuntimeBehavior( 10788 E->getOperatorLoc(), E, 10789 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10790 : diag::warn_tautological_bool_compare) 10791 << OS.str() << classifyConstantValue(Constant) << OtherT 10792 << OtherIsBooleanDespiteType << *Result 10793 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10794 } else { 10795 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10796 ? (HasEnumType(OriginalOther) 10797 ? diag::warn_unsigned_enum_always_true_comparison 10798 : diag::warn_unsigned_always_true_comparison) 10799 : diag::warn_tautological_constant_compare; 10800 10801 S.Diag(E->getOperatorLoc(), Diag) 10802 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10803 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10804 } 10805 10806 return true; 10807 } 10808 10809 /// Analyze the operands of the given comparison. Implements the 10810 /// fallback case from AnalyzeComparison. 10811 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10812 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10813 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10814 } 10815 10816 /// Implements -Wsign-compare. 10817 /// 10818 /// \param E the binary operator to check for warnings 10819 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10820 // The type the comparison is being performed in. 10821 QualType T = E->getLHS()->getType(); 10822 10823 // Only analyze comparison operators where both sides have been converted to 10824 // the same type. 10825 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10826 return AnalyzeImpConvsInComparison(S, E); 10827 10828 // Don't analyze value-dependent comparisons directly. 10829 if (E->isValueDependent()) 10830 return AnalyzeImpConvsInComparison(S, E); 10831 10832 Expr *LHS = E->getLHS(); 10833 Expr *RHS = E->getRHS(); 10834 10835 if (T->isIntegralType(S.Context)) { 10836 llvm::APSInt RHSValue; 10837 llvm::APSInt LHSValue; 10838 10839 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10840 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10841 10842 // We don't care about expressions whose result is a constant. 10843 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10844 return AnalyzeImpConvsInComparison(S, E); 10845 10846 // We only care about expressions where just one side is literal 10847 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10848 // Is the constant on the RHS or LHS? 10849 const bool RhsConstant = IsRHSIntegralLiteral; 10850 Expr *Const = RhsConstant ? RHS : LHS; 10851 Expr *Other = RhsConstant ? LHS : RHS; 10852 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10853 10854 // Check whether an integer constant comparison results in a value 10855 // of 'true' or 'false'. 10856 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10857 return AnalyzeImpConvsInComparison(S, E); 10858 } 10859 } 10860 10861 if (!T->hasUnsignedIntegerRepresentation()) { 10862 // We don't do anything special if this isn't an unsigned integral 10863 // comparison: we're only interested in integral comparisons, and 10864 // signed comparisons only happen in cases we don't care to warn about. 10865 return AnalyzeImpConvsInComparison(S, E); 10866 } 10867 10868 LHS = LHS->IgnoreParenImpCasts(); 10869 RHS = RHS->IgnoreParenImpCasts(); 10870 10871 if (!S.getLangOpts().CPlusPlus) { 10872 // Avoid warning about comparison of integers with different signs when 10873 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10874 // the type of `E`. 10875 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10876 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10877 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10878 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10879 } 10880 10881 // Check to see if one of the (unmodified) operands is of different 10882 // signedness. 10883 Expr *signedOperand, *unsignedOperand; 10884 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10885 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10886 "unsigned comparison between two signed integer expressions?"); 10887 signedOperand = LHS; 10888 unsignedOperand = RHS; 10889 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10890 signedOperand = RHS; 10891 unsignedOperand = LHS; 10892 } else { 10893 return AnalyzeImpConvsInComparison(S, E); 10894 } 10895 10896 // Otherwise, calculate the effective range of the signed operand. 10897 IntRange signedRange = 10898 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10899 10900 // Go ahead and analyze implicit conversions in the operands. Note 10901 // that we skip the implicit conversions on both sides. 10902 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10903 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10904 10905 // If the signed range is non-negative, -Wsign-compare won't fire. 10906 if (signedRange.NonNegative) 10907 return; 10908 10909 // For (in)equality comparisons, if the unsigned operand is a 10910 // constant which cannot collide with a overflowed signed operand, 10911 // then reinterpreting the signed operand as unsigned will not 10912 // change the result of the comparison. 10913 if (E->isEqualityOp()) { 10914 unsigned comparisonWidth = S.Context.getIntWidth(T); 10915 IntRange unsignedRange = 10916 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10917 10918 // We should never be unable to prove that the unsigned operand is 10919 // non-negative. 10920 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10921 10922 if (unsignedRange.Width < comparisonWidth) 10923 return; 10924 } 10925 10926 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10927 S.PDiag(diag::warn_mixed_sign_comparison) 10928 << LHS->getType() << RHS->getType() 10929 << LHS->getSourceRange() << RHS->getSourceRange()); 10930 } 10931 10932 /// Analyzes an attempt to assign the given value to a bitfield. 10933 /// 10934 /// Returns true if there was something fishy about the attempt. 10935 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10936 SourceLocation InitLoc) { 10937 assert(Bitfield->isBitField()); 10938 if (Bitfield->isInvalidDecl()) 10939 return false; 10940 10941 // White-list bool bitfields. 10942 QualType BitfieldType = Bitfield->getType(); 10943 if (BitfieldType->isBooleanType()) 10944 return false; 10945 10946 if (BitfieldType->isEnumeralType()) { 10947 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10948 // If the underlying enum type was not explicitly specified as an unsigned 10949 // type and the enum contain only positive values, MSVC++ will cause an 10950 // inconsistency by storing this as a signed type. 10951 if (S.getLangOpts().CPlusPlus11 && 10952 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10953 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10954 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10955 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10956 << BitfieldEnumDecl->getNameAsString(); 10957 } 10958 } 10959 10960 if (Bitfield->getType()->isBooleanType()) 10961 return false; 10962 10963 // Ignore value- or type-dependent expressions. 10964 if (Bitfield->getBitWidth()->isValueDependent() || 10965 Bitfield->getBitWidth()->isTypeDependent() || 10966 Init->isValueDependent() || 10967 Init->isTypeDependent()) 10968 return false; 10969 10970 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10971 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10972 10973 Expr::EvalResult Result; 10974 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10975 Expr::SE_AllowSideEffects)) { 10976 // The RHS is not constant. If the RHS has an enum type, make sure the 10977 // bitfield is wide enough to hold all the values of the enum without 10978 // truncation. 10979 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10980 EnumDecl *ED = EnumTy->getDecl(); 10981 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10982 10983 // Enum types are implicitly signed on Windows, so check if there are any 10984 // negative enumerators to see if the enum was intended to be signed or 10985 // not. 10986 bool SignedEnum = ED->getNumNegativeBits() > 0; 10987 10988 // Check for surprising sign changes when assigning enum values to a 10989 // bitfield of different signedness. If the bitfield is signed and we 10990 // have exactly the right number of bits to store this unsigned enum, 10991 // suggest changing the enum to an unsigned type. This typically happens 10992 // on Windows where unfixed enums always use an underlying type of 'int'. 10993 unsigned DiagID = 0; 10994 if (SignedEnum && !SignedBitfield) { 10995 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10996 } else if (SignedBitfield && !SignedEnum && 10997 ED->getNumPositiveBits() == FieldWidth) { 10998 DiagID = diag::warn_signed_bitfield_enum_conversion; 10999 } 11000 11001 if (DiagID) { 11002 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11003 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11004 SourceRange TypeRange = 11005 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11006 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11007 << SignedEnum << TypeRange; 11008 } 11009 11010 // Compute the required bitwidth. If the enum has negative values, we need 11011 // one more bit than the normal number of positive bits to represent the 11012 // sign bit. 11013 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11014 ED->getNumNegativeBits()) 11015 : ED->getNumPositiveBits(); 11016 11017 // Check the bitwidth. 11018 if (BitsNeeded > FieldWidth) { 11019 Expr *WidthExpr = Bitfield->getBitWidth(); 11020 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11021 << Bitfield << ED; 11022 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11023 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11024 } 11025 } 11026 11027 return false; 11028 } 11029 11030 llvm::APSInt Value = Result.Val.getInt(); 11031 11032 unsigned OriginalWidth = Value.getBitWidth(); 11033 11034 if (!Value.isSigned() || Value.isNegative()) 11035 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11036 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11037 OriginalWidth = Value.getMinSignedBits(); 11038 11039 if (OriginalWidth <= FieldWidth) 11040 return false; 11041 11042 // Compute the value which the bitfield will contain. 11043 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11044 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11045 11046 // Check whether the stored value is equal to the original value. 11047 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11048 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11049 return false; 11050 11051 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11052 // therefore don't strictly fit into a signed bitfield of width 1. 11053 if (FieldWidth == 1 && Value == 1) 11054 return false; 11055 11056 std::string PrettyValue = Value.toString(10); 11057 std::string PrettyTrunc = TruncatedValue.toString(10); 11058 11059 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11060 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11061 << Init->getSourceRange(); 11062 11063 return true; 11064 } 11065 11066 /// Analyze the given simple or compound assignment for warning-worthy 11067 /// operations. 11068 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11069 // Just recurse on the LHS. 11070 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11071 11072 // We want to recurse on the RHS as normal unless we're assigning to 11073 // a bitfield. 11074 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11075 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11076 E->getOperatorLoc())) { 11077 // Recurse, ignoring any implicit conversions on the RHS. 11078 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11079 E->getOperatorLoc()); 11080 } 11081 } 11082 11083 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11084 11085 // Diagnose implicitly sequentially-consistent atomic assignment. 11086 if (E->getLHS()->getType()->isAtomicType()) 11087 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11088 } 11089 11090 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11091 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11092 SourceLocation CContext, unsigned diag, 11093 bool pruneControlFlow = false) { 11094 if (pruneControlFlow) { 11095 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11096 S.PDiag(diag) 11097 << SourceType << T << E->getSourceRange() 11098 << SourceRange(CContext)); 11099 return; 11100 } 11101 S.Diag(E->getExprLoc(), diag) 11102 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11103 } 11104 11105 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11106 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11107 SourceLocation CContext, 11108 unsigned diag, bool pruneControlFlow = false) { 11109 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11110 } 11111 11112 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11113 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11114 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11115 } 11116 11117 static void adornObjCBoolConversionDiagWithTernaryFixit( 11118 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11119 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11120 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11121 Ignored = OVE->getSourceExpr(); 11122 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11123 isa<BinaryOperator>(Ignored) || 11124 isa<CXXOperatorCallExpr>(Ignored); 11125 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11126 if (NeedsParens) 11127 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11128 << FixItHint::CreateInsertion(EndLoc, ")"); 11129 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11130 } 11131 11132 /// Diagnose an implicit cast from a floating point value to an integer value. 11133 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11134 SourceLocation CContext) { 11135 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11136 const bool PruneWarnings = S.inTemplateInstantiation(); 11137 11138 Expr *InnerE = E->IgnoreParenImpCasts(); 11139 // We also want to warn on, e.g., "int i = -1.234" 11140 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11141 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11142 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11143 11144 const bool IsLiteral = 11145 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11146 11147 llvm::APFloat Value(0.0); 11148 bool IsConstant = 11149 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11150 if (!IsConstant) { 11151 if (isObjCSignedCharBool(S, T)) { 11152 return adornObjCBoolConversionDiagWithTernaryFixit( 11153 S, E, 11154 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11155 << E->getType()); 11156 } 11157 11158 return DiagnoseImpCast(S, E, T, CContext, 11159 diag::warn_impcast_float_integer, PruneWarnings); 11160 } 11161 11162 bool isExact = false; 11163 11164 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11165 T->hasUnsignedIntegerRepresentation()); 11166 llvm::APFloat::opStatus Result = Value.convertToInteger( 11167 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11168 11169 // FIXME: Force the precision of the source value down so we don't print 11170 // digits which are usually useless (we don't really care here if we 11171 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11172 // would automatically print the shortest representation, but it's a bit 11173 // tricky to implement. 11174 SmallString<16> PrettySourceValue; 11175 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11176 precision = (precision * 59 + 195) / 196; 11177 Value.toString(PrettySourceValue, precision); 11178 11179 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11180 return adornObjCBoolConversionDiagWithTernaryFixit( 11181 S, E, 11182 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11183 << PrettySourceValue); 11184 } 11185 11186 if (Result == llvm::APFloat::opOK && isExact) { 11187 if (IsLiteral) return; 11188 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11189 PruneWarnings); 11190 } 11191 11192 // Conversion of a floating-point value to a non-bool integer where the 11193 // integral part cannot be represented by the integer type is undefined. 11194 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11195 return DiagnoseImpCast( 11196 S, E, T, CContext, 11197 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11198 : diag::warn_impcast_float_to_integer_out_of_range, 11199 PruneWarnings); 11200 11201 unsigned DiagID = 0; 11202 if (IsLiteral) { 11203 // Warn on floating point literal to integer. 11204 DiagID = diag::warn_impcast_literal_float_to_integer; 11205 } else if (IntegerValue == 0) { 11206 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11207 return DiagnoseImpCast(S, E, T, CContext, 11208 diag::warn_impcast_float_integer, PruneWarnings); 11209 } 11210 // Warn on non-zero to zero conversion. 11211 DiagID = diag::warn_impcast_float_to_integer_zero; 11212 } else { 11213 if (IntegerValue.isUnsigned()) { 11214 if (!IntegerValue.isMaxValue()) { 11215 return DiagnoseImpCast(S, E, T, CContext, 11216 diag::warn_impcast_float_integer, PruneWarnings); 11217 } 11218 } else { // IntegerValue.isSigned() 11219 if (!IntegerValue.isMaxSignedValue() && 11220 !IntegerValue.isMinSignedValue()) { 11221 return DiagnoseImpCast(S, E, T, CContext, 11222 diag::warn_impcast_float_integer, PruneWarnings); 11223 } 11224 } 11225 // Warn on evaluatable floating point expression to integer conversion. 11226 DiagID = diag::warn_impcast_float_to_integer; 11227 } 11228 11229 SmallString<16> PrettyTargetValue; 11230 if (IsBool) 11231 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11232 else 11233 IntegerValue.toString(PrettyTargetValue); 11234 11235 if (PruneWarnings) { 11236 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11237 S.PDiag(DiagID) 11238 << E->getType() << T.getUnqualifiedType() 11239 << PrettySourceValue << PrettyTargetValue 11240 << E->getSourceRange() << SourceRange(CContext)); 11241 } else { 11242 S.Diag(E->getExprLoc(), DiagID) 11243 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11244 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11245 } 11246 } 11247 11248 /// Analyze the given compound assignment for the possible losing of 11249 /// floating-point precision. 11250 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11251 assert(isa<CompoundAssignOperator>(E) && 11252 "Must be compound assignment operation"); 11253 // Recurse on the LHS and RHS in here 11254 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11255 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11256 11257 if (E->getLHS()->getType()->isAtomicType()) 11258 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11259 11260 // Now check the outermost expression 11261 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11262 const auto *RBT = cast<CompoundAssignOperator>(E) 11263 ->getComputationResultType() 11264 ->getAs<BuiltinType>(); 11265 11266 // The below checks assume source is floating point. 11267 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11268 11269 // If source is floating point but target is an integer. 11270 if (ResultBT->isInteger()) 11271 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11272 E->getExprLoc(), diag::warn_impcast_float_integer); 11273 11274 if (!ResultBT->isFloatingPoint()) 11275 return; 11276 11277 // If both source and target are floating points, warn about losing precision. 11278 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11279 QualType(ResultBT, 0), QualType(RBT, 0)); 11280 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11281 // warn about dropping FP rank. 11282 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11283 diag::warn_impcast_float_result_precision); 11284 } 11285 11286 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11287 IntRange Range) { 11288 if (!Range.Width) return "0"; 11289 11290 llvm::APSInt ValueInRange = Value; 11291 ValueInRange.setIsSigned(!Range.NonNegative); 11292 ValueInRange = ValueInRange.trunc(Range.Width); 11293 return ValueInRange.toString(10); 11294 } 11295 11296 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11297 if (!isa<ImplicitCastExpr>(Ex)) 11298 return false; 11299 11300 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11301 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11302 const Type *Source = 11303 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11304 if (Target->isDependentType()) 11305 return false; 11306 11307 const BuiltinType *FloatCandidateBT = 11308 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11309 const Type *BoolCandidateType = ToBool ? Target : Source; 11310 11311 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11312 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11313 } 11314 11315 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11316 SourceLocation CC) { 11317 unsigned NumArgs = TheCall->getNumArgs(); 11318 for (unsigned i = 0; i < NumArgs; ++i) { 11319 Expr *CurrA = TheCall->getArg(i); 11320 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11321 continue; 11322 11323 bool IsSwapped = ((i > 0) && 11324 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11325 IsSwapped |= ((i < (NumArgs - 1)) && 11326 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11327 if (IsSwapped) { 11328 // Warn on this floating-point to bool conversion. 11329 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11330 CurrA->getType(), CC, 11331 diag::warn_impcast_floating_point_to_bool); 11332 } 11333 } 11334 } 11335 11336 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11337 SourceLocation CC) { 11338 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11339 E->getExprLoc())) 11340 return; 11341 11342 // Don't warn on functions which have return type nullptr_t. 11343 if (isa<CallExpr>(E)) 11344 return; 11345 11346 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11347 const Expr::NullPointerConstantKind NullKind = 11348 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11349 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11350 return; 11351 11352 // Return if target type is a safe conversion. 11353 if (T->isAnyPointerType() || T->isBlockPointerType() || 11354 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11355 return; 11356 11357 SourceLocation Loc = E->getSourceRange().getBegin(); 11358 11359 // Venture through the macro stacks to get to the source of macro arguments. 11360 // The new location is a better location than the complete location that was 11361 // passed in. 11362 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11363 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11364 11365 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11366 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11367 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11368 Loc, S.SourceMgr, S.getLangOpts()); 11369 if (MacroName == "NULL") 11370 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11371 } 11372 11373 // Only warn if the null and context location are in the same macro expansion. 11374 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11375 return; 11376 11377 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11378 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11379 << FixItHint::CreateReplacement(Loc, 11380 S.getFixItZeroLiteralForType(T, Loc)); 11381 } 11382 11383 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11384 ObjCArrayLiteral *ArrayLiteral); 11385 11386 static void 11387 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11388 ObjCDictionaryLiteral *DictionaryLiteral); 11389 11390 /// Check a single element within a collection literal against the 11391 /// target element type. 11392 static void checkObjCCollectionLiteralElement(Sema &S, 11393 QualType TargetElementType, 11394 Expr *Element, 11395 unsigned ElementKind) { 11396 // Skip a bitcast to 'id' or qualified 'id'. 11397 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11398 if (ICE->getCastKind() == CK_BitCast && 11399 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11400 Element = ICE->getSubExpr(); 11401 } 11402 11403 QualType ElementType = Element->getType(); 11404 ExprResult ElementResult(Element); 11405 if (ElementType->getAs<ObjCObjectPointerType>() && 11406 S.CheckSingleAssignmentConstraints(TargetElementType, 11407 ElementResult, 11408 false, false) 11409 != Sema::Compatible) { 11410 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11411 << ElementType << ElementKind << TargetElementType 11412 << Element->getSourceRange(); 11413 } 11414 11415 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11416 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11417 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11418 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11419 } 11420 11421 /// Check an Objective-C array literal being converted to the given 11422 /// target type. 11423 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11424 ObjCArrayLiteral *ArrayLiteral) { 11425 if (!S.NSArrayDecl) 11426 return; 11427 11428 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11429 if (!TargetObjCPtr) 11430 return; 11431 11432 if (TargetObjCPtr->isUnspecialized() || 11433 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11434 != S.NSArrayDecl->getCanonicalDecl()) 11435 return; 11436 11437 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11438 if (TypeArgs.size() != 1) 11439 return; 11440 11441 QualType TargetElementType = TypeArgs[0]; 11442 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11443 checkObjCCollectionLiteralElement(S, TargetElementType, 11444 ArrayLiteral->getElement(I), 11445 0); 11446 } 11447 } 11448 11449 /// Check an Objective-C dictionary literal being converted to the given 11450 /// target type. 11451 static void 11452 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11453 ObjCDictionaryLiteral *DictionaryLiteral) { 11454 if (!S.NSDictionaryDecl) 11455 return; 11456 11457 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11458 if (!TargetObjCPtr) 11459 return; 11460 11461 if (TargetObjCPtr->isUnspecialized() || 11462 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11463 != S.NSDictionaryDecl->getCanonicalDecl()) 11464 return; 11465 11466 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11467 if (TypeArgs.size() != 2) 11468 return; 11469 11470 QualType TargetKeyType = TypeArgs[0]; 11471 QualType TargetObjectType = TypeArgs[1]; 11472 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11473 auto Element = DictionaryLiteral->getKeyValueElement(I); 11474 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11475 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11476 } 11477 } 11478 11479 // Helper function to filter out cases for constant width constant conversion. 11480 // Don't warn on char array initialization or for non-decimal values. 11481 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11482 SourceLocation CC) { 11483 // If initializing from a constant, and the constant starts with '0', 11484 // then it is a binary, octal, or hexadecimal. Allow these constants 11485 // to fill all the bits, even if there is a sign change. 11486 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11487 const char FirstLiteralCharacter = 11488 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11489 if (FirstLiteralCharacter == '0') 11490 return false; 11491 } 11492 11493 // If the CC location points to a '{', and the type is char, then assume 11494 // assume it is an array initialization. 11495 if (CC.isValid() && T->isCharType()) { 11496 const char FirstContextCharacter = 11497 S.getSourceManager().getCharacterData(CC)[0]; 11498 if (FirstContextCharacter == '{') 11499 return false; 11500 } 11501 11502 return true; 11503 } 11504 11505 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11506 const auto *IL = dyn_cast<IntegerLiteral>(E); 11507 if (!IL) { 11508 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11509 if (UO->getOpcode() == UO_Minus) 11510 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11511 } 11512 } 11513 11514 return IL; 11515 } 11516 11517 static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc, 11518 Expr *LHS, Expr *RHS) { 11519 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 11520 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 11521 11522 const auto *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 11523 if (!LHSEnumType) 11524 return; 11525 const auto *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 11526 if (!RHSEnumType) 11527 return; 11528 11529 // Ignore anonymous enums. 11530 if (!LHSEnumType->getDecl()->hasNameForLinkage()) 11531 return; 11532 if (!RHSEnumType->getDecl()->hasNameForLinkage()) 11533 return; 11534 11535 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 11536 return; 11537 11538 S.Diag(Loc, diag::warn_conditional_mixed_enum_types) 11539 << LHSStrippedType << RHSStrippedType << LHS->getSourceRange() 11540 << RHS->getSourceRange(); 11541 } 11542 11543 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11544 E = E->IgnoreParenImpCasts(); 11545 SourceLocation ExprLoc = E->getExprLoc(); 11546 11547 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11548 BinaryOperator::Opcode Opc = BO->getOpcode(); 11549 Expr::EvalResult Result; 11550 // Do not diagnose unsigned shifts. 11551 if (Opc == BO_Shl) { 11552 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11553 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11554 if (LHS && LHS->getValue() == 0) 11555 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11556 else if (!E->isValueDependent() && LHS && RHS && 11557 RHS->getValue().isNonNegative() && 11558 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11559 S.Diag(ExprLoc, diag::warn_left_shift_always) 11560 << (Result.Val.getInt() != 0); 11561 else if (E->getType()->isSignedIntegerType()) 11562 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11563 } 11564 } 11565 11566 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11567 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11568 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11569 if (!LHS || !RHS) 11570 return; 11571 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11572 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11573 // Do not diagnose common idioms. 11574 return; 11575 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11576 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11577 } 11578 } 11579 11580 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11581 SourceLocation CC, 11582 bool *ICContext = nullptr, 11583 bool IsListInit = false) { 11584 if (E->isTypeDependent() || E->isValueDependent()) return; 11585 11586 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11587 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11588 if (Source == Target) return; 11589 if (Target->isDependentType()) return; 11590 11591 // If the conversion context location is invalid don't complain. We also 11592 // don't want to emit a warning if the issue occurs from the expansion of 11593 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11594 // delay this check as long as possible. Once we detect we are in that 11595 // scenario, we just return. 11596 if (CC.isInvalid()) 11597 return; 11598 11599 if (Source->isAtomicType()) 11600 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11601 11602 // Diagnose implicit casts to bool. 11603 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11604 if (isa<StringLiteral>(E)) 11605 // Warn on string literal to bool. Checks for string literals in logical 11606 // and expressions, for instance, assert(0 && "error here"), are 11607 // prevented by a check in AnalyzeImplicitConversions(). 11608 return DiagnoseImpCast(S, E, T, CC, 11609 diag::warn_impcast_string_literal_to_bool); 11610 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11611 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11612 // This covers the literal expressions that evaluate to Objective-C 11613 // objects. 11614 return DiagnoseImpCast(S, E, T, CC, 11615 diag::warn_impcast_objective_c_literal_to_bool); 11616 } 11617 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11618 // Warn on pointer to bool conversion that is always true. 11619 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11620 SourceRange(CC)); 11621 } 11622 } 11623 11624 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11625 // is a typedef for signed char (macOS), then that constant value has to be 1 11626 // or 0. 11627 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11628 Expr::EvalResult Result; 11629 if (E->EvaluateAsInt(Result, S.getASTContext(), 11630 Expr::SE_AllowSideEffects)) { 11631 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11632 adornObjCBoolConversionDiagWithTernaryFixit( 11633 S, E, 11634 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11635 << Result.Val.getInt().toString(10)); 11636 } 11637 return; 11638 } 11639 } 11640 11641 // Check implicit casts from Objective-C collection literals to specialized 11642 // collection types, e.g., NSArray<NSString *> *. 11643 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11644 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11645 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11646 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11647 11648 // Strip vector types. 11649 if (isa<VectorType>(Source)) { 11650 if (!isa<VectorType>(Target)) { 11651 if (S.SourceMgr.isInSystemMacro(CC)) 11652 return; 11653 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11654 } 11655 11656 // If the vector cast is cast between two vectors of the same size, it is 11657 // a bitcast, not a conversion. 11658 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11659 return; 11660 11661 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11662 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11663 } 11664 if (auto VecTy = dyn_cast<VectorType>(Target)) 11665 Target = VecTy->getElementType().getTypePtr(); 11666 11667 // Strip complex types. 11668 if (isa<ComplexType>(Source)) { 11669 if (!isa<ComplexType>(Target)) { 11670 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11671 return; 11672 11673 return DiagnoseImpCast(S, E, T, CC, 11674 S.getLangOpts().CPlusPlus 11675 ? diag::err_impcast_complex_scalar 11676 : diag::warn_impcast_complex_scalar); 11677 } 11678 11679 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11680 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11681 } 11682 11683 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11684 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11685 11686 // If the source is floating point... 11687 if (SourceBT && SourceBT->isFloatingPoint()) { 11688 // ...and the target is floating point... 11689 if (TargetBT && TargetBT->isFloatingPoint()) { 11690 // ...then warn if we're dropping FP rank. 11691 11692 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11693 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11694 if (Order > 0) { 11695 // Don't warn about float constants that are precisely 11696 // representable in the target type. 11697 Expr::EvalResult result; 11698 if (E->EvaluateAsRValue(result, S.Context)) { 11699 // Value might be a float, a float vector, or a float complex. 11700 if (IsSameFloatAfterCast(result.Val, 11701 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11702 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11703 return; 11704 } 11705 11706 if (S.SourceMgr.isInSystemMacro(CC)) 11707 return; 11708 11709 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11710 } 11711 // ... or possibly if we're increasing rank, too 11712 else if (Order < 0) { 11713 if (S.SourceMgr.isInSystemMacro(CC)) 11714 return; 11715 11716 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11717 } 11718 return; 11719 } 11720 11721 // If the target is integral, always warn. 11722 if (TargetBT && TargetBT->isInteger()) { 11723 if (S.SourceMgr.isInSystemMacro(CC)) 11724 return; 11725 11726 DiagnoseFloatingImpCast(S, E, T, CC); 11727 } 11728 11729 // Detect the case where a call result is converted from floating-point to 11730 // to bool, and the final argument to the call is converted from bool, to 11731 // discover this typo: 11732 // 11733 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11734 // 11735 // FIXME: This is an incredibly special case; is there some more general 11736 // way to detect this class of misplaced-parentheses bug? 11737 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11738 // Check last argument of function call to see if it is an 11739 // implicit cast from a type matching the type the result 11740 // is being cast to. 11741 CallExpr *CEx = cast<CallExpr>(E); 11742 if (unsigned NumArgs = CEx->getNumArgs()) { 11743 Expr *LastA = CEx->getArg(NumArgs - 1); 11744 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11745 if (isa<ImplicitCastExpr>(LastA) && 11746 InnerE->getType()->isBooleanType()) { 11747 // Warn on this floating-point to bool conversion 11748 DiagnoseImpCast(S, E, T, CC, 11749 diag::warn_impcast_floating_point_to_bool); 11750 } 11751 } 11752 } 11753 return; 11754 } 11755 11756 // Valid casts involving fixed point types should be accounted for here. 11757 if (Source->isFixedPointType()) { 11758 if (Target->isUnsaturatedFixedPointType()) { 11759 Expr::EvalResult Result; 11760 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11761 S.isConstantEvaluated())) { 11762 APFixedPoint Value = Result.Val.getFixedPoint(); 11763 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11764 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11765 if (Value > MaxVal || Value < MinVal) { 11766 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11767 S.PDiag(diag::warn_impcast_fixed_point_range) 11768 << Value.toString() << T 11769 << E->getSourceRange() 11770 << clang::SourceRange(CC)); 11771 return; 11772 } 11773 } 11774 } else if (Target->isIntegerType()) { 11775 Expr::EvalResult Result; 11776 if (!S.isConstantEvaluated() && 11777 E->EvaluateAsFixedPoint(Result, S.Context, 11778 Expr::SE_AllowSideEffects)) { 11779 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11780 11781 bool Overflowed; 11782 llvm::APSInt IntResult = FXResult.convertToInt( 11783 S.Context.getIntWidth(T), 11784 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11785 11786 if (Overflowed) { 11787 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11788 S.PDiag(diag::warn_impcast_fixed_point_range) 11789 << FXResult.toString() << T 11790 << E->getSourceRange() 11791 << clang::SourceRange(CC)); 11792 return; 11793 } 11794 } 11795 } 11796 } else if (Target->isUnsaturatedFixedPointType()) { 11797 if (Source->isIntegerType()) { 11798 Expr::EvalResult Result; 11799 if (!S.isConstantEvaluated() && 11800 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11801 llvm::APSInt Value = Result.Val.getInt(); 11802 11803 bool Overflowed; 11804 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11805 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11806 11807 if (Overflowed) { 11808 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11809 S.PDiag(diag::warn_impcast_fixed_point_range) 11810 << Value.toString(/*Radix=*/10) << T 11811 << E->getSourceRange() 11812 << clang::SourceRange(CC)); 11813 return; 11814 } 11815 } 11816 } 11817 } 11818 11819 // If we are casting an integer type to a floating point type without 11820 // initialization-list syntax, we might lose accuracy if the floating 11821 // point type has a narrower significand than the integer type. 11822 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11823 TargetBT->isFloatingType() && !IsListInit) { 11824 // Determine the number of precision bits in the source integer type. 11825 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11826 unsigned int SourcePrecision = SourceRange.Width; 11827 11828 // Determine the number of precision bits in the 11829 // target floating point type. 11830 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11831 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11832 11833 if (SourcePrecision > 0 && TargetPrecision > 0 && 11834 SourcePrecision > TargetPrecision) { 11835 11836 llvm::APSInt SourceInt; 11837 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11838 // If the source integer is a constant, convert it to the target 11839 // floating point type. Issue a warning if the value changes 11840 // during the whole conversion. 11841 llvm::APFloat TargetFloatValue( 11842 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11843 llvm::APFloat::opStatus ConversionStatus = 11844 TargetFloatValue.convertFromAPInt( 11845 SourceInt, SourceBT->isSignedInteger(), 11846 llvm::APFloat::rmNearestTiesToEven); 11847 11848 if (ConversionStatus != llvm::APFloat::opOK) { 11849 std::string PrettySourceValue = SourceInt.toString(10); 11850 SmallString<32> PrettyTargetValue; 11851 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11852 11853 S.DiagRuntimeBehavior( 11854 E->getExprLoc(), E, 11855 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11856 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11857 << E->getSourceRange() << clang::SourceRange(CC)); 11858 } 11859 } else { 11860 // Otherwise, the implicit conversion may lose precision. 11861 DiagnoseImpCast(S, E, T, CC, 11862 diag::warn_impcast_integer_float_precision); 11863 } 11864 } 11865 } 11866 11867 DiagnoseNullConversion(S, E, T, CC); 11868 11869 S.DiscardMisalignedMemberAddress(Target, E); 11870 11871 if (Target->isBooleanType()) 11872 DiagnoseIntInBoolContext(S, E); 11873 11874 if (!Source->isIntegerType() || !Target->isIntegerType()) 11875 return; 11876 11877 // TODO: remove this early return once the false positives for constant->bool 11878 // in templates, macros, etc, are reduced or removed. 11879 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11880 return; 11881 11882 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11883 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11884 return adornObjCBoolConversionDiagWithTernaryFixit( 11885 S, E, 11886 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11887 << E->getType()); 11888 } 11889 11890 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11891 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11892 11893 if (SourceRange.Width > TargetRange.Width) { 11894 // If the source is a constant, use a default-on diagnostic. 11895 // TODO: this should happen for bitfield stores, too. 11896 Expr::EvalResult Result; 11897 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11898 S.isConstantEvaluated())) { 11899 llvm::APSInt Value(32); 11900 Value = Result.Val.getInt(); 11901 11902 if (S.SourceMgr.isInSystemMacro(CC)) 11903 return; 11904 11905 std::string PrettySourceValue = Value.toString(10); 11906 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11907 11908 S.DiagRuntimeBehavior( 11909 E->getExprLoc(), E, 11910 S.PDiag(diag::warn_impcast_integer_precision_constant) 11911 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11912 << E->getSourceRange() << clang::SourceRange(CC)); 11913 return; 11914 } 11915 11916 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11917 if (S.SourceMgr.isInSystemMacro(CC)) 11918 return; 11919 11920 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11921 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11922 /* pruneControlFlow */ true); 11923 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11924 } 11925 11926 if (TargetRange.Width > SourceRange.Width) { 11927 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11928 if (UO->getOpcode() == UO_Minus) 11929 if (Source->isUnsignedIntegerType()) { 11930 if (Target->isUnsignedIntegerType()) 11931 return DiagnoseImpCast(S, E, T, CC, 11932 diag::warn_impcast_high_order_zero_bits); 11933 if (Target->isSignedIntegerType()) 11934 return DiagnoseImpCast(S, E, T, CC, 11935 diag::warn_impcast_nonnegative_result); 11936 } 11937 } 11938 11939 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11940 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11941 // Warn when doing a signed to signed conversion, warn if the positive 11942 // source value is exactly the width of the target type, which will 11943 // cause a negative value to be stored. 11944 11945 Expr::EvalResult Result; 11946 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11947 !S.SourceMgr.isInSystemMacro(CC)) { 11948 llvm::APSInt Value = Result.Val.getInt(); 11949 if (isSameWidthConstantConversion(S, E, T, CC)) { 11950 std::string PrettySourceValue = Value.toString(10); 11951 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11952 11953 S.DiagRuntimeBehavior( 11954 E->getExprLoc(), E, 11955 S.PDiag(diag::warn_impcast_integer_precision_constant) 11956 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11957 << E->getSourceRange() << clang::SourceRange(CC)); 11958 return; 11959 } 11960 } 11961 11962 // Fall through for non-constants to give a sign conversion warning. 11963 } 11964 11965 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11966 (!TargetRange.NonNegative && SourceRange.NonNegative && 11967 SourceRange.Width == TargetRange.Width)) { 11968 if (S.SourceMgr.isInSystemMacro(CC)) 11969 return; 11970 11971 unsigned DiagID = diag::warn_impcast_integer_sign; 11972 11973 // Traditionally, gcc has warned about this under -Wsign-compare. 11974 // We also want to warn about it in -Wconversion. 11975 // So if -Wconversion is off, use a completely identical diagnostic 11976 // in the sign-compare group. 11977 // The conditional-checking code will 11978 if (ICContext) { 11979 DiagID = diag::warn_impcast_integer_sign_conditional; 11980 *ICContext = true; 11981 } 11982 11983 return DiagnoseImpCast(S, E, T, CC, DiagID); 11984 } 11985 11986 // Diagnose conversions between different enumeration types. 11987 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11988 // type, to give us better diagnostics. 11989 QualType SourceType = E->getType(); 11990 if (!S.getLangOpts().CPlusPlus) { 11991 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11992 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11993 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11994 SourceType = S.Context.getTypeDeclType(Enum); 11995 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11996 } 11997 } 11998 11999 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12000 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12001 if (SourceEnum->getDecl()->hasNameForLinkage() && 12002 TargetEnum->getDecl()->hasNameForLinkage() && 12003 SourceEnum != TargetEnum) { 12004 if (S.SourceMgr.isInSystemMacro(CC)) 12005 return; 12006 12007 return DiagnoseImpCast(S, E, SourceType, T, CC, 12008 diag::warn_impcast_different_enum_types); 12009 } 12010 } 12011 12012 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 12013 SourceLocation CC, QualType T); 12014 12015 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12016 SourceLocation CC, bool &ICContext) { 12017 E = E->IgnoreParenImpCasts(); 12018 12019 if (isa<ConditionalOperator>(E)) 12020 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 12021 12022 AnalyzeImplicitConversions(S, E, CC); 12023 if (E->getType() != T) 12024 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12025 } 12026 12027 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 12028 SourceLocation CC, QualType T) { 12029 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12030 12031 bool Suspicious = false; 12032 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 12033 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12034 CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(), 12035 E->getFalseExpr()); 12036 12037 if (T->isBooleanType()) 12038 DiagnoseIntInBoolContext(S, E); 12039 12040 // If -Wconversion would have warned about either of the candidates 12041 // for a signedness conversion to the context type... 12042 if (!Suspicious) return; 12043 12044 // ...but it's currently ignored... 12045 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12046 return; 12047 12048 // ...then check whether it would have warned about either of the 12049 // candidates for a signedness conversion to the condition type. 12050 if (E->getType() == T) return; 12051 12052 Suspicious = false; 12053 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 12054 E->getType(), CC, &Suspicious); 12055 if (!Suspicious) 12056 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12057 E->getType(), CC, &Suspicious); 12058 } 12059 12060 /// Check conversion of given expression to boolean. 12061 /// Input argument E is a logical expression. 12062 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12063 if (S.getLangOpts().Bool) 12064 return; 12065 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12066 return; 12067 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12068 } 12069 12070 /// AnalyzeImplicitConversions - Find and report any interesting 12071 /// implicit conversions in the given expression. There are a couple 12072 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12073 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12074 bool IsListInit/*= false*/) { 12075 QualType T = OrigE->getType(); 12076 Expr *E = OrigE->IgnoreParenImpCasts(); 12077 12078 // Propagate whether we are in a C++ list initialization expression. 12079 // If so, we do not issue warnings for implicit int-float conversion 12080 // precision loss, because C++11 narrowing already handles it. 12081 IsListInit = 12082 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12083 12084 if (E->isTypeDependent() || E->isValueDependent()) 12085 return; 12086 12087 if (const auto *UO = dyn_cast<UnaryOperator>(E)) 12088 if (UO->getOpcode() == UO_Not && 12089 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12090 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12091 << OrigE->getSourceRange() << T->isBooleanType() 12092 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12093 12094 // For conditional operators, we analyze the arguments as if they 12095 // were being fed directly into the output. 12096 if (isa<ConditionalOperator>(E)) { 12097 ConditionalOperator *CO = cast<ConditionalOperator>(E); 12098 CheckConditionalOperator(S, CO, CC, T); 12099 return; 12100 } 12101 12102 // Check implicit argument conversions for function calls. 12103 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 12104 CheckImplicitArgumentConversions(S, Call, CC); 12105 12106 // Go ahead and check any implicit conversions we might have skipped. 12107 // The non-canonical typecheck is just an optimization; 12108 // CheckImplicitConversion will filter out dead implicit conversions. 12109 if (E->getType() != T) 12110 CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit); 12111 12112 // Now continue drilling into this expression. 12113 12114 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12115 // The bound subexpressions in a PseudoObjectExpr are not reachable 12116 // as transitive children. 12117 // FIXME: Use a more uniform representation for this. 12118 for (auto *SE : POE->semantics()) 12119 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12120 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit); 12121 } 12122 12123 // Skip past explicit casts. 12124 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12125 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12126 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12127 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12128 return AnalyzeImplicitConversions(S, E, CC, IsListInit); 12129 } 12130 12131 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12132 // Do a somewhat different check with comparison operators. 12133 if (BO->isComparisonOp()) 12134 return AnalyzeComparison(S, BO); 12135 12136 // And with simple assignments. 12137 if (BO->getOpcode() == BO_Assign) 12138 return AnalyzeAssignment(S, BO); 12139 // And with compound assignments. 12140 if (BO->isAssignmentOp()) 12141 return AnalyzeCompoundAssignment(S, BO); 12142 } 12143 12144 // These break the otherwise-useful invariant below. Fortunately, 12145 // we don't really need to recurse into them, because any internal 12146 // expressions should have been analyzed already when they were 12147 // built into statements. 12148 if (isa<StmtExpr>(E)) return; 12149 12150 // Don't descend into unevaluated contexts. 12151 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12152 12153 // Now just recurse over the expression's children. 12154 CC = E->getExprLoc(); 12155 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12156 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12157 for (Stmt *SubStmt : E->children()) { 12158 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12159 if (!ChildExpr) 12160 continue; 12161 12162 if (IsLogicalAndOperator && 12163 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12164 // Ignore checking string literals that are in logical and operators. 12165 // This is a common pattern for asserts. 12166 continue; 12167 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit); 12168 } 12169 12170 if (BO && BO->isLogicalOp()) { 12171 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12172 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12173 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12174 12175 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12176 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12177 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12178 } 12179 12180 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12181 if (U->getOpcode() == UO_LNot) { 12182 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12183 } else if (U->getOpcode() != UO_AddrOf) { 12184 if (U->getSubExpr()->getType()->isAtomicType()) 12185 S.Diag(U->getSubExpr()->getBeginLoc(), 12186 diag::warn_atomic_implicit_seq_cst); 12187 } 12188 } 12189 } 12190 12191 /// Diagnose integer type and any valid implicit conversion to it. 12192 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12193 // Taking into account implicit conversions, 12194 // allow any integer. 12195 if (!E->getType()->isIntegerType()) { 12196 S.Diag(E->getBeginLoc(), 12197 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12198 return true; 12199 } 12200 // Potentially emit standard warnings for implicit conversions if enabled 12201 // using -Wconversion. 12202 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12203 return false; 12204 } 12205 12206 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12207 // Returns true when emitting a warning about taking the address of a reference. 12208 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12209 const PartialDiagnostic &PD) { 12210 E = E->IgnoreParenImpCasts(); 12211 12212 const FunctionDecl *FD = nullptr; 12213 12214 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12215 if (!DRE->getDecl()->getType()->isReferenceType()) 12216 return false; 12217 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12218 if (!M->getMemberDecl()->getType()->isReferenceType()) 12219 return false; 12220 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12221 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12222 return false; 12223 FD = Call->getDirectCallee(); 12224 } else { 12225 return false; 12226 } 12227 12228 SemaRef.Diag(E->getExprLoc(), PD); 12229 12230 // If possible, point to location of function. 12231 if (FD) { 12232 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12233 } 12234 12235 return true; 12236 } 12237 12238 // Returns true if the SourceLocation is expanded from any macro body. 12239 // Returns false if the SourceLocation is invalid, is from not in a macro 12240 // expansion, or is from expanded from a top-level macro argument. 12241 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12242 if (Loc.isInvalid()) 12243 return false; 12244 12245 while (Loc.isMacroID()) { 12246 if (SM.isMacroBodyExpansion(Loc)) 12247 return true; 12248 Loc = SM.getImmediateMacroCallerLoc(Loc); 12249 } 12250 12251 return false; 12252 } 12253 12254 /// Diagnose pointers that are always non-null. 12255 /// \param E the expression containing the pointer 12256 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12257 /// compared to a null pointer 12258 /// \param IsEqual True when the comparison is equal to a null pointer 12259 /// \param Range Extra SourceRange to highlight in the diagnostic 12260 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12261 Expr::NullPointerConstantKind NullKind, 12262 bool IsEqual, SourceRange Range) { 12263 if (!E) 12264 return; 12265 12266 // Don't warn inside macros. 12267 if (E->getExprLoc().isMacroID()) { 12268 const SourceManager &SM = getSourceManager(); 12269 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12270 IsInAnyMacroBody(SM, Range.getBegin())) 12271 return; 12272 } 12273 E = E->IgnoreImpCasts(); 12274 12275 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12276 12277 if (isa<CXXThisExpr>(E)) { 12278 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12279 : diag::warn_this_bool_conversion; 12280 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12281 return; 12282 } 12283 12284 bool IsAddressOf = false; 12285 12286 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12287 if (UO->getOpcode() != UO_AddrOf) 12288 return; 12289 IsAddressOf = true; 12290 E = UO->getSubExpr(); 12291 } 12292 12293 if (IsAddressOf) { 12294 unsigned DiagID = IsCompare 12295 ? diag::warn_address_of_reference_null_compare 12296 : diag::warn_address_of_reference_bool_conversion; 12297 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12298 << IsEqual; 12299 if (CheckForReference(*this, E, PD)) { 12300 return; 12301 } 12302 } 12303 12304 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12305 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12306 std::string Str; 12307 llvm::raw_string_ostream S(Str); 12308 E->printPretty(S, nullptr, getPrintingPolicy()); 12309 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12310 : diag::warn_cast_nonnull_to_bool; 12311 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12312 << E->getSourceRange() << Range << IsEqual; 12313 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12314 }; 12315 12316 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12317 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12318 if (auto *Callee = Call->getDirectCallee()) { 12319 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12320 ComplainAboutNonnullParamOrCall(A); 12321 return; 12322 } 12323 } 12324 } 12325 12326 // Expect to find a single Decl. Skip anything more complicated. 12327 ValueDecl *D = nullptr; 12328 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12329 D = R->getDecl(); 12330 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12331 D = M->getMemberDecl(); 12332 } 12333 12334 // Weak Decls can be null. 12335 if (!D || D->isWeak()) 12336 return; 12337 12338 // Check for parameter decl with nonnull attribute 12339 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12340 if (getCurFunction() && 12341 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12342 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12343 ComplainAboutNonnullParamOrCall(A); 12344 return; 12345 } 12346 12347 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12348 // Skip function template not specialized yet. 12349 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12350 return; 12351 auto ParamIter = llvm::find(FD->parameters(), PV); 12352 assert(ParamIter != FD->param_end()); 12353 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12354 12355 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12356 if (!NonNull->args_size()) { 12357 ComplainAboutNonnullParamOrCall(NonNull); 12358 return; 12359 } 12360 12361 for (const ParamIdx &ArgNo : NonNull->args()) { 12362 if (ArgNo.getASTIndex() == ParamNo) { 12363 ComplainAboutNonnullParamOrCall(NonNull); 12364 return; 12365 } 12366 } 12367 } 12368 } 12369 } 12370 } 12371 12372 QualType T = D->getType(); 12373 const bool IsArray = T->isArrayType(); 12374 const bool IsFunction = T->isFunctionType(); 12375 12376 // Address of function is used to silence the function warning. 12377 if (IsAddressOf && IsFunction) { 12378 return; 12379 } 12380 12381 // Found nothing. 12382 if (!IsAddressOf && !IsFunction && !IsArray) 12383 return; 12384 12385 // Pretty print the expression for the diagnostic. 12386 std::string Str; 12387 llvm::raw_string_ostream S(Str); 12388 E->printPretty(S, nullptr, getPrintingPolicy()); 12389 12390 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12391 : diag::warn_impcast_pointer_to_bool; 12392 enum { 12393 AddressOf, 12394 FunctionPointer, 12395 ArrayPointer 12396 } DiagType; 12397 if (IsAddressOf) 12398 DiagType = AddressOf; 12399 else if (IsFunction) 12400 DiagType = FunctionPointer; 12401 else if (IsArray) 12402 DiagType = ArrayPointer; 12403 else 12404 llvm_unreachable("Could not determine diagnostic."); 12405 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12406 << Range << IsEqual; 12407 12408 if (!IsFunction) 12409 return; 12410 12411 // Suggest '&' to silence the function warning. 12412 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12413 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12414 12415 // Check to see if '()' fixit should be emitted. 12416 QualType ReturnType; 12417 UnresolvedSet<4> NonTemplateOverloads; 12418 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12419 if (ReturnType.isNull()) 12420 return; 12421 12422 if (IsCompare) { 12423 // There are two cases here. If there is null constant, the only suggest 12424 // for a pointer return type. If the null is 0, then suggest if the return 12425 // type is a pointer or an integer type. 12426 if (!ReturnType->isPointerType()) { 12427 if (NullKind == Expr::NPCK_ZeroExpression || 12428 NullKind == Expr::NPCK_ZeroLiteral) { 12429 if (!ReturnType->isIntegerType()) 12430 return; 12431 } else { 12432 return; 12433 } 12434 } 12435 } else { // !IsCompare 12436 // For function to bool, only suggest if the function pointer has bool 12437 // return type. 12438 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12439 return; 12440 } 12441 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12442 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12443 } 12444 12445 /// Diagnoses "dangerous" implicit conversions within the given 12446 /// expression (which is a full expression). Implements -Wconversion 12447 /// and -Wsign-compare. 12448 /// 12449 /// \param CC the "context" location of the implicit conversion, i.e. 12450 /// the most location of the syntactic entity requiring the implicit 12451 /// conversion 12452 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12453 // Don't diagnose in unevaluated contexts. 12454 if (isUnevaluatedContext()) 12455 return; 12456 12457 // Don't diagnose for value- or type-dependent expressions. 12458 if (E->isTypeDependent() || E->isValueDependent()) 12459 return; 12460 12461 // Check for array bounds violations in cases where the check isn't triggered 12462 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12463 // ArraySubscriptExpr is on the RHS of a variable initialization. 12464 CheckArrayAccess(E); 12465 12466 // This is not the right CC for (e.g.) a variable initialization. 12467 AnalyzeImplicitConversions(*this, E, CC); 12468 } 12469 12470 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12471 /// Input argument E is a logical expression. 12472 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12473 ::CheckBoolLikeConversion(*this, E, CC); 12474 } 12475 12476 /// Diagnose when expression is an integer constant expression and its evaluation 12477 /// results in integer overflow 12478 void Sema::CheckForIntOverflow (Expr *E) { 12479 // Use a work list to deal with nested struct initializers. 12480 SmallVector<Expr *, 2> Exprs(1, E); 12481 12482 do { 12483 Expr *OriginalE = Exprs.pop_back_val(); 12484 Expr *E = OriginalE->IgnoreParenCasts(); 12485 12486 if (isa<BinaryOperator>(E)) { 12487 E->EvaluateForOverflow(Context); 12488 continue; 12489 } 12490 12491 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12492 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12493 else if (isa<ObjCBoxedExpr>(OriginalE)) 12494 E->EvaluateForOverflow(Context); 12495 else if (auto Call = dyn_cast<CallExpr>(E)) 12496 Exprs.append(Call->arg_begin(), Call->arg_end()); 12497 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12498 Exprs.append(Message->arg_begin(), Message->arg_end()); 12499 } while (!Exprs.empty()); 12500 } 12501 12502 namespace { 12503 12504 /// Visitor for expressions which looks for unsequenced operations on the 12505 /// same object. 12506 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 12507 using Base = EvaluatedExprVisitor<SequenceChecker>; 12508 12509 /// A tree of sequenced regions within an expression. Two regions are 12510 /// unsequenced if one is an ancestor or a descendent of the other. When we 12511 /// finish processing an expression with sequencing, such as a comma 12512 /// expression, we fold its tree nodes into its parent, since they are 12513 /// unsequenced with respect to nodes we will visit later. 12514 class SequenceTree { 12515 struct Value { 12516 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12517 unsigned Parent : 31; 12518 unsigned Merged : 1; 12519 }; 12520 SmallVector<Value, 8> Values; 12521 12522 public: 12523 /// A region within an expression which may be sequenced with respect 12524 /// to some other region. 12525 class Seq { 12526 friend class SequenceTree; 12527 12528 unsigned Index; 12529 12530 explicit Seq(unsigned N) : Index(N) {} 12531 12532 public: 12533 Seq() : Index(0) {} 12534 }; 12535 12536 SequenceTree() { Values.push_back(Value(0)); } 12537 Seq root() const { return Seq(0); } 12538 12539 /// Create a new sequence of operations, which is an unsequenced 12540 /// subset of \p Parent. This sequence of operations is sequenced with 12541 /// respect to other children of \p Parent. 12542 Seq allocate(Seq Parent) { 12543 Values.push_back(Value(Parent.Index)); 12544 return Seq(Values.size() - 1); 12545 } 12546 12547 /// Merge a sequence of operations into its parent. 12548 void merge(Seq S) { 12549 Values[S.Index].Merged = true; 12550 } 12551 12552 /// Determine whether two operations are unsequenced. This operation 12553 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12554 /// should have been merged into its parent as appropriate. 12555 bool isUnsequenced(Seq Cur, Seq Old) { 12556 unsigned C = representative(Cur.Index); 12557 unsigned Target = representative(Old.Index); 12558 while (C >= Target) { 12559 if (C == Target) 12560 return true; 12561 C = Values[C].Parent; 12562 } 12563 return false; 12564 } 12565 12566 private: 12567 /// Pick a representative for a sequence. 12568 unsigned representative(unsigned K) { 12569 if (Values[K].Merged) 12570 // Perform path compression as we go. 12571 return Values[K].Parent = representative(Values[K].Parent); 12572 return K; 12573 } 12574 }; 12575 12576 /// An object for which we can track unsequenced uses. 12577 using Object = NamedDecl *; 12578 12579 /// Different flavors of object usage which we track. We only track the 12580 /// least-sequenced usage of each kind. 12581 enum UsageKind { 12582 /// A read of an object. Multiple unsequenced reads are OK. 12583 UK_Use, 12584 12585 /// A modification of an object which is sequenced before the value 12586 /// computation of the expression, such as ++n in C++. 12587 UK_ModAsValue, 12588 12589 /// A modification of an object which is not sequenced before the value 12590 /// computation of the expression, such as n++. 12591 UK_ModAsSideEffect, 12592 12593 UK_Count = UK_ModAsSideEffect + 1 12594 }; 12595 12596 struct Usage { 12597 Expr *Use; 12598 SequenceTree::Seq Seq; 12599 12600 Usage() : Use(nullptr), Seq() {} 12601 }; 12602 12603 struct UsageInfo { 12604 Usage Uses[UK_Count]; 12605 12606 /// Have we issued a diagnostic for this variable already? 12607 bool Diagnosed; 12608 12609 UsageInfo() : Uses(), Diagnosed(false) {} 12610 }; 12611 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12612 12613 Sema &SemaRef; 12614 12615 /// Sequenced regions within the expression. 12616 SequenceTree Tree; 12617 12618 /// Declaration modifications and references which we have seen. 12619 UsageInfoMap UsageMap; 12620 12621 /// The region we are currently within. 12622 SequenceTree::Seq Region; 12623 12624 /// Filled in with declarations which were modified as a side-effect 12625 /// (that is, post-increment operations). 12626 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12627 12628 /// Expressions to check later. We defer checking these to reduce 12629 /// stack usage. 12630 SmallVectorImpl<Expr *> &WorkList; 12631 12632 /// RAII object wrapping the visitation of a sequenced subexpression of an 12633 /// expression. At the end of this process, the side-effects of the evaluation 12634 /// become sequenced with respect to the value computation of the result, so 12635 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12636 /// UK_ModAsValue. 12637 struct SequencedSubexpression { 12638 SequencedSubexpression(SequenceChecker &Self) 12639 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12640 Self.ModAsSideEffect = &ModAsSideEffect; 12641 } 12642 12643 ~SequencedSubexpression() { 12644 for (auto &M : llvm::reverse(ModAsSideEffect)) { 12645 UsageInfo &U = Self.UsageMap[M.first]; 12646 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 12647 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 12648 SideEffectUsage = M.second; 12649 } 12650 Self.ModAsSideEffect = OldModAsSideEffect; 12651 } 12652 12653 SequenceChecker &Self; 12654 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12655 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12656 }; 12657 12658 /// RAII object wrapping the visitation of a subexpression which we might 12659 /// choose to evaluate as a constant. If any subexpression is evaluated and 12660 /// found to be non-constant, this allows us to suppress the evaluation of 12661 /// the outer expression. 12662 class EvaluationTracker { 12663 public: 12664 EvaluationTracker(SequenceChecker &Self) 12665 : Self(Self), Prev(Self.EvalTracker) { 12666 Self.EvalTracker = this; 12667 } 12668 12669 ~EvaluationTracker() { 12670 Self.EvalTracker = Prev; 12671 if (Prev) 12672 Prev->EvalOK &= EvalOK; 12673 } 12674 12675 bool evaluate(const Expr *E, bool &Result) { 12676 if (!EvalOK || E->isValueDependent()) 12677 return false; 12678 EvalOK = E->EvaluateAsBooleanCondition( 12679 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12680 return EvalOK; 12681 } 12682 12683 private: 12684 SequenceChecker &Self; 12685 EvaluationTracker *Prev; 12686 bool EvalOK = true; 12687 } *EvalTracker = nullptr; 12688 12689 /// Find the object which is produced by the specified expression, 12690 /// if any. 12691 Object getObject(Expr *E, bool Mod) const { 12692 E = E->IgnoreParenCasts(); 12693 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12694 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12695 return getObject(UO->getSubExpr(), Mod); 12696 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12697 if (BO->getOpcode() == BO_Comma) 12698 return getObject(BO->getRHS(), Mod); 12699 if (Mod && BO->isAssignmentOp()) 12700 return getObject(BO->getLHS(), Mod); 12701 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12702 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12703 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12704 return ME->getMemberDecl(); 12705 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12706 // FIXME: If this is a reference, map through to its value. 12707 return DRE->getDecl(); 12708 return nullptr; 12709 } 12710 12711 /// Note that an object was modified or used by an expression. 12712 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 12713 Usage &U = UI.Uses[UK]; 12714 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 12715 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12716 ModAsSideEffect->push_back(std::make_pair(O, U)); 12717 U.Use = Ref; 12718 U.Seq = Region; 12719 } 12720 } 12721 12722 /// Check whether a modification or use conflicts with a prior usage. 12723 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 12724 bool IsModMod) { 12725 if (UI.Diagnosed) 12726 return; 12727 12728 const Usage &U = UI.Uses[OtherKind]; 12729 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 12730 return; 12731 12732 Expr *Mod = U.Use; 12733 Expr *ModOrUse = Ref; 12734 if (OtherKind == UK_Use) 12735 std::swap(Mod, ModOrUse); 12736 12737 SemaRef.DiagRuntimeBehavior( 12738 Mod->getExprLoc(), {Mod, ModOrUse}, 12739 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12740 : diag::warn_unsequenced_mod_use) 12741 << O << SourceRange(ModOrUse->getExprLoc())); 12742 UI.Diagnosed = true; 12743 } 12744 12745 void notePreUse(Object O, Expr *Use) { 12746 UsageInfo &U = UsageMap[O]; 12747 // Uses conflict with other modifications. 12748 checkUsage(O, U, Use, UK_ModAsValue, false); 12749 } 12750 12751 void notePostUse(Object O, Expr *Use) { 12752 UsageInfo &U = UsageMap[O]; 12753 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 12754 addUsage(U, O, Use, UK_Use); 12755 } 12756 12757 void notePreMod(Object O, Expr *Mod) { 12758 UsageInfo &U = UsageMap[O]; 12759 // Modifications conflict with other modifications and with uses. 12760 checkUsage(O, U, Mod, UK_ModAsValue, true); 12761 checkUsage(O, U, Mod, UK_Use, false); 12762 } 12763 12764 void notePostMod(Object O, Expr *Use, UsageKind UK) { 12765 UsageInfo &U = UsageMap[O]; 12766 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 12767 addUsage(U, O, Use, UK); 12768 } 12769 12770 public: 12771 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 12772 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12773 Visit(E); 12774 } 12775 12776 void VisitStmt(Stmt *S) { 12777 // Skip all statements which aren't expressions for now. 12778 } 12779 12780 void VisitExpr(Expr *E) { 12781 // By default, just recurse to evaluated subexpressions. 12782 Base::VisitStmt(E); 12783 } 12784 12785 void VisitCastExpr(CastExpr *E) { 12786 Object O = Object(); 12787 if (E->getCastKind() == CK_LValueToRValue) 12788 O = getObject(E->getSubExpr(), false); 12789 12790 if (O) 12791 notePreUse(O, E); 12792 VisitExpr(E); 12793 if (O) 12794 notePostUse(O, E); 12795 } 12796 12797 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) { 12798 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12799 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12800 SequenceTree::Seq OldRegion = Region; 12801 12802 { 12803 SequencedSubexpression SeqBefore(*this); 12804 Region = BeforeRegion; 12805 Visit(SequencedBefore); 12806 } 12807 12808 Region = AfterRegion; 12809 Visit(SequencedAfter); 12810 12811 Region = OldRegion; 12812 12813 Tree.merge(BeforeRegion); 12814 Tree.merge(AfterRegion); 12815 } 12816 12817 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) { 12818 // C++17 [expr.sub]p1: 12819 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12820 // expression E1 is sequenced before the expression E2. 12821 if (SemaRef.getLangOpts().CPlusPlus17) 12822 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12823 else 12824 Base::VisitStmt(ASE); 12825 } 12826 12827 void VisitBinComma(BinaryOperator *BO) { 12828 // C++11 [expr.comma]p1: 12829 // Every value computation and side effect associated with the left 12830 // expression is sequenced before every value computation and side 12831 // effect associated with the right expression. 12832 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12833 } 12834 12835 void VisitBinAssign(BinaryOperator *BO) { 12836 // The modification is sequenced after the value computation of the LHS 12837 // and RHS, so check it before inspecting the operands and update the 12838 // map afterwards. 12839 Object O = getObject(BO->getLHS(), true); 12840 if (!O) 12841 return VisitExpr(BO); 12842 12843 notePreMod(O, BO); 12844 12845 // C++11 [expr.ass]p7: 12846 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 12847 // only once. 12848 // 12849 // Therefore, for a compound assignment operator, O is considered used 12850 // everywhere except within the evaluation of E1 itself. 12851 if (isa<CompoundAssignOperator>(BO)) 12852 notePreUse(O, BO); 12853 12854 Visit(BO->getLHS()); 12855 12856 if (isa<CompoundAssignOperator>(BO)) 12857 notePostUse(O, BO); 12858 12859 Visit(BO->getRHS()); 12860 12861 // C++11 [expr.ass]p1: 12862 // the assignment is sequenced [...] before the value computation of the 12863 // assignment expression. 12864 // C11 6.5.16/3 has no such rule. 12865 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12866 : UK_ModAsSideEffect); 12867 } 12868 12869 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 12870 VisitBinAssign(CAO); 12871 } 12872 12873 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12874 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12875 void VisitUnaryPreIncDec(UnaryOperator *UO) { 12876 Object O = getObject(UO->getSubExpr(), true); 12877 if (!O) 12878 return VisitExpr(UO); 12879 12880 notePreMod(O, UO); 12881 Visit(UO->getSubExpr()); 12882 // C++11 [expr.pre.incr]p1: 12883 // the expression ++x is equivalent to x+=1 12884 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12885 : UK_ModAsSideEffect); 12886 } 12887 12888 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12889 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12890 void VisitUnaryPostIncDec(UnaryOperator *UO) { 12891 Object O = getObject(UO->getSubExpr(), true); 12892 if (!O) 12893 return VisitExpr(UO); 12894 12895 notePreMod(O, UO); 12896 Visit(UO->getSubExpr()); 12897 notePostMod(O, UO, UK_ModAsSideEffect); 12898 } 12899 12900 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 12901 void VisitBinLOr(BinaryOperator *BO) { 12902 // The side-effects of the LHS of an '&&' are sequenced before the 12903 // value computation of the RHS, and hence before the value computation 12904 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 12905 // as if they were unconditionally sequenced. 12906 EvaluationTracker Eval(*this); 12907 { 12908 SequencedSubexpression Sequenced(*this); 12909 Visit(BO->getLHS()); 12910 } 12911 12912 bool Result; 12913 if (Eval.evaluate(BO->getLHS(), Result)) { 12914 if (!Result) 12915 Visit(BO->getRHS()); 12916 } else { 12917 // Check for unsequenced operations in the RHS, treating it as an 12918 // entirely separate evaluation. 12919 // 12920 // FIXME: If there are operations in the RHS which are unsequenced 12921 // with respect to operations outside the RHS, and those operations 12922 // are unconditionally evaluated, diagnose them. 12923 WorkList.push_back(BO->getRHS()); 12924 } 12925 } 12926 void VisitBinLAnd(BinaryOperator *BO) { 12927 EvaluationTracker Eval(*this); 12928 { 12929 SequencedSubexpression Sequenced(*this); 12930 Visit(BO->getLHS()); 12931 } 12932 12933 bool Result; 12934 if (Eval.evaluate(BO->getLHS(), Result)) { 12935 if (Result) 12936 Visit(BO->getRHS()); 12937 } else { 12938 WorkList.push_back(BO->getRHS()); 12939 } 12940 } 12941 12942 // Only visit the condition, unless we can be sure which subexpression will 12943 // be chosen. 12944 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 12945 EvaluationTracker Eval(*this); 12946 { 12947 SequencedSubexpression Sequenced(*this); 12948 Visit(CO->getCond()); 12949 } 12950 12951 bool Result; 12952 if (Eval.evaluate(CO->getCond(), Result)) 12953 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 12954 else { 12955 WorkList.push_back(CO->getTrueExpr()); 12956 WorkList.push_back(CO->getFalseExpr()); 12957 } 12958 } 12959 12960 void VisitCallExpr(CallExpr *CE) { 12961 // C++11 [intro.execution]p15: 12962 // When calling a function [...], every value computation and side effect 12963 // associated with any argument expression, or with the postfix expression 12964 // designating the called function, is sequenced before execution of every 12965 // expression or statement in the body of the function [and thus before 12966 // the value computation of its result]. 12967 SequencedSubexpression Sequenced(*this); 12968 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), 12969 [&] { Base::VisitCallExpr(CE); }); 12970 12971 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12972 } 12973 12974 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 12975 // This is a call, so all subexpressions are sequenced before the result. 12976 SequencedSubexpression Sequenced(*this); 12977 12978 if (!CCE->isListInitialization()) 12979 return VisitExpr(CCE); 12980 12981 // In C++11, list initializations are sequenced. 12982 SmallVector<SequenceTree::Seq, 32> Elts; 12983 SequenceTree::Seq Parent = Region; 12984 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 12985 E = CCE->arg_end(); 12986 I != E; ++I) { 12987 Region = Tree.allocate(Parent); 12988 Elts.push_back(Region); 12989 Visit(*I); 12990 } 12991 12992 // Forget that the initializers are sequenced. 12993 Region = Parent; 12994 for (unsigned I = 0; I < Elts.size(); ++I) 12995 Tree.merge(Elts[I]); 12996 } 12997 12998 void VisitInitListExpr(InitListExpr *ILE) { 12999 if (!SemaRef.getLangOpts().CPlusPlus11) 13000 return VisitExpr(ILE); 13001 13002 // In C++11, list initializations are sequenced. 13003 SmallVector<SequenceTree::Seq, 32> Elts; 13004 SequenceTree::Seq Parent = Region; 13005 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13006 Expr *E = ILE->getInit(I); 13007 if (!E) continue; 13008 Region = Tree.allocate(Parent); 13009 Elts.push_back(Region); 13010 Visit(E); 13011 } 13012 13013 // Forget that the initializers are sequenced. 13014 Region = Parent; 13015 for (unsigned I = 0; I < Elts.size(); ++I) 13016 Tree.merge(Elts[I]); 13017 } 13018 }; 13019 13020 } // namespace 13021 13022 void Sema::CheckUnsequencedOperations(Expr *E) { 13023 SmallVector<Expr *, 8> WorkList; 13024 WorkList.push_back(E); 13025 while (!WorkList.empty()) { 13026 Expr *Item = WorkList.pop_back_val(); 13027 SequenceChecker(*this, Item, WorkList); 13028 } 13029 } 13030 13031 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13032 bool IsConstexpr) { 13033 llvm::SaveAndRestore<bool> ConstantContext( 13034 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13035 CheckImplicitConversions(E, CheckLoc); 13036 if (!E->isInstantiationDependent()) 13037 CheckUnsequencedOperations(E); 13038 if (!IsConstexpr && !E->isValueDependent()) 13039 CheckForIntOverflow(E); 13040 DiagnoseMisalignedMembers(); 13041 } 13042 13043 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13044 FieldDecl *BitField, 13045 Expr *Init) { 13046 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13047 } 13048 13049 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13050 SourceLocation Loc) { 13051 if (!PType->isVariablyModifiedType()) 13052 return; 13053 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13054 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13055 return; 13056 } 13057 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13058 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13059 return; 13060 } 13061 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13062 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13063 return; 13064 } 13065 13066 const ArrayType *AT = S.Context.getAsArrayType(PType); 13067 if (!AT) 13068 return; 13069 13070 if (AT->getSizeModifier() != ArrayType::Star) { 13071 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13072 return; 13073 } 13074 13075 S.Diag(Loc, diag::err_array_star_in_function_definition); 13076 } 13077 13078 /// CheckParmsForFunctionDef - Check that the parameters of the given 13079 /// function are appropriate for the definition of a function. This 13080 /// takes care of any checks that cannot be performed on the 13081 /// declaration itself, e.g., that the types of each of the function 13082 /// parameters are complete. 13083 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13084 bool CheckParameterNames) { 13085 bool HasInvalidParm = false; 13086 for (ParmVarDecl *Param : Parameters) { 13087 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13088 // function declarator that is part of a function definition of 13089 // that function shall not have incomplete type. 13090 // 13091 // This is also C++ [dcl.fct]p6. 13092 if (!Param->isInvalidDecl() && 13093 RequireCompleteType(Param->getLocation(), Param->getType(), 13094 diag::err_typecheck_decl_incomplete_type)) { 13095 Param->setInvalidDecl(); 13096 HasInvalidParm = true; 13097 } 13098 13099 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13100 // declaration of each parameter shall include an identifier. 13101 if (CheckParameterNames && 13102 Param->getIdentifier() == nullptr && 13103 !Param->isImplicit() && 13104 !getLangOpts().CPlusPlus) 13105 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13106 13107 // C99 6.7.5.3p12: 13108 // If the function declarator is not part of a definition of that 13109 // function, parameters may have incomplete type and may use the [*] 13110 // notation in their sequences of declarator specifiers to specify 13111 // variable length array types. 13112 QualType PType = Param->getOriginalType(); 13113 // FIXME: This diagnostic should point the '[*]' if source-location 13114 // information is added for it. 13115 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13116 13117 // If the parameter is a c++ class type and it has to be destructed in the 13118 // callee function, declare the destructor so that it can be called by the 13119 // callee function. Do not perform any direct access check on the dtor here. 13120 if (!Param->isInvalidDecl()) { 13121 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13122 if (!ClassDecl->isInvalidDecl() && 13123 !ClassDecl->hasIrrelevantDestructor() && 13124 !ClassDecl->isDependentContext() && 13125 ClassDecl->isParamDestroyedInCallee()) { 13126 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13127 MarkFunctionReferenced(Param->getLocation(), Destructor); 13128 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13129 } 13130 } 13131 } 13132 13133 // Parameters with the pass_object_size attribute only need to be marked 13134 // constant at function definitions. Because we lack information about 13135 // whether we're on a declaration or definition when we're instantiating the 13136 // attribute, we need to check for constness here. 13137 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13138 if (!Param->getType().isConstQualified()) 13139 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13140 << Attr->getSpelling() << 1; 13141 13142 // Check for parameter names shadowing fields from the class. 13143 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13144 // The owning context for the parameter should be the function, but we 13145 // want to see if this function's declaration context is a record. 13146 DeclContext *DC = Param->getDeclContext(); 13147 if (DC && DC->isFunctionOrMethod()) { 13148 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13149 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13150 RD, /*DeclIsField*/ false); 13151 } 13152 } 13153 } 13154 13155 return HasInvalidParm; 13156 } 13157 13158 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 13159 /// or MemberExpr. 13160 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 13161 ASTContext &Context) { 13162 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 13163 return Context.getDeclAlign(DRE->getDecl()); 13164 13165 if (const auto *ME = dyn_cast<MemberExpr>(E)) 13166 return Context.getDeclAlign(ME->getMemberDecl()); 13167 13168 return TypeAlign; 13169 } 13170 13171 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13172 /// pointer cast increases the alignment requirements. 13173 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13174 // This is actually a lot of work to potentially be doing on every 13175 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13176 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13177 return; 13178 13179 // Ignore dependent types. 13180 if (T->isDependentType() || Op->getType()->isDependentType()) 13181 return; 13182 13183 // Require that the destination be a pointer type. 13184 const PointerType *DestPtr = T->getAs<PointerType>(); 13185 if (!DestPtr) return; 13186 13187 // If the destination has alignment 1, we're done. 13188 QualType DestPointee = DestPtr->getPointeeType(); 13189 if (DestPointee->isIncompleteType()) return; 13190 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13191 if (DestAlign.isOne()) return; 13192 13193 // Require that the source be a pointer type. 13194 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13195 if (!SrcPtr) return; 13196 QualType SrcPointee = SrcPtr->getPointeeType(); 13197 13198 // Whitelist casts from cv void*. We already implicitly 13199 // whitelisted casts to cv void*, since they have alignment 1. 13200 // Also whitelist casts involving incomplete types, which implicitly 13201 // includes 'void'. 13202 if (SrcPointee->isIncompleteType()) return; 13203 13204 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 13205 13206 if (auto *CE = dyn_cast<CastExpr>(Op)) { 13207 if (CE->getCastKind() == CK_ArrayToPointerDecay) 13208 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 13209 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 13210 if (UO->getOpcode() == UO_AddrOf) 13211 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 13212 } 13213 13214 if (SrcAlign >= DestAlign) return; 13215 13216 Diag(TRange.getBegin(), diag::warn_cast_align) 13217 << Op->getType() << T 13218 << static_cast<unsigned>(SrcAlign.getQuantity()) 13219 << static_cast<unsigned>(DestAlign.getQuantity()) 13220 << TRange << Op->getSourceRange(); 13221 } 13222 13223 /// Check whether this array fits the idiom of a size-one tail padded 13224 /// array member of a struct. 13225 /// 13226 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13227 /// commonly used to emulate flexible arrays in C89 code. 13228 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13229 const NamedDecl *ND) { 13230 if (Size != 1 || !ND) return false; 13231 13232 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13233 if (!FD) return false; 13234 13235 // Don't consider sizes resulting from macro expansions or template argument 13236 // substitution to form C89 tail-padded arrays. 13237 13238 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13239 while (TInfo) { 13240 TypeLoc TL = TInfo->getTypeLoc(); 13241 // Look through typedefs. 13242 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13243 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13244 TInfo = TDL->getTypeSourceInfo(); 13245 continue; 13246 } 13247 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13248 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13249 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13250 return false; 13251 } 13252 break; 13253 } 13254 13255 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13256 if (!RD) return false; 13257 if (RD->isUnion()) return false; 13258 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13259 if (!CRD->isStandardLayout()) return false; 13260 } 13261 13262 // See if this is the last field decl in the record. 13263 const Decl *D = FD; 13264 while ((D = D->getNextDeclInContext())) 13265 if (isa<FieldDecl>(D)) 13266 return false; 13267 return true; 13268 } 13269 13270 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13271 const ArraySubscriptExpr *ASE, 13272 bool AllowOnePastEnd, bool IndexNegated) { 13273 // Already diagnosed by the constant evaluator. 13274 if (isConstantEvaluated()) 13275 return; 13276 13277 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13278 if (IndexExpr->isValueDependent()) 13279 return; 13280 13281 const Type *EffectiveType = 13282 BaseExpr->getType()->getPointeeOrArrayElementType(); 13283 BaseExpr = BaseExpr->IgnoreParenCasts(); 13284 const ConstantArrayType *ArrayTy = 13285 Context.getAsConstantArrayType(BaseExpr->getType()); 13286 13287 if (!ArrayTy) 13288 return; 13289 13290 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13291 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13292 return; 13293 13294 Expr::EvalResult Result; 13295 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13296 return; 13297 13298 llvm::APSInt index = Result.Val.getInt(); 13299 if (IndexNegated) 13300 index = -index; 13301 13302 const NamedDecl *ND = nullptr; 13303 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13304 ND = DRE->getDecl(); 13305 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13306 ND = ME->getMemberDecl(); 13307 13308 if (index.isUnsigned() || !index.isNegative()) { 13309 // It is possible that the type of the base expression after 13310 // IgnoreParenCasts is incomplete, even though the type of the base 13311 // expression before IgnoreParenCasts is complete (see PR39746 for an 13312 // example). In this case we have no information about whether the array 13313 // access exceeds the array bounds. However we can still diagnose an array 13314 // access which precedes the array bounds. 13315 if (BaseType->isIncompleteType()) 13316 return; 13317 13318 llvm::APInt size = ArrayTy->getSize(); 13319 if (!size.isStrictlyPositive()) 13320 return; 13321 13322 if (BaseType != EffectiveType) { 13323 // Make sure we're comparing apples to apples when comparing index to size 13324 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13325 uint64_t array_typesize = Context.getTypeSize(BaseType); 13326 // Handle ptrarith_typesize being zero, such as when casting to void* 13327 if (!ptrarith_typesize) ptrarith_typesize = 1; 13328 if (ptrarith_typesize != array_typesize) { 13329 // There's a cast to a different size type involved 13330 uint64_t ratio = array_typesize / ptrarith_typesize; 13331 // TODO: Be smarter about handling cases where array_typesize is not a 13332 // multiple of ptrarith_typesize 13333 if (ptrarith_typesize * ratio == array_typesize) 13334 size *= llvm::APInt(size.getBitWidth(), ratio); 13335 } 13336 } 13337 13338 if (size.getBitWidth() > index.getBitWidth()) 13339 index = index.zext(size.getBitWidth()); 13340 else if (size.getBitWidth() < index.getBitWidth()) 13341 size = size.zext(index.getBitWidth()); 13342 13343 // For array subscripting the index must be less than size, but for pointer 13344 // arithmetic also allow the index (offset) to be equal to size since 13345 // computing the next address after the end of the array is legal and 13346 // commonly done e.g. in C++ iterators and range-based for loops. 13347 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13348 return; 13349 13350 // Also don't warn for arrays of size 1 which are members of some 13351 // structure. These are often used to approximate flexible arrays in C89 13352 // code. 13353 if (IsTailPaddedMemberArray(*this, size, ND)) 13354 return; 13355 13356 // Suppress the warning if the subscript expression (as identified by the 13357 // ']' location) and the index expression are both from macro expansions 13358 // within a system header. 13359 if (ASE) { 13360 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13361 ASE->getRBracketLoc()); 13362 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13363 SourceLocation IndexLoc = 13364 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13365 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13366 return; 13367 } 13368 } 13369 13370 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13371 if (ASE) 13372 DiagID = diag::warn_array_index_exceeds_bounds; 13373 13374 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13375 PDiag(DiagID) << index.toString(10, true) 13376 << size.toString(10, true) 13377 << (unsigned)size.getLimitedValue(~0U) 13378 << IndexExpr->getSourceRange()); 13379 } else { 13380 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13381 if (!ASE) { 13382 DiagID = diag::warn_ptr_arith_precedes_bounds; 13383 if (index.isNegative()) index = -index; 13384 } 13385 13386 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13387 PDiag(DiagID) << index.toString(10, true) 13388 << IndexExpr->getSourceRange()); 13389 } 13390 13391 if (!ND) { 13392 // Try harder to find a NamedDecl to point at in the note. 13393 while (const ArraySubscriptExpr *ASE = 13394 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13395 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13396 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13397 ND = DRE->getDecl(); 13398 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13399 ND = ME->getMemberDecl(); 13400 } 13401 13402 if (ND) 13403 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13404 PDiag(diag::note_array_declared_here) 13405 << ND->getDeclName()); 13406 } 13407 13408 void Sema::CheckArrayAccess(const Expr *expr) { 13409 int AllowOnePastEnd = 0; 13410 while (expr) { 13411 expr = expr->IgnoreParenImpCasts(); 13412 switch (expr->getStmtClass()) { 13413 case Stmt::ArraySubscriptExprClass: { 13414 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13415 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13416 AllowOnePastEnd > 0); 13417 expr = ASE->getBase(); 13418 break; 13419 } 13420 case Stmt::MemberExprClass: { 13421 expr = cast<MemberExpr>(expr)->getBase(); 13422 break; 13423 } 13424 case Stmt::OMPArraySectionExprClass: { 13425 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13426 if (ASE->getLowerBound()) 13427 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13428 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13429 return; 13430 } 13431 case Stmt::UnaryOperatorClass: { 13432 // Only unwrap the * and & unary operators 13433 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13434 expr = UO->getSubExpr(); 13435 switch (UO->getOpcode()) { 13436 case UO_AddrOf: 13437 AllowOnePastEnd++; 13438 break; 13439 case UO_Deref: 13440 AllowOnePastEnd--; 13441 break; 13442 default: 13443 return; 13444 } 13445 break; 13446 } 13447 case Stmt::ConditionalOperatorClass: { 13448 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13449 if (const Expr *lhs = cond->getLHS()) 13450 CheckArrayAccess(lhs); 13451 if (const Expr *rhs = cond->getRHS()) 13452 CheckArrayAccess(rhs); 13453 return; 13454 } 13455 case Stmt::CXXOperatorCallExprClass: { 13456 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13457 for (const auto *Arg : OCE->arguments()) 13458 CheckArrayAccess(Arg); 13459 return; 13460 } 13461 default: 13462 return; 13463 } 13464 } 13465 } 13466 13467 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13468 13469 namespace { 13470 13471 struct RetainCycleOwner { 13472 VarDecl *Variable = nullptr; 13473 SourceRange Range; 13474 SourceLocation Loc; 13475 bool Indirect = false; 13476 13477 RetainCycleOwner() = default; 13478 13479 void setLocsFrom(Expr *e) { 13480 Loc = e->getExprLoc(); 13481 Range = e->getSourceRange(); 13482 } 13483 }; 13484 13485 } // namespace 13486 13487 /// Consider whether capturing the given variable can possibly lead to 13488 /// a retain cycle. 13489 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13490 // In ARC, it's captured strongly iff the variable has __strong 13491 // lifetime. In MRR, it's captured strongly if the variable is 13492 // __block and has an appropriate type. 13493 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13494 return false; 13495 13496 owner.Variable = var; 13497 if (ref) 13498 owner.setLocsFrom(ref); 13499 return true; 13500 } 13501 13502 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13503 while (true) { 13504 e = e->IgnoreParens(); 13505 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13506 switch (cast->getCastKind()) { 13507 case CK_BitCast: 13508 case CK_LValueBitCast: 13509 case CK_LValueToRValue: 13510 case CK_ARCReclaimReturnedObject: 13511 e = cast->getSubExpr(); 13512 continue; 13513 13514 default: 13515 return false; 13516 } 13517 } 13518 13519 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13520 ObjCIvarDecl *ivar = ref->getDecl(); 13521 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13522 return false; 13523 13524 // Try to find a retain cycle in the base. 13525 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13526 return false; 13527 13528 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13529 owner.Indirect = true; 13530 return true; 13531 } 13532 13533 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13534 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13535 if (!var) return false; 13536 return considerVariable(var, ref, owner); 13537 } 13538 13539 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13540 if (member->isArrow()) return false; 13541 13542 // Don't count this as an indirect ownership. 13543 e = member->getBase(); 13544 continue; 13545 } 13546 13547 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13548 // Only pay attention to pseudo-objects on property references. 13549 ObjCPropertyRefExpr *pre 13550 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13551 ->IgnoreParens()); 13552 if (!pre) return false; 13553 if (pre->isImplicitProperty()) return false; 13554 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13555 if (!property->isRetaining() && 13556 !(property->getPropertyIvarDecl() && 13557 property->getPropertyIvarDecl()->getType() 13558 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13559 return false; 13560 13561 owner.Indirect = true; 13562 if (pre->isSuperReceiver()) { 13563 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13564 if (!owner.Variable) 13565 return false; 13566 owner.Loc = pre->getLocation(); 13567 owner.Range = pre->getSourceRange(); 13568 return true; 13569 } 13570 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13571 ->getSourceExpr()); 13572 continue; 13573 } 13574 13575 // Array ivars? 13576 13577 return false; 13578 } 13579 } 13580 13581 namespace { 13582 13583 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13584 ASTContext &Context; 13585 VarDecl *Variable; 13586 Expr *Capturer = nullptr; 13587 bool VarWillBeReased = false; 13588 13589 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13590 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13591 Context(Context), Variable(variable) {} 13592 13593 void VisitDeclRefExpr(DeclRefExpr *ref) { 13594 if (ref->getDecl() == Variable && !Capturer) 13595 Capturer = ref; 13596 } 13597 13598 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13599 if (Capturer) return; 13600 Visit(ref->getBase()); 13601 if (Capturer && ref->isFreeIvar()) 13602 Capturer = ref; 13603 } 13604 13605 void VisitBlockExpr(BlockExpr *block) { 13606 // Look inside nested blocks 13607 if (block->getBlockDecl()->capturesVariable(Variable)) 13608 Visit(block->getBlockDecl()->getBody()); 13609 } 13610 13611 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13612 if (Capturer) return; 13613 if (OVE->getSourceExpr()) 13614 Visit(OVE->getSourceExpr()); 13615 } 13616 13617 void VisitBinaryOperator(BinaryOperator *BinOp) { 13618 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13619 return; 13620 Expr *LHS = BinOp->getLHS(); 13621 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13622 if (DRE->getDecl() != Variable) 13623 return; 13624 if (Expr *RHS = BinOp->getRHS()) { 13625 RHS = RHS->IgnoreParenCasts(); 13626 llvm::APSInt Value; 13627 VarWillBeReased = 13628 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13629 } 13630 } 13631 } 13632 }; 13633 13634 } // namespace 13635 13636 /// Check whether the given argument is a block which captures a 13637 /// variable. 13638 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13639 assert(owner.Variable && owner.Loc.isValid()); 13640 13641 e = e->IgnoreParenCasts(); 13642 13643 // Look through [^{...} copy] and Block_copy(^{...}). 13644 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13645 Selector Cmd = ME->getSelector(); 13646 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13647 e = ME->getInstanceReceiver(); 13648 if (!e) 13649 return nullptr; 13650 e = e->IgnoreParenCasts(); 13651 } 13652 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13653 if (CE->getNumArgs() == 1) { 13654 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13655 if (Fn) { 13656 const IdentifierInfo *FnI = Fn->getIdentifier(); 13657 if (FnI && FnI->isStr("_Block_copy")) { 13658 e = CE->getArg(0)->IgnoreParenCasts(); 13659 } 13660 } 13661 } 13662 } 13663 13664 BlockExpr *block = dyn_cast<BlockExpr>(e); 13665 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13666 return nullptr; 13667 13668 FindCaptureVisitor visitor(S.Context, owner.Variable); 13669 visitor.Visit(block->getBlockDecl()->getBody()); 13670 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13671 } 13672 13673 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13674 RetainCycleOwner &owner) { 13675 assert(capturer); 13676 assert(owner.Variable && owner.Loc.isValid()); 13677 13678 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13679 << owner.Variable << capturer->getSourceRange(); 13680 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13681 << owner.Indirect << owner.Range; 13682 } 13683 13684 /// Check for a keyword selector that starts with the word 'add' or 13685 /// 'set'. 13686 static bool isSetterLikeSelector(Selector sel) { 13687 if (sel.isUnarySelector()) return false; 13688 13689 StringRef str = sel.getNameForSlot(0); 13690 while (!str.empty() && str.front() == '_') str = str.substr(1); 13691 if (str.startswith("set")) 13692 str = str.substr(3); 13693 else if (str.startswith("add")) { 13694 // Specially whitelist 'addOperationWithBlock:'. 13695 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13696 return false; 13697 str = str.substr(3); 13698 } 13699 else 13700 return false; 13701 13702 if (str.empty()) return true; 13703 return !isLowercase(str.front()); 13704 } 13705 13706 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13707 ObjCMessageExpr *Message) { 13708 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13709 Message->getReceiverInterface(), 13710 NSAPI::ClassId_NSMutableArray); 13711 if (!IsMutableArray) { 13712 return None; 13713 } 13714 13715 Selector Sel = Message->getSelector(); 13716 13717 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13718 S.NSAPIObj->getNSArrayMethodKind(Sel); 13719 if (!MKOpt) { 13720 return None; 13721 } 13722 13723 NSAPI::NSArrayMethodKind MK = *MKOpt; 13724 13725 switch (MK) { 13726 case NSAPI::NSMutableArr_addObject: 13727 case NSAPI::NSMutableArr_insertObjectAtIndex: 13728 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13729 return 0; 13730 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13731 return 1; 13732 13733 default: 13734 return None; 13735 } 13736 13737 return None; 13738 } 13739 13740 static 13741 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13742 ObjCMessageExpr *Message) { 13743 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13744 Message->getReceiverInterface(), 13745 NSAPI::ClassId_NSMutableDictionary); 13746 if (!IsMutableDictionary) { 13747 return None; 13748 } 13749 13750 Selector Sel = Message->getSelector(); 13751 13752 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13753 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13754 if (!MKOpt) { 13755 return None; 13756 } 13757 13758 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13759 13760 switch (MK) { 13761 case NSAPI::NSMutableDict_setObjectForKey: 13762 case NSAPI::NSMutableDict_setValueForKey: 13763 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13764 return 0; 13765 13766 default: 13767 return None; 13768 } 13769 13770 return None; 13771 } 13772 13773 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13774 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13775 Message->getReceiverInterface(), 13776 NSAPI::ClassId_NSMutableSet); 13777 13778 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13779 Message->getReceiverInterface(), 13780 NSAPI::ClassId_NSMutableOrderedSet); 13781 if (!IsMutableSet && !IsMutableOrderedSet) { 13782 return None; 13783 } 13784 13785 Selector Sel = Message->getSelector(); 13786 13787 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13788 if (!MKOpt) { 13789 return None; 13790 } 13791 13792 NSAPI::NSSetMethodKind MK = *MKOpt; 13793 13794 switch (MK) { 13795 case NSAPI::NSMutableSet_addObject: 13796 case NSAPI::NSOrderedSet_setObjectAtIndex: 13797 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13798 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13799 return 0; 13800 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13801 return 1; 13802 } 13803 13804 return None; 13805 } 13806 13807 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13808 if (!Message->isInstanceMessage()) { 13809 return; 13810 } 13811 13812 Optional<int> ArgOpt; 13813 13814 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13815 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13816 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13817 return; 13818 } 13819 13820 int ArgIndex = *ArgOpt; 13821 13822 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13823 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13824 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13825 } 13826 13827 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13828 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13829 if (ArgRE->isObjCSelfExpr()) { 13830 Diag(Message->getSourceRange().getBegin(), 13831 diag::warn_objc_circular_container) 13832 << ArgRE->getDecl() << StringRef("'super'"); 13833 } 13834 } 13835 } else { 13836 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13837 13838 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13839 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13840 } 13841 13842 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13843 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13844 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13845 ValueDecl *Decl = ReceiverRE->getDecl(); 13846 Diag(Message->getSourceRange().getBegin(), 13847 diag::warn_objc_circular_container) 13848 << Decl << Decl; 13849 if (!ArgRE->isObjCSelfExpr()) { 13850 Diag(Decl->getLocation(), 13851 diag::note_objc_circular_container_declared_here) 13852 << Decl; 13853 } 13854 } 13855 } 13856 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13857 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13858 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13859 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13860 Diag(Message->getSourceRange().getBegin(), 13861 diag::warn_objc_circular_container) 13862 << Decl << Decl; 13863 Diag(Decl->getLocation(), 13864 diag::note_objc_circular_container_declared_here) 13865 << Decl; 13866 } 13867 } 13868 } 13869 } 13870 } 13871 13872 /// Check a message send to see if it's likely to cause a retain cycle. 13873 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13874 // Only check instance methods whose selector looks like a setter. 13875 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13876 return; 13877 13878 // Try to find a variable that the receiver is strongly owned by. 13879 RetainCycleOwner owner; 13880 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13881 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13882 return; 13883 } else { 13884 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13885 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13886 owner.Loc = msg->getSuperLoc(); 13887 owner.Range = msg->getSuperLoc(); 13888 } 13889 13890 // Check whether the receiver is captured by any of the arguments. 13891 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13892 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13893 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13894 // noescape blocks should not be retained by the method. 13895 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13896 continue; 13897 return diagnoseRetainCycle(*this, capturer, owner); 13898 } 13899 } 13900 } 13901 13902 /// Check a property assign to see if it's likely to cause a retain cycle. 13903 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13904 RetainCycleOwner owner; 13905 if (!findRetainCycleOwner(*this, receiver, owner)) 13906 return; 13907 13908 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13909 diagnoseRetainCycle(*this, capturer, owner); 13910 } 13911 13912 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13913 RetainCycleOwner Owner; 13914 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13915 return; 13916 13917 // Because we don't have an expression for the variable, we have to set the 13918 // location explicitly here. 13919 Owner.Loc = Var->getLocation(); 13920 Owner.Range = Var->getSourceRange(); 13921 13922 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13923 diagnoseRetainCycle(*this, Capturer, Owner); 13924 } 13925 13926 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13927 Expr *RHS, bool isProperty) { 13928 // Check if RHS is an Objective-C object literal, which also can get 13929 // immediately zapped in a weak reference. Note that we explicitly 13930 // allow ObjCStringLiterals, since those are designed to never really die. 13931 RHS = RHS->IgnoreParenImpCasts(); 13932 13933 // This enum needs to match with the 'select' in 13934 // warn_objc_arc_literal_assign (off-by-1). 13935 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13936 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13937 return false; 13938 13939 S.Diag(Loc, diag::warn_arc_literal_assign) 13940 << (unsigned) Kind 13941 << (isProperty ? 0 : 1) 13942 << RHS->getSourceRange(); 13943 13944 return true; 13945 } 13946 13947 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13948 Qualifiers::ObjCLifetime LT, 13949 Expr *RHS, bool isProperty) { 13950 // Strip off any implicit cast added to get to the one ARC-specific. 13951 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13952 if (cast->getCastKind() == CK_ARCConsumeObject) { 13953 S.Diag(Loc, diag::warn_arc_retained_assign) 13954 << (LT == Qualifiers::OCL_ExplicitNone) 13955 << (isProperty ? 0 : 1) 13956 << RHS->getSourceRange(); 13957 return true; 13958 } 13959 RHS = cast->getSubExpr(); 13960 } 13961 13962 if (LT == Qualifiers::OCL_Weak && 13963 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13964 return true; 13965 13966 return false; 13967 } 13968 13969 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13970 QualType LHS, Expr *RHS) { 13971 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13972 13973 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13974 return false; 13975 13976 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13977 return true; 13978 13979 return false; 13980 } 13981 13982 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13983 Expr *LHS, Expr *RHS) { 13984 QualType LHSType; 13985 // PropertyRef on LHS type need be directly obtained from 13986 // its declaration as it has a PseudoType. 13987 ObjCPropertyRefExpr *PRE 13988 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13989 if (PRE && !PRE->isImplicitProperty()) { 13990 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13991 if (PD) 13992 LHSType = PD->getType(); 13993 } 13994 13995 if (LHSType.isNull()) 13996 LHSType = LHS->getType(); 13997 13998 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13999 14000 if (LT == Qualifiers::OCL_Weak) { 14001 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14002 getCurFunction()->markSafeWeakUse(LHS); 14003 } 14004 14005 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14006 return; 14007 14008 // FIXME. Check for other life times. 14009 if (LT != Qualifiers::OCL_None) 14010 return; 14011 14012 if (PRE) { 14013 if (PRE->isImplicitProperty()) 14014 return; 14015 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14016 if (!PD) 14017 return; 14018 14019 unsigned Attributes = PD->getPropertyAttributes(); 14020 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 14021 // when 'assign' attribute was not explicitly specified 14022 // by user, ignore it and rely on property type itself 14023 // for lifetime info. 14024 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14025 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 14026 LHSType->isObjCRetainableType()) 14027 return; 14028 14029 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14030 if (cast->getCastKind() == CK_ARCConsumeObject) { 14031 Diag(Loc, diag::warn_arc_retained_property_assign) 14032 << RHS->getSourceRange(); 14033 return; 14034 } 14035 RHS = cast->getSubExpr(); 14036 } 14037 } 14038 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 14039 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14040 return; 14041 } 14042 } 14043 } 14044 14045 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14046 14047 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14048 SourceLocation StmtLoc, 14049 const NullStmt *Body) { 14050 // Do not warn if the body is a macro that expands to nothing, e.g: 14051 // 14052 // #define CALL(x) 14053 // if (condition) 14054 // CALL(0); 14055 if (Body->hasLeadingEmptyMacro()) 14056 return false; 14057 14058 // Get line numbers of statement and body. 14059 bool StmtLineInvalid; 14060 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14061 &StmtLineInvalid); 14062 if (StmtLineInvalid) 14063 return false; 14064 14065 bool BodyLineInvalid; 14066 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14067 &BodyLineInvalid); 14068 if (BodyLineInvalid) 14069 return false; 14070 14071 // Warn if null statement and body are on the same line. 14072 if (StmtLine != BodyLine) 14073 return false; 14074 14075 return true; 14076 } 14077 14078 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14079 const Stmt *Body, 14080 unsigned DiagID) { 14081 // Since this is a syntactic check, don't emit diagnostic for template 14082 // instantiations, this just adds noise. 14083 if (CurrentInstantiationScope) 14084 return; 14085 14086 // The body should be a null statement. 14087 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14088 if (!NBody) 14089 return; 14090 14091 // Do the usual checks. 14092 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14093 return; 14094 14095 Diag(NBody->getSemiLoc(), DiagID); 14096 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14097 } 14098 14099 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14100 const Stmt *PossibleBody) { 14101 assert(!CurrentInstantiationScope); // Ensured by caller 14102 14103 SourceLocation StmtLoc; 14104 const Stmt *Body; 14105 unsigned DiagID; 14106 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14107 StmtLoc = FS->getRParenLoc(); 14108 Body = FS->getBody(); 14109 DiagID = diag::warn_empty_for_body; 14110 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14111 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14112 Body = WS->getBody(); 14113 DiagID = diag::warn_empty_while_body; 14114 } else 14115 return; // Neither `for' nor `while'. 14116 14117 // The body should be a null statement. 14118 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14119 if (!NBody) 14120 return; 14121 14122 // Skip expensive checks if diagnostic is disabled. 14123 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14124 return; 14125 14126 // Do the usual checks. 14127 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14128 return; 14129 14130 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14131 // noise level low, emit diagnostics only if for/while is followed by a 14132 // CompoundStmt, e.g.: 14133 // for (int i = 0; i < n; i++); 14134 // { 14135 // a(i); 14136 // } 14137 // or if for/while is followed by a statement with more indentation 14138 // than for/while itself: 14139 // for (int i = 0; i < n; i++); 14140 // a(i); 14141 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14142 if (!ProbableTypo) { 14143 bool BodyColInvalid; 14144 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14145 PossibleBody->getBeginLoc(), &BodyColInvalid); 14146 if (BodyColInvalid) 14147 return; 14148 14149 bool StmtColInvalid; 14150 unsigned StmtCol = 14151 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14152 if (StmtColInvalid) 14153 return; 14154 14155 if (BodyCol > StmtCol) 14156 ProbableTypo = true; 14157 } 14158 14159 if (ProbableTypo) { 14160 Diag(NBody->getSemiLoc(), DiagID); 14161 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14162 } 14163 } 14164 14165 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14166 14167 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14168 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14169 SourceLocation OpLoc) { 14170 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14171 return; 14172 14173 if (inTemplateInstantiation()) 14174 return; 14175 14176 // Strip parens and casts away. 14177 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14178 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14179 14180 // Check for a call expression 14181 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14182 if (!CE || CE->getNumArgs() != 1) 14183 return; 14184 14185 // Check for a call to std::move 14186 if (!CE->isCallToStdMove()) 14187 return; 14188 14189 // Get argument from std::move 14190 RHSExpr = CE->getArg(0); 14191 14192 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14193 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14194 14195 // Two DeclRefExpr's, check that the decls are the same. 14196 if (LHSDeclRef && RHSDeclRef) { 14197 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14198 return; 14199 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14200 RHSDeclRef->getDecl()->getCanonicalDecl()) 14201 return; 14202 14203 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14204 << LHSExpr->getSourceRange() 14205 << RHSExpr->getSourceRange(); 14206 return; 14207 } 14208 14209 // Member variables require a different approach to check for self moves. 14210 // MemberExpr's are the same if every nested MemberExpr refers to the same 14211 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14212 // the base Expr's are CXXThisExpr's. 14213 const Expr *LHSBase = LHSExpr; 14214 const Expr *RHSBase = RHSExpr; 14215 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14216 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14217 if (!LHSME || !RHSME) 14218 return; 14219 14220 while (LHSME && RHSME) { 14221 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14222 RHSME->getMemberDecl()->getCanonicalDecl()) 14223 return; 14224 14225 LHSBase = LHSME->getBase(); 14226 RHSBase = RHSME->getBase(); 14227 LHSME = dyn_cast<MemberExpr>(LHSBase); 14228 RHSME = dyn_cast<MemberExpr>(RHSBase); 14229 } 14230 14231 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14232 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14233 if (LHSDeclRef && RHSDeclRef) { 14234 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14235 return; 14236 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14237 RHSDeclRef->getDecl()->getCanonicalDecl()) 14238 return; 14239 14240 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14241 << LHSExpr->getSourceRange() 14242 << RHSExpr->getSourceRange(); 14243 return; 14244 } 14245 14246 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14247 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14248 << LHSExpr->getSourceRange() 14249 << RHSExpr->getSourceRange(); 14250 } 14251 14252 //===--- Layout compatibility ----------------------------------------------// 14253 14254 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14255 14256 /// Check if two enumeration types are layout-compatible. 14257 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14258 // C++11 [dcl.enum] p8: 14259 // Two enumeration types are layout-compatible if they have the same 14260 // underlying type. 14261 return ED1->isComplete() && ED2->isComplete() && 14262 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14263 } 14264 14265 /// Check if two fields are layout-compatible. 14266 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14267 FieldDecl *Field2) { 14268 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14269 return false; 14270 14271 if (Field1->isBitField() != Field2->isBitField()) 14272 return false; 14273 14274 if (Field1->isBitField()) { 14275 // Make sure that the bit-fields are the same length. 14276 unsigned Bits1 = Field1->getBitWidthValue(C); 14277 unsigned Bits2 = Field2->getBitWidthValue(C); 14278 14279 if (Bits1 != Bits2) 14280 return false; 14281 } 14282 14283 return true; 14284 } 14285 14286 /// Check if two standard-layout structs are layout-compatible. 14287 /// (C++11 [class.mem] p17) 14288 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14289 RecordDecl *RD2) { 14290 // If both records are C++ classes, check that base classes match. 14291 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14292 // If one of records is a CXXRecordDecl we are in C++ mode, 14293 // thus the other one is a CXXRecordDecl, too. 14294 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14295 // Check number of base classes. 14296 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14297 return false; 14298 14299 // Check the base classes. 14300 for (CXXRecordDecl::base_class_const_iterator 14301 Base1 = D1CXX->bases_begin(), 14302 BaseEnd1 = D1CXX->bases_end(), 14303 Base2 = D2CXX->bases_begin(); 14304 Base1 != BaseEnd1; 14305 ++Base1, ++Base2) { 14306 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14307 return false; 14308 } 14309 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14310 // If only RD2 is a C++ class, it should have zero base classes. 14311 if (D2CXX->getNumBases() > 0) 14312 return false; 14313 } 14314 14315 // Check the fields. 14316 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14317 Field2End = RD2->field_end(), 14318 Field1 = RD1->field_begin(), 14319 Field1End = RD1->field_end(); 14320 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14321 if (!isLayoutCompatible(C, *Field1, *Field2)) 14322 return false; 14323 } 14324 if (Field1 != Field1End || Field2 != Field2End) 14325 return false; 14326 14327 return true; 14328 } 14329 14330 /// Check if two standard-layout unions are layout-compatible. 14331 /// (C++11 [class.mem] p18) 14332 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14333 RecordDecl *RD2) { 14334 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14335 for (auto *Field2 : RD2->fields()) 14336 UnmatchedFields.insert(Field2); 14337 14338 for (auto *Field1 : RD1->fields()) { 14339 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14340 I = UnmatchedFields.begin(), 14341 E = UnmatchedFields.end(); 14342 14343 for ( ; I != E; ++I) { 14344 if (isLayoutCompatible(C, Field1, *I)) { 14345 bool Result = UnmatchedFields.erase(*I); 14346 (void) Result; 14347 assert(Result); 14348 break; 14349 } 14350 } 14351 if (I == E) 14352 return false; 14353 } 14354 14355 return UnmatchedFields.empty(); 14356 } 14357 14358 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14359 RecordDecl *RD2) { 14360 if (RD1->isUnion() != RD2->isUnion()) 14361 return false; 14362 14363 if (RD1->isUnion()) 14364 return isLayoutCompatibleUnion(C, RD1, RD2); 14365 else 14366 return isLayoutCompatibleStruct(C, RD1, RD2); 14367 } 14368 14369 /// Check if two types are layout-compatible in C++11 sense. 14370 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14371 if (T1.isNull() || T2.isNull()) 14372 return false; 14373 14374 // C++11 [basic.types] p11: 14375 // If two types T1 and T2 are the same type, then T1 and T2 are 14376 // layout-compatible types. 14377 if (C.hasSameType(T1, T2)) 14378 return true; 14379 14380 T1 = T1.getCanonicalType().getUnqualifiedType(); 14381 T2 = T2.getCanonicalType().getUnqualifiedType(); 14382 14383 const Type::TypeClass TC1 = T1->getTypeClass(); 14384 const Type::TypeClass TC2 = T2->getTypeClass(); 14385 14386 if (TC1 != TC2) 14387 return false; 14388 14389 if (TC1 == Type::Enum) { 14390 return isLayoutCompatible(C, 14391 cast<EnumType>(T1)->getDecl(), 14392 cast<EnumType>(T2)->getDecl()); 14393 } else if (TC1 == Type::Record) { 14394 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14395 return false; 14396 14397 return isLayoutCompatible(C, 14398 cast<RecordType>(T1)->getDecl(), 14399 cast<RecordType>(T2)->getDecl()); 14400 } 14401 14402 return false; 14403 } 14404 14405 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14406 14407 /// Given a type tag expression find the type tag itself. 14408 /// 14409 /// \param TypeExpr Type tag expression, as it appears in user's code. 14410 /// 14411 /// \param VD Declaration of an identifier that appears in a type tag. 14412 /// 14413 /// \param MagicValue Type tag magic value. 14414 /// 14415 /// \param isConstantEvaluated wether the evalaution should be performed in 14416 14417 /// constant context. 14418 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14419 const ValueDecl **VD, uint64_t *MagicValue, 14420 bool isConstantEvaluated) { 14421 while(true) { 14422 if (!TypeExpr) 14423 return false; 14424 14425 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14426 14427 switch (TypeExpr->getStmtClass()) { 14428 case Stmt::UnaryOperatorClass: { 14429 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14430 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14431 TypeExpr = UO->getSubExpr(); 14432 continue; 14433 } 14434 return false; 14435 } 14436 14437 case Stmt::DeclRefExprClass: { 14438 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14439 *VD = DRE->getDecl(); 14440 return true; 14441 } 14442 14443 case Stmt::IntegerLiteralClass: { 14444 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14445 llvm::APInt MagicValueAPInt = IL->getValue(); 14446 if (MagicValueAPInt.getActiveBits() <= 64) { 14447 *MagicValue = MagicValueAPInt.getZExtValue(); 14448 return true; 14449 } else 14450 return false; 14451 } 14452 14453 case Stmt::BinaryConditionalOperatorClass: 14454 case Stmt::ConditionalOperatorClass: { 14455 const AbstractConditionalOperator *ACO = 14456 cast<AbstractConditionalOperator>(TypeExpr); 14457 bool Result; 14458 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14459 isConstantEvaluated)) { 14460 if (Result) 14461 TypeExpr = ACO->getTrueExpr(); 14462 else 14463 TypeExpr = ACO->getFalseExpr(); 14464 continue; 14465 } 14466 return false; 14467 } 14468 14469 case Stmt::BinaryOperatorClass: { 14470 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14471 if (BO->getOpcode() == BO_Comma) { 14472 TypeExpr = BO->getRHS(); 14473 continue; 14474 } 14475 return false; 14476 } 14477 14478 default: 14479 return false; 14480 } 14481 } 14482 } 14483 14484 /// Retrieve the C type corresponding to type tag TypeExpr. 14485 /// 14486 /// \param TypeExpr Expression that specifies a type tag. 14487 /// 14488 /// \param MagicValues Registered magic values. 14489 /// 14490 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14491 /// kind. 14492 /// 14493 /// \param TypeInfo Information about the corresponding C type. 14494 /// 14495 /// \param isConstantEvaluated wether the evalaution should be performed in 14496 /// constant context. 14497 /// 14498 /// \returns true if the corresponding C type was found. 14499 static bool GetMatchingCType( 14500 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14501 const ASTContext &Ctx, 14502 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14503 *MagicValues, 14504 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14505 bool isConstantEvaluated) { 14506 FoundWrongKind = false; 14507 14508 // Variable declaration that has type_tag_for_datatype attribute. 14509 const ValueDecl *VD = nullptr; 14510 14511 uint64_t MagicValue; 14512 14513 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14514 return false; 14515 14516 if (VD) { 14517 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14518 if (I->getArgumentKind() != ArgumentKind) { 14519 FoundWrongKind = true; 14520 return false; 14521 } 14522 TypeInfo.Type = I->getMatchingCType(); 14523 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14524 TypeInfo.MustBeNull = I->getMustBeNull(); 14525 return true; 14526 } 14527 return false; 14528 } 14529 14530 if (!MagicValues) 14531 return false; 14532 14533 llvm::DenseMap<Sema::TypeTagMagicValue, 14534 Sema::TypeTagData>::const_iterator I = 14535 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14536 if (I == MagicValues->end()) 14537 return false; 14538 14539 TypeInfo = I->second; 14540 return true; 14541 } 14542 14543 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14544 uint64_t MagicValue, QualType Type, 14545 bool LayoutCompatible, 14546 bool MustBeNull) { 14547 if (!TypeTagForDatatypeMagicValues) 14548 TypeTagForDatatypeMagicValues.reset( 14549 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14550 14551 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14552 (*TypeTagForDatatypeMagicValues)[Magic] = 14553 TypeTagData(Type, LayoutCompatible, MustBeNull); 14554 } 14555 14556 static bool IsSameCharType(QualType T1, QualType T2) { 14557 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14558 if (!BT1) 14559 return false; 14560 14561 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14562 if (!BT2) 14563 return false; 14564 14565 BuiltinType::Kind T1Kind = BT1->getKind(); 14566 BuiltinType::Kind T2Kind = BT2->getKind(); 14567 14568 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14569 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14570 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14571 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14572 } 14573 14574 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14575 const ArrayRef<const Expr *> ExprArgs, 14576 SourceLocation CallSiteLoc) { 14577 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14578 bool IsPointerAttr = Attr->getIsPointer(); 14579 14580 // Retrieve the argument representing the 'type_tag'. 14581 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14582 if (TypeTagIdxAST >= ExprArgs.size()) { 14583 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14584 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14585 return; 14586 } 14587 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14588 bool FoundWrongKind; 14589 TypeTagData TypeInfo; 14590 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14591 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14592 TypeInfo, isConstantEvaluated())) { 14593 if (FoundWrongKind) 14594 Diag(TypeTagExpr->getExprLoc(), 14595 diag::warn_type_tag_for_datatype_wrong_kind) 14596 << TypeTagExpr->getSourceRange(); 14597 return; 14598 } 14599 14600 // Retrieve the argument representing the 'arg_idx'. 14601 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14602 if (ArgumentIdxAST >= ExprArgs.size()) { 14603 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14604 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14605 return; 14606 } 14607 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14608 if (IsPointerAttr) { 14609 // Skip implicit cast of pointer to `void *' (as a function argument). 14610 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14611 if (ICE->getType()->isVoidPointerType() && 14612 ICE->getCastKind() == CK_BitCast) 14613 ArgumentExpr = ICE->getSubExpr(); 14614 } 14615 QualType ArgumentType = ArgumentExpr->getType(); 14616 14617 // Passing a `void*' pointer shouldn't trigger a warning. 14618 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14619 return; 14620 14621 if (TypeInfo.MustBeNull) { 14622 // Type tag with matching void type requires a null pointer. 14623 if (!ArgumentExpr->isNullPointerConstant(Context, 14624 Expr::NPC_ValueDependentIsNotNull)) { 14625 Diag(ArgumentExpr->getExprLoc(), 14626 diag::warn_type_safety_null_pointer_required) 14627 << ArgumentKind->getName() 14628 << ArgumentExpr->getSourceRange() 14629 << TypeTagExpr->getSourceRange(); 14630 } 14631 return; 14632 } 14633 14634 QualType RequiredType = TypeInfo.Type; 14635 if (IsPointerAttr) 14636 RequiredType = Context.getPointerType(RequiredType); 14637 14638 bool mismatch = false; 14639 if (!TypeInfo.LayoutCompatible) { 14640 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14641 14642 // C++11 [basic.fundamental] p1: 14643 // Plain char, signed char, and unsigned char are three distinct types. 14644 // 14645 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14646 // char' depending on the current char signedness mode. 14647 if (mismatch) 14648 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14649 RequiredType->getPointeeType())) || 14650 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14651 mismatch = false; 14652 } else 14653 if (IsPointerAttr) 14654 mismatch = !isLayoutCompatible(Context, 14655 ArgumentType->getPointeeType(), 14656 RequiredType->getPointeeType()); 14657 else 14658 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14659 14660 if (mismatch) 14661 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14662 << ArgumentType << ArgumentKind 14663 << TypeInfo.LayoutCompatible << RequiredType 14664 << ArgumentExpr->getSourceRange() 14665 << TypeTagExpr->getSourceRange(); 14666 } 14667 14668 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14669 CharUnits Alignment) { 14670 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14671 } 14672 14673 void Sema::DiagnoseMisalignedMembers() { 14674 for (MisalignedMember &m : MisalignedMembers) { 14675 const NamedDecl *ND = m.RD; 14676 if (ND->getName().empty()) { 14677 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14678 ND = TD; 14679 } 14680 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14681 << m.MD << ND << m.E->getSourceRange(); 14682 } 14683 MisalignedMembers.clear(); 14684 } 14685 14686 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14687 E = E->IgnoreParens(); 14688 if (!T->isPointerType() && !T->isIntegerType()) 14689 return; 14690 if (isa<UnaryOperator>(E) && 14691 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14692 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14693 if (isa<MemberExpr>(Op)) { 14694 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14695 if (MA != MisalignedMembers.end() && 14696 (T->isIntegerType() || 14697 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14698 Context.getTypeAlignInChars( 14699 T->getPointeeType()) <= MA->Alignment)))) 14700 MisalignedMembers.erase(MA); 14701 } 14702 } 14703 } 14704 14705 void Sema::RefersToMemberWithReducedAlignment( 14706 Expr *E, 14707 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14708 Action) { 14709 const auto *ME = dyn_cast<MemberExpr>(E); 14710 if (!ME) 14711 return; 14712 14713 // No need to check expressions with an __unaligned-qualified type. 14714 if (E->getType().getQualifiers().hasUnaligned()) 14715 return; 14716 14717 // For a chain of MemberExpr like "a.b.c.d" this list 14718 // will keep FieldDecl's like [d, c, b]. 14719 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14720 const MemberExpr *TopME = nullptr; 14721 bool AnyIsPacked = false; 14722 do { 14723 QualType BaseType = ME->getBase()->getType(); 14724 if (BaseType->isDependentType()) 14725 return; 14726 if (ME->isArrow()) 14727 BaseType = BaseType->getPointeeType(); 14728 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14729 if (RD->isInvalidDecl()) 14730 return; 14731 14732 ValueDecl *MD = ME->getMemberDecl(); 14733 auto *FD = dyn_cast<FieldDecl>(MD); 14734 // We do not care about non-data members. 14735 if (!FD || FD->isInvalidDecl()) 14736 return; 14737 14738 AnyIsPacked = 14739 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14740 ReverseMemberChain.push_back(FD); 14741 14742 TopME = ME; 14743 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14744 } while (ME); 14745 assert(TopME && "We did not compute a topmost MemberExpr!"); 14746 14747 // Not the scope of this diagnostic. 14748 if (!AnyIsPacked) 14749 return; 14750 14751 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14752 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14753 // TODO: The innermost base of the member expression may be too complicated. 14754 // For now, just disregard these cases. This is left for future 14755 // improvement. 14756 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14757 return; 14758 14759 // Alignment expected by the whole expression. 14760 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14761 14762 // No need to do anything else with this case. 14763 if (ExpectedAlignment.isOne()) 14764 return; 14765 14766 // Synthesize offset of the whole access. 14767 CharUnits Offset; 14768 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14769 I++) { 14770 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14771 } 14772 14773 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14774 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14775 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14776 14777 // The base expression of the innermost MemberExpr may give 14778 // stronger guarantees than the class containing the member. 14779 if (DRE && !TopME->isArrow()) { 14780 const ValueDecl *VD = DRE->getDecl(); 14781 if (!VD->getType()->isReferenceType()) 14782 CompleteObjectAlignment = 14783 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14784 } 14785 14786 // Check if the synthesized offset fulfills the alignment. 14787 if (Offset % ExpectedAlignment != 0 || 14788 // It may fulfill the offset it but the effective alignment may still be 14789 // lower than the expected expression alignment. 14790 CompleteObjectAlignment < ExpectedAlignment) { 14791 // If this happens, we want to determine a sensible culprit of this. 14792 // Intuitively, watching the chain of member expressions from right to 14793 // left, we start with the required alignment (as required by the field 14794 // type) but some packed attribute in that chain has reduced the alignment. 14795 // It may happen that another packed structure increases it again. But if 14796 // we are here such increase has not been enough. So pointing the first 14797 // FieldDecl that either is packed or else its RecordDecl is, 14798 // seems reasonable. 14799 FieldDecl *FD = nullptr; 14800 CharUnits Alignment; 14801 for (FieldDecl *FDI : ReverseMemberChain) { 14802 if (FDI->hasAttr<PackedAttr>() || 14803 FDI->getParent()->hasAttr<PackedAttr>()) { 14804 FD = FDI; 14805 Alignment = std::min( 14806 Context.getTypeAlignInChars(FD->getType()), 14807 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14808 break; 14809 } 14810 } 14811 assert(FD && "We did not find a packed FieldDecl!"); 14812 Action(E, FD->getParent(), FD, Alignment); 14813 } 14814 } 14815 14816 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14817 using namespace std::placeholders; 14818 14819 RefersToMemberWithReducedAlignment( 14820 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14821 _2, _3, _4)); 14822 } 14823