1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements extra semantic analysis beyond what is enforced 11 // by the C type system. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/AST/APValue.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/AttrIterator.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclarationName.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/ExprCXX.h" 28 #include "clang/AST/ExprObjC.h" 29 #include "clang/AST/ExprOpenMP.h" 30 #include "clang/AST/FormatString.h" 31 #include "clang/AST/NSAPI.h" 32 #include "clang/AST/NonTrivialTypeVisitor.h" 33 #include "clang/AST/OperationKinds.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.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 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 195 if (checkArgCount(S, TheCall, 3)) 196 return true; 197 198 // First two arguments should be integers. 199 for (unsigned I = 0; I < 2; ++I) { 200 ExprResult Arg = TheCall->getArg(I); 201 QualType Ty = Arg.get()->getType(); 202 if (!Ty->isIntegerType()) { 203 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 204 << Ty << Arg.get()->getSourceRange(); 205 return true; 206 } 207 InitializedEntity Entity = InitializedEntity::InitializeParameter( 208 S.getASTContext(), Ty, /*consume*/ false); 209 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 210 if (Arg.isInvalid()) 211 return true; 212 TheCall->setArg(I, Arg.get()); 213 } 214 215 // Third argument should be a pointer to a non-const integer. 216 // IRGen correctly handles volatile, restrict, and address spaces, and 217 // the other qualifiers aren't possible. 218 { 219 ExprResult Arg = TheCall->getArg(2); 220 QualType Ty = Arg.get()->getType(); 221 const auto *PtrTy = Ty->getAs<PointerType>(); 222 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 223 !PtrTy->getPointeeType().isConstQualified())) { 224 S.Diag(Arg.get()->getBeginLoc(), 225 diag::err_overflow_builtin_must_be_ptr_int) 226 << Ty << Arg.get()->getSourceRange(); 227 return true; 228 } 229 InitializedEntity Entity = InitializedEntity::InitializeParameter( 230 S.getASTContext(), Ty, /*consume*/ false); 231 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 232 if (Arg.isInvalid()) 233 return true; 234 TheCall->setArg(2, Arg.get()); 235 } 236 return false; 237 } 238 239 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 240 CallExpr *TheCall, unsigned SizeIdx, 241 unsigned DstSizeIdx, 242 StringRef LikelyMacroName) { 243 if (TheCall->getNumArgs() <= SizeIdx || 244 TheCall->getNumArgs() <= DstSizeIdx) 245 return; 246 247 const Expr *SizeArg = TheCall->getArg(SizeIdx); 248 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 249 250 Expr::EvalResult SizeResult, DstSizeResult; 251 252 // find out if both sizes are known at compile time 253 if (!SizeArg->EvaluateAsInt(SizeResult, S.Context) || 254 !DstSizeArg->EvaluateAsInt(DstSizeResult, S.Context)) 255 return; 256 257 llvm::APSInt Size = SizeResult.Val.getInt(); 258 llvm::APSInt DstSize = DstSizeResult.Val.getInt(); 259 260 if (Size.ule(DstSize)) 261 return; 262 263 // Confirmed overflow, so generate the diagnostic. 264 StringRef FunctionName = FDecl->getName(); 265 SourceLocation SL = TheCall->getBeginLoc(); 266 SourceManager &SM = S.getSourceManager(); 267 // If we're in an expansion of a macro whose name corresponds to this builtin, 268 // use the simple macro name and location. 269 if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) == 270 LikelyMacroName) { 271 FunctionName = LikelyMacroName; 272 SL = SM.getImmediateMacroCallerLoc(SL); 273 } 274 275 S.Diag(SL, diag::warn_memcpy_chk_overflow) 276 << FunctionName << DstSize.toString(/*Radix=*/10) 277 << Size.toString(/*Radix=*/10); 278 } 279 280 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 281 if (checkArgCount(S, BuiltinCall, 2)) 282 return true; 283 284 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 285 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 286 Expr *Call = BuiltinCall->getArg(0); 287 Expr *Chain = BuiltinCall->getArg(1); 288 289 if (Call->getStmtClass() != Stmt::CallExprClass) { 290 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 291 << Call->getSourceRange(); 292 return true; 293 } 294 295 auto CE = cast<CallExpr>(Call); 296 if (CE->getCallee()->getType()->isBlockPointerType()) { 297 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 298 << Call->getSourceRange(); 299 return true; 300 } 301 302 const Decl *TargetDecl = CE->getCalleeDecl(); 303 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 304 if (FD->getBuiltinID()) { 305 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 306 << Call->getSourceRange(); 307 return true; 308 } 309 310 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 311 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 312 << Call->getSourceRange(); 313 return true; 314 } 315 316 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 317 if (ChainResult.isInvalid()) 318 return true; 319 if (!ChainResult.get()->getType()->isPointerType()) { 320 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 321 << Chain->getSourceRange(); 322 return true; 323 } 324 325 QualType ReturnTy = CE->getCallReturnType(S.Context); 326 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 327 QualType BuiltinTy = S.Context.getFunctionType( 328 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 329 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 330 331 Builtin = 332 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 333 334 BuiltinCall->setType(CE->getType()); 335 BuiltinCall->setValueKind(CE->getValueKind()); 336 BuiltinCall->setObjectKind(CE->getObjectKind()); 337 BuiltinCall->setCallee(Builtin); 338 BuiltinCall->setArg(1, ChainResult.get()); 339 340 return false; 341 } 342 343 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 344 Scope::ScopeFlags NeededScopeFlags, 345 unsigned DiagID) { 346 // Scopes aren't available during instantiation. Fortunately, builtin 347 // functions cannot be template args so they cannot be formed through template 348 // instantiation. Therefore checking once during the parse is sufficient. 349 if (SemaRef.inTemplateInstantiation()) 350 return false; 351 352 Scope *S = SemaRef.getCurScope(); 353 while (S && !S->isSEHExceptScope()) 354 S = S->getParent(); 355 if (!S || !(S->getFlags() & NeededScopeFlags)) { 356 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 357 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 358 << DRE->getDecl()->getIdentifier(); 359 return true; 360 } 361 362 return false; 363 } 364 365 static inline bool isBlockPointer(Expr *Arg) { 366 return Arg->getType()->isBlockPointerType(); 367 } 368 369 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 370 /// void*, which is a requirement of device side enqueue. 371 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 372 const BlockPointerType *BPT = 373 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 374 ArrayRef<QualType> Params = 375 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 376 unsigned ArgCounter = 0; 377 bool IllegalParams = false; 378 // Iterate through the block parameters until either one is found that is not 379 // a local void*, or the block is valid. 380 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 381 I != E; ++I, ++ArgCounter) { 382 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 383 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 384 LangAS::opencl_local) { 385 // Get the location of the error. If a block literal has been passed 386 // (BlockExpr) then we can point straight to the offending argument, 387 // else we just point to the variable reference. 388 SourceLocation ErrorLoc; 389 if (isa<BlockExpr>(BlockArg)) { 390 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 391 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 392 } else if (isa<DeclRefExpr>(BlockArg)) { 393 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 394 } 395 S.Diag(ErrorLoc, 396 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 397 IllegalParams = true; 398 } 399 } 400 401 return IllegalParams; 402 } 403 404 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 405 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 406 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 407 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 408 return true; 409 } 410 return false; 411 } 412 413 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 414 if (checkArgCount(S, TheCall, 2)) 415 return true; 416 417 if (checkOpenCLSubgroupExt(S, TheCall)) 418 return true; 419 420 // First argument is an ndrange_t type. 421 Expr *NDRangeArg = TheCall->getArg(0); 422 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 423 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 424 << TheCall->getDirectCallee() << "'ndrange_t'"; 425 return true; 426 } 427 428 Expr *BlockArg = TheCall->getArg(1); 429 if (!isBlockPointer(BlockArg)) { 430 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 431 << TheCall->getDirectCallee() << "block"; 432 return true; 433 } 434 return checkOpenCLBlockArgs(S, BlockArg); 435 } 436 437 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 438 /// get_kernel_work_group_size 439 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 440 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 441 if (checkArgCount(S, TheCall, 1)) 442 return true; 443 444 Expr *BlockArg = TheCall->getArg(0); 445 if (!isBlockPointer(BlockArg)) { 446 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 447 << TheCall->getDirectCallee() << "block"; 448 return true; 449 } 450 return checkOpenCLBlockArgs(S, BlockArg); 451 } 452 453 /// Diagnose integer type and any valid implicit conversion to it. 454 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 455 const QualType &IntType); 456 457 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 458 unsigned Start, unsigned End) { 459 bool IllegalParams = false; 460 for (unsigned I = Start; I <= End; ++I) 461 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 462 S.Context.getSizeType()); 463 return IllegalParams; 464 } 465 466 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 467 /// 'local void*' parameter of passed block. 468 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 469 Expr *BlockArg, 470 unsigned NumNonVarArgs) { 471 const BlockPointerType *BPT = 472 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 473 unsigned NumBlockParams = 474 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 475 unsigned TotalNumArgs = TheCall->getNumArgs(); 476 477 // For each argument passed to the block, a corresponding uint needs to 478 // be passed to describe the size of the local memory. 479 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 480 S.Diag(TheCall->getBeginLoc(), 481 diag::err_opencl_enqueue_kernel_local_size_args); 482 return true; 483 } 484 485 // Check that the sizes of the local memory are specified by integers. 486 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 487 TotalNumArgs - 1); 488 } 489 490 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 491 /// overload formats specified in Table 6.13.17.1. 492 /// int enqueue_kernel(queue_t queue, 493 /// kernel_enqueue_flags_t flags, 494 /// const ndrange_t ndrange, 495 /// void (^block)(void)) 496 /// int enqueue_kernel(queue_t queue, 497 /// kernel_enqueue_flags_t flags, 498 /// const ndrange_t ndrange, 499 /// uint num_events_in_wait_list, 500 /// clk_event_t *event_wait_list, 501 /// clk_event_t *event_ret, 502 /// void (^block)(void)) 503 /// int enqueue_kernel(queue_t queue, 504 /// kernel_enqueue_flags_t flags, 505 /// const ndrange_t ndrange, 506 /// void (^block)(local void*, ...), 507 /// uint size0, ...) 508 /// int enqueue_kernel(queue_t queue, 509 /// kernel_enqueue_flags_t flags, 510 /// const ndrange_t ndrange, 511 /// uint num_events_in_wait_list, 512 /// clk_event_t *event_wait_list, 513 /// clk_event_t *event_ret, 514 /// void (^block)(local void*, ...), 515 /// uint size0, ...) 516 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 517 unsigned NumArgs = TheCall->getNumArgs(); 518 519 if (NumArgs < 4) { 520 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args); 521 return true; 522 } 523 524 Expr *Arg0 = TheCall->getArg(0); 525 Expr *Arg1 = TheCall->getArg(1); 526 Expr *Arg2 = TheCall->getArg(2); 527 Expr *Arg3 = TheCall->getArg(3); 528 529 // First argument always needs to be a queue_t type. 530 if (!Arg0->getType()->isQueueT()) { 531 S.Diag(TheCall->getArg(0)->getBeginLoc(), 532 diag::err_opencl_builtin_expected_type) 533 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 534 return true; 535 } 536 537 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 538 if (!Arg1->getType()->isIntegerType()) { 539 S.Diag(TheCall->getArg(1)->getBeginLoc(), 540 diag::err_opencl_builtin_expected_type) 541 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 542 return true; 543 } 544 545 // Third argument is always an ndrange_t type. 546 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 547 S.Diag(TheCall->getArg(2)->getBeginLoc(), 548 diag::err_opencl_builtin_expected_type) 549 << TheCall->getDirectCallee() << "'ndrange_t'"; 550 return true; 551 } 552 553 // With four arguments, there is only one form that the function could be 554 // called in: no events and no variable arguments. 555 if (NumArgs == 4) { 556 // check that the last argument is the right block type. 557 if (!isBlockPointer(Arg3)) { 558 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 559 << TheCall->getDirectCallee() << "block"; 560 return true; 561 } 562 // we have a block type, check the prototype 563 const BlockPointerType *BPT = 564 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 565 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 566 S.Diag(Arg3->getBeginLoc(), 567 diag::err_opencl_enqueue_kernel_blocks_no_args); 568 return true; 569 } 570 return false; 571 } 572 // we can have block + varargs. 573 if (isBlockPointer(Arg3)) 574 return (checkOpenCLBlockArgs(S, Arg3) || 575 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 576 // last two cases with either exactly 7 args or 7 args and varargs. 577 if (NumArgs >= 7) { 578 // check common block argument. 579 Expr *Arg6 = TheCall->getArg(6); 580 if (!isBlockPointer(Arg6)) { 581 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 582 << TheCall->getDirectCallee() << "block"; 583 return true; 584 } 585 if (checkOpenCLBlockArgs(S, Arg6)) 586 return true; 587 588 // Forth argument has to be any integer type. 589 if (!Arg3->getType()->isIntegerType()) { 590 S.Diag(TheCall->getArg(3)->getBeginLoc(), 591 diag::err_opencl_builtin_expected_type) 592 << TheCall->getDirectCallee() << "integer"; 593 return true; 594 } 595 // check remaining common arguments. 596 Expr *Arg4 = TheCall->getArg(4); 597 Expr *Arg5 = TheCall->getArg(5); 598 599 // Fifth argument is always passed as a pointer to clk_event_t. 600 if (!Arg4->isNullPointerConstant(S.Context, 601 Expr::NPC_ValueDependentIsNotNull) && 602 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 603 S.Diag(TheCall->getArg(4)->getBeginLoc(), 604 diag::err_opencl_builtin_expected_type) 605 << TheCall->getDirectCallee() 606 << S.Context.getPointerType(S.Context.OCLClkEventTy); 607 return true; 608 } 609 610 // Sixth argument is always passed as a pointer to clk_event_t. 611 if (!Arg5->isNullPointerConstant(S.Context, 612 Expr::NPC_ValueDependentIsNotNull) && 613 !(Arg5->getType()->isPointerType() && 614 Arg5->getType()->getPointeeType()->isClkEventT())) { 615 S.Diag(TheCall->getArg(5)->getBeginLoc(), 616 diag::err_opencl_builtin_expected_type) 617 << TheCall->getDirectCallee() 618 << S.Context.getPointerType(S.Context.OCLClkEventTy); 619 return true; 620 } 621 622 if (NumArgs == 7) 623 return false; 624 625 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 626 } 627 628 // None of the specific case has been detected, give generic error 629 S.Diag(TheCall->getBeginLoc(), 630 diag::err_opencl_enqueue_kernel_incorrect_args); 631 return true; 632 } 633 634 /// Returns OpenCL access qual. 635 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 636 return D->getAttr<OpenCLAccessAttr>(); 637 } 638 639 /// Returns true if pipe element type is different from the pointer. 640 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 641 const Expr *Arg0 = Call->getArg(0); 642 // First argument type should always be pipe. 643 if (!Arg0->getType()->isPipeType()) { 644 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 645 << Call->getDirectCallee() << Arg0->getSourceRange(); 646 return true; 647 } 648 OpenCLAccessAttr *AccessQual = 649 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 650 // Validates the access qualifier is compatible with the call. 651 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 652 // read_only and write_only, and assumed to be read_only if no qualifier is 653 // specified. 654 switch (Call->getDirectCallee()->getBuiltinID()) { 655 case Builtin::BIread_pipe: 656 case Builtin::BIreserve_read_pipe: 657 case Builtin::BIcommit_read_pipe: 658 case Builtin::BIwork_group_reserve_read_pipe: 659 case Builtin::BIsub_group_reserve_read_pipe: 660 case Builtin::BIwork_group_commit_read_pipe: 661 case Builtin::BIsub_group_commit_read_pipe: 662 if (!(!AccessQual || AccessQual->isReadOnly())) { 663 S.Diag(Arg0->getBeginLoc(), 664 diag::err_opencl_builtin_pipe_invalid_access_modifier) 665 << "read_only" << Arg0->getSourceRange(); 666 return true; 667 } 668 break; 669 case Builtin::BIwrite_pipe: 670 case Builtin::BIreserve_write_pipe: 671 case Builtin::BIcommit_write_pipe: 672 case Builtin::BIwork_group_reserve_write_pipe: 673 case Builtin::BIsub_group_reserve_write_pipe: 674 case Builtin::BIwork_group_commit_write_pipe: 675 case Builtin::BIsub_group_commit_write_pipe: 676 if (!(AccessQual && AccessQual->isWriteOnly())) { 677 S.Diag(Arg0->getBeginLoc(), 678 diag::err_opencl_builtin_pipe_invalid_access_modifier) 679 << "write_only" << Arg0->getSourceRange(); 680 return true; 681 } 682 break; 683 default: 684 break; 685 } 686 return false; 687 } 688 689 /// Returns true if pipe element type is different from the pointer. 690 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 691 const Expr *Arg0 = Call->getArg(0); 692 const Expr *ArgIdx = Call->getArg(Idx); 693 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 694 const QualType EltTy = PipeTy->getElementType(); 695 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 696 // The Idx argument should be a pointer and the type of the pointer and 697 // the type of pipe element should also be the same. 698 if (!ArgTy || 699 !S.Context.hasSameType( 700 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 701 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 702 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 703 << ArgIdx->getType() << ArgIdx->getSourceRange(); 704 return true; 705 } 706 return false; 707 } 708 709 // Performs semantic analysis for the read/write_pipe call. 710 // \param S Reference to the semantic analyzer. 711 // \param Call A pointer to the builtin call. 712 // \return True if a semantic error has been found, false otherwise. 713 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 714 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 715 // functions have two forms. 716 switch (Call->getNumArgs()) { 717 case 2: 718 if (checkOpenCLPipeArg(S, Call)) 719 return true; 720 // The call with 2 arguments should be 721 // read/write_pipe(pipe T, T*). 722 // Check packet type T. 723 if (checkOpenCLPipePacketType(S, Call, 1)) 724 return true; 725 break; 726 727 case 4: { 728 if (checkOpenCLPipeArg(S, Call)) 729 return true; 730 // The call with 4 arguments should be 731 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 732 // Check reserve_id_t. 733 if (!Call->getArg(1)->getType()->isReserveIDT()) { 734 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 735 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 736 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 737 return true; 738 } 739 740 // Check the index. 741 const Expr *Arg2 = Call->getArg(2); 742 if (!Arg2->getType()->isIntegerType() && 743 !Arg2->getType()->isUnsignedIntegerType()) { 744 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 745 << Call->getDirectCallee() << S.Context.UnsignedIntTy 746 << Arg2->getType() << Arg2->getSourceRange(); 747 return true; 748 } 749 750 // Check packet type T. 751 if (checkOpenCLPipePacketType(S, Call, 3)) 752 return true; 753 } break; 754 default: 755 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 756 << Call->getDirectCallee() << Call->getSourceRange(); 757 return true; 758 } 759 760 return false; 761 } 762 763 // Performs a semantic analysis on the {work_group_/sub_group_ 764 // /_}reserve_{read/write}_pipe 765 // \param S Reference to the semantic analyzer. 766 // \param Call The call to the builtin function to be analyzed. 767 // \return True if a semantic error was found, false otherwise. 768 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 769 if (checkArgCount(S, Call, 2)) 770 return true; 771 772 if (checkOpenCLPipeArg(S, Call)) 773 return true; 774 775 // Check the reserve size. 776 if (!Call->getArg(1)->getType()->isIntegerType() && 777 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 778 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 779 << Call->getDirectCallee() << S.Context.UnsignedIntTy 780 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 781 return true; 782 } 783 784 // Since return type of reserve_read/write_pipe built-in function is 785 // reserve_id_t, which is not defined in the builtin def file , we used int 786 // as return type and need to override the return type of these functions. 787 Call->setType(S.Context.OCLReserveIDTy); 788 789 return false; 790 } 791 792 // Performs a semantic analysis on {work_group_/sub_group_ 793 // /_}commit_{read/write}_pipe 794 // \param S Reference to the semantic analyzer. 795 // \param Call The call to the builtin function to be analyzed. 796 // \return True if a semantic error was found, false otherwise. 797 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 798 if (checkArgCount(S, Call, 2)) 799 return true; 800 801 if (checkOpenCLPipeArg(S, Call)) 802 return true; 803 804 // Check reserve_id_t. 805 if (!Call->getArg(1)->getType()->isReserveIDT()) { 806 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 807 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 808 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 809 return true; 810 } 811 812 return false; 813 } 814 815 // Performs a semantic analysis on the call to built-in Pipe 816 // Query Functions. 817 // \param S Reference to the semantic analyzer. 818 // \param Call The call to the builtin function to be analyzed. 819 // \return True if a semantic error was found, false otherwise. 820 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 821 if (checkArgCount(S, Call, 1)) 822 return true; 823 824 if (!Call->getArg(0)->getType()->isPipeType()) { 825 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 826 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 827 return true; 828 } 829 830 return false; 831 } 832 833 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 834 // Performs semantic analysis for the to_global/local/private call. 835 // \param S Reference to the semantic analyzer. 836 // \param BuiltinID ID of the builtin function. 837 // \param Call A pointer to the builtin call. 838 // \return True if a semantic error has been found, false otherwise. 839 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 840 CallExpr *Call) { 841 if (Call->getNumArgs() != 1) { 842 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 843 << Call->getDirectCallee() << Call->getSourceRange(); 844 return true; 845 } 846 847 auto RT = Call->getArg(0)->getType(); 848 if (!RT->isPointerType() || RT->getPointeeType() 849 .getAddressSpace() == LangAS::opencl_constant) { 850 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 851 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 852 return true; 853 } 854 855 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 856 S.Diag(Call->getArg(0)->getBeginLoc(), 857 diag::warn_opencl_generic_address_space_arg) 858 << Call->getDirectCallee()->getNameInfo().getAsString() 859 << Call->getArg(0)->getSourceRange(); 860 } 861 862 RT = RT->getPointeeType(); 863 auto Qual = RT.getQualifiers(); 864 switch (BuiltinID) { 865 case Builtin::BIto_global: 866 Qual.setAddressSpace(LangAS::opencl_global); 867 break; 868 case Builtin::BIto_local: 869 Qual.setAddressSpace(LangAS::opencl_local); 870 break; 871 case Builtin::BIto_private: 872 Qual.setAddressSpace(LangAS::opencl_private); 873 break; 874 default: 875 llvm_unreachable("Invalid builtin function"); 876 } 877 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 878 RT.getUnqualifiedType(), Qual))); 879 880 return false; 881 } 882 883 // Emit an error and return true if the current architecture is not in the list 884 // of supported architectures. 885 static bool 886 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 887 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 888 llvm::Triple::ArchType CurArch = 889 S.getASTContext().getTargetInfo().getTriple().getArch(); 890 if (llvm::is_contained(SupportedArchs, CurArch)) 891 return false; 892 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 893 << TheCall->getSourceRange(); 894 return true; 895 } 896 897 ExprResult 898 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 899 CallExpr *TheCall) { 900 ExprResult TheCallResult(TheCall); 901 902 // Find out if any arguments are required to be integer constant expressions. 903 unsigned ICEArguments = 0; 904 ASTContext::GetBuiltinTypeError Error; 905 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 906 if (Error != ASTContext::GE_None) 907 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 908 909 // If any arguments are required to be ICE's, check and diagnose. 910 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 911 // Skip arguments not required to be ICE's. 912 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 913 914 llvm::APSInt Result; 915 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 916 return true; 917 ICEArguments &= ~(1 << ArgNo); 918 } 919 920 switch (BuiltinID) { 921 case Builtin::BI__builtin___CFStringMakeConstantString: 922 assert(TheCall->getNumArgs() == 1 && 923 "Wrong # arguments to builtin CFStringMakeConstantString"); 924 if (CheckObjCString(TheCall->getArg(0))) 925 return ExprError(); 926 break; 927 case Builtin::BI__builtin_ms_va_start: 928 case Builtin::BI__builtin_stdarg_start: 929 case Builtin::BI__builtin_va_start: 930 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 931 return ExprError(); 932 break; 933 case Builtin::BI__va_start: { 934 switch (Context.getTargetInfo().getTriple().getArch()) { 935 case llvm::Triple::aarch64: 936 case llvm::Triple::arm: 937 case llvm::Triple::thumb: 938 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 939 return ExprError(); 940 break; 941 default: 942 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 943 return ExprError(); 944 break; 945 } 946 break; 947 } 948 949 // The acquire, release, and no fence variants are ARM and AArch64 only. 950 case Builtin::BI_interlockedbittestandset_acq: 951 case Builtin::BI_interlockedbittestandset_rel: 952 case Builtin::BI_interlockedbittestandset_nf: 953 case Builtin::BI_interlockedbittestandreset_acq: 954 case Builtin::BI_interlockedbittestandreset_rel: 955 case Builtin::BI_interlockedbittestandreset_nf: 956 if (CheckBuiltinTargetSupport( 957 *this, BuiltinID, TheCall, 958 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 959 return ExprError(); 960 break; 961 962 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 963 case Builtin::BI_bittest64: 964 case Builtin::BI_bittestandcomplement64: 965 case Builtin::BI_bittestandreset64: 966 case Builtin::BI_bittestandset64: 967 case Builtin::BI_interlockedbittestandreset64: 968 case Builtin::BI_interlockedbittestandset64: 969 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 970 {llvm::Triple::x86_64, llvm::Triple::arm, 971 llvm::Triple::thumb, llvm::Triple::aarch64})) 972 return ExprError(); 973 break; 974 975 case Builtin::BI__builtin_isgreater: 976 case Builtin::BI__builtin_isgreaterequal: 977 case Builtin::BI__builtin_isless: 978 case Builtin::BI__builtin_islessequal: 979 case Builtin::BI__builtin_islessgreater: 980 case Builtin::BI__builtin_isunordered: 981 if (SemaBuiltinUnorderedCompare(TheCall)) 982 return ExprError(); 983 break; 984 case Builtin::BI__builtin_fpclassify: 985 if (SemaBuiltinFPClassification(TheCall, 6)) 986 return ExprError(); 987 break; 988 case Builtin::BI__builtin_isfinite: 989 case Builtin::BI__builtin_isinf: 990 case Builtin::BI__builtin_isinf_sign: 991 case Builtin::BI__builtin_isnan: 992 case Builtin::BI__builtin_isnormal: 993 case Builtin::BI__builtin_signbit: 994 case Builtin::BI__builtin_signbitf: 995 case Builtin::BI__builtin_signbitl: 996 if (SemaBuiltinFPClassification(TheCall, 1)) 997 return ExprError(); 998 break; 999 case Builtin::BI__builtin_shufflevector: 1000 return SemaBuiltinShuffleVector(TheCall); 1001 // TheCall will be freed by the smart pointer here, but that's fine, since 1002 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1003 case Builtin::BI__builtin_prefetch: 1004 if (SemaBuiltinPrefetch(TheCall)) 1005 return ExprError(); 1006 break; 1007 case Builtin::BI__builtin_alloca_with_align: 1008 if (SemaBuiltinAllocaWithAlign(TheCall)) 1009 return ExprError(); 1010 break; 1011 case Builtin::BI__assume: 1012 case Builtin::BI__builtin_assume: 1013 if (SemaBuiltinAssume(TheCall)) 1014 return ExprError(); 1015 break; 1016 case Builtin::BI__builtin_assume_aligned: 1017 if (SemaBuiltinAssumeAligned(TheCall)) 1018 return ExprError(); 1019 break; 1020 case Builtin::BI__builtin_object_size: 1021 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1022 return ExprError(); 1023 break; 1024 case Builtin::BI__builtin_longjmp: 1025 if (SemaBuiltinLongjmp(TheCall)) 1026 return ExprError(); 1027 break; 1028 case Builtin::BI__builtin_setjmp: 1029 if (SemaBuiltinSetjmp(TheCall)) 1030 return ExprError(); 1031 break; 1032 case Builtin::BI_setjmp: 1033 case Builtin::BI_setjmpex: 1034 if (checkArgCount(*this, TheCall, 1)) 1035 return true; 1036 break; 1037 case Builtin::BI__builtin_classify_type: 1038 if (checkArgCount(*this, TheCall, 1)) return true; 1039 TheCall->setType(Context.IntTy); 1040 break; 1041 case Builtin::BI__builtin_constant_p: 1042 if (checkArgCount(*this, TheCall, 1)) return true; 1043 TheCall->setType(Context.IntTy); 1044 break; 1045 case Builtin::BI__sync_fetch_and_add: 1046 case Builtin::BI__sync_fetch_and_add_1: 1047 case Builtin::BI__sync_fetch_and_add_2: 1048 case Builtin::BI__sync_fetch_and_add_4: 1049 case Builtin::BI__sync_fetch_and_add_8: 1050 case Builtin::BI__sync_fetch_and_add_16: 1051 case Builtin::BI__sync_fetch_and_sub: 1052 case Builtin::BI__sync_fetch_and_sub_1: 1053 case Builtin::BI__sync_fetch_and_sub_2: 1054 case Builtin::BI__sync_fetch_and_sub_4: 1055 case Builtin::BI__sync_fetch_and_sub_8: 1056 case Builtin::BI__sync_fetch_and_sub_16: 1057 case Builtin::BI__sync_fetch_and_or: 1058 case Builtin::BI__sync_fetch_and_or_1: 1059 case Builtin::BI__sync_fetch_and_or_2: 1060 case Builtin::BI__sync_fetch_and_or_4: 1061 case Builtin::BI__sync_fetch_and_or_8: 1062 case Builtin::BI__sync_fetch_and_or_16: 1063 case Builtin::BI__sync_fetch_and_and: 1064 case Builtin::BI__sync_fetch_and_and_1: 1065 case Builtin::BI__sync_fetch_and_and_2: 1066 case Builtin::BI__sync_fetch_and_and_4: 1067 case Builtin::BI__sync_fetch_and_and_8: 1068 case Builtin::BI__sync_fetch_and_and_16: 1069 case Builtin::BI__sync_fetch_and_xor: 1070 case Builtin::BI__sync_fetch_and_xor_1: 1071 case Builtin::BI__sync_fetch_and_xor_2: 1072 case Builtin::BI__sync_fetch_and_xor_4: 1073 case Builtin::BI__sync_fetch_and_xor_8: 1074 case Builtin::BI__sync_fetch_and_xor_16: 1075 case Builtin::BI__sync_fetch_and_nand: 1076 case Builtin::BI__sync_fetch_and_nand_1: 1077 case Builtin::BI__sync_fetch_and_nand_2: 1078 case Builtin::BI__sync_fetch_and_nand_4: 1079 case Builtin::BI__sync_fetch_and_nand_8: 1080 case Builtin::BI__sync_fetch_and_nand_16: 1081 case Builtin::BI__sync_add_and_fetch: 1082 case Builtin::BI__sync_add_and_fetch_1: 1083 case Builtin::BI__sync_add_and_fetch_2: 1084 case Builtin::BI__sync_add_and_fetch_4: 1085 case Builtin::BI__sync_add_and_fetch_8: 1086 case Builtin::BI__sync_add_and_fetch_16: 1087 case Builtin::BI__sync_sub_and_fetch: 1088 case Builtin::BI__sync_sub_and_fetch_1: 1089 case Builtin::BI__sync_sub_and_fetch_2: 1090 case Builtin::BI__sync_sub_and_fetch_4: 1091 case Builtin::BI__sync_sub_and_fetch_8: 1092 case Builtin::BI__sync_sub_and_fetch_16: 1093 case Builtin::BI__sync_and_and_fetch: 1094 case Builtin::BI__sync_and_and_fetch_1: 1095 case Builtin::BI__sync_and_and_fetch_2: 1096 case Builtin::BI__sync_and_and_fetch_4: 1097 case Builtin::BI__sync_and_and_fetch_8: 1098 case Builtin::BI__sync_and_and_fetch_16: 1099 case Builtin::BI__sync_or_and_fetch: 1100 case Builtin::BI__sync_or_and_fetch_1: 1101 case Builtin::BI__sync_or_and_fetch_2: 1102 case Builtin::BI__sync_or_and_fetch_4: 1103 case Builtin::BI__sync_or_and_fetch_8: 1104 case Builtin::BI__sync_or_and_fetch_16: 1105 case Builtin::BI__sync_xor_and_fetch: 1106 case Builtin::BI__sync_xor_and_fetch_1: 1107 case Builtin::BI__sync_xor_and_fetch_2: 1108 case Builtin::BI__sync_xor_and_fetch_4: 1109 case Builtin::BI__sync_xor_and_fetch_8: 1110 case Builtin::BI__sync_xor_and_fetch_16: 1111 case Builtin::BI__sync_nand_and_fetch: 1112 case Builtin::BI__sync_nand_and_fetch_1: 1113 case Builtin::BI__sync_nand_and_fetch_2: 1114 case Builtin::BI__sync_nand_and_fetch_4: 1115 case Builtin::BI__sync_nand_and_fetch_8: 1116 case Builtin::BI__sync_nand_and_fetch_16: 1117 case Builtin::BI__sync_val_compare_and_swap: 1118 case Builtin::BI__sync_val_compare_and_swap_1: 1119 case Builtin::BI__sync_val_compare_and_swap_2: 1120 case Builtin::BI__sync_val_compare_and_swap_4: 1121 case Builtin::BI__sync_val_compare_and_swap_8: 1122 case Builtin::BI__sync_val_compare_and_swap_16: 1123 case Builtin::BI__sync_bool_compare_and_swap: 1124 case Builtin::BI__sync_bool_compare_and_swap_1: 1125 case Builtin::BI__sync_bool_compare_and_swap_2: 1126 case Builtin::BI__sync_bool_compare_and_swap_4: 1127 case Builtin::BI__sync_bool_compare_and_swap_8: 1128 case Builtin::BI__sync_bool_compare_and_swap_16: 1129 case Builtin::BI__sync_lock_test_and_set: 1130 case Builtin::BI__sync_lock_test_and_set_1: 1131 case Builtin::BI__sync_lock_test_and_set_2: 1132 case Builtin::BI__sync_lock_test_and_set_4: 1133 case Builtin::BI__sync_lock_test_and_set_8: 1134 case Builtin::BI__sync_lock_test_and_set_16: 1135 case Builtin::BI__sync_lock_release: 1136 case Builtin::BI__sync_lock_release_1: 1137 case Builtin::BI__sync_lock_release_2: 1138 case Builtin::BI__sync_lock_release_4: 1139 case Builtin::BI__sync_lock_release_8: 1140 case Builtin::BI__sync_lock_release_16: 1141 case Builtin::BI__sync_swap: 1142 case Builtin::BI__sync_swap_1: 1143 case Builtin::BI__sync_swap_2: 1144 case Builtin::BI__sync_swap_4: 1145 case Builtin::BI__sync_swap_8: 1146 case Builtin::BI__sync_swap_16: 1147 return SemaBuiltinAtomicOverloaded(TheCallResult); 1148 case Builtin::BI__sync_synchronize: 1149 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1150 << TheCall->getCallee()->getSourceRange(); 1151 break; 1152 case Builtin::BI__builtin_nontemporal_load: 1153 case Builtin::BI__builtin_nontemporal_store: 1154 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1155 #define BUILTIN(ID, TYPE, ATTRS) 1156 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1157 case Builtin::BI##ID: \ 1158 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1159 #include "clang/Basic/Builtins.def" 1160 case Builtin::BI__annotation: 1161 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1162 return ExprError(); 1163 break; 1164 case Builtin::BI__builtin_annotation: 1165 if (SemaBuiltinAnnotation(*this, TheCall)) 1166 return ExprError(); 1167 break; 1168 case Builtin::BI__builtin_addressof: 1169 if (SemaBuiltinAddressof(*this, TheCall)) 1170 return ExprError(); 1171 break; 1172 case Builtin::BI__builtin_add_overflow: 1173 case Builtin::BI__builtin_sub_overflow: 1174 case Builtin::BI__builtin_mul_overflow: 1175 if (SemaBuiltinOverflow(*this, TheCall)) 1176 return ExprError(); 1177 break; 1178 case Builtin::BI__builtin_operator_new: 1179 case Builtin::BI__builtin_operator_delete: { 1180 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1181 ExprResult Res = 1182 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1183 if (Res.isInvalid()) 1184 CorrectDelayedTyposInExpr(TheCallResult.get()); 1185 return Res; 1186 } 1187 case Builtin::BI__builtin_dump_struct: { 1188 // We first want to ensure we are called with 2 arguments 1189 if (checkArgCount(*this, TheCall, 2)) 1190 return ExprError(); 1191 // Ensure that the first argument is of type 'struct XX *' 1192 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1193 const QualType PtrArgType = PtrArg->getType(); 1194 if (!PtrArgType->isPointerType() || 1195 !PtrArgType->getPointeeType()->isRecordType()) { 1196 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1197 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1198 << "structure pointer"; 1199 return ExprError(); 1200 } 1201 1202 // Ensure that the second argument is of type 'FunctionType' 1203 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1204 const QualType FnPtrArgType = FnPtrArg->getType(); 1205 if (!FnPtrArgType->isPointerType()) { 1206 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1207 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1208 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1209 return ExprError(); 1210 } 1211 1212 const auto *FuncType = 1213 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1214 1215 if (!FuncType) { 1216 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1217 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1218 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1219 return ExprError(); 1220 } 1221 1222 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1223 if (!FT->getNumParams()) { 1224 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1225 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1226 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1227 return ExprError(); 1228 } 1229 QualType PT = FT->getParamType(0); 1230 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1231 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1232 !PT->getPointeeType().isConstQualified()) { 1233 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1234 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1235 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1236 return ExprError(); 1237 } 1238 } 1239 1240 TheCall->setType(Context.IntTy); 1241 break; 1242 } 1243 1244 // check secure string manipulation functions where overflows 1245 // are detectable at compile time 1246 case Builtin::BI__builtin___memcpy_chk: 1247 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy"); 1248 break; 1249 case Builtin::BI__builtin___memmove_chk: 1250 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove"); 1251 break; 1252 case Builtin::BI__builtin___memset_chk: 1253 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset"); 1254 break; 1255 case Builtin::BI__builtin___strlcat_chk: 1256 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat"); 1257 break; 1258 case Builtin::BI__builtin___strlcpy_chk: 1259 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy"); 1260 break; 1261 case Builtin::BI__builtin___strncat_chk: 1262 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat"); 1263 break; 1264 case Builtin::BI__builtin___strncpy_chk: 1265 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy"); 1266 break; 1267 case Builtin::BI__builtin___stpncpy_chk: 1268 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy"); 1269 break; 1270 case Builtin::BI__builtin___memccpy_chk: 1271 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy"); 1272 break; 1273 case Builtin::BI__builtin___snprintf_chk: 1274 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf"); 1275 break; 1276 case Builtin::BI__builtin___vsnprintf_chk: 1277 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf"); 1278 break; 1279 case Builtin::BI__builtin_call_with_static_chain: 1280 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1281 return ExprError(); 1282 break; 1283 case Builtin::BI__exception_code: 1284 case Builtin::BI_exception_code: 1285 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1286 diag::err_seh___except_block)) 1287 return ExprError(); 1288 break; 1289 case Builtin::BI__exception_info: 1290 case Builtin::BI_exception_info: 1291 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1292 diag::err_seh___except_filter)) 1293 return ExprError(); 1294 break; 1295 case Builtin::BI__GetExceptionInfo: 1296 if (checkArgCount(*this, TheCall, 1)) 1297 return ExprError(); 1298 1299 if (CheckCXXThrowOperand( 1300 TheCall->getBeginLoc(), 1301 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1302 TheCall)) 1303 return ExprError(); 1304 1305 TheCall->setType(Context.VoidPtrTy); 1306 break; 1307 // OpenCL v2.0, s6.13.16 - Pipe functions 1308 case Builtin::BIread_pipe: 1309 case Builtin::BIwrite_pipe: 1310 // Since those two functions are declared with var args, we need a semantic 1311 // check for the argument. 1312 if (SemaBuiltinRWPipe(*this, TheCall)) 1313 return ExprError(); 1314 break; 1315 case Builtin::BIreserve_read_pipe: 1316 case Builtin::BIreserve_write_pipe: 1317 case Builtin::BIwork_group_reserve_read_pipe: 1318 case Builtin::BIwork_group_reserve_write_pipe: 1319 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1320 return ExprError(); 1321 break; 1322 case Builtin::BIsub_group_reserve_read_pipe: 1323 case Builtin::BIsub_group_reserve_write_pipe: 1324 if (checkOpenCLSubgroupExt(*this, TheCall) || 1325 SemaBuiltinReserveRWPipe(*this, TheCall)) 1326 return ExprError(); 1327 break; 1328 case Builtin::BIcommit_read_pipe: 1329 case Builtin::BIcommit_write_pipe: 1330 case Builtin::BIwork_group_commit_read_pipe: 1331 case Builtin::BIwork_group_commit_write_pipe: 1332 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1333 return ExprError(); 1334 break; 1335 case Builtin::BIsub_group_commit_read_pipe: 1336 case Builtin::BIsub_group_commit_write_pipe: 1337 if (checkOpenCLSubgroupExt(*this, TheCall) || 1338 SemaBuiltinCommitRWPipe(*this, TheCall)) 1339 return ExprError(); 1340 break; 1341 case Builtin::BIget_pipe_num_packets: 1342 case Builtin::BIget_pipe_max_packets: 1343 if (SemaBuiltinPipePackets(*this, TheCall)) 1344 return ExprError(); 1345 break; 1346 case Builtin::BIto_global: 1347 case Builtin::BIto_local: 1348 case Builtin::BIto_private: 1349 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1350 return ExprError(); 1351 break; 1352 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1353 case Builtin::BIenqueue_kernel: 1354 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1355 return ExprError(); 1356 break; 1357 case Builtin::BIget_kernel_work_group_size: 1358 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1359 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1360 return ExprError(); 1361 break; 1362 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1363 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1364 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1365 return ExprError(); 1366 break; 1367 case Builtin::BI__builtin_os_log_format: 1368 case Builtin::BI__builtin_os_log_format_buffer_size: 1369 if (SemaBuiltinOSLogFormat(TheCall)) 1370 return ExprError(); 1371 break; 1372 } 1373 1374 // Since the target specific builtins for each arch overlap, only check those 1375 // of the arch we are compiling for. 1376 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1377 switch (Context.getTargetInfo().getTriple().getArch()) { 1378 case llvm::Triple::arm: 1379 case llvm::Triple::armeb: 1380 case llvm::Triple::thumb: 1381 case llvm::Triple::thumbeb: 1382 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1383 return ExprError(); 1384 break; 1385 case llvm::Triple::aarch64: 1386 case llvm::Triple::aarch64_be: 1387 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1388 return ExprError(); 1389 break; 1390 case llvm::Triple::hexagon: 1391 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1392 return ExprError(); 1393 break; 1394 case llvm::Triple::mips: 1395 case llvm::Triple::mipsel: 1396 case llvm::Triple::mips64: 1397 case llvm::Triple::mips64el: 1398 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1399 return ExprError(); 1400 break; 1401 case llvm::Triple::systemz: 1402 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1403 return ExprError(); 1404 break; 1405 case llvm::Triple::x86: 1406 case llvm::Triple::x86_64: 1407 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1408 return ExprError(); 1409 break; 1410 case llvm::Triple::ppc: 1411 case llvm::Triple::ppc64: 1412 case llvm::Triple::ppc64le: 1413 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1414 return ExprError(); 1415 break; 1416 default: 1417 break; 1418 } 1419 } 1420 1421 return TheCallResult; 1422 } 1423 1424 // Get the valid immediate range for the specified NEON type code. 1425 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1426 NeonTypeFlags Type(t); 1427 int IsQuad = ForceQuad ? true : Type.isQuad(); 1428 switch (Type.getEltType()) { 1429 case NeonTypeFlags::Int8: 1430 case NeonTypeFlags::Poly8: 1431 return shift ? 7 : (8 << IsQuad) - 1; 1432 case NeonTypeFlags::Int16: 1433 case NeonTypeFlags::Poly16: 1434 return shift ? 15 : (4 << IsQuad) - 1; 1435 case NeonTypeFlags::Int32: 1436 return shift ? 31 : (2 << IsQuad) - 1; 1437 case NeonTypeFlags::Int64: 1438 case NeonTypeFlags::Poly64: 1439 return shift ? 63 : (1 << IsQuad) - 1; 1440 case NeonTypeFlags::Poly128: 1441 return shift ? 127 : (1 << IsQuad) - 1; 1442 case NeonTypeFlags::Float16: 1443 assert(!shift && "cannot shift float types!"); 1444 return (4 << IsQuad) - 1; 1445 case NeonTypeFlags::Float32: 1446 assert(!shift && "cannot shift float types!"); 1447 return (2 << IsQuad) - 1; 1448 case NeonTypeFlags::Float64: 1449 assert(!shift && "cannot shift float types!"); 1450 return (1 << IsQuad) - 1; 1451 } 1452 llvm_unreachable("Invalid NeonTypeFlag!"); 1453 } 1454 1455 /// getNeonEltType - Return the QualType corresponding to the elements of 1456 /// the vector type specified by the NeonTypeFlags. This is used to check 1457 /// the pointer arguments for Neon load/store intrinsics. 1458 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1459 bool IsPolyUnsigned, bool IsInt64Long) { 1460 switch (Flags.getEltType()) { 1461 case NeonTypeFlags::Int8: 1462 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1463 case NeonTypeFlags::Int16: 1464 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1465 case NeonTypeFlags::Int32: 1466 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1467 case NeonTypeFlags::Int64: 1468 if (IsInt64Long) 1469 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1470 else 1471 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1472 : Context.LongLongTy; 1473 case NeonTypeFlags::Poly8: 1474 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1475 case NeonTypeFlags::Poly16: 1476 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1477 case NeonTypeFlags::Poly64: 1478 if (IsInt64Long) 1479 return Context.UnsignedLongTy; 1480 else 1481 return Context.UnsignedLongLongTy; 1482 case NeonTypeFlags::Poly128: 1483 break; 1484 case NeonTypeFlags::Float16: 1485 return Context.HalfTy; 1486 case NeonTypeFlags::Float32: 1487 return Context.FloatTy; 1488 case NeonTypeFlags::Float64: 1489 return Context.DoubleTy; 1490 } 1491 llvm_unreachable("Invalid NeonTypeFlag!"); 1492 } 1493 1494 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1495 llvm::APSInt Result; 1496 uint64_t mask = 0; 1497 unsigned TV = 0; 1498 int PtrArgNum = -1; 1499 bool HasConstPtr = false; 1500 switch (BuiltinID) { 1501 #define GET_NEON_OVERLOAD_CHECK 1502 #include "clang/Basic/arm_neon.inc" 1503 #include "clang/Basic/arm_fp16.inc" 1504 #undef GET_NEON_OVERLOAD_CHECK 1505 } 1506 1507 // For NEON intrinsics which are overloaded on vector element type, validate 1508 // the immediate which specifies which variant to emit. 1509 unsigned ImmArg = TheCall->getNumArgs()-1; 1510 if (mask) { 1511 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1512 return true; 1513 1514 TV = Result.getLimitedValue(64); 1515 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1516 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1517 << TheCall->getArg(ImmArg)->getSourceRange(); 1518 } 1519 1520 if (PtrArgNum >= 0) { 1521 // Check that pointer arguments have the specified type. 1522 Expr *Arg = TheCall->getArg(PtrArgNum); 1523 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1524 Arg = ICE->getSubExpr(); 1525 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1526 QualType RHSTy = RHS.get()->getType(); 1527 1528 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1529 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1530 Arch == llvm::Triple::aarch64_be; 1531 bool IsInt64Long = 1532 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1533 QualType EltTy = 1534 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1535 if (HasConstPtr) 1536 EltTy = EltTy.withConst(); 1537 QualType LHSTy = Context.getPointerType(EltTy); 1538 AssignConvertType ConvTy; 1539 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1540 if (RHS.isInvalid()) 1541 return true; 1542 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1543 RHS.get(), AA_Assigning)) 1544 return true; 1545 } 1546 1547 // For NEON intrinsics which take an immediate value as part of the 1548 // instruction, range check them here. 1549 unsigned i = 0, l = 0, u = 0; 1550 switch (BuiltinID) { 1551 default: 1552 return false; 1553 #define GET_NEON_IMMEDIATE_CHECK 1554 #include "clang/Basic/arm_neon.inc" 1555 #include "clang/Basic/arm_fp16.inc" 1556 #undef GET_NEON_IMMEDIATE_CHECK 1557 } 1558 1559 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1560 } 1561 1562 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1563 unsigned MaxWidth) { 1564 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1565 BuiltinID == ARM::BI__builtin_arm_ldaex || 1566 BuiltinID == ARM::BI__builtin_arm_strex || 1567 BuiltinID == ARM::BI__builtin_arm_stlex || 1568 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1569 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1570 BuiltinID == AArch64::BI__builtin_arm_strex || 1571 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1572 "unexpected ARM builtin"); 1573 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1574 BuiltinID == ARM::BI__builtin_arm_ldaex || 1575 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1576 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1577 1578 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1579 1580 // Ensure that we have the proper number of arguments. 1581 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1582 return true; 1583 1584 // Inspect the pointer argument of the atomic builtin. This should always be 1585 // a pointer type, whose element is an integral scalar or pointer type. 1586 // Because it is a pointer type, we don't have to worry about any implicit 1587 // casts here. 1588 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1589 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1590 if (PointerArgRes.isInvalid()) 1591 return true; 1592 PointerArg = PointerArgRes.get(); 1593 1594 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1595 if (!pointerType) { 1596 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1597 << PointerArg->getType() << PointerArg->getSourceRange(); 1598 return true; 1599 } 1600 1601 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1602 // task is to insert the appropriate casts into the AST. First work out just 1603 // what the appropriate type is. 1604 QualType ValType = pointerType->getPointeeType(); 1605 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1606 if (IsLdrex) 1607 AddrType.addConst(); 1608 1609 // Issue a warning if the cast is dodgy. 1610 CastKind CastNeeded = CK_NoOp; 1611 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1612 CastNeeded = CK_BitCast; 1613 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1614 << PointerArg->getType() << Context.getPointerType(AddrType) 1615 << AA_Passing << PointerArg->getSourceRange(); 1616 } 1617 1618 // Finally, do the cast and replace the argument with the corrected version. 1619 AddrType = Context.getPointerType(AddrType); 1620 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1621 if (PointerArgRes.isInvalid()) 1622 return true; 1623 PointerArg = PointerArgRes.get(); 1624 1625 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1626 1627 // In general, we allow ints, floats and pointers to be loaded and stored. 1628 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1629 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1630 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1631 << PointerArg->getType() << PointerArg->getSourceRange(); 1632 return true; 1633 } 1634 1635 // But ARM doesn't have instructions to deal with 128-bit versions. 1636 if (Context.getTypeSize(ValType) > MaxWidth) { 1637 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1638 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1639 << PointerArg->getType() << PointerArg->getSourceRange(); 1640 return true; 1641 } 1642 1643 switch (ValType.getObjCLifetime()) { 1644 case Qualifiers::OCL_None: 1645 case Qualifiers::OCL_ExplicitNone: 1646 // okay 1647 break; 1648 1649 case Qualifiers::OCL_Weak: 1650 case Qualifiers::OCL_Strong: 1651 case Qualifiers::OCL_Autoreleasing: 1652 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1653 << ValType << PointerArg->getSourceRange(); 1654 return true; 1655 } 1656 1657 if (IsLdrex) { 1658 TheCall->setType(ValType); 1659 return false; 1660 } 1661 1662 // Initialize the argument to be stored. 1663 ExprResult ValArg = TheCall->getArg(0); 1664 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1665 Context, ValType, /*consume*/ false); 1666 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1667 if (ValArg.isInvalid()) 1668 return true; 1669 TheCall->setArg(0, ValArg.get()); 1670 1671 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1672 // but the custom checker bypasses all default analysis. 1673 TheCall->setType(Context.IntTy); 1674 return false; 1675 } 1676 1677 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1678 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1679 BuiltinID == ARM::BI__builtin_arm_ldaex || 1680 BuiltinID == ARM::BI__builtin_arm_strex || 1681 BuiltinID == ARM::BI__builtin_arm_stlex) { 1682 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1683 } 1684 1685 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1686 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1687 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1688 } 1689 1690 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1691 BuiltinID == ARM::BI__builtin_arm_wsr64) 1692 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1693 1694 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1695 BuiltinID == ARM::BI__builtin_arm_rsrp || 1696 BuiltinID == ARM::BI__builtin_arm_wsr || 1697 BuiltinID == ARM::BI__builtin_arm_wsrp) 1698 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1699 1700 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1701 return true; 1702 1703 // For intrinsics which take an immediate value as part of the instruction, 1704 // range check them here. 1705 // FIXME: VFP Intrinsics should error if VFP not present. 1706 switch (BuiltinID) { 1707 default: return false; 1708 case ARM::BI__builtin_arm_ssat: 1709 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1710 case ARM::BI__builtin_arm_usat: 1711 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1712 case ARM::BI__builtin_arm_ssat16: 1713 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1714 case ARM::BI__builtin_arm_usat16: 1715 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1716 case ARM::BI__builtin_arm_vcvtr_f: 1717 case ARM::BI__builtin_arm_vcvtr_d: 1718 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1719 case ARM::BI__builtin_arm_dmb: 1720 case ARM::BI__builtin_arm_dsb: 1721 case ARM::BI__builtin_arm_isb: 1722 case ARM::BI__builtin_arm_dbg: 1723 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1724 } 1725 } 1726 1727 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1728 CallExpr *TheCall) { 1729 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1730 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1731 BuiltinID == AArch64::BI__builtin_arm_strex || 1732 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1733 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1734 } 1735 1736 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1737 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1738 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1739 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1740 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1741 } 1742 1743 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1744 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1745 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1746 1747 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1748 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1749 BuiltinID == AArch64::BI__builtin_arm_wsr || 1750 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1751 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1752 1753 // Only check the valid encoding range. Any constant in this range would be 1754 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 1755 // an exception for incorrect registers. This matches MSVC behavior. 1756 if (BuiltinID == AArch64::BI_ReadStatusReg || 1757 BuiltinID == AArch64::BI_WriteStatusReg) 1758 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 1759 1760 if (BuiltinID == AArch64::BI__getReg) 1761 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1762 1763 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1764 return true; 1765 1766 // For intrinsics which take an immediate value as part of the instruction, 1767 // range check them here. 1768 unsigned i = 0, l = 0, u = 0; 1769 switch (BuiltinID) { 1770 default: return false; 1771 case AArch64::BI__builtin_arm_dmb: 1772 case AArch64::BI__builtin_arm_dsb: 1773 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1774 } 1775 1776 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1777 } 1778 1779 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1780 struct BuiltinAndString { 1781 unsigned BuiltinID; 1782 const char *Str; 1783 }; 1784 1785 static BuiltinAndString ValidCPU[] = { 1786 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65" }, 1787 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65" }, 1788 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65" }, 1789 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65" }, 1790 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65" }, 1791 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65" }, 1792 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65" }, 1793 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65" }, 1794 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65" }, 1795 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65" }, 1796 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65" }, 1797 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65" }, 1798 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65" }, 1799 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65" }, 1800 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65" }, 1801 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65" }, 1802 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65" }, 1803 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65" }, 1804 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65" }, 1805 }; 1806 1807 static BuiltinAndString ValidHVX[] = { 1808 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65" }, 1809 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65" }, 1810 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65" }, 1811 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65" }, 1812 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65" }, 1813 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65" }, 1814 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65" }, 1815 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65" }, 1816 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65" }, 1817 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65" }, 1818 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65" }, 1819 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65" }, 1820 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65" }, 1821 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65" }, 1822 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65" }, 1823 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65" }, 1824 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65" }, 1825 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65" }, 1826 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65" }, 1827 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65" }, 1828 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65" }, 1829 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65" }, 1830 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65" }, 1831 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65" }, 1832 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65" }, 1833 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65" }, 1834 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65" }, 1835 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65" }, 1836 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65" }, 1837 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65" }, 1838 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65" }, 1839 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65" }, 1840 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65" }, 1841 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65" }, 1842 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65" }, 1843 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65" }, 1844 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65" }, 1845 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65" }, 1846 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65" }, 1847 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65" }, 1848 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65" }, 1849 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65" }, 1850 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65" }, 1851 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65" }, 1852 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65" }, 1853 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65" }, 1854 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65" }, 1855 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65" }, 1856 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65" }, 1857 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65" }, 1858 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65" }, 1859 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65" }, 1860 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65" }, 1861 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65" }, 1862 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65" }, 1863 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65" }, 1864 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65" }, 1865 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65" }, 1866 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65" }, 1867 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65" }, 1868 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65" }, 1869 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65" }, 1870 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65" }, 1871 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65" }, 1872 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65" }, 1873 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65" }, 1874 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65" }, 1875 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65" }, 1876 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65" }, 1877 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65" }, 1878 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65" }, 1879 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65" }, 1880 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65" }, 1881 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65" }, 1882 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65" }, 1883 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65" }, 1884 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65" }, 1885 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65" }, 1886 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65" }, 1887 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65" }, 1888 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65" }, 1889 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65" }, 1890 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65" }, 1891 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65" }, 1892 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65" }, 1893 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65" }, 1894 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65" }, 1895 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65" }, 1896 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65" }, 1897 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65" }, 1898 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65" }, 1899 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65" }, 1900 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65" }, 1901 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65" }, 1902 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65" }, 1903 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65" }, 1904 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65" }, 1905 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65" }, 1906 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65" }, 1907 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65" }, 1908 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65" }, 1909 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65" }, 1910 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65" }, 1911 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65" }, 1912 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65" }, 1913 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65" }, 1914 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65" }, 1915 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65" }, 1916 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65" }, 1917 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65" }, 1918 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65" }, 1919 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65" }, 1920 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65" }, 1921 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65" }, 1922 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65" }, 1923 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65" }, 1924 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65" }, 1925 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65" }, 1926 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65" }, 1927 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65" }, 1928 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65" }, 1929 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65" }, 1930 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65" }, 1931 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65" }, 1932 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65" }, 1933 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65" }, 1934 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65" }, 1935 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65" }, 1936 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65" }, 1937 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65" }, 1938 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65" }, 1939 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65" }, 1940 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65" }, 1941 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65" }, 1942 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65" }, 1943 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65" }, 1944 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65" }, 1945 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65" }, 1946 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65" }, 1947 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65" }, 1948 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65" }, 1949 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65" }, 1950 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65" }, 1951 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65" }, 1952 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65" }, 1953 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65" }, 1954 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65" }, 1955 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65" }, 1956 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65" }, 1957 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65" }, 1958 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65" }, 1959 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65" }, 1960 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65" }, 1961 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65" }, 1962 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65" }, 1963 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65" }, 1964 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65" }, 1965 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65" }, 1966 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65" }, 1967 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65" }, 1968 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65" }, 1969 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65" }, 1970 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65" }, 1971 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65" }, 1972 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65" }, 1973 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65" }, 1974 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65" }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65" }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65" }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65" }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65" }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65" }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65" }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65" }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65" }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65" }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65" }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65" }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65" }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65" }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65" }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65" }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65" }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65" }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65" }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65" }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65" }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65" }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65" }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65" }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65" }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65" }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65" }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65" }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65" }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65" }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65" }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65" }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65" }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65" }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65" }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65" }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65" }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65" }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65" }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65" }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65" }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65" }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65" }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65" }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65" }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65" }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65" }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65" }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65" }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65" }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65" }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65" }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65" }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65" }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65" }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65" }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65" }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65" }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65" }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65" }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65" }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65" }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65" }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65" }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65" }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65" }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65" }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65" }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65" }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65" }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65" }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65" }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65" }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65" }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65" }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65" }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65" }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65" }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65" }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65" }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65" }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65" }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65" }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65" }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65" }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65" }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65" }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65" }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65" }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65" }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65" }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65" }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65" }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65" }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65" }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65" }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65" }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65" }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65" }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65" }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65" }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65" }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65" }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65" }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65" }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65" }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65" }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65" }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65" }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65" }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65" }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65" }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65" }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65" }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65" }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65" }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65" }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65" }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65" }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65" }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65" }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65" }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65" }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65" }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65" }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65" }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65" }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65" }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65" }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65" }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65" }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65" }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65" }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65" }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65" }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65" }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65" }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65" }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65" }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65" }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65" }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65" }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65" }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65" }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65" }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65" }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65" }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65" }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65" }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65" }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65" }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65" }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65" }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65" }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65" }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65" }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65" }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65" }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65" }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65" }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65" }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65" }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65" }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65" }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65" }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65" }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65" }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65" }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65" }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65" }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65" }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65" }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65" }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65" }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65" }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65" }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65" }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65" }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65" }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65" }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65" }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65" }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65" }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65" }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65" }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65" }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65" }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65" }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65" }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65" }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65" }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65" }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65" }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65" }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65" }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65" }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65" }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65" }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65" }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65" }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65" }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65" }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65" }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65" }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65" }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65" }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65" }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65" }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65" }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65" }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65" }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65" }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65" }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65" }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65" }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65" }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65" }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65" }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65" }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65" }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65" }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65" }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65" }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65" }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65" }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65" }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65" }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65" }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65" }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65" }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65" }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65" }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65" }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65" }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65" }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65" }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65" }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65" }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65" }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65" }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65" }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65" }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65" }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65" }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65" }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65" }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65" }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65" }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65" }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65" }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65" }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65" }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65" }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65" }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65" }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65" }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65" }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65" }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65" }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65" }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65" }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65" }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65" }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65" }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65" }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65" }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65" }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65" }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65" }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65" }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65" }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65" }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65" }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65" }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65" }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65" }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65" }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65" }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65" }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65" }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65" }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65" }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65" }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65" }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65" }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65" }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65" }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65" }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65" }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65" }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65" }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65" }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65" }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65" }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65" }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65" }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65" }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65" }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65" }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65" }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65" }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65" }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65" }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65" }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65" }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65" }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65" }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65" }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65" }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65" }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65" }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65" }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65" }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65" }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65" }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65" }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65" }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65" }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65" }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65" }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65" }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65" }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65" }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65" }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65" }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65" }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65" }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65" }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65" }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65" }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65" }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65" }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65" }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65" }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65" }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65" }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65" }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65" }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65" }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65" }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65" }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65" }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65" }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65" }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65" }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65" }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65" }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65" }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65" }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65" }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65" }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65" }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65" }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65" }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65" }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65" }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65" }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65" }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65" }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65" }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65" }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65" }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65" }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65" }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65" }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65" }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65" }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65" }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65" }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65" }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65" }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65" }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65" }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65" }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65" }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65" }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65" }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65" }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65" }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65" }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65" }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65" }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65" }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65" }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65" }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65" }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65" }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65" }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65" }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65" }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65" }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65" }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65" }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65" }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65" }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65" }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65" }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65" }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65" }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65" }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65" }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65" }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65" }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65" }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65" }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65" }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65" }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65" }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65" }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65" }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65" }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65" }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65" }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65" }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65" }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65" }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65" }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65" }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65" }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65" }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65" }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65" }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65" }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65" }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65" }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65" }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65" }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65" }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65" }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65" }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65" }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65" }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65" }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65" }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65" }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65" }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65" }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65" }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65" }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65" }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65" }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65" }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65" }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65" }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65" }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65" }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65" }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65" }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65" }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65" }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65" }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65" }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65" }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65" }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65" }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65" }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65" }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65" }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65" }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65" }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65" }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65" }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65" }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65" }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65" }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65" }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65" }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65" }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65" }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65" }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65" }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65" }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65" }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65" }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65" }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65" }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65" }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65" }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65" }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65" }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65" }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65" }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65" }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65" }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65" }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65" }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65" }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65" }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65" }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65" }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65" }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65" }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65" }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65" }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65" }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65" }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65" }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65" }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65" }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65" }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65" }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65" }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65" }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65" }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65" }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65" }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65" }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65" }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65" }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65" }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65" }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65" }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65" }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65" }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65" }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65" }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65" }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65" }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65" }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65" }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65" }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65" }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65" }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65" }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65" }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65" }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65" }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65" }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65" }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65" }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65" }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65" }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65" }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65" }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65" }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65" }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65" }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65" }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65" }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65" }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65" }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65" }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65" }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65" }, 2526 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65" }, 2527 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65" }, 2528 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65" }, 2529 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65" }, 2530 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65" }, 2531 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65" }, 2532 }; 2533 2534 // Sort the tables on first execution so we can binary search them. 2535 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { 2536 return LHS.BuiltinID < RHS.BuiltinID; 2537 }; 2538 static const bool SortOnce = 2539 (std::sort(std::begin(ValidCPU), std::end(ValidCPU), SortCmp), 2540 std::sort(std::begin(ValidHVX), std::end(ValidHVX), SortCmp), true); 2541 (void)SortOnce; 2542 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { 2543 return BI.BuiltinID < BuiltinID; 2544 }; 2545 2546 const TargetInfo &TI = Context.getTargetInfo(); 2547 2548 const BuiltinAndString *FC = 2549 std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID, 2550 LowerBoundCmp); 2551 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { 2552 const TargetOptions &Opts = TI.getTargetOpts(); 2553 StringRef CPU = Opts.CPU; 2554 if (!CPU.empty()) { 2555 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2556 CPU.consume_front("hexagon"); 2557 SmallVector<StringRef, 3> CPUs; 2558 StringRef(FC->Str).split(CPUs, ','); 2559 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) 2560 return Diag(TheCall->getBeginLoc(), 2561 diag::err_hexagon_builtin_unsupported_cpu); 2562 } 2563 } 2564 2565 const BuiltinAndString *FH = 2566 std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID, 2567 LowerBoundCmp); 2568 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { 2569 if (!TI.hasFeature("hvx")) 2570 return Diag(TheCall->getBeginLoc(), 2571 diag::err_hexagon_builtin_requires_hvx); 2572 2573 SmallVector<StringRef, 3> HVXs; 2574 StringRef(FH->Str).split(HVXs, ','); 2575 bool IsValid = llvm::any_of(HVXs, 2576 [&TI] (StringRef V) { 2577 std::string F = "hvx" + V.str(); 2578 return TI.hasFeature(F); 2579 }); 2580 if (!IsValid) 2581 return Diag(TheCall->getBeginLoc(), 2582 diag::err_hexagon_builtin_unsupported_hvx); 2583 } 2584 2585 return false; 2586 } 2587 2588 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2589 struct ArgInfo { 2590 uint8_t OpNum; 2591 bool IsSigned; 2592 uint8_t BitWidth; 2593 uint8_t Align; 2594 }; 2595 struct BuiltinInfo { 2596 unsigned BuiltinID; 2597 ArgInfo Infos[2]; 2598 }; 2599 2600 static BuiltinInfo Infos[] = { 2601 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2602 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2603 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2604 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2605 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2606 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2607 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2608 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2609 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2610 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2611 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2612 2613 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2614 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2615 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2616 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2617 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2618 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2619 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2620 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2621 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2622 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2623 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2624 2625 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2626 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2627 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2628 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2629 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2630 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2631 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2632 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2633 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2634 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2635 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2636 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2637 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2639 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2641 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2642 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2645 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2646 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2648 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2649 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2650 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2652 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2653 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2656 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2657 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2658 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2659 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2660 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2661 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2662 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2663 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2668 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2670 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2672 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2673 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2675 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2676 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2677 {{ 1, false, 6, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2679 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2680 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2683 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2685 {{ 1, false, 5, 0 }} }, 2686 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2692 { 2, false, 5, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2694 { 2, false, 6, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2696 { 3, false, 5, 0 }} }, 2697 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2698 { 3, false, 6, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2701 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2706 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2709 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2713 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2715 {{ 2, false, 4, 0 }, 2716 { 3, false, 5, 0 }} }, 2717 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2718 {{ 2, false, 4, 0 }, 2719 { 3, false, 5, 0 }} }, 2720 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2721 {{ 2, false, 4, 0 }, 2722 { 3, false, 5, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2724 {{ 2, false, 4, 0 }, 2725 { 3, false, 5, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2727 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2728 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2730 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2731 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2732 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2733 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2737 { 2, false, 5, 0 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2739 { 2, false, 6, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2745 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2749 {{ 1, false, 4, 0 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2752 {{ 1, false, 4, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2773 {{ 3, false, 1, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2778 {{ 3, false, 1, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2783 {{ 3, false, 1, 0 }} }, 2784 }; 2785 2786 // Use a dynamically initialized static to sort the table exactly once on 2787 // first run. 2788 static const bool SortOnce = 2789 (std::sort(std::begin(Infos), std::end(Infos), 2790 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2791 return LHS.BuiltinID < RHS.BuiltinID; 2792 }), 2793 true); 2794 (void)SortOnce; 2795 2796 const BuiltinInfo *F = 2797 std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID, 2798 [](const BuiltinInfo &BI, unsigned BuiltinID) { 2799 return BI.BuiltinID < BuiltinID; 2800 }); 2801 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2802 return false; 2803 2804 bool Error = false; 2805 2806 for (const ArgInfo &A : F->Infos) { 2807 // Ignore empty ArgInfo elements. 2808 if (A.BitWidth == 0) 2809 continue; 2810 2811 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2812 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2813 if (!A.Align) { 2814 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2815 } else { 2816 unsigned M = 1 << A.Align; 2817 Min *= M; 2818 Max *= M; 2819 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2820 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2821 } 2822 } 2823 return Error; 2824 } 2825 2826 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2827 CallExpr *TheCall) { 2828 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2829 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2830 } 2831 2832 2833 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 2834 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2835 // ordering for DSP is unspecified. MSA is ordered by the data format used 2836 // by the underlying instruction i.e., df/m, df/n and then by size. 2837 // 2838 // FIXME: The size tests here should instead be tablegen'd along with the 2839 // definitions from include/clang/Basic/BuiltinsMips.def. 2840 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2841 // be too. 2842 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2843 unsigned i = 0, l = 0, u = 0, m = 0; 2844 switch (BuiltinID) { 2845 default: return false; 2846 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2847 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2848 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2849 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2850 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2851 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2852 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2853 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 2854 // df/m field. 2855 // These intrinsics take an unsigned 3 bit immediate. 2856 case Mips::BI__builtin_msa_bclri_b: 2857 case Mips::BI__builtin_msa_bnegi_b: 2858 case Mips::BI__builtin_msa_bseti_b: 2859 case Mips::BI__builtin_msa_sat_s_b: 2860 case Mips::BI__builtin_msa_sat_u_b: 2861 case Mips::BI__builtin_msa_slli_b: 2862 case Mips::BI__builtin_msa_srai_b: 2863 case Mips::BI__builtin_msa_srari_b: 2864 case Mips::BI__builtin_msa_srli_b: 2865 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2866 case Mips::BI__builtin_msa_binsli_b: 2867 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2868 // These intrinsics take an unsigned 4 bit immediate. 2869 case Mips::BI__builtin_msa_bclri_h: 2870 case Mips::BI__builtin_msa_bnegi_h: 2871 case Mips::BI__builtin_msa_bseti_h: 2872 case Mips::BI__builtin_msa_sat_s_h: 2873 case Mips::BI__builtin_msa_sat_u_h: 2874 case Mips::BI__builtin_msa_slli_h: 2875 case Mips::BI__builtin_msa_srai_h: 2876 case Mips::BI__builtin_msa_srari_h: 2877 case Mips::BI__builtin_msa_srli_h: 2878 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2879 case Mips::BI__builtin_msa_binsli_h: 2880 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2881 // These intrinsics take an unsigned 5 bit immediate. 2882 // The first block of intrinsics actually have an unsigned 5 bit field, 2883 // not a df/n field. 2884 case Mips::BI__builtin_msa_clei_u_b: 2885 case Mips::BI__builtin_msa_clei_u_h: 2886 case Mips::BI__builtin_msa_clei_u_w: 2887 case Mips::BI__builtin_msa_clei_u_d: 2888 case Mips::BI__builtin_msa_clti_u_b: 2889 case Mips::BI__builtin_msa_clti_u_h: 2890 case Mips::BI__builtin_msa_clti_u_w: 2891 case Mips::BI__builtin_msa_clti_u_d: 2892 case Mips::BI__builtin_msa_maxi_u_b: 2893 case Mips::BI__builtin_msa_maxi_u_h: 2894 case Mips::BI__builtin_msa_maxi_u_w: 2895 case Mips::BI__builtin_msa_maxi_u_d: 2896 case Mips::BI__builtin_msa_mini_u_b: 2897 case Mips::BI__builtin_msa_mini_u_h: 2898 case Mips::BI__builtin_msa_mini_u_w: 2899 case Mips::BI__builtin_msa_mini_u_d: 2900 case Mips::BI__builtin_msa_addvi_b: 2901 case Mips::BI__builtin_msa_addvi_h: 2902 case Mips::BI__builtin_msa_addvi_w: 2903 case Mips::BI__builtin_msa_addvi_d: 2904 case Mips::BI__builtin_msa_bclri_w: 2905 case Mips::BI__builtin_msa_bnegi_w: 2906 case Mips::BI__builtin_msa_bseti_w: 2907 case Mips::BI__builtin_msa_sat_s_w: 2908 case Mips::BI__builtin_msa_sat_u_w: 2909 case Mips::BI__builtin_msa_slli_w: 2910 case Mips::BI__builtin_msa_srai_w: 2911 case Mips::BI__builtin_msa_srari_w: 2912 case Mips::BI__builtin_msa_srli_w: 2913 case Mips::BI__builtin_msa_srlri_w: 2914 case Mips::BI__builtin_msa_subvi_b: 2915 case Mips::BI__builtin_msa_subvi_h: 2916 case Mips::BI__builtin_msa_subvi_w: 2917 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2918 case Mips::BI__builtin_msa_binsli_w: 2919 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2920 // These intrinsics take an unsigned 6 bit immediate. 2921 case Mips::BI__builtin_msa_bclri_d: 2922 case Mips::BI__builtin_msa_bnegi_d: 2923 case Mips::BI__builtin_msa_bseti_d: 2924 case Mips::BI__builtin_msa_sat_s_d: 2925 case Mips::BI__builtin_msa_sat_u_d: 2926 case Mips::BI__builtin_msa_slli_d: 2927 case Mips::BI__builtin_msa_srai_d: 2928 case Mips::BI__builtin_msa_srari_d: 2929 case Mips::BI__builtin_msa_srli_d: 2930 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2931 case Mips::BI__builtin_msa_binsli_d: 2932 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2933 // These intrinsics take a signed 5 bit immediate. 2934 case Mips::BI__builtin_msa_ceqi_b: 2935 case Mips::BI__builtin_msa_ceqi_h: 2936 case Mips::BI__builtin_msa_ceqi_w: 2937 case Mips::BI__builtin_msa_ceqi_d: 2938 case Mips::BI__builtin_msa_clti_s_b: 2939 case Mips::BI__builtin_msa_clti_s_h: 2940 case Mips::BI__builtin_msa_clti_s_w: 2941 case Mips::BI__builtin_msa_clti_s_d: 2942 case Mips::BI__builtin_msa_clei_s_b: 2943 case Mips::BI__builtin_msa_clei_s_h: 2944 case Mips::BI__builtin_msa_clei_s_w: 2945 case Mips::BI__builtin_msa_clei_s_d: 2946 case Mips::BI__builtin_msa_maxi_s_b: 2947 case Mips::BI__builtin_msa_maxi_s_h: 2948 case Mips::BI__builtin_msa_maxi_s_w: 2949 case Mips::BI__builtin_msa_maxi_s_d: 2950 case Mips::BI__builtin_msa_mini_s_b: 2951 case Mips::BI__builtin_msa_mini_s_h: 2952 case Mips::BI__builtin_msa_mini_s_w: 2953 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2954 // These intrinsics take an unsigned 8 bit immediate. 2955 case Mips::BI__builtin_msa_andi_b: 2956 case Mips::BI__builtin_msa_nori_b: 2957 case Mips::BI__builtin_msa_ori_b: 2958 case Mips::BI__builtin_msa_shf_b: 2959 case Mips::BI__builtin_msa_shf_h: 2960 case Mips::BI__builtin_msa_shf_w: 2961 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2962 case Mips::BI__builtin_msa_bseli_b: 2963 case Mips::BI__builtin_msa_bmnzi_b: 2964 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2965 // df/n format 2966 // These intrinsics take an unsigned 4 bit immediate. 2967 case Mips::BI__builtin_msa_copy_s_b: 2968 case Mips::BI__builtin_msa_copy_u_b: 2969 case Mips::BI__builtin_msa_insve_b: 2970 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2971 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2972 // These intrinsics take an unsigned 3 bit immediate. 2973 case Mips::BI__builtin_msa_copy_s_h: 2974 case Mips::BI__builtin_msa_copy_u_h: 2975 case Mips::BI__builtin_msa_insve_h: 2976 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2977 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2978 // These intrinsics take an unsigned 2 bit immediate. 2979 case Mips::BI__builtin_msa_copy_s_w: 2980 case Mips::BI__builtin_msa_copy_u_w: 2981 case Mips::BI__builtin_msa_insve_w: 2982 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2983 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2984 // These intrinsics take an unsigned 1 bit immediate. 2985 case Mips::BI__builtin_msa_copy_s_d: 2986 case Mips::BI__builtin_msa_copy_u_d: 2987 case Mips::BI__builtin_msa_insve_d: 2988 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2989 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2990 // Memory offsets and immediate loads. 2991 // These intrinsics take a signed 10 bit immediate. 2992 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2993 case Mips::BI__builtin_msa_ldi_h: 2994 case Mips::BI__builtin_msa_ldi_w: 2995 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2996 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 2997 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 2998 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 2999 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3000 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3001 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3002 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3003 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3004 } 3005 3006 if (!m) 3007 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3008 3009 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3010 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3011 } 3012 3013 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3014 unsigned i = 0, l = 0, u = 0; 3015 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3016 BuiltinID == PPC::BI__builtin_divdeu || 3017 BuiltinID == PPC::BI__builtin_bpermd; 3018 bool IsTarget64Bit = Context.getTargetInfo() 3019 .getTypeWidth(Context 3020 .getTargetInfo() 3021 .getIntPtrType()) == 64; 3022 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3023 BuiltinID == PPC::BI__builtin_divweu || 3024 BuiltinID == PPC::BI__builtin_divde || 3025 BuiltinID == PPC::BI__builtin_divdeu; 3026 3027 if (Is64BitBltin && !IsTarget64Bit) 3028 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3029 << TheCall->getSourceRange(); 3030 3031 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 3032 (BuiltinID == PPC::BI__builtin_bpermd && 3033 !Context.getTargetInfo().hasFeature("bpermd"))) 3034 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3035 << TheCall->getSourceRange(); 3036 3037 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3038 if (!Context.getTargetInfo().hasFeature("vsx")) 3039 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3040 << TheCall->getSourceRange(); 3041 return false; 3042 }; 3043 3044 switch (BuiltinID) { 3045 default: return false; 3046 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3047 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3048 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3049 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3050 case PPC::BI__builtin_tbegin: 3051 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3052 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3053 case PPC::BI__builtin_tabortwc: 3054 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3055 case PPC::BI__builtin_tabortwci: 3056 case PPC::BI__builtin_tabortdci: 3057 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3058 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3059 case PPC::BI__builtin_vsx_xxpermdi: 3060 case PPC::BI__builtin_vsx_xxsldwi: 3061 return SemaBuiltinVSX(TheCall); 3062 case PPC::BI__builtin_unpack_vector_int128: 3063 return SemaVSXCheck(TheCall) || 3064 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3065 case PPC::BI__builtin_pack_vector_int128: 3066 return SemaVSXCheck(TheCall); 3067 } 3068 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3069 } 3070 3071 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3072 CallExpr *TheCall) { 3073 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3074 Expr *Arg = TheCall->getArg(0); 3075 llvm::APSInt AbortCode(32); 3076 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3077 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3078 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3079 << Arg->getSourceRange(); 3080 } 3081 3082 // For intrinsics which take an immediate value as part of the instruction, 3083 // range check them here. 3084 unsigned i = 0, l = 0, u = 0; 3085 switch (BuiltinID) { 3086 default: return false; 3087 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3088 case SystemZ::BI__builtin_s390_verimb: 3089 case SystemZ::BI__builtin_s390_verimh: 3090 case SystemZ::BI__builtin_s390_verimf: 3091 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3092 case SystemZ::BI__builtin_s390_vfaeb: 3093 case SystemZ::BI__builtin_s390_vfaeh: 3094 case SystemZ::BI__builtin_s390_vfaef: 3095 case SystemZ::BI__builtin_s390_vfaebs: 3096 case SystemZ::BI__builtin_s390_vfaehs: 3097 case SystemZ::BI__builtin_s390_vfaefs: 3098 case SystemZ::BI__builtin_s390_vfaezb: 3099 case SystemZ::BI__builtin_s390_vfaezh: 3100 case SystemZ::BI__builtin_s390_vfaezf: 3101 case SystemZ::BI__builtin_s390_vfaezbs: 3102 case SystemZ::BI__builtin_s390_vfaezhs: 3103 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3104 case SystemZ::BI__builtin_s390_vfisb: 3105 case SystemZ::BI__builtin_s390_vfidb: 3106 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3107 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3108 case SystemZ::BI__builtin_s390_vftcisb: 3109 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3110 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3111 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3112 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3113 case SystemZ::BI__builtin_s390_vstrcb: 3114 case SystemZ::BI__builtin_s390_vstrch: 3115 case SystemZ::BI__builtin_s390_vstrcf: 3116 case SystemZ::BI__builtin_s390_vstrczb: 3117 case SystemZ::BI__builtin_s390_vstrczh: 3118 case SystemZ::BI__builtin_s390_vstrczf: 3119 case SystemZ::BI__builtin_s390_vstrcbs: 3120 case SystemZ::BI__builtin_s390_vstrchs: 3121 case SystemZ::BI__builtin_s390_vstrcfs: 3122 case SystemZ::BI__builtin_s390_vstrczbs: 3123 case SystemZ::BI__builtin_s390_vstrczhs: 3124 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3125 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3126 case SystemZ::BI__builtin_s390_vfminsb: 3127 case SystemZ::BI__builtin_s390_vfmaxsb: 3128 case SystemZ::BI__builtin_s390_vfmindb: 3129 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3130 } 3131 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3132 } 3133 3134 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3135 /// This checks that the target supports __builtin_cpu_supports and 3136 /// that the string argument is constant and valid. 3137 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3138 Expr *Arg = TheCall->getArg(0); 3139 3140 // Check if the argument is a string literal. 3141 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3142 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3143 << Arg->getSourceRange(); 3144 3145 // Check the contents of the string. 3146 StringRef Feature = 3147 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3148 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3149 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3150 << Arg->getSourceRange(); 3151 return false; 3152 } 3153 3154 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3155 /// This checks that the target supports __builtin_cpu_is and 3156 /// that the string argument is constant and valid. 3157 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3158 Expr *Arg = TheCall->getArg(0); 3159 3160 // Check if the argument is a string literal. 3161 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3162 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3163 << Arg->getSourceRange(); 3164 3165 // Check the contents of the string. 3166 StringRef Feature = 3167 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3168 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3169 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3170 << Arg->getSourceRange(); 3171 return false; 3172 } 3173 3174 // Check if the rounding mode is legal. 3175 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3176 // Indicates if this instruction has rounding control or just SAE. 3177 bool HasRC = false; 3178 3179 unsigned ArgNum = 0; 3180 switch (BuiltinID) { 3181 default: 3182 return false; 3183 case X86::BI__builtin_ia32_vcvttsd2si32: 3184 case X86::BI__builtin_ia32_vcvttsd2si64: 3185 case X86::BI__builtin_ia32_vcvttsd2usi32: 3186 case X86::BI__builtin_ia32_vcvttsd2usi64: 3187 case X86::BI__builtin_ia32_vcvttss2si32: 3188 case X86::BI__builtin_ia32_vcvttss2si64: 3189 case X86::BI__builtin_ia32_vcvttss2usi32: 3190 case X86::BI__builtin_ia32_vcvttss2usi64: 3191 ArgNum = 1; 3192 break; 3193 case X86::BI__builtin_ia32_maxpd512: 3194 case X86::BI__builtin_ia32_maxps512: 3195 case X86::BI__builtin_ia32_minpd512: 3196 case X86::BI__builtin_ia32_minps512: 3197 ArgNum = 2; 3198 break; 3199 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3200 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3201 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3202 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3203 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3204 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3205 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3206 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3207 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3208 case X86::BI__builtin_ia32_exp2pd_mask: 3209 case X86::BI__builtin_ia32_exp2ps_mask: 3210 case X86::BI__builtin_ia32_getexppd512_mask: 3211 case X86::BI__builtin_ia32_getexpps512_mask: 3212 case X86::BI__builtin_ia32_rcp28pd_mask: 3213 case X86::BI__builtin_ia32_rcp28ps_mask: 3214 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3215 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3216 case X86::BI__builtin_ia32_vcomisd: 3217 case X86::BI__builtin_ia32_vcomiss: 3218 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3219 ArgNum = 3; 3220 break; 3221 case X86::BI__builtin_ia32_cmppd512_mask: 3222 case X86::BI__builtin_ia32_cmpps512_mask: 3223 case X86::BI__builtin_ia32_cmpsd_mask: 3224 case X86::BI__builtin_ia32_cmpss_mask: 3225 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3226 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3227 case X86::BI__builtin_ia32_getexpss128_round_mask: 3228 case X86::BI__builtin_ia32_maxsd_round_mask: 3229 case X86::BI__builtin_ia32_maxss_round_mask: 3230 case X86::BI__builtin_ia32_minsd_round_mask: 3231 case X86::BI__builtin_ia32_minss_round_mask: 3232 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3233 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3234 case X86::BI__builtin_ia32_reducepd512_mask: 3235 case X86::BI__builtin_ia32_reduceps512_mask: 3236 case X86::BI__builtin_ia32_rndscalepd_mask: 3237 case X86::BI__builtin_ia32_rndscaleps_mask: 3238 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3239 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3240 ArgNum = 4; 3241 break; 3242 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3243 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3244 case X86::BI__builtin_ia32_fixupimmps512_mask: 3245 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3246 case X86::BI__builtin_ia32_fixupimmsd_mask: 3247 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3248 case X86::BI__builtin_ia32_fixupimmss_mask: 3249 case X86::BI__builtin_ia32_fixupimmss_maskz: 3250 case X86::BI__builtin_ia32_rangepd512_mask: 3251 case X86::BI__builtin_ia32_rangeps512_mask: 3252 case X86::BI__builtin_ia32_rangesd128_round_mask: 3253 case X86::BI__builtin_ia32_rangess128_round_mask: 3254 case X86::BI__builtin_ia32_reducesd_mask: 3255 case X86::BI__builtin_ia32_reducess_mask: 3256 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3257 case X86::BI__builtin_ia32_rndscaless_round_mask: 3258 ArgNum = 5; 3259 break; 3260 case X86::BI__builtin_ia32_vcvtsd2si64: 3261 case X86::BI__builtin_ia32_vcvtsd2si32: 3262 case X86::BI__builtin_ia32_vcvtsd2usi32: 3263 case X86::BI__builtin_ia32_vcvtsd2usi64: 3264 case X86::BI__builtin_ia32_vcvtss2si32: 3265 case X86::BI__builtin_ia32_vcvtss2si64: 3266 case X86::BI__builtin_ia32_vcvtss2usi32: 3267 case X86::BI__builtin_ia32_vcvtss2usi64: 3268 case X86::BI__builtin_ia32_sqrtpd512: 3269 case X86::BI__builtin_ia32_sqrtps512: 3270 ArgNum = 1; 3271 HasRC = true; 3272 break; 3273 case X86::BI__builtin_ia32_addpd512: 3274 case X86::BI__builtin_ia32_addps512: 3275 case X86::BI__builtin_ia32_divpd512: 3276 case X86::BI__builtin_ia32_divps512: 3277 case X86::BI__builtin_ia32_mulpd512: 3278 case X86::BI__builtin_ia32_mulps512: 3279 case X86::BI__builtin_ia32_subpd512: 3280 case X86::BI__builtin_ia32_subps512: 3281 case X86::BI__builtin_ia32_cvtsi2sd64: 3282 case X86::BI__builtin_ia32_cvtsi2ss32: 3283 case X86::BI__builtin_ia32_cvtsi2ss64: 3284 case X86::BI__builtin_ia32_cvtusi2sd64: 3285 case X86::BI__builtin_ia32_cvtusi2ss32: 3286 case X86::BI__builtin_ia32_cvtusi2ss64: 3287 ArgNum = 2; 3288 HasRC = true; 3289 break; 3290 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3291 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3292 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3293 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3294 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3295 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3296 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3297 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3298 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3299 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3300 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3301 ArgNum = 3; 3302 HasRC = true; 3303 break; 3304 case X86::BI__builtin_ia32_addss_round_mask: 3305 case X86::BI__builtin_ia32_addsd_round_mask: 3306 case X86::BI__builtin_ia32_divss_round_mask: 3307 case X86::BI__builtin_ia32_divsd_round_mask: 3308 case X86::BI__builtin_ia32_mulss_round_mask: 3309 case X86::BI__builtin_ia32_mulsd_round_mask: 3310 case X86::BI__builtin_ia32_subss_round_mask: 3311 case X86::BI__builtin_ia32_subsd_round_mask: 3312 case X86::BI__builtin_ia32_scalefpd512_mask: 3313 case X86::BI__builtin_ia32_scalefps512_mask: 3314 case X86::BI__builtin_ia32_scalefsd_round_mask: 3315 case X86::BI__builtin_ia32_scalefss_round_mask: 3316 case X86::BI__builtin_ia32_getmantpd512_mask: 3317 case X86::BI__builtin_ia32_getmantps512_mask: 3318 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3319 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3320 case X86::BI__builtin_ia32_sqrtss_round_mask: 3321 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3322 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3323 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3324 case X86::BI__builtin_ia32_vfmaddss3_mask: 3325 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3326 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3327 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3328 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3329 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3330 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3331 case X86::BI__builtin_ia32_vfmaddps512_mask: 3332 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3333 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3334 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3335 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3336 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3337 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3338 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3339 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3340 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3341 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3342 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3343 ArgNum = 4; 3344 HasRC = true; 3345 break; 3346 case X86::BI__builtin_ia32_getmantsd_round_mask: 3347 case X86::BI__builtin_ia32_getmantss_round_mask: 3348 ArgNum = 5; 3349 HasRC = true; 3350 break; 3351 } 3352 3353 llvm::APSInt Result; 3354 3355 // We can't check the value of a dependent argument. 3356 Expr *Arg = TheCall->getArg(ArgNum); 3357 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3358 return false; 3359 3360 // Check constant-ness first. 3361 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3362 return true; 3363 3364 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3365 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3366 // combined with ROUND_NO_EXC. 3367 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3368 Result == 8/*ROUND_NO_EXC*/ || 3369 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3370 return false; 3371 3372 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3373 << Arg->getSourceRange(); 3374 } 3375 3376 // Check if the gather/scatter scale is legal. 3377 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3378 CallExpr *TheCall) { 3379 unsigned ArgNum = 0; 3380 switch (BuiltinID) { 3381 default: 3382 return false; 3383 case X86::BI__builtin_ia32_gatherpfdpd: 3384 case X86::BI__builtin_ia32_gatherpfdps: 3385 case X86::BI__builtin_ia32_gatherpfqpd: 3386 case X86::BI__builtin_ia32_gatherpfqps: 3387 case X86::BI__builtin_ia32_scatterpfdpd: 3388 case X86::BI__builtin_ia32_scatterpfdps: 3389 case X86::BI__builtin_ia32_scatterpfqpd: 3390 case X86::BI__builtin_ia32_scatterpfqps: 3391 ArgNum = 3; 3392 break; 3393 case X86::BI__builtin_ia32_gatherd_pd: 3394 case X86::BI__builtin_ia32_gatherd_pd256: 3395 case X86::BI__builtin_ia32_gatherq_pd: 3396 case X86::BI__builtin_ia32_gatherq_pd256: 3397 case X86::BI__builtin_ia32_gatherd_ps: 3398 case X86::BI__builtin_ia32_gatherd_ps256: 3399 case X86::BI__builtin_ia32_gatherq_ps: 3400 case X86::BI__builtin_ia32_gatherq_ps256: 3401 case X86::BI__builtin_ia32_gatherd_q: 3402 case X86::BI__builtin_ia32_gatherd_q256: 3403 case X86::BI__builtin_ia32_gatherq_q: 3404 case X86::BI__builtin_ia32_gatherq_q256: 3405 case X86::BI__builtin_ia32_gatherd_d: 3406 case X86::BI__builtin_ia32_gatherd_d256: 3407 case X86::BI__builtin_ia32_gatherq_d: 3408 case X86::BI__builtin_ia32_gatherq_d256: 3409 case X86::BI__builtin_ia32_gather3div2df: 3410 case X86::BI__builtin_ia32_gather3div2di: 3411 case X86::BI__builtin_ia32_gather3div4df: 3412 case X86::BI__builtin_ia32_gather3div4di: 3413 case X86::BI__builtin_ia32_gather3div4sf: 3414 case X86::BI__builtin_ia32_gather3div4si: 3415 case X86::BI__builtin_ia32_gather3div8sf: 3416 case X86::BI__builtin_ia32_gather3div8si: 3417 case X86::BI__builtin_ia32_gather3siv2df: 3418 case X86::BI__builtin_ia32_gather3siv2di: 3419 case X86::BI__builtin_ia32_gather3siv4df: 3420 case X86::BI__builtin_ia32_gather3siv4di: 3421 case X86::BI__builtin_ia32_gather3siv4sf: 3422 case X86::BI__builtin_ia32_gather3siv4si: 3423 case X86::BI__builtin_ia32_gather3siv8sf: 3424 case X86::BI__builtin_ia32_gather3siv8si: 3425 case X86::BI__builtin_ia32_gathersiv8df: 3426 case X86::BI__builtin_ia32_gathersiv16sf: 3427 case X86::BI__builtin_ia32_gatherdiv8df: 3428 case X86::BI__builtin_ia32_gatherdiv16sf: 3429 case X86::BI__builtin_ia32_gathersiv8di: 3430 case X86::BI__builtin_ia32_gathersiv16si: 3431 case X86::BI__builtin_ia32_gatherdiv8di: 3432 case X86::BI__builtin_ia32_gatherdiv16si: 3433 case X86::BI__builtin_ia32_scatterdiv2df: 3434 case X86::BI__builtin_ia32_scatterdiv2di: 3435 case X86::BI__builtin_ia32_scatterdiv4df: 3436 case X86::BI__builtin_ia32_scatterdiv4di: 3437 case X86::BI__builtin_ia32_scatterdiv4sf: 3438 case X86::BI__builtin_ia32_scatterdiv4si: 3439 case X86::BI__builtin_ia32_scatterdiv8sf: 3440 case X86::BI__builtin_ia32_scatterdiv8si: 3441 case X86::BI__builtin_ia32_scattersiv2df: 3442 case X86::BI__builtin_ia32_scattersiv2di: 3443 case X86::BI__builtin_ia32_scattersiv4df: 3444 case X86::BI__builtin_ia32_scattersiv4di: 3445 case X86::BI__builtin_ia32_scattersiv4sf: 3446 case X86::BI__builtin_ia32_scattersiv4si: 3447 case X86::BI__builtin_ia32_scattersiv8sf: 3448 case X86::BI__builtin_ia32_scattersiv8si: 3449 case X86::BI__builtin_ia32_scattersiv8df: 3450 case X86::BI__builtin_ia32_scattersiv16sf: 3451 case X86::BI__builtin_ia32_scatterdiv8df: 3452 case X86::BI__builtin_ia32_scatterdiv16sf: 3453 case X86::BI__builtin_ia32_scattersiv8di: 3454 case X86::BI__builtin_ia32_scattersiv16si: 3455 case X86::BI__builtin_ia32_scatterdiv8di: 3456 case X86::BI__builtin_ia32_scatterdiv16si: 3457 ArgNum = 4; 3458 break; 3459 } 3460 3461 llvm::APSInt Result; 3462 3463 // We can't check the value of a dependent argument. 3464 Expr *Arg = TheCall->getArg(ArgNum); 3465 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3466 return false; 3467 3468 // Check constant-ness first. 3469 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3470 return true; 3471 3472 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3473 return false; 3474 3475 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3476 << Arg->getSourceRange(); 3477 } 3478 3479 static bool isX86_32Builtin(unsigned BuiltinID) { 3480 // These builtins only work on x86-32 targets. 3481 switch (BuiltinID) { 3482 case X86::BI__builtin_ia32_readeflags_u32: 3483 case X86::BI__builtin_ia32_writeeflags_u32: 3484 return true; 3485 } 3486 3487 return false; 3488 } 3489 3490 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3491 if (BuiltinID == X86::BI__builtin_cpu_supports) 3492 return SemaBuiltinCpuSupports(*this, TheCall); 3493 3494 if (BuiltinID == X86::BI__builtin_cpu_is) 3495 return SemaBuiltinCpuIs(*this, TheCall); 3496 3497 // Check for 32-bit only builtins on a 64-bit target. 3498 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3499 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3500 return Diag(TheCall->getCallee()->getBeginLoc(), 3501 diag::err_32_bit_builtin_64_bit_tgt); 3502 3503 // If the intrinsic has rounding or SAE make sure its valid. 3504 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3505 return true; 3506 3507 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3508 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3509 return true; 3510 3511 // For intrinsics which take an immediate value as part of the instruction, 3512 // range check them here. 3513 int i = 0, l = 0, u = 0; 3514 switch (BuiltinID) { 3515 default: 3516 return false; 3517 case X86::BI__builtin_ia32_vec_ext_v2si: 3518 case X86::BI__builtin_ia32_vec_ext_v2di: 3519 case X86::BI__builtin_ia32_vextractf128_pd256: 3520 case X86::BI__builtin_ia32_vextractf128_ps256: 3521 case X86::BI__builtin_ia32_vextractf128_si256: 3522 case X86::BI__builtin_ia32_extract128i256: 3523 case X86::BI__builtin_ia32_extractf64x4_mask: 3524 case X86::BI__builtin_ia32_extracti64x4_mask: 3525 case X86::BI__builtin_ia32_extractf32x8_mask: 3526 case X86::BI__builtin_ia32_extracti32x8_mask: 3527 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3528 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3529 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3530 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3531 i = 1; l = 0; u = 1; 3532 break; 3533 case X86::BI__builtin_ia32_vec_set_v2di: 3534 case X86::BI__builtin_ia32_vinsertf128_pd256: 3535 case X86::BI__builtin_ia32_vinsertf128_ps256: 3536 case X86::BI__builtin_ia32_vinsertf128_si256: 3537 case X86::BI__builtin_ia32_insert128i256: 3538 case X86::BI__builtin_ia32_insertf32x8: 3539 case X86::BI__builtin_ia32_inserti32x8: 3540 case X86::BI__builtin_ia32_insertf64x4: 3541 case X86::BI__builtin_ia32_inserti64x4: 3542 case X86::BI__builtin_ia32_insertf64x2_256: 3543 case X86::BI__builtin_ia32_inserti64x2_256: 3544 case X86::BI__builtin_ia32_insertf32x4_256: 3545 case X86::BI__builtin_ia32_inserti32x4_256: 3546 i = 2; l = 0; u = 1; 3547 break; 3548 case X86::BI__builtin_ia32_vpermilpd: 3549 case X86::BI__builtin_ia32_vec_ext_v4hi: 3550 case X86::BI__builtin_ia32_vec_ext_v4si: 3551 case X86::BI__builtin_ia32_vec_ext_v4sf: 3552 case X86::BI__builtin_ia32_vec_ext_v4di: 3553 case X86::BI__builtin_ia32_extractf32x4_mask: 3554 case X86::BI__builtin_ia32_extracti32x4_mask: 3555 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3556 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3557 i = 1; l = 0; u = 3; 3558 break; 3559 case X86::BI_mm_prefetch: 3560 case X86::BI__builtin_ia32_vec_ext_v8hi: 3561 case X86::BI__builtin_ia32_vec_ext_v8si: 3562 i = 1; l = 0; u = 7; 3563 break; 3564 case X86::BI__builtin_ia32_sha1rnds4: 3565 case X86::BI__builtin_ia32_blendpd: 3566 case X86::BI__builtin_ia32_shufpd: 3567 case X86::BI__builtin_ia32_vec_set_v4hi: 3568 case X86::BI__builtin_ia32_vec_set_v4si: 3569 case X86::BI__builtin_ia32_vec_set_v4di: 3570 case X86::BI__builtin_ia32_shuf_f32x4_256: 3571 case X86::BI__builtin_ia32_shuf_f64x2_256: 3572 case X86::BI__builtin_ia32_shuf_i32x4_256: 3573 case X86::BI__builtin_ia32_shuf_i64x2_256: 3574 case X86::BI__builtin_ia32_insertf64x2_512: 3575 case X86::BI__builtin_ia32_inserti64x2_512: 3576 case X86::BI__builtin_ia32_insertf32x4: 3577 case X86::BI__builtin_ia32_inserti32x4: 3578 i = 2; l = 0; u = 3; 3579 break; 3580 case X86::BI__builtin_ia32_vpermil2pd: 3581 case X86::BI__builtin_ia32_vpermil2pd256: 3582 case X86::BI__builtin_ia32_vpermil2ps: 3583 case X86::BI__builtin_ia32_vpermil2ps256: 3584 i = 3; l = 0; u = 3; 3585 break; 3586 case X86::BI__builtin_ia32_cmpb128_mask: 3587 case X86::BI__builtin_ia32_cmpw128_mask: 3588 case X86::BI__builtin_ia32_cmpd128_mask: 3589 case X86::BI__builtin_ia32_cmpq128_mask: 3590 case X86::BI__builtin_ia32_cmpb256_mask: 3591 case X86::BI__builtin_ia32_cmpw256_mask: 3592 case X86::BI__builtin_ia32_cmpd256_mask: 3593 case X86::BI__builtin_ia32_cmpq256_mask: 3594 case X86::BI__builtin_ia32_cmpb512_mask: 3595 case X86::BI__builtin_ia32_cmpw512_mask: 3596 case X86::BI__builtin_ia32_cmpd512_mask: 3597 case X86::BI__builtin_ia32_cmpq512_mask: 3598 case X86::BI__builtin_ia32_ucmpb128_mask: 3599 case X86::BI__builtin_ia32_ucmpw128_mask: 3600 case X86::BI__builtin_ia32_ucmpd128_mask: 3601 case X86::BI__builtin_ia32_ucmpq128_mask: 3602 case X86::BI__builtin_ia32_ucmpb256_mask: 3603 case X86::BI__builtin_ia32_ucmpw256_mask: 3604 case X86::BI__builtin_ia32_ucmpd256_mask: 3605 case X86::BI__builtin_ia32_ucmpq256_mask: 3606 case X86::BI__builtin_ia32_ucmpb512_mask: 3607 case X86::BI__builtin_ia32_ucmpw512_mask: 3608 case X86::BI__builtin_ia32_ucmpd512_mask: 3609 case X86::BI__builtin_ia32_ucmpq512_mask: 3610 case X86::BI__builtin_ia32_vpcomub: 3611 case X86::BI__builtin_ia32_vpcomuw: 3612 case X86::BI__builtin_ia32_vpcomud: 3613 case X86::BI__builtin_ia32_vpcomuq: 3614 case X86::BI__builtin_ia32_vpcomb: 3615 case X86::BI__builtin_ia32_vpcomw: 3616 case X86::BI__builtin_ia32_vpcomd: 3617 case X86::BI__builtin_ia32_vpcomq: 3618 case X86::BI__builtin_ia32_vec_set_v8hi: 3619 case X86::BI__builtin_ia32_vec_set_v8si: 3620 i = 2; l = 0; u = 7; 3621 break; 3622 case X86::BI__builtin_ia32_vpermilpd256: 3623 case X86::BI__builtin_ia32_roundps: 3624 case X86::BI__builtin_ia32_roundpd: 3625 case X86::BI__builtin_ia32_roundps256: 3626 case X86::BI__builtin_ia32_roundpd256: 3627 case X86::BI__builtin_ia32_getmantpd128_mask: 3628 case X86::BI__builtin_ia32_getmantpd256_mask: 3629 case X86::BI__builtin_ia32_getmantps128_mask: 3630 case X86::BI__builtin_ia32_getmantps256_mask: 3631 case X86::BI__builtin_ia32_getmantpd512_mask: 3632 case X86::BI__builtin_ia32_getmantps512_mask: 3633 case X86::BI__builtin_ia32_vec_ext_v16qi: 3634 case X86::BI__builtin_ia32_vec_ext_v16hi: 3635 i = 1; l = 0; u = 15; 3636 break; 3637 case X86::BI__builtin_ia32_pblendd128: 3638 case X86::BI__builtin_ia32_blendps: 3639 case X86::BI__builtin_ia32_blendpd256: 3640 case X86::BI__builtin_ia32_shufpd256: 3641 case X86::BI__builtin_ia32_roundss: 3642 case X86::BI__builtin_ia32_roundsd: 3643 case X86::BI__builtin_ia32_rangepd128_mask: 3644 case X86::BI__builtin_ia32_rangepd256_mask: 3645 case X86::BI__builtin_ia32_rangepd512_mask: 3646 case X86::BI__builtin_ia32_rangeps128_mask: 3647 case X86::BI__builtin_ia32_rangeps256_mask: 3648 case X86::BI__builtin_ia32_rangeps512_mask: 3649 case X86::BI__builtin_ia32_getmantsd_round_mask: 3650 case X86::BI__builtin_ia32_getmantss_round_mask: 3651 case X86::BI__builtin_ia32_vec_set_v16qi: 3652 case X86::BI__builtin_ia32_vec_set_v16hi: 3653 i = 2; l = 0; u = 15; 3654 break; 3655 case X86::BI__builtin_ia32_vec_ext_v32qi: 3656 i = 1; l = 0; u = 31; 3657 break; 3658 case X86::BI__builtin_ia32_cmpps: 3659 case X86::BI__builtin_ia32_cmpss: 3660 case X86::BI__builtin_ia32_cmppd: 3661 case X86::BI__builtin_ia32_cmpsd: 3662 case X86::BI__builtin_ia32_cmpps256: 3663 case X86::BI__builtin_ia32_cmppd256: 3664 case X86::BI__builtin_ia32_cmpps128_mask: 3665 case X86::BI__builtin_ia32_cmppd128_mask: 3666 case X86::BI__builtin_ia32_cmpps256_mask: 3667 case X86::BI__builtin_ia32_cmppd256_mask: 3668 case X86::BI__builtin_ia32_cmpps512_mask: 3669 case X86::BI__builtin_ia32_cmppd512_mask: 3670 case X86::BI__builtin_ia32_cmpsd_mask: 3671 case X86::BI__builtin_ia32_cmpss_mask: 3672 case X86::BI__builtin_ia32_vec_set_v32qi: 3673 i = 2; l = 0; u = 31; 3674 break; 3675 case X86::BI__builtin_ia32_permdf256: 3676 case X86::BI__builtin_ia32_permdi256: 3677 case X86::BI__builtin_ia32_permdf512: 3678 case X86::BI__builtin_ia32_permdi512: 3679 case X86::BI__builtin_ia32_vpermilps: 3680 case X86::BI__builtin_ia32_vpermilps256: 3681 case X86::BI__builtin_ia32_vpermilpd512: 3682 case X86::BI__builtin_ia32_vpermilps512: 3683 case X86::BI__builtin_ia32_pshufd: 3684 case X86::BI__builtin_ia32_pshufd256: 3685 case X86::BI__builtin_ia32_pshufd512: 3686 case X86::BI__builtin_ia32_pshufhw: 3687 case X86::BI__builtin_ia32_pshufhw256: 3688 case X86::BI__builtin_ia32_pshufhw512: 3689 case X86::BI__builtin_ia32_pshuflw: 3690 case X86::BI__builtin_ia32_pshuflw256: 3691 case X86::BI__builtin_ia32_pshuflw512: 3692 case X86::BI__builtin_ia32_vcvtps2ph: 3693 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3694 case X86::BI__builtin_ia32_vcvtps2ph256: 3695 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3696 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3697 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3698 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3699 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3700 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3701 case X86::BI__builtin_ia32_rndscaleps_mask: 3702 case X86::BI__builtin_ia32_rndscalepd_mask: 3703 case X86::BI__builtin_ia32_reducepd128_mask: 3704 case X86::BI__builtin_ia32_reducepd256_mask: 3705 case X86::BI__builtin_ia32_reducepd512_mask: 3706 case X86::BI__builtin_ia32_reduceps128_mask: 3707 case X86::BI__builtin_ia32_reduceps256_mask: 3708 case X86::BI__builtin_ia32_reduceps512_mask: 3709 case X86::BI__builtin_ia32_prold512: 3710 case X86::BI__builtin_ia32_prolq512: 3711 case X86::BI__builtin_ia32_prold128: 3712 case X86::BI__builtin_ia32_prold256: 3713 case X86::BI__builtin_ia32_prolq128: 3714 case X86::BI__builtin_ia32_prolq256: 3715 case X86::BI__builtin_ia32_prord512: 3716 case X86::BI__builtin_ia32_prorq512: 3717 case X86::BI__builtin_ia32_prord128: 3718 case X86::BI__builtin_ia32_prord256: 3719 case X86::BI__builtin_ia32_prorq128: 3720 case X86::BI__builtin_ia32_prorq256: 3721 case X86::BI__builtin_ia32_fpclasspd128_mask: 3722 case X86::BI__builtin_ia32_fpclasspd256_mask: 3723 case X86::BI__builtin_ia32_fpclassps128_mask: 3724 case X86::BI__builtin_ia32_fpclassps256_mask: 3725 case X86::BI__builtin_ia32_fpclassps512_mask: 3726 case X86::BI__builtin_ia32_fpclasspd512_mask: 3727 case X86::BI__builtin_ia32_fpclasssd_mask: 3728 case X86::BI__builtin_ia32_fpclassss_mask: 3729 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3730 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3731 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3732 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3733 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3734 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3735 case X86::BI__builtin_ia32_kshiftliqi: 3736 case X86::BI__builtin_ia32_kshiftlihi: 3737 case X86::BI__builtin_ia32_kshiftlisi: 3738 case X86::BI__builtin_ia32_kshiftlidi: 3739 case X86::BI__builtin_ia32_kshiftriqi: 3740 case X86::BI__builtin_ia32_kshiftrihi: 3741 case X86::BI__builtin_ia32_kshiftrisi: 3742 case X86::BI__builtin_ia32_kshiftridi: 3743 i = 1; l = 0; u = 255; 3744 break; 3745 case X86::BI__builtin_ia32_vperm2f128_pd256: 3746 case X86::BI__builtin_ia32_vperm2f128_ps256: 3747 case X86::BI__builtin_ia32_vperm2f128_si256: 3748 case X86::BI__builtin_ia32_permti256: 3749 case X86::BI__builtin_ia32_pblendw128: 3750 case X86::BI__builtin_ia32_pblendw256: 3751 case X86::BI__builtin_ia32_blendps256: 3752 case X86::BI__builtin_ia32_pblendd256: 3753 case X86::BI__builtin_ia32_palignr128: 3754 case X86::BI__builtin_ia32_palignr256: 3755 case X86::BI__builtin_ia32_palignr512: 3756 case X86::BI__builtin_ia32_alignq512: 3757 case X86::BI__builtin_ia32_alignd512: 3758 case X86::BI__builtin_ia32_alignd128: 3759 case X86::BI__builtin_ia32_alignd256: 3760 case X86::BI__builtin_ia32_alignq128: 3761 case X86::BI__builtin_ia32_alignq256: 3762 case X86::BI__builtin_ia32_vcomisd: 3763 case X86::BI__builtin_ia32_vcomiss: 3764 case X86::BI__builtin_ia32_shuf_f32x4: 3765 case X86::BI__builtin_ia32_shuf_f64x2: 3766 case X86::BI__builtin_ia32_shuf_i32x4: 3767 case X86::BI__builtin_ia32_shuf_i64x2: 3768 case X86::BI__builtin_ia32_shufpd512: 3769 case X86::BI__builtin_ia32_shufps: 3770 case X86::BI__builtin_ia32_shufps256: 3771 case X86::BI__builtin_ia32_shufps512: 3772 case X86::BI__builtin_ia32_dbpsadbw128: 3773 case X86::BI__builtin_ia32_dbpsadbw256: 3774 case X86::BI__builtin_ia32_dbpsadbw512: 3775 case X86::BI__builtin_ia32_vpshldd128: 3776 case X86::BI__builtin_ia32_vpshldd256: 3777 case X86::BI__builtin_ia32_vpshldd512: 3778 case X86::BI__builtin_ia32_vpshldq128: 3779 case X86::BI__builtin_ia32_vpshldq256: 3780 case X86::BI__builtin_ia32_vpshldq512: 3781 case X86::BI__builtin_ia32_vpshldw128: 3782 case X86::BI__builtin_ia32_vpshldw256: 3783 case X86::BI__builtin_ia32_vpshldw512: 3784 case X86::BI__builtin_ia32_vpshrdd128: 3785 case X86::BI__builtin_ia32_vpshrdd256: 3786 case X86::BI__builtin_ia32_vpshrdd512: 3787 case X86::BI__builtin_ia32_vpshrdq128: 3788 case X86::BI__builtin_ia32_vpshrdq256: 3789 case X86::BI__builtin_ia32_vpshrdq512: 3790 case X86::BI__builtin_ia32_vpshrdw128: 3791 case X86::BI__builtin_ia32_vpshrdw256: 3792 case X86::BI__builtin_ia32_vpshrdw512: 3793 i = 2; l = 0; u = 255; 3794 break; 3795 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3796 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3797 case X86::BI__builtin_ia32_fixupimmps512_mask: 3798 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3799 case X86::BI__builtin_ia32_fixupimmsd_mask: 3800 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3801 case X86::BI__builtin_ia32_fixupimmss_mask: 3802 case X86::BI__builtin_ia32_fixupimmss_maskz: 3803 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3804 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3805 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3806 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3807 case X86::BI__builtin_ia32_fixupimmps128_mask: 3808 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3809 case X86::BI__builtin_ia32_fixupimmps256_mask: 3810 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3811 case X86::BI__builtin_ia32_pternlogd512_mask: 3812 case X86::BI__builtin_ia32_pternlogd512_maskz: 3813 case X86::BI__builtin_ia32_pternlogq512_mask: 3814 case X86::BI__builtin_ia32_pternlogq512_maskz: 3815 case X86::BI__builtin_ia32_pternlogd128_mask: 3816 case X86::BI__builtin_ia32_pternlogd128_maskz: 3817 case X86::BI__builtin_ia32_pternlogd256_mask: 3818 case X86::BI__builtin_ia32_pternlogd256_maskz: 3819 case X86::BI__builtin_ia32_pternlogq128_mask: 3820 case X86::BI__builtin_ia32_pternlogq128_maskz: 3821 case X86::BI__builtin_ia32_pternlogq256_mask: 3822 case X86::BI__builtin_ia32_pternlogq256_maskz: 3823 i = 3; l = 0; u = 255; 3824 break; 3825 case X86::BI__builtin_ia32_gatherpfdpd: 3826 case X86::BI__builtin_ia32_gatherpfdps: 3827 case X86::BI__builtin_ia32_gatherpfqpd: 3828 case X86::BI__builtin_ia32_gatherpfqps: 3829 case X86::BI__builtin_ia32_scatterpfdpd: 3830 case X86::BI__builtin_ia32_scatterpfdps: 3831 case X86::BI__builtin_ia32_scatterpfqpd: 3832 case X86::BI__builtin_ia32_scatterpfqps: 3833 i = 4; l = 2; u = 3; 3834 break; 3835 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3836 case X86::BI__builtin_ia32_rndscaless_round_mask: 3837 i = 4; l = 0; u = 255; 3838 break; 3839 } 3840 3841 // Note that we don't force a hard error on the range check here, allowing 3842 // template-generated or macro-generated dead code to potentially have out-of- 3843 // range values. These need to code generate, but don't need to necessarily 3844 // make any sense. We use a warning that defaults to an error. 3845 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3846 } 3847 3848 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3849 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3850 /// Returns true when the format fits the function and the FormatStringInfo has 3851 /// been populated. 3852 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3853 FormatStringInfo *FSI) { 3854 FSI->HasVAListArg = Format->getFirstArg() == 0; 3855 FSI->FormatIdx = Format->getFormatIdx() - 1; 3856 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3857 3858 // The way the format attribute works in GCC, the implicit this argument 3859 // of member functions is counted. However, it doesn't appear in our own 3860 // lists, so decrement format_idx in that case. 3861 if (IsCXXMember) { 3862 if(FSI->FormatIdx == 0) 3863 return false; 3864 --FSI->FormatIdx; 3865 if (FSI->FirstDataArg != 0) 3866 --FSI->FirstDataArg; 3867 } 3868 return true; 3869 } 3870 3871 /// Checks if a the given expression evaluates to null. 3872 /// 3873 /// Returns true if the value evaluates to null. 3874 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3875 // If the expression has non-null type, it doesn't evaluate to null. 3876 if (auto nullability 3877 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3878 if (*nullability == NullabilityKind::NonNull) 3879 return false; 3880 } 3881 3882 // As a special case, transparent unions initialized with zero are 3883 // considered null for the purposes of the nonnull attribute. 3884 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3885 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3886 if (const CompoundLiteralExpr *CLE = 3887 dyn_cast<CompoundLiteralExpr>(Expr)) 3888 if (const InitListExpr *ILE = 3889 dyn_cast<InitListExpr>(CLE->getInitializer())) 3890 Expr = ILE->getInit(0); 3891 } 3892 3893 bool Result; 3894 return (!Expr->isValueDependent() && 3895 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3896 !Result); 3897 } 3898 3899 static void CheckNonNullArgument(Sema &S, 3900 const Expr *ArgExpr, 3901 SourceLocation CallSiteLoc) { 3902 if (CheckNonNullExpr(S, ArgExpr)) 3903 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3904 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 3905 } 3906 3907 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3908 FormatStringInfo FSI; 3909 if ((GetFormatStringType(Format) == FST_NSString) && 3910 getFormatStringInfo(Format, false, &FSI)) { 3911 Idx = FSI.FormatIdx; 3912 return true; 3913 } 3914 return false; 3915 } 3916 3917 /// Diagnose use of %s directive in an NSString which is being passed 3918 /// as formatting string to formatting method. 3919 static void 3920 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3921 const NamedDecl *FDecl, 3922 Expr **Args, 3923 unsigned NumArgs) { 3924 unsigned Idx = 0; 3925 bool Format = false; 3926 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3927 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3928 Idx = 2; 3929 Format = true; 3930 } 3931 else 3932 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3933 if (S.GetFormatNSStringIdx(I, Idx)) { 3934 Format = true; 3935 break; 3936 } 3937 } 3938 if (!Format || NumArgs <= Idx) 3939 return; 3940 const Expr *FormatExpr = Args[Idx]; 3941 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3942 FormatExpr = CSCE->getSubExpr(); 3943 const StringLiteral *FormatString; 3944 if (const ObjCStringLiteral *OSL = 3945 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3946 FormatString = OSL->getString(); 3947 else 3948 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3949 if (!FormatString) 3950 return; 3951 if (S.FormatStringHasSArg(FormatString)) { 3952 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3953 << "%s" << 1 << 1; 3954 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3955 << FDecl->getDeclName(); 3956 } 3957 } 3958 3959 /// Determine whether the given type has a non-null nullability annotation. 3960 static bool isNonNullType(ASTContext &ctx, QualType type) { 3961 if (auto nullability = type->getNullability(ctx)) 3962 return *nullability == NullabilityKind::NonNull; 3963 3964 return false; 3965 } 3966 3967 static void CheckNonNullArguments(Sema &S, 3968 const NamedDecl *FDecl, 3969 const FunctionProtoType *Proto, 3970 ArrayRef<const Expr *> Args, 3971 SourceLocation CallSiteLoc) { 3972 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3973 3974 // Check the attributes attached to the method/function itself. 3975 llvm::SmallBitVector NonNullArgs; 3976 if (FDecl) { 3977 // Handle the nonnull attribute on the function/method declaration itself. 3978 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3979 if (!NonNull->args_size()) { 3980 // Easy case: all pointer arguments are nonnull. 3981 for (const auto *Arg : Args) 3982 if (S.isValidPointerAttrType(Arg->getType())) 3983 CheckNonNullArgument(S, Arg, CallSiteLoc); 3984 return; 3985 } 3986 3987 for (const ParamIdx &Idx : NonNull->args()) { 3988 unsigned IdxAST = Idx.getASTIndex(); 3989 if (IdxAST >= Args.size()) 3990 continue; 3991 if (NonNullArgs.empty()) 3992 NonNullArgs.resize(Args.size()); 3993 NonNullArgs.set(IdxAST); 3994 } 3995 } 3996 } 3997 3998 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3999 // Handle the nonnull attribute on the parameters of the 4000 // function/method. 4001 ArrayRef<ParmVarDecl*> parms; 4002 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4003 parms = FD->parameters(); 4004 else 4005 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4006 4007 unsigned ParamIndex = 0; 4008 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4009 I != E; ++I, ++ParamIndex) { 4010 const ParmVarDecl *PVD = *I; 4011 if (PVD->hasAttr<NonNullAttr>() || 4012 isNonNullType(S.Context, PVD->getType())) { 4013 if (NonNullArgs.empty()) 4014 NonNullArgs.resize(Args.size()); 4015 4016 NonNullArgs.set(ParamIndex); 4017 } 4018 } 4019 } else { 4020 // If we have a non-function, non-method declaration but no 4021 // function prototype, try to dig out the function prototype. 4022 if (!Proto) { 4023 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4024 QualType type = VD->getType().getNonReferenceType(); 4025 if (auto pointerType = type->getAs<PointerType>()) 4026 type = pointerType->getPointeeType(); 4027 else if (auto blockType = type->getAs<BlockPointerType>()) 4028 type = blockType->getPointeeType(); 4029 // FIXME: data member pointers? 4030 4031 // Dig out the function prototype, if there is one. 4032 Proto = type->getAs<FunctionProtoType>(); 4033 } 4034 } 4035 4036 // Fill in non-null argument information from the nullability 4037 // information on the parameter types (if we have them). 4038 if (Proto) { 4039 unsigned Index = 0; 4040 for (auto paramType : Proto->getParamTypes()) { 4041 if (isNonNullType(S.Context, paramType)) { 4042 if (NonNullArgs.empty()) 4043 NonNullArgs.resize(Args.size()); 4044 4045 NonNullArgs.set(Index); 4046 } 4047 4048 ++Index; 4049 } 4050 } 4051 } 4052 4053 // Check for non-null arguments. 4054 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4055 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4056 if (NonNullArgs[ArgIndex]) 4057 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4058 } 4059 } 4060 4061 /// Handles the checks for format strings, non-POD arguments to vararg 4062 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4063 /// attributes. 4064 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4065 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4066 bool IsMemberFunction, SourceLocation Loc, 4067 SourceRange Range, VariadicCallType CallType) { 4068 // FIXME: We should check as much as we can in the template definition. 4069 if (CurContext->isDependentContext()) 4070 return; 4071 4072 // Printf and scanf checking. 4073 llvm::SmallBitVector CheckedVarArgs; 4074 if (FDecl) { 4075 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4076 // Only create vector if there are format attributes. 4077 CheckedVarArgs.resize(Args.size()); 4078 4079 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4080 CheckedVarArgs); 4081 } 4082 } 4083 4084 // Refuse POD arguments that weren't caught by the format string 4085 // checks above. 4086 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4087 if (CallType != VariadicDoesNotApply && 4088 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4089 unsigned NumParams = Proto ? Proto->getNumParams() 4090 : FDecl && isa<FunctionDecl>(FDecl) 4091 ? cast<FunctionDecl>(FDecl)->getNumParams() 4092 : FDecl && isa<ObjCMethodDecl>(FDecl) 4093 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4094 : 0; 4095 4096 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4097 // Args[ArgIdx] can be null in malformed code. 4098 if (const Expr *Arg = Args[ArgIdx]) { 4099 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4100 checkVariadicArgument(Arg, CallType); 4101 } 4102 } 4103 } 4104 4105 if (FDecl || Proto) { 4106 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4107 4108 // Type safety checking. 4109 if (FDecl) { 4110 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4111 CheckArgumentWithTypeTag(I, Args, Loc); 4112 } 4113 } 4114 4115 if (FD) 4116 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4117 } 4118 4119 /// CheckConstructorCall - Check a constructor call for correctness and safety 4120 /// properties not enforced by the C type system. 4121 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4122 ArrayRef<const Expr *> Args, 4123 const FunctionProtoType *Proto, 4124 SourceLocation Loc) { 4125 VariadicCallType CallType = 4126 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4127 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4128 Loc, SourceRange(), CallType); 4129 } 4130 4131 /// CheckFunctionCall - Check a direct function call for various correctness 4132 /// and safety properties not strictly enforced by the C type system. 4133 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4134 const FunctionProtoType *Proto) { 4135 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4136 isa<CXXMethodDecl>(FDecl); 4137 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4138 IsMemberOperatorCall; 4139 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4140 TheCall->getCallee()); 4141 Expr** Args = TheCall->getArgs(); 4142 unsigned NumArgs = TheCall->getNumArgs(); 4143 4144 Expr *ImplicitThis = nullptr; 4145 if (IsMemberOperatorCall) { 4146 // If this is a call to a member operator, hide the first argument 4147 // from checkCall. 4148 // FIXME: Our choice of AST representation here is less than ideal. 4149 ImplicitThis = Args[0]; 4150 ++Args; 4151 --NumArgs; 4152 } else if (IsMemberFunction) 4153 ImplicitThis = 4154 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4155 4156 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4157 IsMemberFunction, TheCall->getRParenLoc(), 4158 TheCall->getCallee()->getSourceRange(), CallType); 4159 4160 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4161 // None of the checks below are needed for functions that don't have 4162 // simple names (e.g., C++ conversion functions). 4163 if (!FnInfo) 4164 return false; 4165 4166 CheckAbsoluteValueFunction(TheCall, FDecl); 4167 CheckMaxUnsignedZero(TheCall, FDecl); 4168 4169 if (getLangOpts().ObjC) 4170 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4171 4172 unsigned CMId = FDecl->getMemoryFunctionKind(); 4173 if (CMId == 0) 4174 return false; 4175 4176 // Handle memory setting and copying functions. 4177 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4178 CheckStrlcpycatArguments(TheCall, FnInfo); 4179 else if (CMId == Builtin::BIstrncat) 4180 CheckStrncatArguments(TheCall, FnInfo); 4181 else 4182 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4183 4184 return false; 4185 } 4186 4187 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4188 ArrayRef<const Expr *> Args) { 4189 VariadicCallType CallType = 4190 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4191 4192 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4193 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4194 CallType); 4195 4196 return false; 4197 } 4198 4199 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4200 const FunctionProtoType *Proto) { 4201 QualType Ty; 4202 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4203 Ty = V->getType().getNonReferenceType(); 4204 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4205 Ty = F->getType().getNonReferenceType(); 4206 else 4207 return false; 4208 4209 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4210 !Ty->isFunctionProtoType()) 4211 return false; 4212 4213 VariadicCallType CallType; 4214 if (!Proto || !Proto->isVariadic()) { 4215 CallType = VariadicDoesNotApply; 4216 } else if (Ty->isBlockPointerType()) { 4217 CallType = VariadicBlock; 4218 } else { // Ty->isFunctionPointerType() 4219 CallType = VariadicFunction; 4220 } 4221 4222 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4223 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4224 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4225 TheCall->getCallee()->getSourceRange(), CallType); 4226 4227 return false; 4228 } 4229 4230 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4231 /// such as function pointers returned from functions. 4232 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4233 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4234 TheCall->getCallee()); 4235 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4236 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4237 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4238 TheCall->getCallee()->getSourceRange(), CallType); 4239 4240 return false; 4241 } 4242 4243 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4244 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4245 return false; 4246 4247 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4248 switch (Op) { 4249 case AtomicExpr::AO__c11_atomic_init: 4250 case AtomicExpr::AO__opencl_atomic_init: 4251 llvm_unreachable("There is no ordering argument for an init"); 4252 4253 case AtomicExpr::AO__c11_atomic_load: 4254 case AtomicExpr::AO__opencl_atomic_load: 4255 case AtomicExpr::AO__atomic_load_n: 4256 case AtomicExpr::AO__atomic_load: 4257 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4258 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4259 4260 case AtomicExpr::AO__c11_atomic_store: 4261 case AtomicExpr::AO__opencl_atomic_store: 4262 case AtomicExpr::AO__atomic_store: 4263 case AtomicExpr::AO__atomic_store_n: 4264 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4265 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4266 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4267 4268 default: 4269 return true; 4270 } 4271 } 4272 4273 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4274 AtomicExpr::AtomicOp Op) { 4275 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4276 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4277 4278 // All the non-OpenCL operations take one of the following forms. 4279 // The OpenCL operations take the __c11 forms with one extra argument for 4280 // synchronization scope. 4281 enum { 4282 // C __c11_atomic_init(A *, C) 4283 Init, 4284 4285 // C __c11_atomic_load(A *, int) 4286 Load, 4287 4288 // void __atomic_load(A *, CP, int) 4289 LoadCopy, 4290 4291 // void __atomic_store(A *, CP, int) 4292 Copy, 4293 4294 // C __c11_atomic_add(A *, M, int) 4295 Arithmetic, 4296 4297 // C __atomic_exchange_n(A *, CP, int) 4298 Xchg, 4299 4300 // void __atomic_exchange(A *, C *, CP, int) 4301 GNUXchg, 4302 4303 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4304 C11CmpXchg, 4305 4306 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4307 GNUCmpXchg 4308 } Form = Init; 4309 4310 const unsigned NumForm = GNUCmpXchg + 1; 4311 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4312 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4313 // where: 4314 // C is an appropriate type, 4315 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4316 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4317 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4318 // the int parameters are for orderings. 4319 4320 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4321 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4322 "need to update code for modified forms"); 4323 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4324 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4325 AtomicExpr::AO__atomic_load, 4326 "need to update code for modified C11 atomics"); 4327 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4328 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4329 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4330 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4331 IsOpenCL; 4332 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4333 Op == AtomicExpr::AO__atomic_store_n || 4334 Op == AtomicExpr::AO__atomic_exchange_n || 4335 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4336 bool IsAddSub = false; 4337 bool IsMinMax = false; 4338 4339 switch (Op) { 4340 case AtomicExpr::AO__c11_atomic_init: 4341 case AtomicExpr::AO__opencl_atomic_init: 4342 Form = Init; 4343 break; 4344 4345 case AtomicExpr::AO__c11_atomic_load: 4346 case AtomicExpr::AO__opencl_atomic_load: 4347 case AtomicExpr::AO__atomic_load_n: 4348 Form = Load; 4349 break; 4350 4351 case AtomicExpr::AO__atomic_load: 4352 Form = LoadCopy; 4353 break; 4354 4355 case AtomicExpr::AO__c11_atomic_store: 4356 case AtomicExpr::AO__opencl_atomic_store: 4357 case AtomicExpr::AO__atomic_store: 4358 case AtomicExpr::AO__atomic_store_n: 4359 Form = Copy; 4360 break; 4361 4362 case AtomicExpr::AO__c11_atomic_fetch_add: 4363 case AtomicExpr::AO__c11_atomic_fetch_sub: 4364 case AtomicExpr::AO__opencl_atomic_fetch_add: 4365 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4366 case AtomicExpr::AO__opencl_atomic_fetch_min: 4367 case AtomicExpr::AO__opencl_atomic_fetch_max: 4368 case AtomicExpr::AO__atomic_fetch_add: 4369 case AtomicExpr::AO__atomic_fetch_sub: 4370 case AtomicExpr::AO__atomic_add_fetch: 4371 case AtomicExpr::AO__atomic_sub_fetch: 4372 IsAddSub = true; 4373 LLVM_FALLTHROUGH; 4374 case AtomicExpr::AO__c11_atomic_fetch_and: 4375 case AtomicExpr::AO__c11_atomic_fetch_or: 4376 case AtomicExpr::AO__c11_atomic_fetch_xor: 4377 case AtomicExpr::AO__opencl_atomic_fetch_and: 4378 case AtomicExpr::AO__opencl_atomic_fetch_or: 4379 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4380 case AtomicExpr::AO__atomic_fetch_and: 4381 case AtomicExpr::AO__atomic_fetch_or: 4382 case AtomicExpr::AO__atomic_fetch_xor: 4383 case AtomicExpr::AO__atomic_fetch_nand: 4384 case AtomicExpr::AO__atomic_and_fetch: 4385 case AtomicExpr::AO__atomic_or_fetch: 4386 case AtomicExpr::AO__atomic_xor_fetch: 4387 case AtomicExpr::AO__atomic_nand_fetch: 4388 Form = Arithmetic; 4389 break; 4390 4391 case AtomicExpr::AO__atomic_fetch_min: 4392 case AtomicExpr::AO__atomic_fetch_max: 4393 IsMinMax = true; 4394 Form = Arithmetic; 4395 break; 4396 4397 case AtomicExpr::AO__c11_atomic_exchange: 4398 case AtomicExpr::AO__opencl_atomic_exchange: 4399 case AtomicExpr::AO__atomic_exchange_n: 4400 Form = Xchg; 4401 break; 4402 4403 case AtomicExpr::AO__atomic_exchange: 4404 Form = GNUXchg; 4405 break; 4406 4407 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4408 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4409 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4410 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4411 Form = C11CmpXchg; 4412 break; 4413 4414 case AtomicExpr::AO__atomic_compare_exchange: 4415 case AtomicExpr::AO__atomic_compare_exchange_n: 4416 Form = GNUCmpXchg; 4417 break; 4418 } 4419 4420 unsigned AdjustedNumArgs = NumArgs[Form]; 4421 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4422 ++AdjustedNumArgs; 4423 // Check we have the right number of arguments. 4424 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4425 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4426 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4427 << TheCall->getCallee()->getSourceRange(); 4428 return ExprError(); 4429 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4430 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4431 diag::err_typecheck_call_too_many_args) 4432 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4433 << TheCall->getCallee()->getSourceRange(); 4434 return ExprError(); 4435 } 4436 4437 // Inspect the first argument of the atomic operation. 4438 Expr *Ptr = TheCall->getArg(0); 4439 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4440 if (ConvertedPtr.isInvalid()) 4441 return ExprError(); 4442 4443 Ptr = ConvertedPtr.get(); 4444 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4445 if (!pointerType) { 4446 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4447 << Ptr->getType() << Ptr->getSourceRange(); 4448 return ExprError(); 4449 } 4450 4451 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4452 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4453 QualType ValType = AtomTy; // 'C' 4454 if (IsC11) { 4455 if (!AtomTy->isAtomicType()) { 4456 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4457 << Ptr->getType() << Ptr->getSourceRange(); 4458 return ExprError(); 4459 } 4460 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4461 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4462 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4463 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4464 << Ptr->getSourceRange(); 4465 return ExprError(); 4466 } 4467 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4468 } else if (Form != Load && Form != LoadCopy) { 4469 if (ValType.isConstQualified()) { 4470 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4471 << Ptr->getType() << Ptr->getSourceRange(); 4472 return ExprError(); 4473 } 4474 } 4475 4476 // For an arithmetic operation, the implied arithmetic must be well-formed. 4477 if (Form == Arithmetic) { 4478 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4479 if (IsAddSub && !ValType->isIntegerType() 4480 && !ValType->isPointerType()) { 4481 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4482 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4483 return ExprError(); 4484 } 4485 if (IsMinMax) { 4486 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4487 if (!BT || (BT->getKind() != BuiltinType::Int && 4488 BT->getKind() != BuiltinType::UInt)) { 4489 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4490 return ExprError(); 4491 } 4492 } 4493 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4494 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4495 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4496 return ExprError(); 4497 } 4498 if (IsC11 && ValType->isPointerType() && 4499 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4500 diag::err_incomplete_type)) { 4501 return ExprError(); 4502 } 4503 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4504 // For __atomic_*_n operations, the value type must be a scalar integral or 4505 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4506 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4507 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4508 return ExprError(); 4509 } 4510 4511 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4512 !AtomTy->isScalarType()) { 4513 // For GNU atomics, require a trivially-copyable type. This is not part of 4514 // the GNU atomics specification, but we enforce it for sanity. 4515 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4516 << Ptr->getType() << Ptr->getSourceRange(); 4517 return ExprError(); 4518 } 4519 4520 switch (ValType.getObjCLifetime()) { 4521 case Qualifiers::OCL_None: 4522 case Qualifiers::OCL_ExplicitNone: 4523 // okay 4524 break; 4525 4526 case Qualifiers::OCL_Weak: 4527 case Qualifiers::OCL_Strong: 4528 case Qualifiers::OCL_Autoreleasing: 4529 // FIXME: Can this happen? By this point, ValType should be known 4530 // to be trivially copyable. 4531 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4532 << ValType << Ptr->getSourceRange(); 4533 return ExprError(); 4534 } 4535 4536 // All atomic operations have an overload which takes a pointer to a volatile 4537 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4538 // into the result or the other operands. Similarly atomic_load takes a 4539 // pointer to a const 'A'. 4540 ValType.removeLocalVolatile(); 4541 ValType.removeLocalConst(); 4542 QualType ResultType = ValType; 4543 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4544 Form == Init) 4545 ResultType = Context.VoidTy; 4546 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4547 ResultType = Context.BoolTy; 4548 4549 // The type of a parameter passed 'by value'. In the GNU atomics, such 4550 // arguments are actually passed as pointers. 4551 QualType ByValType = ValType; // 'CP' 4552 bool IsPassedByAddress = false; 4553 if (!IsC11 && !IsN) { 4554 ByValType = Ptr->getType(); 4555 IsPassedByAddress = true; 4556 } 4557 4558 // The first argument's non-CV pointer type is used to deduce the type of 4559 // subsequent arguments, except for: 4560 // - weak flag (always converted to bool) 4561 // - memory order (always converted to int) 4562 // - scope (always converted to int) 4563 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4564 QualType Ty; 4565 if (i < NumVals[Form] + 1) { 4566 switch (i) { 4567 case 0: 4568 // The first argument is always a pointer. It has a fixed type. 4569 // It is always dereferenced, a nullptr is undefined. 4570 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4571 // Nothing else to do: we already know all we want about this pointer. 4572 continue; 4573 case 1: 4574 // The second argument is the non-atomic operand. For arithmetic, this 4575 // is always passed by value, and for a compare_exchange it is always 4576 // passed by address. For the rest, GNU uses by-address and C11 uses 4577 // by-value. 4578 assert(Form != Load); 4579 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4580 Ty = ValType; 4581 else if (Form == Copy || Form == Xchg) { 4582 if (IsPassedByAddress) 4583 // The value pointer is always dereferenced, a nullptr is undefined. 4584 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4585 Ty = ByValType; 4586 } else if (Form == Arithmetic) 4587 Ty = Context.getPointerDiffType(); 4588 else { 4589 Expr *ValArg = TheCall->getArg(i); 4590 // The value pointer is always dereferenced, a nullptr is undefined. 4591 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4592 LangAS AS = LangAS::Default; 4593 // Keep address space of non-atomic pointer type. 4594 if (const PointerType *PtrTy = 4595 ValArg->getType()->getAs<PointerType>()) { 4596 AS = PtrTy->getPointeeType().getAddressSpace(); 4597 } 4598 Ty = Context.getPointerType( 4599 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4600 } 4601 break; 4602 case 2: 4603 // The third argument to compare_exchange / GNU exchange is the desired 4604 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4605 if (IsPassedByAddress) 4606 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4607 Ty = ByValType; 4608 break; 4609 case 3: 4610 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4611 Ty = Context.BoolTy; 4612 break; 4613 } 4614 } else { 4615 // The order(s) and scope are always converted to int. 4616 Ty = Context.IntTy; 4617 } 4618 4619 InitializedEntity Entity = 4620 InitializedEntity::InitializeParameter(Context, Ty, false); 4621 ExprResult Arg = TheCall->getArg(i); 4622 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4623 if (Arg.isInvalid()) 4624 return true; 4625 TheCall->setArg(i, Arg.get()); 4626 } 4627 4628 // Permute the arguments into a 'consistent' order. 4629 SmallVector<Expr*, 5> SubExprs; 4630 SubExprs.push_back(Ptr); 4631 switch (Form) { 4632 case Init: 4633 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4634 SubExprs.push_back(TheCall->getArg(1)); // Val1 4635 break; 4636 case Load: 4637 SubExprs.push_back(TheCall->getArg(1)); // Order 4638 break; 4639 case LoadCopy: 4640 case Copy: 4641 case Arithmetic: 4642 case Xchg: 4643 SubExprs.push_back(TheCall->getArg(2)); // Order 4644 SubExprs.push_back(TheCall->getArg(1)); // Val1 4645 break; 4646 case GNUXchg: 4647 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4648 SubExprs.push_back(TheCall->getArg(3)); // Order 4649 SubExprs.push_back(TheCall->getArg(1)); // Val1 4650 SubExprs.push_back(TheCall->getArg(2)); // Val2 4651 break; 4652 case C11CmpXchg: 4653 SubExprs.push_back(TheCall->getArg(3)); // Order 4654 SubExprs.push_back(TheCall->getArg(1)); // Val1 4655 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4656 SubExprs.push_back(TheCall->getArg(2)); // Val2 4657 break; 4658 case GNUCmpXchg: 4659 SubExprs.push_back(TheCall->getArg(4)); // Order 4660 SubExprs.push_back(TheCall->getArg(1)); // Val1 4661 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4662 SubExprs.push_back(TheCall->getArg(2)); // Val2 4663 SubExprs.push_back(TheCall->getArg(3)); // Weak 4664 break; 4665 } 4666 4667 if (SubExprs.size() >= 2 && Form != Init) { 4668 llvm::APSInt Result(32); 4669 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4670 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4671 Diag(SubExprs[1]->getBeginLoc(), 4672 diag::warn_atomic_op_has_invalid_memory_order) 4673 << SubExprs[1]->getSourceRange(); 4674 } 4675 4676 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4677 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4678 llvm::APSInt Result(32); 4679 if (Scope->isIntegerConstantExpr(Result, Context) && 4680 !ScopeModel->isValid(Result.getZExtValue())) { 4681 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4682 << Scope->getSourceRange(); 4683 } 4684 SubExprs.push_back(Scope); 4685 } 4686 4687 AtomicExpr *AE = 4688 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4689 ResultType, Op, TheCall->getRParenLoc()); 4690 4691 if ((Op == AtomicExpr::AO__c11_atomic_load || 4692 Op == AtomicExpr::AO__c11_atomic_store || 4693 Op == AtomicExpr::AO__opencl_atomic_load || 4694 Op == AtomicExpr::AO__opencl_atomic_store ) && 4695 Context.AtomicUsesUnsupportedLibcall(AE)) 4696 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4697 << ((Op == AtomicExpr::AO__c11_atomic_load || 4698 Op == AtomicExpr::AO__opencl_atomic_load) 4699 ? 0 4700 : 1); 4701 4702 return AE; 4703 } 4704 4705 /// checkBuiltinArgument - Given a call to a builtin function, perform 4706 /// normal type-checking on the given argument, updating the call in 4707 /// place. This is useful when a builtin function requires custom 4708 /// type-checking for some of its arguments but not necessarily all of 4709 /// them. 4710 /// 4711 /// Returns true on error. 4712 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4713 FunctionDecl *Fn = E->getDirectCallee(); 4714 assert(Fn && "builtin call without direct callee!"); 4715 4716 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4717 InitializedEntity Entity = 4718 InitializedEntity::InitializeParameter(S.Context, Param); 4719 4720 ExprResult Arg = E->getArg(0); 4721 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4722 if (Arg.isInvalid()) 4723 return true; 4724 4725 E->setArg(ArgIndex, Arg.get()); 4726 return false; 4727 } 4728 4729 /// We have a call to a function like __sync_fetch_and_add, which is an 4730 /// overloaded function based on the pointer type of its first argument. 4731 /// The main ActOnCallExpr routines have already promoted the types of 4732 /// arguments because all of these calls are prototyped as void(...). 4733 /// 4734 /// This function goes through and does final semantic checking for these 4735 /// builtins, as well as generating any warnings. 4736 ExprResult 4737 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4738 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4739 Expr *Callee = TheCall->getCallee(); 4740 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4741 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4742 4743 // Ensure that we have at least one argument to do type inference from. 4744 if (TheCall->getNumArgs() < 1) { 4745 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4746 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4747 return ExprError(); 4748 } 4749 4750 // Inspect the first argument of the atomic builtin. This should always be 4751 // a pointer type, whose element is an integral scalar or pointer type. 4752 // Because it is a pointer type, we don't have to worry about any implicit 4753 // casts here. 4754 // FIXME: We don't allow floating point scalars as input. 4755 Expr *FirstArg = TheCall->getArg(0); 4756 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4757 if (FirstArgResult.isInvalid()) 4758 return ExprError(); 4759 FirstArg = FirstArgResult.get(); 4760 TheCall->setArg(0, FirstArg); 4761 4762 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4763 if (!pointerType) { 4764 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4765 << FirstArg->getType() << FirstArg->getSourceRange(); 4766 return ExprError(); 4767 } 4768 4769 QualType ValType = pointerType->getPointeeType(); 4770 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4771 !ValType->isBlockPointerType()) { 4772 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4773 << FirstArg->getType() << FirstArg->getSourceRange(); 4774 return ExprError(); 4775 } 4776 4777 if (ValType.isConstQualified()) { 4778 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4779 << FirstArg->getType() << FirstArg->getSourceRange(); 4780 return ExprError(); 4781 } 4782 4783 switch (ValType.getObjCLifetime()) { 4784 case Qualifiers::OCL_None: 4785 case Qualifiers::OCL_ExplicitNone: 4786 // okay 4787 break; 4788 4789 case Qualifiers::OCL_Weak: 4790 case Qualifiers::OCL_Strong: 4791 case Qualifiers::OCL_Autoreleasing: 4792 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4793 << ValType << FirstArg->getSourceRange(); 4794 return ExprError(); 4795 } 4796 4797 // Strip any qualifiers off ValType. 4798 ValType = ValType.getUnqualifiedType(); 4799 4800 // The majority of builtins return a value, but a few have special return 4801 // types, so allow them to override appropriately below. 4802 QualType ResultType = ValType; 4803 4804 // We need to figure out which concrete builtin this maps onto. For example, 4805 // __sync_fetch_and_add with a 2 byte object turns into 4806 // __sync_fetch_and_add_2. 4807 #define BUILTIN_ROW(x) \ 4808 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4809 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4810 4811 static const unsigned BuiltinIndices[][5] = { 4812 BUILTIN_ROW(__sync_fetch_and_add), 4813 BUILTIN_ROW(__sync_fetch_and_sub), 4814 BUILTIN_ROW(__sync_fetch_and_or), 4815 BUILTIN_ROW(__sync_fetch_and_and), 4816 BUILTIN_ROW(__sync_fetch_and_xor), 4817 BUILTIN_ROW(__sync_fetch_and_nand), 4818 4819 BUILTIN_ROW(__sync_add_and_fetch), 4820 BUILTIN_ROW(__sync_sub_and_fetch), 4821 BUILTIN_ROW(__sync_and_and_fetch), 4822 BUILTIN_ROW(__sync_or_and_fetch), 4823 BUILTIN_ROW(__sync_xor_and_fetch), 4824 BUILTIN_ROW(__sync_nand_and_fetch), 4825 4826 BUILTIN_ROW(__sync_val_compare_and_swap), 4827 BUILTIN_ROW(__sync_bool_compare_and_swap), 4828 BUILTIN_ROW(__sync_lock_test_and_set), 4829 BUILTIN_ROW(__sync_lock_release), 4830 BUILTIN_ROW(__sync_swap) 4831 }; 4832 #undef BUILTIN_ROW 4833 4834 // Determine the index of the size. 4835 unsigned SizeIndex; 4836 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4837 case 1: SizeIndex = 0; break; 4838 case 2: SizeIndex = 1; break; 4839 case 4: SizeIndex = 2; break; 4840 case 8: SizeIndex = 3; break; 4841 case 16: SizeIndex = 4; break; 4842 default: 4843 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4844 << FirstArg->getType() << FirstArg->getSourceRange(); 4845 return ExprError(); 4846 } 4847 4848 // Each of these builtins has one pointer argument, followed by some number of 4849 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4850 // that we ignore. Find out which row of BuiltinIndices to read from as well 4851 // as the number of fixed args. 4852 unsigned BuiltinID = FDecl->getBuiltinID(); 4853 unsigned BuiltinIndex, NumFixed = 1; 4854 bool WarnAboutSemanticsChange = false; 4855 switch (BuiltinID) { 4856 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4857 case Builtin::BI__sync_fetch_and_add: 4858 case Builtin::BI__sync_fetch_and_add_1: 4859 case Builtin::BI__sync_fetch_and_add_2: 4860 case Builtin::BI__sync_fetch_and_add_4: 4861 case Builtin::BI__sync_fetch_and_add_8: 4862 case Builtin::BI__sync_fetch_and_add_16: 4863 BuiltinIndex = 0; 4864 break; 4865 4866 case Builtin::BI__sync_fetch_and_sub: 4867 case Builtin::BI__sync_fetch_and_sub_1: 4868 case Builtin::BI__sync_fetch_and_sub_2: 4869 case Builtin::BI__sync_fetch_and_sub_4: 4870 case Builtin::BI__sync_fetch_and_sub_8: 4871 case Builtin::BI__sync_fetch_and_sub_16: 4872 BuiltinIndex = 1; 4873 break; 4874 4875 case Builtin::BI__sync_fetch_and_or: 4876 case Builtin::BI__sync_fetch_and_or_1: 4877 case Builtin::BI__sync_fetch_and_or_2: 4878 case Builtin::BI__sync_fetch_and_or_4: 4879 case Builtin::BI__sync_fetch_and_or_8: 4880 case Builtin::BI__sync_fetch_and_or_16: 4881 BuiltinIndex = 2; 4882 break; 4883 4884 case Builtin::BI__sync_fetch_and_and: 4885 case Builtin::BI__sync_fetch_and_and_1: 4886 case Builtin::BI__sync_fetch_and_and_2: 4887 case Builtin::BI__sync_fetch_and_and_4: 4888 case Builtin::BI__sync_fetch_and_and_8: 4889 case Builtin::BI__sync_fetch_and_and_16: 4890 BuiltinIndex = 3; 4891 break; 4892 4893 case Builtin::BI__sync_fetch_and_xor: 4894 case Builtin::BI__sync_fetch_and_xor_1: 4895 case Builtin::BI__sync_fetch_and_xor_2: 4896 case Builtin::BI__sync_fetch_and_xor_4: 4897 case Builtin::BI__sync_fetch_and_xor_8: 4898 case Builtin::BI__sync_fetch_and_xor_16: 4899 BuiltinIndex = 4; 4900 break; 4901 4902 case Builtin::BI__sync_fetch_and_nand: 4903 case Builtin::BI__sync_fetch_and_nand_1: 4904 case Builtin::BI__sync_fetch_and_nand_2: 4905 case Builtin::BI__sync_fetch_and_nand_4: 4906 case Builtin::BI__sync_fetch_and_nand_8: 4907 case Builtin::BI__sync_fetch_and_nand_16: 4908 BuiltinIndex = 5; 4909 WarnAboutSemanticsChange = true; 4910 break; 4911 4912 case Builtin::BI__sync_add_and_fetch: 4913 case Builtin::BI__sync_add_and_fetch_1: 4914 case Builtin::BI__sync_add_and_fetch_2: 4915 case Builtin::BI__sync_add_and_fetch_4: 4916 case Builtin::BI__sync_add_and_fetch_8: 4917 case Builtin::BI__sync_add_and_fetch_16: 4918 BuiltinIndex = 6; 4919 break; 4920 4921 case Builtin::BI__sync_sub_and_fetch: 4922 case Builtin::BI__sync_sub_and_fetch_1: 4923 case Builtin::BI__sync_sub_and_fetch_2: 4924 case Builtin::BI__sync_sub_and_fetch_4: 4925 case Builtin::BI__sync_sub_and_fetch_8: 4926 case Builtin::BI__sync_sub_and_fetch_16: 4927 BuiltinIndex = 7; 4928 break; 4929 4930 case Builtin::BI__sync_and_and_fetch: 4931 case Builtin::BI__sync_and_and_fetch_1: 4932 case Builtin::BI__sync_and_and_fetch_2: 4933 case Builtin::BI__sync_and_and_fetch_4: 4934 case Builtin::BI__sync_and_and_fetch_8: 4935 case Builtin::BI__sync_and_and_fetch_16: 4936 BuiltinIndex = 8; 4937 break; 4938 4939 case Builtin::BI__sync_or_and_fetch: 4940 case Builtin::BI__sync_or_and_fetch_1: 4941 case Builtin::BI__sync_or_and_fetch_2: 4942 case Builtin::BI__sync_or_and_fetch_4: 4943 case Builtin::BI__sync_or_and_fetch_8: 4944 case Builtin::BI__sync_or_and_fetch_16: 4945 BuiltinIndex = 9; 4946 break; 4947 4948 case Builtin::BI__sync_xor_and_fetch: 4949 case Builtin::BI__sync_xor_and_fetch_1: 4950 case Builtin::BI__sync_xor_and_fetch_2: 4951 case Builtin::BI__sync_xor_and_fetch_4: 4952 case Builtin::BI__sync_xor_and_fetch_8: 4953 case Builtin::BI__sync_xor_and_fetch_16: 4954 BuiltinIndex = 10; 4955 break; 4956 4957 case Builtin::BI__sync_nand_and_fetch: 4958 case Builtin::BI__sync_nand_and_fetch_1: 4959 case Builtin::BI__sync_nand_and_fetch_2: 4960 case Builtin::BI__sync_nand_and_fetch_4: 4961 case Builtin::BI__sync_nand_and_fetch_8: 4962 case Builtin::BI__sync_nand_and_fetch_16: 4963 BuiltinIndex = 11; 4964 WarnAboutSemanticsChange = true; 4965 break; 4966 4967 case Builtin::BI__sync_val_compare_and_swap: 4968 case Builtin::BI__sync_val_compare_and_swap_1: 4969 case Builtin::BI__sync_val_compare_and_swap_2: 4970 case Builtin::BI__sync_val_compare_and_swap_4: 4971 case Builtin::BI__sync_val_compare_and_swap_8: 4972 case Builtin::BI__sync_val_compare_and_swap_16: 4973 BuiltinIndex = 12; 4974 NumFixed = 2; 4975 break; 4976 4977 case Builtin::BI__sync_bool_compare_and_swap: 4978 case Builtin::BI__sync_bool_compare_and_swap_1: 4979 case Builtin::BI__sync_bool_compare_and_swap_2: 4980 case Builtin::BI__sync_bool_compare_and_swap_4: 4981 case Builtin::BI__sync_bool_compare_and_swap_8: 4982 case Builtin::BI__sync_bool_compare_and_swap_16: 4983 BuiltinIndex = 13; 4984 NumFixed = 2; 4985 ResultType = Context.BoolTy; 4986 break; 4987 4988 case Builtin::BI__sync_lock_test_and_set: 4989 case Builtin::BI__sync_lock_test_and_set_1: 4990 case Builtin::BI__sync_lock_test_and_set_2: 4991 case Builtin::BI__sync_lock_test_and_set_4: 4992 case Builtin::BI__sync_lock_test_and_set_8: 4993 case Builtin::BI__sync_lock_test_and_set_16: 4994 BuiltinIndex = 14; 4995 break; 4996 4997 case Builtin::BI__sync_lock_release: 4998 case Builtin::BI__sync_lock_release_1: 4999 case Builtin::BI__sync_lock_release_2: 5000 case Builtin::BI__sync_lock_release_4: 5001 case Builtin::BI__sync_lock_release_8: 5002 case Builtin::BI__sync_lock_release_16: 5003 BuiltinIndex = 15; 5004 NumFixed = 0; 5005 ResultType = Context.VoidTy; 5006 break; 5007 5008 case Builtin::BI__sync_swap: 5009 case Builtin::BI__sync_swap_1: 5010 case Builtin::BI__sync_swap_2: 5011 case Builtin::BI__sync_swap_4: 5012 case Builtin::BI__sync_swap_8: 5013 case Builtin::BI__sync_swap_16: 5014 BuiltinIndex = 16; 5015 break; 5016 } 5017 5018 // Now that we know how many fixed arguments we expect, first check that we 5019 // have at least that many. 5020 if (TheCall->getNumArgs() < 1+NumFixed) { 5021 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5022 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5023 << Callee->getSourceRange(); 5024 return ExprError(); 5025 } 5026 5027 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5028 << Callee->getSourceRange(); 5029 5030 if (WarnAboutSemanticsChange) { 5031 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5032 << Callee->getSourceRange(); 5033 } 5034 5035 // Get the decl for the concrete builtin from this, we can tell what the 5036 // concrete integer type we should convert to is. 5037 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5038 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5039 FunctionDecl *NewBuiltinDecl; 5040 if (NewBuiltinID == BuiltinID) 5041 NewBuiltinDecl = FDecl; 5042 else { 5043 // Perform builtin lookup to avoid redeclaring it. 5044 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5045 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5046 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5047 assert(Res.getFoundDecl()); 5048 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5049 if (!NewBuiltinDecl) 5050 return ExprError(); 5051 } 5052 5053 // The first argument --- the pointer --- has a fixed type; we 5054 // deduce the types of the rest of the arguments accordingly. Walk 5055 // the remaining arguments, converting them to the deduced value type. 5056 for (unsigned i = 0; i != NumFixed; ++i) { 5057 ExprResult Arg = TheCall->getArg(i+1); 5058 5059 // GCC does an implicit conversion to the pointer or integer ValType. This 5060 // can fail in some cases (1i -> int**), check for this error case now. 5061 // Initialize the argument. 5062 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5063 ValType, /*consume*/ false); 5064 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5065 if (Arg.isInvalid()) 5066 return ExprError(); 5067 5068 // Okay, we have something that *can* be converted to the right type. Check 5069 // to see if there is a potentially weird extension going on here. This can 5070 // happen when you do an atomic operation on something like an char* and 5071 // pass in 42. The 42 gets converted to char. This is even more strange 5072 // for things like 45.123 -> char, etc. 5073 // FIXME: Do this check. 5074 TheCall->setArg(i+1, Arg.get()); 5075 } 5076 5077 ASTContext& Context = this->getASTContext(); 5078 5079 // Create a new DeclRefExpr to refer to the new decl. 5080 DeclRefExpr* NewDRE = DeclRefExpr::Create( 5081 Context, 5082 DRE->getQualifierLoc(), 5083 SourceLocation(), 5084 NewBuiltinDecl, 5085 /*enclosing*/ false, 5086 DRE->getLocation(), 5087 Context.BuiltinFnTy, 5088 DRE->getValueKind()); 5089 5090 // Set the callee in the CallExpr. 5091 // FIXME: This loses syntactic information. 5092 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5093 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5094 CK_BuiltinFnToFnPtr); 5095 TheCall->setCallee(PromotedCall.get()); 5096 5097 // Change the result type of the call to match the original value type. This 5098 // is arbitrary, but the codegen for these builtins ins design to handle it 5099 // gracefully. 5100 TheCall->setType(ResultType); 5101 5102 return TheCallResult; 5103 } 5104 5105 /// SemaBuiltinNontemporalOverloaded - We have a call to 5106 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5107 /// overloaded function based on the pointer type of its last argument. 5108 /// 5109 /// This function goes through and does final semantic checking for these 5110 /// builtins. 5111 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5112 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5113 DeclRefExpr *DRE = 5114 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5115 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5116 unsigned BuiltinID = FDecl->getBuiltinID(); 5117 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5118 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5119 "Unexpected nontemporal load/store builtin!"); 5120 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5121 unsigned numArgs = isStore ? 2 : 1; 5122 5123 // Ensure that we have the proper number of arguments. 5124 if (checkArgCount(*this, TheCall, numArgs)) 5125 return ExprError(); 5126 5127 // Inspect the last argument of the nontemporal builtin. This should always 5128 // be a pointer type, from which we imply the type of the memory access. 5129 // Because it is a pointer type, we don't have to worry about any implicit 5130 // casts here. 5131 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5132 ExprResult PointerArgResult = 5133 DefaultFunctionArrayLvalueConversion(PointerArg); 5134 5135 if (PointerArgResult.isInvalid()) 5136 return ExprError(); 5137 PointerArg = PointerArgResult.get(); 5138 TheCall->setArg(numArgs - 1, PointerArg); 5139 5140 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5141 if (!pointerType) { 5142 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5143 << PointerArg->getType() << PointerArg->getSourceRange(); 5144 return ExprError(); 5145 } 5146 5147 QualType ValType = pointerType->getPointeeType(); 5148 5149 // Strip any qualifiers off ValType. 5150 ValType = ValType.getUnqualifiedType(); 5151 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5152 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5153 !ValType->isVectorType()) { 5154 Diag(DRE->getBeginLoc(), 5155 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5156 << PointerArg->getType() << PointerArg->getSourceRange(); 5157 return ExprError(); 5158 } 5159 5160 if (!isStore) { 5161 TheCall->setType(ValType); 5162 return TheCallResult; 5163 } 5164 5165 ExprResult ValArg = TheCall->getArg(0); 5166 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5167 Context, ValType, /*consume*/ false); 5168 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5169 if (ValArg.isInvalid()) 5170 return ExprError(); 5171 5172 TheCall->setArg(0, ValArg.get()); 5173 TheCall->setType(Context.VoidTy); 5174 return TheCallResult; 5175 } 5176 5177 /// CheckObjCString - Checks that the argument to the builtin 5178 /// CFString constructor is correct 5179 /// Note: It might also make sense to do the UTF-16 conversion here (would 5180 /// simplify the backend). 5181 bool Sema::CheckObjCString(Expr *Arg) { 5182 Arg = Arg->IgnoreParenCasts(); 5183 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5184 5185 if (!Literal || !Literal->isAscii()) { 5186 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5187 << Arg->getSourceRange(); 5188 return true; 5189 } 5190 5191 if (Literal->containsNonAsciiOrNull()) { 5192 StringRef String = Literal->getString(); 5193 unsigned NumBytes = String.size(); 5194 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5195 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5196 llvm::UTF16 *ToPtr = &ToBuf[0]; 5197 5198 llvm::ConversionResult Result = 5199 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5200 ToPtr + NumBytes, llvm::strictConversion); 5201 // Check for conversion failure. 5202 if (Result != llvm::conversionOK) 5203 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5204 << Arg->getSourceRange(); 5205 } 5206 return false; 5207 } 5208 5209 /// CheckObjCString - Checks that the format string argument to the os_log() 5210 /// and os_trace() functions is correct, and converts it to const char *. 5211 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5212 Arg = Arg->IgnoreParenCasts(); 5213 auto *Literal = dyn_cast<StringLiteral>(Arg); 5214 if (!Literal) { 5215 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5216 Literal = ObjcLiteral->getString(); 5217 } 5218 } 5219 5220 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5221 return ExprError( 5222 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5223 << Arg->getSourceRange()); 5224 } 5225 5226 ExprResult Result(Literal); 5227 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5228 InitializedEntity Entity = 5229 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5230 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5231 return Result; 5232 } 5233 5234 /// Check that the user is calling the appropriate va_start builtin for the 5235 /// target and calling convention. 5236 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5237 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5238 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5239 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5240 bool IsWindows = TT.isOSWindows(); 5241 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5242 if (IsX64 || IsAArch64) { 5243 CallingConv CC = CC_C; 5244 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5245 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5246 if (IsMSVAStart) { 5247 // Don't allow this in System V ABI functions. 5248 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5249 return S.Diag(Fn->getBeginLoc(), 5250 diag::err_ms_va_start_used_in_sysv_function); 5251 } else { 5252 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5253 // On x64 Windows, don't allow this in System V ABI functions. 5254 // (Yes, that means there's no corresponding way to support variadic 5255 // System V ABI functions on Windows.) 5256 if ((IsWindows && CC == CC_X86_64SysV) || 5257 (!IsWindows && CC == CC_Win64)) 5258 return S.Diag(Fn->getBeginLoc(), 5259 diag::err_va_start_used_in_wrong_abi_function) 5260 << !IsWindows; 5261 } 5262 return false; 5263 } 5264 5265 if (IsMSVAStart) 5266 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5267 return false; 5268 } 5269 5270 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5271 ParmVarDecl **LastParam = nullptr) { 5272 // Determine whether the current function, block, or obj-c method is variadic 5273 // and get its parameter list. 5274 bool IsVariadic = false; 5275 ArrayRef<ParmVarDecl *> Params; 5276 DeclContext *Caller = S.CurContext; 5277 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5278 IsVariadic = Block->isVariadic(); 5279 Params = Block->parameters(); 5280 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5281 IsVariadic = FD->isVariadic(); 5282 Params = FD->parameters(); 5283 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5284 IsVariadic = MD->isVariadic(); 5285 // FIXME: This isn't correct for methods (results in bogus warning). 5286 Params = MD->parameters(); 5287 } else if (isa<CapturedDecl>(Caller)) { 5288 // We don't support va_start in a CapturedDecl. 5289 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5290 return true; 5291 } else { 5292 // This must be some other declcontext that parses exprs. 5293 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5294 return true; 5295 } 5296 5297 if (!IsVariadic) { 5298 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5299 return true; 5300 } 5301 5302 if (LastParam) 5303 *LastParam = Params.empty() ? nullptr : Params.back(); 5304 5305 return false; 5306 } 5307 5308 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5309 /// for validity. Emit an error and return true on failure; return false 5310 /// on success. 5311 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5312 Expr *Fn = TheCall->getCallee(); 5313 5314 if (checkVAStartABI(*this, BuiltinID, Fn)) 5315 return true; 5316 5317 if (TheCall->getNumArgs() > 2) { 5318 Diag(TheCall->getArg(2)->getBeginLoc(), 5319 diag::err_typecheck_call_too_many_args) 5320 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5321 << Fn->getSourceRange() 5322 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5323 (*(TheCall->arg_end() - 1))->getEndLoc()); 5324 return true; 5325 } 5326 5327 if (TheCall->getNumArgs() < 2) { 5328 return Diag(TheCall->getEndLoc(), 5329 diag::err_typecheck_call_too_few_args_at_least) 5330 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5331 } 5332 5333 // Type-check the first argument normally. 5334 if (checkBuiltinArgument(*this, TheCall, 0)) 5335 return true; 5336 5337 // Check that the current function is variadic, and get its last parameter. 5338 ParmVarDecl *LastParam; 5339 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5340 return true; 5341 5342 // Verify that the second argument to the builtin is the last argument of the 5343 // current function or method. 5344 bool SecondArgIsLastNamedArgument = false; 5345 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5346 5347 // These are valid if SecondArgIsLastNamedArgument is false after the next 5348 // block. 5349 QualType Type; 5350 SourceLocation ParamLoc; 5351 bool IsCRegister = false; 5352 5353 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5354 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5355 SecondArgIsLastNamedArgument = PV == LastParam; 5356 5357 Type = PV->getType(); 5358 ParamLoc = PV->getLocation(); 5359 IsCRegister = 5360 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5361 } 5362 } 5363 5364 if (!SecondArgIsLastNamedArgument) 5365 Diag(TheCall->getArg(1)->getBeginLoc(), 5366 diag::warn_second_arg_of_va_start_not_last_named_param); 5367 else if (IsCRegister || Type->isReferenceType() || 5368 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5369 // Promotable integers are UB, but enumerations need a bit of 5370 // extra checking to see what their promotable type actually is. 5371 if (!Type->isPromotableIntegerType()) 5372 return false; 5373 if (!Type->isEnumeralType()) 5374 return true; 5375 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5376 return !(ED && 5377 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5378 }()) { 5379 unsigned Reason = 0; 5380 if (Type->isReferenceType()) Reason = 1; 5381 else if (IsCRegister) Reason = 2; 5382 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5383 Diag(ParamLoc, diag::note_parameter_type) << Type; 5384 } 5385 5386 TheCall->setType(Context.VoidTy); 5387 return false; 5388 } 5389 5390 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5391 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5392 // const char *named_addr); 5393 5394 Expr *Func = Call->getCallee(); 5395 5396 if (Call->getNumArgs() < 3) 5397 return Diag(Call->getEndLoc(), 5398 diag::err_typecheck_call_too_few_args_at_least) 5399 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5400 5401 // Type-check the first argument normally. 5402 if (checkBuiltinArgument(*this, Call, 0)) 5403 return true; 5404 5405 // Check that the current function is variadic. 5406 if (checkVAStartIsInVariadicFunction(*this, Func)) 5407 return true; 5408 5409 // __va_start on Windows does not validate the parameter qualifiers 5410 5411 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5412 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5413 5414 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5415 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5416 5417 const QualType &ConstCharPtrTy = 5418 Context.getPointerType(Context.CharTy.withConst()); 5419 if (!Arg1Ty->isPointerType() || 5420 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5421 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5422 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5423 << 0 /* qualifier difference */ 5424 << 3 /* parameter mismatch */ 5425 << 2 << Arg1->getType() << ConstCharPtrTy; 5426 5427 const QualType SizeTy = Context.getSizeType(); 5428 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5429 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5430 << Arg2->getType() << SizeTy << 1 /* different class */ 5431 << 0 /* qualifier difference */ 5432 << 3 /* parameter mismatch */ 5433 << 3 << Arg2->getType() << SizeTy; 5434 5435 return false; 5436 } 5437 5438 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5439 /// friends. This is declared to take (...), so we have to check everything. 5440 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5441 if (TheCall->getNumArgs() < 2) 5442 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5443 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5444 if (TheCall->getNumArgs() > 2) 5445 return Diag(TheCall->getArg(2)->getBeginLoc(), 5446 diag::err_typecheck_call_too_many_args) 5447 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5448 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5449 (*(TheCall->arg_end() - 1))->getEndLoc()); 5450 5451 ExprResult OrigArg0 = TheCall->getArg(0); 5452 ExprResult OrigArg1 = TheCall->getArg(1); 5453 5454 // Do standard promotions between the two arguments, returning their common 5455 // type. 5456 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5457 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5458 return true; 5459 5460 // Make sure any conversions are pushed back into the call; this is 5461 // type safe since unordered compare builtins are declared as "_Bool 5462 // foo(...)". 5463 TheCall->setArg(0, OrigArg0.get()); 5464 TheCall->setArg(1, OrigArg1.get()); 5465 5466 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5467 return false; 5468 5469 // If the common type isn't a real floating type, then the arguments were 5470 // invalid for this operation. 5471 if (Res.isNull() || !Res->isRealFloatingType()) 5472 return Diag(OrigArg0.get()->getBeginLoc(), 5473 diag::err_typecheck_call_invalid_ordered_compare) 5474 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5475 << SourceRange(OrigArg0.get()->getBeginLoc(), 5476 OrigArg1.get()->getEndLoc()); 5477 5478 return false; 5479 } 5480 5481 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5482 /// __builtin_isnan and friends. This is declared to take (...), so we have 5483 /// to check everything. We expect the last argument to be a floating point 5484 /// value. 5485 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5486 if (TheCall->getNumArgs() < NumArgs) 5487 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5488 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5489 if (TheCall->getNumArgs() > NumArgs) 5490 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5491 diag::err_typecheck_call_too_many_args) 5492 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5493 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5494 (*(TheCall->arg_end() - 1))->getEndLoc()); 5495 5496 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5497 5498 if (OrigArg->isTypeDependent()) 5499 return false; 5500 5501 // This operation requires a non-_Complex floating-point number. 5502 if (!OrigArg->getType()->isRealFloatingType()) 5503 return Diag(OrigArg->getBeginLoc(), 5504 diag::err_typecheck_call_invalid_unary_fp) 5505 << OrigArg->getType() << OrigArg->getSourceRange(); 5506 5507 // If this is an implicit conversion from float -> float, double, or 5508 // long double, remove it. 5509 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5510 // Only remove standard FloatCasts, leaving other casts inplace 5511 if (Cast->getCastKind() == CK_FloatingCast) { 5512 Expr *CastArg = Cast->getSubExpr(); 5513 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5514 assert( 5515 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5516 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5517 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5518 "promotion from float to either float, double, or long double is " 5519 "the only expected cast here"); 5520 Cast->setSubExpr(nullptr); 5521 TheCall->setArg(NumArgs-1, CastArg); 5522 } 5523 } 5524 } 5525 5526 return false; 5527 } 5528 5529 // Customized Sema Checking for VSX builtins that have the following signature: 5530 // vector [...] builtinName(vector [...], vector [...], const int); 5531 // Which takes the same type of vectors (any legal vector type) for the first 5532 // two arguments and takes compile time constant for the third argument. 5533 // Example builtins are : 5534 // vector double vec_xxpermdi(vector double, vector double, int); 5535 // vector short vec_xxsldwi(vector short, vector short, int); 5536 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5537 unsigned ExpectedNumArgs = 3; 5538 if (TheCall->getNumArgs() < ExpectedNumArgs) 5539 return Diag(TheCall->getEndLoc(), 5540 diag::err_typecheck_call_too_few_args_at_least) 5541 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5542 << TheCall->getSourceRange(); 5543 5544 if (TheCall->getNumArgs() > ExpectedNumArgs) 5545 return Diag(TheCall->getEndLoc(), 5546 diag::err_typecheck_call_too_many_args_at_most) 5547 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5548 << TheCall->getSourceRange(); 5549 5550 // Check the third argument is a compile time constant 5551 llvm::APSInt Value; 5552 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5553 return Diag(TheCall->getBeginLoc(), 5554 diag::err_vsx_builtin_nonconstant_argument) 5555 << 3 /* argument index */ << TheCall->getDirectCallee() 5556 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5557 TheCall->getArg(2)->getEndLoc()); 5558 5559 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5560 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5561 5562 // Check the type of argument 1 and argument 2 are vectors. 5563 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5564 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5565 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5566 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5567 << TheCall->getDirectCallee() 5568 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5569 TheCall->getArg(1)->getEndLoc()); 5570 } 5571 5572 // Check the first two arguments are the same type. 5573 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5574 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5575 << TheCall->getDirectCallee() 5576 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5577 TheCall->getArg(1)->getEndLoc()); 5578 } 5579 5580 // When default clang type checking is turned off and the customized type 5581 // checking is used, the returning type of the function must be explicitly 5582 // set. Otherwise it is _Bool by default. 5583 TheCall->setType(Arg1Ty); 5584 5585 return false; 5586 } 5587 5588 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5589 // This is declared to take (...), so we have to check everything. 5590 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5591 if (TheCall->getNumArgs() < 2) 5592 return ExprError(Diag(TheCall->getEndLoc(), 5593 diag::err_typecheck_call_too_few_args_at_least) 5594 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5595 << TheCall->getSourceRange()); 5596 5597 // Determine which of the following types of shufflevector we're checking: 5598 // 1) unary, vector mask: (lhs, mask) 5599 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5600 QualType resType = TheCall->getArg(0)->getType(); 5601 unsigned numElements = 0; 5602 5603 if (!TheCall->getArg(0)->isTypeDependent() && 5604 !TheCall->getArg(1)->isTypeDependent()) { 5605 QualType LHSType = TheCall->getArg(0)->getType(); 5606 QualType RHSType = TheCall->getArg(1)->getType(); 5607 5608 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5609 return ExprError( 5610 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5611 << TheCall->getDirectCallee() 5612 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5613 TheCall->getArg(1)->getEndLoc())); 5614 5615 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5616 unsigned numResElements = TheCall->getNumArgs() - 2; 5617 5618 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5619 // with mask. If so, verify that RHS is an integer vector type with the 5620 // same number of elts as lhs. 5621 if (TheCall->getNumArgs() == 2) { 5622 if (!RHSType->hasIntegerRepresentation() || 5623 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5624 return ExprError(Diag(TheCall->getBeginLoc(), 5625 diag::err_vec_builtin_incompatible_vector) 5626 << TheCall->getDirectCallee() 5627 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5628 TheCall->getArg(1)->getEndLoc())); 5629 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5630 return ExprError(Diag(TheCall->getBeginLoc(), 5631 diag::err_vec_builtin_incompatible_vector) 5632 << TheCall->getDirectCallee() 5633 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5634 TheCall->getArg(1)->getEndLoc())); 5635 } else if (numElements != numResElements) { 5636 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5637 resType = Context.getVectorType(eltType, numResElements, 5638 VectorType::GenericVector); 5639 } 5640 } 5641 5642 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5643 if (TheCall->getArg(i)->isTypeDependent() || 5644 TheCall->getArg(i)->isValueDependent()) 5645 continue; 5646 5647 llvm::APSInt Result(32); 5648 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5649 return ExprError(Diag(TheCall->getBeginLoc(), 5650 diag::err_shufflevector_nonconstant_argument) 5651 << TheCall->getArg(i)->getSourceRange()); 5652 5653 // Allow -1 which will be translated to undef in the IR. 5654 if (Result.isSigned() && Result.isAllOnesValue()) 5655 continue; 5656 5657 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5658 return ExprError(Diag(TheCall->getBeginLoc(), 5659 diag::err_shufflevector_argument_too_large) 5660 << TheCall->getArg(i)->getSourceRange()); 5661 } 5662 5663 SmallVector<Expr*, 32> exprs; 5664 5665 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5666 exprs.push_back(TheCall->getArg(i)); 5667 TheCall->setArg(i, nullptr); 5668 } 5669 5670 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5671 TheCall->getCallee()->getBeginLoc(), 5672 TheCall->getRParenLoc()); 5673 } 5674 5675 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5676 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5677 SourceLocation BuiltinLoc, 5678 SourceLocation RParenLoc) { 5679 ExprValueKind VK = VK_RValue; 5680 ExprObjectKind OK = OK_Ordinary; 5681 QualType DstTy = TInfo->getType(); 5682 QualType SrcTy = E->getType(); 5683 5684 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5685 return ExprError(Diag(BuiltinLoc, 5686 diag::err_convertvector_non_vector) 5687 << E->getSourceRange()); 5688 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5689 return ExprError(Diag(BuiltinLoc, 5690 diag::err_convertvector_non_vector_type)); 5691 5692 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5693 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5694 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5695 if (SrcElts != DstElts) 5696 return ExprError(Diag(BuiltinLoc, 5697 diag::err_convertvector_incompatible_vector) 5698 << E->getSourceRange()); 5699 } 5700 5701 return new (Context) 5702 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5703 } 5704 5705 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5706 // This is declared to take (const void*, ...) and can take two 5707 // optional constant int args. 5708 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5709 unsigned NumArgs = TheCall->getNumArgs(); 5710 5711 if (NumArgs > 3) 5712 return Diag(TheCall->getEndLoc(), 5713 diag::err_typecheck_call_too_many_args_at_most) 5714 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5715 5716 // Argument 0 is checked for us and the remaining arguments must be 5717 // constant integers. 5718 for (unsigned i = 1; i != NumArgs; ++i) 5719 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5720 return true; 5721 5722 return false; 5723 } 5724 5725 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5726 // __assume does not evaluate its arguments, and should warn if its argument 5727 // has side effects. 5728 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5729 Expr *Arg = TheCall->getArg(0); 5730 if (Arg->isInstantiationDependent()) return false; 5731 5732 if (Arg->HasSideEffects(Context)) 5733 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5734 << Arg->getSourceRange() 5735 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5736 5737 return false; 5738 } 5739 5740 /// Handle __builtin_alloca_with_align. This is declared 5741 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5742 /// than 8. 5743 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5744 // The alignment must be a constant integer. 5745 Expr *Arg = TheCall->getArg(1); 5746 5747 // We can't check the value of a dependent argument. 5748 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5749 if (const auto *UE = 5750 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5751 if (UE->getKind() == UETT_AlignOf || 5752 UE->getKind() == UETT_PreferredAlignOf) 5753 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5754 << Arg->getSourceRange(); 5755 5756 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5757 5758 if (!Result.isPowerOf2()) 5759 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5760 << Arg->getSourceRange(); 5761 5762 if (Result < Context.getCharWidth()) 5763 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5764 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5765 5766 if (Result > std::numeric_limits<int32_t>::max()) 5767 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5768 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5769 } 5770 5771 return false; 5772 } 5773 5774 /// Handle __builtin_assume_aligned. This is declared 5775 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5776 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5777 unsigned NumArgs = TheCall->getNumArgs(); 5778 5779 if (NumArgs > 3) 5780 return Diag(TheCall->getEndLoc(), 5781 diag::err_typecheck_call_too_many_args_at_most) 5782 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5783 5784 // The alignment must be a constant integer. 5785 Expr *Arg = TheCall->getArg(1); 5786 5787 // We can't check the value of a dependent argument. 5788 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5789 llvm::APSInt Result; 5790 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5791 return true; 5792 5793 if (!Result.isPowerOf2()) 5794 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5795 << Arg->getSourceRange(); 5796 } 5797 5798 if (NumArgs > 2) { 5799 ExprResult Arg(TheCall->getArg(2)); 5800 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5801 Context.getSizeType(), false); 5802 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5803 if (Arg.isInvalid()) return true; 5804 TheCall->setArg(2, Arg.get()); 5805 } 5806 5807 return false; 5808 } 5809 5810 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5811 unsigned BuiltinID = 5812 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5813 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5814 5815 unsigned NumArgs = TheCall->getNumArgs(); 5816 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5817 if (NumArgs < NumRequiredArgs) { 5818 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5819 << 0 /* function call */ << NumRequiredArgs << NumArgs 5820 << TheCall->getSourceRange(); 5821 } 5822 if (NumArgs >= NumRequiredArgs + 0x100) { 5823 return Diag(TheCall->getEndLoc(), 5824 diag::err_typecheck_call_too_many_args_at_most) 5825 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5826 << TheCall->getSourceRange(); 5827 } 5828 unsigned i = 0; 5829 5830 // For formatting call, check buffer arg. 5831 if (!IsSizeCall) { 5832 ExprResult Arg(TheCall->getArg(i)); 5833 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5834 Context, Context.VoidPtrTy, false); 5835 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5836 if (Arg.isInvalid()) 5837 return true; 5838 TheCall->setArg(i, Arg.get()); 5839 i++; 5840 } 5841 5842 // Check string literal arg. 5843 unsigned FormatIdx = i; 5844 { 5845 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5846 if (Arg.isInvalid()) 5847 return true; 5848 TheCall->setArg(i, Arg.get()); 5849 i++; 5850 } 5851 5852 // Make sure variadic args are scalar. 5853 unsigned FirstDataArg = i; 5854 while (i < NumArgs) { 5855 ExprResult Arg = DefaultVariadicArgumentPromotion( 5856 TheCall->getArg(i), VariadicFunction, nullptr); 5857 if (Arg.isInvalid()) 5858 return true; 5859 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5860 if (ArgSize.getQuantity() >= 0x100) { 5861 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5862 << i << (int)ArgSize.getQuantity() << 0xff 5863 << TheCall->getSourceRange(); 5864 } 5865 TheCall->setArg(i, Arg.get()); 5866 i++; 5867 } 5868 5869 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5870 // call to avoid duplicate diagnostics. 5871 if (!IsSizeCall) { 5872 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5873 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5874 bool Success = CheckFormatArguments( 5875 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5876 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5877 CheckedVarArgs); 5878 if (!Success) 5879 return true; 5880 } 5881 5882 if (IsSizeCall) { 5883 TheCall->setType(Context.getSizeType()); 5884 } else { 5885 TheCall->setType(Context.VoidPtrTy); 5886 } 5887 return false; 5888 } 5889 5890 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5891 /// TheCall is a constant expression. 5892 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5893 llvm::APSInt &Result) { 5894 Expr *Arg = TheCall->getArg(ArgNum); 5895 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5896 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5897 5898 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5899 5900 if (!Arg->isIntegerConstantExpr(Result, Context)) 5901 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5902 << FDecl->getDeclName() << Arg->getSourceRange(); 5903 5904 return false; 5905 } 5906 5907 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5908 /// TheCall is a constant expression in the range [Low, High]. 5909 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5910 int Low, int High, bool RangeIsError) { 5911 llvm::APSInt Result; 5912 5913 // We can't check the value of a dependent argument. 5914 Expr *Arg = TheCall->getArg(ArgNum); 5915 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5916 return false; 5917 5918 // Check constant-ness first. 5919 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5920 return true; 5921 5922 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5923 if (RangeIsError) 5924 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5925 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5926 else 5927 // Defer the warning until we know if the code will be emitted so that 5928 // dead code can ignore this. 5929 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5930 PDiag(diag::warn_argument_invalid_range) 5931 << Result.toString(10) << Low << High 5932 << Arg->getSourceRange()); 5933 } 5934 5935 return false; 5936 } 5937 5938 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5939 /// TheCall is a constant expression is a multiple of Num.. 5940 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5941 unsigned Num) { 5942 llvm::APSInt Result; 5943 5944 // We can't check the value of a dependent argument. 5945 Expr *Arg = TheCall->getArg(ArgNum); 5946 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5947 return false; 5948 5949 // Check constant-ness first. 5950 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5951 return true; 5952 5953 if (Result.getSExtValue() % Num != 0) 5954 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5955 << Num << Arg->getSourceRange(); 5956 5957 return false; 5958 } 5959 5960 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 5961 /// TheCall is an ARM/AArch64 special register string literal. 5962 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 5963 int ArgNum, unsigned ExpectedFieldNum, 5964 bool AllowName) { 5965 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 5966 BuiltinID == ARM::BI__builtin_arm_wsr64 || 5967 BuiltinID == ARM::BI__builtin_arm_rsr || 5968 BuiltinID == ARM::BI__builtin_arm_rsrp || 5969 BuiltinID == ARM::BI__builtin_arm_wsr || 5970 BuiltinID == ARM::BI__builtin_arm_wsrp; 5971 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 5972 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 5973 BuiltinID == AArch64::BI__builtin_arm_rsr || 5974 BuiltinID == AArch64::BI__builtin_arm_rsrp || 5975 BuiltinID == AArch64::BI__builtin_arm_wsr || 5976 BuiltinID == AArch64::BI__builtin_arm_wsrp; 5977 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 5978 5979 // We can't check the value of a dependent argument. 5980 Expr *Arg = TheCall->getArg(ArgNum); 5981 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5982 return false; 5983 5984 // Check if the argument is a string literal. 5985 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 5986 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 5987 << Arg->getSourceRange(); 5988 5989 // Check the type of special register given. 5990 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 5991 SmallVector<StringRef, 6> Fields; 5992 Reg.split(Fields, ":"); 5993 5994 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 5995 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 5996 << Arg->getSourceRange(); 5997 5998 // If the string is the name of a register then we cannot check that it is 5999 // valid here but if the string is of one the forms described in ACLE then we 6000 // can check that the supplied fields are integers and within the valid 6001 // ranges. 6002 if (Fields.size() > 1) { 6003 bool FiveFields = Fields.size() == 5; 6004 6005 bool ValidString = true; 6006 if (IsARMBuiltin) { 6007 ValidString &= Fields[0].startswith_lower("cp") || 6008 Fields[0].startswith_lower("p"); 6009 if (ValidString) 6010 Fields[0] = 6011 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6012 6013 ValidString &= Fields[2].startswith_lower("c"); 6014 if (ValidString) 6015 Fields[2] = Fields[2].drop_front(1); 6016 6017 if (FiveFields) { 6018 ValidString &= Fields[3].startswith_lower("c"); 6019 if (ValidString) 6020 Fields[3] = Fields[3].drop_front(1); 6021 } 6022 } 6023 6024 SmallVector<int, 5> Ranges; 6025 if (FiveFields) 6026 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6027 else 6028 Ranges.append({15, 7, 15}); 6029 6030 for (unsigned i=0; i<Fields.size(); ++i) { 6031 int IntField; 6032 ValidString &= !Fields[i].getAsInteger(10, IntField); 6033 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6034 } 6035 6036 if (!ValidString) 6037 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6038 << Arg->getSourceRange(); 6039 } else if (IsAArch64Builtin && Fields.size() == 1) { 6040 // If the register name is one of those that appear in the condition below 6041 // and the special register builtin being used is one of the write builtins, 6042 // then we require that the argument provided for writing to the register 6043 // is an integer constant expression. This is because it will be lowered to 6044 // an MSR (immediate) instruction, so we need to know the immediate at 6045 // compile time. 6046 if (TheCall->getNumArgs() != 2) 6047 return false; 6048 6049 std::string RegLower = Reg.lower(); 6050 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6051 RegLower != "pan" && RegLower != "uao") 6052 return false; 6053 6054 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6055 } 6056 6057 return false; 6058 } 6059 6060 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6061 /// This checks that the target supports __builtin_longjmp and 6062 /// that val is a constant 1. 6063 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6064 if (!Context.getTargetInfo().hasSjLjLowering()) 6065 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6066 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6067 6068 Expr *Arg = TheCall->getArg(1); 6069 llvm::APSInt Result; 6070 6071 // TODO: This is less than ideal. Overload this to take a value. 6072 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6073 return true; 6074 6075 if (Result != 1) 6076 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6077 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6078 6079 return false; 6080 } 6081 6082 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6083 /// This checks that the target supports __builtin_setjmp. 6084 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6085 if (!Context.getTargetInfo().hasSjLjLowering()) 6086 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6087 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6088 return false; 6089 } 6090 6091 namespace { 6092 6093 class UncoveredArgHandler { 6094 enum { Unknown = -1, AllCovered = -2 }; 6095 6096 signed FirstUncoveredArg = Unknown; 6097 SmallVector<const Expr *, 4> DiagnosticExprs; 6098 6099 public: 6100 UncoveredArgHandler() = default; 6101 6102 bool hasUncoveredArg() const { 6103 return (FirstUncoveredArg >= 0); 6104 } 6105 6106 unsigned getUncoveredArg() const { 6107 assert(hasUncoveredArg() && "no uncovered argument"); 6108 return FirstUncoveredArg; 6109 } 6110 6111 void setAllCovered() { 6112 // A string has been found with all arguments covered, so clear out 6113 // the diagnostics. 6114 DiagnosticExprs.clear(); 6115 FirstUncoveredArg = AllCovered; 6116 } 6117 6118 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6119 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6120 6121 // Don't update if a previous string covers all arguments. 6122 if (FirstUncoveredArg == AllCovered) 6123 return; 6124 6125 // UncoveredArgHandler tracks the highest uncovered argument index 6126 // and with it all the strings that match this index. 6127 if (NewFirstUncoveredArg == FirstUncoveredArg) 6128 DiagnosticExprs.push_back(StrExpr); 6129 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6130 DiagnosticExprs.clear(); 6131 DiagnosticExprs.push_back(StrExpr); 6132 FirstUncoveredArg = NewFirstUncoveredArg; 6133 } 6134 } 6135 6136 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6137 }; 6138 6139 enum StringLiteralCheckType { 6140 SLCT_NotALiteral, 6141 SLCT_UncheckedLiteral, 6142 SLCT_CheckedLiteral 6143 }; 6144 6145 } // namespace 6146 6147 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6148 BinaryOperatorKind BinOpKind, 6149 bool AddendIsRight) { 6150 unsigned BitWidth = Offset.getBitWidth(); 6151 unsigned AddendBitWidth = Addend.getBitWidth(); 6152 // There might be negative interim results. 6153 if (Addend.isUnsigned()) { 6154 Addend = Addend.zext(++AddendBitWidth); 6155 Addend.setIsSigned(true); 6156 } 6157 // Adjust the bit width of the APSInts. 6158 if (AddendBitWidth > BitWidth) { 6159 Offset = Offset.sext(AddendBitWidth); 6160 BitWidth = AddendBitWidth; 6161 } else if (BitWidth > AddendBitWidth) { 6162 Addend = Addend.sext(BitWidth); 6163 } 6164 6165 bool Ov = false; 6166 llvm::APSInt ResOffset = Offset; 6167 if (BinOpKind == BO_Add) 6168 ResOffset = Offset.sadd_ov(Addend, Ov); 6169 else { 6170 assert(AddendIsRight && BinOpKind == BO_Sub && 6171 "operator must be add or sub with addend on the right"); 6172 ResOffset = Offset.ssub_ov(Addend, Ov); 6173 } 6174 6175 // We add an offset to a pointer here so we should support an offset as big as 6176 // possible. 6177 if (Ov) { 6178 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6179 "index (intermediate) result too big"); 6180 Offset = Offset.sext(2 * BitWidth); 6181 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6182 return; 6183 } 6184 6185 Offset = ResOffset; 6186 } 6187 6188 namespace { 6189 6190 // This is a wrapper class around StringLiteral to support offsetted string 6191 // literals as format strings. It takes the offset into account when returning 6192 // the string and its length or the source locations to display notes correctly. 6193 class FormatStringLiteral { 6194 const StringLiteral *FExpr; 6195 int64_t Offset; 6196 6197 public: 6198 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6199 : FExpr(fexpr), Offset(Offset) {} 6200 6201 StringRef getString() const { 6202 return FExpr->getString().drop_front(Offset); 6203 } 6204 6205 unsigned getByteLength() const { 6206 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6207 } 6208 6209 unsigned getLength() const { return FExpr->getLength() - Offset; } 6210 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6211 6212 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6213 6214 QualType getType() const { return FExpr->getType(); } 6215 6216 bool isAscii() const { return FExpr->isAscii(); } 6217 bool isWide() const { return FExpr->isWide(); } 6218 bool isUTF8() const { return FExpr->isUTF8(); } 6219 bool isUTF16() const { return FExpr->isUTF16(); } 6220 bool isUTF32() const { return FExpr->isUTF32(); } 6221 bool isPascal() const { return FExpr->isPascal(); } 6222 6223 SourceLocation getLocationOfByte( 6224 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6225 const TargetInfo &Target, unsigned *StartToken = nullptr, 6226 unsigned *StartTokenByteOffset = nullptr) const { 6227 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6228 StartToken, StartTokenByteOffset); 6229 } 6230 6231 SourceLocation getBeginLoc() const LLVM_READONLY { 6232 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6233 } 6234 6235 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6236 }; 6237 6238 } // namespace 6239 6240 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6241 const Expr *OrigFormatExpr, 6242 ArrayRef<const Expr *> Args, 6243 bool HasVAListArg, unsigned format_idx, 6244 unsigned firstDataArg, 6245 Sema::FormatStringType Type, 6246 bool inFunctionCall, 6247 Sema::VariadicCallType CallType, 6248 llvm::SmallBitVector &CheckedVarArgs, 6249 UncoveredArgHandler &UncoveredArg); 6250 6251 // Determine if an expression is a string literal or constant string. 6252 // If this function returns false on the arguments to a function expecting a 6253 // format string, we will usually need to emit a warning. 6254 // True string literals are then checked by CheckFormatString. 6255 static StringLiteralCheckType 6256 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6257 bool HasVAListArg, unsigned format_idx, 6258 unsigned firstDataArg, Sema::FormatStringType Type, 6259 Sema::VariadicCallType CallType, bool InFunctionCall, 6260 llvm::SmallBitVector &CheckedVarArgs, 6261 UncoveredArgHandler &UncoveredArg, 6262 llvm::APSInt Offset) { 6263 tryAgain: 6264 assert(Offset.isSigned() && "invalid offset"); 6265 6266 if (E->isTypeDependent() || E->isValueDependent()) 6267 return SLCT_NotALiteral; 6268 6269 E = E->IgnoreParenCasts(); 6270 6271 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6272 // Technically -Wformat-nonliteral does not warn about this case. 6273 // The behavior of printf and friends in this case is implementation 6274 // dependent. Ideally if the format string cannot be null then 6275 // it should have a 'nonnull' attribute in the function prototype. 6276 return SLCT_UncheckedLiteral; 6277 6278 switch (E->getStmtClass()) { 6279 case Stmt::BinaryConditionalOperatorClass: 6280 case Stmt::ConditionalOperatorClass: { 6281 // The expression is a literal if both sub-expressions were, and it was 6282 // completely checked only if both sub-expressions were checked. 6283 const AbstractConditionalOperator *C = 6284 cast<AbstractConditionalOperator>(E); 6285 6286 // Determine whether it is necessary to check both sub-expressions, for 6287 // example, because the condition expression is a constant that can be 6288 // evaluated at compile time. 6289 bool CheckLeft = true, CheckRight = true; 6290 6291 bool Cond; 6292 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 6293 if (Cond) 6294 CheckRight = false; 6295 else 6296 CheckLeft = false; 6297 } 6298 6299 // We need to maintain the offsets for the right and the left hand side 6300 // separately to check if every possible indexed expression is a valid 6301 // string literal. They might have different offsets for different string 6302 // literals in the end. 6303 StringLiteralCheckType Left; 6304 if (!CheckLeft) 6305 Left = SLCT_UncheckedLiteral; 6306 else { 6307 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6308 HasVAListArg, format_idx, firstDataArg, 6309 Type, CallType, InFunctionCall, 6310 CheckedVarArgs, UncoveredArg, Offset); 6311 if (Left == SLCT_NotALiteral || !CheckRight) { 6312 return Left; 6313 } 6314 } 6315 6316 StringLiteralCheckType Right = 6317 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6318 HasVAListArg, format_idx, firstDataArg, 6319 Type, CallType, InFunctionCall, CheckedVarArgs, 6320 UncoveredArg, Offset); 6321 6322 return (CheckLeft && Left < Right) ? Left : Right; 6323 } 6324 6325 case Stmt::ImplicitCastExprClass: 6326 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6327 goto tryAgain; 6328 6329 case Stmt::OpaqueValueExprClass: 6330 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6331 E = src; 6332 goto tryAgain; 6333 } 6334 return SLCT_NotALiteral; 6335 6336 case Stmt::PredefinedExprClass: 6337 // While __func__, etc., are technically not string literals, they 6338 // cannot contain format specifiers and thus are not a security 6339 // liability. 6340 return SLCT_UncheckedLiteral; 6341 6342 case Stmt::DeclRefExprClass: { 6343 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6344 6345 // As an exception, do not flag errors for variables binding to 6346 // const string literals. 6347 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6348 bool isConstant = false; 6349 QualType T = DR->getType(); 6350 6351 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6352 isConstant = AT->getElementType().isConstant(S.Context); 6353 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6354 isConstant = T.isConstant(S.Context) && 6355 PT->getPointeeType().isConstant(S.Context); 6356 } else if (T->isObjCObjectPointerType()) { 6357 // In ObjC, there is usually no "const ObjectPointer" type, 6358 // so don't check if the pointee type is constant. 6359 isConstant = T.isConstant(S.Context); 6360 } 6361 6362 if (isConstant) { 6363 if (const Expr *Init = VD->getAnyInitializer()) { 6364 // Look through initializers like const char c[] = { "foo" } 6365 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6366 if (InitList->isStringLiteralInit()) 6367 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6368 } 6369 return checkFormatStringExpr(S, Init, Args, 6370 HasVAListArg, format_idx, 6371 firstDataArg, Type, CallType, 6372 /*InFunctionCall*/ false, CheckedVarArgs, 6373 UncoveredArg, Offset); 6374 } 6375 } 6376 6377 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6378 // special check to see if the format string is a function parameter 6379 // of the function calling the printf function. If the function 6380 // has an attribute indicating it is a printf-like function, then we 6381 // should suppress warnings concerning non-literals being used in a call 6382 // to a vprintf function. For example: 6383 // 6384 // void 6385 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6386 // va_list ap; 6387 // va_start(ap, fmt); 6388 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6389 // ... 6390 // } 6391 if (HasVAListArg) { 6392 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6393 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6394 int PVIndex = PV->getFunctionScopeIndex() + 1; 6395 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6396 // adjust for implicit parameter 6397 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6398 if (MD->isInstance()) 6399 ++PVIndex; 6400 // We also check if the formats are compatible. 6401 // We can't pass a 'scanf' string to a 'printf' function. 6402 if (PVIndex == PVFormat->getFormatIdx() && 6403 Type == S.GetFormatStringType(PVFormat)) 6404 return SLCT_UncheckedLiteral; 6405 } 6406 } 6407 } 6408 } 6409 } 6410 6411 return SLCT_NotALiteral; 6412 } 6413 6414 case Stmt::CallExprClass: 6415 case Stmt::CXXMemberCallExprClass: { 6416 const CallExpr *CE = cast<CallExpr>(E); 6417 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6418 bool IsFirst = true; 6419 StringLiteralCheckType CommonResult; 6420 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6421 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6422 StringLiteralCheckType Result = checkFormatStringExpr( 6423 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6424 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6425 if (IsFirst) { 6426 CommonResult = Result; 6427 IsFirst = false; 6428 } 6429 } 6430 if (!IsFirst) 6431 return CommonResult; 6432 6433 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6434 unsigned BuiltinID = FD->getBuiltinID(); 6435 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6436 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6437 const Expr *Arg = CE->getArg(0); 6438 return checkFormatStringExpr(S, Arg, Args, 6439 HasVAListArg, format_idx, 6440 firstDataArg, Type, CallType, 6441 InFunctionCall, CheckedVarArgs, 6442 UncoveredArg, Offset); 6443 } 6444 } 6445 } 6446 6447 return SLCT_NotALiteral; 6448 } 6449 case Stmt::ObjCMessageExprClass: { 6450 const auto *ME = cast<ObjCMessageExpr>(E); 6451 if (const auto *ND = ME->getMethodDecl()) { 6452 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6453 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6454 return checkFormatStringExpr( 6455 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6456 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6457 } 6458 } 6459 6460 return SLCT_NotALiteral; 6461 } 6462 case Stmt::ObjCStringLiteralClass: 6463 case Stmt::StringLiteralClass: { 6464 const StringLiteral *StrE = nullptr; 6465 6466 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6467 StrE = ObjCFExpr->getString(); 6468 else 6469 StrE = cast<StringLiteral>(E); 6470 6471 if (StrE) { 6472 if (Offset.isNegative() || Offset > StrE->getLength()) { 6473 // TODO: It would be better to have an explicit warning for out of 6474 // bounds literals. 6475 return SLCT_NotALiteral; 6476 } 6477 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6478 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6479 firstDataArg, Type, InFunctionCall, CallType, 6480 CheckedVarArgs, UncoveredArg); 6481 return SLCT_CheckedLiteral; 6482 } 6483 6484 return SLCT_NotALiteral; 6485 } 6486 case Stmt::BinaryOperatorClass: { 6487 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6488 6489 // A string literal + an int offset is still a string literal. 6490 if (BinOp->isAdditiveOp()) { 6491 Expr::EvalResult LResult, RResult; 6492 6493 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 6494 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 6495 6496 if (LIsInt != RIsInt) { 6497 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6498 6499 if (LIsInt) { 6500 if (BinOpKind == BO_Add) { 6501 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6502 E = BinOp->getRHS(); 6503 goto tryAgain; 6504 } 6505 } else { 6506 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6507 E = BinOp->getLHS(); 6508 goto tryAgain; 6509 } 6510 } 6511 } 6512 6513 return SLCT_NotALiteral; 6514 } 6515 case Stmt::UnaryOperatorClass: { 6516 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6517 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6518 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6519 Expr::EvalResult IndexResult; 6520 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 6521 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6522 /*RHS is int*/ true); 6523 E = ASE->getBase(); 6524 goto tryAgain; 6525 } 6526 } 6527 6528 return SLCT_NotALiteral; 6529 } 6530 6531 default: 6532 return SLCT_NotALiteral; 6533 } 6534 } 6535 6536 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6537 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6538 .Case("scanf", FST_Scanf) 6539 .Cases("printf", "printf0", FST_Printf) 6540 .Cases("NSString", "CFString", FST_NSString) 6541 .Case("strftime", FST_Strftime) 6542 .Case("strfmon", FST_Strfmon) 6543 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6544 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6545 .Case("os_trace", FST_OSLog) 6546 .Case("os_log", FST_OSLog) 6547 .Default(FST_Unknown); 6548 } 6549 6550 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6551 /// functions) for correct use of format strings. 6552 /// Returns true if a format string has been fully checked. 6553 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6554 ArrayRef<const Expr *> Args, 6555 bool IsCXXMember, 6556 VariadicCallType CallType, 6557 SourceLocation Loc, SourceRange Range, 6558 llvm::SmallBitVector &CheckedVarArgs) { 6559 FormatStringInfo FSI; 6560 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6561 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6562 FSI.FirstDataArg, GetFormatStringType(Format), 6563 CallType, Loc, Range, CheckedVarArgs); 6564 return false; 6565 } 6566 6567 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6568 bool HasVAListArg, unsigned format_idx, 6569 unsigned firstDataArg, FormatStringType Type, 6570 VariadicCallType CallType, 6571 SourceLocation Loc, SourceRange Range, 6572 llvm::SmallBitVector &CheckedVarArgs) { 6573 // CHECK: printf/scanf-like function is called with no format string. 6574 if (format_idx >= Args.size()) { 6575 Diag(Loc, diag::warn_missing_format_string) << Range; 6576 return false; 6577 } 6578 6579 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6580 6581 // CHECK: format string is not a string literal. 6582 // 6583 // Dynamically generated format strings are difficult to 6584 // automatically vet at compile time. Requiring that format strings 6585 // are string literals: (1) permits the checking of format strings by 6586 // the compiler and thereby (2) can practically remove the source of 6587 // many format string exploits. 6588 6589 // Format string can be either ObjC string (e.g. @"%d") or 6590 // C string (e.g. "%d") 6591 // ObjC string uses the same format specifiers as C string, so we can use 6592 // the same format string checking logic for both ObjC and C strings. 6593 UncoveredArgHandler UncoveredArg; 6594 StringLiteralCheckType CT = 6595 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6596 format_idx, firstDataArg, Type, CallType, 6597 /*IsFunctionCall*/ true, CheckedVarArgs, 6598 UncoveredArg, 6599 /*no string offset*/ llvm::APSInt(64, false) = 0); 6600 6601 // Generate a diagnostic where an uncovered argument is detected. 6602 if (UncoveredArg.hasUncoveredArg()) { 6603 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6604 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6605 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6606 } 6607 6608 if (CT != SLCT_NotALiteral) 6609 // Literal format string found, check done! 6610 return CT == SLCT_CheckedLiteral; 6611 6612 // Strftime is particular as it always uses a single 'time' argument, 6613 // so it is safe to pass a non-literal string. 6614 if (Type == FST_Strftime) 6615 return false; 6616 6617 // Do not emit diag when the string param is a macro expansion and the 6618 // format is either NSString or CFString. This is a hack to prevent 6619 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6620 // which are usually used in place of NS and CF string literals. 6621 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6622 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6623 return false; 6624 6625 // If there are no arguments specified, warn with -Wformat-security, otherwise 6626 // warn only with -Wformat-nonliteral. 6627 if (Args.size() == firstDataArg) { 6628 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6629 << OrigFormatExpr->getSourceRange(); 6630 switch (Type) { 6631 default: 6632 break; 6633 case FST_Kprintf: 6634 case FST_FreeBSDKPrintf: 6635 case FST_Printf: 6636 Diag(FormatLoc, diag::note_format_security_fixit) 6637 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6638 break; 6639 case FST_NSString: 6640 Diag(FormatLoc, diag::note_format_security_fixit) 6641 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6642 break; 6643 } 6644 } else { 6645 Diag(FormatLoc, diag::warn_format_nonliteral) 6646 << OrigFormatExpr->getSourceRange(); 6647 } 6648 return false; 6649 } 6650 6651 namespace { 6652 6653 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6654 protected: 6655 Sema &S; 6656 const FormatStringLiteral *FExpr; 6657 const Expr *OrigFormatExpr; 6658 const Sema::FormatStringType FSType; 6659 const unsigned FirstDataArg; 6660 const unsigned NumDataArgs; 6661 const char *Beg; // Start of format string. 6662 const bool HasVAListArg; 6663 ArrayRef<const Expr *> Args; 6664 unsigned FormatIdx; 6665 llvm::SmallBitVector CoveredArgs; 6666 bool usesPositionalArgs = false; 6667 bool atFirstArg = true; 6668 bool inFunctionCall; 6669 Sema::VariadicCallType CallType; 6670 llvm::SmallBitVector &CheckedVarArgs; 6671 UncoveredArgHandler &UncoveredArg; 6672 6673 public: 6674 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6675 const Expr *origFormatExpr, 6676 const Sema::FormatStringType type, unsigned firstDataArg, 6677 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6678 ArrayRef<const Expr *> Args, unsigned formatIdx, 6679 bool inFunctionCall, Sema::VariadicCallType callType, 6680 llvm::SmallBitVector &CheckedVarArgs, 6681 UncoveredArgHandler &UncoveredArg) 6682 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6683 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6684 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6685 inFunctionCall(inFunctionCall), CallType(callType), 6686 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6687 CoveredArgs.resize(numDataArgs); 6688 CoveredArgs.reset(); 6689 } 6690 6691 void DoneProcessing(); 6692 6693 void HandleIncompleteSpecifier(const char *startSpecifier, 6694 unsigned specifierLen) override; 6695 6696 void HandleInvalidLengthModifier( 6697 const analyze_format_string::FormatSpecifier &FS, 6698 const analyze_format_string::ConversionSpecifier &CS, 6699 const char *startSpecifier, unsigned specifierLen, 6700 unsigned DiagID); 6701 6702 void HandleNonStandardLengthModifier( 6703 const analyze_format_string::FormatSpecifier &FS, 6704 const char *startSpecifier, unsigned specifierLen); 6705 6706 void HandleNonStandardConversionSpecifier( 6707 const analyze_format_string::ConversionSpecifier &CS, 6708 const char *startSpecifier, unsigned specifierLen); 6709 6710 void HandlePosition(const char *startPos, unsigned posLen) override; 6711 6712 void HandleInvalidPosition(const char *startSpecifier, 6713 unsigned specifierLen, 6714 analyze_format_string::PositionContext p) override; 6715 6716 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6717 6718 void HandleNullChar(const char *nullCharacter) override; 6719 6720 template <typename Range> 6721 static void 6722 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6723 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6724 bool IsStringLocation, Range StringRange, 6725 ArrayRef<FixItHint> Fixit = None); 6726 6727 protected: 6728 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6729 const char *startSpec, 6730 unsigned specifierLen, 6731 const char *csStart, unsigned csLen); 6732 6733 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6734 const char *startSpec, 6735 unsigned specifierLen); 6736 6737 SourceRange getFormatStringRange(); 6738 CharSourceRange getSpecifierRange(const char *startSpecifier, 6739 unsigned specifierLen); 6740 SourceLocation getLocationOfByte(const char *x); 6741 6742 const Expr *getDataArg(unsigned i) const; 6743 6744 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6745 const analyze_format_string::ConversionSpecifier &CS, 6746 const char *startSpecifier, unsigned specifierLen, 6747 unsigned argIndex); 6748 6749 template <typename Range> 6750 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6751 bool IsStringLocation, Range StringRange, 6752 ArrayRef<FixItHint> Fixit = None); 6753 }; 6754 6755 } // namespace 6756 6757 SourceRange CheckFormatHandler::getFormatStringRange() { 6758 return OrigFormatExpr->getSourceRange(); 6759 } 6760 6761 CharSourceRange CheckFormatHandler:: 6762 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6763 SourceLocation Start = getLocationOfByte(startSpecifier); 6764 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6765 6766 // Advance the end SourceLocation by one due to half-open ranges. 6767 End = End.getLocWithOffset(1); 6768 6769 return CharSourceRange::getCharRange(Start, End); 6770 } 6771 6772 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6773 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6774 S.getLangOpts(), S.Context.getTargetInfo()); 6775 } 6776 6777 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6778 unsigned specifierLen){ 6779 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6780 getLocationOfByte(startSpecifier), 6781 /*IsStringLocation*/true, 6782 getSpecifierRange(startSpecifier, specifierLen)); 6783 } 6784 6785 void CheckFormatHandler::HandleInvalidLengthModifier( 6786 const analyze_format_string::FormatSpecifier &FS, 6787 const analyze_format_string::ConversionSpecifier &CS, 6788 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6789 using namespace analyze_format_string; 6790 6791 const LengthModifier &LM = FS.getLengthModifier(); 6792 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6793 6794 // See if we know how to fix this length modifier. 6795 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6796 if (FixedLM) { 6797 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6798 getLocationOfByte(LM.getStart()), 6799 /*IsStringLocation*/true, 6800 getSpecifierRange(startSpecifier, specifierLen)); 6801 6802 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6803 << FixedLM->toString() 6804 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6805 6806 } else { 6807 FixItHint Hint; 6808 if (DiagID == diag::warn_format_nonsensical_length) 6809 Hint = FixItHint::CreateRemoval(LMRange); 6810 6811 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6812 getLocationOfByte(LM.getStart()), 6813 /*IsStringLocation*/true, 6814 getSpecifierRange(startSpecifier, specifierLen), 6815 Hint); 6816 } 6817 } 6818 6819 void CheckFormatHandler::HandleNonStandardLengthModifier( 6820 const analyze_format_string::FormatSpecifier &FS, 6821 const char *startSpecifier, unsigned specifierLen) { 6822 using namespace analyze_format_string; 6823 6824 const LengthModifier &LM = FS.getLengthModifier(); 6825 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6826 6827 // See if we know how to fix this length modifier. 6828 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6829 if (FixedLM) { 6830 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6831 << LM.toString() << 0, 6832 getLocationOfByte(LM.getStart()), 6833 /*IsStringLocation*/true, 6834 getSpecifierRange(startSpecifier, specifierLen)); 6835 6836 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6837 << FixedLM->toString() 6838 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6839 6840 } else { 6841 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6842 << LM.toString() << 0, 6843 getLocationOfByte(LM.getStart()), 6844 /*IsStringLocation*/true, 6845 getSpecifierRange(startSpecifier, specifierLen)); 6846 } 6847 } 6848 6849 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6850 const analyze_format_string::ConversionSpecifier &CS, 6851 const char *startSpecifier, unsigned specifierLen) { 6852 using namespace analyze_format_string; 6853 6854 // See if we know how to fix this conversion specifier. 6855 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 6856 if (FixedCS) { 6857 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6858 << CS.toString() << /*conversion specifier*/1, 6859 getLocationOfByte(CS.getStart()), 6860 /*IsStringLocation*/true, 6861 getSpecifierRange(startSpecifier, specifierLen)); 6862 6863 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 6864 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 6865 << FixedCS->toString() 6866 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 6867 } else { 6868 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6869 << CS.toString() << /*conversion specifier*/1, 6870 getLocationOfByte(CS.getStart()), 6871 /*IsStringLocation*/true, 6872 getSpecifierRange(startSpecifier, specifierLen)); 6873 } 6874 } 6875 6876 void CheckFormatHandler::HandlePosition(const char *startPos, 6877 unsigned posLen) { 6878 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 6879 getLocationOfByte(startPos), 6880 /*IsStringLocation*/true, 6881 getSpecifierRange(startPos, posLen)); 6882 } 6883 6884 void 6885 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 6886 analyze_format_string::PositionContext p) { 6887 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 6888 << (unsigned) p, 6889 getLocationOfByte(startPos), /*IsStringLocation*/true, 6890 getSpecifierRange(startPos, posLen)); 6891 } 6892 6893 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 6894 unsigned posLen) { 6895 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 6896 getLocationOfByte(startPos), 6897 /*IsStringLocation*/true, 6898 getSpecifierRange(startPos, posLen)); 6899 } 6900 6901 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 6902 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 6903 // The presence of a null character is likely an error. 6904 EmitFormatDiagnostic( 6905 S.PDiag(diag::warn_printf_format_string_contains_null_char), 6906 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 6907 getFormatStringRange()); 6908 } 6909 } 6910 6911 // Note that this may return NULL if there was an error parsing or building 6912 // one of the argument expressions. 6913 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 6914 return Args[FirstDataArg + i]; 6915 } 6916 6917 void CheckFormatHandler::DoneProcessing() { 6918 // Does the number of data arguments exceed the number of 6919 // format conversions in the format string? 6920 if (!HasVAListArg) { 6921 // Find any arguments that weren't covered. 6922 CoveredArgs.flip(); 6923 signed notCoveredArg = CoveredArgs.find_first(); 6924 if (notCoveredArg >= 0) { 6925 assert((unsigned)notCoveredArg < NumDataArgs); 6926 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 6927 } else { 6928 UncoveredArg.setAllCovered(); 6929 } 6930 } 6931 } 6932 6933 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 6934 const Expr *ArgExpr) { 6935 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 6936 "Invalid state"); 6937 6938 if (!ArgExpr) 6939 return; 6940 6941 SourceLocation Loc = ArgExpr->getBeginLoc(); 6942 6943 if (S.getSourceManager().isInSystemMacro(Loc)) 6944 return; 6945 6946 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 6947 for (auto E : DiagnosticExprs) 6948 PDiag << E->getSourceRange(); 6949 6950 CheckFormatHandler::EmitFormatDiagnostic( 6951 S, IsFunctionCall, DiagnosticExprs[0], 6952 PDiag, Loc, /*IsStringLocation*/false, 6953 DiagnosticExprs[0]->getSourceRange()); 6954 } 6955 6956 bool 6957 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 6958 SourceLocation Loc, 6959 const char *startSpec, 6960 unsigned specifierLen, 6961 const char *csStart, 6962 unsigned csLen) { 6963 bool keepGoing = true; 6964 if (argIndex < NumDataArgs) { 6965 // Consider the argument coverered, even though the specifier doesn't 6966 // make sense. 6967 CoveredArgs.set(argIndex); 6968 } 6969 else { 6970 // If argIndex exceeds the number of data arguments we 6971 // don't issue a warning because that is just a cascade of warnings (and 6972 // they may have intended '%%' anyway). We don't want to continue processing 6973 // the format string after this point, however, as we will like just get 6974 // gibberish when trying to match arguments. 6975 keepGoing = false; 6976 } 6977 6978 StringRef Specifier(csStart, csLen); 6979 6980 // If the specifier in non-printable, it could be the first byte of a UTF-8 6981 // sequence. In that case, print the UTF-8 code point. If not, print the byte 6982 // hex value. 6983 std::string CodePointStr; 6984 if (!llvm::sys::locale::isPrint(*csStart)) { 6985 llvm::UTF32 CodePoint; 6986 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 6987 const llvm::UTF8 *E = 6988 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 6989 llvm::ConversionResult Result = 6990 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 6991 6992 if (Result != llvm::conversionOK) { 6993 unsigned char FirstChar = *csStart; 6994 CodePoint = (llvm::UTF32)FirstChar; 6995 } 6996 6997 llvm::raw_string_ostream OS(CodePointStr); 6998 if (CodePoint < 256) 6999 OS << "\\x" << llvm::format("%02x", CodePoint); 7000 else if (CodePoint <= 0xFFFF) 7001 OS << "\\u" << llvm::format("%04x", CodePoint); 7002 else 7003 OS << "\\U" << llvm::format("%08x", CodePoint); 7004 OS.flush(); 7005 Specifier = CodePointStr; 7006 } 7007 7008 EmitFormatDiagnostic( 7009 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7010 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7011 7012 return keepGoing; 7013 } 7014 7015 void 7016 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7017 const char *startSpec, 7018 unsigned specifierLen) { 7019 EmitFormatDiagnostic( 7020 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7021 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7022 } 7023 7024 bool 7025 CheckFormatHandler::CheckNumArgs( 7026 const analyze_format_string::FormatSpecifier &FS, 7027 const analyze_format_string::ConversionSpecifier &CS, 7028 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7029 7030 if (argIndex >= NumDataArgs) { 7031 PartialDiagnostic PDiag = FS.usesPositionalArg() 7032 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7033 << (argIndex+1) << NumDataArgs) 7034 : S.PDiag(diag::warn_printf_insufficient_data_args); 7035 EmitFormatDiagnostic( 7036 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7037 getSpecifierRange(startSpecifier, specifierLen)); 7038 7039 // Since more arguments than conversion tokens are given, by extension 7040 // all arguments are covered, so mark this as so. 7041 UncoveredArg.setAllCovered(); 7042 return false; 7043 } 7044 return true; 7045 } 7046 7047 template<typename Range> 7048 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7049 SourceLocation Loc, 7050 bool IsStringLocation, 7051 Range StringRange, 7052 ArrayRef<FixItHint> FixIt) { 7053 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7054 Loc, IsStringLocation, StringRange, FixIt); 7055 } 7056 7057 /// If the format string is not within the function call, emit a note 7058 /// so that the function call and string are in diagnostic messages. 7059 /// 7060 /// \param InFunctionCall if true, the format string is within the function 7061 /// call and only one diagnostic message will be produced. Otherwise, an 7062 /// extra note will be emitted pointing to location of the format string. 7063 /// 7064 /// \param ArgumentExpr the expression that is passed as the format string 7065 /// argument in the function call. Used for getting locations when two 7066 /// diagnostics are emitted. 7067 /// 7068 /// \param PDiag the callee should already have provided any strings for the 7069 /// diagnostic message. This function only adds locations and fixits 7070 /// to diagnostics. 7071 /// 7072 /// \param Loc primary location for diagnostic. If two diagnostics are 7073 /// required, one will be at Loc and a new SourceLocation will be created for 7074 /// the other one. 7075 /// 7076 /// \param IsStringLocation if true, Loc points to the format string should be 7077 /// used for the note. Otherwise, Loc points to the argument list and will 7078 /// be used with PDiag. 7079 /// 7080 /// \param StringRange some or all of the string to highlight. This is 7081 /// templated so it can accept either a CharSourceRange or a SourceRange. 7082 /// 7083 /// \param FixIt optional fix it hint for the format string. 7084 template <typename Range> 7085 void CheckFormatHandler::EmitFormatDiagnostic( 7086 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7087 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7088 Range StringRange, ArrayRef<FixItHint> FixIt) { 7089 if (InFunctionCall) { 7090 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7091 D << StringRange; 7092 D << FixIt; 7093 } else { 7094 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7095 << ArgumentExpr->getSourceRange(); 7096 7097 const Sema::SemaDiagnosticBuilder &Note = 7098 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7099 diag::note_format_string_defined); 7100 7101 Note << StringRange; 7102 Note << FixIt; 7103 } 7104 } 7105 7106 //===--- CHECK: Printf format string checking ------------------------------===// 7107 7108 namespace { 7109 7110 class CheckPrintfHandler : public CheckFormatHandler { 7111 public: 7112 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7113 const Expr *origFormatExpr, 7114 const Sema::FormatStringType type, unsigned firstDataArg, 7115 unsigned numDataArgs, bool isObjC, const char *beg, 7116 bool hasVAListArg, ArrayRef<const Expr *> Args, 7117 unsigned formatIdx, bool inFunctionCall, 7118 Sema::VariadicCallType CallType, 7119 llvm::SmallBitVector &CheckedVarArgs, 7120 UncoveredArgHandler &UncoveredArg) 7121 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7122 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7123 inFunctionCall, CallType, CheckedVarArgs, 7124 UncoveredArg) {} 7125 7126 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7127 7128 /// Returns true if '%@' specifiers are allowed in the format string. 7129 bool allowsObjCArg() const { 7130 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7131 FSType == Sema::FST_OSTrace; 7132 } 7133 7134 bool HandleInvalidPrintfConversionSpecifier( 7135 const analyze_printf::PrintfSpecifier &FS, 7136 const char *startSpecifier, 7137 unsigned specifierLen) override; 7138 7139 void handleInvalidMaskType(StringRef MaskType) override; 7140 7141 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7142 const char *startSpecifier, 7143 unsigned specifierLen) override; 7144 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7145 const char *StartSpecifier, 7146 unsigned SpecifierLen, 7147 const Expr *E); 7148 7149 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7150 const char *startSpecifier, unsigned specifierLen); 7151 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7152 const analyze_printf::OptionalAmount &Amt, 7153 unsigned type, 7154 const char *startSpecifier, unsigned specifierLen); 7155 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7156 const analyze_printf::OptionalFlag &flag, 7157 const char *startSpecifier, unsigned specifierLen); 7158 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7159 const analyze_printf::OptionalFlag &ignoredFlag, 7160 const analyze_printf::OptionalFlag &flag, 7161 const char *startSpecifier, unsigned specifierLen); 7162 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7163 const Expr *E); 7164 7165 void HandleEmptyObjCModifierFlag(const char *startFlag, 7166 unsigned flagLen) override; 7167 7168 void HandleInvalidObjCModifierFlag(const char *startFlag, 7169 unsigned flagLen) override; 7170 7171 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7172 const char *flagsEnd, 7173 const char *conversionPosition) 7174 override; 7175 }; 7176 7177 } // namespace 7178 7179 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7180 const analyze_printf::PrintfSpecifier &FS, 7181 const char *startSpecifier, 7182 unsigned specifierLen) { 7183 const analyze_printf::PrintfConversionSpecifier &CS = 7184 FS.getConversionSpecifier(); 7185 7186 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7187 getLocationOfByte(CS.getStart()), 7188 startSpecifier, specifierLen, 7189 CS.getStart(), CS.getLength()); 7190 } 7191 7192 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7193 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7194 } 7195 7196 bool CheckPrintfHandler::HandleAmount( 7197 const analyze_format_string::OptionalAmount &Amt, 7198 unsigned k, const char *startSpecifier, 7199 unsigned specifierLen) { 7200 if (Amt.hasDataArgument()) { 7201 if (!HasVAListArg) { 7202 unsigned argIndex = Amt.getArgIndex(); 7203 if (argIndex >= NumDataArgs) { 7204 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7205 << k, 7206 getLocationOfByte(Amt.getStart()), 7207 /*IsStringLocation*/true, 7208 getSpecifierRange(startSpecifier, specifierLen)); 7209 // Don't do any more checking. We will just emit 7210 // spurious errors. 7211 return false; 7212 } 7213 7214 // Type check the data argument. It should be an 'int'. 7215 // Although not in conformance with C99, we also allow the argument to be 7216 // an 'unsigned int' as that is a reasonably safe case. GCC also 7217 // doesn't emit a warning for that case. 7218 CoveredArgs.set(argIndex); 7219 const Expr *Arg = getDataArg(argIndex); 7220 if (!Arg) 7221 return false; 7222 7223 QualType T = Arg->getType(); 7224 7225 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7226 assert(AT.isValid()); 7227 7228 if (!AT.matchesType(S.Context, T)) { 7229 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7230 << k << AT.getRepresentativeTypeName(S.Context) 7231 << T << Arg->getSourceRange(), 7232 getLocationOfByte(Amt.getStart()), 7233 /*IsStringLocation*/true, 7234 getSpecifierRange(startSpecifier, specifierLen)); 7235 // Don't do any more checking. We will just emit 7236 // spurious errors. 7237 return false; 7238 } 7239 } 7240 } 7241 return true; 7242 } 7243 7244 void CheckPrintfHandler::HandleInvalidAmount( 7245 const analyze_printf::PrintfSpecifier &FS, 7246 const analyze_printf::OptionalAmount &Amt, 7247 unsigned type, 7248 const char *startSpecifier, 7249 unsigned specifierLen) { 7250 const analyze_printf::PrintfConversionSpecifier &CS = 7251 FS.getConversionSpecifier(); 7252 7253 FixItHint fixit = 7254 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7255 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7256 Amt.getConstantLength())) 7257 : FixItHint(); 7258 7259 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7260 << type << CS.toString(), 7261 getLocationOfByte(Amt.getStart()), 7262 /*IsStringLocation*/true, 7263 getSpecifierRange(startSpecifier, specifierLen), 7264 fixit); 7265 } 7266 7267 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7268 const analyze_printf::OptionalFlag &flag, 7269 const char *startSpecifier, 7270 unsigned specifierLen) { 7271 // Warn about pointless flag with a fixit removal. 7272 const analyze_printf::PrintfConversionSpecifier &CS = 7273 FS.getConversionSpecifier(); 7274 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7275 << flag.toString() << CS.toString(), 7276 getLocationOfByte(flag.getPosition()), 7277 /*IsStringLocation*/true, 7278 getSpecifierRange(startSpecifier, specifierLen), 7279 FixItHint::CreateRemoval( 7280 getSpecifierRange(flag.getPosition(), 1))); 7281 } 7282 7283 void CheckPrintfHandler::HandleIgnoredFlag( 7284 const analyze_printf::PrintfSpecifier &FS, 7285 const analyze_printf::OptionalFlag &ignoredFlag, 7286 const analyze_printf::OptionalFlag &flag, 7287 const char *startSpecifier, 7288 unsigned specifierLen) { 7289 // Warn about ignored flag with a fixit removal. 7290 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7291 << ignoredFlag.toString() << flag.toString(), 7292 getLocationOfByte(ignoredFlag.getPosition()), 7293 /*IsStringLocation*/true, 7294 getSpecifierRange(startSpecifier, specifierLen), 7295 FixItHint::CreateRemoval( 7296 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7297 } 7298 7299 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7300 unsigned flagLen) { 7301 // Warn about an empty flag. 7302 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7303 getLocationOfByte(startFlag), 7304 /*IsStringLocation*/true, 7305 getSpecifierRange(startFlag, flagLen)); 7306 } 7307 7308 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7309 unsigned flagLen) { 7310 // Warn about an invalid flag. 7311 auto Range = getSpecifierRange(startFlag, flagLen); 7312 StringRef flag(startFlag, flagLen); 7313 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7314 getLocationOfByte(startFlag), 7315 /*IsStringLocation*/true, 7316 Range, FixItHint::CreateRemoval(Range)); 7317 } 7318 7319 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7320 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7321 // Warn about using '[...]' without a '@' conversion. 7322 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7323 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7324 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7325 getLocationOfByte(conversionPosition), 7326 /*IsStringLocation*/true, 7327 Range, FixItHint::CreateRemoval(Range)); 7328 } 7329 7330 // Determines if the specified is a C++ class or struct containing 7331 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7332 // "c_str()"). 7333 template<typename MemberKind> 7334 static llvm::SmallPtrSet<MemberKind*, 1> 7335 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7336 const RecordType *RT = Ty->getAs<RecordType>(); 7337 llvm::SmallPtrSet<MemberKind*, 1> Results; 7338 7339 if (!RT) 7340 return Results; 7341 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7342 if (!RD || !RD->getDefinition()) 7343 return Results; 7344 7345 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7346 Sema::LookupMemberName); 7347 R.suppressDiagnostics(); 7348 7349 // We just need to include all members of the right kind turned up by the 7350 // filter, at this point. 7351 if (S.LookupQualifiedName(R, RT->getDecl())) 7352 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7353 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7354 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7355 Results.insert(FK); 7356 } 7357 return Results; 7358 } 7359 7360 /// Check if we could call '.c_str()' on an object. 7361 /// 7362 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7363 /// allow the call, or if it would be ambiguous). 7364 bool Sema::hasCStrMethod(const Expr *E) { 7365 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7366 7367 MethodSet Results = 7368 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7369 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7370 MI != ME; ++MI) 7371 if ((*MI)->getMinRequiredArguments() == 0) 7372 return true; 7373 return false; 7374 } 7375 7376 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7377 // better diagnostic if so. AT is assumed to be valid. 7378 // Returns true when a c_str() conversion method is found. 7379 bool CheckPrintfHandler::checkForCStrMembers( 7380 const analyze_printf::ArgType &AT, const Expr *E) { 7381 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7382 7383 MethodSet Results = 7384 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7385 7386 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7387 MI != ME; ++MI) { 7388 const CXXMethodDecl *Method = *MI; 7389 if (Method->getMinRequiredArguments() == 0 && 7390 AT.matchesType(S.Context, Method->getReturnType())) { 7391 // FIXME: Suggest parens if the expression needs them. 7392 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7393 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7394 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7395 return true; 7396 } 7397 } 7398 7399 return false; 7400 } 7401 7402 bool 7403 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7404 &FS, 7405 const char *startSpecifier, 7406 unsigned specifierLen) { 7407 using namespace analyze_format_string; 7408 using namespace analyze_printf; 7409 7410 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7411 7412 if (FS.consumesDataArgument()) { 7413 if (atFirstArg) { 7414 atFirstArg = false; 7415 usesPositionalArgs = FS.usesPositionalArg(); 7416 } 7417 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7418 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7419 startSpecifier, specifierLen); 7420 return false; 7421 } 7422 } 7423 7424 // First check if the field width, precision, and conversion specifier 7425 // have matching data arguments. 7426 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7427 startSpecifier, specifierLen)) { 7428 return false; 7429 } 7430 7431 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7432 startSpecifier, specifierLen)) { 7433 return false; 7434 } 7435 7436 if (!CS.consumesDataArgument()) { 7437 // FIXME: Technically specifying a precision or field width here 7438 // makes no sense. Worth issuing a warning at some point. 7439 return true; 7440 } 7441 7442 // Consume the argument. 7443 unsigned argIndex = FS.getArgIndex(); 7444 if (argIndex < NumDataArgs) { 7445 // The check to see if the argIndex is valid will come later. 7446 // We set the bit here because we may exit early from this 7447 // function if we encounter some other error. 7448 CoveredArgs.set(argIndex); 7449 } 7450 7451 // FreeBSD kernel extensions. 7452 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7453 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7454 // We need at least two arguments. 7455 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7456 return false; 7457 7458 // Claim the second argument. 7459 CoveredArgs.set(argIndex + 1); 7460 7461 // Type check the first argument (int for %b, pointer for %D) 7462 const Expr *Ex = getDataArg(argIndex); 7463 const analyze_printf::ArgType &AT = 7464 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7465 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7466 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7467 EmitFormatDiagnostic( 7468 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7469 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7470 << false << Ex->getSourceRange(), 7471 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7472 getSpecifierRange(startSpecifier, specifierLen)); 7473 7474 // Type check the second argument (char * for both %b and %D) 7475 Ex = getDataArg(argIndex + 1); 7476 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7477 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7478 EmitFormatDiagnostic( 7479 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7480 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7481 << false << Ex->getSourceRange(), 7482 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7483 getSpecifierRange(startSpecifier, specifierLen)); 7484 7485 return true; 7486 } 7487 7488 // Check for using an Objective-C specific conversion specifier 7489 // in a non-ObjC literal. 7490 if (!allowsObjCArg() && CS.isObjCArg()) { 7491 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7492 specifierLen); 7493 } 7494 7495 // %P can only be used with os_log. 7496 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7497 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7498 specifierLen); 7499 } 7500 7501 // %n is not allowed with os_log. 7502 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7503 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7504 getLocationOfByte(CS.getStart()), 7505 /*IsStringLocation*/ false, 7506 getSpecifierRange(startSpecifier, specifierLen)); 7507 7508 return true; 7509 } 7510 7511 // Only scalars are allowed for os_trace. 7512 if (FSType == Sema::FST_OSTrace && 7513 (CS.getKind() == ConversionSpecifier::PArg || 7514 CS.getKind() == ConversionSpecifier::sArg || 7515 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7516 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7517 specifierLen); 7518 } 7519 7520 // Check for use of public/private annotation outside of os_log(). 7521 if (FSType != Sema::FST_OSLog) { 7522 if (FS.isPublic().isSet()) { 7523 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7524 << "public", 7525 getLocationOfByte(FS.isPublic().getPosition()), 7526 /*IsStringLocation*/ false, 7527 getSpecifierRange(startSpecifier, specifierLen)); 7528 } 7529 if (FS.isPrivate().isSet()) { 7530 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7531 << "private", 7532 getLocationOfByte(FS.isPrivate().getPosition()), 7533 /*IsStringLocation*/ false, 7534 getSpecifierRange(startSpecifier, specifierLen)); 7535 } 7536 } 7537 7538 // Check for invalid use of field width 7539 if (!FS.hasValidFieldWidth()) { 7540 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7541 startSpecifier, specifierLen); 7542 } 7543 7544 // Check for invalid use of precision 7545 if (!FS.hasValidPrecision()) { 7546 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7547 startSpecifier, specifierLen); 7548 } 7549 7550 // Precision is mandatory for %P specifier. 7551 if (CS.getKind() == ConversionSpecifier::PArg && 7552 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7553 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7554 getLocationOfByte(startSpecifier), 7555 /*IsStringLocation*/ false, 7556 getSpecifierRange(startSpecifier, specifierLen)); 7557 } 7558 7559 // Check each flag does not conflict with any other component. 7560 if (!FS.hasValidThousandsGroupingPrefix()) 7561 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7562 if (!FS.hasValidLeadingZeros()) 7563 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7564 if (!FS.hasValidPlusPrefix()) 7565 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7566 if (!FS.hasValidSpacePrefix()) 7567 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7568 if (!FS.hasValidAlternativeForm()) 7569 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7570 if (!FS.hasValidLeftJustified()) 7571 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7572 7573 // Check that flags are not ignored by another flag 7574 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7575 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7576 startSpecifier, specifierLen); 7577 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7578 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7579 startSpecifier, specifierLen); 7580 7581 // Check the length modifier is valid with the given conversion specifier. 7582 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7583 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7584 diag::warn_format_nonsensical_length); 7585 else if (!FS.hasStandardLengthModifier()) 7586 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7587 else if (!FS.hasStandardLengthConversionCombination()) 7588 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7589 diag::warn_format_non_standard_conversion_spec); 7590 7591 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7592 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7593 7594 // The remaining checks depend on the data arguments. 7595 if (HasVAListArg) 7596 return true; 7597 7598 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7599 return false; 7600 7601 const Expr *Arg = getDataArg(argIndex); 7602 if (!Arg) 7603 return true; 7604 7605 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7606 } 7607 7608 static bool requiresParensToAddCast(const Expr *E) { 7609 // FIXME: We should have a general way to reason about operator 7610 // precedence and whether parens are actually needed here. 7611 // Take care of a few common cases where they aren't. 7612 const Expr *Inside = E->IgnoreImpCasts(); 7613 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7614 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7615 7616 switch (Inside->getStmtClass()) { 7617 case Stmt::ArraySubscriptExprClass: 7618 case Stmt::CallExprClass: 7619 case Stmt::CharacterLiteralClass: 7620 case Stmt::CXXBoolLiteralExprClass: 7621 case Stmt::DeclRefExprClass: 7622 case Stmt::FloatingLiteralClass: 7623 case Stmt::IntegerLiteralClass: 7624 case Stmt::MemberExprClass: 7625 case Stmt::ObjCArrayLiteralClass: 7626 case Stmt::ObjCBoolLiteralExprClass: 7627 case Stmt::ObjCBoxedExprClass: 7628 case Stmt::ObjCDictionaryLiteralClass: 7629 case Stmt::ObjCEncodeExprClass: 7630 case Stmt::ObjCIvarRefExprClass: 7631 case Stmt::ObjCMessageExprClass: 7632 case Stmt::ObjCPropertyRefExprClass: 7633 case Stmt::ObjCStringLiteralClass: 7634 case Stmt::ObjCSubscriptRefExprClass: 7635 case Stmt::ParenExprClass: 7636 case Stmt::StringLiteralClass: 7637 case Stmt::UnaryOperatorClass: 7638 return false; 7639 default: 7640 return true; 7641 } 7642 } 7643 7644 static std::pair<QualType, StringRef> 7645 shouldNotPrintDirectly(const ASTContext &Context, 7646 QualType IntendedTy, 7647 const Expr *E) { 7648 // Use a 'while' to peel off layers of typedefs. 7649 QualType TyTy = IntendedTy; 7650 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7651 StringRef Name = UserTy->getDecl()->getName(); 7652 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7653 .Case("CFIndex", Context.getNSIntegerType()) 7654 .Case("NSInteger", Context.getNSIntegerType()) 7655 .Case("NSUInteger", Context.getNSUIntegerType()) 7656 .Case("SInt32", Context.IntTy) 7657 .Case("UInt32", Context.UnsignedIntTy) 7658 .Default(QualType()); 7659 7660 if (!CastTy.isNull()) 7661 return std::make_pair(CastTy, Name); 7662 7663 TyTy = UserTy->desugar(); 7664 } 7665 7666 // Strip parens if necessary. 7667 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7668 return shouldNotPrintDirectly(Context, 7669 PE->getSubExpr()->getType(), 7670 PE->getSubExpr()); 7671 7672 // If this is a conditional expression, then its result type is constructed 7673 // via usual arithmetic conversions and thus there might be no necessary 7674 // typedef sugar there. Recurse to operands to check for NSInteger & 7675 // Co. usage condition. 7676 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7677 QualType TrueTy, FalseTy; 7678 StringRef TrueName, FalseName; 7679 7680 std::tie(TrueTy, TrueName) = 7681 shouldNotPrintDirectly(Context, 7682 CO->getTrueExpr()->getType(), 7683 CO->getTrueExpr()); 7684 std::tie(FalseTy, FalseName) = 7685 shouldNotPrintDirectly(Context, 7686 CO->getFalseExpr()->getType(), 7687 CO->getFalseExpr()); 7688 7689 if (TrueTy == FalseTy) 7690 return std::make_pair(TrueTy, TrueName); 7691 else if (TrueTy.isNull()) 7692 return std::make_pair(FalseTy, FalseName); 7693 else if (FalseTy.isNull()) 7694 return std::make_pair(TrueTy, TrueName); 7695 } 7696 7697 return std::make_pair(QualType(), StringRef()); 7698 } 7699 7700 bool 7701 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7702 const char *StartSpecifier, 7703 unsigned SpecifierLen, 7704 const Expr *E) { 7705 using namespace analyze_format_string; 7706 using namespace analyze_printf; 7707 7708 // Now type check the data expression that matches the 7709 // format specifier. 7710 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7711 if (!AT.isValid()) 7712 return true; 7713 7714 QualType ExprTy = E->getType(); 7715 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7716 ExprTy = TET->getUnderlyingExpr()->getType(); 7717 } 7718 7719 const analyze_printf::ArgType::MatchKind Match = 7720 AT.matchesType(S.Context, ExprTy); 7721 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 7722 if (Match == analyze_printf::ArgType::Match) 7723 return true; 7724 7725 // Look through argument promotions for our error message's reported type. 7726 // This includes the integral and floating promotions, but excludes array 7727 // and function pointer decay; seeing that an argument intended to be a 7728 // string has type 'char [6]' is probably more confusing than 'char *'. 7729 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7730 if (ICE->getCastKind() == CK_IntegralCast || 7731 ICE->getCastKind() == CK_FloatingCast) { 7732 E = ICE->getSubExpr(); 7733 ExprTy = E->getType(); 7734 7735 // Check if we didn't match because of an implicit cast from a 'char' 7736 // or 'short' to an 'int'. This is done because printf is a varargs 7737 // function. 7738 if (ICE->getType() == S.Context.IntTy || 7739 ICE->getType() == S.Context.UnsignedIntTy) { 7740 // All further checking is done on the subexpression. 7741 if (AT.matchesType(S.Context, ExprTy)) 7742 return true; 7743 } 7744 } 7745 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7746 // Special case for 'a', which has type 'int' in C. 7747 // Note, however, that we do /not/ want to treat multibyte constants like 7748 // 'MooV' as characters! This form is deprecated but still exists. 7749 if (ExprTy == S.Context.IntTy) 7750 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 7751 ExprTy = S.Context.CharTy; 7752 } 7753 7754 // Look through enums to their underlying type. 7755 bool IsEnum = false; 7756 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7757 ExprTy = EnumTy->getDecl()->getIntegerType(); 7758 IsEnum = true; 7759 } 7760 7761 // %C in an Objective-C context prints a unichar, not a wchar_t. 7762 // If the argument is an integer of some kind, believe the %C and suggest 7763 // a cast instead of changing the conversion specifier. 7764 QualType IntendedTy = ExprTy; 7765 if (isObjCContext() && 7766 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7767 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7768 !ExprTy->isCharType()) { 7769 // 'unichar' is defined as a typedef of unsigned short, but we should 7770 // prefer using the typedef if it is visible. 7771 IntendedTy = S.Context.UnsignedShortTy; 7772 7773 // While we are here, check if the value is an IntegerLiteral that happens 7774 // to be within the valid range. 7775 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7776 const llvm::APInt &V = IL->getValue(); 7777 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7778 return true; 7779 } 7780 7781 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7782 Sema::LookupOrdinaryName); 7783 if (S.LookupName(Result, S.getCurScope())) { 7784 NamedDecl *ND = Result.getFoundDecl(); 7785 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7786 if (TD->getUnderlyingType() == IntendedTy) 7787 IntendedTy = S.Context.getTypedefType(TD); 7788 } 7789 } 7790 } 7791 7792 // Special-case some of Darwin's platform-independence types by suggesting 7793 // casts to primitive types that are known to be large enough. 7794 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7795 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7796 QualType CastTy; 7797 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7798 if (!CastTy.isNull()) { 7799 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7800 // (long in ASTContext). Only complain to pedants. 7801 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7802 (AT.isSizeT() || AT.isPtrdiffT()) && 7803 AT.matchesType(S.Context, CastTy)) 7804 Pedantic = true; 7805 IntendedTy = CastTy; 7806 ShouldNotPrintDirectly = true; 7807 } 7808 } 7809 7810 // We may be able to offer a FixItHint if it is a supported type. 7811 PrintfSpecifier fixedFS = FS; 7812 bool Success = 7813 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7814 7815 if (Success) { 7816 // Get the fix string from the fixed format specifier 7817 SmallString<16> buf; 7818 llvm::raw_svector_ostream os(buf); 7819 fixedFS.toString(os); 7820 7821 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 7822 7823 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 7824 unsigned Diag = 7825 Pedantic 7826 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7827 : diag::warn_format_conversion_argument_type_mismatch; 7828 // In this case, the specifier is wrong and should be changed to match 7829 // the argument. 7830 EmitFormatDiagnostic(S.PDiag(Diag) 7831 << AT.getRepresentativeTypeName(S.Context) 7832 << IntendedTy << IsEnum << E->getSourceRange(), 7833 E->getBeginLoc(), 7834 /*IsStringLocation*/ false, SpecRange, 7835 FixItHint::CreateReplacement(SpecRange, os.str())); 7836 } else { 7837 // The canonical type for formatting this value is different from the 7838 // actual type of the expression. (This occurs, for example, with Darwin's 7839 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 7840 // should be printed as 'long' for 64-bit compatibility.) 7841 // Rather than emitting a normal format/argument mismatch, we want to 7842 // add a cast to the recommended type (and correct the format string 7843 // if necessary). 7844 SmallString<16> CastBuf; 7845 llvm::raw_svector_ostream CastFix(CastBuf); 7846 CastFix << "("; 7847 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 7848 CastFix << ")"; 7849 7850 SmallVector<FixItHint,4> Hints; 7851 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 7852 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 7853 7854 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 7855 // If there's already a cast present, just replace it. 7856 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 7857 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 7858 7859 } else if (!requiresParensToAddCast(E)) { 7860 // If the expression has high enough precedence, 7861 // just write the C-style cast. 7862 Hints.push_back( 7863 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7864 } else { 7865 // Otherwise, add parens around the expression as well as the cast. 7866 CastFix << "("; 7867 Hints.push_back( 7868 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7869 7870 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 7871 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 7872 } 7873 7874 if (ShouldNotPrintDirectly) { 7875 // The expression has a type that should not be printed directly. 7876 // We extract the name from the typedef because we don't want to show 7877 // the underlying type in the diagnostic. 7878 StringRef Name; 7879 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 7880 Name = TypedefTy->getDecl()->getName(); 7881 else 7882 Name = CastTyName; 7883 unsigned Diag = Pedantic 7884 ? diag::warn_format_argument_needs_cast_pedantic 7885 : diag::warn_format_argument_needs_cast; 7886 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 7887 << E->getSourceRange(), 7888 E->getBeginLoc(), /*IsStringLocation=*/false, 7889 SpecRange, Hints); 7890 } else { 7891 // In this case, the expression could be printed using a different 7892 // specifier, but we've decided that the specifier is probably correct 7893 // and we should cast instead. Just use the normal warning message. 7894 EmitFormatDiagnostic( 7895 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7896 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 7897 << E->getSourceRange(), 7898 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 7899 } 7900 } 7901 } else { 7902 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 7903 SpecifierLen); 7904 // Since the warning for passing non-POD types to variadic functions 7905 // was deferred until now, we emit a warning for non-POD 7906 // arguments here. 7907 switch (S.isValidVarArgType(ExprTy)) { 7908 case Sema::VAK_Valid: 7909 case Sema::VAK_ValidInCXX11: { 7910 unsigned Diag = 7911 Pedantic 7912 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7913 : diag::warn_format_conversion_argument_type_mismatch; 7914 7915 EmitFormatDiagnostic( 7916 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 7917 << IsEnum << CSR << E->getSourceRange(), 7918 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7919 break; 7920 } 7921 case Sema::VAK_Undefined: 7922 case Sema::VAK_MSVCUndefined: 7923 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 7924 << S.getLangOpts().CPlusPlus11 << ExprTy 7925 << CallType 7926 << AT.getRepresentativeTypeName(S.Context) << CSR 7927 << E->getSourceRange(), 7928 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7929 checkForCStrMembers(AT, E); 7930 break; 7931 7932 case Sema::VAK_Invalid: 7933 if (ExprTy->isObjCObjectType()) 7934 EmitFormatDiagnostic( 7935 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 7936 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 7937 << AT.getRepresentativeTypeName(S.Context) << CSR 7938 << E->getSourceRange(), 7939 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7940 else 7941 // FIXME: If this is an initializer list, suggest removing the braces 7942 // or inserting a cast to the target type. 7943 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 7944 << isa<InitListExpr>(E) << ExprTy << CallType 7945 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 7946 break; 7947 } 7948 7949 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 7950 "format string specifier index out of range"); 7951 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 7952 } 7953 7954 return true; 7955 } 7956 7957 //===--- CHECK: Scanf format string checking ------------------------------===// 7958 7959 namespace { 7960 7961 class CheckScanfHandler : public CheckFormatHandler { 7962 public: 7963 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 7964 const Expr *origFormatExpr, Sema::FormatStringType type, 7965 unsigned firstDataArg, unsigned numDataArgs, 7966 const char *beg, bool hasVAListArg, 7967 ArrayRef<const Expr *> Args, unsigned formatIdx, 7968 bool inFunctionCall, Sema::VariadicCallType CallType, 7969 llvm::SmallBitVector &CheckedVarArgs, 7970 UncoveredArgHandler &UncoveredArg) 7971 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7972 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7973 inFunctionCall, CallType, CheckedVarArgs, 7974 UncoveredArg) {} 7975 7976 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 7977 const char *startSpecifier, 7978 unsigned specifierLen) override; 7979 7980 bool HandleInvalidScanfConversionSpecifier( 7981 const analyze_scanf::ScanfSpecifier &FS, 7982 const char *startSpecifier, 7983 unsigned specifierLen) override; 7984 7985 void HandleIncompleteScanList(const char *start, const char *end) override; 7986 }; 7987 7988 } // namespace 7989 7990 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 7991 const char *end) { 7992 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 7993 getLocationOfByte(end), /*IsStringLocation*/true, 7994 getSpecifierRange(start, end - start)); 7995 } 7996 7997 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 7998 const analyze_scanf::ScanfSpecifier &FS, 7999 const char *startSpecifier, 8000 unsigned specifierLen) { 8001 const analyze_scanf::ScanfConversionSpecifier &CS = 8002 FS.getConversionSpecifier(); 8003 8004 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8005 getLocationOfByte(CS.getStart()), 8006 startSpecifier, specifierLen, 8007 CS.getStart(), CS.getLength()); 8008 } 8009 8010 bool CheckScanfHandler::HandleScanfSpecifier( 8011 const analyze_scanf::ScanfSpecifier &FS, 8012 const char *startSpecifier, 8013 unsigned specifierLen) { 8014 using namespace analyze_scanf; 8015 using namespace analyze_format_string; 8016 8017 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8018 8019 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8020 // be used to decide if we are using positional arguments consistently. 8021 if (FS.consumesDataArgument()) { 8022 if (atFirstArg) { 8023 atFirstArg = false; 8024 usesPositionalArgs = FS.usesPositionalArg(); 8025 } 8026 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8027 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8028 startSpecifier, specifierLen); 8029 return false; 8030 } 8031 } 8032 8033 // Check if the field with is non-zero. 8034 const OptionalAmount &Amt = FS.getFieldWidth(); 8035 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8036 if (Amt.getConstantAmount() == 0) { 8037 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8038 Amt.getConstantLength()); 8039 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8040 getLocationOfByte(Amt.getStart()), 8041 /*IsStringLocation*/true, R, 8042 FixItHint::CreateRemoval(R)); 8043 } 8044 } 8045 8046 if (!FS.consumesDataArgument()) { 8047 // FIXME: Technically specifying a precision or field width here 8048 // makes no sense. Worth issuing a warning at some point. 8049 return true; 8050 } 8051 8052 // Consume the argument. 8053 unsigned argIndex = FS.getArgIndex(); 8054 if (argIndex < NumDataArgs) { 8055 // The check to see if the argIndex is valid will come later. 8056 // We set the bit here because we may exit early from this 8057 // function if we encounter some other error. 8058 CoveredArgs.set(argIndex); 8059 } 8060 8061 // Check the length modifier is valid with the given conversion specifier. 8062 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 8063 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8064 diag::warn_format_nonsensical_length); 8065 else if (!FS.hasStandardLengthModifier()) 8066 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8067 else if (!FS.hasStandardLengthConversionCombination()) 8068 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8069 diag::warn_format_non_standard_conversion_spec); 8070 8071 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8072 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8073 8074 // The remaining checks depend on the data arguments. 8075 if (HasVAListArg) 8076 return true; 8077 8078 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8079 return false; 8080 8081 // Check that the argument type matches the format specifier. 8082 const Expr *Ex = getDataArg(argIndex); 8083 if (!Ex) 8084 return true; 8085 8086 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8087 8088 if (!AT.isValid()) { 8089 return true; 8090 } 8091 8092 analyze_format_string::ArgType::MatchKind Match = 8093 AT.matchesType(S.Context, Ex->getType()); 8094 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8095 if (Match == analyze_format_string::ArgType::Match) 8096 return true; 8097 8098 ScanfSpecifier fixedFS = FS; 8099 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8100 S.getLangOpts(), S.Context); 8101 8102 unsigned Diag = 8103 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8104 : diag::warn_format_conversion_argument_type_mismatch; 8105 8106 if (Success) { 8107 // Get the fix string from the fixed format specifier. 8108 SmallString<128> buf; 8109 llvm::raw_svector_ostream os(buf); 8110 fixedFS.toString(os); 8111 8112 EmitFormatDiagnostic( 8113 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8114 << Ex->getType() << false << Ex->getSourceRange(), 8115 Ex->getBeginLoc(), 8116 /*IsStringLocation*/ false, 8117 getSpecifierRange(startSpecifier, specifierLen), 8118 FixItHint::CreateReplacement( 8119 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8120 } else { 8121 EmitFormatDiagnostic(S.PDiag(Diag) 8122 << AT.getRepresentativeTypeName(S.Context) 8123 << Ex->getType() << false << Ex->getSourceRange(), 8124 Ex->getBeginLoc(), 8125 /*IsStringLocation*/ false, 8126 getSpecifierRange(startSpecifier, specifierLen)); 8127 } 8128 8129 return true; 8130 } 8131 8132 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8133 const Expr *OrigFormatExpr, 8134 ArrayRef<const Expr *> Args, 8135 bool HasVAListArg, unsigned format_idx, 8136 unsigned firstDataArg, 8137 Sema::FormatStringType Type, 8138 bool inFunctionCall, 8139 Sema::VariadicCallType CallType, 8140 llvm::SmallBitVector &CheckedVarArgs, 8141 UncoveredArgHandler &UncoveredArg) { 8142 // CHECK: is the format string a wide literal? 8143 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8144 CheckFormatHandler::EmitFormatDiagnostic( 8145 S, inFunctionCall, Args[format_idx], 8146 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8147 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8148 return; 8149 } 8150 8151 // Str - The format string. NOTE: this is NOT null-terminated! 8152 StringRef StrRef = FExpr->getString(); 8153 const char *Str = StrRef.data(); 8154 // Account for cases where the string literal is truncated in a declaration. 8155 const ConstantArrayType *T = 8156 S.Context.getAsConstantArrayType(FExpr->getType()); 8157 assert(T && "String literal not of constant array type!"); 8158 size_t TypeSize = T->getSize().getZExtValue(); 8159 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8160 const unsigned numDataArgs = Args.size() - firstDataArg; 8161 8162 // Emit a warning if the string literal is truncated and does not contain an 8163 // embedded null character. 8164 if (TypeSize <= StrRef.size() && 8165 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8166 CheckFormatHandler::EmitFormatDiagnostic( 8167 S, inFunctionCall, Args[format_idx], 8168 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8169 FExpr->getBeginLoc(), 8170 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8171 return; 8172 } 8173 8174 // CHECK: empty format string? 8175 if (StrLen == 0 && numDataArgs > 0) { 8176 CheckFormatHandler::EmitFormatDiagnostic( 8177 S, inFunctionCall, Args[format_idx], 8178 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8179 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8180 return; 8181 } 8182 8183 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8184 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8185 Type == Sema::FST_OSTrace) { 8186 CheckPrintfHandler H( 8187 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8188 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8189 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8190 CheckedVarArgs, UncoveredArg); 8191 8192 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8193 S.getLangOpts(), 8194 S.Context.getTargetInfo(), 8195 Type == Sema::FST_FreeBSDKPrintf)) 8196 H.DoneProcessing(); 8197 } else if (Type == Sema::FST_Scanf) { 8198 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8199 numDataArgs, Str, HasVAListArg, Args, format_idx, 8200 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8201 8202 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8203 S.getLangOpts(), 8204 S.Context.getTargetInfo())) 8205 H.DoneProcessing(); 8206 } // TODO: handle other formats 8207 } 8208 8209 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8210 // Str - The format string. NOTE: this is NOT null-terminated! 8211 StringRef StrRef = FExpr->getString(); 8212 const char *Str = StrRef.data(); 8213 // Account for cases where the string literal is truncated in a declaration. 8214 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8215 assert(T && "String literal not of constant array type!"); 8216 size_t TypeSize = T->getSize().getZExtValue(); 8217 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8218 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8219 getLangOpts(), 8220 Context.getTargetInfo()); 8221 } 8222 8223 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8224 8225 // Returns the related absolute value function that is larger, of 0 if one 8226 // does not exist. 8227 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8228 switch (AbsFunction) { 8229 default: 8230 return 0; 8231 8232 case Builtin::BI__builtin_abs: 8233 return Builtin::BI__builtin_labs; 8234 case Builtin::BI__builtin_labs: 8235 return Builtin::BI__builtin_llabs; 8236 case Builtin::BI__builtin_llabs: 8237 return 0; 8238 8239 case Builtin::BI__builtin_fabsf: 8240 return Builtin::BI__builtin_fabs; 8241 case Builtin::BI__builtin_fabs: 8242 return Builtin::BI__builtin_fabsl; 8243 case Builtin::BI__builtin_fabsl: 8244 return 0; 8245 8246 case Builtin::BI__builtin_cabsf: 8247 return Builtin::BI__builtin_cabs; 8248 case Builtin::BI__builtin_cabs: 8249 return Builtin::BI__builtin_cabsl; 8250 case Builtin::BI__builtin_cabsl: 8251 return 0; 8252 8253 case Builtin::BIabs: 8254 return Builtin::BIlabs; 8255 case Builtin::BIlabs: 8256 return Builtin::BIllabs; 8257 case Builtin::BIllabs: 8258 return 0; 8259 8260 case Builtin::BIfabsf: 8261 return Builtin::BIfabs; 8262 case Builtin::BIfabs: 8263 return Builtin::BIfabsl; 8264 case Builtin::BIfabsl: 8265 return 0; 8266 8267 case Builtin::BIcabsf: 8268 return Builtin::BIcabs; 8269 case Builtin::BIcabs: 8270 return Builtin::BIcabsl; 8271 case Builtin::BIcabsl: 8272 return 0; 8273 } 8274 } 8275 8276 // Returns the argument type of the absolute value function. 8277 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8278 unsigned AbsType) { 8279 if (AbsType == 0) 8280 return QualType(); 8281 8282 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8283 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8284 if (Error != ASTContext::GE_None) 8285 return QualType(); 8286 8287 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8288 if (!FT) 8289 return QualType(); 8290 8291 if (FT->getNumParams() != 1) 8292 return QualType(); 8293 8294 return FT->getParamType(0); 8295 } 8296 8297 // Returns the best absolute value function, or zero, based on type and 8298 // current absolute value function. 8299 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8300 unsigned AbsFunctionKind) { 8301 unsigned BestKind = 0; 8302 uint64_t ArgSize = Context.getTypeSize(ArgType); 8303 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8304 Kind = getLargerAbsoluteValueFunction(Kind)) { 8305 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8306 if (Context.getTypeSize(ParamType) >= ArgSize) { 8307 if (BestKind == 0) 8308 BestKind = Kind; 8309 else if (Context.hasSameType(ParamType, ArgType)) { 8310 BestKind = Kind; 8311 break; 8312 } 8313 } 8314 } 8315 return BestKind; 8316 } 8317 8318 enum AbsoluteValueKind { 8319 AVK_Integer, 8320 AVK_Floating, 8321 AVK_Complex 8322 }; 8323 8324 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8325 if (T->isIntegralOrEnumerationType()) 8326 return AVK_Integer; 8327 if (T->isRealFloatingType()) 8328 return AVK_Floating; 8329 if (T->isAnyComplexType()) 8330 return AVK_Complex; 8331 8332 llvm_unreachable("Type not integer, floating, or complex"); 8333 } 8334 8335 // Changes the absolute value function to a different type. Preserves whether 8336 // the function is a builtin. 8337 static unsigned changeAbsFunction(unsigned AbsKind, 8338 AbsoluteValueKind ValueKind) { 8339 switch (ValueKind) { 8340 case AVK_Integer: 8341 switch (AbsKind) { 8342 default: 8343 return 0; 8344 case Builtin::BI__builtin_fabsf: 8345 case Builtin::BI__builtin_fabs: 8346 case Builtin::BI__builtin_fabsl: 8347 case Builtin::BI__builtin_cabsf: 8348 case Builtin::BI__builtin_cabs: 8349 case Builtin::BI__builtin_cabsl: 8350 return Builtin::BI__builtin_abs; 8351 case Builtin::BIfabsf: 8352 case Builtin::BIfabs: 8353 case Builtin::BIfabsl: 8354 case Builtin::BIcabsf: 8355 case Builtin::BIcabs: 8356 case Builtin::BIcabsl: 8357 return Builtin::BIabs; 8358 } 8359 case AVK_Floating: 8360 switch (AbsKind) { 8361 default: 8362 return 0; 8363 case Builtin::BI__builtin_abs: 8364 case Builtin::BI__builtin_labs: 8365 case Builtin::BI__builtin_llabs: 8366 case Builtin::BI__builtin_cabsf: 8367 case Builtin::BI__builtin_cabs: 8368 case Builtin::BI__builtin_cabsl: 8369 return Builtin::BI__builtin_fabsf; 8370 case Builtin::BIabs: 8371 case Builtin::BIlabs: 8372 case Builtin::BIllabs: 8373 case Builtin::BIcabsf: 8374 case Builtin::BIcabs: 8375 case Builtin::BIcabsl: 8376 return Builtin::BIfabsf; 8377 } 8378 case AVK_Complex: 8379 switch (AbsKind) { 8380 default: 8381 return 0; 8382 case Builtin::BI__builtin_abs: 8383 case Builtin::BI__builtin_labs: 8384 case Builtin::BI__builtin_llabs: 8385 case Builtin::BI__builtin_fabsf: 8386 case Builtin::BI__builtin_fabs: 8387 case Builtin::BI__builtin_fabsl: 8388 return Builtin::BI__builtin_cabsf; 8389 case Builtin::BIabs: 8390 case Builtin::BIlabs: 8391 case Builtin::BIllabs: 8392 case Builtin::BIfabsf: 8393 case Builtin::BIfabs: 8394 case Builtin::BIfabsl: 8395 return Builtin::BIcabsf; 8396 } 8397 } 8398 llvm_unreachable("Unable to convert function"); 8399 } 8400 8401 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8402 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8403 if (!FnInfo) 8404 return 0; 8405 8406 switch (FDecl->getBuiltinID()) { 8407 default: 8408 return 0; 8409 case Builtin::BI__builtin_abs: 8410 case Builtin::BI__builtin_fabs: 8411 case Builtin::BI__builtin_fabsf: 8412 case Builtin::BI__builtin_fabsl: 8413 case Builtin::BI__builtin_labs: 8414 case Builtin::BI__builtin_llabs: 8415 case Builtin::BI__builtin_cabs: 8416 case Builtin::BI__builtin_cabsf: 8417 case Builtin::BI__builtin_cabsl: 8418 case Builtin::BIabs: 8419 case Builtin::BIlabs: 8420 case Builtin::BIllabs: 8421 case Builtin::BIfabs: 8422 case Builtin::BIfabsf: 8423 case Builtin::BIfabsl: 8424 case Builtin::BIcabs: 8425 case Builtin::BIcabsf: 8426 case Builtin::BIcabsl: 8427 return FDecl->getBuiltinID(); 8428 } 8429 llvm_unreachable("Unknown Builtin type"); 8430 } 8431 8432 // If the replacement is valid, emit a note with replacement function. 8433 // Additionally, suggest including the proper header if not already included. 8434 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8435 unsigned AbsKind, QualType ArgType) { 8436 bool EmitHeaderHint = true; 8437 const char *HeaderName = nullptr; 8438 const char *FunctionName = nullptr; 8439 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8440 FunctionName = "std::abs"; 8441 if (ArgType->isIntegralOrEnumerationType()) { 8442 HeaderName = "cstdlib"; 8443 } else if (ArgType->isRealFloatingType()) { 8444 HeaderName = "cmath"; 8445 } else { 8446 llvm_unreachable("Invalid Type"); 8447 } 8448 8449 // Lookup all std::abs 8450 if (NamespaceDecl *Std = S.getStdNamespace()) { 8451 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8452 R.suppressDiagnostics(); 8453 S.LookupQualifiedName(R, Std); 8454 8455 for (const auto *I : R) { 8456 const FunctionDecl *FDecl = nullptr; 8457 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8458 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8459 } else { 8460 FDecl = dyn_cast<FunctionDecl>(I); 8461 } 8462 if (!FDecl) 8463 continue; 8464 8465 // Found std::abs(), check that they are the right ones. 8466 if (FDecl->getNumParams() != 1) 8467 continue; 8468 8469 // Check that the parameter type can handle the argument. 8470 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8471 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8472 S.Context.getTypeSize(ArgType) <= 8473 S.Context.getTypeSize(ParamType)) { 8474 // Found a function, don't need the header hint. 8475 EmitHeaderHint = false; 8476 break; 8477 } 8478 } 8479 } 8480 } else { 8481 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8482 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8483 8484 if (HeaderName) { 8485 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8486 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8487 R.suppressDiagnostics(); 8488 S.LookupName(R, S.getCurScope()); 8489 8490 if (R.isSingleResult()) { 8491 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8492 if (FD && FD->getBuiltinID() == AbsKind) { 8493 EmitHeaderHint = false; 8494 } else { 8495 return; 8496 } 8497 } else if (!R.empty()) { 8498 return; 8499 } 8500 } 8501 } 8502 8503 S.Diag(Loc, diag::note_replace_abs_function) 8504 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8505 8506 if (!HeaderName) 8507 return; 8508 8509 if (!EmitHeaderHint) 8510 return; 8511 8512 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8513 << FunctionName; 8514 } 8515 8516 template <std::size_t StrLen> 8517 static bool IsStdFunction(const FunctionDecl *FDecl, 8518 const char (&Str)[StrLen]) { 8519 if (!FDecl) 8520 return false; 8521 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8522 return false; 8523 if (!FDecl->isInStdNamespace()) 8524 return false; 8525 8526 return true; 8527 } 8528 8529 // Warn when using the wrong abs() function. 8530 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8531 const FunctionDecl *FDecl) { 8532 if (Call->getNumArgs() != 1) 8533 return; 8534 8535 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8536 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8537 if (AbsKind == 0 && !IsStdAbs) 8538 return; 8539 8540 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8541 QualType ParamType = Call->getArg(0)->getType(); 8542 8543 // Unsigned types cannot be negative. Suggest removing the absolute value 8544 // function call. 8545 if (ArgType->isUnsignedIntegerType()) { 8546 const char *FunctionName = 8547 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8548 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8549 Diag(Call->getExprLoc(), diag::note_remove_abs) 8550 << FunctionName 8551 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8552 return; 8553 } 8554 8555 // Taking the absolute value of a pointer is very suspicious, they probably 8556 // wanted to index into an array, dereference a pointer, call a function, etc. 8557 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8558 unsigned DiagType = 0; 8559 if (ArgType->isFunctionType()) 8560 DiagType = 1; 8561 else if (ArgType->isArrayType()) 8562 DiagType = 2; 8563 8564 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8565 return; 8566 } 8567 8568 // std::abs has overloads which prevent most of the absolute value problems 8569 // from occurring. 8570 if (IsStdAbs) 8571 return; 8572 8573 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8574 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8575 8576 // The argument and parameter are the same kind. Check if they are the right 8577 // size. 8578 if (ArgValueKind == ParamValueKind) { 8579 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8580 return; 8581 8582 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8583 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8584 << FDecl << ArgType << ParamType; 8585 8586 if (NewAbsKind == 0) 8587 return; 8588 8589 emitReplacement(*this, Call->getExprLoc(), 8590 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8591 return; 8592 } 8593 8594 // ArgValueKind != ParamValueKind 8595 // The wrong type of absolute value function was used. Attempt to find the 8596 // proper one. 8597 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8598 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8599 if (NewAbsKind == 0) 8600 return; 8601 8602 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8603 << FDecl << ParamValueKind << ArgValueKind; 8604 8605 emitReplacement(*this, Call->getExprLoc(), 8606 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8607 } 8608 8609 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8610 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8611 const FunctionDecl *FDecl) { 8612 if (!Call || !FDecl) return; 8613 8614 // Ignore template specializations and macros. 8615 if (inTemplateInstantiation()) return; 8616 if (Call->getExprLoc().isMacroID()) return; 8617 8618 // Only care about the one template argument, two function parameter std::max 8619 if (Call->getNumArgs() != 2) return; 8620 if (!IsStdFunction(FDecl, "max")) return; 8621 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8622 if (!ArgList) return; 8623 if (ArgList->size() != 1) return; 8624 8625 // Check that template type argument is unsigned integer. 8626 const auto& TA = ArgList->get(0); 8627 if (TA.getKind() != TemplateArgument::Type) return; 8628 QualType ArgType = TA.getAsType(); 8629 if (!ArgType->isUnsignedIntegerType()) return; 8630 8631 // See if either argument is a literal zero. 8632 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8633 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8634 if (!MTE) return false; 8635 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8636 if (!Num) return false; 8637 if (Num->getValue() != 0) return false; 8638 return true; 8639 }; 8640 8641 const Expr *FirstArg = Call->getArg(0); 8642 const Expr *SecondArg = Call->getArg(1); 8643 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8644 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8645 8646 // Only warn when exactly one argument is zero. 8647 if (IsFirstArgZero == IsSecondArgZero) return; 8648 8649 SourceRange FirstRange = FirstArg->getSourceRange(); 8650 SourceRange SecondRange = SecondArg->getSourceRange(); 8651 8652 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8653 8654 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8655 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8656 8657 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8658 SourceRange RemovalRange; 8659 if (IsFirstArgZero) { 8660 RemovalRange = SourceRange(FirstRange.getBegin(), 8661 SecondRange.getBegin().getLocWithOffset(-1)); 8662 } else { 8663 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8664 SecondRange.getEnd()); 8665 } 8666 8667 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8668 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8669 << FixItHint::CreateRemoval(RemovalRange); 8670 } 8671 8672 //===--- CHECK: Standard memory functions ---------------------------------===// 8673 8674 /// Takes the expression passed to the size_t parameter of functions 8675 /// such as memcmp, strncat, etc and warns if it's a comparison. 8676 /// 8677 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8678 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8679 IdentifierInfo *FnName, 8680 SourceLocation FnLoc, 8681 SourceLocation RParenLoc) { 8682 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8683 if (!Size) 8684 return false; 8685 8686 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8687 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8688 return false; 8689 8690 SourceRange SizeRange = Size->getSourceRange(); 8691 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8692 << SizeRange << FnName; 8693 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8694 << FnName 8695 << FixItHint::CreateInsertion( 8696 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8697 << FixItHint::CreateRemoval(RParenLoc); 8698 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8699 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8700 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8701 ")"); 8702 8703 return true; 8704 } 8705 8706 /// Determine whether the given type is or contains a dynamic class type 8707 /// (e.g., whether it has a vtable). 8708 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8709 bool &IsContained) { 8710 // Look through array types while ignoring qualifiers. 8711 const Type *Ty = T->getBaseElementTypeUnsafe(); 8712 IsContained = false; 8713 8714 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8715 RD = RD ? RD->getDefinition() : nullptr; 8716 if (!RD || RD->isInvalidDecl()) 8717 return nullptr; 8718 8719 if (RD->isDynamicClass()) 8720 return RD; 8721 8722 // Check all the fields. If any bases were dynamic, the class is dynamic. 8723 // It's impossible for a class to transitively contain itself by value, so 8724 // infinite recursion is impossible. 8725 for (auto *FD : RD->fields()) { 8726 bool SubContained; 8727 if (const CXXRecordDecl *ContainedRD = 8728 getContainedDynamicClass(FD->getType(), SubContained)) { 8729 IsContained = true; 8730 return ContainedRD; 8731 } 8732 } 8733 8734 return nullptr; 8735 } 8736 8737 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8738 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8739 if (Unary->getKind() == UETT_SizeOf) 8740 return Unary; 8741 return nullptr; 8742 } 8743 8744 /// If E is a sizeof expression, returns its argument expression, 8745 /// otherwise returns NULL. 8746 static const Expr *getSizeOfExprArg(const Expr *E) { 8747 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8748 if (!SizeOf->isArgumentType()) 8749 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8750 return nullptr; 8751 } 8752 8753 /// If E is a sizeof expression, returns its argument type. 8754 static QualType getSizeOfArgType(const Expr *E) { 8755 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8756 return SizeOf->getTypeOfArgument(); 8757 return QualType(); 8758 } 8759 8760 namespace { 8761 8762 struct SearchNonTrivialToInitializeField 8763 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8764 using Super = 8765 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8766 8767 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8768 8769 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8770 SourceLocation SL) { 8771 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8772 asDerived().visitArray(PDIK, AT, SL); 8773 return; 8774 } 8775 8776 Super::visitWithKind(PDIK, FT, SL); 8777 } 8778 8779 void visitARCStrong(QualType FT, SourceLocation SL) { 8780 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8781 } 8782 void visitARCWeak(QualType FT, SourceLocation SL) { 8783 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8784 } 8785 void visitStruct(QualType FT, SourceLocation SL) { 8786 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8787 visit(FD->getType(), FD->getLocation()); 8788 } 8789 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8790 const ArrayType *AT, SourceLocation SL) { 8791 visit(getContext().getBaseElementType(AT), SL); 8792 } 8793 void visitTrivial(QualType FT, SourceLocation SL) {} 8794 8795 static void diag(QualType RT, const Expr *E, Sema &S) { 8796 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 8797 } 8798 8799 ASTContext &getContext() { return S.getASTContext(); } 8800 8801 const Expr *E; 8802 Sema &S; 8803 }; 8804 8805 struct SearchNonTrivialToCopyField 8806 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 8807 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 8808 8809 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 8810 8811 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 8812 SourceLocation SL) { 8813 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8814 asDerived().visitArray(PCK, AT, SL); 8815 return; 8816 } 8817 8818 Super::visitWithKind(PCK, FT, SL); 8819 } 8820 8821 void visitARCStrong(QualType FT, SourceLocation SL) { 8822 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8823 } 8824 void visitARCWeak(QualType FT, SourceLocation SL) { 8825 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8826 } 8827 void visitStruct(QualType FT, SourceLocation SL) { 8828 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8829 visit(FD->getType(), FD->getLocation()); 8830 } 8831 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 8832 SourceLocation SL) { 8833 visit(getContext().getBaseElementType(AT), SL); 8834 } 8835 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 8836 SourceLocation SL) {} 8837 void visitTrivial(QualType FT, SourceLocation SL) {} 8838 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 8839 8840 static void diag(QualType RT, const Expr *E, Sema &S) { 8841 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 8842 } 8843 8844 ASTContext &getContext() { return S.getASTContext(); } 8845 8846 const Expr *E; 8847 Sema &S; 8848 }; 8849 8850 } 8851 8852 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 8853 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 8854 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 8855 8856 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 8857 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 8858 return false; 8859 8860 return doesExprLikelyComputeSize(BO->getLHS()) || 8861 doesExprLikelyComputeSize(BO->getRHS()); 8862 } 8863 8864 return getAsSizeOfExpr(SizeofExpr) != nullptr; 8865 } 8866 8867 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 8868 /// 8869 /// \code 8870 /// #define MACRO 0 8871 /// foo(MACRO); 8872 /// foo(0); 8873 /// \endcode 8874 /// 8875 /// This should return true for the first call to foo, but not for the second 8876 /// (regardless of whether foo is a macro or function). 8877 static bool isArgumentExpandedFromMacro(SourceManager &SM, 8878 SourceLocation CallLoc, 8879 SourceLocation ArgLoc) { 8880 if (!CallLoc.isMacroID()) 8881 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 8882 8883 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 8884 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 8885 } 8886 8887 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 8888 /// last two arguments transposed. 8889 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 8890 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 8891 return; 8892 8893 const Expr *SizeArg = 8894 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 8895 8896 auto isLiteralZero = [](const Expr *E) { 8897 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 8898 }; 8899 8900 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 8901 SourceLocation CallLoc = Call->getRParenLoc(); 8902 SourceManager &SM = S.getSourceManager(); 8903 if (isLiteralZero(SizeArg) && 8904 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 8905 8906 SourceLocation DiagLoc = SizeArg->getExprLoc(); 8907 8908 // Some platforms #define bzero to __builtin_memset. See if this is the 8909 // case, and if so, emit a better diagnostic. 8910 if (BId == Builtin::BIbzero || 8911 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 8912 CallLoc, SM, S.getLangOpts()) == "bzero")) { 8913 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 8914 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 8915 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 8916 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 8917 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 8918 } 8919 return; 8920 } 8921 8922 // If the second argument to a memset is a sizeof expression and the third 8923 // isn't, this is also likely an error. This should catch 8924 // 'memset(buf, sizeof(buf), 0xff)'. 8925 if (BId == Builtin::BImemset && 8926 doesExprLikelyComputeSize(Call->getArg(1)) && 8927 !doesExprLikelyComputeSize(Call->getArg(2))) { 8928 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 8929 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 8930 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 8931 return; 8932 } 8933 } 8934 8935 /// Check for dangerous or invalid arguments to memset(). 8936 /// 8937 /// This issues warnings on known problematic, dangerous or unspecified 8938 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 8939 /// function calls. 8940 /// 8941 /// \param Call The call expression to diagnose. 8942 void Sema::CheckMemaccessArguments(const CallExpr *Call, 8943 unsigned BId, 8944 IdentifierInfo *FnName) { 8945 assert(BId != 0); 8946 8947 // It is possible to have a non-standard definition of memset. Validate 8948 // we have enough arguments, and if not, abort further checking. 8949 unsigned ExpectedNumArgs = 8950 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 8951 if (Call->getNumArgs() < ExpectedNumArgs) 8952 return; 8953 8954 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 8955 BId == Builtin::BIstrndup ? 1 : 2); 8956 unsigned LenArg = 8957 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 8958 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 8959 8960 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 8961 Call->getBeginLoc(), Call->getRParenLoc())) 8962 return; 8963 8964 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 8965 CheckMemaccessSize(*this, BId, Call); 8966 8967 // We have special checking when the length is a sizeof expression. 8968 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 8969 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 8970 llvm::FoldingSetNodeID SizeOfArgID; 8971 8972 // Although widely used, 'bzero' is not a standard function. Be more strict 8973 // with the argument types before allowing diagnostics and only allow the 8974 // form bzero(ptr, sizeof(...)). 8975 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8976 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 8977 return; 8978 8979 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 8980 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 8981 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 8982 8983 QualType DestTy = Dest->getType(); 8984 QualType PointeeTy; 8985 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 8986 PointeeTy = DestPtrTy->getPointeeType(); 8987 8988 // Never warn about void type pointers. This can be used to suppress 8989 // false positives. 8990 if (PointeeTy->isVoidType()) 8991 continue; 8992 8993 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 8994 // actually comparing the expressions for equality. Because computing the 8995 // expression IDs can be expensive, we only do this if the diagnostic is 8996 // enabled. 8997 if (SizeOfArg && 8998 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 8999 SizeOfArg->getExprLoc())) { 9000 // We only compute IDs for expressions if the warning is enabled, and 9001 // cache the sizeof arg's ID. 9002 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9003 SizeOfArg->Profile(SizeOfArgID, Context, true); 9004 llvm::FoldingSetNodeID DestID; 9005 Dest->Profile(DestID, Context, true); 9006 if (DestID == SizeOfArgID) { 9007 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9008 // over sizeof(src) as well. 9009 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9010 StringRef ReadableName = FnName->getName(); 9011 9012 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9013 if (UnaryOp->getOpcode() == UO_AddrOf) 9014 ActionIdx = 1; // If its an address-of operator, just remove it. 9015 if (!PointeeTy->isIncompleteType() && 9016 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9017 ActionIdx = 2; // If the pointee's size is sizeof(char), 9018 // suggest an explicit length. 9019 9020 // If the function is defined as a builtin macro, do not show macro 9021 // expansion. 9022 SourceLocation SL = SizeOfArg->getExprLoc(); 9023 SourceRange DSR = Dest->getSourceRange(); 9024 SourceRange SSR = SizeOfArg->getSourceRange(); 9025 SourceManager &SM = getSourceManager(); 9026 9027 if (SM.isMacroArgExpansion(SL)) { 9028 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9029 SL = SM.getSpellingLoc(SL); 9030 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9031 SM.getSpellingLoc(DSR.getEnd())); 9032 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9033 SM.getSpellingLoc(SSR.getEnd())); 9034 } 9035 9036 DiagRuntimeBehavior(SL, SizeOfArg, 9037 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9038 << ReadableName 9039 << PointeeTy 9040 << DestTy 9041 << DSR 9042 << SSR); 9043 DiagRuntimeBehavior(SL, SizeOfArg, 9044 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9045 << ActionIdx 9046 << SSR); 9047 9048 break; 9049 } 9050 } 9051 9052 // Also check for cases where the sizeof argument is the exact same 9053 // type as the memory argument, and where it points to a user-defined 9054 // record type. 9055 if (SizeOfArgTy != QualType()) { 9056 if (PointeeTy->isRecordType() && 9057 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9058 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9059 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9060 << FnName << SizeOfArgTy << ArgIdx 9061 << PointeeTy << Dest->getSourceRange() 9062 << LenExpr->getSourceRange()); 9063 break; 9064 } 9065 } 9066 } else if (DestTy->isArrayType()) { 9067 PointeeTy = DestTy; 9068 } 9069 9070 if (PointeeTy == QualType()) 9071 continue; 9072 9073 // Always complain about dynamic classes. 9074 bool IsContained; 9075 if (const CXXRecordDecl *ContainedRD = 9076 getContainedDynamicClass(PointeeTy, IsContained)) { 9077 9078 unsigned OperationType = 0; 9079 // "overwritten" if we're warning about the destination for any call 9080 // but memcmp; otherwise a verb appropriate to the call. 9081 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 9082 if (BId == Builtin::BImemcpy) 9083 OperationType = 1; 9084 else if(BId == Builtin::BImemmove) 9085 OperationType = 2; 9086 else if (BId == Builtin::BImemcmp) 9087 OperationType = 3; 9088 } 9089 9090 DiagRuntimeBehavior( 9091 Dest->getExprLoc(), Dest, 9092 PDiag(diag::warn_dyn_class_memaccess) 9093 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 9094 << FnName << IsContained << ContainedRD << OperationType 9095 << Call->getCallee()->getSourceRange()); 9096 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9097 BId != Builtin::BImemset) 9098 DiagRuntimeBehavior( 9099 Dest->getExprLoc(), Dest, 9100 PDiag(diag::warn_arc_object_memaccess) 9101 << ArgIdx << FnName << PointeeTy 9102 << Call->getCallee()->getSourceRange()); 9103 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9104 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9105 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9106 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9107 PDiag(diag::warn_cstruct_memaccess) 9108 << ArgIdx << FnName << PointeeTy << 0); 9109 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9110 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9111 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9112 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9113 PDiag(diag::warn_cstruct_memaccess) 9114 << ArgIdx << FnName << PointeeTy << 1); 9115 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9116 } else { 9117 continue; 9118 } 9119 } else 9120 continue; 9121 9122 DiagRuntimeBehavior( 9123 Dest->getExprLoc(), Dest, 9124 PDiag(diag::note_bad_memaccess_silence) 9125 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9126 break; 9127 } 9128 } 9129 9130 // A little helper routine: ignore addition and subtraction of integer literals. 9131 // This intentionally does not ignore all integer constant expressions because 9132 // we don't want to remove sizeof(). 9133 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9134 Ex = Ex->IgnoreParenCasts(); 9135 9136 while (true) { 9137 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9138 if (!BO || !BO->isAdditiveOp()) 9139 break; 9140 9141 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9142 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9143 9144 if (isa<IntegerLiteral>(RHS)) 9145 Ex = LHS; 9146 else if (isa<IntegerLiteral>(LHS)) 9147 Ex = RHS; 9148 else 9149 break; 9150 } 9151 9152 return Ex; 9153 } 9154 9155 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9156 ASTContext &Context) { 9157 // Only handle constant-sized or VLAs, but not flexible members. 9158 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9159 // Only issue the FIXIT for arrays of size > 1. 9160 if (CAT->getSize().getSExtValue() <= 1) 9161 return false; 9162 } else if (!Ty->isVariableArrayType()) { 9163 return false; 9164 } 9165 return true; 9166 } 9167 9168 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9169 // be the size of the source, instead of the destination. 9170 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9171 IdentifierInfo *FnName) { 9172 9173 // Don't crash if the user has the wrong number of arguments 9174 unsigned NumArgs = Call->getNumArgs(); 9175 if ((NumArgs != 3) && (NumArgs != 4)) 9176 return; 9177 9178 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9179 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9180 const Expr *CompareWithSrc = nullptr; 9181 9182 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9183 Call->getBeginLoc(), Call->getRParenLoc())) 9184 return; 9185 9186 // Look for 'strlcpy(dst, x, sizeof(x))' 9187 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9188 CompareWithSrc = Ex; 9189 else { 9190 // Look for 'strlcpy(dst, x, strlen(x))' 9191 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9192 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9193 SizeCall->getNumArgs() == 1) 9194 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9195 } 9196 } 9197 9198 if (!CompareWithSrc) 9199 return; 9200 9201 // Determine if the argument to sizeof/strlen is equal to the source 9202 // argument. In principle there's all kinds of things you could do 9203 // here, for instance creating an == expression and evaluating it with 9204 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9205 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9206 if (!SrcArgDRE) 9207 return; 9208 9209 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9210 if (!CompareWithSrcDRE || 9211 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9212 return; 9213 9214 const Expr *OriginalSizeArg = Call->getArg(2); 9215 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9216 << OriginalSizeArg->getSourceRange() << FnName; 9217 9218 // Output a FIXIT hint if the destination is an array (rather than a 9219 // pointer to an array). This could be enhanced to handle some 9220 // pointers if we know the actual size, like if DstArg is 'array+2' 9221 // we could say 'sizeof(array)-2'. 9222 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9223 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9224 return; 9225 9226 SmallString<128> sizeString; 9227 llvm::raw_svector_ostream OS(sizeString); 9228 OS << "sizeof("; 9229 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9230 OS << ")"; 9231 9232 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9233 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9234 OS.str()); 9235 } 9236 9237 /// Check if two expressions refer to the same declaration. 9238 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9239 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9240 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9241 return D1->getDecl() == D2->getDecl(); 9242 return false; 9243 } 9244 9245 static const Expr *getStrlenExprArg(const Expr *E) { 9246 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9247 const FunctionDecl *FD = CE->getDirectCallee(); 9248 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9249 return nullptr; 9250 return CE->getArg(0)->IgnoreParenCasts(); 9251 } 9252 return nullptr; 9253 } 9254 9255 // Warn on anti-patterns as the 'size' argument to strncat. 9256 // The correct size argument should look like following: 9257 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9258 void Sema::CheckStrncatArguments(const CallExpr *CE, 9259 IdentifierInfo *FnName) { 9260 // Don't crash if the user has the wrong number of arguments. 9261 if (CE->getNumArgs() < 3) 9262 return; 9263 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9264 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9265 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9266 9267 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9268 CE->getRParenLoc())) 9269 return; 9270 9271 // Identify common expressions, which are wrongly used as the size argument 9272 // to strncat and may lead to buffer overflows. 9273 unsigned PatternType = 0; 9274 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9275 // - sizeof(dst) 9276 if (referToTheSameDecl(SizeOfArg, DstArg)) 9277 PatternType = 1; 9278 // - sizeof(src) 9279 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9280 PatternType = 2; 9281 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9282 if (BE->getOpcode() == BO_Sub) { 9283 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9284 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9285 // - sizeof(dst) - strlen(dst) 9286 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9287 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9288 PatternType = 1; 9289 // - sizeof(src) - (anything) 9290 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9291 PatternType = 2; 9292 } 9293 } 9294 9295 if (PatternType == 0) 9296 return; 9297 9298 // Generate the diagnostic. 9299 SourceLocation SL = LenArg->getBeginLoc(); 9300 SourceRange SR = LenArg->getSourceRange(); 9301 SourceManager &SM = getSourceManager(); 9302 9303 // If the function is defined as a builtin macro, do not show macro expansion. 9304 if (SM.isMacroArgExpansion(SL)) { 9305 SL = SM.getSpellingLoc(SL); 9306 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9307 SM.getSpellingLoc(SR.getEnd())); 9308 } 9309 9310 // Check if the destination is an array (rather than a pointer to an array). 9311 QualType DstTy = DstArg->getType(); 9312 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9313 Context); 9314 if (!isKnownSizeArray) { 9315 if (PatternType == 1) 9316 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9317 else 9318 Diag(SL, diag::warn_strncat_src_size) << SR; 9319 return; 9320 } 9321 9322 if (PatternType == 1) 9323 Diag(SL, diag::warn_strncat_large_size) << SR; 9324 else 9325 Diag(SL, diag::warn_strncat_src_size) << SR; 9326 9327 SmallString<128> sizeString; 9328 llvm::raw_svector_ostream OS(sizeString); 9329 OS << "sizeof("; 9330 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9331 OS << ") - "; 9332 OS << "strlen("; 9333 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9334 OS << ") - 1"; 9335 9336 Diag(SL, diag::note_strncat_wrong_size) 9337 << FixItHint::CreateReplacement(SR, OS.str()); 9338 } 9339 9340 void 9341 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9342 SourceLocation ReturnLoc, 9343 bool isObjCMethod, 9344 const AttrVec *Attrs, 9345 const FunctionDecl *FD) { 9346 // Check if the return value is null but should not be. 9347 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9348 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9349 CheckNonNullExpr(*this, RetValExp)) 9350 Diag(ReturnLoc, diag::warn_null_ret) 9351 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9352 9353 // C++11 [basic.stc.dynamic.allocation]p4: 9354 // If an allocation function declared with a non-throwing 9355 // exception-specification fails to allocate storage, it shall return 9356 // a null pointer. Any other allocation function that fails to allocate 9357 // storage shall indicate failure only by throwing an exception [...] 9358 if (FD) { 9359 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9360 if (Op == OO_New || Op == OO_Array_New) { 9361 const FunctionProtoType *Proto 9362 = FD->getType()->castAs<FunctionProtoType>(); 9363 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9364 CheckNonNullExpr(*this, RetValExp)) 9365 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9366 << FD << getLangOpts().CPlusPlus11; 9367 } 9368 } 9369 } 9370 9371 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9372 9373 /// Check for comparisons of floating point operands using != and ==. 9374 /// Issue a warning if these are no self-comparisons, as they are not likely 9375 /// to do what the programmer intended. 9376 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9377 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9378 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9379 9380 // Special case: check for x == x (which is OK). 9381 // Do not emit warnings for such cases. 9382 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9383 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9384 if (DRL->getDecl() == DRR->getDecl()) 9385 return; 9386 9387 // Special case: check for comparisons against literals that can be exactly 9388 // represented by APFloat. In such cases, do not emit a warning. This 9389 // is a heuristic: often comparison against such literals are used to 9390 // detect if a value in a variable has not changed. This clearly can 9391 // lead to false negatives. 9392 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9393 if (FLL->isExact()) 9394 return; 9395 } else 9396 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9397 if (FLR->isExact()) 9398 return; 9399 9400 // Check for comparisons with builtin types. 9401 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9402 if (CL->getBuiltinCallee()) 9403 return; 9404 9405 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9406 if (CR->getBuiltinCallee()) 9407 return; 9408 9409 // Emit the diagnostic. 9410 Diag(Loc, diag::warn_floatingpoint_eq) 9411 << LHS->getSourceRange() << RHS->getSourceRange(); 9412 } 9413 9414 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9415 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9416 9417 namespace { 9418 9419 /// Structure recording the 'active' range of an integer-valued 9420 /// expression. 9421 struct IntRange { 9422 /// The number of bits active in the int. 9423 unsigned Width; 9424 9425 /// True if the int is known not to have negative values. 9426 bool NonNegative; 9427 9428 IntRange(unsigned Width, bool NonNegative) 9429 : Width(Width), NonNegative(NonNegative) {} 9430 9431 /// Returns the range of the bool type. 9432 static IntRange forBoolType() { 9433 return IntRange(1, true); 9434 } 9435 9436 /// Returns the range of an opaque value of the given integral type. 9437 static IntRange forValueOfType(ASTContext &C, QualType T) { 9438 return forValueOfCanonicalType(C, 9439 T->getCanonicalTypeInternal().getTypePtr()); 9440 } 9441 9442 /// Returns the range of an opaque value of a canonical integral type. 9443 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9444 assert(T->isCanonicalUnqualified()); 9445 9446 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9447 T = VT->getElementType().getTypePtr(); 9448 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9449 T = CT->getElementType().getTypePtr(); 9450 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9451 T = AT->getValueType().getTypePtr(); 9452 9453 if (!C.getLangOpts().CPlusPlus) { 9454 // For enum types in C code, use the underlying datatype. 9455 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9456 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9457 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9458 // For enum types in C++, use the known bit width of the enumerators. 9459 EnumDecl *Enum = ET->getDecl(); 9460 // In C++11, enums can have a fixed underlying type. Use this type to 9461 // compute the range. 9462 if (Enum->isFixed()) { 9463 return IntRange(C.getIntWidth(QualType(T, 0)), 9464 !ET->isSignedIntegerOrEnumerationType()); 9465 } 9466 9467 unsigned NumPositive = Enum->getNumPositiveBits(); 9468 unsigned NumNegative = Enum->getNumNegativeBits(); 9469 9470 if (NumNegative == 0) 9471 return IntRange(NumPositive, true/*NonNegative*/); 9472 else 9473 return IntRange(std::max(NumPositive + 1, NumNegative), 9474 false/*NonNegative*/); 9475 } 9476 9477 const BuiltinType *BT = cast<BuiltinType>(T); 9478 assert(BT->isInteger()); 9479 9480 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9481 } 9482 9483 /// Returns the "target" range of a canonical integral type, i.e. 9484 /// the range of values expressible in the type. 9485 /// 9486 /// This matches forValueOfCanonicalType except that enums have the 9487 /// full range of their type, not the range of their enumerators. 9488 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9489 assert(T->isCanonicalUnqualified()); 9490 9491 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9492 T = VT->getElementType().getTypePtr(); 9493 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9494 T = CT->getElementType().getTypePtr(); 9495 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9496 T = AT->getValueType().getTypePtr(); 9497 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9498 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9499 9500 const BuiltinType *BT = cast<BuiltinType>(T); 9501 assert(BT->isInteger()); 9502 9503 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9504 } 9505 9506 /// Returns the supremum of two ranges: i.e. their conservative merge. 9507 static IntRange join(IntRange L, IntRange R) { 9508 return IntRange(std::max(L.Width, R.Width), 9509 L.NonNegative && R.NonNegative); 9510 } 9511 9512 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9513 static IntRange meet(IntRange L, IntRange R) { 9514 return IntRange(std::min(L.Width, R.Width), 9515 L.NonNegative || R.NonNegative); 9516 } 9517 }; 9518 9519 } // namespace 9520 9521 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9522 unsigned MaxWidth) { 9523 if (value.isSigned() && value.isNegative()) 9524 return IntRange(value.getMinSignedBits(), false); 9525 9526 if (value.getBitWidth() > MaxWidth) 9527 value = value.trunc(MaxWidth); 9528 9529 // isNonNegative() just checks the sign bit without considering 9530 // signedness. 9531 return IntRange(value.getActiveBits(), true); 9532 } 9533 9534 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9535 unsigned MaxWidth) { 9536 if (result.isInt()) 9537 return GetValueRange(C, result.getInt(), MaxWidth); 9538 9539 if (result.isVector()) { 9540 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9541 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9542 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9543 R = IntRange::join(R, El); 9544 } 9545 return R; 9546 } 9547 9548 if (result.isComplexInt()) { 9549 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9550 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9551 return IntRange::join(R, I); 9552 } 9553 9554 // This can happen with lossless casts to intptr_t of "based" lvalues. 9555 // Assume it might use arbitrary bits. 9556 // FIXME: The only reason we need to pass the type in here is to get 9557 // the sign right on this one case. It would be nice if APValue 9558 // preserved this. 9559 assert(result.isLValue() || result.isAddrLabelDiff()); 9560 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9561 } 9562 9563 static QualType GetExprType(const Expr *E) { 9564 QualType Ty = E->getType(); 9565 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9566 Ty = AtomicRHS->getValueType(); 9567 return Ty; 9568 } 9569 9570 /// Pseudo-evaluate the given integer expression, estimating the 9571 /// range of values it might take. 9572 /// 9573 /// \param MaxWidth - the width to which the value will be truncated 9574 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 9575 E = E->IgnoreParens(); 9576 9577 // Try a full evaluation first. 9578 Expr::EvalResult result; 9579 if (E->EvaluateAsRValue(result, C)) 9580 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9581 9582 // I think we only want to look through implicit casts here; if the 9583 // user has an explicit widening cast, we should treat the value as 9584 // being of the new, wider type. 9585 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9586 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9587 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 9588 9589 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9590 9591 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9592 CE->getCastKind() == CK_BooleanToSignedIntegral; 9593 9594 // Assume that non-integer casts can span the full range of the type. 9595 if (!isIntegerCast) 9596 return OutputTypeRange; 9597 9598 IntRange SubRange 9599 = GetExprRange(C, CE->getSubExpr(), 9600 std::min(MaxWidth, OutputTypeRange.Width)); 9601 9602 // Bail out if the subexpr's range is as wide as the cast type. 9603 if (SubRange.Width >= OutputTypeRange.Width) 9604 return OutputTypeRange; 9605 9606 // Otherwise, we take the smaller width, and we're non-negative if 9607 // either the output type or the subexpr is. 9608 return IntRange(SubRange.Width, 9609 SubRange.NonNegative || OutputTypeRange.NonNegative); 9610 } 9611 9612 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9613 // If we can fold the condition, just take that operand. 9614 bool CondResult; 9615 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9616 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9617 : CO->getFalseExpr(), 9618 MaxWidth); 9619 9620 // Otherwise, conservatively merge. 9621 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9622 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9623 return IntRange::join(L, R); 9624 } 9625 9626 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9627 switch (BO->getOpcode()) { 9628 case BO_Cmp: 9629 llvm_unreachable("builtin <=> should have class type"); 9630 9631 // Boolean-valued operations are single-bit and positive. 9632 case BO_LAnd: 9633 case BO_LOr: 9634 case BO_LT: 9635 case BO_GT: 9636 case BO_LE: 9637 case BO_GE: 9638 case BO_EQ: 9639 case BO_NE: 9640 return IntRange::forBoolType(); 9641 9642 // The type of the assignments is the type of the LHS, so the RHS 9643 // is not necessarily the same type. 9644 case BO_MulAssign: 9645 case BO_DivAssign: 9646 case BO_RemAssign: 9647 case BO_AddAssign: 9648 case BO_SubAssign: 9649 case BO_XorAssign: 9650 case BO_OrAssign: 9651 // TODO: bitfields? 9652 return IntRange::forValueOfType(C, GetExprType(E)); 9653 9654 // Simple assignments just pass through the RHS, which will have 9655 // been coerced to the LHS type. 9656 case BO_Assign: 9657 // TODO: bitfields? 9658 return GetExprRange(C, BO->getRHS(), MaxWidth); 9659 9660 // Operations with opaque sources are black-listed. 9661 case BO_PtrMemD: 9662 case BO_PtrMemI: 9663 return IntRange::forValueOfType(C, GetExprType(E)); 9664 9665 // Bitwise-and uses the *infinum* of the two source ranges. 9666 case BO_And: 9667 case BO_AndAssign: 9668 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9669 GetExprRange(C, BO->getRHS(), MaxWidth)); 9670 9671 // Left shift gets black-listed based on a judgement call. 9672 case BO_Shl: 9673 // ...except that we want to treat '1 << (blah)' as logically 9674 // positive. It's an important idiom. 9675 if (IntegerLiteral *I 9676 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9677 if (I->getValue() == 1) { 9678 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9679 return IntRange(R.Width, /*NonNegative*/ true); 9680 } 9681 } 9682 LLVM_FALLTHROUGH; 9683 9684 case BO_ShlAssign: 9685 return IntRange::forValueOfType(C, GetExprType(E)); 9686 9687 // Right shift by a constant can narrow its left argument. 9688 case BO_Shr: 9689 case BO_ShrAssign: { 9690 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9691 9692 // If the shift amount is a positive constant, drop the width by 9693 // that much. 9694 llvm::APSInt shift; 9695 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9696 shift.isNonNegative()) { 9697 unsigned zext = shift.getZExtValue(); 9698 if (zext >= L.Width) 9699 L.Width = (L.NonNegative ? 0 : 1); 9700 else 9701 L.Width -= zext; 9702 } 9703 9704 return L; 9705 } 9706 9707 // Comma acts as its right operand. 9708 case BO_Comma: 9709 return GetExprRange(C, BO->getRHS(), MaxWidth); 9710 9711 // Black-list pointer subtractions. 9712 case BO_Sub: 9713 if (BO->getLHS()->getType()->isPointerType()) 9714 return IntRange::forValueOfType(C, GetExprType(E)); 9715 break; 9716 9717 // The width of a division result is mostly determined by the size 9718 // of the LHS. 9719 case BO_Div: { 9720 // Don't 'pre-truncate' the operands. 9721 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9722 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9723 9724 // If the divisor is constant, use that. 9725 llvm::APSInt divisor; 9726 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9727 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9728 if (log2 >= L.Width) 9729 L.Width = (L.NonNegative ? 0 : 1); 9730 else 9731 L.Width = std::min(L.Width - log2, MaxWidth); 9732 return L; 9733 } 9734 9735 // Otherwise, just use the LHS's width. 9736 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9737 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9738 } 9739 9740 // The result of a remainder can't be larger than the result of 9741 // either side. 9742 case BO_Rem: { 9743 // Don't 'pre-truncate' the operands. 9744 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9745 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9746 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9747 9748 IntRange meet = IntRange::meet(L, R); 9749 meet.Width = std::min(meet.Width, MaxWidth); 9750 return meet; 9751 } 9752 9753 // The default behavior is okay for these. 9754 case BO_Mul: 9755 case BO_Add: 9756 case BO_Xor: 9757 case BO_Or: 9758 break; 9759 } 9760 9761 // The default case is to treat the operation as if it were closed 9762 // on the narrowest type that encompasses both operands. 9763 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9764 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9765 return IntRange::join(L, R); 9766 } 9767 9768 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9769 switch (UO->getOpcode()) { 9770 // Boolean-valued operations are white-listed. 9771 case UO_LNot: 9772 return IntRange::forBoolType(); 9773 9774 // Operations with opaque sources are black-listed. 9775 case UO_Deref: 9776 case UO_AddrOf: // should be impossible 9777 return IntRange::forValueOfType(C, GetExprType(E)); 9778 9779 default: 9780 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9781 } 9782 } 9783 9784 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9785 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9786 9787 if (const auto *BitField = E->getSourceBitField()) 9788 return IntRange(BitField->getBitWidthValue(C), 9789 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9790 9791 return IntRange::forValueOfType(C, GetExprType(E)); 9792 } 9793 9794 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9795 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9796 } 9797 9798 /// Checks whether the given value, which currently has the given 9799 /// source semantics, has the same value when coerced through the 9800 /// target semantics. 9801 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9802 const llvm::fltSemantics &Src, 9803 const llvm::fltSemantics &Tgt) { 9804 llvm::APFloat truncated = value; 9805 9806 bool ignored; 9807 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9808 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9809 9810 return truncated.bitwiseIsEqual(value); 9811 } 9812 9813 /// Checks whether the given value, which currently has the given 9814 /// source semantics, has the same value when coerced through the 9815 /// target semantics. 9816 /// 9817 /// The value might be a vector of floats (or a complex number). 9818 static bool IsSameFloatAfterCast(const APValue &value, 9819 const llvm::fltSemantics &Src, 9820 const llvm::fltSemantics &Tgt) { 9821 if (value.isFloat()) 9822 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9823 9824 if (value.isVector()) { 9825 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9826 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9827 return false; 9828 return true; 9829 } 9830 9831 assert(value.isComplexFloat()); 9832 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9833 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9834 } 9835 9836 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9837 9838 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9839 // Suppress cases where we are comparing against an enum constant. 9840 if (const DeclRefExpr *DR = 9841 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9842 if (isa<EnumConstantDecl>(DR->getDecl())) 9843 return true; 9844 9845 // Suppress cases where the '0' value is expanded from a macro. 9846 if (E->getBeginLoc().isMacroID()) 9847 return true; 9848 9849 return false; 9850 } 9851 9852 static bool isKnownToHaveUnsignedValue(Expr *E) { 9853 return E->getType()->isIntegerType() && 9854 (!E->getType()->isSignedIntegerType() || 9855 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9856 } 9857 9858 namespace { 9859 /// The promoted range of values of a type. In general this has the 9860 /// following structure: 9861 /// 9862 /// |-----------| . . . |-----------| 9863 /// ^ ^ ^ ^ 9864 /// Min HoleMin HoleMax Max 9865 /// 9866 /// ... where there is only a hole if a signed type is promoted to unsigned 9867 /// (in which case Min and Max are the smallest and largest representable 9868 /// values). 9869 struct PromotedRange { 9870 // Min, or HoleMax if there is a hole. 9871 llvm::APSInt PromotedMin; 9872 // Max, or HoleMin if there is a hole. 9873 llvm::APSInt PromotedMax; 9874 9875 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9876 if (R.Width == 0) 9877 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9878 else if (R.Width >= BitWidth && !Unsigned) { 9879 // Promotion made the type *narrower*. This happens when promoting 9880 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9881 // Treat all values of 'signed int' as being in range for now. 9882 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9883 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9884 } else { 9885 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9886 .extOrTrunc(BitWidth); 9887 PromotedMin.setIsUnsigned(Unsigned); 9888 9889 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9890 .extOrTrunc(BitWidth); 9891 PromotedMax.setIsUnsigned(Unsigned); 9892 } 9893 } 9894 9895 // Determine whether this range is contiguous (has no hole). 9896 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9897 9898 // Where a constant value is within the range. 9899 enum ComparisonResult { 9900 LT = 0x1, 9901 LE = 0x2, 9902 GT = 0x4, 9903 GE = 0x8, 9904 EQ = 0x10, 9905 NE = 0x20, 9906 InRangeFlag = 0x40, 9907 9908 Less = LE | LT | NE, 9909 Min = LE | InRangeFlag, 9910 InRange = InRangeFlag, 9911 Max = GE | InRangeFlag, 9912 Greater = GE | GT | NE, 9913 9914 OnlyValue = LE | GE | EQ | InRangeFlag, 9915 InHole = NE 9916 }; 9917 9918 ComparisonResult compare(const llvm::APSInt &Value) const { 9919 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 9920 Value.isUnsigned() == PromotedMin.isUnsigned()); 9921 if (!isContiguous()) { 9922 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 9923 if (Value.isMinValue()) return Min; 9924 if (Value.isMaxValue()) return Max; 9925 if (Value >= PromotedMin) return InRange; 9926 if (Value <= PromotedMax) return InRange; 9927 return InHole; 9928 } 9929 9930 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 9931 case -1: return Less; 9932 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 9933 case 1: 9934 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 9935 case -1: return InRange; 9936 case 0: return Max; 9937 case 1: return Greater; 9938 } 9939 } 9940 9941 llvm_unreachable("impossible compare result"); 9942 } 9943 9944 static llvm::Optional<StringRef> 9945 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 9946 if (Op == BO_Cmp) { 9947 ComparisonResult LTFlag = LT, GTFlag = GT; 9948 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 9949 9950 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 9951 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 9952 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 9953 return llvm::None; 9954 } 9955 9956 ComparisonResult TrueFlag, FalseFlag; 9957 if (Op == BO_EQ) { 9958 TrueFlag = EQ; 9959 FalseFlag = NE; 9960 } else if (Op == BO_NE) { 9961 TrueFlag = NE; 9962 FalseFlag = EQ; 9963 } else { 9964 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 9965 TrueFlag = LT; 9966 FalseFlag = GE; 9967 } else { 9968 TrueFlag = GT; 9969 FalseFlag = LE; 9970 } 9971 if (Op == BO_GE || Op == BO_LE) 9972 std::swap(TrueFlag, FalseFlag); 9973 } 9974 if (R & TrueFlag) 9975 return StringRef("true"); 9976 if (R & FalseFlag) 9977 return StringRef("false"); 9978 return llvm::None; 9979 } 9980 }; 9981 } 9982 9983 static bool HasEnumType(Expr *E) { 9984 // Strip off implicit integral promotions. 9985 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9986 if (ICE->getCastKind() != CK_IntegralCast && 9987 ICE->getCastKind() != CK_NoOp) 9988 break; 9989 E = ICE->getSubExpr(); 9990 } 9991 9992 return E->getType()->isEnumeralType(); 9993 } 9994 9995 static int classifyConstantValue(Expr *Constant) { 9996 // The values of this enumeration are used in the diagnostics 9997 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 9998 enum ConstantValueKind { 9999 Miscellaneous = 0, 10000 LiteralTrue, 10001 LiteralFalse 10002 }; 10003 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10004 return BL->getValue() ? ConstantValueKind::LiteralTrue 10005 : ConstantValueKind::LiteralFalse; 10006 return ConstantValueKind::Miscellaneous; 10007 } 10008 10009 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10010 Expr *Constant, Expr *Other, 10011 const llvm::APSInt &Value, 10012 bool RhsConstant) { 10013 if (S.inTemplateInstantiation()) 10014 return false; 10015 10016 Expr *OriginalOther = Other; 10017 10018 Constant = Constant->IgnoreParenImpCasts(); 10019 Other = Other->IgnoreParenImpCasts(); 10020 10021 // Suppress warnings on tautological comparisons between values of the same 10022 // enumeration type. There are only two ways we could warn on this: 10023 // - If the constant is outside the range of representable values of 10024 // the enumeration. In such a case, we should warn about the cast 10025 // to enumeration type, not about the comparison. 10026 // - If the constant is the maximum / minimum in-range value. For an 10027 // enumeratin type, such comparisons can be meaningful and useful. 10028 if (Constant->getType()->isEnumeralType() && 10029 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10030 return false; 10031 10032 // TODO: Investigate using GetExprRange() to get tighter bounds 10033 // on the bit ranges. 10034 QualType OtherT = Other->getType(); 10035 if (const auto *AT = OtherT->getAs<AtomicType>()) 10036 OtherT = AT->getValueType(); 10037 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10038 10039 // Whether we're treating Other as being a bool because of the form of 10040 // expression despite it having another type (typically 'int' in C). 10041 bool OtherIsBooleanDespiteType = 10042 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10043 if (OtherIsBooleanDespiteType) 10044 OtherRange = IntRange::forBoolType(); 10045 10046 // Determine the promoted range of the other type and see if a comparison of 10047 // the constant against that range is tautological. 10048 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10049 Value.isUnsigned()); 10050 auto Cmp = OtherPromotedRange.compare(Value); 10051 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10052 if (!Result) 10053 return false; 10054 10055 // Suppress the diagnostic for an in-range comparison if the constant comes 10056 // from a macro or enumerator. We don't want to diagnose 10057 // 10058 // some_long_value <= INT_MAX 10059 // 10060 // when sizeof(int) == sizeof(long). 10061 bool InRange = Cmp & PromotedRange::InRangeFlag; 10062 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10063 return false; 10064 10065 // If this is a comparison to an enum constant, include that 10066 // constant in the diagnostic. 10067 const EnumConstantDecl *ED = nullptr; 10068 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10069 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10070 10071 // Should be enough for uint128 (39 decimal digits) 10072 SmallString<64> PrettySourceValue; 10073 llvm::raw_svector_ostream OS(PrettySourceValue); 10074 if (ED) 10075 OS << '\'' << *ED << "' (" << Value << ")"; 10076 else 10077 OS << Value; 10078 10079 // FIXME: We use a somewhat different formatting for the in-range cases and 10080 // cases involving boolean values for historical reasons. We should pick a 10081 // consistent way of presenting these diagnostics. 10082 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10083 S.DiagRuntimeBehavior( 10084 E->getOperatorLoc(), E, 10085 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10086 : diag::warn_tautological_bool_compare) 10087 << OS.str() << classifyConstantValue(Constant) 10088 << OtherT << OtherIsBooleanDespiteType << *Result 10089 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10090 } else { 10091 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10092 ? (HasEnumType(OriginalOther) 10093 ? diag::warn_unsigned_enum_always_true_comparison 10094 : diag::warn_unsigned_always_true_comparison) 10095 : diag::warn_tautological_constant_compare; 10096 10097 S.Diag(E->getOperatorLoc(), Diag) 10098 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10099 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10100 } 10101 10102 return true; 10103 } 10104 10105 /// Analyze the operands of the given comparison. Implements the 10106 /// fallback case from AnalyzeComparison. 10107 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10108 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10109 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10110 } 10111 10112 /// Implements -Wsign-compare. 10113 /// 10114 /// \param E the binary operator to check for warnings 10115 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10116 // The type the comparison is being performed in. 10117 QualType T = E->getLHS()->getType(); 10118 10119 // Only analyze comparison operators where both sides have been converted to 10120 // the same type. 10121 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10122 return AnalyzeImpConvsInComparison(S, E); 10123 10124 // Don't analyze value-dependent comparisons directly. 10125 if (E->isValueDependent()) 10126 return AnalyzeImpConvsInComparison(S, E); 10127 10128 Expr *LHS = E->getLHS(); 10129 Expr *RHS = E->getRHS(); 10130 10131 if (T->isIntegralType(S.Context)) { 10132 llvm::APSInt RHSValue; 10133 llvm::APSInt LHSValue; 10134 10135 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10136 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10137 10138 // We don't care about expressions whose result is a constant. 10139 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10140 return AnalyzeImpConvsInComparison(S, E); 10141 10142 // We only care about expressions where just one side is literal 10143 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10144 // Is the constant on the RHS or LHS? 10145 const bool RhsConstant = IsRHSIntegralLiteral; 10146 Expr *Const = RhsConstant ? RHS : LHS; 10147 Expr *Other = RhsConstant ? LHS : RHS; 10148 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10149 10150 // Check whether an integer constant comparison results in a value 10151 // of 'true' or 'false'. 10152 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10153 return AnalyzeImpConvsInComparison(S, E); 10154 } 10155 } 10156 10157 if (!T->hasUnsignedIntegerRepresentation()) { 10158 // We don't do anything special if this isn't an unsigned integral 10159 // comparison: we're only interested in integral comparisons, and 10160 // signed comparisons only happen in cases we don't care to warn about. 10161 return AnalyzeImpConvsInComparison(S, E); 10162 } 10163 10164 LHS = LHS->IgnoreParenImpCasts(); 10165 RHS = RHS->IgnoreParenImpCasts(); 10166 10167 if (!S.getLangOpts().CPlusPlus) { 10168 // Avoid warning about comparison of integers with different signs when 10169 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10170 // the type of `E`. 10171 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10172 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10173 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10174 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10175 } 10176 10177 // Check to see if one of the (unmodified) operands is of different 10178 // signedness. 10179 Expr *signedOperand, *unsignedOperand; 10180 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10181 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10182 "unsigned comparison between two signed integer expressions?"); 10183 signedOperand = LHS; 10184 unsignedOperand = RHS; 10185 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10186 signedOperand = RHS; 10187 unsignedOperand = LHS; 10188 } else { 10189 return AnalyzeImpConvsInComparison(S, E); 10190 } 10191 10192 // Otherwise, calculate the effective range of the signed operand. 10193 IntRange signedRange = GetExprRange(S.Context, signedOperand); 10194 10195 // Go ahead and analyze implicit conversions in the operands. Note 10196 // that we skip the implicit conversions on both sides. 10197 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10198 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10199 10200 // If the signed range is non-negative, -Wsign-compare won't fire. 10201 if (signedRange.NonNegative) 10202 return; 10203 10204 // For (in)equality comparisons, if the unsigned operand is a 10205 // constant which cannot collide with a overflowed signed operand, 10206 // then reinterpreting the signed operand as unsigned will not 10207 // change the result of the comparison. 10208 if (E->isEqualityOp()) { 10209 unsigned comparisonWidth = S.Context.getIntWidth(T); 10210 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 10211 10212 // We should never be unable to prove that the unsigned operand is 10213 // non-negative. 10214 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10215 10216 if (unsignedRange.Width < comparisonWidth) 10217 return; 10218 } 10219 10220 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10221 S.PDiag(diag::warn_mixed_sign_comparison) 10222 << LHS->getType() << RHS->getType() 10223 << LHS->getSourceRange() << RHS->getSourceRange()); 10224 } 10225 10226 /// Analyzes an attempt to assign the given value to a bitfield. 10227 /// 10228 /// Returns true if there was something fishy about the attempt. 10229 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10230 SourceLocation InitLoc) { 10231 assert(Bitfield->isBitField()); 10232 if (Bitfield->isInvalidDecl()) 10233 return false; 10234 10235 // White-list bool bitfields. 10236 QualType BitfieldType = Bitfield->getType(); 10237 if (BitfieldType->isBooleanType()) 10238 return false; 10239 10240 if (BitfieldType->isEnumeralType()) { 10241 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10242 // If the underlying enum type was not explicitly specified as an unsigned 10243 // type and the enum contain only positive values, MSVC++ will cause an 10244 // inconsistency by storing this as a signed type. 10245 if (S.getLangOpts().CPlusPlus11 && 10246 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10247 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10248 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10249 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10250 << BitfieldEnumDecl->getNameAsString(); 10251 } 10252 } 10253 10254 if (Bitfield->getType()->isBooleanType()) 10255 return false; 10256 10257 // Ignore value- or type-dependent expressions. 10258 if (Bitfield->getBitWidth()->isValueDependent() || 10259 Bitfield->getBitWidth()->isTypeDependent() || 10260 Init->isValueDependent() || 10261 Init->isTypeDependent()) 10262 return false; 10263 10264 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10265 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10266 10267 Expr::EvalResult Result; 10268 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10269 Expr::SE_AllowSideEffects)) { 10270 // The RHS is not constant. If the RHS has an enum type, make sure the 10271 // bitfield is wide enough to hold all the values of the enum without 10272 // truncation. 10273 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10274 EnumDecl *ED = EnumTy->getDecl(); 10275 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10276 10277 // Enum types are implicitly signed on Windows, so check if there are any 10278 // negative enumerators to see if the enum was intended to be signed or 10279 // not. 10280 bool SignedEnum = ED->getNumNegativeBits() > 0; 10281 10282 // Check for surprising sign changes when assigning enum values to a 10283 // bitfield of different signedness. If the bitfield is signed and we 10284 // have exactly the right number of bits to store this unsigned enum, 10285 // suggest changing the enum to an unsigned type. This typically happens 10286 // on Windows where unfixed enums always use an underlying type of 'int'. 10287 unsigned DiagID = 0; 10288 if (SignedEnum && !SignedBitfield) { 10289 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10290 } else if (SignedBitfield && !SignedEnum && 10291 ED->getNumPositiveBits() == FieldWidth) { 10292 DiagID = diag::warn_signed_bitfield_enum_conversion; 10293 } 10294 10295 if (DiagID) { 10296 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10297 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10298 SourceRange TypeRange = 10299 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10300 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10301 << SignedEnum << TypeRange; 10302 } 10303 10304 // Compute the required bitwidth. If the enum has negative values, we need 10305 // one more bit than the normal number of positive bits to represent the 10306 // sign bit. 10307 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10308 ED->getNumNegativeBits()) 10309 : ED->getNumPositiveBits(); 10310 10311 // Check the bitwidth. 10312 if (BitsNeeded > FieldWidth) { 10313 Expr *WidthExpr = Bitfield->getBitWidth(); 10314 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10315 << Bitfield << ED; 10316 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10317 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10318 } 10319 } 10320 10321 return false; 10322 } 10323 10324 llvm::APSInt Value = Result.Val.getInt(); 10325 10326 unsigned OriginalWidth = Value.getBitWidth(); 10327 10328 if (!Value.isSigned() || Value.isNegative()) 10329 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10330 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10331 OriginalWidth = Value.getMinSignedBits(); 10332 10333 if (OriginalWidth <= FieldWidth) 10334 return false; 10335 10336 // Compute the value which the bitfield will contain. 10337 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10338 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10339 10340 // Check whether the stored value is equal to the original value. 10341 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10342 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10343 return false; 10344 10345 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10346 // therefore don't strictly fit into a signed bitfield of width 1. 10347 if (FieldWidth == 1 && Value == 1) 10348 return false; 10349 10350 std::string PrettyValue = Value.toString(10); 10351 std::string PrettyTrunc = TruncatedValue.toString(10); 10352 10353 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10354 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10355 << Init->getSourceRange(); 10356 10357 return true; 10358 } 10359 10360 /// Analyze the given simple or compound assignment for warning-worthy 10361 /// operations. 10362 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10363 // Just recurse on the LHS. 10364 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10365 10366 // We want to recurse on the RHS as normal unless we're assigning to 10367 // a bitfield. 10368 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10369 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10370 E->getOperatorLoc())) { 10371 // Recurse, ignoring any implicit conversions on the RHS. 10372 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10373 E->getOperatorLoc()); 10374 } 10375 } 10376 10377 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10378 10379 // Diagnose implicitly sequentially-consistent atomic assignment. 10380 if (E->getLHS()->getType()->isAtomicType()) 10381 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10382 } 10383 10384 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10385 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10386 SourceLocation CContext, unsigned diag, 10387 bool pruneControlFlow = false) { 10388 if (pruneControlFlow) { 10389 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10390 S.PDiag(diag) 10391 << SourceType << T << E->getSourceRange() 10392 << SourceRange(CContext)); 10393 return; 10394 } 10395 S.Diag(E->getExprLoc(), diag) 10396 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10397 } 10398 10399 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10400 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10401 SourceLocation CContext, 10402 unsigned diag, bool pruneControlFlow = false) { 10403 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10404 } 10405 10406 /// Diagnose an implicit cast from a floating point value to an integer value. 10407 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10408 SourceLocation CContext) { 10409 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10410 const bool PruneWarnings = S.inTemplateInstantiation(); 10411 10412 Expr *InnerE = E->IgnoreParenImpCasts(); 10413 // We also want to warn on, e.g., "int i = -1.234" 10414 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10415 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10416 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10417 10418 const bool IsLiteral = 10419 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10420 10421 llvm::APFloat Value(0.0); 10422 bool IsConstant = 10423 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10424 if (!IsConstant) { 10425 return DiagnoseImpCast(S, E, T, CContext, 10426 diag::warn_impcast_float_integer, PruneWarnings); 10427 } 10428 10429 bool isExact = false; 10430 10431 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10432 T->hasUnsignedIntegerRepresentation()); 10433 llvm::APFloat::opStatus Result = Value.convertToInteger( 10434 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10435 10436 if (Result == llvm::APFloat::opOK && isExact) { 10437 if (IsLiteral) return; 10438 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10439 PruneWarnings); 10440 } 10441 10442 // Conversion of a floating-point value to a non-bool integer where the 10443 // integral part cannot be represented by the integer type is undefined. 10444 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10445 return DiagnoseImpCast( 10446 S, E, T, CContext, 10447 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10448 : diag::warn_impcast_float_to_integer_out_of_range, 10449 PruneWarnings); 10450 10451 unsigned DiagID = 0; 10452 if (IsLiteral) { 10453 // Warn on floating point literal to integer. 10454 DiagID = diag::warn_impcast_literal_float_to_integer; 10455 } else if (IntegerValue == 0) { 10456 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10457 return DiagnoseImpCast(S, E, T, CContext, 10458 diag::warn_impcast_float_integer, PruneWarnings); 10459 } 10460 // Warn on non-zero to zero conversion. 10461 DiagID = diag::warn_impcast_float_to_integer_zero; 10462 } else { 10463 if (IntegerValue.isUnsigned()) { 10464 if (!IntegerValue.isMaxValue()) { 10465 return DiagnoseImpCast(S, E, T, CContext, 10466 diag::warn_impcast_float_integer, PruneWarnings); 10467 } 10468 } else { // IntegerValue.isSigned() 10469 if (!IntegerValue.isMaxSignedValue() && 10470 !IntegerValue.isMinSignedValue()) { 10471 return DiagnoseImpCast(S, E, T, CContext, 10472 diag::warn_impcast_float_integer, PruneWarnings); 10473 } 10474 } 10475 // Warn on evaluatable floating point expression to integer conversion. 10476 DiagID = diag::warn_impcast_float_to_integer; 10477 } 10478 10479 // FIXME: Force the precision of the source value down so we don't print 10480 // digits which are usually useless (we don't really care here if we 10481 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10482 // would automatically print the shortest representation, but it's a bit 10483 // tricky to implement. 10484 SmallString<16> PrettySourceValue; 10485 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10486 precision = (precision * 59 + 195) / 196; 10487 Value.toString(PrettySourceValue, precision); 10488 10489 SmallString<16> PrettyTargetValue; 10490 if (IsBool) 10491 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10492 else 10493 IntegerValue.toString(PrettyTargetValue); 10494 10495 if (PruneWarnings) { 10496 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10497 S.PDiag(DiagID) 10498 << E->getType() << T.getUnqualifiedType() 10499 << PrettySourceValue << PrettyTargetValue 10500 << E->getSourceRange() << SourceRange(CContext)); 10501 } else { 10502 S.Diag(E->getExprLoc(), DiagID) 10503 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10504 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10505 } 10506 } 10507 10508 /// Analyze the given compound assignment for the possible losing of 10509 /// floating-point precision. 10510 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10511 assert(isa<CompoundAssignOperator>(E) && 10512 "Must be compound assignment operation"); 10513 // Recurse on the LHS and RHS in here 10514 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10515 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10516 10517 if (E->getLHS()->getType()->isAtomicType()) 10518 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10519 10520 // Now check the outermost expression 10521 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10522 const auto *RBT = cast<CompoundAssignOperator>(E) 10523 ->getComputationResultType() 10524 ->getAs<BuiltinType>(); 10525 10526 // The below checks assume source is floating point. 10527 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10528 10529 // If source is floating point but target is not. 10530 if (!ResultBT->isFloatingPoint()) 10531 return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(), 10532 E->getExprLoc()); 10533 10534 // If both source and target are floating points. 10535 // Builtin FP kinds are ordered by increasing FP rank. 10536 if (ResultBT->getKind() < RBT->getKind() && 10537 // We don't want to warn for system macro. 10538 !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10539 // warn about dropping FP rank. 10540 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10541 diag::warn_impcast_float_result_precision); 10542 } 10543 10544 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10545 IntRange Range) { 10546 if (!Range.Width) return "0"; 10547 10548 llvm::APSInt ValueInRange = Value; 10549 ValueInRange.setIsSigned(!Range.NonNegative); 10550 ValueInRange = ValueInRange.trunc(Range.Width); 10551 return ValueInRange.toString(10); 10552 } 10553 10554 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10555 if (!isa<ImplicitCastExpr>(Ex)) 10556 return false; 10557 10558 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10559 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10560 const Type *Source = 10561 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10562 if (Target->isDependentType()) 10563 return false; 10564 10565 const BuiltinType *FloatCandidateBT = 10566 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10567 const Type *BoolCandidateType = ToBool ? Target : Source; 10568 10569 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10570 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10571 } 10572 10573 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10574 SourceLocation CC) { 10575 unsigned NumArgs = TheCall->getNumArgs(); 10576 for (unsigned i = 0; i < NumArgs; ++i) { 10577 Expr *CurrA = TheCall->getArg(i); 10578 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10579 continue; 10580 10581 bool IsSwapped = ((i > 0) && 10582 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10583 IsSwapped |= ((i < (NumArgs - 1)) && 10584 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10585 if (IsSwapped) { 10586 // Warn on this floating-point to bool conversion. 10587 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10588 CurrA->getType(), CC, 10589 diag::warn_impcast_floating_point_to_bool); 10590 } 10591 } 10592 } 10593 10594 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10595 SourceLocation CC) { 10596 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10597 E->getExprLoc())) 10598 return; 10599 10600 // Don't warn on functions which have return type nullptr_t. 10601 if (isa<CallExpr>(E)) 10602 return; 10603 10604 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10605 const Expr::NullPointerConstantKind NullKind = 10606 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10607 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10608 return; 10609 10610 // Return if target type is a safe conversion. 10611 if (T->isAnyPointerType() || T->isBlockPointerType() || 10612 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10613 return; 10614 10615 SourceLocation Loc = E->getSourceRange().getBegin(); 10616 10617 // Venture through the macro stacks to get to the source of macro arguments. 10618 // The new location is a better location than the complete location that was 10619 // passed in. 10620 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10621 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10622 10623 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10624 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10625 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10626 Loc, S.SourceMgr, S.getLangOpts()); 10627 if (MacroName == "NULL") 10628 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10629 } 10630 10631 // Only warn if the null and context location are in the same macro expansion. 10632 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10633 return; 10634 10635 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10636 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10637 << FixItHint::CreateReplacement(Loc, 10638 S.getFixItZeroLiteralForType(T, Loc)); 10639 } 10640 10641 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10642 ObjCArrayLiteral *ArrayLiteral); 10643 10644 static void 10645 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10646 ObjCDictionaryLiteral *DictionaryLiteral); 10647 10648 /// Check a single element within a collection literal against the 10649 /// target element type. 10650 static void checkObjCCollectionLiteralElement(Sema &S, 10651 QualType TargetElementType, 10652 Expr *Element, 10653 unsigned ElementKind) { 10654 // Skip a bitcast to 'id' or qualified 'id'. 10655 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10656 if (ICE->getCastKind() == CK_BitCast && 10657 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10658 Element = ICE->getSubExpr(); 10659 } 10660 10661 QualType ElementType = Element->getType(); 10662 ExprResult ElementResult(Element); 10663 if (ElementType->getAs<ObjCObjectPointerType>() && 10664 S.CheckSingleAssignmentConstraints(TargetElementType, 10665 ElementResult, 10666 false, false) 10667 != Sema::Compatible) { 10668 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 10669 << ElementType << ElementKind << TargetElementType 10670 << Element->getSourceRange(); 10671 } 10672 10673 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10674 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10675 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10676 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10677 } 10678 10679 /// Check an Objective-C array literal being converted to the given 10680 /// target type. 10681 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10682 ObjCArrayLiteral *ArrayLiteral) { 10683 if (!S.NSArrayDecl) 10684 return; 10685 10686 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10687 if (!TargetObjCPtr) 10688 return; 10689 10690 if (TargetObjCPtr->isUnspecialized() || 10691 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10692 != S.NSArrayDecl->getCanonicalDecl()) 10693 return; 10694 10695 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10696 if (TypeArgs.size() != 1) 10697 return; 10698 10699 QualType TargetElementType = TypeArgs[0]; 10700 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10701 checkObjCCollectionLiteralElement(S, TargetElementType, 10702 ArrayLiteral->getElement(I), 10703 0); 10704 } 10705 } 10706 10707 /// Check an Objective-C dictionary literal being converted to the given 10708 /// target type. 10709 static void 10710 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10711 ObjCDictionaryLiteral *DictionaryLiteral) { 10712 if (!S.NSDictionaryDecl) 10713 return; 10714 10715 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10716 if (!TargetObjCPtr) 10717 return; 10718 10719 if (TargetObjCPtr->isUnspecialized() || 10720 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10721 != S.NSDictionaryDecl->getCanonicalDecl()) 10722 return; 10723 10724 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10725 if (TypeArgs.size() != 2) 10726 return; 10727 10728 QualType TargetKeyType = TypeArgs[0]; 10729 QualType TargetObjectType = TypeArgs[1]; 10730 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10731 auto Element = DictionaryLiteral->getKeyValueElement(I); 10732 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10733 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10734 } 10735 } 10736 10737 // Helper function to filter out cases for constant width constant conversion. 10738 // Don't warn on char array initialization or for non-decimal values. 10739 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10740 SourceLocation CC) { 10741 // If initializing from a constant, and the constant starts with '0', 10742 // then it is a binary, octal, or hexadecimal. Allow these constants 10743 // to fill all the bits, even if there is a sign change. 10744 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10745 const char FirstLiteralCharacter = 10746 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 10747 if (FirstLiteralCharacter == '0') 10748 return false; 10749 } 10750 10751 // If the CC location points to a '{', and the type is char, then assume 10752 // assume it is an array initialization. 10753 if (CC.isValid() && T->isCharType()) { 10754 const char FirstContextCharacter = 10755 S.getSourceManager().getCharacterData(CC)[0]; 10756 if (FirstContextCharacter == '{') 10757 return false; 10758 } 10759 10760 return true; 10761 } 10762 10763 static void 10764 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10765 bool *ICContext = nullptr) { 10766 if (E->isTypeDependent() || E->isValueDependent()) return; 10767 10768 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10769 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10770 if (Source == Target) return; 10771 if (Target->isDependentType()) return; 10772 10773 // If the conversion context location is invalid don't complain. We also 10774 // don't want to emit a warning if the issue occurs from the expansion of 10775 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10776 // delay this check as long as possible. Once we detect we are in that 10777 // scenario, we just return. 10778 if (CC.isInvalid()) 10779 return; 10780 10781 if (Source->isAtomicType()) 10782 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 10783 10784 // Diagnose implicit casts to bool. 10785 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10786 if (isa<StringLiteral>(E)) 10787 // Warn on string literal to bool. Checks for string literals in logical 10788 // and expressions, for instance, assert(0 && "error here"), are 10789 // prevented by a check in AnalyzeImplicitConversions(). 10790 return DiagnoseImpCast(S, E, T, CC, 10791 diag::warn_impcast_string_literal_to_bool); 10792 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10793 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10794 // This covers the literal expressions that evaluate to Objective-C 10795 // objects. 10796 return DiagnoseImpCast(S, E, T, CC, 10797 diag::warn_impcast_objective_c_literal_to_bool); 10798 } 10799 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10800 // Warn on pointer to bool conversion that is always true. 10801 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10802 SourceRange(CC)); 10803 } 10804 } 10805 10806 // Check implicit casts from Objective-C collection literals to specialized 10807 // collection types, e.g., NSArray<NSString *> *. 10808 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10809 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10810 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10811 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10812 10813 // Strip vector types. 10814 if (isa<VectorType>(Source)) { 10815 if (!isa<VectorType>(Target)) { 10816 if (S.SourceMgr.isInSystemMacro(CC)) 10817 return; 10818 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10819 } 10820 10821 // If the vector cast is cast between two vectors of the same size, it is 10822 // a bitcast, not a conversion. 10823 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10824 return; 10825 10826 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10827 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10828 } 10829 if (auto VecTy = dyn_cast<VectorType>(Target)) 10830 Target = VecTy->getElementType().getTypePtr(); 10831 10832 // Strip complex types. 10833 if (isa<ComplexType>(Source)) { 10834 if (!isa<ComplexType>(Target)) { 10835 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10836 return; 10837 10838 return DiagnoseImpCast(S, E, T, CC, 10839 S.getLangOpts().CPlusPlus 10840 ? diag::err_impcast_complex_scalar 10841 : diag::warn_impcast_complex_scalar); 10842 } 10843 10844 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10845 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10846 } 10847 10848 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10849 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10850 10851 // If the source is floating point... 10852 if (SourceBT && SourceBT->isFloatingPoint()) { 10853 // ...and the target is floating point... 10854 if (TargetBT && TargetBT->isFloatingPoint()) { 10855 // ...then warn if we're dropping FP rank. 10856 10857 // Builtin FP kinds are ordered by increasing FP rank. 10858 if (SourceBT->getKind() > TargetBT->getKind()) { 10859 // Don't warn about float constants that are precisely 10860 // representable in the target type. 10861 Expr::EvalResult result; 10862 if (E->EvaluateAsRValue(result, S.Context)) { 10863 // Value might be a float, a float vector, or a float complex. 10864 if (IsSameFloatAfterCast(result.Val, 10865 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10866 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10867 return; 10868 } 10869 10870 if (S.SourceMgr.isInSystemMacro(CC)) 10871 return; 10872 10873 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10874 } 10875 // ... or possibly if we're increasing rank, too 10876 else if (TargetBT->getKind() > SourceBT->getKind()) { 10877 if (S.SourceMgr.isInSystemMacro(CC)) 10878 return; 10879 10880 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10881 } 10882 return; 10883 } 10884 10885 // If the target is integral, always warn. 10886 if (TargetBT && TargetBT->isInteger()) { 10887 if (S.SourceMgr.isInSystemMacro(CC)) 10888 return; 10889 10890 DiagnoseFloatingImpCast(S, E, T, CC); 10891 } 10892 10893 // Detect the case where a call result is converted from floating-point to 10894 // to bool, and the final argument to the call is converted from bool, to 10895 // discover this typo: 10896 // 10897 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10898 // 10899 // FIXME: This is an incredibly special case; is there some more general 10900 // way to detect this class of misplaced-parentheses bug? 10901 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10902 // Check last argument of function call to see if it is an 10903 // implicit cast from a type matching the type the result 10904 // is being cast to. 10905 CallExpr *CEx = cast<CallExpr>(E); 10906 if (unsigned NumArgs = CEx->getNumArgs()) { 10907 Expr *LastA = CEx->getArg(NumArgs - 1); 10908 Expr *InnerE = LastA->IgnoreParenImpCasts(); 10909 if (isa<ImplicitCastExpr>(LastA) && 10910 InnerE->getType()->isBooleanType()) { 10911 // Warn on this floating-point to bool conversion 10912 DiagnoseImpCast(S, E, T, CC, 10913 diag::warn_impcast_floating_point_to_bool); 10914 } 10915 } 10916 } 10917 return; 10918 } 10919 10920 DiagnoseNullConversion(S, E, T, CC); 10921 10922 S.DiscardMisalignedMemberAddress(Target, E); 10923 10924 if (!Source->isIntegerType() || !Target->isIntegerType()) 10925 return; 10926 10927 // TODO: remove this early return once the false positives for constant->bool 10928 // in templates, macros, etc, are reduced or removed. 10929 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 10930 return; 10931 10932 IntRange SourceRange = GetExprRange(S.Context, E); 10933 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 10934 10935 if (SourceRange.Width > TargetRange.Width) { 10936 // If the source is a constant, use a default-on diagnostic. 10937 // TODO: this should happen for bitfield stores, too. 10938 Expr::EvalResult Result; 10939 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 10940 llvm::APSInt Value(32); 10941 Value = Result.Val.getInt(); 10942 10943 if (S.SourceMgr.isInSystemMacro(CC)) 10944 return; 10945 10946 std::string PrettySourceValue = Value.toString(10); 10947 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10948 10949 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10950 S.PDiag(diag::warn_impcast_integer_precision_constant) 10951 << PrettySourceValue << PrettyTargetValue 10952 << E->getType() << T << E->getSourceRange() 10953 << clang::SourceRange(CC)); 10954 return; 10955 } 10956 10957 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 10958 if (S.SourceMgr.isInSystemMacro(CC)) 10959 return; 10960 10961 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 10962 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 10963 /* pruneControlFlow */ true); 10964 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 10965 } 10966 10967 if (TargetRange.Width > SourceRange.Width) { 10968 if (auto *UO = dyn_cast<UnaryOperator>(E)) 10969 if (UO->getOpcode() == UO_Minus) 10970 if (Source->isUnsignedIntegerType()) { 10971 if (Target->isUnsignedIntegerType()) 10972 return DiagnoseImpCast(S, E, T, CC, 10973 diag::warn_impcast_high_order_zero_bits); 10974 if (Target->isSignedIntegerType()) 10975 return DiagnoseImpCast(S, E, T, CC, 10976 diag::warn_impcast_nonnegative_result); 10977 } 10978 } 10979 10980 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 10981 SourceRange.NonNegative && Source->isSignedIntegerType()) { 10982 // Warn when doing a signed to signed conversion, warn if the positive 10983 // source value is exactly the width of the target type, which will 10984 // cause a negative value to be stored. 10985 10986 Expr::EvalResult Result; 10987 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 10988 !S.SourceMgr.isInSystemMacro(CC)) { 10989 llvm::APSInt Value = Result.Val.getInt(); 10990 if (isSameWidthConstantConversion(S, E, T, CC)) { 10991 std::string PrettySourceValue = Value.toString(10); 10992 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10993 10994 S.DiagRuntimeBehavior( 10995 E->getExprLoc(), E, 10996 S.PDiag(diag::warn_impcast_integer_precision_constant) 10997 << PrettySourceValue << PrettyTargetValue << E->getType() << T 10998 << E->getSourceRange() << clang::SourceRange(CC)); 10999 return; 11000 } 11001 } 11002 11003 // Fall through for non-constants to give a sign conversion warning. 11004 } 11005 11006 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11007 (!TargetRange.NonNegative && SourceRange.NonNegative && 11008 SourceRange.Width == TargetRange.Width)) { 11009 if (S.SourceMgr.isInSystemMacro(CC)) 11010 return; 11011 11012 unsigned DiagID = diag::warn_impcast_integer_sign; 11013 11014 // Traditionally, gcc has warned about this under -Wsign-compare. 11015 // We also want to warn about it in -Wconversion. 11016 // So if -Wconversion is off, use a completely identical diagnostic 11017 // in the sign-compare group. 11018 // The conditional-checking code will 11019 if (ICContext) { 11020 DiagID = diag::warn_impcast_integer_sign_conditional; 11021 *ICContext = true; 11022 } 11023 11024 return DiagnoseImpCast(S, E, T, CC, DiagID); 11025 } 11026 11027 // Diagnose conversions between different enumeration types. 11028 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11029 // type, to give us better diagnostics. 11030 QualType SourceType = E->getType(); 11031 if (!S.getLangOpts().CPlusPlus) { 11032 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11033 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11034 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11035 SourceType = S.Context.getTypeDeclType(Enum); 11036 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11037 } 11038 } 11039 11040 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11041 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11042 if (SourceEnum->getDecl()->hasNameForLinkage() && 11043 TargetEnum->getDecl()->hasNameForLinkage() && 11044 SourceEnum != TargetEnum) { 11045 if (S.SourceMgr.isInSystemMacro(CC)) 11046 return; 11047 11048 return DiagnoseImpCast(S, E, SourceType, T, CC, 11049 diag::warn_impcast_different_enum_types); 11050 } 11051 } 11052 11053 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11054 SourceLocation CC, QualType T); 11055 11056 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11057 SourceLocation CC, bool &ICContext) { 11058 E = E->IgnoreParenImpCasts(); 11059 11060 if (isa<ConditionalOperator>(E)) 11061 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11062 11063 AnalyzeImplicitConversions(S, E, CC); 11064 if (E->getType() != T) 11065 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11066 } 11067 11068 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11069 SourceLocation CC, QualType T) { 11070 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11071 11072 bool Suspicious = false; 11073 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11074 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11075 11076 // If -Wconversion would have warned about either of the candidates 11077 // for a signedness conversion to the context type... 11078 if (!Suspicious) return; 11079 11080 // ...but it's currently ignored... 11081 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11082 return; 11083 11084 // ...then check whether it would have warned about either of the 11085 // candidates for a signedness conversion to the condition type. 11086 if (E->getType() == T) return; 11087 11088 Suspicious = false; 11089 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11090 E->getType(), CC, &Suspicious); 11091 if (!Suspicious) 11092 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11093 E->getType(), CC, &Suspicious); 11094 } 11095 11096 /// Check conversion of given expression to boolean. 11097 /// Input argument E is a logical expression. 11098 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11099 if (S.getLangOpts().Bool) 11100 return; 11101 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11102 return; 11103 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11104 } 11105 11106 /// AnalyzeImplicitConversions - Find and report any interesting 11107 /// implicit conversions in the given expression. There are a couple 11108 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11109 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 11110 SourceLocation CC) { 11111 QualType T = OrigE->getType(); 11112 Expr *E = OrigE->IgnoreParenImpCasts(); 11113 11114 if (E->isTypeDependent() || E->isValueDependent()) 11115 return; 11116 11117 // For conditional operators, we analyze the arguments as if they 11118 // were being fed directly into the output. 11119 if (isa<ConditionalOperator>(E)) { 11120 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11121 CheckConditionalOperator(S, CO, CC, T); 11122 return; 11123 } 11124 11125 // Check implicit argument conversions for function calls. 11126 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11127 CheckImplicitArgumentConversions(S, Call, CC); 11128 11129 // Go ahead and check any implicit conversions we might have skipped. 11130 // The non-canonical typecheck is just an optimization; 11131 // CheckImplicitConversion will filter out dead implicit conversions. 11132 if (E->getType() != T) 11133 CheckImplicitConversion(S, E, T, CC); 11134 11135 // Now continue drilling into this expression. 11136 11137 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11138 // The bound subexpressions in a PseudoObjectExpr are not reachable 11139 // as transitive children. 11140 // FIXME: Use a more uniform representation for this. 11141 for (auto *SE : POE->semantics()) 11142 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11143 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 11144 } 11145 11146 // Skip past explicit casts. 11147 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11148 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11149 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11150 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11151 return AnalyzeImplicitConversions(S, E, CC); 11152 } 11153 11154 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11155 // Do a somewhat different check with comparison operators. 11156 if (BO->isComparisonOp()) 11157 return AnalyzeComparison(S, BO); 11158 11159 // And with simple assignments. 11160 if (BO->getOpcode() == BO_Assign) 11161 return AnalyzeAssignment(S, BO); 11162 // And with compound assignments. 11163 if (BO->isAssignmentOp()) 11164 return AnalyzeCompoundAssignment(S, BO); 11165 } 11166 11167 // These break the otherwise-useful invariant below. Fortunately, 11168 // we don't really need to recurse into them, because any internal 11169 // expressions should have been analyzed already when they were 11170 // built into statements. 11171 if (isa<StmtExpr>(E)) return; 11172 11173 // Don't descend into unevaluated contexts. 11174 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11175 11176 // Now just recurse over the expression's children. 11177 CC = E->getExprLoc(); 11178 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11179 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11180 for (Stmt *SubStmt : E->children()) { 11181 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11182 if (!ChildExpr) 11183 continue; 11184 11185 if (IsLogicalAndOperator && 11186 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11187 // Ignore checking string literals that are in logical and operators. 11188 // This is a common pattern for asserts. 11189 continue; 11190 AnalyzeImplicitConversions(S, ChildExpr, CC); 11191 } 11192 11193 if (BO && BO->isLogicalOp()) { 11194 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11195 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11196 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11197 11198 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11199 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11200 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11201 } 11202 11203 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11204 if (U->getOpcode() == UO_LNot) { 11205 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11206 } else if (U->getOpcode() != UO_AddrOf) { 11207 if (U->getSubExpr()->getType()->isAtomicType()) 11208 S.Diag(U->getSubExpr()->getBeginLoc(), 11209 diag::warn_atomic_implicit_seq_cst); 11210 } 11211 } 11212 } 11213 11214 /// Diagnose integer type and any valid implicit conversion to it. 11215 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11216 // Taking into account implicit conversions, 11217 // allow any integer. 11218 if (!E->getType()->isIntegerType()) { 11219 S.Diag(E->getBeginLoc(), 11220 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11221 return true; 11222 } 11223 // Potentially emit standard warnings for implicit conversions if enabled 11224 // using -Wconversion. 11225 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11226 return false; 11227 } 11228 11229 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11230 // Returns true when emitting a warning about taking the address of a reference. 11231 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11232 const PartialDiagnostic &PD) { 11233 E = E->IgnoreParenImpCasts(); 11234 11235 const FunctionDecl *FD = nullptr; 11236 11237 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11238 if (!DRE->getDecl()->getType()->isReferenceType()) 11239 return false; 11240 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11241 if (!M->getMemberDecl()->getType()->isReferenceType()) 11242 return false; 11243 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11244 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11245 return false; 11246 FD = Call->getDirectCallee(); 11247 } else { 11248 return false; 11249 } 11250 11251 SemaRef.Diag(E->getExprLoc(), PD); 11252 11253 // If possible, point to location of function. 11254 if (FD) { 11255 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11256 } 11257 11258 return true; 11259 } 11260 11261 // Returns true if the SourceLocation is expanded from any macro body. 11262 // Returns false if the SourceLocation is invalid, is from not in a macro 11263 // expansion, or is from expanded from a top-level macro argument. 11264 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11265 if (Loc.isInvalid()) 11266 return false; 11267 11268 while (Loc.isMacroID()) { 11269 if (SM.isMacroBodyExpansion(Loc)) 11270 return true; 11271 Loc = SM.getImmediateMacroCallerLoc(Loc); 11272 } 11273 11274 return false; 11275 } 11276 11277 /// Diagnose pointers that are always non-null. 11278 /// \param E the expression containing the pointer 11279 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11280 /// compared to a null pointer 11281 /// \param IsEqual True when the comparison is equal to a null pointer 11282 /// \param Range Extra SourceRange to highlight in the diagnostic 11283 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11284 Expr::NullPointerConstantKind NullKind, 11285 bool IsEqual, SourceRange Range) { 11286 if (!E) 11287 return; 11288 11289 // Don't warn inside macros. 11290 if (E->getExprLoc().isMacroID()) { 11291 const SourceManager &SM = getSourceManager(); 11292 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11293 IsInAnyMacroBody(SM, Range.getBegin())) 11294 return; 11295 } 11296 E = E->IgnoreImpCasts(); 11297 11298 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11299 11300 if (isa<CXXThisExpr>(E)) { 11301 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11302 : diag::warn_this_bool_conversion; 11303 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11304 return; 11305 } 11306 11307 bool IsAddressOf = false; 11308 11309 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11310 if (UO->getOpcode() != UO_AddrOf) 11311 return; 11312 IsAddressOf = true; 11313 E = UO->getSubExpr(); 11314 } 11315 11316 if (IsAddressOf) { 11317 unsigned DiagID = IsCompare 11318 ? diag::warn_address_of_reference_null_compare 11319 : diag::warn_address_of_reference_bool_conversion; 11320 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11321 << IsEqual; 11322 if (CheckForReference(*this, E, PD)) { 11323 return; 11324 } 11325 } 11326 11327 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11328 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11329 std::string Str; 11330 llvm::raw_string_ostream S(Str); 11331 E->printPretty(S, nullptr, getPrintingPolicy()); 11332 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11333 : diag::warn_cast_nonnull_to_bool; 11334 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11335 << E->getSourceRange() << Range << IsEqual; 11336 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11337 }; 11338 11339 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11340 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11341 if (auto *Callee = Call->getDirectCallee()) { 11342 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11343 ComplainAboutNonnullParamOrCall(A); 11344 return; 11345 } 11346 } 11347 } 11348 11349 // Expect to find a single Decl. Skip anything more complicated. 11350 ValueDecl *D = nullptr; 11351 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11352 D = R->getDecl(); 11353 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11354 D = M->getMemberDecl(); 11355 } 11356 11357 // Weak Decls can be null. 11358 if (!D || D->isWeak()) 11359 return; 11360 11361 // Check for parameter decl with nonnull attribute 11362 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11363 if (getCurFunction() && 11364 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11365 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11366 ComplainAboutNonnullParamOrCall(A); 11367 return; 11368 } 11369 11370 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11371 auto ParamIter = llvm::find(FD->parameters(), PV); 11372 assert(ParamIter != FD->param_end()); 11373 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11374 11375 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11376 if (!NonNull->args_size()) { 11377 ComplainAboutNonnullParamOrCall(NonNull); 11378 return; 11379 } 11380 11381 for (const ParamIdx &ArgNo : NonNull->args()) { 11382 if (ArgNo.getASTIndex() == ParamNo) { 11383 ComplainAboutNonnullParamOrCall(NonNull); 11384 return; 11385 } 11386 } 11387 } 11388 } 11389 } 11390 } 11391 11392 QualType T = D->getType(); 11393 const bool IsArray = T->isArrayType(); 11394 const bool IsFunction = T->isFunctionType(); 11395 11396 // Address of function is used to silence the function warning. 11397 if (IsAddressOf && IsFunction) { 11398 return; 11399 } 11400 11401 // Found nothing. 11402 if (!IsAddressOf && !IsFunction && !IsArray) 11403 return; 11404 11405 // Pretty print the expression for the diagnostic. 11406 std::string Str; 11407 llvm::raw_string_ostream S(Str); 11408 E->printPretty(S, nullptr, getPrintingPolicy()); 11409 11410 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11411 : diag::warn_impcast_pointer_to_bool; 11412 enum { 11413 AddressOf, 11414 FunctionPointer, 11415 ArrayPointer 11416 } DiagType; 11417 if (IsAddressOf) 11418 DiagType = AddressOf; 11419 else if (IsFunction) 11420 DiagType = FunctionPointer; 11421 else if (IsArray) 11422 DiagType = ArrayPointer; 11423 else 11424 llvm_unreachable("Could not determine diagnostic."); 11425 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11426 << Range << IsEqual; 11427 11428 if (!IsFunction) 11429 return; 11430 11431 // Suggest '&' to silence the function warning. 11432 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11433 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11434 11435 // Check to see if '()' fixit should be emitted. 11436 QualType ReturnType; 11437 UnresolvedSet<4> NonTemplateOverloads; 11438 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11439 if (ReturnType.isNull()) 11440 return; 11441 11442 if (IsCompare) { 11443 // There are two cases here. If there is null constant, the only suggest 11444 // for a pointer return type. If the null is 0, then suggest if the return 11445 // type is a pointer or an integer type. 11446 if (!ReturnType->isPointerType()) { 11447 if (NullKind == Expr::NPCK_ZeroExpression || 11448 NullKind == Expr::NPCK_ZeroLiteral) { 11449 if (!ReturnType->isIntegerType()) 11450 return; 11451 } else { 11452 return; 11453 } 11454 } 11455 } else { // !IsCompare 11456 // For function to bool, only suggest if the function pointer has bool 11457 // return type. 11458 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11459 return; 11460 } 11461 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11462 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11463 } 11464 11465 /// Diagnoses "dangerous" implicit conversions within the given 11466 /// expression (which is a full expression). Implements -Wconversion 11467 /// and -Wsign-compare. 11468 /// 11469 /// \param CC the "context" location of the implicit conversion, i.e. 11470 /// the most location of the syntactic entity requiring the implicit 11471 /// conversion 11472 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11473 // Don't diagnose in unevaluated contexts. 11474 if (isUnevaluatedContext()) 11475 return; 11476 11477 // Don't diagnose for value- or type-dependent expressions. 11478 if (E->isTypeDependent() || E->isValueDependent()) 11479 return; 11480 11481 // Check for array bounds violations in cases where the check isn't triggered 11482 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11483 // ArraySubscriptExpr is on the RHS of a variable initialization. 11484 CheckArrayAccess(E); 11485 11486 // This is not the right CC for (e.g.) a variable initialization. 11487 AnalyzeImplicitConversions(*this, E, CC); 11488 } 11489 11490 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11491 /// Input argument E is a logical expression. 11492 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11493 ::CheckBoolLikeConversion(*this, E, CC); 11494 } 11495 11496 /// Diagnose when expression is an integer constant expression and its evaluation 11497 /// results in integer overflow 11498 void Sema::CheckForIntOverflow (Expr *E) { 11499 // Use a work list to deal with nested struct initializers. 11500 SmallVector<Expr *, 2> Exprs(1, E); 11501 11502 do { 11503 Expr *OriginalE = Exprs.pop_back_val(); 11504 Expr *E = OriginalE->IgnoreParenCasts(); 11505 11506 if (isa<BinaryOperator>(E)) { 11507 E->EvaluateForOverflow(Context); 11508 continue; 11509 } 11510 11511 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11512 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11513 else if (isa<ObjCBoxedExpr>(OriginalE)) 11514 E->EvaluateForOverflow(Context); 11515 else if (auto Call = dyn_cast<CallExpr>(E)) 11516 Exprs.append(Call->arg_begin(), Call->arg_end()); 11517 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 11518 Exprs.append(Message->arg_begin(), Message->arg_end()); 11519 } while (!Exprs.empty()); 11520 } 11521 11522 namespace { 11523 11524 /// Visitor for expressions which looks for unsequenced operations on the 11525 /// same object. 11526 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 11527 using Base = EvaluatedExprVisitor<SequenceChecker>; 11528 11529 /// A tree of sequenced regions within an expression. Two regions are 11530 /// unsequenced if one is an ancestor or a descendent of the other. When we 11531 /// finish processing an expression with sequencing, such as a comma 11532 /// expression, we fold its tree nodes into its parent, since they are 11533 /// unsequenced with respect to nodes we will visit later. 11534 class SequenceTree { 11535 struct Value { 11536 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 11537 unsigned Parent : 31; 11538 unsigned Merged : 1; 11539 }; 11540 SmallVector<Value, 8> Values; 11541 11542 public: 11543 /// A region within an expression which may be sequenced with respect 11544 /// to some other region. 11545 class Seq { 11546 friend class SequenceTree; 11547 11548 unsigned Index = 0; 11549 11550 explicit Seq(unsigned N) : Index(N) {} 11551 11552 public: 11553 Seq() = default; 11554 }; 11555 11556 SequenceTree() { Values.push_back(Value(0)); } 11557 Seq root() const { return Seq(0); } 11558 11559 /// Create a new sequence of operations, which is an unsequenced 11560 /// subset of \p Parent. This sequence of operations is sequenced with 11561 /// respect to other children of \p Parent. 11562 Seq allocate(Seq Parent) { 11563 Values.push_back(Value(Parent.Index)); 11564 return Seq(Values.size() - 1); 11565 } 11566 11567 /// Merge a sequence of operations into its parent. 11568 void merge(Seq S) { 11569 Values[S.Index].Merged = true; 11570 } 11571 11572 /// Determine whether two operations are unsequenced. This operation 11573 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 11574 /// should have been merged into its parent as appropriate. 11575 bool isUnsequenced(Seq Cur, Seq Old) { 11576 unsigned C = representative(Cur.Index); 11577 unsigned Target = representative(Old.Index); 11578 while (C >= Target) { 11579 if (C == Target) 11580 return true; 11581 C = Values[C].Parent; 11582 } 11583 return false; 11584 } 11585 11586 private: 11587 /// Pick a representative for a sequence. 11588 unsigned representative(unsigned K) { 11589 if (Values[K].Merged) 11590 // Perform path compression as we go. 11591 return Values[K].Parent = representative(Values[K].Parent); 11592 return K; 11593 } 11594 }; 11595 11596 /// An object for which we can track unsequenced uses. 11597 using Object = NamedDecl *; 11598 11599 /// Different flavors of object usage which we track. We only track the 11600 /// least-sequenced usage of each kind. 11601 enum UsageKind { 11602 /// A read of an object. Multiple unsequenced reads are OK. 11603 UK_Use, 11604 11605 /// A modification of an object which is sequenced before the value 11606 /// computation of the expression, such as ++n in C++. 11607 UK_ModAsValue, 11608 11609 /// A modification of an object which is not sequenced before the value 11610 /// computation of the expression, such as n++. 11611 UK_ModAsSideEffect, 11612 11613 UK_Count = UK_ModAsSideEffect + 1 11614 }; 11615 11616 struct Usage { 11617 Expr *Use = nullptr; 11618 SequenceTree::Seq Seq; 11619 11620 Usage() = default; 11621 }; 11622 11623 struct UsageInfo { 11624 Usage Uses[UK_Count]; 11625 11626 /// Have we issued a diagnostic for this variable already? 11627 bool Diagnosed = false; 11628 11629 UsageInfo() = default; 11630 }; 11631 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 11632 11633 Sema &SemaRef; 11634 11635 /// Sequenced regions within the expression. 11636 SequenceTree Tree; 11637 11638 /// Declaration modifications and references which we have seen. 11639 UsageInfoMap UsageMap; 11640 11641 /// The region we are currently within. 11642 SequenceTree::Seq Region; 11643 11644 /// Filled in with declarations which were modified as a side-effect 11645 /// (that is, post-increment operations). 11646 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 11647 11648 /// Expressions to check later. We defer checking these to reduce 11649 /// stack usage. 11650 SmallVectorImpl<Expr *> &WorkList; 11651 11652 /// RAII object wrapping the visitation of a sequenced subexpression of an 11653 /// expression. At the end of this process, the side-effects of the evaluation 11654 /// become sequenced with respect to the value computation of the result, so 11655 /// we downgrade any UK_ModAsSideEffect within the evaluation to 11656 /// UK_ModAsValue. 11657 struct SequencedSubexpression { 11658 SequencedSubexpression(SequenceChecker &Self) 11659 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11660 Self.ModAsSideEffect = &ModAsSideEffect; 11661 } 11662 11663 ~SequencedSubexpression() { 11664 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11665 UsageInfo &U = Self.UsageMap[M.first]; 11666 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11667 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11668 SideEffectUsage = M.second; 11669 } 11670 Self.ModAsSideEffect = OldModAsSideEffect; 11671 } 11672 11673 SequenceChecker &Self; 11674 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11675 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11676 }; 11677 11678 /// RAII object wrapping the visitation of a subexpression which we might 11679 /// choose to evaluate as a constant. If any subexpression is evaluated and 11680 /// found to be non-constant, this allows us to suppress the evaluation of 11681 /// the outer expression. 11682 class EvaluationTracker { 11683 public: 11684 EvaluationTracker(SequenceChecker &Self) 11685 : Self(Self), Prev(Self.EvalTracker) { 11686 Self.EvalTracker = this; 11687 } 11688 11689 ~EvaluationTracker() { 11690 Self.EvalTracker = Prev; 11691 if (Prev) 11692 Prev->EvalOK &= EvalOK; 11693 } 11694 11695 bool evaluate(const Expr *E, bool &Result) { 11696 if (!EvalOK || E->isValueDependent()) 11697 return false; 11698 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11699 return EvalOK; 11700 } 11701 11702 private: 11703 SequenceChecker &Self; 11704 EvaluationTracker *Prev; 11705 bool EvalOK = true; 11706 } *EvalTracker = nullptr; 11707 11708 /// Find the object which is produced by the specified expression, 11709 /// if any. 11710 Object getObject(Expr *E, bool Mod) const { 11711 E = E->IgnoreParenCasts(); 11712 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11713 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11714 return getObject(UO->getSubExpr(), Mod); 11715 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11716 if (BO->getOpcode() == BO_Comma) 11717 return getObject(BO->getRHS(), Mod); 11718 if (Mod && BO->isAssignmentOp()) 11719 return getObject(BO->getLHS(), Mod); 11720 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11721 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11722 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11723 return ME->getMemberDecl(); 11724 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11725 // FIXME: If this is a reference, map through to its value. 11726 return DRE->getDecl(); 11727 return nullptr; 11728 } 11729 11730 /// Note that an object was modified or used by an expression. 11731 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11732 Usage &U = UI.Uses[UK]; 11733 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11734 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11735 ModAsSideEffect->push_back(std::make_pair(O, U)); 11736 U.Use = Ref; 11737 U.Seq = Region; 11738 } 11739 } 11740 11741 /// Check whether a modification or use conflicts with a prior usage. 11742 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11743 bool IsModMod) { 11744 if (UI.Diagnosed) 11745 return; 11746 11747 const Usage &U = UI.Uses[OtherKind]; 11748 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11749 return; 11750 11751 Expr *Mod = U.Use; 11752 Expr *ModOrUse = Ref; 11753 if (OtherKind == UK_Use) 11754 std::swap(Mod, ModOrUse); 11755 11756 SemaRef.Diag(Mod->getExprLoc(), 11757 IsModMod ? diag::warn_unsequenced_mod_mod 11758 : diag::warn_unsequenced_mod_use) 11759 << O << SourceRange(ModOrUse->getExprLoc()); 11760 UI.Diagnosed = true; 11761 } 11762 11763 void notePreUse(Object O, Expr *Use) { 11764 UsageInfo &U = UsageMap[O]; 11765 // Uses conflict with other modifications. 11766 checkUsage(O, U, Use, UK_ModAsValue, false); 11767 } 11768 11769 void notePostUse(Object O, Expr *Use) { 11770 UsageInfo &U = UsageMap[O]; 11771 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 11772 addUsage(U, O, Use, UK_Use); 11773 } 11774 11775 void notePreMod(Object O, Expr *Mod) { 11776 UsageInfo &U = UsageMap[O]; 11777 // Modifications conflict with other modifications and with uses. 11778 checkUsage(O, U, Mod, UK_ModAsValue, true); 11779 checkUsage(O, U, Mod, UK_Use, false); 11780 } 11781 11782 void notePostMod(Object O, Expr *Use, UsageKind UK) { 11783 UsageInfo &U = UsageMap[O]; 11784 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 11785 addUsage(U, O, Use, UK); 11786 } 11787 11788 public: 11789 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 11790 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 11791 Visit(E); 11792 } 11793 11794 void VisitStmt(Stmt *S) { 11795 // Skip all statements which aren't expressions for now. 11796 } 11797 11798 void VisitExpr(Expr *E) { 11799 // By default, just recurse to evaluated subexpressions. 11800 Base::VisitStmt(E); 11801 } 11802 11803 void VisitCastExpr(CastExpr *E) { 11804 Object O = Object(); 11805 if (E->getCastKind() == CK_LValueToRValue) 11806 O = getObject(E->getSubExpr(), false); 11807 11808 if (O) 11809 notePreUse(O, E); 11810 VisitExpr(E); 11811 if (O) 11812 notePostUse(O, E); 11813 } 11814 11815 void VisitBinComma(BinaryOperator *BO) { 11816 // C++11 [expr.comma]p1: 11817 // Every value computation and side effect associated with the left 11818 // expression is sequenced before every value computation and side 11819 // effect associated with the right expression. 11820 SequenceTree::Seq LHS = Tree.allocate(Region); 11821 SequenceTree::Seq RHS = Tree.allocate(Region); 11822 SequenceTree::Seq OldRegion = Region; 11823 11824 { 11825 SequencedSubexpression SeqLHS(*this); 11826 Region = LHS; 11827 Visit(BO->getLHS()); 11828 } 11829 11830 Region = RHS; 11831 Visit(BO->getRHS()); 11832 11833 Region = OldRegion; 11834 11835 // Forget that LHS and RHS are sequenced. They are both unsequenced 11836 // with respect to other stuff. 11837 Tree.merge(LHS); 11838 Tree.merge(RHS); 11839 } 11840 11841 void VisitBinAssign(BinaryOperator *BO) { 11842 // The modification is sequenced after the value computation of the LHS 11843 // and RHS, so check it before inspecting the operands and update the 11844 // map afterwards. 11845 Object O = getObject(BO->getLHS(), true); 11846 if (!O) 11847 return VisitExpr(BO); 11848 11849 notePreMod(O, BO); 11850 11851 // C++11 [expr.ass]p7: 11852 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11853 // only once. 11854 // 11855 // Therefore, for a compound assignment operator, O is considered used 11856 // everywhere except within the evaluation of E1 itself. 11857 if (isa<CompoundAssignOperator>(BO)) 11858 notePreUse(O, BO); 11859 11860 Visit(BO->getLHS()); 11861 11862 if (isa<CompoundAssignOperator>(BO)) 11863 notePostUse(O, BO); 11864 11865 Visit(BO->getRHS()); 11866 11867 // C++11 [expr.ass]p1: 11868 // the assignment is sequenced [...] before the value computation of the 11869 // assignment expression. 11870 // C11 6.5.16/3 has no such rule. 11871 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11872 : UK_ModAsSideEffect); 11873 } 11874 11875 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11876 VisitBinAssign(CAO); 11877 } 11878 11879 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11880 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11881 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11882 Object O = getObject(UO->getSubExpr(), true); 11883 if (!O) 11884 return VisitExpr(UO); 11885 11886 notePreMod(O, UO); 11887 Visit(UO->getSubExpr()); 11888 // C++11 [expr.pre.incr]p1: 11889 // the expression ++x is equivalent to x+=1 11890 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11891 : UK_ModAsSideEffect); 11892 } 11893 11894 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11895 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11896 void VisitUnaryPostIncDec(UnaryOperator *UO) { 11897 Object O = getObject(UO->getSubExpr(), true); 11898 if (!O) 11899 return VisitExpr(UO); 11900 11901 notePreMod(O, UO); 11902 Visit(UO->getSubExpr()); 11903 notePostMod(O, UO, UK_ModAsSideEffect); 11904 } 11905 11906 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 11907 void VisitBinLOr(BinaryOperator *BO) { 11908 // The side-effects of the LHS of an '&&' are sequenced before the 11909 // value computation of the RHS, and hence before the value computation 11910 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 11911 // as if they were unconditionally sequenced. 11912 EvaluationTracker Eval(*this); 11913 { 11914 SequencedSubexpression Sequenced(*this); 11915 Visit(BO->getLHS()); 11916 } 11917 11918 bool Result; 11919 if (Eval.evaluate(BO->getLHS(), Result)) { 11920 if (!Result) 11921 Visit(BO->getRHS()); 11922 } else { 11923 // Check for unsequenced operations in the RHS, treating it as an 11924 // entirely separate evaluation. 11925 // 11926 // FIXME: If there are operations in the RHS which are unsequenced 11927 // with respect to operations outside the RHS, and those operations 11928 // are unconditionally evaluated, diagnose them. 11929 WorkList.push_back(BO->getRHS()); 11930 } 11931 } 11932 void VisitBinLAnd(BinaryOperator *BO) { 11933 EvaluationTracker Eval(*this); 11934 { 11935 SequencedSubexpression Sequenced(*this); 11936 Visit(BO->getLHS()); 11937 } 11938 11939 bool Result; 11940 if (Eval.evaluate(BO->getLHS(), Result)) { 11941 if (Result) 11942 Visit(BO->getRHS()); 11943 } else { 11944 WorkList.push_back(BO->getRHS()); 11945 } 11946 } 11947 11948 // Only visit the condition, unless we can be sure which subexpression will 11949 // be chosen. 11950 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 11951 EvaluationTracker Eval(*this); 11952 { 11953 SequencedSubexpression Sequenced(*this); 11954 Visit(CO->getCond()); 11955 } 11956 11957 bool Result; 11958 if (Eval.evaluate(CO->getCond(), Result)) 11959 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 11960 else { 11961 WorkList.push_back(CO->getTrueExpr()); 11962 WorkList.push_back(CO->getFalseExpr()); 11963 } 11964 } 11965 11966 void VisitCallExpr(CallExpr *CE) { 11967 // C++11 [intro.execution]p15: 11968 // When calling a function [...], every value computation and side effect 11969 // associated with any argument expression, or with the postfix expression 11970 // designating the called function, is sequenced before execution of every 11971 // expression or statement in the body of the function [and thus before 11972 // the value computation of its result]. 11973 SequencedSubexpression Sequenced(*this); 11974 Base::VisitCallExpr(CE); 11975 11976 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 11977 } 11978 11979 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 11980 // This is a call, so all subexpressions are sequenced before the result. 11981 SequencedSubexpression Sequenced(*this); 11982 11983 if (!CCE->isListInitialization()) 11984 return VisitExpr(CCE); 11985 11986 // In C++11, list initializations are sequenced. 11987 SmallVector<SequenceTree::Seq, 32> Elts; 11988 SequenceTree::Seq Parent = Region; 11989 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 11990 E = CCE->arg_end(); 11991 I != E; ++I) { 11992 Region = Tree.allocate(Parent); 11993 Elts.push_back(Region); 11994 Visit(*I); 11995 } 11996 11997 // Forget that the initializers are sequenced. 11998 Region = Parent; 11999 for (unsigned I = 0; I < Elts.size(); ++I) 12000 Tree.merge(Elts[I]); 12001 } 12002 12003 void VisitInitListExpr(InitListExpr *ILE) { 12004 if (!SemaRef.getLangOpts().CPlusPlus11) 12005 return VisitExpr(ILE); 12006 12007 // In C++11, list initializations are sequenced. 12008 SmallVector<SequenceTree::Seq, 32> Elts; 12009 SequenceTree::Seq Parent = Region; 12010 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12011 Expr *E = ILE->getInit(I); 12012 if (!E) continue; 12013 Region = Tree.allocate(Parent); 12014 Elts.push_back(Region); 12015 Visit(E); 12016 } 12017 12018 // Forget that the initializers are sequenced. 12019 Region = Parent; 12020 for (unsigned I = 0; I < Elts.size(); ++I) 12021 Tree.merge(Elts[I]); 12022 } 12023 }; 12024 12025 } // namespace 12026 12027 void Sema::CheckUnsequencedOperations(Expr *E) { 12028 SmallVector<Expr *, 8> WorkList; 12029 WorkList.push_back(E); 12030 while (!WorkList.empty()) { 12031 Expr *Item = WorkList.pop_back_val(); 12032 SequenceChecker(*this, Item, WorkList); 12033 } 12034 } 12035 12036 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12037 bool IsConstexpr) { 12038 CheckImplicitConversions(E, CheckLoc); 12039 if (!E->isInstantiationDependent()) 12040 CheckUnsequencedOperations(E); 12041 if (!IsConstexpr && !E->isValueDependent()) 12042 CheckForIntOverflow(E); 12043 DiagnoseMisalignedMembers(); 12044 } 12045 12046 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12047 FieldDecl *BitField, 12048 Expr *Init) { 12049 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12050 } 12051 12052 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12053 SourceLocation Loc) { 12054 if (!PType->isVariablyModifiedType()) 12055 return; 12056 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12057 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12058 return; 12059 } 12060 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12061 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12062 return; 12063 } 12064 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12065 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12066 return; 12067 } 12068 12069 const ArrayType *AT = S.Context.getAsArrayType(PType); 12070 if (!AT) 12071 return; 12072 12073 if (AT->getSizeModifier() != ArrayType::Star) { 12074 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12075 return; 12076 } 12077 12078 S.Diag(Loc, diag::err_array_star_in_function_definition); 12079 } 12080 12081 /// CheckParmsForFunctionDef - Check that the parameters of the given 12082 /// function are appropriate for the definition of a function. This 12083 /// takes care of any checks that cannot be performed on the 12084 /// declaration itself, e.g., that the types of each of the function 12085 /// parameters are complete. 12086 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12087 bool CheckParameterNames) { 12088 bool HasInvalidParm = false; 12089 for (ParmVarDecl *Param : Parameters) { 12090 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12091 // function declarator that is part of a function definition of 12092 // that function shall not have incomplete type. 12093 // 12094 // This is also C++ [dcl.fct]p6. 12095 if (!Param->isInvalidDecl() && 12096 RequireCompleteType(Param->getLocation(), Param->getType(), 12097 diag::err_typecheck_decl_incomplete_type)) { 12098 Param->setInvalidDecl(); 12099 HasInvalidParm = true; 12100 } 12101 12102 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12103 // declaration of each parameter shall include an identifier. 12104 if (CheckParameterNames && 12105 Param->getIdentifier() == nullptr && 12106 !Param->isImplicit() && 12107 !getLangOpts().CPlusPlus) 12108 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12109 12110 // C99 6.7.5.3p12: 12111 // If the function declarator is not part of a definition of that 12112 // function, parameters may have incomplete type and may use the [*] 12113 // notation in their sequences of declarator specifiers to specify 12114 // variable length array types. 12115 QualType PType = Param->getOriginalType(); 12116 // FIXME: This diagnostic should point the '[*]' if source-location 12117 // information is added for it. 12118 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12119 12120 // If the parameter is a c++ class type and it has to be destructed in the 12121 // callee function, declare the destructor so that it can be called by the 12122 // callee function. Do not perform any direct access check on the dtor here. 12123 if (!Param->isInvalidDecl()) { 12124 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12125 if (!ClassDecl->isInvalidDecl() && 12126 !ClassDecl->hasIrrelevantDestructor() && 12127 !ClassDecl->isDependentContext() && 12128 ClassDecl->isParamDestroyedInCallee()) { 12129 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12130 MarkFunctionReferenced(Param->getLocation(), Destructor); 12131 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12132 } 12133 } 12134 } 12135 12136 // Parameters with the pass_object_size attribute only need to be marked 12137 // constant at function definitions. Because we lack information about 12138 // whether we're on a declaration or definition when we're instantiating the 12139 // attribute, we need to check for constness here. 12140 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12141 if (!Param->getType().isConstQualified()) 12142 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12143 << Attr->getSpelling() << 1; 12144 } 12145 12146 return HasInvalidParm; 12147 } 12148 12149 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12150 /// or MemberExpr. 12151 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12152 ASTContext &Context) { 12153 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12154 return Context.getDeclAlign(DRE->getDecl()); 12155 12156 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12157 return Context.getDeclAlign(ME->getMemberDecl()); 12158 12159 return TypeAlign; 12160 } 12161 12162 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12163 /// pointer cast increases the alignment requirements. 12164 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12165 // This is actually a lot of work to potentially be doing on every 12166 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12167 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12168 return; 12169 12170 // Ignore dependent types. 12171 if (T->isDependentType() || Op->getType()->isDependentType()) 12172 return; 12173 12174 // Require that the destination be a pointer type. 12175 const PointerType *DestPtr = T->getAs<PointerType>(); 12176 if (!DestPtr) return; 12177 12178 // If the destination has alignment 1, we're done. 12179 QualType DestPointee = DestPtr->getPointeeType(); 12180 if (DestPointee->isIncompleteType()) return; 12181 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12182 if (DestAlign.isOne()) return; 12183 12184 // Require that the source be a pointer type. 12185 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12186 if (!SrcPtr) return; 12187 QualType SrcPointee = SrcPtr->getPointeeType(); 12188 12189 // Whitelist casts from cv void*. We already implicitly 12190 // whitelisted casts to cv void*, since they have alignment 1. 12191 // Also whitelist casts involving incomplete types, which implicitly 12192 // includes 'void'. 12193 if (SrcPointee->isIncompleteType()) return; 12194 12195 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12196 12197 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12198 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12199 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12200 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12201 if (UO->getOpcode() == UO_AddrOf) 12202 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12203 } 12204 12205 if (SrcAlign >= DestAlign) return; 12206 12207 Diag(TRange.getBegin(), diag::warn_cast_align) 12208 << Op->getType() << T 12209 << static_cast<unsigned>(SrcAlign.getQuantity()) 12210 << static_cast<unsigned>(DestAlign.getQuantity()) 12211 << TRange << Op->getSourceRange(); 12212 } 12213 12214 /// Check whether this array fits the idiom of a size-one tail padded 12215 /// array member of a struct. 12216 /// 12217 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12218 /// commonly used to emulate flexible arrays in C89 code. 12219 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12220 const NamedDecl *ND) { 12221 if (Size != 1 || !ND) return false; 12222 12223 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12224 if (!FD) return false; 12225 12226 // Don't consider sizes resulting from macro expansions or template argument 12227 // substitution to form C89 tail-padded arrays. 12228 12229 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12230 while (TInfo) { 12231 TypeLoc TL = TInfo->getTypeLoc(); 12232 // Look through typedefs. 12233 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12234 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12235 TInfo = TDL->getTypeSourceInfo(); 12236 continue; 12237 } 12238 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12239 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12240 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12241 return false; 12242 } 12243 break; 12244 } 12245 12246 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12247 if (!RD) return false; 12248 if (RD->isUnion()) return false; 12249 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12250 if (!CRD->isStandardLayout()) return false; 12251 } 12252 12253 // See if this is the last field decl in the record. 12254 const Decl *D = FD; 12255 while ((D = D->getNextDeclInContext())) 12256 if (isa<FieldDecl>(D)) 12257 return false; 12258 return true; 12259 } 12260 12261 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12262 const ArraySubscriptExpr *ASE, 12263 bool AllowOnePastEnd, bool IndexNegated) { 12264 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12265 if (IndexExpr->isValueDependent()) 12266 return; 12267 12268 const Type *EffectiveType = 12269 BaseExpr->getType()->getPointeeOrArrayElementType(); 12270 BaseExpr = BaseExpr->IgnoreParenCasts(); 12271 const ConstantArrayType *ArrayTy = 12272 Context.getAsConstantArrayType(BaseExpr->getType()); 12273 if (!ArrayTy) 12274 return; 12275 12276 Expr::EvalResult Result; 12277 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 12278 return; 12279 12280 llvm::APSInt index = Result.Val.getInt(); 12281 if (IndexNegated) 12282 index = -index; 12283 12284 const NamedDecl *ND = nullptr; 12285 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12286 ND = DRE->getDecl(); 12287 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12288 ND = ME->getMemberDecl(); 12289 12290 if (index.isUnsigned() || !index.isNegative()) { 12291 llvm::APInt size = ArrayTy->getSize(); 12292 if (!size.isStrictlyPositive()) 12293 return; 12294 12295 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 12296 if (BaseType != EffectiveType) { 12297 // Make sure we're comparing apples to apples when comparing index to size 12298 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12299 uint64_t array_typesize = Context.getTypeSize(BaseType); 12300 // Handle ptrarith_typesize being zero, such as when casting to void* 12301 if (!ptrarith_typesize) ptrarith_typesize = 1; 12302 if (ptrarith_typesize != array_typesize) { 12303 // There's a cast to a different size type involved 12304 uint64_t ratio = array_typesize / ptrarith_typesize; 12305 // TODO: Be smarter about handling cases where array_typesize is not a 12306 // multiple of ptrarith_typesize 12307 if (ptrarith_typesize * ratio == array_typesize) 12308 size *= llvm::APInt(size.getBitWidth(), ratio); 12309 } 12310 } 12311 12312 if (size.getBitWidth() > index.getBitWidth()) 12313 index = index.zext(size.getBitWidth()); 12314 else if (size.getBitWidth() < index.getBitWidth()) 12315 size = size.zext(index.getBitWidth()); 12316 12317 // For array subscripting the index must be less than size, but for pointer 12318 // arithmetic also allow the index (offset) to be equal to size since 12319 // computing the next address after the end of the array is legal and 12320 // commonly done e.g. in C++ iterators and range-based for loops. 12321 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12322 return; 12323 12324 // Also don't warn for arrays of size 1 which are members of some 12325 // structure. These are often used to approximate flexible arrays in C89 12326 // code. 12327 if (IsTailPaddedMemberArray(*this, size, ND)) 12328 return; 12329 12330 // Suppress the warning if the subscript expression (as identified by the 12331 // ']' location) and the index expression are both from macro expansions 12332 // within a system header. 12333 if (ASE) { 12334 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12335 ASE->getRBracketLoc()); 12336 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12337 SourceLocation IndexLoc = 12338 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12339 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12340 return; 12341 } 12342 } 12343 12344 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12345 if (ASE) 12346 DiagID = diag::warn_array_index_exceeds_bounds; 12347 12348 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12349 PDiag(DiagID) << index.toString(10, true) 12350 << size.toString(10, true) 12351 << (unsigned)size.getLimitedValue(~0U) 12352 << IndexExpr->getSourceRange()); 12353 } else { 12354 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12355 if (!ASE) { 12356 DiagID = diag::warn_ptr_arith_precedes_bounds; 12357 if (index.isNegative()) index = -index; 12358 } 12359 12360 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12361 PDiag(DiagID) << index.toString(10, true) 12362 << IndexExpr->getSourceRange()); 12363 } 12364 12365 if (!ND) { 12366 // Try harder to find a NamedDecl to point at in the note. 12367 while (const ArraySubscriptExpr *ASE = 12368 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12369 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12370 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12371 ND = DRE->getDecl(); 12372 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12373 ND = ME->getMemberDecl(); 12374 } 12375 12376 if (ND) 12377 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12378 PDiag(diag::note_array_index_out_of_bounds) 12379 << ND->getDeclName()); 12380 } 12381 12382 void Sema::CheckArrayAccess(const Expr *expr) { 12383 int AllowOnePastEnd = 0; 12384 while (expr) { 12385 expr = expr->IgnoreParenImpCasts(); 12386 switch (expr->getStmtClass()) { 12387 case Stmt::ArraySubscriptExprClass: { 12388 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12389 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12390 AllowOnePastEnd > 0); 12391 expr = ASE->getBase(); 12392 break; 12393 } 12394 case Stmt::MemberExprClass: { 12395 expr = cast<MemberExpr>(expr)->getBase(); 12396 break; 12397 } 12398 case Stmt::OMPArraySectionExprClass: { 12399 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12400 if (ASE->getLowerBound()) 12401 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12402 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12403 return; 12404 } 12405 case Stmt::UnaryOperatorClass: { 12406 // Only unwrap the * and & unary operators 12407 const UnaryOperator *UO = cast<UnaryOperator>(expr); 12408 expr = UO->getSubExpr(); 12409 switch (UO->getOpcode()) { 12410 case UO_AddrOf: 12411 AllowOnePastEnd++; 12412 break; 12413 case UO_Deref: 12414 AllowOnePastEnd--; 12415 break; 12416 default: 12417 return; 12418 } 12419 break; 12420 } 12421 case Stmt::ConditionalOperatorClass: { 12422 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 12423 if (const Expr *lhs = cond->getLHS()) 12424 CheckArrayAccess(lhs); 12425 if (const Expr *rhs = cond->getRHS()) 12426 CheckArrayAccess(rhs); 12427 return; 12428 } 12429 case Stmt::CXXOperatorCallExprClass: { 12430 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 12431 for (const auto *Arg : OCE->arguments()) 12432 CheckArrayAccess(Arg); 12433 return; 12434 } 12435 default: 12436 return; 12437 } 12438 } 12439 } 12440 12441 //===--- CHECK: Objective-C retain cycles ----------------------------------// 12442 12443 namespace { 12444 12445 struct RetainCycleOwner { 12446 VarDecl *Variable = nullptr; 12447 SourceRange Range; 12448 SourceLocation Loc; 12449 bool Indirect = false; 12450 12451 RetainCycleOwner() = default; 12452 12453 void setLocsFrom(Expr *e) { 12454 Loc = e->getExprLoc(); 12455 Range = e->getSourceRange(); 12456 } 12457 }; 12458 12459 } // namespace 12460 12461 /// Consider whether capturing the given variable can possibly lead to 12462 /// a retain cycle. 12463 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 12464 // In ARC, it's captured strongly iff the variable has __strong 12465 // lifetime. In MRR, it's captured strongly if the variable is 12466 // __block and has an appropriate type. 12467 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12468 return false; 12469 12470 owner.Variable = var; 12471 if (ref) 12472 owner.setLocsFrom(ref); 12473 return true; 12474 } 12475 12476 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 12477 while (true) { 12478 e = e->IgnoreParens(); 12479 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 12480 switch (cast->getCastKind()) { 12481 case CK_BitCast: 12482 case CK_LValueBitCast: 12483 case CK_LValueToRValue: 12484 case CK_ARCReclaimReturnedObject: 12485 e = cast->getSubExpr(); 12486 continue; 12487 12488 default: 12489 return false; 12490 } 12491 } 12492 12493 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 12494 ObjCIvarDecl *ivar = ref->getDecl(); 12495 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12496 return false; 12497 12498 // Try to find a retain cycle in the base. 12499 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 12500 return false; 12501 12502 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 12503 owner.Indirect = true; 12504 return true; 12505 } 12506 12507 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 12508 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 12509 if (!var) return false; 12510 return considerVariable(var, ref, owner); 12511 } 12512 12513 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 12514 if (member->isArrow()) return false; 12515 12516 // Don't count this as an indirect ownership. 12517 e = member->getBase(); 12518 continue; 12519 } 12520 12521 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 12522 // Only pay attention to pseudo-objects on property references. 12523 ObjCPropertyRefExpr *pre 12524 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 12525 ->IgnoreParens()); 12526 if (!pre) return false; 12527 if (pre->isImplicitProperty()) return false; 12528 ObjCPropertyDecl *property = pre->getExplicitProperty(); 12529 if (!property->isRetaining() && 12530 !(property->getPropertyIvarDecl() && 12531 property->getPropertyIvarDecl()->getType() 12532 .getObjCLifetime() == Qualifiers::OCL_Strong)) 12533 return false; 12534 12535 owner.Indirect = true; 12536 if (pre->isSuperReceiver()) { 12537 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 12538 if (!owner.Variable) 12539 return false; 12540 owner.Loc = pre->getLocation(); 12541 owner.Range = pre->getSourceRange(); 12542 return true; 12543 } 12544 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 12545 ->getSourceExpr()); 12546 continue; 12547 } 12548 12549 // Array ivars? 12550 12551 return false; 12552 } 12553 } 12554 12555 namespace { 12556 12557 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 12558 ASTContext &Context; 12559 VarDecl *Variable; 12560 Expr *Capturer = nullptr; 12561 bool VarWillBeReased = false; 12562 12563 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 12564 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 12565 Context(Context), Variable(variable) {} 12566 12567 void VisitDeclRefExpr(DeclRefExpr *ref) { 12568 if (ref->getDecl() == Variable && !Capturer) 12569 Capturer = ref; 12570 } 12571 12572 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 12573 if (Capturer) return; 12574 Visit(ref->getBase()); 12575 if (Capturer && ref->isFreeIvar()) 12576 Capturer = ref; 12577 } 12578 12579 void VisitBlockExpr(BlockExpr *block) { 12580 // Look inside nested blocks 12581 if (block->getBlockDecl()->capturesVariable(Variable)) 12582 Visit(block->getBlockDecl()->getBody()); 12583 } 12584 12585 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 12586 if (Capturer) return; 12587 if (OVE->getSourceExpr()) 12588 Visit(OVE->getSourceExpr()); 12589 } 12590 12591 void VisitBinaryOperator(BinaryOperator *BinOp) { 12592 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 12593 return; 12594 Expr *LHS = BinOp->getLHS(); 12595 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 12596 if (DRE->getDecl() != Variable) 12597 return; 12598 if (Expr *RHS = BinOp->getRHS()) { 12599 RHS = RHS->IgnoreParenCasts(); 12600 llvm::APSInt Value; 12601 VarWillBeReased = 12602 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 12603 } 12604 } 12605 } 12606 }; 12607 12608 } // namespace 12609 12610 /// Check whether the given argument is a block which captures a 12611 /// variable. 12612 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 12613 assert(owner.Variable && owner.Loc.isValid()); 12614 12615 e = e->IgnoreParenCasts(); 12616 12617 // Look through [^{...} copy] and Block_copy(^{...}). 12618 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 12619 Selector Cmd = ME->getSelector(); 12620 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 12621 e = ME->getInstanceReceiver(); 12622 if (!e) 12623 return nullptr; 12624 e = e->IgnoreParenCasts(); 12625 } 12626 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 12627 if (CE->getNumArgs() == 1) { 12628 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 12629 if (Fn) { 12630 const IdentifierInfo *FnI = Fn->getIdentifier(); 12631 if (FnI && FnI->isStr("_Block_copy")) { 12632 e = CE->getArg(0)->IgnoreParenCasts(); 12633 } 12634 } 12635 } 12636 } 12637 12638 BlockExpr *block = dyn_cast<BlockExpr>(e); 12639 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 12640 return nullptr; 12641 12642 FindCaptureVisitor visitor(S.Context, owner.Variable); 12643 visitor.Visit(block->getBlockDecl()->getBody()); 12644 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 12645 } 12646 12647 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 12648 RetainCycleOwner &owner) { 12649 assert(capturer); 12650 assert(owner.Variable && owner.Loc.isValid()); 12651 12652 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 12653 << owner.Variable << capturer->getSourceRange(); 12654 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 12655 << owner.Indirect << owner.Range; 12656 } 12657 12658 /// Check for a keyword selector that starts with the word 'add' or 12659 /// 'set'. 12660 static bool isSetterLikeSelector(Selector sel) { 12661 if (sel.isUnarySelector()) return false; 12662 12663 StringRef str = sel.getNameForSlot(0); 12664 while (!str.empty() && str.front() == '_') str = str.substr(1); 12665 if (str.startswith("set")) 12666 str = str.substr(3); 12667 else if (str.startswith("add")) { 12668 // Specially whitelist 'addOperationWithBlock:'. 12669 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12670 return false; 12671 str = str.substr(3); 12672 } 12673 else 12674 return false; 12675 12676 if (str.empty()) return true; 12677 return !isLowercase(str.front()); 12678 } 12679 12680 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12681 ObjCMessageExpr *Message) { 12682 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12683 Message->getReceiverInterface(), 12684 NSAPI::ClassId_NSMutableArray); 12685 if (!IsMutableArray) { 12686 return None; 12687 } 12688 12689 Selector Sel = Message->getSelector(); 12690 12691 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12692 S.NSAPIObj->getNSArrayMethodKind(Sel); 12693 if (!MKOpt) { 12694 return None; 12695 } 12696 12697 NSAPI::NSArrayMethodKind MK = *MKOpt; 12698 12699 switch (MK) { 12700 case NSAPI::NSMutableArr_addObject: 12701 case NSAPI::NSMutableArr_insertObjectAtIndex: 12702 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12703 return 0; 12704 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12705 return 1; 12706 12707 default: 12708 return None; 12709 } 12710 12711 return None; 12712 } 12713 12714 static 12715 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12716 ObjCMessageExpr *Message) { 12717 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12718 Message->getReceiverInterface(), 12719 NSAPI::ClassId_NSMutableDictionary); 12720 if (!IsMutableDictionary) { 12721 return None; 12722 } 12723 12724 Selector Sel = Message->getSelector(); 12725 12726 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 12727 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 12728 if (!MKOpt) { 12729 return None; 12730 } 12731 12732 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 12733 12734 switch (MK) { 12735 case NSAPI::NSMutableDict_setObjectForKey: 12736 case NSAPI::NSMutableDict_setValueForKey: 12737 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 12738 return 0; 12739 12740 default: 12741 return None; 12742 } 12743 12744 return None; 12745 } 12746 12747 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 12748 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 12749 Message->getReceiverInterface(), 12750 NSAPI::ClassId_NSMutableSet); 12751 12752 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 12753 Message->getReceiverInterface(), 12754 NSAPI::ClassId_NSMutableOrderedSet); 12755 if (!IsMutableSet && !IsMutableOrderedSet) { 12756 return None; 12757 } 12758 12759 Selector Sel = Message->getSelector(); 12760 12761 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 12762 if (!MKOpt) { 12763 return None; 12764 } 12765 12766 NSAPI::NSSetMethodKind MK = *MKOpt; 12767 12768 switch (MK) { 12769 case NSAPI::NSMutableSet_addObject: 12770 case NSAPI::NSOrderedSet_setObjectAtIndex: 12771 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 12772 case NSAPI::NSOrderedSet_insertObjectAtIndex: 12773 return 0; 12774 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 12775 return 1; 12776 } 12777 12778 return None; 12779 } 12780 12781 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 12782 if (!Message->isInstanceMessage()) { 12783 return; 12784 } 12785 12786 Optional<int> ArgOpt; 12787 12788 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 12789 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 12790 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 12791 return; 12792 } 12793 12794 int ArgIndex = *ArgOpt; 12795 12796 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 12797 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 12798 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 12799 } 12800 12801 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 12802 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12803 if (ArgRE->isObjCSelfExpr()) { 12804 Diag(Message->getSourceRange().getBegin(), 12805 diag::warn_objc_circular_container) 12806 << ArgRE->getDecl() << StringRef("'super'"); 12807 } 12808 } 12809 } else { 12810 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 12811 12812 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 12813 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 12814 } 12815 12816 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 12817 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12818 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 12819 ValueDecl *Decl = ReceiverRE->getDecl(); 12820 Diag(Message->getSourceRange().getBegin(), 12821 diag::warn_objc_circular_container) 12822 << Decl << Decl; 12823 if (!ArgRE->isObjCSelfExpr()) { 12824 Diag(Decl->getLocation(), 12825 diag::note_objc_circular_container_declared_here) 12826 << Decl; 12827 } 12828 } 12829 } 12830 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12831 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12832 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12833 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12834 Diag(Message->getSourceRange().getBegin(), 12835 diag::warn_objc_circular_container) 12836 << Decl << Decl; 12837 Diag(Decl->getLocation(), 12838 diag::note_objc_circular_container_declared_here) 12839 << Decl; 12840 } 12841 } 12842 } 12843 } 12844 } 12845 12846 /// Check a message send to see if it's likely to cause a retain cycle. 12847 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 12848 // Only check instance methods whose selector looks like a setter. 12849 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12850 return; 12851 12852 // Try to find a variable that the receiver is strongly owned by. 12853 RetainCycleOwner owner; 12854 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12855 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12856 return; 12857 } else { 12858 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12859 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12860 owner.Loc = msg->getSuperLoc(); 12861 owner.Range = msg->getSuperLoc(); 12862 } 12863 12864 // Check whether the receiver is captured by any of the arguments. 12865 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12866 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12867 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12868 // noescape blocks should not be retained by the method. 12869 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 12870 continue; 12871 return diagnoseRetainCycle(*this, capturer, owner); 12872 } 12873 } 12874 } 12875 12876 /// Check a property assign to see if it's likely to cause a retain cycle. 12877 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 12878 RetainCycleOwner owner; 12879 if (!findRetainCycleOwner(*this, receiver, owner)) 12880 return; 12881 12882 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 12883 diagnoseRetainCycle(*this, capturer, owner); 12884 } 12885 12886 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 12887 RetainCycleOwner Owner; 12888 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 12889 return; 12890 12891 // Because we don't have an expression for the variable, we have to set the 12892 // location explicitly here. 12893 Owner.Loc = Var->getLocation(); 12894 Owner.Range = Var->getSourceRange(); 12895 12896 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 12897 diagnoseRetainCycle(*this, Capturer, Owner); 12898 } 12899 12900 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 12901 Expr *RHS, bool isProperty) { 12902 // Check if RHS is an Objective-C object literal, which also can get 12903 // immediately zapped in a weak reference. Note that we explicitly 12904 // allow ObjCStringLiterals, since those are designed to never really die. 12905 RHS = RHS->IgnoreParenImpCasts(); 12906 12907 // This enum needs to match with the 'select' in 12908 // warn_objc_arc_literal_assign (off-by-1). 12909 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 12910 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 12911 return false; 12912 12913 S.Diag(Loc, diag::warn_arc_literal_assign) 12914 << (unsigned) Kind 12915 << (isProperty ? 0 : 1) 12916 << RHS->getSourceRange(); 12917 12918 return true; 12919 } 12920 12921 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 12922 Qualifiers::ObjCLifetime LT, 12923 Expr *RHS, bool isProperty) { 12924 // Strip off any implicit cast added to get to the one ARC-specific. 12925 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12926 if (cast->getCastKind() == CK_ARCConsumeObject) { 12927 S.Diag(Loc, diag::warn_arc_retained_assign) 12928 << (LT == Qualifiers::OCL_ExplicitNone) 12929 << (isProperty ? 0 : 1) 12930 << RHS->getSourceRange(); 12931 return true; 12932 } 12933 RHS = cast->getSubExpr(); 12934 } 12935 12936 if (LT == Qualifiers::OCL_Weak && 12937 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 12938 return true; 12939 12940 return false; 12941 } 12942 12943 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 12944 QualType LHS, Expr *RHS) { 12945 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 12946 12947 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 12948 return false; 12949 12950 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 12951 return true; 12952 12953 return false; 12954 } 12955 12956 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 12957 Expr *LHS, Expr *RHS) { 12958 QualType LHSType; 12959 // PropertyRef on LHS type need be directly obtained from 12960 // its declaration as it has a PseudoType. 12961 ObjCPropertyRefExpr *PRE 12962 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 12963 if (PRE && !PRE->isImplicitProperty()) { 12964 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12965 if (PD) 12966 LHSType = PD->getType(); 12967 } 12968 12969 if (LHSType.isNull()) 12970 LHSType = LHS->getType(); 12971 12972 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 12973 12974 if (LT == Qualifiers::OCL_Weak) { 12975 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 12976 getCurFunction()->markSafeWeakUse(LHS); 12977 } 12978 12979 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 12980 return; 12981 12982 // FIXME. Check for other life times. 12983 if (LT != Qualifiers::OCL_None) 12984 return; 12985 12986 if (PRE) { 12987 if (PRE->isImplicitProperty()) 12988 return; 12989 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12990 if (!PD) 12991 return; 12992 12993 unsigned Attributes = PD->getPropertyAttributes(); 12994 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 12995 // when 'assign' attribute was not explicitly specified 12996 // by user, ignore it and rely on property type itself 12997 // for lifetime info. 12998 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 12999 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13000 LHSType->isObjCRetainableType()) 13001 return; 13002 13003 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13004 if (cast->getCastKind() == CK_ARCConsumeObject) { 13005 Diag(Loc, diag::warn_arc_retained_property_assign) 13006 << RHS->getSourceRange(); 13007 return; 13008 } 13009 RHS = cast->getSubExpr(); 13010 } 13011 } 13012 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13013 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13014 return; 13015 } 13016 } 13017 } 13018 13019 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13020 13021 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13022 SourceLocation StmtLoc, 13023 const NullStmt *Body) { 13024 // Do not warn if the body is a macro that expands to nothing, e.g: 13025 // 13026 // #define CALL(x) 13027 // if (condition) 13028 // CALL(0); 13029 if (Body->hasLeadingEmptyMacro()) 13030 return false; 13031 13032 // Get line numbers of statement and body. 13033 bool StmtLineInvalid; 13034 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13035 &StmtLineInvalid); 13036 if (StmtLineInvalid) 13037 return false; 13038 13039 bool BodyLineInvalid; 13040 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13041 &BodyLineInvalid); 13042 if (BodyLineInvalid) 13043 return false; 13044 13045 // Warn if null statement and body are on the same line. 13046 if (StmtLine != BodyLine) 13047 return false; 13048 13049 return true; 13050 } 13051 13052 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13053 const Stmt *Body, 13054 unsigned DiagID) { 13055 // Since this is a syntactic check, don't emit diagnostic for template 13056 // instantiations, this just adds noise. 13057 if (CurrentInstantiationScope) 13058 return; 13059 13060 // The body should be a null statement. 13061 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13062 if (!NBody) 13063 return; 13064 13065 // Do the usual checks. 13066 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13067 return; 13068 13069 Diag(NBody->getSemiLoc(), DiagID); 13070 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13071 } 13072 13073 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13074 const Stmt *PossibleBody) { 13075 assert(!CurrentInstantiationScope); // Ensured by caller 13076 13077 SourceLocation StmtLoc; 13078 const Stmt *Body; 13079 unsigned DiagID; 13080 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13081 StmtLoc = FS->getRParenLoc(); 13082 Body = FS->getBody(); 13083 DiagID = diag::warn_empty_for_body; 13084 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13085 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13086 Body = WS->getBody(); 13087 DiagID = diag::warn_empty_while_body; 13088 } else 13089 return; // Neither `for' nor `while'. 13090 13091 // The body should be a null statement. 13092 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13093 if (!NBody) 13094 return; 13095 13096 // Skip expensive checks if diagnostic is disabled. 13097 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13098 return; 13099 13100 // Do the usual checks. 13101 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13102 return; 13103 13104 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13105 // noise level low, emit diagnostics only if for/while is followed by a 13106 // CompoundStmt, e.g.: 13107 // for (int i = 0; i < n; i++); 13108 // { 13109 // a(i); 13110 // } 13111 // or if for/while is followed by a statement with more indentation 13112 // than for/while itself: 13113 // for (int i = 0; i < n; i++); 13114 // a(i); 13115 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13116 if (!ProbableTypo) { 13117 bool BodyColInvalid; 13118 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13119 PossibleBody->getBeginLoc(), &BodyColInvalid); 13120 if (BodyColInvalid) 13121 return; 13122 13123 bool StmtColInvalid; 13124 unsigned StmtCol = 13125 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13126 if (StmtColInvalid) 13127 return; 13128 13129 if (BodyCol > StmtCol) 13130 ProbableTypo = true; 13131 } 13132 13133 if (ProbableTypo) { 13134 Diag(NBody->getSemiLoc(), DiagID); 13135 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13136 } 13137 } 13138 13139 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13140 13141 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13142 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13143 SourceLocation OpLoc) { 13144 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13145 return; 13146 13147 if (inTemplateInstantiation()) 13148 return; 13149 13150 // Strip parens and casts away. 13151 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13152 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13153 13154 // Check for a call expression 13155 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13156 if (!CE || CE->getNumArgs() != 1) 13157 return; 13158 13159 // Check for a call to std::move 13160 if (!CE->isCallToStdMove()) 13161 return; 13162 13163 // Get argument from std::move 13164 RHSExpr = CE->getArg(0); 13165 13166 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13167 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13168 13169 // Two DeclRefExpr's, check that the decls are the same. 13170 if (LHSDeclRef && RHSDeclRef) { 13171 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13172 return; 13173 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13174 RHSDeclRef->getDecl()->getCanonicalDecl()) 13175 return; 13176 13177 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13178 << LHSExpr->getSourceRange() 13179 << RHSExpr->getSourceRange(); 13180 return; 13181 } 13182 13183 // Member variables require a different approach to check for self moves. 13184 // MemberExpr's are the same if every nested MemberExpr refers to the same 13185 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13186 // the base Expr's are CXXThisExpr's. 13187 const Expr *LHSBase = LHSExpr; 13188 const Expr *RHSBase = RHSExpr; 13189 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13190 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13191 if (!LHSME || !RHSME) 13192 return; 13193 13194 while (LHSME && RHSME) { 13195 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13196 RHSME->getMemberDecl()->getCanonicalDecl()) 13197 return; 13198 13199 LHSBase = LHSME->getBase(); 13200 RHSBase = RHSME->getBase(); 13201 LHSME = dyn_cast<MemberExpr>(LHSBase); 13202 RHSME = dyn_cast<MemberExpr>(RHSBase); 13203 } 13204 13205 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13206 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13207 if (LHSDeclRef && RHSDeclRef) { 13208 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13209 return; 13210 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13211 RHSDeclRef->getDecl()->getCanonicalDecl()) 13212 return; 13213 13214 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13215 << LHSExpr->getSourceRange() 13216 << RHSExpr->getSourceRange(); 13217 return; 13218 } 13219 13220 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13221 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13222 << LHSExpr->getSourceRange() 13223 << RHSExpr->getSourceRange(); 13224 } 13225 13226 //===--- Layout compatibility ----------------------------------------------// 13227 13228 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13229 13230 /// Check if two enumeration types are layout-compatible. 13231 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13232 // C++11 [dcl.enum] p8: 13233 // Two enumeration types are layout-compatible if they have the same 13234 // underlying type. 13235 return ED1->isComplete() && ED2->isComplete() && 13236 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13237 } 13238 13239 /// Check if two fields are layout-compatible. 13240 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13241 FieldDecl *Field2) { 13242 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13243 return false; 13244 13245 if (Field1->isBitField() != Field2->isBitField()) 13246 return false; 13247 13248 if (Field1->isBitField()) { 13249 // Make sure that the bit-fields are the same length. 13250 unsigned Bits1 = Field1->getBitWidthValue(C); 13251 unsigned Bits2 = Field2->getBitWidthValue(C); 13252 13253 if (Bits1 != Bits2) 13254 return false; 13255 } 13256 13257 return true; 13258 } 13259 13260 /// Check if two standard-layout structs are layout-compatible. 13261 /// (C++11 [class.mem] p17) 13262 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13263 RecordDecl *RD2) { 13264 // If both records are C++ classes, check that base classes match. 13265 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13266 // If one of records is a CXXRecordDecl we are in C++ mode, 13267 // thus the other one is a CXXRecordDecl, too. 13268 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13269 // Check number of base classes. 13270 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13271 return false; 13272 13273 // Check the base classes. 13274 for (CXXRecordDecl::base_class_const_iterator 13275 Base1 = D1CXX->bases_begin(), 13276 BaseEnd1 = D1CXX->bases_end(), 13277 Base2 = D2CXX->bases_begin(); 13278 Base1 != BaseEnd1; 13279 ++Base1, ++Base2) { 13280 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13281 return false; 13282 } 13283 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13284 // If only RD2 is a C++ class, it should have zero base classes. 13285 if (D2CXX->getNumBases() > 0) 13286 return false; 13287 } 13288 13289 // Check the fields. 13290 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13291 Field2End = RD2->field_end(), 13292 Field1 = RD1->field_begin(), 13293 Field1End = RD1->field_end(); 13294 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13295 if (!isLayoutCompatible(C, *Field1, *Field2)) 13296 return false; 13297 } 13298 if (Field1 != Field1End || Field2 != Field2End) 13299 return false; 13300 13301 return true; 13302 } 13303 13304 /// Check if two standard-layout unions are layout-compatible. 13305 /// (C++11 [class.mem] p18) 13306 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13307 RecordDecl *RD2) { 13308 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13309 for (auto *Field2 : RD2->fields()) 13310 UnmatchedFields.insert(Field2); 13311 13312 for (auto *Field1 : RD1->fields()) { 13313 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13314 I = UnmatchedFields.begin(), 13315 E = UnmatchedFields.end(); 13316 13317 for ( ; I != E; ++I) { 13318 if (isLayoutCompatible(C, Field1, *I)) { 13319 bool Result = UnmatchedFields.erase(*I); 13320 (void) Result; 13321 assert(Result); 13322 break; 13323 } 13324 } 13325 if (I == E) 13326 return false; 13327 } 13328 13329 return UnmatchedFields.empty(); 13330 } 13331 13332 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13333 RecordDecl *RD2) { 13334 if (RD1->isUnion() != RD2->isUnion()) 13335 return false; 13336 13337 if (RD1->isUnion()) 13338 return isLayoutCompatibleUnion(C, RD1, RD2); 13339 else 13340 return isLayoutCompatibleStruct(C, RD1, RD2); 13341 } 13342 13343 /// Check if two types are layout-compatible in C++11 sense. 13344 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13345 if (T1.isNull() || T2.isNull()) 13346 return false; 13347 13348 // C++11 [basic.types] p11: 13349 // If two types T1 and T2 are the same type, then T1 and T2 are 13350 // layout-compatible types. 13351 if (C.hasSameType(T1, T2)) 13352 return true; 13353 13354 T1 = T1.getCanonicalType().getUnqualifiedType(); 13355 T2 = T2.getCanonicalType().getUnqualifiedType(); 13356 13357 const Type::TypeClass TC1 = T1->getTypeClass(); 13358 const Type::TypeClass TC2 = T2->getTypeClass(); 13359 13360 if (TC1 != TC2) 13361 return false; 13362 13363 if (TC1 == Type::Enum) { 13364 return isLayoutCompatible(C, 13365 cast<EnumType>(T1)->getDecl(), 13366 cast<EnumType>(T2)->getDecl()); 13367 } else if (TC1 == Type::Record) { 13368 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13369 return false; 13370 13371 return isLayoutCompatible(C, 13372 cast<RecordType>(T1)->getDecl(), 13373 cast<RecordType>(T2)->getDecl()); 13374 } 13375 13376 return false; 13377 } 13378 13379 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13380 13381 /// Given a type tag expression find the type tag itself. 13382 /// 13383 /// \param TypeExpr Type tag expression, as it appears in user's code. 13384 /// 13385 /// \param VD Declaration of an identifier that appears in a type tag. 13386 /// 13387 /// \param MagicValue Type tag magic value. 13388 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13389 const ValueDecl **VD, uint64_t *MagicValue) { 13390 while(true) { 13391 if (!TypeExpr) 13392 return false; 13393 13394 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13395 13396 switch (TypeExpr->getStmtClass()) { 13397 case Stmt::UnaryOperatorClass: { 13398 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13399 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13400 TypeExpr = UO->getSubExpr(); 13401 continue; 13402 } 13403 return false; 13404 } 13405 13406 case Stmt::DeclRefExprClass: { 13407 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 13408 *VD = DRE->getDecl(); 13409 return true; 13410 } 13411 13412 case Stmt::IntegerLiteralClass: { 13413 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 13414 llvm::APInt MagicValueAPInt = IL->getValue(); 13415 if (MagicValueAPInt.getActiveBits() <= 64) { 13416 *MagicValue = MagicValueAPInt.getZExtValue(); 13417 return true; 13418 } else 13419 return false; 13420 } 13421 13422 case Stmt::BinaryConditionalOperatorClass: 13423 case Stmt::ConditionalOperatorClass: { 13424 const AbstractConditionalOperator *ACO = 13425 cast<AbstractConditionalOperator>(TypeExpr); 13426 bool Result; 13427 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 13428 if (Result) 13429 TypeExpr = ACO->getTrueExpr(); 13430 else 13431 TypeExpr = ACO->getFalseExpr(); 13432 continue; 13433 } 13434 return false; 13435 } 13436 13437 case Stmt::BinaryOperatorClass: { 13438 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 13439 if (BO->getOpcode() == BO_Comma) { 13440 TypeExpr = BO->getRHS(); 13441 continue; 13442 } 13443 return false; 13444 } 13445 13446 default: 13447 return false; 13448 } 13449 } 13450 } 13451 13452 /// Retrieve the C type corresponding to type tag TypeExpr. 13453 /// 13454 /// \param TypeExpr Expression that specifies a type tag. 13455 /// 13456 /// \param MagicValues Registered magic values. 13457 /// 13458 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 13459 /// kind. 13460 /// 13461 /// \param TypeInfo Information about the corresponding C type. 13462 /// 13463 /// \returns true if the corresponding C type was found. 13464 static bool GetMatchingCType( 13465 const IdentifierInfo *ArgumentKind, 13466 const Expr *TypeExpr, const ASTContext &Ctx, 13467 const llvm::DenseMap<Sema::TypeTagMagicValue, 13468 Sema::TypeTagData> *MagicValues, 13469 bool &FoundWrongKind, 13470 Sema::TypeTagData &TypeInfo) { 13471 FoundWrongKind = false; 13472 13473 // Variable declaration that has type_tag_for_datatype attribute. 13474 const ValueDecl *VD = nullptr; 13475 13476 uint64_t MagicValue; 13477 13478 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 13479 return false; 13480 13481 if (VD) { 13482 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 13483 if (I->getArgumentKind() != ArgumentKind) { 13484 FoundWrongKind = true; 13485 return false; 13486 } 13487 TypeInfo.Type = I->getMatchingCType(); 13488 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 13489 TypeInfo.MustBeNull = I->getMustBeNull(); 13490 return true; 13491 } 13492 return false; 13493 } 13494 13495 if (!MagicValues) 13496 return false; 13497 13498 llvm::DenseMap<Sema::TypeTagMagicValue, 13499 Sema::TypeTagData>::const_iterator I = 13500 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 13501 if (I == MagicValues->end()) 13502 return false; 13503 13504 TypeInfo = I->second; 13505 return true; 13506 } 13507 13508 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 13509 uint64_t MagicValue, QualType Type, 13510 bool LayoutCompatible, 13511 bool MustBeNull) { 13512 if (!TypeTagForDatatypeMagicValues) 13513 TypeTagForDatatypeMagicValues.reset( 13514 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 13515 13516 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 13517 (*TypeTagForDatatypeMagicValues)[Magic] = 13518 TypeTagData(Type, LayoutCompatible, MustBeNull); 13519 } 13520 13521 static bool IsSameCharType(QualType T1, QualType T2) { 13522 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 13523 if (!BT1) 13524 return false; 13525 13526 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 13527 if (!BT2) 13528 return false; 13529 13530 BuiltinType::Kind T1Kind = BT1->getKind(); 13531 BuiltinType::Kind T2Kind = BT2->getKind(); 13532 13533 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 13534 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 13535 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 13536 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 13537 } 13538 13539 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 13540 const ArrayRef<const Expr *> ExprArgs, 13541 SourceLocation CallSiteLoc) { 13542 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 13543 bool IsPointerAttr = Attr->getIsPointer(); 13544 13545 // Retrieve the argument representing the 'type_tag'. 13546 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 13547 if (TypeTagIdxAST >= ExprArgs.size()) { 13548 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13549 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 13550 return; 13551 } 13552 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 13553 bool FoundWrongKind; 13554 TypeTagData TypeInfo; 13555 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 13556 TypeTagForDatatypeMagicValues.get(), 13557 FoundWrongKind, TypeInfo)) { 13558 if (FoundWrongKind) 13559 Diag(TypeTagExpr->getExprLoc(), 13560 diag::warn_type_tag_for_datatype_wrong_kind) 13561 << TypeTagExpr->getSourceRange(); 13562 return; 13563 } 13564 13565 // Retrieve the argument representing the 'arg_idx'. 13566 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 13567 if (ArgumentIdxAST >= ExprArgs.size()) { 13568 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13569 << 1 << Attr->getArgumentIdx().getSourceIndex(); 13570 return; 13571 } 13572 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 13573 if (IsPointerAttr) { 13574 // Skip implicit cast of pointer to `void *' (as a function argument). 13575 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 13576 if (ICE->getType()->isVoidPointerType() && 13577 ICE->getCastKind() == CK_BitCast) 13578 ArgumentExpr = ICE->getSubExpr(); 13579 } 13580 QualType ArgumentType = ArgumentExpr->getType(); 13581 13582 // Passing a `void*' pointer shouldn't trigger a warning. 13583 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 13584 return; 13585 13586 if (TypeInfo.MustBeNull) { 13587 // Type tag with matching void type requires a null pointer. 13588 if (!ArgumentExpr->isNullPointerConstant(Context, 13589 Expr::NPC_ValueDependentIsNotNull)) { 13590 Diag(ArgumentExpr->getExprLoc(), 13591 diag::warn_type_safety_null_pointer_required) 13592 << ArgumentKind->getName() 13593 << ArgumentExpr->getSourceRange() 13594 << TypeTagExpr->getSourceRange(); 13595 } 13596 return; 13597 } 13598 13599 QualType RequiredType = TypeInfo.Type; 13600 if (IsPointerAttr) 13601 RequiredType = Context.getPointerType(RequiredType); 13602 13603 bool mismatch = false; 13604 if (!TypeInfo.LayoutCompatible) { 13605 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 13606 13607 // C++11 [basic.fundamental] p1: 13608 // Plain char, signed char, and unsigned char are three distinct types. 13609 // 13610 // But we treat plain `char' as equivalent to `signed char' or `unsigned 13611 // char' depending on the current char signedness mode. 13612 if (mismatch) 13613 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 13614 RequiredType->getPointeeType())) || 13615 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 13616 mismatch = false; 13617 } else 13618 if (IsPointerAttr) 13619 mismatch = !isLayoutCompatible(Context, 13620 ArgumentType->getPointeeType(), 13621 RequiredType->getPointeeType()); 13622 else 13623 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 13624 13625 if (mismatch) 13626 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 13627 << ArgumentType << ArgumentKind 13628 << TypeInfo.LayoutCompatible << RequiredType 13629 << ArgumentExpr->getSourceRange() 13630 << TypeTagExpr->getSourceRange(); 13631 } 13632 13633 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 13634 CharUnits Alignment) { 13635 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 13636 } 13637 13638 void Sema::DiagnoseMisalignedMembers() { 13639 for (MisalignedMember &m : MisalignedMembers) { 13640 const NamedDecl *ND = m.RD; 13641 if (ND->getName().empty()) { 13642 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 13643 ND = TD; 13644 } 13645 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 13646 << m.MD << ND << m.E->getSourceRange(); 13647 } 13648 MisalignedMembers.clear(); 13649 } 13650 13651 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 13652 E = E->IgnoreParens(); 13653 if (!T->isPointerType() && !T->isIntegerType()) 13654 return; 13655 if (isa<UnaryOperator>(E) && 13656 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13657 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13658 if (isa<MemberExpr>(Op)) { 13659 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 13660 MisalignedMember(Op)); 13661 if (MA != MisalignedMembers.end() && 13662 (T->isIntegerType() || 13663 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13664 Context.getTypeAlignInChars( 13665 T->getPointeeType()) <= MA->Alignment)))) 13666 MisalignedMembers.erase(MA); 13667 } 13668 } 13669 } 13670 13671 void Sema::RefersToMemberWithReducedAlignment( 13672 Expr *E, 13673 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13674 Action) { 13675 const auto *ME = dyn_cast<MemberExpr>(E); 13676 if (!ME) 13677 return; 13678 13679 // No need to check expressions with an __unaligned-qualified type. 13680 if (E->getType().getQualifiers().hasUnaligned()) 13681 return; 13682 13683 // For a chain of MemberExpr like "a.b.c.d" this list 13684 // will keep FieldDecl's like [d, c, b]. 13685 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13686 const MemberExpr *TopME = nullptr; 13687 bool AnyIsPacked = false; 13688 do { 13689 QualType BaseType = ME->getBase()->getType(); 13690 if (ME->isArrow()) 13691 BaseType = BaseType->getPointeeType(); 13692 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13693 if (RD->isInvalidDecl()) 13694 return; 13695 13696 ValueDecl *MD = ME->getMemberDecl(); 13697 auto *FD = dyn_cast<FieldDecl>(MD); 13698 // We do not care about non-data members. 13699 if (!FD || FD->isInvalidDecl()) 13700 return; 13701 13702 AnyIsPacked = 13703 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13704 ReverseMemberChain.push_back(FD); 13705 13706 TopME = ME; 13707 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13708 } while (ME); 13709 assert(TopME && "We did not compute a topmost MemberExpr!"); 13710 13711 // Not the scope of this diagnostic. 13712 if (!AnyIsPacked) 13713 return; 13714 13715 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13716 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13717 // TODO: The innermost base of the member expression may be too complicated. 13718 // For now, just disregard these cases. This is left for future 13719 // improvement. 13720 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13721 return; 13722 13723 // Alignment expected by the whole expression. 13724 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13725 13726 // No need to do anything else with this case. 13727 if (ExpectedAlignment.isOne()) 13728 return; 13729 13730 // Synthesize offset of the whole access. 13731 CharUnits Offset; 13732 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 13733 I++) { 13734 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 13735 } 13736 13737 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 13738 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 13739 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 13740 13741 // The base expression of the innermost MemberExpr may give 13742 // stronger guarantees than the class containing the member. 13743 if (DRE && !TopME->isArrow()) { 13744 const ValueDecl *VD = DRE->getDecl(); 13745 if (!VD->getType()->isReferenceType()) 13746 CompleteObjectAlignment = 13747 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 13748 } 13749 13750 // Check if the synthesized offset fulfills the alignment. 13751 if (Offset % ExpectedAlignment != 0 || 13752 // It may fulfill the offset it but the effective alignment may still be 13753 // lower than the expected expression alignment. 13754 CompleteObjectAlignment < ExpectedAlignment) { 13755 // If this happens, we want to determine a sensible culprit of this. 13756 // Intuitively, watching the chain of member expressions from right to 13757 // left, we start with the required alignment (as required by the field 13758 // type) but some packed attribute in that chain has reduced the alignment. 13759 // It may happen that another packed structure increases it again. But if 13760 // we are here such increase has not been enough. So pointing the first 13761 // FieldDecl that either is packed or else its RecordDecl is, 13762 // seems reasonable. 13763 FieldDecl *FD = nullptr; 13764 CharUnits Alignment; 13765 for (FieldDecl *FDI : ReverseMemberChain) { 13766 if (FDI->hasAttr<PackedAttr>() || 13767 FDI->getParent()->hasAttr<PackedAttr>()) { 13768 FD = FDI; 13769 Alignment = std::min( 13770 Context.getTypeAlignInChars(FD->getType()), 13771 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 13772 break; 13773 } 13774 } 13775 assert(FD && "We did not find a packed FieldDecl!"); 13776 Action(E, FD->getParent(), FD, Alignment); 13777 } 13778 } 13779 13780 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 13781 using namespace std::placeholders; 13782 13783 RefersToMemberWithReducedAlignment( 13784 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 13785 _2, _3, _4)); 13786 } 13787