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/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/Stmt.h" 34 #include "clang/AST/TemplateBase.h" 35 #include "clang/AST/Type.h" 36 #include "clang/AST/TypeLoc.h" 37 #include "clang/AST/UnresolvedSet.h" 38 #include "clang/Analysis/Analyses/FormatString.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 if (TheCall->getNumArgs() <= SizeIdx || 243 TheCall->getNumArgs() <= DstSizeIdx) 244 return; 245 246 const Expr *SizeArg = TheCall->getArg(SizeIdx); 247 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 248 249 llvm::APSInt Size, DstSize; 250 251 // find out if both sizes are known at compile time 252 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 253 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 254 return; 255 256 if (Size.ule(DstSize)) 257 return; 258 259 // confirmed overflow so generate the diagnostic. 260 IdentifierInfo *FnName = FDecl->getIdentifier(); 261 SourceLocation SL = TheCall->getBeginLoc(); 262 SourceRange SR = TheCall->getSourceRange(); 263 264 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 265 } 266 267 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 268 if (checkArgCount(S, BuiltinCall, 2)) 269 return true; 270 271 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 272 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 273 Expr *Call = BuiltinCall->getArg(0); 274 Expr *Chain = BuiltinCall->getArg(1); 275 276 if (Call->getStmtClass() != Stmt::CallExprClass) { 277 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 278 << Call->getSourceRange(); 279 return true; 280 } 281 282 auto CE = cast<CallExpr>(Call); 283 if (CE->getCallee()->getType()->isBlockPointerType()) { 284 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 285 << Call->getSourceRange(); 286 return true; 287 } 288 289 const Decl *TargetDecl = CE->getCalleeDecl(); 290 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 291 if (FD->getBuiltinID()) { 292 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 293 << Call->getSourceRange(); 294 return true; 295 } 296 297 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 298 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 299 << Call->getSourceRange(); 300 return true; 301 } 302 303 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 304 if (ChainResult.isInvalid()) 305 return true; 306 if (!ChainResult.get()->getType()->isPointerType()) { 307 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 308 << Chain->getSourceRange(); 309 return true; 310 } 311 312 QualType ReturnTy = CE->getCallReturnType(S.Context); 313 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 314 QualType BuiltinTy = S.Context.getFunctionType( 315 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 316 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 317 318 Builtin = 319 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 320 321 BuiltinCall->setType(CE->getType()); 322 BuiltinCall->setValueKind(CE->getValueKind()); 323 BuiltinCall->setObjectKind(CE->getObjectKind()); 324 BuiltinCall->setCallee(Builtin); 325 BuiltinCall->setArg(1, ChainResult.get()); 326 327 return false; 328 } 329 330 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 331 Scope::ScopeFlags NeededScopeFlags, 332 unsigned DiagID) { 333 // Scopes aren't available during instantiation. Fortunately, builtin 334 // functions cannot be template args so they cannot be formed through template 335 // instantiation. Therefore checking once during the parse is sufficient. 336 if (SemaRef.inTemplateInstantiation()) 337 return false; 338 339 Scope *S = SemaRef.getCurScope(); 340 while (S && !S->isSEHExceptScope()) 341 S = S->getParent(); 342 if (!S || !(S->getFlags() & NeededScopeFlags)) { 343 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 344 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 345 << DRE->getDecl()->getIdentifier(); 346 return true; 347 } 348 349 return false; 350 } 351 352 static inline bool isBlockPointer(Expr *Arg) { 353 return Arg->getType()->isBlockPointerType(); 354 } 355 356 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 357 /// void*, which is a requirement of device side enqueue. 358 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 359 const BlockPointerType *BPT = 360 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 361 ArrayRef<QualType> Params = 362 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 363 unsigned ArgCounter = 0; 364 bool IllegalParams = false; 365 // Iterate through the block parameters until either one is found that is not 366 // a local void*, or the block is valid. 367 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 368 I != E; ++I, ++ArgCounter) { 369 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 370 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 371 LangAS::opencl_local) { 372 // Get the location of the error. If a block literal has been passed 373 // (BlockExpr) then we can point straight to the offending argument, 374 // else we just point to the variable reference. 375 SourceLocation ErrorLoc; 376 if (isa<BlockExpr>(BlockArg)) { 377 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 378 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 379 } else if (isa<DeclRefExpr>(BlockArg)) { 380 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 381 } 382 S.Diag(ErrorLoc, 383 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 384 IllegalParams = true; 385 } 386 } 387 388 return IllegalParams; 389 } 390 391 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 392 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 393 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 394 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 395 return true; 396 } 397 return false; 398 } 399 400 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 401 if (checkArgCount(S, TheCall, 2)) 402 return true; 403 404 if (checkOpenCLSubgroupExt(S, TheCall)) 405 return true; 406 407 // First argument is an ndrange_t type. 408 Expr *NDRangeArg = TheCall->getArg(0); 409 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 410 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 411 << TheCall->getDirectCallee() << "'ndrange_t'"; 412 return true; 413 } 414 415 Expr *BlockArg = TheCall->getArg(1); 416 if (!isBlockPointer(BlockArg)) { 417 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 418 << TheCall->getDirectCallee() << "block"; 419 return true; 420 } 421 return checkOpenCLBlockArgs(S, BlockArg); 422 } 423 424 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 425 /// get_kernel_work_group_size 426 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 427 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 428 if (checkArgCount(S, TheCall, 1)) 429 return true; 430 431 Expr *BlockArg = TheCall->getArg(0); 432 if (!isBlockPointer(BlockArg)) { 433 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 434 << TheCall->getDirectCallee() << "block"; 435 return true; 436 } 437 return checkOpenCLBlockArgs(S, BlockArg); 438 } 439 440 /// Diagnose integer type and any valid implicit conversion to it. 441 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 442 const QualType &IntType); 443 444 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 445 unsigned Start, unsigned End) { 446 bool IllegalParams = false; 447 for (unsigned I = Start; I <= End; ++I) 448 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 449 S.Context.getSizeType()); 450 return IllegalParams; 451 } 452 453 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 454 /// 'local void*' parameter of passed block. 455 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 456 Expr *BlockArg, 457 unsigned NumNonVarArgs) { 458 const BlockPointerType *BPT = 459 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 460 unsigned NumBlockParams = 461 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 462 unsigned TotalNumArgs = TheCall->getNumArgs(); 463 464 // For each argument passed to the block, a corresponding uint needs to 465 // be passed to describe the size of the local memory. 466 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 467 S.Diag(TheCall->getBeginLoc(), 468 diag::err_opencl_enqueue_kernel_local_size_args); 469 return true; 470 } 471 472 // Check that the sizes of the local memory are specified by integers. 473 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 474 TotalNumArgs - 1); 475 } 476 477 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 478 /// overload formats specified in Table 6.13.17.1. 479 /// int enqueue_kernel(queue_t queue, 480 /// kernel_enqueue_flags_t flags, 481 /// const ndrange_t ndrange, 482 /// void (^block)(void)) 483 /// int enqueue_kernel(queue_t queue, 484 /// kernel_enqueue_flags_t flags, 485 /// const ndrange_t ndrange, 486 /// uint num_events_in_wait_list, 487 /// clk_event_t *event_wait_list, 488 /// clk_event_t *event_ret, 489 /// void (^block)(void)) 490 /// int enqueue_kernel(queue_t queue, 491 /// kernel_enqueue_flags_t flags, 492 /// const ndrange_t ndrange, 493 /// void (^block)(local void*, ...), 494 /// uint size0, ...) 495 /// int enqueue_kernel(queue_t queue, 496 /// kernel_enqueue_flags_t flags, 497 /// const ndrange_t ndrange, 498 /// uint num_events_in_wait_list, 499 /// clk_event_t *event_wait_list, 500 /// clk_event_t *event_ret, 501 /// void (^block)(local void*, ...), 502 /// uint size0, ...) 503 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 504 unsigned NumArgs = TheCall->getNumArgs(); 505 506 if (NumArgs < 4) { 507 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args); 508 return true; 509 } 510 511 Expr *Arg0 = TheCall->getArg(0); 512 Expr *Arg1 = TheCall->getArg(1); 513 Expr *Arg2 = TheCall->getArg(2); 514 Expr *Arg3 = TheCall->getArg(3); 515 516 // First argument always needs to be a queue_t type. 517 if (!Arg0->getType()->isQueueT()) { 518 S.Diag(TheCall->getArg(0)->getBeginLoc(), 519 diag::err_opencl_builtin_expected_type) 520 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 521 return true; 522 } 523 524 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 525 if (!Arg1->getType()->isIntegerType()) { 526 S.Diag(TheCall->getArg(1)->getBeginLoc(), 527 diag::err_opencl_builtin_expected_type) 528 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 529 return true; 530 } 531 532 // Third argument is always an ndrange_t type. 533 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 534 S.Diag(TheCall->getArg(2)->getBeginLoc(), 535 diag::err_opencl_builtin_expected_type) 536 << TheCall->getDirectCallee() << "'ndrange_t'"; 537 return true; 538 } 539 540 // With four arguments, there is only one form that the function could be 541 // called in: no events and no variable arguments. 542 if (NumArgs == 4) { 543 // check that the last argument is the right block type. 544 if (!isBlockPointer(Arg3)) { 545 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 546 << TheCall->getDirectCallee() << "block"; 547 return true; 548 } 549 // we have a block type, check the prototype 550 const BlockPointerType *BPT = 551 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 552 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 553 S.Diag(Arg3->getBeginLoc(), 554 diag::err_opencl_enqueue_kernel_blocks_no_args); 555 return true; 556 } 557 return false; 558 } 559 // we can have block + varargs. 560 if (isBlockPointer(Arg3)) 561 return (checkOpenCLBlockArgs(S, Arg3) || 562 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 563 // last two cases with either exactly 7 args or 7 args and varargs. 564 if (NumArgs >= 7) { 565 // check common block argument. 566 Expr *Arg6 = TheCall->getArg(6); 567 if (!isBlockPointer(Arg6)) { 568 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 569 << TheCall->getDirectCallee() << "block"; 570 return true; 571 } 572 if (checkOpenCLBlockArgs(S, Arg6)) 573 return true; 574 575 // Forth argument has to be any integer type. 576 if (!Arg3->getType()->isIntegerType()) { 577 S.Diag(TheCall->getArg(3)->getBeginLoc(), 578 diag::err_opencl_builtin_expected_type) 579 << TheCall->getDirectCallee() << "integer"; 580 return true; 581 } 582 // check remaining common arguments. 583 Expr *Arg4 = TheCall->getArg(4); 584 Expr *Arg5 = TheCall->getArg(5); 585 586 // Fifth argument is always passed as a pointer to clk_event_t. 587 if (!Arg4->isNullPointerConstant(S.Context, 588 Expr::NPC_ValueDependentIsNotNull) && 589 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 590 S.Diag(TheCall->getArg(4)->getBeginLoc(), 591 diag::err_opencl_builtin_expected_type) 592 << TheCall->getDirectCallee() 593 << S.Context.getPointerType(S.Context.OCLClkEventTy); 594 return true; 595 } 596 597 // Sixth argument is always passed as a pointer to clk_event_t. 598 if (!Arg5->isNullPointerConstant(S.Context, 599 Expr::NPC_ValueDependentIsNotNull) && 600 !(Arg5->getType()->isPointerType() && 601 Arg5->getType()->getPointeeType()->isClkEventT())) { 602 S.Diag(TheCall->getArg(5)->getBeginLoc(), 603 diag::err_opencl_builtin_expected_type) 604 << TheCall->getDirectCallee() 605 << S.Context.getPointerType(S.Context.OCLClkEventTy); 606 return true; 607 } 608 609 if (NumArgs == 7) 610 return false; 611 612 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 613 } 614 615 // None of the specific case has been detected, give generic error 616 S.Diag(TheCall->getBeginLoc(), 617 diag::err_opencl_enqueue_kernel_incorrect_args); 618 return true; 619 } 620 621 /// Returns OpenCL access qual. 622 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 623 return D->getAttr<OpenCLAccessAttr>(); 624 } 625 626 /// Returns true if pipe element type is different from the pointer. 627 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 628 const Expr *Arg0 = Call->getArg(0); 629 // First argument type should always be pipe. 630 if (!Arg0->getType()->isPipeType()) { 631 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 632 << Call->getDirectCallee() << Arg0->getSourceRange(); 633 return true; 634 } 635 OpenCLAccessAttr *AccessQual = 636 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 637 // Validates the access qualifier is compatible with the call. 638 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 639 // read_only and write_only, and assumed to be read_only if no qualifier is 640 // specified. 641 switch (Call->getDirectCallee()->getBuiltinID()) { 642 case Builtin::BIread_pipe: 643 case Builtin::BIreserve_read_pipe: 644 case Builtin::BIcommit_read_pipe: 645 case Builtin::BIwork_group_reserve_read_pipe: 646 case Builtin::BIsub_group_reserve_read_pipe: 647 case Builtin::BIwork_group_commit_read_pipe: 648 case Builtin::BIsub_group_commit_read_pipe: 649 if (!(!AccessQual || AccessQual->isReadOnly())) { 650 S.Diag(Arg0->getBeginLoc(), 651 diag::err_opencl_builtin_pipe_invalid_access_modifier) 652 << "read_only" << Arg0->getSourceRange(); 653 return true; 654 } 655 break; 656 case Builtin::BIwrite_pipe: 657 case Builtin::BIreserve_write_pipe: 658 case Builtin::BIcommit_write_pipe: 659 case Builtin::BIwork_group_reserve_write_pipe: 660 case Builtin::BIsub_group_reserve_write_pipe: 661 case Builtin::BIwork_group_commit_write_pipe: 662 case Builtin::BIsub_group_commit_write_pipe: 663 if (!(AccessQual && AccessQual->isWriteOnly())) { 664 S.Diag(Arg0->getBeginLoc(), 665 diag::err_opencl_builtin_pipe_invalid_access_modifier) 666 << "write_only" << Arg0->getSourceRange(); 667 return true; 668 } 669 break; 670 default: 671 break; 672 } 673 return false; 674 } 675 676 /// Returns true if pipe element type is different from the pointer. 677 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 678 const Expr *Arg0 = Call->getArg(0); 679 const Expr *ArgIdx = Call->getArg(Idx); 680 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 681 const QualType EltTy = PipeTy->getElementType(); 682 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 683 // The Idx argument should be a pointer and the type of the pointer and 684 // the type of pipe element should also be the same. 685 if (!ArgTy || 686 !S.Context.hasSameType( 687 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 688 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 689 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 690 << ArgIdx->getType() << ArgIdx->getSourceRange(); 691 return true; 692 } 693 return false; 694 } 695 696 // Performs semantic analysis for the read/write_pipe call. 697 // \param S Reference to the semantic analyzer. 698 // \param Call A pointer to the builtin call. 699 // \return True if a semantic error has been found, false otherwise. 700 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 701 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 702 // functions have two forms. 703 switch (Call->getNumArgs()) { 704 case 2: 705 if (checkOpenCLPipeArg(S, Call)) 706 return true; 707 // The call with 2 arguments should be 708 // read/write_pipe(pipe T, T*). 709 // Check packet type T. 710 if (checkOpenCLPipePacketType(S, Call, 1)) 711 return true; 712 break; 713 714 case 4: { 715 if (checkOpenCLPipeArg(S, Call)) 716 return true; 717 // The call with 4 arguments should be 718 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 719 // Check reserve_id_t. 720 if (!Call->getArg(1)->getType()->isReserveIDT()) { 721 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 722 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 723 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 724 return true; 725 } 726 727 // Check the index. 728 const Expr *Arg2 = Call->getArg(2); 729 if (!Arg2->getType()->isIntegerType() && 730 !Arg2->getType()->isUnsignedIntegerType()) { 731 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 732 << Call->getDirectCallee() << S.Context.UnsignedIntTy 733 << Arg2->getType() << Arg2->getSourceRange(); 734 return true; 735 } 736 737 // Check packet type T. 738 if (checkOpenCLPipePacketType(S, Call, 3)) 739 return true; 740 } break; 741 default: 742 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 743 << Call->getDirectCallee() << Call->getSourceRange(); 744 return true; 745 } 746 747 return false; 748 } 749 750 // Performs a semantic analysis on the {work_group_/sub_group_ 751 // /_}reserve_{read/write}_pipe 752 // \param S Reference to the semantic analyzer. 753 // \param Call The call to the builtin function to be analyzed. 754 // \return True if a semantic error was found, false otherwise. 755 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 756 if (checkArgCount(S, Call, 2)) 757 return true; 758 759 if (checkOpenCLPipeArg(S, Call)) 760 return true; 761 762 // Check the reserve size. 763 if (!Call->getArg(1)->getType()->isIntegerType() && 764 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 765 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 766 << Call->getDirectCallee() << S.Context.UnsignedIntTy 767 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 768 return true; 769 } 770 771 // Since return type of reserve_read/write_pipe built-in function is 772 // reserve_id_t, which is not defined in the builtin def file , we used int 773 // as return type and need to override the return type of these functions. 774 Call->setType(S.Context.OCLReserveIDTy); 775 776 return false; 777 } 778 779 // Performs a semantic analysis on {work_group_/sub_group_ 780 // /_}commit_{read/write}_pipe 781 // \param S Reference to the semantic analyzer. 782 // \param Call The call to the builtin function to be analyzed. 783 // \return True if a semantic error was found, false otherwise. 784 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 785 if (checkArgCount(S, Call, 2)) 786 return true; 787 788 if (checkOpenCLPipeArg(S, Call)) 789 return true; 790 791 // Check reserve_id_t. 792 if (!Call->getArg(1)->getType()->isReserveIDT()) { 793 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 794 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 795 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 796 return true; 797 } 798 799 return false; 800 } 801 802 // Performs a semantic analysis on the call to built-in Pipe 803 // Query Functions. 804 // \param S Reference to the semantic analyzer. 805 // \param Call The call to the builtin function to be analyzed. 806 // \return True if a semantic error was found, false otherwise. 807 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 808 if (checkArgCount(S, Call, 1)) 809 return true; 810 811 if (!Call->getArg(0)->getType()->isPipeType()) { 812 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 813 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 814 return true; 815 } 816 817 return false; 818 } 819 820 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 821 // Performs semantic analysis for the to_global/local/private call. 822 // \param S Reference to the semantic analyzer. 823 // \param BuiltinID ID of the builtin function. 824 // \param Call A pointer to the builtin call. 825 // \return True if a semantic error has been found, false otherwise. 826 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 827 CallExpr *Call) { 828 if (Call->getNumArgs() != 1) { 829 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 830 << Call->getDirectCallee() << Call->getSourceRange(); 831 return true; 832 } 833 834 auto RT = Call->getArg(0)->getType(); 835 if (!RT->isPointerType() || RT->getPointeeType() 836 .getAddressSpace() == LangAS::opencl_constant) { 837 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 838 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 839 return true; 840 } 841 842 RT = RT->getPointeeType(); 843 auto Qual = RT.getQualifiers(); 844 switch (BuiltinID) { 845 case Builtin::BIto_global: 846 Qual.setAddressSpace(LangAS::opencl_global); 847 break; 848 case Builtin::BIto_local: 849 Qual.setAddressSpace(LangAS::opencl_local); 850 break; 851 case Builtin::BIto_private: 852 Qual.setAddressSpace(LangAS::opencl_private); 853 break; 854 default: 855 llvm_unreachable("Invalid builtin function"); 856 } 857 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 858 RT.getUnqualifiedType(), Qual))); 859 860 return false; 861 } 862 863 // Emit an error and return true if the current architecture is not in the list 864 // of supported architectures. 865 static bool 866 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 867 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 868 llvm::Triple::ArchType CurArch = 869 S.getASTContext().getTargetInfo().getTriple().getArch(); 870 if (llvm::is_contained(SupportedArchs, CurArch)) 871 return false; 872 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 873 << TheCall->getSourceRange(); 874 return true; 875 } 876 877 ExprResult 878 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 879 CallExpr *TheCall) { 880 ExprResult TheCallResult(TheCall); 881 882 // Find out if any arguments are required to be integer constant expressions. 883 unsigned ICEArguments = 0; 884 ASTContext::GetBuiltinTypeError Error; 885 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 886 if (Error != ASTContext::GE_None) 887 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 888 889 // If any arguments are required to be ICE's, check and diagnose. 890 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 891 // Skip arguments not required to be ICE's. 892 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 893 894 llvm::APSInt Result; 895 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 896 return true; 897 ICEArguments &= ~(1 << ArgNo); 898 } 899 900 switch (BuiltinID) { 901 case Builtin::BI__builtin___CFStringMakeConstantString: 902 assert(TheCall->getNumArgs() == 1 && 903 "Wrong # arguments to builtin CFStringMakeConstantString"); 904 if (CheckObjCString(TheCall->getArg(0))) 905 return ExprError(); 906 break; 907 case Builtin::BI__builtin_ms_va_start: 908 case Builtin::BI__builtin_stdarg_start: 909 case Builtin::BI__builtin_va_start: 910 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 911 return ExprError(); 912 break; 913 case Builtin::BI__va_start: { 914 switch (Context.getTargetInfo().getTriple().getArch()) { 915 case llvm::Triple::arm: 916 case llvm::Triple::thumb: 917 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 918 return ExprError(); 919 break; 920 default: 921 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 922 return ExprError(); 923 break; 924 } 925 break; 926 } 927 928 // The acquire, release, and no fence variants are ARM and AArch64 only. 929 case Builtin::BI_interlockedbittestandset_acq: 930 case Builtin::BI_interlockedbittestandset_rel: 931 case Builtin::BI_interlockedbittestandset_nf: 932 case Builtin::BI_interlockedbittestandreset_acq: 933 case Builtin::BI_interlockedbittestandreset_rel: 934 case Builtin::BI_interlockedbittestandreset_nf: 935 if (CheckBuiltinTargetSupport( 936 *this, BuiltinID, TheCall, 937 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 938 return ExprError(); 939 break; 940 941 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 942 case Builtin::BI_bittest64: 943 case Builtin::BI_bittestandcomplement64: 944 case Builtin::BI_bittestandreset64: 945 case Builtin::BI_bittestandset64: 946 case Builtin::BI_interlockedbittestandreset64: 947 case Builtin::BI_interlockedbittestandset64: 948 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 949 {llvm::Triple::x86_64, llvm::Triple::arm, 950 llvm::Triple::thumb, llvm::Triple::aarch64})) 951 return ExprError(); 952 break; 953 954 case Builtin::BI__builtin_isgreater: 955 case Builtin::BI__builtin_isgreaterequal: 956 case Builtin::BI__builtin_isless: 957 case Builtin::BI__builtin_islessequal: 958 case Builtin::BI__builtin_islessgreater: 959 case Builtin::BI__builtin_isunordered: 960 if (SemaBuiltinUnorderedCompare(TheCall)) 961 return ExprError(); 962 break; 963 case Builtin::BI__builtin_fpclassify: 964 if (SemaBuiltinFPClassification(TheCall, 6)) 965 return ExprError(); 966 break; 967 case Builtin::BI__builtin_isfinite: 968 case Builtin::BI__builtin_isinf: 969 case Builtin::BI__builtin_isinf_sign: 970 case Builtin::BI__builtin_isnan: 971 case Builtin::BI__builtin_isnormal: 972 case Builtin::BI__builtin_signbit: 973 case Builtin::BI__builtin_signbitf: 974 case Builtin::BI__builtin_signbitl: 975 if (SemaBuiltinFPClassification(TheCall, 1)) 976 return ExprError(); 977 break; 978 case Builtin::BI__builtin_shufflevector: 979 return SemaBuiltinShuffleVector(TheCall); 980 // TheCall will be freed by the smart pointer here, but that's fine, since 981 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 982 case Builtin::BI__builtin_prefetch: 983 if (SemaBuiltinPrefetch(TheCall)) 984 return ExprError(); 985 break; 986 case Builtin::BI__builtin_alloca_with_align: 987 if (SemaBuiltinAllocaWithAlign(TheCall)) 988 return ExprError(); 989 break; 990 case Builtin::BI__assume: 991 case Builtin::BI__builtin_assume: 992 if (SemaBuiltinAssume(TheCall)) 993 return ExprError(); 994 break; 995 case Builtin::BI__builtin_assume_aligned: 996 if (SemaBuiltinAssumeAligned(TheCall)) 997 return ExprError(); 998 break; 999 case Builtin::BI__builtin_object_size: 1000 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1001 return ExprError(); 1002 break; 1003 case Builtin::BI__builtin_longjmp: 1004 if (SemaBuiltinLongjmp(TheCall)) 1005 return ExprError(); 1006 break; 1007 case Builtin::BI__builtin_setjmp: 1008 if (SemaBuiltinSetjmp(TheCall)) 1009 return ExprError(); 1010 break; 1011 case Builtin::BI_setjmp: 1012 case Builtin::BI_setjmpex: 1013 if (checkArgCount(*this, TheCall, 1)) 1014 return true; 1015 break; 1016 case Builtin::BI__builtin_classify_type: 1017 if (checkArgCount(*this, TheCall, 1)) return true; 1018 TheCall->setType(Context.IntTy); 1019 break; 1020 case Builtin::BI__builtin_constant_p: 1021 if (checkArgCount(*this, TheCall, 1)) return true; 1022 TheCall->setType(Context.IntTy); 1023 break; 1024 case Builtin::BI__sync_fetch_and_add: 1025 case Builtin::BI__sync_fetch_and_add_1: 1026 case Builtin::BI__sync_fetch_and_add_2: 1027 case Builtin::BI__sync_fetch_and_add_4: 1028 case Builtin::BI__sync_fetch_and_add_8: 1029 case Builtin::BI__sync_fetch_and_add_16: 1030 case Builtin::BI__sync_fetch_and_sub: 1031 case Builtin::BI__sync_fetch_and_sub_1: 1032 case Builtin::BI__sync_fetch_and_sub_2: 1033 case Builtin::BI__sync_fetch_and_sub_4: 1034 case Builtin::BI__sync_fetch_and_sub_8: 1035 case Builtin::BI__sync_fetch_and_sub_16: 1036 case Builtin::BI__sync_fetch_and_or: 1037 case Builtin::BI__sync_fetch_and_or_1: 1038 case Builtin::BI__sync_fetch_and_or_2: 1039 case Builtin::BI__sync_fetch_and_or_4: 1040 case Builtin::BI__sync_fetch_and_or_8: 1041 case Builtin::BI__sync_fetch_and_or_16: 1042 case Builtin::BI__sync_fetch_and_and: 1043 case Builtin::BI__sync_fetch_and_and_1: 1044 case Builtin::BI__sync_fetch_and_and_2: 1045 case Builtin::BI__sync_fetch_and_and_4: 1046 case Builtin::BI__sync_fetch_and_and_8: 1047 case Builtin::BI__sync_fetch_and_and_16: 1048 case Builtin::BI__sync_fetch_and_xor: 1049 case Builtin::BI__sync_fetch_and_xor_1: 1050 case Builtin::BI__sync_fetch_and_xor_2: 1051 case Builtin::BI__sync_fetch_and_xor_4: 1052 case Builtin::BI__sync_fetch_and_xor_8: 1053 case Builtin::BI__sync_fetch_and_xor_16: 1054 case Builtin::BI__sync_fetch_and_nand: 1055 case Builtin::BI__sync_fetch_and_nand_1: 1056 case Builtin::BI__sync_fetch_and_nand_2: 1057 case Builtin::BI__sync_fetch_and_nand_4: 1058 case Builtin::BI__sync_fetch_and_nand_8: 1059 case Builtin::BI__sync_fetch_and_nand_16: 1060 case Builtin::BI__sync_add_and_fetch: 1061 case Builtin::BI__sync_add_and_fetch_1: 1062 case Builtin::BI__sync_add_and_fetch_2: 1063 case Builtin::BI__sync_add_and_fetch_4: 1064 case Builtin::BI__sync_add_and_fetch_8: 1065 case Builtin::BI__sync_add_and_fetch_16: 1066 case Builtin::BI__sync_sub_and_fetch: 1067 case Builtin::BI__sync_sub_and_fetch_1: 1068 case Builtin::BI__sync_sub_and_fetch_2: 1069 case Builtin::BI__sync_sub_and_fetch_4: 1070 case Builtin::BI__sync_sub_and_fetch_8: 1071 case Builtin::BI__sync_sub_and_fetch_16: 1072 case Builtin::BI__sync_and_and_fetch: 1073 case Builtin::BI__sync_and_and_fetch_1: 1074 case Builtin::BI__sync_and_and_fetch_2: 1075 case Builtin::BI__sync_and_and_fetch_4: 1076 case Builtin::BI__sync_and_and_fetch_8: 1077 case Builtin::BI__sync_and_and_fetch_16: 1078 case Builtin::BI__sync_or_and_fetch: 1079 case Builtin::BI__sync_or_and_fetch_1: 1080 case Builtin::BI__sync_or_and_fetch_2: 1081 case Builtin::BI__sync_or_and_fetch_4: 1082 case Builtin::BI__sync_or_and_fetch_8: 1083 case Builtin::BI__sync_or_and_fetch_16: 1084 case Builtin::BI__sync_xor_and_fetch: 1085 case Builtin::BI__sync_xor_and_fetch_1: 1086 case Builtin::BI__sync_xor_and_fetch_2: 1087 case Builtin::BI__sync_xor_and_fetch_4: 1088 case Builtin::BI__sync_xor_and_fetch_8: 1089 case Builtin::BI__sync_xor_and_fetch_16: 1090 case Builtin::BI__sync_nand_and_fetch: 1091 case Builtin::BI__sync_nand_and_fetch_1: 1092 case Builtin::BI__sync_nand_and_fetch_2: 1093 case Builtin::BI__sync_nand_and_fetch_4: 1094 case Builtin::BI__sync_nand_and_fetch_8: 1095 case Builtin::BI__sync_nand_and_fetch_16: 1096 case Builtin::BI__sync_val_compare_and_swap: 1097 case Builtin::BI__sync_val_compare_and_swap_1: 1098 case Builtin::BI__sync_val_compare_and_swap_2: 1099 case Builtin::BI__sync_val_compare_and_swap_4: 1100 case Builtin::BI__sync_val_compare_and_swap_8: 1101 case Builtin::BI__sync_val_compare_and_swap_16: 1102 case Builtin::BI__sync_bool_compare_and_swap: 1103 case Builtin::BI__sync_bool_compare_and_swap_1: 1104 case Builtin::BI__sync_bool_compare_and_swap_2: 1105 case Builtin::BI__sync_bool_compare_and_swap_4: 1106 case Builtin::BI__sync_bool_compare_and_swap_8: 1107 case Builtin::BI__sync_bool_compare_and_swap_16: 1108 case Builtin::BI__sync_lock_test_and_set: 1109 case Builtin::BI__sync_lock_test_and_set_1: 1110 case Builtin::BI__sync_lock_test_and_set_2: 1111 case Builtin::BI__sync_lock_test_and_set_4: 1112 case Builtin::BI__sync_lock_test_and_set_8: 1113 case Builtin::BI__sync_lock_test_and_set_16: 1114 case Builtin::BI__sync_lock_release: 1115 case Builtin::BI__sync_lock_release_1: 1116 case Builtin::BI__sync_lock_release_2: 1117 case Builtin::BI__sync_lock_release_4: 1118 case Builtin::BI__sync_lock_release_8: 1119 case Builtin::BI__sync_lock_release_16: 1120 case Builtin::BI__sync_swap: 1121 case Builtin::BI__sync_swap_1: 1122 case Builtin::BI__sync_swap_2: 1123 case Builtin::BI__sync_swap_4: 1124 case Builtin::BI__sync_swap_8: 1125 case Builtin::BI__sync_swap_16: 1126 return SemaBuiltinAtomicOverloaded(TheCallResult); 1127 case Builtin::BI__builtin_nontemporal_load: 1128 case Builtin::BI__builtin_nontemporal_store: 1129 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1130 #define BUILTIN(ID, TYPE, ATTRS) 1131 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1132 case Builtin::BI##ID: \ 1133 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1134 #include "clang/Basic/Builtins.def" 1135 case Builtin::BI__annotation: 1136 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1137 return ExprError(); 1138 break; 1139 case Builtin::BI__builtin_annotation: 1140 if (SemaBuiltinAnnotation(*this, TheCall)) 1141 return ExprError(); 1142 break; 1143 case Builtin::BI__builtin_addressof: 1144 if (SemaBuiltinAddressof(*this, TheCall)) 1145 return ExprError(); 1146 break; 1147 case Builtin::BI__builtin_add_overflow: 1148 case Builtin::BI__builtin_sub_overflow: 1149 case Builtin::BI__builtin_mul_overflow: 1150 if (SemaBuiltinOverflow(*this, TheCall)) 1151 return ExprError(); 1152 break; 1153 case Builtin::BI__builtin_operator_new: 1154 case Builtin::BI__builtin_operator_delete: { 1155 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1156 ExprResult Res = 1157 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1158 if (Res.isInvalid()) 1159 CorrectDelayedTyposInExpr(TheCallResult.get()); 1160 return Res; 1161 } 1162 case Builtin::BI__builtin_dump_struct: { 1163 // We first want to ensure we are called with 2 arguments 1164 if (checkArgCount(*this, TheCall, 2)) 1165 return ExprError(); 1166 // Ensure that the first argument is of type 'struct XX *' 1167 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1168 const QualType PtrArgType = PtrArg->getType(); 1169 if (!PtrArgType->isPointerType() || 1170 !PtrArgType->getPointeeType()->isRecordType()) { 1171 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1172 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1173 << "structure pointer"; 1174 return ExprError(); 1175 } 1176 1177 // Ensure that the second argument is of type 'FunctionType' 1178 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1179 const QualType FnPtrArgType = FnPtrArg->getType(); 1180 if (!FnPtrArgType->isPointerType()) { 1181 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1182 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1183 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1184 return ExprError(); 1185 } 1186 1187 const auto *FuncType = 1188 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1189 1190 if (!FuncType) { 1191 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1192 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1193 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1194 return ExprError(); 1195 } 1196 1197 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1198 if (!FT->getNumParams()) { 1199 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1200 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1201 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1202 return ExprError(); 1203 } 1204 QualType PT = FT->getParamType(0); 1205 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1206 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1207 !PT->getPointeeType().isConstQualified()) { 1208 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1209 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1210 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1211 return ExprError(); 1212 } 1213 } 1214 1215 TheCall->setType(Context.IntTy); 1216 break; 1217 } 1218 1219 // check secure string manipulation functions where overflows 1220 // are detectable at compile time 1221 case Builtin::BI__builtin___memcpy_chk: 1222 case Builtin::BI__builtin___memmove_chk: 1223 case Builtin::BI__builtin___memset_chk: 1224 case Builtin::BI__builtin___strlcat_chk: 1225 case Builtin::BI__builtin___strlcpy_chk: 1226 case Builtin::BI__builtin___strncat_chk: 1227 case Builtin::BI__builtin___strncpy_chk: 1228 case Builtin::BI__builtin___stpncpy_chk: 1229 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1230 break; 1231 case Builtin::BI__builtin___memccpy_chk: 1232 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1233 break; 1234 case Builtin::BI__builtin___snprintf_chk: 1235 case Builtin::BI__builtin___vsnprintf_chk: 1236 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1237 break; 1238 case Builtin::BI__builtin_call_with_static_chain: 1239 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1240 return ExprError(); 1241 break; 1242 case Builtin::BI__exception_code: 1243 case Builtin::BI_exception_code: 1244 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1245 diag::err_seh___except_block)) 1246 return ExprError(); 1247 break; 1248 case Builtin::BI__exception_info: 1249 case Builtin::BI_exception_info: 1250 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1251 diag::err_seh___except_filter)) 1252 return ExprError(); 1253 break; 1254 case Builtin::BI__GetExceptionInfo: 1255 if (checkArgCount(*this, TheCall, 1)) 1256 return ExprError(); 1257 1258 if (CheckCXXThrowOperand( 1259 TheCall->getBeginLoc(), 1260 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1261 TheCall)) 1262 return ExprError(); 1263 1264 TheCall->setType(Context.VoidPtrTy); 1265 break; 1266 // OpenCL v2.0, s6.13.16 - Pipe functions 1267 case Builtin::BIread_pipe: 1268 case Builtin::BIwrite_pipe: 1269 // Since those two functions are declared with var args, we need a semantic 1270 // check for the argument. 1271 if (SemaBuiltinRWPipe(*this, TheCall)) 1272 return ExprError(); 1273 TheCall->setType(Context.IntTy); 1274 break; 1275 case Builtin::BIreserve_read_pipe: 1276 case Builtin::BIreserve_write_pipe: 1277 case Builtin::BIwork_group_reserve_read_pipe: 1278 case Builtin::BIwork_group_reserve_write_pipe: 1279 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1280 return ExprError(); 1281 break; 1282 case Builtin::BIsub_group_reserve_read_pipe: 1283 case Builtin::BIsub_group_reserve_write_pipe: 1284 if (checkOpenCLSubgroupExt(*this, TheCall) || 1285 SemaBuiltinReserveRWPipe(*this, TheCall)) 1286 return ExprError(); 1287 break; 1288 case Builtin::BIcommit_read_pipe: 1289 case Builtin::BIcommit_write_pipe: 1290 case Builtin::BIwork_group_commit_read_pipe: 1291 case Builtin::BIwork_group_commit_write_pipe: 1292 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1293 return ExprError(); 1294 break; 1295 case Builtin::BIsub_group_commit_read_pipe: 1296 case Builtin::BIsub_group_commit_write_pipe: 1297 if (checkOpenCLSubgroupExt(*this, TheCall) || 1298 SemaBuiltinCommitRWPipe(*this, TheCall)) 1299 return ExprError(); 1300 break; 1301 case Builtin::BIget_pipe_num_packets: 1302 case Builtin::BIget_pipe_max_packets: 1303 if (SemaBuiltinPipePackets(*this, TheCall)) 1304 return ExprError(); 1305 TheCall->setType(Context.UnsignedIntTy); 1306 break; 1307 case Builtin::BIto_global: 1308 case Builtin::BIto_local: 1309 case Builtin::BIto_private: 1310 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1311 return ExprError(); 1312 break; 1313 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1314 case Builtin::BIenqueue_kernel: 1315 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1316 return ExprError(); 1317 break; 1318 case Builtin::BIget_kernel_work_group_size: 1319 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1320 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1321 return ExprError(); 1322 break; 1323 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1324 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1325 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1326 return ExprError(); 1327 break; 1328 case Builtin::BI__builtin_os_log_format: 1329 case Builtin::BI__builtin_os_log_format_buffer_size: 1330 if (SemaBuiltinOSLogFormat(TheCall)) 1331 return ExprError(); 1332 break; 1333 } 1334 1335 // Since the target specific builtins for each arch overlap, only check those 1336 // of the arch we are compiling for. 1337 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1338 switch (Context.getTargetInfo().getTriple().getArch()) { 1339 case llvm::Triple::arm: 1340 case llvm::Triple::armeb: 1341 case llvm::Triple::thumb: 1342 case llvm::Triple::thumbeb: 1343 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1344 return ExprError(); 1345 break; 1346 case llvm::Triple::aarch64: 1347 case llvm::Triple::aarch64_be: 1348 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1349 return ExprError(); 1350 break; 1351 case llvm::Triple::hexagon: 1352 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1353 return ExprError(); 1354 break; 1355 case llvm::Triple::mips: 1356 case llvm::Triple::mipsel: 1357 case llvm::Triple::mips64: 1358 case llvm::Triple::mips64el: 1359 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1360 return ExprError(); 1361 break; 1362 case llvm::Triple::systemz: 1363 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1364 return ExprError(); 1365 break; 1366 case llvm::Triple::x86: 1367 case llvm::Triple::x86_64: 1368 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1369 return ExprError(); 1370 break; 1371 case llvm::Triple::ppc: 1372 case llvm::Triple::ppc64: 1373 case llvm::Triple::ppc64le: 1374 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1375 return ExprError(); 1376 break; 1377 default: 1378 break; 1379 } 1380 } 1381 1382 return TheCallResult; 1383 } 1384 1385 // Get the valid immediate range for the specified NEON type code. 1386 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1387 NeonTypeFlags Type(t); 1388 int IsQuad = ForceQuad ? true : Type.isQuad(); 1389 switch (Type.getEltType()) { 1390 case NeonTypeFlags::Int8: 1391 case NeonTypeFlags::Poly8: 1392 return shift ? 7 : (8 << IsQuad) - 1; 1393 case NeonTypeFlags::Int16: 1394 case NeonTypeFlags::Poly16: 1395 return shift ? 15 : (4 << IsQuad) - 1; 1396 case NeonTypeFlags::Int32: 1397 return shift ? 31 : (2 << IsQuad) - 1; 1398 case NeonTypeFlags::Int64: 1399 case NeonTypeFlags::Poly64: 1400 return shift ? 63 : (1 << IsQuad) - 1; 1401 case NeonTypeFlags::Poly128: 1402 return shift ? 127 : (1 << IsQuad) - 1; 1403 case NeonTypeFlags::Float16: 1404 assert(!shift && "cannot shift float types!"); 1405 return (4 << IsQuad) - 1; 1406 case NeonTypeFlags::Float32: 1407 assert(!shift && "cannot shift float types!"); 1408 return (2 << IsQuad) - 1; 1409 case NeonTypeFlags::Float64: 1410 assert(!shift && "cannot shift float types!"); 1411 return (1 << IsQuad) - 1; 1412 } 1413 llvm_unreachable("Invalid NeonTypeFlag!"); 1414 } 1415 1416 /// getNeonEltType - Return the QualType corresponding to the elements of 1417 /// the vector type specified by the NeonTypeFlags. This is used to check 1418 /// the pointer arguments for Neon load/store intrinsics. 1419 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1420 bool IsPolyUnsigned, bool IsInt64Long) { 1421 switch (Flags.getEltType()) { 1422 case NeonTypeFlags::Int8: 1423 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1424 case NeonTypeFlags::Int16: 1425 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1426 case NeonTypeFlags::Int32: 1427 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1428 case NeonTypeFlags::Int64: 1429 if (IsInt64Long) 1430 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1431 else 1432 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1433 : Context.LongLongTy; 1434 case NeonTypeFlags::Poly8: 1435 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1436 case NeonTypeFlags::Poly16: 1437 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1438 case NeonTypeFlags::Poly64: 1439 if (IsInt64Long) 1440 return Context.UnsignedLongTy; 1441 else 1442 return Context.UnsignedLongLongTy; 1443 case NeonTypeFlags::Poly128: 1444 break; 1445 case NeonTypeFlags::Float16: 1446 return Context.HalfTy; 1447 case NeonTypeFlags::Float32: 1448 return Context.FloatTy; 1449 case NeonTypeFlags::Float64: 1450 return Context.DoubleTy; 1451 } 1452 llvm_unreachable("Invalid NeonTypeFlag!"); 1453 } 1454 1455 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1456 llvm::APSInt Result; 1457 uint64_t mask = 0; 1458 unsigned TV = 0; 1459 int PtrArgNum = -1; 1460 bool HasConstPtr = false; 1461 switch (BuiltinID) { 1462 #define GET_NEON_OVERLOAD_CHECK 1463 #include "clang/Basic/arm_neon.inc" 1464 #include "clang/Basic/arm_fp16.inc" 1465 #undef GET_NEON_OVERLOAD_CHECK 1466 } 1467 1468 // For NEON intrinsics which are overloaded on vector element type, validate 1469 // the immediate which specifies which variant to emit. 1470 unsigned ImmArg = TheCall->getNumArgs()-1; 1471 if (mask) { 1472 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1473 return true; 1474 1475 TV = Result.getLimitedValue(64); 1476 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1477 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1478 << TheCall->getArg(ImmArg)->getSourceRange(); 1479 } 1480 1481 if (PtrArgNum >= 0) { 1482 // Check that pointer arguments have the specified type. 1483 Expr *Arg = TheCall->getArg(PtrArgNum); 1484 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1485 Arg = ICE->getSubExpr(); 1486 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1487 QualType RHSTy = RHS.get()->getType(); 1488 1489 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1490 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1491 Arch == llvm::Triple::aarch64_be; 1492 bool IsInt64Long = 1493 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1494 QualType EltTy = 1495 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1496 if (HasConstPtr) 1497 EltTy = EltTy.withConst(); 1498 QualType LHSTy = Context.getPointerType(EltTy); 1499 AssignConvertType ConvTy; 1500 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1501 if (RHS.isInvalid()) 1502 return true; 1503 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1504 RHS.get(), AA_Assigning)) 1505 return true; 1506 } 1507 1508 // For NEON intrinsics which take an immediate value as part of the 1509 // instruction, range check them here. 1510 unsigned i = 0, l = 0, u = 0; 1511 switch (BuiltinID) { 1512 default: 1513 return false; 1514 #define GET_NEON_IMMEDIATE_CHECK 1515 #include "clang/Basic/arm_neon.inc" 1516 #include "clang/Basic/arm_fp16.inc" 1517 #undef GET_NEON_IMMEDIATE_CHECK 1518 } 1519 1520 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1521 } 1522 1523 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1524 unsigned MaxWidth) { 1525 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1526 BuiltinID == ARM::BI__builtin_arm_ldaex || 1527 BuiltinID == ARM::BI__builtin_arm_strex || 1528 BuiltinID == ARM::BI__builtin_arm_stlex || 1529 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1530 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1531 BuiltinID == AArch64::BI__builtin_arm_strex || 1532 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1533 "unexpected ARM builtin"); 1534 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1535 BuiltinID == ARM::BI__builtin_arm_ldaex || 1536 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1537 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1538 1539 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1540 1541 // Ensure that we have the proper number of arguments. 1542 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1543 return true; 1544 1545 // Inspect the pointer argument of the atomic builtin. This should always be 1546 // a pointer type, whose element is an integral scalar or pointer type. 1547 // Because it is a pointer type, we don't have to worry about any implicit 1548 // casts here. 1549 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1550 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1551 if (PointerArgRes.isInvalid()) 1552 return true; 1553 PointerArg = PointerArgRes.get(); 1554 1555 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1556 if (!pointerType) { 1557 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1558 << PointerArg->getType() << PointerArg->getSourceRange(); 1559 return true; 1560 } 1561 1562 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1563 // task is to insert the appropriate casts into the AST. First work out just 1564 // what the appropriate type is. 1565 QualType ValType = pointerType->getPointeeType(); 1566 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1567 if (IsLdrex) 1568 AddrType.addConst(); 1569 1570 // Issue a warning if the cast is dodgy. 1571 CastKind CastNeeded = CK_NoOp; 1572 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1573 CastNeeded = CK_BitCast; 1574 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1575 << PointerArg->getType() << Context.getPointerType(AddrType) 1576 << AA_Passing << PointerArg->getSourceRange(); 1577 } 1578 1579 // Finally, do the cast and replace the argument with the corrected version. 1580 AddrType = Context.getPointerType(AddrType); 1581 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1582 if (PointerArgRes.isInvalid()) 1583 return true; 1584 PointerArg = PointerArgRes.get(); 1585 1586 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1587 1588 // In general, we allow ints, floats and pointers to be loaded and stored. 1589 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1590 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1591 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1592 << PointerArg->getType() << PointerArg->getSourceRange(); 1593 return true; 1594 } 1595 1596 // But ARM doesn't have instructions to deal with 128-bit versions. 1597 if (Context.getTypeSize(ValType) > MaxWidth) { 1598 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1599 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1600 << PointerArg->getType() << PointerArg->getSourceRange(); 1601 return true; 1602 } 1603 1604 switch (ValType.getObjCLifetime()) { 1605 case Qualifiers::OCL_None: 1606 case Qualifiers::OCL_ExplicitNone: 1607 // okay 1608 break; 1609 1610 case Qualifiers::OCL_Weak: 1611 case Qualifiers::OCL_Strong: 1612 case Qualifiers::OCL_Autoreleasing: 1613 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1614 << ValType << PointerArg->getSourceRange(); 1615 return true; 1616 } 1617 1618 if (IsLdrex) { 1619 TheCall->setType(ValType); 1620 return false; 1621 } 1622 1623 // Initialize the argument to be stored. 1624 ExprResult ValArg = TheCall->getArg(0); 1625 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1626 Context, ValType, /*consume*/ false); 1627 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1628 if (ValArg.isInvalid()) 1629 return true; 1630 TheCall->setArg(0, ValArg.get()); 1631 1632 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1633 // but the custom checker bypasses all default analysis. 1634 TheCall->setType(Context.IntTy); 1635 return false; 1636 } 1637 1638 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1639 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1640 BuiltinID == ARM::BI__builtin_arm_ldaex || 1641 BuiltinID == ARM::BI__builtin_arm_strex || 1642 BuiltinID == ARM::BI__builtin_arm_stlex) { 1643 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1644 } 1645 1646 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1647 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1648 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1649 } 1650 1651 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1652 BuiltinID == ARM::BI__builtin_arm_wsr64) 1653 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1654 1655 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1656 BuiltinID == ARM::BI__builtin_arm_rsrp || 1657 BuiltinID == ARM::BI__builtin_arm_wsr || 1658 BuiltinID == ARM::BI__builtin_arm_wsrp) 1659 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1660 1661 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1662 return true; 1663 1664 // For intrinsics which take an immediate value as part of the instruction, 1665 // range check them here. 1666 // FIXME: VFP Intrinsics should error if VFP not present. 1667 switch (BuiltinID) { 1668 default: return false; 1669 case ARM::BI__builtin_arm_ssat: 1670 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1671 case ARM::BI__builtin_arm_usat: 1672 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1673 case ARM::BI__builtin_arm_ssat16: 1674 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1675 case ARM::BI__builtin_arm_usat16: 1676 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1677 case ARM::BI__builtin_arm_vcvtr_f: 1678 case ARM::BI__builtin_arm_vcvtr_d: 1679 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1680 case ARM::BI__builtin_arm_dmb: 1681 case ARM::BI__builtin_arm_dsb: 1682 case ARM::BI__builtin_arm_isb: 1683 case ARM::BI__builtin_arm_dbg: 1684 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1685 } 1686 } 1687 1688 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1689 CallExpr *TheCall) { 1690 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1691 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1692 BuiltinID == AArch64::BI__builtin_arm_strex || 1693 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1694 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1695 } 1696 1697 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1698 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1699 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1700 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1701 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1702 } 1703 1704 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1705 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1706 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1707 1708 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1709 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1710 BuiltinID == AArch64::BI__builtin_arm_wsr || 1711 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1712 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1713 1714 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1715 return true; 1716 1717 // For intrinsics which take an immediate value as part of the instruction, 1718 // range check them here. 1719 unsigned i = 0, l = 0, u = 0; 1720 switch (BuiltinID) { 1721 default: return false; 1722 case AArch64::BI__builtin_arm_dmb: 1723 case AArch64::BI__builtin_arm_dsb: 1724 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1725 } 1726 1727 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1728 } 1729 1730 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1731 static const std::map<unsigned, std::vector<StringRef>> ValidCPU = { 1732 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, {"v65"} }, 1733 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, {"v62", "v65"} }, 1734 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, {"v62", "v65"} }, 1735 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, {"v62", "v65"} }, 1736 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {"v60", "v62", "v65"} }, 1737 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {"v60", "v62", "v65"} }, 1738 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {"v60", "v62", "v65"} }, 1739 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {"v60", "v62", "v65"} }, 1740 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {"v60", "v62", "v65"} }, 1741 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {"v60", "v62", "v65"} }, 1742 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {"v60", "v62", "v65"} }, 1743 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {"v60", "v62", "v65"} }, 1744 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {"v60", "v62", "v65"} }, 1745 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {"v60", "v62", "v65"} }, 1746 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {"v60", "v62", "v65"} }, 1747 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {"v60", "v62", "v65"} }, 1748 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, {"v62", "v65"} }, 1749 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, {"v62", "v65"} }, 1750 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, {"v62", "v65"} }, 1751 }; 1752 1753 static const std::map<unsigned, std::vector<StringRef>> ValidHVX = { 1754 { Hexagon::BI__builtin_HEXAGON_V6_extractw, {"v60", "v62", "v65"} }, 1755 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, {"v60", "v62", "v65"} }, 1756 { Hexagon::BI__builtin_HEXAGON_V6_hi, {"v60", "v62", "v65"} }, 1757 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, {"v60", "v62", "v65"} }, 1758 { Hexagon::BI__builtin_HEXAGON_V6_lo, {"v60", "v62", "v65"} }, 1759 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, {"v60", "v62", "v65"} }, 1760 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, {"v62", "v65"} }, 1761 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, {"v62", "v65"} }, 1762 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, {"v62", "v65"} }, 1763 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, {"v62", "v65"} }, 1764 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, {"v60", "v62", "v65"} }, 1765 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, {"v60", "v62", "v65"} }, 1766 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, {"v60", "v62", "v65"} }, 1767 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, {"v60", "v62", "v65"} }, 1768 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, {"v60", "v62", "v65"} }, 1769 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, {"v60", "v62", "v65"} }, 1770 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, {"v60", "v62", "v65"} }, 1771 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, {"v60", "v62", "v65"} }, 1772 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, {"v60", "v62", "v65"} }, 1773 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, {"v60", "v62", "v65"} }, 1774 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, {"v60", "v62", "v65"} }, 1775 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, {"v60", "v62", "v65"} }, 1776 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, {"v60", "v62", "v65"} }, 1777 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, {"v60", "v62", "v65"} }, 1778 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, {"v62", "v65"} }, 1779 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, {"v62", "v65"} }, 1780 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, {"v60", "v62", "v65"} }, 1781 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, {"v60", "v62", "v65"} }, 1782 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, {"v62", "v65"} }, 1783 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, {"v62", "v65"} }, 1784 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, {"v62", "v65"} }, 1785 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, {"v62", "v65"} }, 1786 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, {"v65"} }, 1787 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, {"v65"} }, 1788 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, {"v65"} }, 1789 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, {"v65"} }, 1790 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, {"v60", "v62", "v65"} }, 1791 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, {"v60", "v62", "v65"} }, 1792 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, {"v60", "v62", "v65"} }, 1793 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, {"v60", "v62", "v65"} }, 1794 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, {"v60", "v62", "v65"} }, 1795 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, {"v60", "v62", "v65"} }, 1796 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, {"v60", "v62", "v65"} }, 1797 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, {"v60", "v62", "v65"} }, 1798 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, {"v60", "v62", "v65"} }, 1799 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, {"v60", "v62", "v65"} }, 1800 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, {"v60", "v62", "v65"} }, 1801 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, {"v60", "v62", "v65"} }, 1802 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, {"v60", "v62", "v65"} }, 1803 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, {"v60", "v62", "v65"} }, 1804 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, {"v60", "v62", "v65"} }, 1805 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, {"v60", "v62", "v65"} }, 1806 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, {"v60", "v62", "v65"} }, 1807 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, {"v60", "v62", "v65"} }, 1808 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, {"v60", "v62", "v65"} }, 1809 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, {"v60", "v62", "v65"} }, 1810 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, {"v62", "v65"} }, 1811 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, {"v62", "v65"} }, 1812 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, {"v62", "v65"} }, 1813 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, {"v62", "v65"} }, 1814 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, {"v62", "v65"} }, 1815 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, {"v62", "v65"} }, 1816 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, {"v62", "v65"} }, 1817 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, {"v62", "v65"} }, 1818 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, {"v62", "v65"} }, 1819 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, {"v62", "v65"} }, 1820 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, {"v60", "v62", "v65"} }, 1821 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, {"v60", "v62", "v65"} }, 1822 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, {"v60", "v62", "v65"} }, 1823 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, {"v60", "v62", "v65"} }, 1824 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, {"v60", "v62", "v65"} }, 1825 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, {"v60", "v62", "v65"} }, 1826 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, {"v60", "v62", "v65"} }, 1827 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, {"v60", "v62", "v65"} }, 1828 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, {"v60", "v62", "v65"} }, 1829 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, {"v60", "v62", "v65"} }, 1830 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, {"v62", "v65"} }, 1831 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, {"v62", "v65"} }, 1832 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, {"v60", "v62", "v65"} }, 1833 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, {"v60", "v62", "v65"} }, 1834 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, {"v62", "v65"} }, 1835 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, {"v62", "v65"} }, 1836 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, {"v60", "v62", "v65"} }, 1837 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, {"v60", "v62", "v65"} }, 1838 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, {"v60", "v62", "v65"} }, 1839 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, {"v60", "v62", "v65"} }, 1840 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, {"v62", "v65"} }, 1841 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, {"v62", "v65"} }, 1842 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, {"v60", "v62", "v65"} }, 1843 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, {"v60", "v62", "v65"} }, 1844 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, {"v60", "v62", "v65"} }, 1845 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, {"v60", "v62", "v65"} }, 1846 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, {"v60", "v62", "v65"} }, 1847 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, {"v60", "v62", "v65"} }, 1848 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, {"v62", "v65"} }, 1849 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, {"v62", "v65"} }, 1850 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, {"v62", "v65"} }, 1851 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, {"v62", "v65"} }, 1852 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, {"v62", "v65"} }, 1853 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, {"v62", "v65"} }, 1854 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, {"v60", "v62", "v65"} }, 1855 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, {"v60", "v62", "v65"} }, 1856 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, {"v60", "v62", "v65"} }, 1857 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, {"v60", "v62", "v65"} }, 1858 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, {"v60", "v62", "v65"} }, 1859 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, {"v60", "v62", "v65"} }, 1860 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, {"v60", "v62", "v65"} }, 1861 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, {"v60", "v62", "v65"} }, 1862 { Hexagon::BI__builtin_HEXAGON_V6_valignb, {"v60", "v62", "v65"} }, 1863 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, {"v60", "v62", "v65"} }, 1864 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {"v60", "v62", "v65"} }, 1865 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {"v60", "v62", "v65"} }, 1866 { Hexagon::BI__builtin_HEXAGON_V6_vand, {"v60", "v62", "v65"} }, 1867 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, {"v60", "v62", "v65"} }, 1868 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, {"v62", "v65"} }, 1869 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, {"v62", "v65"} }, 1870 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, {"v62", "v65"} }, 1871 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, {"v62", "v65"} }, 1872 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, {"v60", "v62", "v65"} }, 1873 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, {"v60", "v62", "v65"} }, 1874 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, {"v60", "v62", "v65"} }, 1875 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, {"v60", "v62", "v65"} }, 1876 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, {"v62", "v65"} }, 1877 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, {"v62", "v65"} }, 1878 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, {"v62", "v65"} }, 1879 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, {"v62", "v65"} }, 1880 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, {"v60", "v62", "v65"} }, 1881 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, {"v60", "v62", "v65"} }, 1882 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, {"v60", "v62", "v65"} }, 1883 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, {"v60", "v62", "v65"} }, 1884 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, {"v60", "v62", "v65"} }, 1885 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, {"v60", "v62", "v65"} }, 1886 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, {"v65"} }, 1887 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, {"v65"} }, 1888 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, {"v60", "v62", "v65"} }, 1889 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, {"v60", "v62", "v65"} }, 1890 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, {"v60", "v62", "v65"} }, 1891 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, {"v60", "v62", "v65"} }, 1892 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, {"v60", "v62", "v65"} }, 1893 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, {"v60", "v62", "v65"} }, 1894 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, {"v60", "v62", "v65"} }, 1895 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, {"v60", "v62", "v65"} }, 1896 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, {"v60", "v62", "v65"} }, 1897 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, {"v60", "v62", "v65"} }, 1898 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, {"v65"} }, 1899 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, {"v65"} }, 1900 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, {"v60", "v62", "v65"} }, 1901 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, {"v60", "v62", "v65"} }, 1902 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, {"v62", "v65"} }, 1903 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, {"v62", "v65"} }, 1904 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, {"v60", "v62", "v65"} }, 1905 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, {"v60", "v62", "v65"} }, 1906 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, {"v60", "v62", "v65"} }, 1907 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, {"v60", "v62", "v65"} }, 1908 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, {"v60", "v62", "v65"} }, 1909 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, {"v60", "v62", "v65"} }, 1910 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, {"v65"} }, 1911 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, {"v65"} }, 1912 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, {"v65"} }, 1913 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, {"v65"} }, 1914 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, {"v62", "v65"} }, 1915 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, {"v62", "v65"} }, 1916 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, {"v65"} }, 1917 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, {"v65"} }, 1918 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, {"v60", "v62", "v65"} }, 1919 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, {"v60", "v62", "v65"} }, 1920 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, {"v60", "v62", "v65"} }, 1921 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, {"v60", "v62", "v65"} }, 1922 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, {"v60", "v62", "v65"} }, 1923 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, {"v60", "v62", "v65"} }, 1924 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, {"v60", "v62", "v65"} }, 1925 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, {"v60", "v62", "v65"} }, 1926 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, {"v60", "v62", "v65"} }, 1927 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, {"v60", "v62", "v65"} }, 1928 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, {"v62", "v65"} }, 1929 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, {"v62", "v65"} }, 1930 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, {"v60", "v62", "v65"} }, 1931 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, {"v60", "v62", "v65"} }, 1932 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, {"v60", "v62", "v65"} }, 1933 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, {"v60", "v62", "v65"} }, 1934 { Hexagon::BI__builtin_HEXAGON_V6_vassign, {"v60", "v62", "v65"} }, 1935 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, {"v60", "v62", "v65"} }, 1936 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, {"v60", "v62", "v65"} }, 1937 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, {"v60", "v62", "v65"} }, 1938 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, {"v65"} }, 1939 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, {"v65"} }, 1940 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, {"v65"} }, 1941 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, {"v65"} }, 1942 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, {"v60", "v62", "v65"} }, 1943 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, {"v60", "v62", "v65"} }, 1944 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, {"v60", "v62", "v65"} }, 1945 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, {"v60", "v62", "v65"} }, 1946 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, {"v60", "v62", "v65"} }, 1947 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, {"v60", "v62", "v65"} }, 1948 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, {"v60", "v62", "v65"} }, 1949 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, {"v60", "v62", "v65"} }, 1950 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, {"v60", "v62", "v65"} }, 1951 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, {"v60", "v62", "v65"} }, 1952 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, {"v60", "v62", "v65"} }, 1953 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, {"v60", "v62", "v65"} }, 1954 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, {"v65"} }, 1955 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, {"v65"} }, 1956 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, {"v65"} }, 1957 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, {"v65"} }, 1958 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, {"v60", "v62", "v65"} }, 1959 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, {"v60", "v62", "v65"} }, 1960 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, {"v60", "v62", "v65"} }, 1961 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, {"v60", "v62", "v65"} }, 1962 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, {"v60", "v62", "v65"} }, 1963 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, {"v60", "v62", "v65"} }, 1964 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, {"v60", "v62", "v65"} }, 1965 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, {"v60", "v62", "v65"} }, 1966 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, {"v60", "v62", "v65"} }, 1967 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, {"v60", "v62", "v65"} }, 1968 { Hexagon::BI__builtin_HEXAGON_V6_vd0, {"v60", "v62", "v65"} }, 1969 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, {"v60", "v62", "v65"} }, 1970 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, {"v65"} }, 1971 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, {"v65"} }, 1972 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, {"v60", "v62", "v65"} }, 1973 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, {"v60", "v62", "v65"} }, 1974 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, {"v60", "v62", "v65"} }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, {"v60", "v62", "v65"} }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, {"v60", "v62", "v65"} }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, {"v60", "v62", "v65"} }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, {"v60", "v62", "v65"} }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, {"v60", "v62", "v65"} }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, {"v60", "v62", "v65"} }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, {"v60", "v62", "v65"} }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, {"v60", "v62", "v65"} }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, {"v60", "v62", "v65"} }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, {"v60", "v62", "v65"} }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, {"v60", "v62", "v65"} }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, {"v60", "v62", "v65"} }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, {"v60", "v62", "v65"} }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, {"v60", "v62", "v65"} }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, {"v60", "v62", "v65"} }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, {"v60", "v62", "v65"} }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, {"v60", "v62", "v65"} }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, {"v60", "v62", "v65"} }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, {"v60", "v62", "v65"} }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, {"v60", "v62", "v65"} }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, {"v60", "v62", "v65"} }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, {"v60", "v62", "v65"} }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, {"v60", "v62", "v65"} }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, {"v60", "v62", "v65"} }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, {"v60", "v62", "v65"} }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, {"v60", "v62", "v65"} }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, {"v60", "v62", "v65"} }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, {"v60", "v62", "v65"} }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, {"v60", "v62", "v65"} }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, {"v60", "v62", "v65"} }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, {"v60", "v62", "v65"} }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, {"v60", "v62", "v65"} }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, {"v60", "v62", "v65"} }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, {"v60", "v62", "v65"} }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, {"v60", "v62", "v65"} }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, {"v60", "v62", "v65"} }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, {"v60", "v62", "v65"} }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, {"v60", "v62", "v65"} }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, {"v60", "v62", "v65"} }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, {"v60", "v62", "v65"} }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, {"v60", "v62", "v65"} }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, {"v60", "v62", "v65"} }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, {"v60", "v62", "v65"} }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, {"v60", "v62", "v65"} }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, {"v60", "v62", "v65"} }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, {"v60", "v62", "v65"} }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, {"v60", "v62", "v65"} }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_veqb, {"v60", "v62", "v65"} }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, {"v60", "v62", "v65"} }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, {"v60", "v62", "v65"} }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, {"v60", "v62", "v65"} }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, {"v60", "v62", "v65"} }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, {"v60", "v62", "v65"} }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, {"v60", "v62", "v65"} }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, {"v60", "v62", "v65"} }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_veqh, {"v60", "v62", "v65"} }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, {"v60", "v62", "v65"} }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, {"v60", "v62", "v65"} }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, {"v60", "v62", "v65"} }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, {"v60", "v62", "v65"} }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, {"v60", "v62", "v65"} }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, {"v60", "v62", "v65"} }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, {"v60", "v62", "v65"} }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_veqw, {"v60", "v62", "v65"} }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, {"v60", "v62", "v65"} }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, {"v60", "v62", "v65"} }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, {"v60", "v62", "v65"} }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, {"v60", "v62", "v65"} }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, {"v60", "v62", "v65"} }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, {"v60", "v62", "v65"} }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, {"v60", "v62", "v65"} }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, {"v60", "v62", "v65"} }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, {"v60", "v62", "v65"} }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, {"v60", "v62", "v65"} }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, {"v60", "v62", "v65"} }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, {"v60", "v62", "v65"} }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, {"v60", "v62", "v65"} }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, {"v60", "v62", "v65"} }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, {"v60", "v62", "v65"} }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_vgth, {"v60", "v62", "v65"} }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, {"v60", "v62", "v65"} }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, {"v60", "v62", "v65"} }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, {"v60", "v62", "v65"} }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, {"v60", "v62", "v65"} }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, {"v60", "v62", "v65"} }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, {"v60", "v62", "v65"} }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, {"v60", "v62", "v65"} }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, {"v60", "v62", "v65"} }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, {"v60", "v62", "v65"} }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, {"v60", "v62", "v65"} }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, {"v60", "v62", "v65"} }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, {"v60", "v62", "v65"} }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, {"v60", "v62", "v65"} }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, {"v60", "v62", "v65"} }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, {"v60", "v62", "v65"} }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, {"v60", "v62", "v65"} }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, {"v60", "v62", "v65"} }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, {"v60", "v62", "v65"} }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, {"v60", "v62", "v65"} }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, {"v60", "v62", "v65"} }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, {"v60", "v62", "v65"} }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, {"v60", "v62", "v65"} }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, {"v60", "v62", "v65"} }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, {"v60", "v62", "v65"} }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, {"v60", "v62", "v65"} }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, {"v60", "v62", "v65"} }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, {"v60", "v62", "v65"} }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, {"v60", "v62", "v65"} }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, {"v60", "v62", "v65"} }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, {"v60", "v62", "v65"} }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, {"v60", "v62", "v65"} }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, {"v60", "v62", "v65"} }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, {"v60", "v62", "v65"} }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, {"v60", "v62", "v65"} }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, {"v60", "v62", "v65"} }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, {"v60", "v62", "v65"} }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, {"v60", "v62", "v65"} }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, {"v60", "v62", "v65"} }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, {"v60", "v62", "v65"} }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, {"v60", "v62", "v65"} }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, {"v60", "v62", "v65"} }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, {"v60", "v62", "v65"} }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, {"v60", "v62", "v65"} }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {"v60", "v62", "v65"} }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {"v60", "v62", "v65"} }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, {"v62", "v65"} }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, {"v62", "v65"} }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, {"v60", "v62", "v65"} }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, {"v60", "v62", "v65"} }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, {"v60", "v62", "v65"} }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, {"v60", "v62", "v65"} }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, {"v60", "v62", "v65"} }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, {"v60", "v62", "v65"} }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, {"v60", "v62", "v65"} }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, {"v60", "v62", "v65"} }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, {"v65"} }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, {"v65"} }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, {"v60", "v62", "v65"} }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, {"v60", "v62", "v65"} }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {"v62", "v65"} }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {"v62", "v65"} }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, {"v62", "v65"} }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, {"v62", "v65"} }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, {"v60", "v62", "v65"} }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, {"v60", "v62", "v65"} }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {"v62", "v65"} }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, {"v62", "v65"} }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, {"v60", "v62", "v65"} }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, {"v60", "v62", "v65"} }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {"v62", "v65"} }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {"v62", "v65"} }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, {"v62", "v65"} }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, {"v62", "v65"} }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, {"v60", "v62", "v65"} }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, {"v60", "v62", "v65"} }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {"v62", "v65"} }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, {"v62", "v65"} }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, {"v62", "v65"} }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, {"v62", "v65"} }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, {"v60", "v62", "v65"} }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, {"v60", "v62", "v65"} }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, {"v60", "v62", "v65"} }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, {"v60", "v62", "v65"} }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, {"v60", "v62", "v65"} }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, {"v60", "v62", "v65"} }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, {"v60", "v62", "v65"} }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, {"v60", "v62", "v65"} }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vminb, {"v62", "v65"} }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, {"v62", "v65"} }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vminh, {"v60", "v62", "v65"} }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, {"v60", "v62", "v65"} }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vminub, {"v60", "v62", "v65"} }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, {"v60", "v62", "v65"} }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, {"v60", "v62", "v65"} }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, {"v60", "v62", "v65"} }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vminw, {"v60", "v62", "v65"} }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, {"v60", "v62", "v65"} }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, {"v60", "v62", "v65"} }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, {"v60", "v62", "v65"} }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, {"v60", "v62", "v65"} }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, {"v60", "v62", "v65"} }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, {"v60", "v62", "v65"} }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, {"v60", "v62", "v65"} }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, {"v65"} }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, {"v65"} }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, {"v65"} }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, {"v65"} }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, {"v60", "v62", "v65"} }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, {"v60", "v62", "v65"} }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, {"v60", "v62", "v65"} }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, {"v60", "v62", "v65"} }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, {"v60", "v62", "v65"} }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, {"v60", "v62", "v65"} }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, {"v65"} }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, {"v65"} }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, {"v62", "v65"} }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, {"v62", "v65"} }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, {"v62", "v65"} }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, {"v62", "v65"} }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, {"v65"} }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, {"v65"} }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, {"v65"} }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, {"v65"} }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, {"v60", "v62", "v65"} }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, {"v60", "v62", "v65"} }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, {"v60", "v62", "v65"} }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, {"v60", "v62", "v65"} }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, {"v60", "v62", "v65"} }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, {"v60", "v62", "v65"} }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, {"v60", "v62", "v65"} }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, {"v60", "v62", "v65"} }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, {"v60", "v62", "v65"} }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, {"v60", "v62", "v65"} }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, {"v60", "v62", "v65"} }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, {"v60", "v62", "v65"} }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, {"v60", "v62", "v65"} }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, {"v60", "v62", "v65"} }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, {"v62", "v65"} }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, {"v62", "v65"} }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, {"v60", "v62", "v65"} }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, {"v60", "v62", "v65"} }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, {"v65"} }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, {"v65"} }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, {"v60", "v62", "v65"} }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, {"v60", "v62", "v65"} }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, {"v60", "v62", "v65"} }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, {"v60", "v62", "v65"} }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, {"v60", "v62", "v65"} }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, {"v60", "v62", "v65"} }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, {"v60", "v62", "v65"} }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, {"v60", "v62", "v65"} }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, {"v60", "v62", "v65"} }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, {"v60", "v62", "v65"} }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, {"v60", "v62", "v65"} }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, {"v60", "v62", "v65"} }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, {"v60", "v62", "v65"} }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, {"v60", "v62", "v65"} }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, {"v60", "v62", "v65"} }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, {"v60", "v62", "v65"} }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, {"v60", "v62", "v65"} }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, {"v60", "v62", "v65"} }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, {"v60", "v62", "v65"} }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, {"v60", "v62", "v65"} }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, {"v60", "v62", "v65"} }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, {"v60", "v62", "v65"} }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, {"v60", "v62", "v65"} }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, {"v60", "v62", "v65"} }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, {"v60", "v62", "v65"} }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, {"v60", "v62", "v65"} }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, {"v60", "v62", "v65"} }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, {"v60", "v62", "v65"} }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, {"v60", "v62", "v65"} }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, {"v60", "v62", "v65"} }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, {"v60", "v62", "v65"} }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, {"v60", "v62", "v65"} }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, {"v60", "v62", "v65"} }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, {"v60", "v62", "v65"} }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, {"v60", "v62", "v65"} }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, {"v60", "v62", "v65"} }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, {"v60", "v62", "v65"} }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, {"v60", "v62", "v65"} }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, {"v60", "v62", "v65"} }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, {"v60", "v62", "v65"} }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, {"v60", "v62", "v65"} }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, {"v60", "v62", "v65"} }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, {"v62", "v65"} }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, {"v62", "v65"} }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, {"v62", "v65"} }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, {"v62", "v65"} }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, {"v60", "v62", "v65"} }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, {"v60", "v62", "v65"} }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, {"v62", "v65"} }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, {"v62", "v65"} }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, {"v60", "v62", "v65"} }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, {"v60", "v62", "v65"} }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, {"v60", "v62", "v65"} }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, {"v60", "v62", "v65"} }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, {"v60", "v62", "v65"} }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, {"v60", "v62", "v65"} }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, {"v60", "v62", "v65"} }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, {"v60", "v62", "v65"} }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, {"v60", "v62", "v65"} }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, {"v60", "v62", "v65"} }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, {"v60", "v62", "v65"} }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, {"v60", "v62", "v65"} }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, {"v60", "v62", "v65"} }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, {"v60", "v62", "v65"} }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, {"v60", "v62", "v65"} }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, {"v60", "v62", "v65"} }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, {"v60", "v62", "v65"} }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, {"v60", "v62", "v65"} }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, {"v65"} }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, {"v65"} }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, {"v65"} }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, {"v65"} }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, {"v60", "v62", "v65"} }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, {"v60", "v62", "v65"} }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, {"v60", "v62", "v65"} }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, {"v60", "v62", "v65"} }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vmux, {"v60", "v62", "v65"} }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, {"v60", "v62", "v65"} }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, {"v65"} }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, {"v65"} }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, {"v60", "v62", "v65"} }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, {"v60", "v62", "v65"} }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, {"v60", "v62", "v65"} }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, {"v60", "v62", "v65"} }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, {"v60", "v62", "v65"} }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, {"v60", "v62", "v65"} }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, {"v60", "v62", "v65"} }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, {"v60", "v62", "v65"} }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, {"v60", "v62", "v65"} }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, {"v60", "v62", "v65"} }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vnot, {"v60", "v62", "v65"} }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, {"v60", "v62", "v65"} }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vor, {"v60", "v62", "v65"} }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, {"v60", "v62", "v65"} }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, {"v60", "v62", "v65"} }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, {"v60", "v62", "v65"} }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, {"v60", "v62", "v65"} }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, {"v60", "v62", "v65"} }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, {"v60", "v62", "v65"} }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, {"v60", "v62", "v65"} }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, {"v60", "v62", "v65"} }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, {"v60", "v62", "v65"} }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, {"v60", "v62", "v65"} }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, {"v60", "v62", "v65"} }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, {"v60", "v62", "v65"} }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, {"v60", "v62", "v65"} }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, {"v60", "v62", "v65"} }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, {"v60", "v62", "v65"} }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, {"v60", "v62", "v65"} }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, {"v60", "v62", "v65"} }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, {"v60", "v62", "v65"} }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, {"v60", "v62", "v65"} }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, {"v65"} }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, {"v65"} }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, {"v65"} }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, {"v65"} }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, {"v65"} }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, {"v65"} }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, {"v60", "v62", "v65"} }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, {"v60", "v62", "v65"} }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, {"v65"} }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, {"v65"} }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, {"v65"} }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, {"v65"} }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, {"v60", "v62", "v65"} }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, {"v60", "v62", "v65"} }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, {"v60", "v62", "v65"} }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, {"v60", "v62", "v65"} }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {"v60", "v62", "v65"} }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {"v60", "v62", "v65"} }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {"v60", "v62", "v65"} }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, {"v60", "v62", "v65"} }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, {"v60", "v62", "v65"} }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, {"v60", "v62", "v65"} }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, {"v60", "v62", "v65"} }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, {"v60", "v62", "v65"} }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, {"v60", "v62", "v65"} }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, {"v60", "v62", "v65"} }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, {"v60", "v62", "v65"} }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, {"v60", "v62", "v65"} }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, {"v60", "v62", "v65"} }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, {"v60", "v62", "v65"} }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, {"v60", "v62", "v65"} }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, {"v60", "v62", "v65"} }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {"v60", "v62", "v65"} }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {"v60", "v62", "v65"} }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {"v60", "v62", "v65"} }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, {"v60", "v62", "v65"} }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, {"v65"} }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, {"v65"} }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, {"v65"} }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, {"v65"} }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, {"v60", "v62", "v65"} }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, {"v60", "v62", "v65"} }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, {"v60", "v62", "v65"} }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, {"v60", "v62", "v65"} }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vror, {"v60", "v62", "v65"} }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, {"v60", "v62", "v65"} }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, {"v60", "v62", "v65"} }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, {"v60", "v62", "v65"} }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, {"v60", "v62", "v65"} }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, {"v60", "v62", "v65"} }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, {"v62", "v65"} }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, {"v62", "v65"} }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, {"v62", "v65"} }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, {"v62", "v65"} }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, {"v60", "v62", "v65"} }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, {"v60", "v62", "v65"} }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, {"v60", "v62", "v65"} }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, {"v60", "v62", "v65"} }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {"v60", "v62", "v65"} }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {"v60", "v62", "v65"} }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {"v60", "v62", "v65"} }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, {"v60", "v62", "v65"} }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, {"v60", "v62", "v65"} }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, {"v60", "v62", "v65"} }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, {"v62", "v65"} }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, {"v62", "v65"} }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, {"v60", "v62", "v65"} }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, {"v60", "v62", "v65"} }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vsb, {"v60", "v62", "v65"} }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, {"v60", "v62", "v65"} }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vsh, {"v60", "v62", "v65"} }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, {"v60", "v62", "v65"} }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, {"v60", "v62", "v65"} }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, {"v60", "v62", "v65"} }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, {"v60", "v62", "v65"} }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, {"v60", "v62", "v65"} }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, {"v60", "v62", "v65"} }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, {"v60", "v62", "v65"} }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, {"v60", "v62", "v65"} }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, {"v60", "v62", "v65"} }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, {"v60", "v62", "v65"} }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, {"v60", "v62", "v65"} }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, {"v60", "v62", "v65"} }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, {"v60", "v62", "v65"} }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, {"v60", "v62", "v65"} }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, {"v60", "v62", "v65"} }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, {"v60", "v62", "v65"} }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, {"v60", "v62", "v65"} }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, {"v60", "v62", "v65"} }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, {"v60", "v62", "v65"} }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, {"v60", "v62", "v65"} }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, {"v60", "v62", "v65"} }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, {"v60", "v62", "v65"} }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, {"v60", "v62", "v65"} }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, {"v62", "v65"} }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, {"v62", "v65"} }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, {"v62", "v65"} }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, {"v62", "v65"} }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, {"v62", "v65"} }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, {"v62", "v65"} }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, {"v60", "v62", "v65"} }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, {"v60", "v62", "v65"} }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, {"v60", "v62", "v65"} }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, {"v60", "v62", "v65"} }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, {"v60", "v62", "v65"} }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, {"v60", "v62", "v65"} }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, {"v60", "v62", "v65"} }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, {"v60", "v62", "v65"} }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, {"v60", "v62", "v65"} }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, {"v60", "v62", "v65"} }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, {"v60", "v62", "v65"} }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, {"v60", "v62", "v65"} }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, {"v60", "v62", "v65"} }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, {"v60", "v62", "v65"} }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, {"v60", "v62", "v65"} }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, {"v60", "v62", "v65"} }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, {"v62", "v65"} }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, {"v62", "v65"} }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, {"v60", "v62", "v65"} }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, {"v60", "v62", "v65"} }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, {"v60", "v62", "v65"} }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, {"v60", "v62", "v65"} }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, {"v60", "v62", "v65"} }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, {"v60", "v62", "v65"} }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, {"v62", "v65"} }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, {"v62", "v65"} }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, {"v62", "v65"} }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, {"v62", "v65"} }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, {"v60", "v62", "v65"} }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, {"v60", "v62", "v65"} }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, {"v60", "v62", "v65"} }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, {"v60", "v62", "v65"} }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, {"v60", "v62", "v65"} }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, {"v60", "v62", "v65"} }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, {"v60", "v62", "v65"} }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, {"v60", "v62", "v65"} }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vswap, {"v60", "v62", "v65"} }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, {"v60", "v62", "v65"} }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, {"v60", "v62", "v65"} }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, {"v60", "v62", "v65"} }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, {"v60", "v62", "v65"} }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, {"v60", "v62", "v65"} }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, {"v60", "v62", "v65"} }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, {"v60", "v62", "v65"} }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, {"v60", "v62", "v65"} }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, {"v60", "v62", "v65"} }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, {"v60", "v62", "v65"} }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, {"v60", "v62", "v65"} }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, {"v60", "v62", "v65"} }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, {"v60", "v62", "v65"} }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, {"v60", "v62", "v65"} }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, {"v60", "v62", "v65"} }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, {"v60", "v62", "v65"} }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, {"v60", "v62", "v65"} }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, {"v60", "v62", "v65"} }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, {"v60", "v62", "v65"} }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, {"v60", "v62", "v65"} }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, {"v60", "v62", "v65"} }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, {"v60", "v62", "v65"} }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, {"v60", "v62", "v65"} }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, {"v60", "v62", "v65"} }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, {"v60", "v62", "v65"} }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vxor, {"v60", "v62", "v65"} }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, {"v60", "v62", "v65"} }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vzb, {"v60", "v62", "v65"} }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, {"v60", "v62", "v65"} }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vzh, {"v60", "v62", "v65"} }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, {"v60", "v62", "v65"} }, 2478 }; 2479 2480 const TargetInfo &TI = Context.getTargetInfo(); 2481 2482 auto FC = ValidCPU.find(BuiltinID); 2483 if (FC != ValidCPU.end()) { 2484 const TargetOptions &Opts = TI.getTargetOpts(); 2485 StringRef CPU = Opts.CPU; 2486 if (!CPU.empty()) { 2487 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2488 CPU.consume_front("hexagon"); 2489 if (llvm::none_of(FC->second, [CPU](StringRef S) { return S == CPU; })) 2490 return Diag(TheCall->getBeginLoc(), 2491 diag::err_hexagon_builtin_unsupported_cpu); 2492 } 2493 } 2494 2495 auto FH = ValidHVX.find(BuiltinID); 2496 if (FH != ValidHVX.end()) { 2497 if (!TI.hasFeature("hvx")) 2498 return Diag(TheCall->getBeginLoc(), 2499 diag::err_hexagon_builtin_requires_hvx); 2500 2501 bool IsValid = llvm::any_of(FH->second, 2502 [&TI] (StringRef V) { 2503 std::string F = "hvx" + V.str(); 2504 return TI.hasFeature(F); 2505 }); 2506 if (!IsValid) 2507 return Diag(TheCall->getBeginLoc(), 2508 diag::err_hexagon_builtin_unsupported_hvx); 2509 } 2510 2511 return false; 2512 } 2513 2514 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2515 struct ArgInfo { 2516 ArgInfo(unsigned O, bool S, unsigned W, unsigned A) 2517 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {} 2518 unsigned OpNum = 0; 2519 bool IsSigned = false; 2520 unsigned BitWidth = 0; 2521 unsigned Align = 0; 2522 }; 2523 2524 static const std::map<unsigned, std::vector<ArgInfo>> Infos = { 2525 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2526 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2527 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2528 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2529 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2530 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2531 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2532 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2533 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2534 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2535 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2536 2537 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2538 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2539 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2540 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2541 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2542 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2543 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2544 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2545 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2546 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2547 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2548 2549 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2550 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2551 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2552 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2553 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2554 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2555 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2556 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2557 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2558 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2559 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2560 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2561 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2562 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2563 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2564 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2565 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2566 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2567 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2568 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2569 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2570 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2571 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2572 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2573 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2574 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2575 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2576 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2577 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2578 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2579 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2580 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2581 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2582 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2583 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2584 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2585 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2586 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2587 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2588 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2589 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2590 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2591 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2592 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2593 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2594 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2595 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2596 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2597 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2598 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2599 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2600 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2601 {{ 1, false, 6, 0 }} }, 2602 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2603 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2604 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2605 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2606 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2607 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2608 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2609 {{ 1, false, 5, 0 }} }, 2610 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2611 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2612 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2613 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2614 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2615 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2616 { 2, false, 5, 0 }} }, 2617 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2618 { 2, false, 6, 0 }} }, 2619 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2620 { 3, false, 5, 0 }} }, 2621 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2622 { 3, false, 6, 0 }} }, 2623 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2624 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2625 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2626 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2627 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2628 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2629 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2630 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2631 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2632 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2633 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2634 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2635 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2636 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2637 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2639 {{ 2, false, 4, 0 }, 2640 { 3, false, 5, 0 }} }, 2641 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2642 {{ 2, false, 4, 0 }, 2643 { 3, false, 5, 0 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2645 {{ 2, false, 4, 0 }, 2646 { 3, false, 5, 0 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2648 {{ 2, false, 4, 0 }, 2649 { 3, false, 5, 0 }} }, 2650 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2652 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2653 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2656 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2657 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2658 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2659 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2660 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2661 { 2, false, 5, 0 }} }, 2662 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2663 { 2, false, 6, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2668 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2670 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2672 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2673 {{ 1, false, 4, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2675 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2676 {{ 1, false, 4, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2679 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2680 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2683 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2685 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2686 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2697 {{ 3, false, 1, 0 }} }, 2698 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2701 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2702 {{ 3, false, 1, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2706 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2707 {{ 3, false, 1, 0 }} }, 2708 }; 2709 2710 auto F = Infos.find(BuiltinID); 2711 if (F == Infos.end()) 2712 return false; 2713 2714 bool Error = false; 2715 2716 for (const ArgInfo &A : F->second) { 2717 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0; 2718 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1; 2719 if (!A.Align) { 2720 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2721 } else { 2722 unsigned M = 1 << A.Align; 2723 Min *= M; 2724 Max *= M; 2725 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2726 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2727 } 2728 } 2729 return Error; 2730 } 2731 2732 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2733 CallExpr *TheCall) { 2734 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2735 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2736 } 2737 2738 2739 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 2740 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2741 // ordering for DSP is unspecified. MSA is ordered by the data format used 2742 // by the underlying instruction i.e., df/m, df/n and then by size. 2743 // 2744 // FIXME: The size tests here should instead be tablegen'd along with the 2745 // definitions from include/clang/Basic/BuiltinsMips.def. 2746 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2747 // be too. 2748 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2749 unsigned i = 0, l = 0, u = 0, m = 0; 2750 switch (BuiltinID) { 2751 default: return false; 2752 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2753 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2754 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2755 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2756 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2757 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2758 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2759 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 2760 // df/m field. 2761 // These intrinsics take an unsigned 3 bit immediate. 2762 case Mips::BI__builtin_msa_bclri_b: 2763 case Mips::BI__builtin_msa_bnegi_b: 2764 case Mips::BI__builtin_msa_bseti_b: 2765 case Mips::BI__builtin_msa_sat_s_b: 2766 case Mips::BI__builtin_msa_sat_u_b: 2767 case Mips::BI__builtin_msa_slli_b: 2768 case Mips::BI__builtin_msa_srai_b: 2769 case Mips::BI__builtin_msa_srari_b: 2770 case Mips::BI__builtin_msa_srli_b: 2771 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2772 case Mips::BI__builtin_msa_binsli_b: 2773 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2774 // These intrinsics take an unsigned 4 bit immediate. 2775 case Mips::BI__builtin_msa_bclri_h: 2776 case Mips::BI__builtin_msa_bnegi_h: 2777 case Mips::BI__builtin_msa_bseti_h: 2778 case Mips::BI__builtin_msa_sat_s_h: 2779 case Mips::BI__builtin_msa_sat_u_h: 2780 case Mips::BI__builtin_msa_slli_h: 2781 case Mips::BI__builtin_msa_srai_h: 2782 case Mips::BI__builtin_msa_srari_h: 2783 case Mips::BI__builtin_msa_srli_h: 2784 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2785 case Mips::BI__builtin_msa_binsli_h: 2786 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2787 // These intrinsics take an unsigned 5 bit immediate. 2788 // The first block of intrinsics actually have an unsigned 5 bit field, 2789 // not a df/n field. 2790 case Mips::BI__builtin_msa_clei_u_b: 2791 case Mips::BI__builtin_msa_clei_u_h: 2792 case Mips::BI__builtin_msa_clei_u_w: 2793 case Mips::BI__builtin_msa_clei_u_d: 2794 case Mips::BI__builtin_msa_clti_u_b: 2795 case Mips::BI__builtin_msa_clti_u_h: 2796 case Mips::BI__builtin_msa_clti_u_w: 2797 case Mips::BI__builtin_msa_clti_u_d: 2798 case Mips::BI__builtin_msa_maxi_u_b: 2799 case Mips::BI__builtin_msa_maxi_u_h: 2800 case Mips::BI__builtin_msa_maxi_u_w: 2801 case Mips::BI__builtin_msa_maxi_u_d: 2802 case Mips::BI__builtin_msa_mini_u_b: 2803 case Mips::BI__builtin_msa_mini_u_h: 2804 case Mips::BI__builtin_msa_mini_u_w: 2805 case Mips::BI__builtin_msa_mini_u_d: 2806 case Mips::BI__builtin_msa_addvi_b: 2807 case Mips::BI__builtin_msa_addvi_h: 2808 case Mips::BI__builtin_msa_addvi_w: 2809 case Mips::BI__builtin_msa_addvi_d: 2810 case Mips::BI__builtin_msa_bclri_w: 2811 case Mips::BI__builtin_msa_bnegi_w: 2812 case Mips::BI__builtin_msa_bseti_w: 2813 case Mips::BI__builtin_msa_sat_s_w: 2814 case Mips::BI__builtin_msa_sat_u_w: 2815 case Mips::BI__builtin_msa_slli_w: 2816 case Mips::BI__builtin_msa_srai_w: 2817 case Mips::BI__builtin_msa_srari_w: 2818 case Mips::BI__builtin_msa_srli_w: 2819 case Mips::BI__builtin_msa_srlri_w: 2820 case Mips::BI__builtin_msa_subvi_b: 2821 case Mips::BI__builtin_msa_subvi_h: 2822 case Mips::BI__builtin_msa_subvi_w: 2823 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2824 case Mips::BI__builtin_msa_binsli_w: 2825 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2826 // These intrinsics take an unsigned 6 bit immediate. 2827 case Mips::BI__builtin_msa_bclri_d: 2828 case Mips::BI__builtin_msa_bnegi_d: 2829 case Mips::BI__builtin_msa_bseti_d: 2830 case Mips::BI__builtin_msa_sat_s_d: 2831 case Mips::BI__builtin_msa_sat_u_d: 2832 case Mips::BI__builtin_msa_slli_d: 2833 case Mips::BI__builtin_msa_srai_d: 2834 case Mips::BI__builtin_msa_srari_d: 2835 case Mips::BI__builtin_msa_srli_d: 2836 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2837 case Mips::BI__builtin_msa_binsli_d: 2838 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2839 // These intrinsics take a signed 5 bit immediate. 2840 case Mips::BI__builtin_msa_ceqi_b: 2841 case Mips::BI__builtin_msa_ceqi_h: 2842 case Mips::BI__builtin_msa_ceqi_w: 2843 case Mips::BI__builtin_msa_ceqi_d: 2844 case Mips::BI__builtin_msa_clti_s_b: 2845 case Mips::BI__builtin_msa_clti_s_h: 2846 case Mips::BI__builtin_msa_clti_s_w: 2847 case Mips::BI__builtin_msa_clti_s_d: 2848 case Mips::BI__builtin_msa_clei_s_b: 2849 case Mips::BI__builtin_msa_clei_s_h: 2850 case Mips::BI__builtin_msa_clei_s_w: 2851 case Mips::BI__builtin_msa_clei_s_d: 2852 case Mips::BI__builtin_msa_maxi_s_b: 2853 case Mips::BI__builtin_msa_maxi_s_h: 2854 case Mips::BI__builtin_msa_maxi_s_w: 2855 case Mips::BI__builtin_msa_maxi_s_d: 2856 case Mips::BI__builtin_msa_mini_s_b: 2857 case Mips::BI__builtin_msa_mini_s_h: 2858 case Mips::BI__builtin_msa_mini_s_w: 2859 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2860 // These intrinsics take an unsigned 8 bit immediate. 2861 case Mips::BI__builtin_msa_andi_b: 2862 case Mips::BI__builtin_msa_nori_b: 2863 case Mips::BI__builtin_msa_ori_b: 2864 case Mips::BI__builtin_msa_shf_b: 2865 case Mips::BI__builtin_msa_shf_h: 2866 case Mips::BI__builtin_msa_shf_w: 2867 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2868 case Mips::BI__builtin_msa_bseli_b: 2869 case Mips::BI__builtin_msa_bmnzi_b: 2870 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2871 // df/n format 2872 // These intrinsics take an unsigned 4 bit immediate. 2873 case Mips::BI__builtin_msa_copy_s_b: 2874 case Mips::BI__builtin_msa_copy_u_b: 2875 case Mips::BI__builtin_msa_insve_b: 2876 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2877 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2878 // These intrinsics take an unsigned 3 bit immediate. 2879 case Mips::BI__builtin_msa_copy_s_h: 2880 case Mips::BI__builtin_msa_copy_u_h: 2881 case Mips::BI__builtin_msa_insve_h: 2882 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2883 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2884 // These intrinsics take an unsigned 2 bit immediate. 2885 case Mips::BI__builtin_msa_copy_s_w: 2886 case Mips::BI__builtin_msa_copy_u_w: 2887 case Mips::BI__builtin_msa_insve_w: 2888 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2889 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2890 // These intrinsics take an unsigned 1 bit immediate. 2891 case Mips::BI__builtin_msa_copy_s_d: 2892 case Mips::BI__builtin_msa_copy_u_d: 2893 case Mips::BI__builtin_msa_insve_d: 2894 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2895 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2896 // Memory offsets and immediate loads. 2897 // These intrinsics take a signed 10 bit immediate. 2898 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2899 case Mips::BI__builtin_msa_ldi_h: 2900 case Mips::BI__builtin_msa_ldi_w: 2901 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2902 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 2903 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 2904 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 2905 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 2906 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 2907 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 2908 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 2909 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 2910 } 2911 2912 if (!m) 2913 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2914 2915 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2916 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2917 } 2918 2919 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2920 unsigned i = 0, l = 0, u = 0; 2921 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2922 BuiltinID == PPC::BI__builtin_divdeu || 2923 BuiltinID == PPC::BI__builtin_bpermd; 2924 bool IsTarget64Bit = Context.getTargetInfo() 2925 .getTypeWidth(Context 2926 .getTargetInfo() 2927 .getIntPtrType()) == 64; 2928 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2929 BuiltinID == PPC::BI__builtin_divweu || 2930 BuiltinID == PPC::BI__builtin_divde || 2931 BuiltinID == PPC::BI__builtin_divdeu; 2932 2933 if (Is64BitBltin && !IsTarget64Bit) 2934 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 2935 << TheCall->getSourceRange(); 2936 2937 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2938 (BuiltinID == PPC::BI__builtin_bpermd && 2939 !Context.getTargetInfo().hasFeature("bpermd"))) 2940 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2941 << TheCall->getSourceRange(); 2942 2943 switch (BuiltinID) { 2944 default: return false; 2945 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 2946 case PPC::BI__builtin_altivec_crypto_vshasigmad: 2947 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2948 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2949 case PPC::BI__builtin_tbegin: 2950 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 2951 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 2952 case PPC::BI__builtin_tabortwc: 2953 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 2954 case PPC::BI__builtin_tabortwci: 2955 case PPC::BI__builtin_tabortdci: 2956 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 2957 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 2958 case PPC::BI__builtin_vsx_xxpermdi: 2959 case PPC::BI__builtin_vsx_xxsldwi: 2960 return SemaBuiltinVSX(TheCall); 2961 } 2962 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2963 } 2964 2965 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 2966 CallExpr *TheCall) { 2967 if (BuiltinID == SystemZ::BI__builtin_tabort) { 2968 Expr *Arg = TheCall->getArg(0); 2969 llvm::APSInt AbortCode(32); 2970 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 2971 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 2972 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 2973 << Arg->getSourceRange(); 2974 } 2975 2976 // For intrinsics which take an immediate value as part of the instruction, 2977 // range check them here. 2978 unsigned i = 0, l = 0, u = 0; 2979 switch (BuiltinID) { 2980 default: return false; 2981 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 2982 case SystemZ::BI__builtin_s390_verimb: 2983 case SystemZ::BI__builtin_s390_verimh: 2984 case SystemZ::BI__builtin_s390_verimf: 2985 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 2986 case SystemZ::BI__builtin_s390_vfaeb: 2987 case SystemZ::BI__builtin_s390_vfaeh: 2988 case SystemZ::BI__builtin_s390_vfaef: 2989 case SystemZ::BI__builtin_s390_vfaebs: 2990 case SystemZ::BI__builtin_s390_vfaehs: 2991 case SystemZ::BI__builtin_s390_vfaefs: 2992 case SystemZ::BI__builtin_s390_vfaezb: 2993 case SystemZ::BI__builtin_s390_vfaezh: 2994 case SystemZ::BI__builtin_s390_vfaezf: 2995 case SystemZ::BI__builtin_s390_vfaezbs: 2996 case SystemZ::BI__builtin_s390_vfaezhs: 2997 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 2998 case SystemZ::BI__builtin_s390_vfisb: 2999 case SystemZ::BI__builtin_s390_vfidb: 3000 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3001 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3002 case SystemZ::BI__builtin_s390_vftcisb: 3003 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3004 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3005 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3006 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3007 case SystemZ::BI__builtin_s390_vstrcb: 3008 case SystemZ::BI__builtin_s390_vstrch: 3009 case SystemZ::BI__builtin_s390_vstrcf: 3010 case SystemZ::BI__builtin_s390_vstrczb: 3011 case SystemZ::BI__builtin_s390_vstrczh: 3012 case SystemZ::BI__builtin_s390_vstrczf: 3013 case SystemZ::BI__builtin_s390_vstrcbs: 3014 case SystemZ::BI__builtin_s390_vstrchs: 3015 case SystemZ::BI__builtin_s390_vstrcfs: 3016 case SystemZ::BI__builtin_s390_vstrczbs: 3017 case SystemZ::BI__builtin_s390_vstrczhs: 3018 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3019 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3020 case SystemZ::BI__builtin_s390_vfminsb: 3021 case SystemZ::BI__builtin_s390_vfmaxsb: 3022 case SystemZ::BI__builtin_s390_vfmindb: 3023 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3024 } 3025 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3026 } 3027 3028 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3029 /// This checks that the target supports __builtin_cpu_supports and 3030 /// that the string argument is constant and valid. 3031 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3032 Expr *Arg = TheCall->getArg(0); 3033 3034 // Check if the argument is a string literal. 3035 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3036 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3037 << Arg->getSourceRange(); 3038 3039 // Check the contents of the string. 3040 StringRef Feature = 3041 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3042 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3043 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3044 << Arg->getSourceRange(); 3045 return false; 3046 } 3047 3048 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3049 /// This checks that the target supports __builtin_cpu_is and 3050 /// that the string argument is constant and valid. 3051 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3052 Expr *Arg = TheCall->getArg(0); 3053 3054 // Check if the argument is a string literal. 3055 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3056 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3057 << Arg->getSourceRange(); 3058 3059 // Check the contents of the string. 3060 StringRef Feature = 3061 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3062 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3063 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3064 << Arg->getSourceRange(); 3065 return false; 3066 } 3067 3068 // Check if the rounding mode is legal. 3069 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3070 // Indicates if this instruction has rounding control or just SAE. 3071 bool HasRC = false; 3072 3073 unsigned ArgNum = 0; 3074 switch (BuiltinID) { 3075 default: 3076 return false; 3077 case X86::BI__builtin_ia32_vcvttsd2si32: 3078 case X86::BI__builtin_ia32_vcvttsd2si64: 3079 case X86::BI__builtin_ia32_vcvttsd2usi32: 3080 case X86::BI__builtin_ia32_vcvttsd2usi64: 3081 case X86::BI__builtin_ia32_vcvttss2si32: 3082 case X86::BI__builtin_ia32_vcvttss2si64: 3083 case X86::BI__builtin_ia32_vcvttss2usi32: 3084 case X86::BI__builtin_ia32_vcvttss2usi64: 3085 ArgNum = 1; 3086 break; 3087 case X86::BI__builtin_ia32_maxpd512: 3088 case X86::BI__builtin_ia32_maxps512: 3089 case X86::BI__builtin_ia32_minpd512: 3090 case X86::BI__builtin_ia32_minps512: 3091 ArgNum = 2; 3092 break; 3093 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3094 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3095 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3096 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3097 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3098 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3099 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3100 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3101 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3102 case X86::BI__builtin_ia32_exp2pd_mask: 3103 case X86::BI__builtin_ia32_exp2ps_mask: 3104 case X86::BI__builtin_ia32_getexppd512_mask: 3105 case X86::BI__builtin_ia32_getexpps512_mask: 3106 case X86::BI__builtin_ia32_rcp28pd_mask: 3107 case X86::BI__builtin_ia32_rcp28ps_mask: 3108 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3109 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3110 case X86::BI__builtin_ia32_vcomisd: 3111 case X86::BI__builtin_ia32_vcomiss: 3112 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3113 ArgNum = 3; 3114 break; 3115 case X86::BI__builtin_ia32_cmppd512_mask: 3116 case X86::BI__builtin_ia32_cmpps512_mask: 3117 case X86::BI__builtin_ia32_cmpsd_mask: 3118 case X86::BI__builtin_ia32_cmpss_mask: 3119 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3120 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3121 case X86::BI__builtin_ia32_getexpss128_round_mask: 3122 case X86::BI__builtin_ia32_maxsd_round_mask: 3123 case X86::BI__builtin_ia32_maxss_round_mask: 3124 case X86::BI__builtin_ia32_minsd_round_mask: 3125 case X86::BI__builtin_ia32_minss_round_mask: 3126 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3127 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3128 case X86::BI__builtin_ia32_reducepd512_mask: 3129 case X86::BI__builtin_ia32_reduceps512_mask: 3130 case X86::BI__builtin_ia32_rndscalepd_mask: 3131 case X86::BI__builtin_ia32_rndscaleps_mask: 3132 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3133 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3134 ArgNum = 4; 3135 break; 3136 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3137 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3138 case X86::BI__builtin_ia32_fixupimmps512_mask: 3139 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3140 case X86::BI__builtin_ia32_fixupimmsd_mask: 3141 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3142 case X86::BI__builtin_ia32_fixupimmss_mask: 3143 case X86::BI__builtin_ia32_fixupimmss_maskz: 3144 case X86::BI__builtin_ia32_rangepd512_mask: 3145 case X86::BI__builtin_ia32_rangeps512_mask: 3146 case X86::BI__builtin_ia32_rangesd128_round_mask: 3147 case X86::BI__builtin_ia32_rangess128_round_mask: 3148 case X86::BI__builtin_ia32_reducesd_mask: 3149 case X86::BI__builtin_ia32_reducess_mask: 3150 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3151 case X86::BI__builtin_ia32_rndscaless_round_mask: 3152 ArgNum = 5; 3153 break; 3154 case X86::BI__builtin_ia32_vcvtsd2si64: 3155 case X86::BI__builtin_ia32_vcvtsd2si32: 3156 case X86::BI__builtin_ia32_vcvtsd2usi32: 3157 case X86::BI__builtin_ia32_vcvtsd2usi64: 3158 case X86::BI__builtin_ia32_vcvtss2si32: 3159 case X86::BI__builtin_ia32_vcvtss2si64: 3160 case X86::BI__builtin_ia32_vcvtss2usi32: 3161 case X86::BI__builtin_ia32_vcvtss2usi64: 3162 case X86::BI__builtin_ia32_sqrtpd512: 3163 case X86::BI__builtin_ia32_sqrtps512: 3164 ArgNum = 1; 3165 HasRC = true; 3166 break; 3167 case X86::BI__builtin_ia32_addpd512: 3168 case X86::BI__builtin_ia32_addps512: 3169 case X86::BI__builtin_ia32_divpd512: 3170 case X86::BI__builtin_ia32_divps512: 3171 case X86::BI__builtin_ia32_mulpd512: 3172 case X86::BI__builtin_ia32_mulps512: 3173 case X86::BI__builtin_ia32_subpd512: 3174 case X86::BI__builtin_ia32_subps512: 3175 case X86::BI__builtin_ia32_cvtsi2sd64: 3176 case X86::BI__builtin_ia32_cvtsi2ss32: 3177 case X86::BI__builtin_ia32_cvtsi2ss64: 3178 case X86::BI__builtin_ia32_cvtusi2sd64: 3179 case X86::BI__builtin_ia32_cvtusi2ss32: 3180 case X86::BI__builtin_ia32_cvtusi2ss64: 3181 ArgNum = 2; 3182 HasRC = true; 3183 break; 3184 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3185 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3186 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3187 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3188 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3189 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3190 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3191 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3192 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3193 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3194 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3195 ArgNum = 3; 3196 HasRC = true; 3197 break; 3198 case X86::BI__builtin_ia32_addss_round_mask: 3199 case X86::BI__builtin_ia32_addsd_round_mask: 3200 case X86::BI__builtin_ia32_divss_round_mask: 3201 case X86::BI__builtin_ia32_divsd_round_mask: 3202 case X86::BI__builtin_ia32_mulss_round_mask: 3203 case X86::BI__builtin_ia32_mulsd_round_mask: 3204 case X86::BI__builtin_ia32_subss_round_mask: 3205 case X86::BI__builtin_ia32_subsd_round_mask: 3206 case X86::BI__builtin_ia32_scalefpd512_mask: 3207 case X86::BI__builtin_ia32_scalefps512_mask: 3208 case X86::BI__builtin_ia32_scalefsd_round_mask: 3209 case X86::BI__builtin_ia32_scalefss_round_mask: 3210 case X86::BI__builtin_ia32_getmantpd512_mask: 3211 case X86::BI__builtin_ia32_getmantps512_mask: 3212 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3213 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3214 case X86::BI__builtin_ia32_sqrtss_round_mask: 3215 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3216 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3217 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3218 case X86::BI__builtin_ia32_vfmaddss3_mask: 3219 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3220 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3221 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3222 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3223 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3224 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3225 case X86::BI__builtin_ia32_vfmaddps512_mask: 3226 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3227 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3228 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3229 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3230 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3231 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3232 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3233 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3234 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3235 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3236 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3237 ArgNum = 4; 3238 HasRC = true; 3239 break; 3240 case X86::BI__builtin_ia32_getmantsd_round_mask: 3241 case X86::BI__builtin_ia32_getmantss_round_mask: 3242 ArgNum = 5; 3243 HasRC = true; 3244 break; 3245 } 3246 3247 llvm::APSInt Result; 3248 3249 // We can't check the value of a dependent argument. 3250 Expr *Arg = TheCall->getArg(ArgNum); 3251 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3252 return false; 3253 3254 // Check constant-ness first. 3255 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3256 return true; 3257 3258 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3259 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3260 // combined with ROUND_NO_EXC. 3261 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3262 Result == 8/*ROUND_NO_EXC*/ || 3263 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3264 return false; 3265 3266 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3267 << Arg->getSourceRange(); 3268 } 3269 3270 // Check if the gather/scatter scale is legal. 3271 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3272 CallExpr *TheCall) { 3273 unsigned ArgNum = 0; 3274 switch (BuiltinID) { 3275 default: 3276 return false; 3277 case X86::BI__builtin_ia32_gatherpfdpd: 3278 case X86::BI__builtin_ia32_gatherpfdps: 3279 case X86::BI__builtin_ia32_gatherpfqpd: 3280 case X86::BI__builtin_ia32_gatherpfqps: 3281 case X86::BI__builtin_ia32_scatterpfdpd: 3282 case X86::BI__builtin_ia32_scatterpfdps: 3283 case X86::BI__builtin_ia32_scatterpfqpd: 3284 case X86::BI__builtin_ia32_scatterpfqps: 3285 ArgNum = 3; 3286 break; 3287 case X86::BI__builtin_ia32_gatherd_pd: 3288 case X86::BI__builtin_ia32_gatherd_pd256: 3289 case X86::BI__builtin_ia32_gatherq_pd: 3290 case X86::BI__builtin_ia32_gatherq_pd256: 3291 case X86::BI__builtin_ia32_gatherd_ps: 3292 case X86::BI__builtin_ia32_gatherd_ps256: 3293 case X86::BI__builtin_ia32_gatherq_ps: 3294 case X86::BI__builtin_ia32_gatherq_ps256: 3295 case X86::BI__builtin_ia32_gatherd_q: 3296 case X86::BI__builtin_ia32_gatherd_q256: 3297 case X86::BI__builtin_ia32_gatherq_q: 3298 case X86::BI__builtin_ia32_gatherq_q256: 3299 case X86::BI__builtin_ia32_gatherd_d: 3300 case X86::BI__builtin_ia32_gatherd_d256: 3301 case X86::BI__builtin_ia32_gatherq_d: 3302 case X86::BI__builtin_ia32_gatherq_d256: 3303 case X86::BI__builtin_ia32_gather3div2df: 3304 case X86::BI__builtin_ia32_gather3div2di: 3305 case X86::BI__builtin_ia32_gather3div4df: 3306 case X86::BI__builtin_ia32_gather3div4di: 3307 case X86::BI__builtin_ia32_gather3div4sf: 3308 case X86::BI__builtin_ia32_gather3div4si: 3309 case X86::BI__builtin_ia32_gather3div8sf: 3310 case X86::BI__builtin_ia32_gather3div8si: 3311 case X86::BI__builtin_ia32_gather3siv2df: 3312 case X86::BI__builtin_ia32_gather3siv2di: 3313 case X86::BI__builtin_ia32_gather3siv4df: 3314 case X86::BI__builtin_ia32_gather3siv4di: 3315 case X86::BI__builtin_ia32_gather3siv4sf: 3316 case X86::BI__builtin_ia32_gather3siv4si: 3317 case X86::BI__builtin_ia32_gather3siv8sf: 3318 case X86::BI__builtin_ia32_gather3siv8si: 3319 case X86::BI__builtin_ia32_gathersiv8df: 3320 case X86::BI__builtin_ia32_gathersiv16sf: 3321 case X86::BI__builtin_ia32_gatherdiv8df: 3322 case X86::BI__builtin_ia32_gatherdiv16sf: 3323 case X86::BI__builtin_ia32_gathersiv8di: 3324 case X86::BI__builtin_ia32_gathersiv16si: 3325 case X86::BI__builtin_ia32_gatherdiv8di: 3326 case X86::BI__builtin_ia32_gatherdiv16si: 3327 case X86::BI__builtin_ia32_scatterdiv2df: 3328 case X86::BI__builtin_ia32_scatterdiv2di: 3329 case X86::BI__builtin_ia32_scatterdiv4df: 3330 case X86::BI__builtin_ia32_scatterdiv4di: 3331 case X86::BI__builtin_ia32_scatterdiv4sf: 3332 case X86::BI__builtin_ia32_scatterdiv4si: 3333 case X86::BI__builtin_ia32_scatterdiv8sf: 3334 case X86::BI__builtin_ia32_scatterdiv8si: 3335 case X86::BI__builtin_ia32_scattersiv2df: 3336 case X86::BI__builtin_ia32_scattersiv2di: 3337 case X86::BI__builtin_ia32_scattersiv4df: 3338 case X86::BI__builtin_ia32_scattersiv4di: 3339 case X86::BI__builtin_ia32_scattersiv4sf: 3340 case X86::BI__builtin_ia32_scattersiv4si: 3341 case X86::BI__builtin_ia32_scattersiv8sf: 3342 case X86::BI__builtin_ia32_scattersiv8si: 3343 case X86::BI__builtin_ia32_scattersiv8df: 3344 case X86::BI__builtin_ia32_scattersiv16sf: 3345 case X86::BI__builtin_ia32_scatterdiv8df: 3346 case X86::BI__builtin_ia32_scatterdiv16sf: 3347 case X86::BI__builtin_ia32_scattersiv8di: 3348 case X86::BI__builtin_ia32_scattersiv16si: 3349 case X86::BI__builtin_ia32_scatterdiv8di: 3350 case X86::BI__builtin_ia32_scatterdiv16si: 3351 ArgNum = 4; 3352 break; 3353 } 3354 3355 llvm::APSInt Result; 3356 3357 // We can't check the value of a dependent argument. 3358 Expr *Arg = TheCall->getArg(ArgNum); 3359 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3360 return false; 3361 3362 // Check constant-ness first. 3363 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3364 return true; 3365 3366 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3367 return false; 3368 3369 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3370 << Arg->getSourceRange(); 3371 } 3372 3373 static bool isX86_32Builtin(unsigned BuiltinID) { 3374 // These builtins only work on x86-32 targets. 3375 switch (BuiltinID) { 3376 case X86::BI__builtin_ia32_readeflags_u32: 3377 case X86::BI__builtin_ia32_writeeflags_u32: 3378 return true; 3379 } 3380 3381 return false; 3382 } 3383 3384 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3385 if (BuiltinID == X86::BI__builtin_cpu_supports) 3386 return SemaBuiltinCpuSupports(*this, TheCall); 3387 3388 if (BuiltinID == X86::BI__builtin_cpu_is) 3389 return SemaBuiltinCpuIs(*this, TheCall); 3390 3391 // Check for 32-bit only builtins on a 64-bit target. 3392 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3393 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3394 return Diag(TheCall->getCallee()->getBeginLoc(), 3395 diag::err_32_bit_builtin_64_bit_tgt); 3396 3397 // If the intrinsic has rounding or SAE make sure its valid. 3398 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3399 return true; 3400 3401 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3402 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3403 return true; 3404 3405 // For intrinsics which take an immediate value as part of the instruction, 3406 // range check them here. 3407 int i = 0, l = 0, u = 0; 3408 switch (BuiltinID) { 3409 default: 3410 return false; 3411 case X86::BI__builtin_ia32_vec_ext_v2si: 3412 case X86::BI__builtin_ia32_vec_ext_v2di: 3413 case X86::BI__builtin_ia32_vextractf128_pd256: 3414 case X86::BI__builtin_ia32_vextractf128_ps256: 3415 case X86::BI__builtin_ia32_vextractf128_si256: 3416 case X86::BI__builtin_ia32_extract128i256: 3417 case X86::BI__builtin_ia32_extractf64x4_mask: 3418 case X86::BI__builtin_ia32_extracti64x4_mask: 3419 case X86::BI__builtin_ia32_extractf32x8_mask: 3420 case X86::BI__builtin_ia32_extracti32x8_mask: 3421 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3422 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3423 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3424 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3425 i = 1; l = 0; u = 1; 3426 break; 3427 case X86::BI__builtin_ia32_vec_set_v2di: 3428 case X86::BI__builtin_ia32_vinsertf128_pd256: 3429 case X86::BI__builtin_ia32_vinsertf128_ps256: 3430 case X86::BI__builtin_ia32_vinsertf128_si256: 3431 case X86::BI__builtin_ia32_insert128i256: 3432 case X86::BI__builtin_ia32_insertf32x8: 3433 case X86::BI__builtin_ia32_inserti32x8: 3434 case X86::BI__builtin_ia32_insertf64x4: 3435 case X86::BI__builtin_ia32_inserti64x4: 3436 case X86::BI__builtin_ia32_insertf64x2_256: 3437 case X86::BI__builtin_ia32_inserti64x2_256: 3438 case X86::BI__builtin_ia32_insertf32x4_256: 3439 case X86::BI__builtin_ia32_inserti32x4_256: 3440 i = 2; l = 0; u = 1; 3441 break; 3442 case X86::BI__builtin_ia32_vpermilpd: 3443 case X86::BI__builtin_ia32_vec_ext_v4hi: 3444 case X86::BI__builtin_ia32_vec_ext_v4si: 3445 case X86::BI__builtin_ia32_vec_ext_v4sf: 3446 case X86::BI__builtin_ia32_vec_ext_v4di: 3447 case X86::BI__builtin_ia32_extractf32x4_mask: 3448 case X86::BI__builtin_ia32_extracti32x4_mask: 3449 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3450 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3451 i = 1; l = 0; u = 3; 3452 break; 3453 case X86::BI_mm_prefetch: 3454 case X86::BI__builtin_ia32_vec_ext_v8hi: 3455 case X86::BI__builtin_ia32_vec_ext_v8si: 3456 i = 1; l = 0; u = 7; 3457 break; 3458 case X86::BI__builtin_ia32_sha1rnds4: 3459 case X86::BI__builtin_ia32_blendpd: 3460 case X86::BI__builtin_ia32_shufpd: 3461 case X86::BI__builtin_ia32_vec_set_v4hi: 3462 case X86::BI__builtin_ia32_vec_set_v4si: 3463 case X86::BI__builtin_ia32_vec_set_v4di: 3464 case X86::BI__builtin_ia32_shuf_f32x4_256: 3465 case X86::BI__builtin_ia32_shuf_f64x2_256: 3466 case X86::BI__builtin_ia32_shuf_i32x4_256: 3467 case X86::BI__builtin_ia32_shuf_i64x2_256: 3468 case X86::BI__builtin_ia32_insertf64x2_512: 3469 case X86::BI__builtin_ia32_inserti64x2_512: 3470 case X86::BI__builtin_ia32_insertf32x4: 3471 case X86::BI__builtin_ia32_inserti32x4: 3472 i = 2; l = 0; u = 3; 3473 break; 3474 case X86::BI__builtin_ia32_vpermil2pd: 3475 case X86::BI__builtin_ia32_vpermil2pd256: 3476 case X86::BI__builtin_ia32_vpermil2ps: 3477 case X86::BI__builtin_ia32_vpermil2ps256: 3478 i = 3; l = 0; u = 3; 3479 break; 3480 case X86::BI__builtin_ia32_cmpb128_mask: 3481 case X86::BI__builtin_ia32_cmpw128_mask: 3482 case X86::BI__builtin_ia32_cmpd128_mask: 3483 case X86::BI__builtin_ia32_cmpq128_mask: 3484 case X86::BI__builtin_ia32_cmpb256_mask: 3485 case X86::BI__builtin_ia32_cmpw256_mask: 3486 case X86::BI__builtin_ia32_cmpd256_mask: 3487 case X86::BI__builtin_ia32_cmpq256_mask: 3488 case X86::BI__builtin_ia32_cmpb512_mask: 3489 case X86::BI__builtin_ia32_cmpw512_mask: 3490 case X86::BI__builtin_ia32_cmpd512_mask: 3491 case X86::BI__builtin_ia32_cmpq512_mask: 3492 case X86::BI__builtin_ia32_ucmpb128_mask: 3493 case X86::BI__builtin_ia32_ucmpw128_mask: 3494 case X86::BI__builtin_ia32_ucmpd128_mask: 3495 case X86::BI__builtin_ia32_ucmpq128_mask: 3496 case X86::BI__builtin_ia32_ucmpb256_mask: 3497 case X86::BI__builtin_ia32_ucmpw256_mask: 3498 case X86::BI__builtin_ia32_ucmpd256_mask: 3499 case X86::BI__builtin_ia32_ucmpq256_mask: 3500 case X86::BI__builtin_ia32_ucmpb512_mask: 3501 case X86::BI__builtin_ia32_ucmpw512_mask: 3502 case X86::BI__builtin_ia32_ucmpd512_mask: 3503 case X86::BI__builtin_ia32_ucmpq512_mask: 3504 case X86::BI__builtin_ia32_vpcomub: 3505 case X86::BI__builtin_ia32_vpcomuw: 3506 case X86::BI__builtin_ia32_vpcomud: 3507 case X86::BI__builtin_ia32_vpcomuq: 3508 case X86::BI__builtin_ia32_vpcomb: 3509 case X86::BI__builtin_ia32_vpcomw: 3510 case X86::BI__builtin_ia32_vpcomd: 3511 case X86::BI__builtin_ia32_vpcomq: 3512 case X86::BI__builtin_ia32_vec_set_v8hi: 3513 case X86::BI__builtin_ia32_vec_set_v8si: 3514 i = 2; l = 0; u = 7; 3515 break; 3516 case X86::BI__builtin_ia32_vpermilpd256: 3517 case X86::BI__builtin_ia32_roundps: 3518 case X86::BI__builtin_ia32_roundpd: 3519 case X86::BI__builtin_ia32_roundps256: 3520 case X86::BI__builtin_ia32_roundpd256: 3521 case X86::BI__builtin_ia32_getmantpd128_mask: 3522 case X86::BI__builtin_ia32_getmantpd256_mask: 3523 case X86::BI__builtin_ia32_getmantps128_mask: 3524 case X86::BI__builtin_ia32_getmantps256_mask: 3525 case X86::BI__builtin_ia32_getmantpd512_mask: 3526 case X86::BI__builtin_ia32_getmantps512_mask: 3527 case X86::BI__builtin_ia32_vec_ext_v16qi: 3528 case X86::BI__builtin_ia32_vec_ext_v16hi: 3529 i = 1; l = 0; u = 15; 3530 break; 3531 case X86::BI__builtin_ia32_pblendd128: 3532 case X86::BI__builtin_ia32_blendps: 3533 case X86::BI__builtin_ia32_blendpd256: 3534 case X86::BI__builtin_ia32_shufpd256: 3535 case X86::BI__builtin_ia32_roundss: 3536 case X86::BI__builtin_ia32_roundsd: 3537 case X86::BI__builtin_ia32_rangepd128_mask: 3538 case X86::BI__builtin_ia32_rangepd256_mask: 3539 case X86::BI__builtin_ia32_rangepd512_mask: 3540 case X86::BI__builtin_ia32_rangeps128_mask: 3541 case X86::BI__builtin_ia32_rangeps256_mask: 3542 case X86::BI__builtin_ia32_rangeps512_mask: 3543 case X86::BI__builtin_ia32_getmantsd_round_mask: 3544 case X86::BI__builtin_ia32_getmantss_round_mask: 3545 case X86::BI__builtin_ia32_vec_set_v16qi: 3546 case X86::BI__builtin_ia32_vec_set_v16hi: 3547 i = 2; l = 0; u = 15; 3548 break; 3549 case X86::BI__builtin_ia32_vec_ext_v32qi: 3550 i = 1; l = 0; u = 31; 3551 break; 3552 case X86::BI__builtin_ia32_cmpps: 3553 case X86::BI__builtin_ia32_cmpss: 3554 case X86::BI__builtin_ia32_cmppd: 3555 case X86::BI__builtin_ia32_cmpsd: 3556 case X86::BI__builtin_ia32_cmpps256: 3557 case X86::BI__builtin_ia32_cmppd256: 3558 case X86::BI__builtin_ia32_cmpps128_mask: 3559 case X86::BI__builtin_ia32_cmppd128_mask: 3560 case X86::BI__builtin_ia32_cmpps256_mask: 3561 case X86::BI__builtin_ia32_cmppd256_mask: 3562 case X86::BI__builtin_ia32_cmpps512_mask: 3563 case X86::BI__builtin_ia32_cmppd512_mask: 3564 case X86::BI__builtin_ia32_cmpsd_mask: 3565 case X86::BI__builtin_ia32_cmpss_mask: 3566 case X86::BI__builtin_ia32_vec_set_v32qi: 3567 i = 2; l = 0; u = 31; 3568 break; 3569 case X86::BI__builtin_ia32_permdf256: 3570 case X86::BI__builtin_ia32_permdi256: 3571 case X86::BI__builtin_ia32_permdf512: 3572 case X86::BI__builtin_ia32_permdi512: 3573 case X86::BI__builtin_ia32_vpermilps: 3574 case X86::BI__builtin_ia32_vpermilps256: 3575 case X86::BI__builtin_ia32_vpermilpd512: 3576 case X86::BI__builtin_ia32_vpermilps512: 3577 case X86::BI__builtin_ia32_pshufd: 3578 case X86::BI__builtin_ia32_pshufd256: 3579 case X86::BI__builtin_ia32_pshufd512: 3580 case X86::BI__builtin_ia32_pshufhw: 3581 case X86::BI__builtin_ia32_pshufhw256: 3582 case X86::BI__builtin_ia32_pshufhw512: 3583 case X86::BI__builtin_ia32_pshuflw: 3584 case X86::BI__builtin_ia32_pshuflw256: 3585 case X86::BI__builtin_ia32_pshuflw512: 3586 case X86::BI__builtin_ia32_vcvtps2ph: 3587 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3588 case X86::BI__builtin_ia32_vcvtps2ph256: 3589 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3590 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3591 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3592 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3593 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3594 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3595 case X86::BI__builtin_ia32_rndscaleps_mask: 3596 case X86::BI__builtin_ia32_rndscalepd_mask: 3597 case X86::BI__builtin_ia32_reducepd128_mask: 3598 case X86::BI__builtin_ia32_reducepd256_mask: 3599 case X86::BI__builtin_ia32_reducepd512_mask: 3600 case X86::BI__builtin_ia32_reduceps128_mask: 3601 case X86::BI__builtin_ia32_reduceps256_mask: 3602 case X86::BI__builtin_ia32_reduceps512_mask: 3603 case X86::BI__builtin_ia32_prold512: 3604 case X86::BI__builtin_ia32_prolq512: 3605 case X86::BI__builtin_ia32_prold128: 3606 case X86::BI__builtin_ia32_prold256: 3607 case X86::BI__builtin_ia32_prolq128: 3608 case X86::BI__builtin_ia32_prolq256: 3609 case X86::BI__builtin_ia32_prord512: 3610 case X86::BI__builtin_ia32_prorq512: 3611 case X86::BI__builtin_ia32_prord128: 3612 case X86::BI__builtin_ia32_prord256: 3613 case X86::BI__builtin_ia32_prorq128: 3614 case X86::BI__builtin_ia32_prorq256: 3615 case X86::BI__builtin_ia32_fpclasspd128_mask: 3616 case X86::BI__builtin_ia32_fpclasspd256_mask: 3617 case X86::BI__builtin_ia32_fpclassps128_mask: 3618 case X86::BI__builtin_ia32_fpclassps256_mask: 3619 case X86::BI__builtin_ia32_fpclassps512_mask: 3620 case X86::BI__builtin_ia32_fpclasspd512_mask: 3621 case X86::BI__builtin_ia32_fpclasssd_mask: 3622 case X86::BI__builtin_ia32_fpclassss_mask: 3623 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3624 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3625 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3626 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3627 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3628 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3629 i = 1; l = 0; u = 255; 3630 break; 3631 case X86::BI__builtin_ia32_vperm2f128_pd256: 3632 case X86::BI__builtin_ia32_vperm2f128_ps256: 3633 case X86::BI__builtin_ia32_vperm2f128_si256: 3634 case X86::BI__builtin_ia32_permti256: 3635 case X86::BI__builtin_ia32_pblendw128: 3636 case X86::BI__builtin_ia32_pblendw256: 3637 case X86::BI__builtin_ia32_blendps256: 3638 case X86::BI__builtin_ia32_pblendd256: 3639 case X86::BI__builtin_ia32_palignr128: 3640 case X86::BI__builtin_ia32_palignr256: 3641 case X86::BI__builtin_ia32_palignr512: 3642 case X86::BI__builtin_ia32_alignq512: 3643 case X86::BI__builtin_ia32_alignd512: 3644 case X86::BI__builtin_ia32_alignd128: 3645 case X86::BI__builtin_ia32_alignd256: 3646 case X86::BI__builtin_ia32_alignq128: 3647 case X86::BI__builtin_ia32_alignq256: 3648 case X86::BI__builtin_ia32_vcomisd: 3649 case X86::BI__builtin_ia32_vcomiss: 3650 case X86::BI__builtin_ia32_shuf_f32x4: 3651 case X86::BI__builtin_ia32_shuf_f64x2: 3652 case X86::BI__builtin_ia32_shuf_i32x4: 3653 case X86::BI__builtin_ia32_shuf_i64x2: 3654 case X86::BI__builtin_ia32_shufpd512: 3655 case X86::BI__builtin_ia32_shufps: 3656 case X86::BI__builtin_ia32_shufps256: 3657 case X86::BI__builtin_ia32_shufps512: 3658 case X86::BI__builtin_ia32_dbpsadbw128: 3659 case X86::BI__builtin_ia32_dbpsadbw256: 3660 case X86::BI__builtin_ia32_dbpsadbw512: 3661 case X86::BI__builtin_ia32_vpshldd128: 3662 case X86::BI__builtin_ia32_vpshldd256: 3663 case X86::BI__builtin_ia32_vpshldd512: 3664 case X86::BI__builtin_ia32_vpshldq128: 3665 case X86::BI__builtin_ia32_vpshldq256: 3666 case X86::BI__builtin_ia32_vpshldq512: 3667 case X86::BI__builtin_ia32_vpshldw128: 3668 case X86::BI__builtin_ia32_vpshldw256: 3669 case X86::BI__builtin_ia32_vpshldw512: 3670 case X86::BI__builtin_ia32_vpshrdd128: 3671 case X86::BI__builtin_ia32_vpshrdd256: 3672 case X86::BI__builtin_ia32_vpshrdd512: 3673 case X86::BI__builtin_ia32_vpshrdq128: 3674 case X86::BI__builtin_ia32_vpshrdq256: 3675 case X86::BI__builtin_ia32_vpshrdq512: 3676 case X86::BI__builtin_ia32_vpshrdw128: 3677 case X86::BI__builtin_ia32_vpshrdw256: 3678 case X86::BI__builtin_ia32_vpshrdw512: 3679 i = 2; l = 0; u = 255; 3680 break; 3681 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3682 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3683 case X86::BI__builtin_ia32_fixupimmps512_mask: 3684 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3685 case X86::BI__builtin_ia32_fixupimmsd_mask: 3686 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3687 case X86::BI__builtin_ia32_fixupimmss_mask: 3688 case X86::BI__builtin_ia32_fixupimmss_maskz: 3689 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3690 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3691 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3692 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3693 case X86::BI__builtin_ia32_fixupimmps128_mask: 3694 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3695 case X86::BI__builtin_ia32_fixupimmps256_mask: 3696 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3697 case X86::BI__builtin_ia32_pternlogd512_mask: 3698 case X86::BI__builtin_ia32_pternlogd512_maskz: 3699 case X86::BI__builtin_ia32_pternlogq512_mask: 3700 case X86::BI__builtin_ia32_pternlogq512_maskz: 3701 case X86::BI__builtin_ia32_pternlogd128_mask: 3702 case X86::BI__builtin_ia32_pternlogd128_maskz: 3703 case X86::BI__builtin_ia32_pternlogd256_mask: 3704 case X86::BI__builtin_ia32_pternlogd256_maskz: 3705 case X86::BI__builtin_ia32_pternlogq128_mask: 3706 case X86::BI__builtin_ia32_pternlogq128_maskz: 3707 case X86::BI__builtin_ia32_pternlogq256_mask: 3708 case X86::BI__builtin_ia32_pternlogq256_maskz: 3709 i = 3; l = 0; u = 255; 3710 break; 3711 case X86::BI__builtin_ia32_gatherpfdpd: 3712 case X86::BI__builtin_ia32_gatherpfdps: 3713 case X86::BI__builtin_ia32_gatherpfqpd: 3714 case X86::BI__builtin_ia32_gatherpfqps: 3715 case X86::BI__builtin_ia32_scatterpfdpd: 3716 case X86::BI__builtin_ia32_scatterpfdps: 3717 case X86::BI__builtin_ia32_scatterpfqpd: 3718 case X86::BI__builtin_ia32_scatterpfqps: 3719 i = 4; l = 2; u = 3; 3720 break; 3721 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3722 case X86::BI__builtin_ia32_rndscaless_round_mask: 3723 i = 4; l = 0; u = 255; 3724 break; 3725 } 3726 3727 // Note that we don't force a hard error on the range check here, allowing 3728 // template-generated or macro-generated dead code to potentially have out-of- 3729 // range values. These need to code generate, but don't need to necessarily 3730 // make any sense. We use a warning that defaults to an error. 3731 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3732 } 3733 3734 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3735 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3736 /// Returns true when the format fits the function and the FormatStringInfo has 3737 /// been populated. 3738 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3739 FormatStringInfo *FSI) { 3740 FSI->HasVAListArg = Format->getFirstArg() == 0; 3741 FSI->FormatIdx = Format->getFormatIdx() - 1; 3742 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3743 3744 // The way the format attribute works in GCC, the implicit this argument 3745 // of member functions is counted. However, it doesn't appear in our own 3746 // lists, so decrement format_idx in that case. 3747 if (IsCXXMember) { 3748 if(FSI->FormatIdx == 0) 3749 return false; 3750 --FSI->FormatIdx; 3751 if (FSI->FirstDataArg != 0) 3752 --FSI->FirstDataArg; 3753 } 3754 return true; 3755 } 3756 3757 /// Checks if a the given expression evaluates to null. 3758 /// 3759 /// Returns true if the value evaluates to null. 3760 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3761 // If the expression has non-null type, it doesn't evaluate to null. 3762 if (auto nullability 3763 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3764 if (*nullability == NullabilityKind::NonNull) 3765 return false; 3766 } 3767 3768 // As a special case, transparent unions initialized with zero are 3769 // considered null for the purposes of the nonnull attribute. 3770 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3771 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3772 if (const CompoundLiteralExpr *CLE = 3773 dyn_cast<CompoundLiteralExpr>(Expr)) 3774 if (const InitListExpr *ILE = 3775 dyn_cast<InitListExpr>(CLE->getInitializer())) 3776 Expr = ILE->getInit(0); 3777 } 3778 3779 bool Result; 3780 return (!Expr->isValueDependent() && 3781 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3782 !Result); 3783 } 3784 3785 static void CheckNonNullArgument(Sema &S, 3786 const Expr *ArgExpr, 3787 SourceLocation CallSiteLoc) { 3788 if (CheckNonNullExpr(S, ArgExpr)) 3789 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3790 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 3791 } 3792 3793 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3794 FormatStringInfo FSI; 3795 if ((GetFormatStringType(Format) == FST_NSString) && 3796 getFormatStringInfo(Format, false, &FSI)) { 3797 Idx = FSI.FormatIdx; 3798 return true; 3799 } 3800 return false; 3801 } 3802 3803 /// Diagnose use of %s directive in an NSString which is being passed 3804 /// as formatting string to formatting method. 3805 static void 3806 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3807 const NamedDecl *FDecl, 3808 Expr **Args, 3809 unsigned NumArgs) { 3810 unsigned Idx = 0; 3811 bool Format = false; 3812 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3813 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3814 Idx = 2; 3815 Format = true; 3816 } 3817 else 3818 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3819 if (S.GetFormatNSStringIdx(I, Idx)) { 3820 Format = true; 3821 break; 3822 } 3823 } 3824 if (!Format || NumArgs <= Idx) 3825 return; 3826 const Expr *FormatExpr = Args[Idx]; 3827 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3828 FormatExpr = CSCE->getSubExpr(); 3829 const StringLiteral *FormatString; 3830 if (const ObjCStringLiteral *OSL = 3831 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3832 FormatString = OSL->getString(); 3833 else 3834 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3835 if (!FormatString) 3836 return; 3837 if (S.FormatStringHasSArg(FormatString)) { 3838 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3839 << "%s" << 1 << 1; 3840 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3841 << FDecl->getDeclName(); 3842 } 3843 } 3844 3845 /// Determine whether the given type has a non-null nullability annotation. 3846 static bool isNonNullType(ASTContext &ctx, QualType type) { 3847 if (auto nullability = type->getNullability(ctx)) 3848 return *nullability == NullabilityKind::NonNull; 3849 3850 return false; 3851 } 3852 3853 static void CheckNonNullArguments(Sema &S, 3854 const NamedDecl *FDecl, 3855 const FunctionProtoType *Proto, 3856 ArrayRef<const Expr *> Args, 3857 SourceLocation CallSiteLoc) { 3858 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3859 3860 // Check the attributes attached to the method/function itself. 3861 llvm::SmallBitVector NonNullArgs; 3862 if (FDecl) { 3863 // Handle the nonnull attribute on the function/method declaration itself. 3864 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3865 if (!NonNull->args_size()) { 3866 // Easy case: all pointer arguments are nonnull. 3867 for (const auto *Arg : Args) 3868 if (S.isValidPointerAttrType(Arg->getType())) 3869 CheckNonNullArgument(S, Arg, CallSiteLoc); 3870 return; 3871 } 3872 3873 for (const ParamIdx &Idx : NonNull->args()) { 3874 unsigned IdxAST = Idx.getASTIndex(); 3875 if (IdxAST >= Args.size()) 3876 continue; 3877 if (NonNullArgs.empty()) 3878 NonNullArgs.resize(Args.size()); 3879 NonNullArgs.set(IdxAST); 3880 } 3881 } 3882 } 3883 3884 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3885 // Handle the nonnull attribute on the parameters of the 3886 // function/method. 3887 ArrayRef<ParmVarDecl*> parms; 3888 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3889 parms = FD->parameters(); 3890 else 3891 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3892 3893 unsigned ParamIndex = 0; 3894 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3895 I != E; ++I, ++ParamIndex) { 3896 const ParmVarDecl *PVD = *I; 3897 if (PVD->hasAttr<NonNullAttr>() || 3898 isNonNullType(S.Context, PVD->getType())) { 3899 if (NonNullArgs.empty()) 3900 NonNullArgs.resize(Args.size()); 3901 3902 NonNullArgs.set(ParamIndex); 3903 } 3904 } 3905 } else { 3906 // If we have a non-function, non-method declaration but no 3907 // function prototype, try to dig out the function prototype. 3908 if (!Proto) { 3909 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3910 QualType type = VD->getType().getNonReferenceType(); 3911 if (auto pointerType = type->getAs<PointerType>()) 3912 type = pointerType->getPointeeType(); 3913 else if (auto blockType = type->getAs<BlockPointerType>()) 3914 type = blockType->getPointeeType(); 3915 // FIXME: data member pointers? 3916 3917 // Dig out the function prototype, if there is one. 3918 Proto = type->getAs<FunctionProtoType>(); 3919 } 3920 } 3921 3922 // Fill in non-null argument information from the nullability 3923 // information on the parameter types (if we have them). 3924 if (Proto) { 3925 unsigned Index = 0; 3926 for (auto paramType : Proto->getParamTypes()) { 3927 if (isNonNullType(S.Context, paramType)) { 3928 if (NonNullArgs.empty()) 3929 NonNullArgs.resize(Args.size()); 3930 3931 NonNullArgs.set(Index); 3932 } 3933 3934 ++Index; 3935 } 3936 } 3937 } 3938 3939 // Check for non-null arguments. 3940 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 3941 ArgIndex != ArgIndexEnd; ++ArgIndex) { 3942 if (NonNullArgs[ArgIndex]) 3943 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 3944 } 3945 } 3946 3947 /// Handles the checks for format strings, non-POD arguments to vararg 3948 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 3949 /// attributes. 3950 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 3951 const Expr *ThisArg, ArrayRef<const Expr *> Args, 3952 bool IsMemberFunction, SourceLocation Loc, 3953 SourceRange Range, VariadicCallType CallType) { 3954 // FIXME: We should check as much as we can in the template definition. 3955 if (CurContext->isDependentContext()) 3956 return; 3957 3958 // Printf and scanf checking. 3959 llvm::SmallBitVector CheckedVarArgs; 3960 if (FDecl) { 3961 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3962 // Only create vector if there are format attributes. 3963 CheckedVarArgs.resize(Args.size()); 3964 3965 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 3966 CheckedVarArgs); 3967 } 3968 } 3969 3970 // Refuse POD arguments that weren't caught by the format string 3971 // checks above. 3972 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 3973 if (CallType != VariadicDoesNotApply && 3974 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 3975 unsigned NumParams = Proto ? Proto->getNumParams() 3976 : FDecl && isa<FunctionDecl>(FDecl) 3977 ? cast<FunctionDecl>(FDecl)->getNumParams() 3978 : FDecl && isa<ObjCMethodDecl>(FDecl) 3979 ? cast<ObjCMethodDecl>(FDecl)->param_size() 3980 : 0; 3981 3982 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 3983 // Args[ArgIdx] can be null in malformed code. 3984 if (const Expr *Arg = Args[ArgIdx]) { 3985 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 3986 checkVariadicArgument(Arg, CallType); 3987 } 3988 } 3989 } 3990 3991 if (FDecl || Proto) { 3992 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 3993 3994 // Type safety checking. 3995 if (FDecl) { 3996 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 3997 CheckArgumentWithTypeTag(I, Args, Loc); 3998 } 3999 } 4000 4001 if (FD) 4002 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4003 } 4004 4005 /// CheckConstructorCall - Check a constructor call for correctness and safety 4006 /// properties not enforced by the C type system. 4007 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4008 ArrayRef<const Expr *> Args, 4009 const FunctionProtoType *Proto, 4010 SourceLocation Loc) { 4011 VariadicCallType CallType = 4012 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4013 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4014 Loc, SourceRange(), CallType); 4015 } 4016 4017 /// CheckFunctionCall - Check a direct function call for various correctness 4018 /// and safety properties not strictly enforced by the C type system. 4019 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4020 const FunctionProtoType *Proto) { 4021 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4022 isa<CXXMethodDecl>(FDecl); 4023 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4024 IsMemberOperatorCall; 4025 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4026 TheCall->getCallee()); 4027 Expr** Args = TheCall->getArgs(); 4028 unsigned NumArgs = TheCall->getNumArgs(); 4029 4030 Expr *ImplicitThis = nullptr; 4031 if (IsMemberOperatorCall) { 4032 // If this is a call to a member operator, hide the first argument 4033 // from checkCall. 4034 // FIXME: Our choice of AST representation here is less than ideal. 4035 ImplicitThis = Args[0]; 4036 ++Args; 4037 --NumArgs; 4038 } else if (IsMemberFunction) 4039 ImplicitThis = 4040 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4041 4042 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4043 IsMemberFunction, TheCall->getRParenLoc(), 4044 TheCall->getCallee()->getSourceRange(), CallType); 4045 4046 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4047 // None of the checks below are needed for functions that don't have 4048 // simple names (e.g., C++ conversion functions). 4049 if (!FnInfo) 4050 return false; 4051 4052 CheckAbsoluteValueFunction(TheCall, FDecl); 4053 CheckMaxUnsignedZero(TheCall, FDecl); 4054 4055 if (getLangOpts().ObjC1) 4056 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4057 4058 unsigned CMId = FDecl->getMemoryFunctionKind(); 4059 if (CMId == 0) 4060 return false; 4061 4062 // Handle memory setting and copying functions. 4063 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4064 CheckStrlcpycatArguments(TheCall, FnInfo); 4065 else if (CMId == Builtin::BIstrncat) 4066 CheckStrncatArguments(TheCall, FnInfo); 4067 else 4068 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4069 4070 return false; 4071 } 4072 4073 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4074 ArrayRef<const Expr *> Args) { 4075 VariadicCallType CallType = 4076 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4077 4078 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4079 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4080 CallType); 4081 4082 return false; 4083 } 4084 4085 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4086 const FunctionProtoType *Proto) { 4087 QualType Ty; 4088 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4089 Ty = V->getType().getNonReferenceType(); 4090 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4091 Ty = F->getType().getNonReferenceType(); 4092 else 4093 return false; 4094 4095 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4096 !Ty->isFunctionProtoType()) 4097 return false; 4098 4099 VariadicCallType CallType; 4100 if (!Proto || !Proto->isVariadic()) { 4101 CallType = VariadicDoesNotApply; 4102 } else if (Ty->isBlockPointerType()) { 4103 CallType = VariadicBlock; 4104 } else { // Ty->isFunctionPointerType() 4105 CallType = VariadicFunction; 4106 } 4107 4108 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4109 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4110 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4111 TheCall->getCallee()->getSourceRange(), CallType); 4112 4113 return false; 4114 } 4115 4116 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4117 /// such as function pointers returned from functions. 4118 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4119 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4120 TheCall->getCallee()); 4121 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4122 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4123 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4124 TheCall->getCallee()->getSourceRange(), CallType); 4125 4126 return false; 4127 } 4128 4129 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4130 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4131 return false; 4132 4133 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4134 switch (Op) { 4135 case AtomicExpr::AO__c11_atomic_init: 4136 case AtomicExpr::AO__opencl_atomic_init: 4137 llvm_unreachable("There is no ordering argument for an init"); 4138 4139 case AtomicExpr::AO__c11_atomic_load: 4140 case AtomicExpr::AO__opencl_atomic_load: 4141 case AtomicExpr::AO__atomic_load_n: 4142 case AtomicExpr::AO__atomic_load: 4143 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4144 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4145 4146 case AtomicExpr::AO__c11_atomic_store: 4147 case AtomicExpr::AO__opencl_atomic_store: 4148 case AtomicExpr::AO__atomic_store: 4149 case AtomicExpr::AO__atomic_store_n: 4150 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4151 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4152 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4153 4154 default: 4155 return true; 4156 } 4157 } 4158 4159 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4160 AtomicExpr::AtomicOp Op) { 4161 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4162 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4163 4164 // All the non-OpenCL operations take one of the following forms. 4165 // The OpenCL operations take the __c11 forms with one extra argument for 4166 // synchronization scope. 4167 enum { 4168 // C __c11_atomic_init(A *, C) 4169 Init, 4170 4171 // C __c11_atomic_load(A *, int) 4172 Load, 4173 4174 // void __atomic_load(A *, CP, int) 4175 LoadCopy, 4176 4177 // void __atomic_store(A *, CP, int) 4178 Copy, 4179 4180 // C __c11_atomic_add(A *, M, int) 4181 Arithmetic, 4182 4183 // C __atomic_exchange_n(A *, CP, int) 4184 Xchg, 4185 4186 // void __atomic_exchange(A *, C *, CP, int) 4187 GNUXchg, 4188 4189 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4190 C11CmpXchg, 4191 4192 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4193 GNUCmpXchg 4194 } Form = Init; 4195 4196 const unsigned NumForm = GNUCmpXchg + 1; 4197 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4198 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4199 // where: 4200 // C is an appropriate type, 4201 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4202 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4203 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4204 // the int parameters are for orderings. 4205 4206 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4207 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4208 "need to update code for modified forms"); 4209 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4210 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4211 AtomicExpr::AO__atomic_load, 4212 "need to update code for modified C11 atomics"); 4213 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4214 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4215 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4216 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4217 IsOpenCL; 4218 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4219 Op == AtomicExpr::AO__atomic_store_n || 4220 Op == AtomicExpr::AO__atomic_exchange_n || 4221 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4222 bool IsAddSub = false; 4223 bool IsMinMax = false; 4224 4225 switch (Op) { 4226 case AtomicExpr::AO__c11_atomic_init: 4227 case AtomicExpr::AO__opencl_atomic_init: 4228 Form = Init; 4229 break; 4230 4231 case AtomicExpr::AO__c11_atomic_load: 4232 case AtomicExpr::AO__opencl_atomic_load: 4233 case AtomicExpr::AO__atomic_load_n: 4234 Form = Load; 4235 break; 4236 4237 case AtomicExpr::AO__atomic_load: 4238 Form = LoadCopy; 4239 break; 4240 4241 case AtomicExpr::AO__c11_atomic_store: 4242 case AtomicExpr::AO__opencl_atomic_store: 4243 case AtomicExpr::AO__atomic_store: 4244 case AtomicExpr::AO__atomic_store_n: 4245 Form = Copy; 4246 break; 4247 4248 case AtomicExpr::AO__c11_atomic_fetch_add: 4249 case AtomicExpr::AO__c11_atomic_fetch_sub: 4250 case AtomicExpr::AO__opencl_atomic_fetch_add: 4251 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4252 case AtomicExpr::AO__opencl_atomic_fetch_min: 4253 case AtomicExpr::AO__opencl_atomic_fetch_max: 4254 case AtomicExpr::AO__atomic_fetch_add: 4255 case AtomicExpr::AO__atomic_fetch_sub: 4256 case AtomicExpr::AO__atomic_add_fetch: 4257 case AtomicExpr::AO__atomic_sub_fetch: 4258 IsAddSub = true; 4259 LLVM_FALLTHROUGH; 4260 case AtomicExpr::AO__c11_atomic_fetch_and: 4261 case AtomicExpr::AO__c11_atomic_fetch_or: 4262 case AtomicExpr::AO__c11_atomic_fetch_xor: 4263 case AtomicExpr::AO__opencl_atomic_fetch_and: 4264 case AtomicExpr::AO__opencl_atomic_fetch_or: 4265 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4266 case AtomicExpr::AO__atomic_fetch_and: 4267 case AtomicExpr::AO__atomic_fetch_or: 4268 case AtomicExpr::AO__atomic_fetch_xor: 4269 case AtomicExpr::AO__atomic_fetch_nand: 4270 case AtomicExpr::AO__atomic_and_fetch: 4271 case AtomicExpr::AO__atomic_or_fetch: 4272 case AtomicExpr::AO__atomic_xor_fetch: 4273 case AtomicExpr::AO__atomic_nand_fetch: 4274 Form = Arithmetic; 4275 break; 4276 4277 case AtomicExpr::AO__atomic_fetch_min: 4278 case AtomicExpr::AO__atomic_fetch_max: 4279 IsMinMax = true; 4280 Form = Arithmetic; 4281 break; 4282 4283 case AtomicExpr::AO__c11_atomic_exchange: 4284 case AtomicExpr::AO__opencl_atomic_exchange: 4285 case AtomicExpr::AO__atomic_exchange_n: 4286 Form = Xchg; 4287 break; 4288 4289 case AtomicExpr::AO__atomic_exchange: 4290 Form = GNUXchg; 4291 break; 4292 4293 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4294 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4295 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4296 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4297 Form = C11CmpXchg; 4298 break; 4299 4300 case AtomicExpr::AO__atomic_compare_exchange: 4301 case AtomicExpr::AO__atomic_compare_exchange_n: 4302 Form = GNUCmpXchg; 4303 break; 4304 } 4305 4306 unsigned AdjustedNumArgs = NumArgs[Form]; 4307 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4308 ++AdjustedNumArgs; 4309 // Check we have the right number of arguments. 4310 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4311 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4312 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4313 << TheCall->getCallee()->getSourceRange(); 4314 return ExprError(); 4315 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4316 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4317 diag::err_typecheck_call_too_many_args) 4318 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4319 << TheCall->getCallee()->getSourceRange(); 4320 return ExprError(); 4321 } 4322 4323 // Inspect the first argument of the atomic operation. 4324 Expr *Ptr = TheCall->getArg(0); 4325 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4326 if (ConvertedPtr.isInvalid()) 4327 return ExprError(); 4328 4329 Ptr = ConvertedPtr.get(); 4330 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4331 if (!pointerType) { 4332 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4333 << Ptr->getType() << Ptr->getSourceRange(); 4334 return ExprError(); 4335 } 4336 4337 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4338 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4339 QualType ValType = AtomTy; // 'C' 4340 if (IsC11) { 4341 if (!AtomTy->isAtomicType()) { 4342 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4343 << Ptr->getType() << Ptr->getSourceRange(); 4344 return ExprError(); 4345 } 4346 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4347 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4348 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4349 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4350 << Ptr->getSourceRange(); 4351 return ExprError(); 4352 } 4353 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4354 } else if (Form != Load && Form != LoadCopy) { 4355 if (ValType.isConstQualified()) { 4356 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4357 << Ptr->getType() << Ptr->getSourceRange(); 4358 return ExprError(); 4359 } 4360 } 4361 4362 // For an arithmetic operation, the implied arithmetic must be well-formed. 4363 if (Form == Arithmetic) { 4364 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4365 if (IsAddSub && !ValType->isIntegerType() 4366 && !ValType->isPointerType()) { 4367 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4368 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4369 return ExprError(); 4370 } 4371 if (IsMinMax) { 4372 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4373 if (!BT || (BT->getKind() != BuiltinType::Int && 4374 BT->getKind() != BuiltinType::UInt)) { 4375 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4376 return ExprError(); 4377 } 4378 } 4379 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4380 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4381 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4382 return ExprError(); 4383 } 4384 if (IsC11 && ValType->isPointerType() && 4385 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4386 diag::err_incomplete_type)) { 4387 return ExprError(); 4388 } 4389 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4390 // For __atomic_*_n operations, the value type must be a scalar integral or 4391 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4392 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4393 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4394 return ExprError(); 4395 } 4396 4397 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4398 !AtomTy->isScalarType()) { 4399 // For GNU atomics, require a trivially-copyable type. This is not part of 4400 // the GNU atomics specification, but we enforce it for sanity. 4401 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4402 << Ptr->getType() << Ptr->getSourceRange(); 4403 return ExprError(); 4404 } 4405 4406 switch (ValType.getObjCLifetime()) { 4407 case Qualifiers::OCL_None: 4408 case Qualifiers::OCL_ExplicitNone: 4409 // okay 4410 break; 4411 4412 case Qualifiers::OCL_Weak: 4413 case Qualifiers::OCL_Strong: 4414 case Qualifiers::OCL_Autoreleasing: 4415 // FIXME: Can this happen? By this point, ValType should be known 4416 // to be trivially copyable. 4417 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4418 << ValType << Ptr->getSourceRange(); 4419 return ExprError(); 4420 } 4421 4422 // All atomic operations have an overload which takes a pointer to a volatile 4423 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4424 // into the result or the other operands. Similarly atomic_load takes a 4425 // pointer to a const 'A'. 4426 ValType.removeLocalVolatile(); 4427 ValType.removeLocalConst(); 4428 QualType ResultType = ValType; 4429 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4430 Form == Init) 4431 ResultType = Context.VoidTy; 4432 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4433 ResultType = Context.BoolTy; 4434 4435 // The type of a parameter passed 'by value'. In the GNU atomics, such 4436 // arguments are actually passed as pointers. 4437 QualType ByValType = ValType; // 'CP' 4438 bool IsPassedByAddress = false; 4439 if (!IsC11 && !IsN) { 4440 ByValType = Ptr->getType(); 4441 IsPassedByAddress = true; 4442 } 4443 4444 // The first argument's non-CV pointer type is used to deduce the type of 4445 // subsequent arguments, except for: 4446 // - weak flag (always converted to bool) 4447 // - memory order (always converted to int) 4448 // - scope (always converted to int) 4449 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4450 QualType Ty; 4451 if (i < NumVals[Form] + 1) { 4452 switch (i) { 4453 case 0: 4454 // The first argument is always a pointer. It has a fixed type. 4455 // It is always dereferenced, a nullptr is undefined. 4456 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4457 // Nothing else to do: we already know all we want about this pointer. 4458 continue; 4459 case 1: 4460 // The second argument is the non-atomic operand. For arithmetic, this 4461 // is always passed by value, and for a compare_exchange it is always 4462 // passed by address. For the rest, GNU uses by-address and C11 uses 4463 // by-value. 4464 assert(Form != Load); 4465 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4466 Ty = ValType; 4467 else if (Form == Copy || Form == Xchg) { 4468 if (IsPassedByAddress) 4469 // The value pointer is always dereferenced, a nullptr is undefined. 4470 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4471 Ty = ByValType; 4472 } else if (Form == Arithmetic) 4473 Ty = Context.getPointerDiffType(); 4474 else { 4475 Expr *ValArg = TheCall->getArg(i); 4476 // The value pointer is always dereferenced, a nullptr is undefined. 4477 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4478 LangAS AS = LangAS::Default; 4479 // Keep address space of non-atomic pointer type. 4480 if (const PointerType *PtrTy = 4481 ValArg->getType()->getAs<PointerType>()) { 4482 AS = PtrTy->getPointeeType().getAddressSpace(); 4483 } 4484 Ty = Context.getPointerType( 4485 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4486 } 4487 break; 4488 case 2: 4489 // The third argument to compare_exchange / GNU exchange is the desired 4490 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4491 if (IsPassedByAddress) 4492 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4493 Ty = ByValType; 4494 break; 4495 case 3: 4496 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4497 Ty = Context.BoolTy; 4498 break; 4499 } 4500 } else { 4501 // The order(s) and scope are always converted to int. 4502 Ty = Context.IntTy; 4503 } 4504 4505 InitializedEntity Entity = 4506 InitializedEntity::InitializeParameter(Context, Ty, false); 4507 ExprResult Arg = TheCall->getArg(i); 4508 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4509 if (Arg.isInvalid()) 4510 return true; 4511 TheCall->setArg(i, Arg.get()); 4512 } 4513 4514 // Permute the arguments into a 'consistent' order. 4515 SmallVector<Expr*, 5> SubExprs; 4516 SubExprs.push_back(Ptr); 4517 switch (Form) { 4518 case Init: 4519 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4520 SubExprs.push_back(TheCall->getArg(1)); // Val1 4521 break; 4522 case Load: 4523 SubExprs.push_back(TheCall->getArg(1)); // Order 4524 break; 4525 case LoadCopy: 4526 case Copy: 4527 case Arithmetic: 4528 case Xchg: 4529 SubExprs.push_back(TheCall->getArg(2)); // Order 4530 SubExprs.push_back(TheCall->getArg(1)); // Val1 4531 break; 4532 case GNUXchg: 4533 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4534 SubExprs.push_back(TheCall->getArg(3)); // Order 4535 SubExprs.push_back(TheCall->getArg(1)); // Val1 4536 SubExprs.push_back(TheCall->getArg(2)); // Val2 4537 break; 4538 case C11CmpXchg: 4539 SubExprs.push_back(TheCall->getArg(3)); // Order 4540 SubExprs.push_back(TheCall->getArg(1)); // Val1 4541 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4542 SubExprs.push_back(TheCall->getArg(2)); // Val2 4543 break; 4544 case GNUCmpXchg: 4545 SubExprs.push_back(TheCall->getArg(4)); // Order 4546 SubExprs.push_back(TheCall->getArg(1)); // Val1 4547 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4548 SubExprs.push_back(TheCall->getArg(2)); // Val2 4549 SubExprs.push_back(TheCall->getArg(3)); // Weak 4550 break; 4551 } 4552 4553 if (SubExprs.size() >= 2 && Form != Init) { 4554 llvm::APSInt Result(32); 4555 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4556 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4557 Diag(SubExprs[1]->getBeginLoc(), 4558 diag::warn_atomic_op_has_invalid_memory_order) 4559 << SubExprs[1]->getSourceRange(); 4560 } 4561 4562 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4563 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4564 llvm::APSInt Result(32); 4565 if (Scope->isIntegerConstantExpr(Result, Context) && 4566 !ScopeModel->isValid(Result.getZExtValue())) { 4567 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4568 << Scope->getSourceRange(); 4569 } 4570 SubExprs.push_back(Scope); 4571 } 4572 4573 AtomicExpr *AE = 4574 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4575 ResultType, Op, TheCall->getRParenLoc()); 4576 4577 if ((Op == AtomicExpr::AO__c11_atomic_load || 4578 Op == AtomicExpr::AO__c11_atomic_store || 4579 Op == AtomicExpr::AO__opencl_atomic_load || 4580 Op == AtomicExpr::AO__opencl_atomic_store ) && 4581 Context.AtomicUsesUnsupportedLibcall(AE)) 4582 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4583 << ((Op == AtomicExpr::AO__c11_atomic_load || 4584 Op == AtomicExpr::AO__opencl_atomic_load) 4585 ? 0 4586 : 1); 4587 4588 return AE; 4589 } 4590 4591 /// checkBuiltinArgument - Given a call to a builtin function, perform 4592 /// normal type-checking on the given argument, updating the call in 4593 /// place. This is useful when a builtin function requires custom 4594 /// type-checking for some of its arguments but not necessarily all of 4595 /// them. 4596 /// 4597 /// Returns true on error. 4598 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4599 FunctionDecl *Fn = E->getDirectCallee(); 4600 assert(Fn && "builtin call without direct callee!"); 4601 4602 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4603 InitializedEntity Entity = 4604 InitializedEntity::InitializeParameter(S.Context, Param); 4605 4606 ExprResult Arg = E->getArg(0); 4607 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4608 if (Arg.isInvalid()) 4609 return true; 4610 4611 E->setArg(ArgIndex, Arg.get()); 4612 return false; 4613 } 4614 4615 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 4616 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 4617 /// type of its first argument. The main ActOnCallExpr routines have already 4618 /// promoted the types of arguments because all of these calls are prototyped as 4619 /// void(...). 4620 /// 4621 /// This function goes through and does final semantic checking for these 4622 /// builtins, 4623 ExprResult 4624 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4625 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 4626 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4627 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4628 4629 // Ensure that we have at least one argument to do type inference from. 4630 if (TheCall->getNumArgs() < 1) { 4631 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4632 << 0 << 1 << TheCall->getNumArgs() 4633 << TheCall->getCallee()->getSourceRange(); 4634 return ExprError(); 4635 } 4636 4637 // Inspect the first argument of the atomic builtin. This should always be 4638 // a pointer type, whose element is an integral scalar or pointer type. 4639 // Because it is a pointer type, we don't have to worry about any implicit 4640 // casts here. 4641 // FIXME: We don't allow floating point scalars as input. 4642 Expr *FirstArg = TheCall->getArg(0); 4643 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4644 if (FirstArgResult.isInvalid()) 4645 return ExprError(); 4646 FirstArg = FirstArgResult.get(); 4647 TheCall->setArg(0, FirstArg); 4648 4649 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4650 if (!pointerType) { 4651 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4652 << FirstArg->getType() << FirstArg->getSourceRange(); 4653 return ExprError(); 4654 } 4655 4656 QualType ValType = pointerType->getPointeeType(); 4657 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4658 !ValType->isBlockPointerType()) { 4659 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4660 << FirstArg->getType() << FirstArg->getSourceRange(); 4661 return ExprError(); 4662 } 4663 4664 if (ValType.isConstQualified()) { 4665 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4666 << FirstArg->getType() << FirstArg->getSourceRange(); 4667 return ExprError(); 4668 } 4669 4670 switch (ValType.getObjCLifetime()) { 4671 case Qualifiers::OCL_None: 4672 case Qualifiers::OCL_ExplicitNone: 4673 // okay 4674 break; 4675 4676 case Qualifiers::OCL_Weak: 4677 case Qualifiers::OCL_Strong: 4678 case Qualifiers::OCL_Autoreleasing: 4679 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4680 << ValType << FirstArg->getSourceRange(); 4681 return ExprError(); 4682 } 4683 4684 // Strip any qualifiers off ValType. 4685 ValType = ValType.getUnqualifiedType(); 4686 4687 // The majority of builtins return a value, but a few have special return 4688 // types, so allow them to override appropriately below. 4689 QualType ResultType = ValType; 4690 4691 // We need to figure out which concrete builtin this maps onto. For example, 4692 // __sync_fetch_and_add with a 2 byte object turns into 4693 // __sync_fetch_and_add_2. 4694 #define BUILTIN_ROW(x) \ 4695 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4696 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4697 4698 static const unsigned BuiltinIndices[][5] = { 4699 BUILTIN_ROW(__sync_fetch_and_add), 4700 BUILTIN_ROW(__sync_fetch_and_sub), 4701 BUILTIN_ROW(__sync_fetch_and_or), 4702 BUILTIN_ROW(__sync_fetch_and_and), 4703 BUILTIN_ROW(__sync_fetch_and_xor), 4704 BUILTIN_ROW(__sync_fetch_and_nand), 4705 4706 BUILTIN_ROW(__sync_add_and_fetch), 4707 BUILTIN_ROW(__sync_sub_and_fetch), 4708 BUILTIN_ROW(__sync_and_and_fetch), 4709 BUILTIN_ROW(__sync_or_and_fetch), 4710 BUILTIN_ROW(__sync_xor_and_fetch), 4711 BUILTIN_ROW(__sync_nand_and_fetch), 4712 4713 BUILTIN_ROW(__sync_val_compare_and_swap), 4714 BUILTIN_ROW(__sync_bool_compare_and_swap), 4715 BUILTIN_ROW(__sync_lock_test_and_set), 4716 BUILTIN_ROW(__sync_lock_release), 4717 BUILTIN_ROW(__sync_swap) 4718 }; 4719 #undef BUILTIN_ROW 4720 4721 // Determine the index of the size. 4722 unsigned SizeIndex; 4723 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4724 case 1: SizeIndex = 0; break; 4725 case 2: SizeIndex = 1; break; 4726 case 4: SizeIndex = 2; break; 4727 case 8: SizeIndex = 3; break; 4728 case 16: SizeIndex = 4; break; 4729 default: 4730 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4731 << FirstArg->getType() << FirstArg->getSourceRange(); 4732 return ExprError(); 4733 } 4734 4735 // Each of these builtins has one pointer argument, followed by some number of 4736 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4737 // that we ignore. Find out which row of BuiltinIndices to read from as well 4738 // as the number of fixed args. 4739 unsigned BuiltinID = FDecl->getBuiltinID(); 4740 unsigned BuiltinIndex, NumFixed = 1; 4741 bool WarnAboutSemanticsChange = false; 4742 switch (BuiltinID) { 4743 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4744 case Builtin::BI__sync_fetch_and_add: 4745 case Builtin::BI__sync_fetch_and_add_1: 4746 case Builtin::BI__sync_fetch_and_add_2: 4747 case Builtin::BI__sync_fetch_and_add_4: 4748 case Builtin::BI__sync_fetch_and_add_8: 4749 case Builtin::BI__sync_fetch_and_add_16: 4750 BuiltinIndex = 0; 4751 break; 4752 4753 case Builtin::BI__sync_fetch_and_sub: 4754 case Builtin::BI__sync_fetch_and_sub_1: 4755 case Builtin::BI__sync_fetch_and_sub_2: 4756 case Builtin::BI__sync_fetch_and_sub_4: 4757 case Builtin::BI__sync_fetch_and_sub_8: 4758 case Builtin::BI__sync_fetch_and_sub_16: 4759 BuiltinIndex = 1; 4760 break; 4761 4762 case Builtin::BI__sync_fetch_and_or: 4763 case Builtin::BI__sync_fetch_and_or_1: 4764 case Builtin::BI__sync_fetch_and_or_2: 4765 case Builtin::BI__sync_fetch_and_or_4: 4766 case Builtin::BI__sync_fetch_and_or_8: 4767 case Builtin::BI__sync_fetch_and_or_16: 4768 BuiltinIndex = 2; 4769 break; 4770 4771 case Builtin::BI__sync_fetch_and_and: 4772 case Builtin::BI__sync_fetch_and_and_1: 4773 case Builtin::BI__sync_fetch_and_and_2: 4774 case Builtin::BI__sync_fetch_and_and_4: 4775 case Builtin::BI__sync_fetch_and_and_8: 4776 case Builtin::BI__sync_fetch_and_and_16: 4777 BuiltinIndex = 3; 4778 break; 4779 4780 case Builtin::BI__sync_fetch_and_xor: 4781 case Builtin::BI__sync_fetch_and_xor_1: 4782 case Builtin::BI__sync_fetch_and_xor_2: 4783 case Builtin::BI__sync_fetch_and_xor_4: 4784 case Builtin::BI__sync_fetch_and_xor_8: 4785 case Builtin::BI__sync_fetch_and_xor_16: 4786 BuiltinIndex = 4; 4787 break; 4788 4789 case Builtin::BI__sync_fetch_and_nand: 4790 case Builtin::BI__sync_fetch_and_nand_1: 4791 case Builtin::BI__sync_fetch_and_nand_2: 4792 case Builtin::BI__sync_fetch_and_nand_4: 4793 case Builtin::BI__sync_fetch_and_nand_8: 4794 case Builtin::BI__sync_fetch_and_nand_16: 4795 BuiltinIndex = 5; 4796 WarnAboutSemanticsChange = true; 4797 break; 4798 4799 case Builtin::BI__sync_add_and_fetch: 4800 case Builtin::BI__sync_add_and_fetch_1: 4801 case Builtin::BI__sync_add_and_fetch_2: 4802 case Builtin::BI__sync_add_and_fetch_4: 4803 case Builtin::BI__sync_add_and_fetch_8: 4804 case Builtin::BI__sync_add_and_fetch_16: 4805 BuiltinIndex = 6; 4806 break; 4807 4808 case Builtin::BI__sync_sub_and_fetch: 4809 case Builtin::BI__sync_sub_and_fetch_1: 4810 case Builtin::BI__sync_sub_and_fetch_2: 4811 case Builtin::BI__sync_sub_and_fetch_4: 4812 case Builtin::BI__sync_sub_and_fetch_8: 4813 case Builtin::BI__sync_sub_and_fetch_16: 4814 BuiltinIndex = 7; 4815 break; 4816 4817 case Builtin::BI__sync_and_and_fetch: 4818 case Builtin::BI__sync_and_and_fetch_1: 4819 case Builtin::BI__sync_and_and_fetch_2: 4820 case Builtin::BI__sync_and_and_fetch_4: 4821 case Builtin::BI__sync_and_and_fetch_8: 4822 case Builtin::BI__sync_and_and_fetch_16: 4823 BuiltinIndex = 8; 4824 break; 4825 4826 case Builtin::BI__sync_or_and_fetch: 4827 case Builtin::BI__sync_or_and_fetch_1: 4828 case Builtin::BI__sync_or_and_fetch_2: 4829 case Builtin::BI__sync_or_and_fetch_4: 4830 case Builtin::BI__sync_or_and_fetch_8: 4831 case Builtin::BI__sync_or_and_fetch_16: 4832 BuiltinIndex = 9; 4833 break; 4834 4835 case Builtin::BI__sync_xor_and_fetch: 4836 case Builtin::BI__sync_xor_and_fetch_1: 4837 case Builtin::BI__sync_xor_and_fetch_2: 4838 case Builtin::BI__sync_xor_and_fetch_4: 4839 case Builtin::BI__sync_xor_and_fetch_8: 4840 case Builtin::BI__sync_xor_and_fetch_16: 4841 BuiltinIndex = 10; 4842 break; 4843 4844 case Builtin::BI__sync_nand_and_fetch: 4845 case Builtin::BI__sync_nand_and_fetch_1: 4846 case Builtin::BI__sync_nand_and_fetch_2: 4847 case Builtin::BI__sync_nand_and_fetch_4: 4848 case Builtin::BI__sync_nand_and_fetch_8: 4849 case Builtin::BI__sync_nand_and_fetch_16: 4850 BuiltinIndex = 11; 4851 WarnAboutSemanticsChange = true; 4852 break; 4853 4854 case Builtin::BI__sync_val_compare_and_swap: 4855 case Builtin::BI__sync_val_compare_and_swap_1: 4856 case Builtin::BI__sync_val_compare_and_swap_2: 4857 case Builtin::BI__sync_val_compare_and_swap_4: 4858 case Builtin::BI__sync_val_compare_and_swap_8: 4859 case Builtin::BI__sync_val_compare_and_swap_16: 4860 BuiltinIndex = 12; 4861 NumFixed = 2; 4862 break; 4863 4864 case Builtin::BI__sync_bool_compare_and_swap: 4865 case Builtin::BI__sync_bool_compare_and_swap_1: 4866 case Builtin::BI__sync_bool_compare_and_swap_2: 4867 case Builtin::BI__sync_bool_compare_and_swap_4: 4868 case Builtin::BI__sync_bool_compare_and_swap_8: 4869 case Builtin::BI__sync_bool_compare_and_swap_16: 4870 BuiltinIndex = 13; 4871 NumFixed = 2; 4872 ResultType = Context.BoolTy; 4873 break; 4874 4875 case Builtin::BI__sync_lock_test_and_set: 4876 case Builtin::BI__sync_lock_test_and_set_1: 4877 case Builtin::BI__sync_lock_test_and_set_2: 4878 case Builtin::BI__sync_lock_test_and_set_4: 4879 case Builtin::BI__sync_lock_test_and_set_8: 4880 case Builtin::BI__sync_lock_test_and_set_16: 4881 BuiltinIndex = 14; 4882 break; 4883 4884 case Builtin::BI__sync_lock_release: 4885 case Builtin::BI__sync_lock_release_1: 4886 case Builtin::BI__sync_lock_release_2: 4887 case Builtin::BI__sync_lock_release_4: 4888 case Builtin::BI__sync_lock_release_8: 4889 case Builtin::BI__sync_lock_release_16: 4890 BuiltinIndex = 15; 4891 NumFixed = 0; 4892 ResultType = Context.VoidTy; 4893 break; 4894 4895 case Builtin::BI__sync_swap: 4896 case Builtin::BI__sync_swap_1: 4897 case Builtin::BI__sync_swap_2: 4898 case Builtin::BI__sync_swap_4: 4899 case Builtin::BI__sync_swap_8: 4900 case Builtin::BI__sync_swap_16: 4901 BuiltinIndex = 16; 4902 break; 4903 } 4904 4905 // Now that we know how many fixed arguments we expect, first check that we 4906 // have at least that many. 4907 if (TheCall->getNumArgs() < 1+NumFixed) { 4908 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4909 << 0 << 1 + NumFixed << TheCall->getNumArgs() 4910 << TheCall->getCallee()->getSourceRange(); 4911 return ExprError(); 4912 } 4913 4914 if (WarnAboutSemanticsChange) { 4915 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 4916 << TheCall->getCallee()->getSourceRange(); 4917 } 4918 4919 // Get the decl for the concrete builtin from this, we can tell what the 4920 // concrete integer type we should convert to is. 4921 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4922 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4923 FunctionDecl *NewBuiltinDecl; 4924 if (NewBuiltinID == BuiltinID) 4925 NewBuiltinDecl = FDecl; 4926 else { 4927 // Perform builtin lookup to avoid redeclaring it. 4928 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4929 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 4930 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 4931 assert(Res.getFoundDecl()); 4932 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 4933 if (!NewBuiltinDecl) 4934 return ExprError(); 4935 } 4936 4937 // The first argument --- the pointer --- has a fixed type; we 4938 // deduce the types of the rest of the arguments accordingly. Walk 4939 // the remaining arguments, converting them to the deduced value type. 4940 for (unsigned i = 0; i != NumFixed; ++i) { 4941 ExprResult Arg = TheCall->getArg(i+1); 4942 4943 // GCC does an implicit conversion to the pointer or integer ValType. This 4944 // can fail in some cases (1i -> int**), check for this error case now. 4945 // Initialize the argument. 4946 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4947 ValType, /*consume*/ false); 4948 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4949 if (Arg.isInvalid()) 4950 return ExprError(); 4951 4952 // Okay, we have something that *can* be converted to the right type. Check 4953 // to see if there is a potentially weird extension going on here. This can 4954 // happen when you do an atomic operation on something like an char* and 4955 // pass in 42. The 42 gets converted to char. This is even more strange 4956 // for things like 45.123 -> char, etc. 4957 // FIXME: Do this check. 4958 TheCall->setArg(i+1, Arg.get()); 4959 } 4960 4961 ASTContext& Context = this->getASTContext(); 4962 4963 // Create a new DeclRefExpr to refer to the new decl. 4964 DeclRefExpr* NewDRE = DeclRefExpr::Create( 4965 Context, 4966 DRE->getQualifierLoc(), 4967 SourceLocation(), 4968 NewBuiltinDecl, 4969 /*enclosing*/ false, 4970 DRE->getLocation(), 4971 Context.BuiltinFnTy, 4972 DRE->getValueKind()); 4973 4974 // Set the callee in the CallExpr. 4975 // FIXME: This loses syntactic information. 4976 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 4977 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 4978 CK_BuiltinFnToFnPtr); 4979 TheCall->setCallee(PromotedCall.get()); 4980 4981 // Change the result type of the call to match the original value type. This 4982 // is arbitrary, but the codegen for these builtins ins design to handle it 4983 // gracefully. 4984 TheCall->setType(ResultType); 4985 4986 return TheCallResult; 4987 } 4988 4989 /// SemaBuiltinNontemporalOverloaded - We have a call to 4990 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 4991 /// overloaded function based on the pointer type of its last argument. 4992 /// 4993 /// This function goes through and does final semantic checking for these 4994 /// builtins. 4995 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 4996 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 4997 DeclRefExpr *DRE = 4998 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4999 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5000 unsigned BuiltinID = FDecl->getBuiltinID(); 5001 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5002 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5003 "Unexpected nontemporal load/store builtin!"); 5004 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5005 unsigned numArgs = isStore ? 2 : 1; 5006 5007 // Ensure that we have the proper number of arguments. 5008 if (checkArgCount(*this, TheCall, numArgs)) 5009 return ExprError(); 5010 5011 // Inspect the last argument of the nontemporal builtin. This should always 5012 // be a pointer type, from which we imply the type of the memory access. 5013 // Because it is a pointer type, we don't have to worry about any implicit 5014 // casts here. 5015 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5016 ExprResult PointerArgResult = 5017 DefaultFunctionArrayLvalueConversion(PointerArg); 5018 5019 if (PointerArgResult.isInvalid()) 5020 return ExprError(); 5021 PointerArg = PointerArgResult.get(); 5022 TheCall->setArg(numArgs - 1, PointerArg); 5023 5024 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5025 if (!pointerType) { 5026 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5027 << PointerArg->getType() << PointerArg->getSourceRange(); 5028 return ExprError(); 5029 } 5030 5031 QualType ValType = pointerType->getPointeeType(); 5032 5033 // Strip any qualifiers off ValType. 5034 ValType = ValType.getUnqualifiedType(); 5035 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5036 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5037 !ValType->isVectorType()) { 5038 Diag(DRE->getBeginLoc(), 5039 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5040 << PointerArg->getType() << PointerArg->getSourceRange(); 5041 return ExprError(); 5042 } 5043 5044 if (!isStore) { 5045 TheCall->setType(ValType); 5046 return TheCallResult; 5047 } 5048 5049 ExprResult ValArg = TheCall->getArg(0); 5050 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5051 Context, ValType, /*consume*/ false); 5052 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5053 if (ValArg.isInvalid()) 5054 return ExprError(); 5055 5056 TheCall->setArg(0, ValArg.get()); 5057 TheCall->setType(Context.VoidTy); 5058 return TheCallResult; 5059 } 5060 5061 /// CheckObjCString - Checks that the argument to the builtin 5062 /// CFString constructor is correct 5063 /// Note: It might also make sense to do the UTF-16 conversion here (would 5064 /// simplify the backend). 5065 bool Sema::CheckObjCString(Expr *Arg) { 5066 Arg = Arg->IgnoreParenCasts(); 5067 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5068 5069 if (!Literal || !Literal->isAscii()) { 5070 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5071 << Arg->getSourceRange(); 5072 return true; 5073 } 5074 5075 if (Literal->containsNonAsciiOrNull()) { 5076 StringRef String = Literal->getString(); 5077 unsigned NumBytes = String.size(); 5078 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5079 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5080 llvm::UTF16 *ToPtr = &ToBuf[0]; 5081 5082 llvm::ConversionResult Result = 5083 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5084 ToPtr + NumBytes, llvm::strictConversion); 5085 // Check for conversion failure. 5086 if (Result != llvm::conversionOK) 5087 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5088 << Arg->getSourceRange(); 5089 } 5090 return false; 5091 } 5092 5093 /// CheckObjCString - Checks that the format string argument to the os_log() 5094 /// and os_trace() functions is correct, and converts it to const char *. 5095 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5096 Arg = Arg->IgnoreParenCasts(); 5097 auto *Literal = dyn_cast<StringLiteral>(Arg); 5098 if (!Literal) { 5099 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5100 Literal = ObjcLiteral->getString(); 5101 } 5102 } 5103 5104 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5105 return ExprError( 5106 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5107 << Arg->getSourceRange()); 5108 } 5109 5110 ExprResult Result(Literal); 5111 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5112 InitializedEntity Entity = 5113 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5114 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5115 return Result; 5116 } 5117 5118 /// Check that the user is calling the appropriate va_start builtin for the 5119 /// target and calling convention. 5120 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5121 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5122 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5123 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5124 bool IsWindows = TT.isOSWindows(); 5125 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5126 if (IsX64 || IsAArch64) { 5127 CallingConv CC = CC_C; 5128 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5129 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5130 if (IsMSVAStart) { 5131 // Don't allow this in System V ABI functions. 5132 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5133 return S.Diag(Fn->getBeginLoc(), 5134 diag::err_ms_va_start_used_in_sysv_function); 5135 } else { 5136 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5137 // On x64 Windows, don't allow this in System V ABI functions. 5138 // (Yes, that means there's no corresponding way to support variadic 5139 // System V ABI functions on Windows.) 5140 if ((IsWindows && CC == CC_X86_64SysV) || 5141 (!IsWindows && CC == CC_Win64)) 5142 return S.Diag(Fn->getBeginLoc(), 5143 diag::err_va_start_used_in_wrong_abi_function) 5144 << !IsWindows; 5145 } 5146 return false; 5147 } 5148 5149 if (IsMSVAStart) 5150 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5151 return false; 5152 } 5153 5154 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5155 ParmVarDecl **LastParam = nullptr) { 5156 // Determine whether the current function, block, or obj-c method is variadic 5157 // and get its parameter list. 5158 bool IsVariadic = false; 5159 ArrayRef<ParmVarDecl *> Params; 5160 DeclContext *Caller = S.CurContext; 5161 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5162 IsVariadic = Block->isVariadic(); 5163 Params = Block->parameters(); 5164 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5165 IsVariadic = FD->isVariadic(); 5166 Params = FD->parameters(); 5167 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5168 IsVariadic = MD->isVariadic(); 5169 // FIXME: This isn't correct for methods (results in bogus warning). 5170 Params = MD->parameters(); 5171 } else if (isa<CapturedDecl>(Caller)) { 5172 // We don't support va_start in a CapturedDecl. 5173 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5174 return true; 5175 } else { 5176 // This must be some other declcontext that parses exprs. 5177 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5178 return true; 5179 } 5180 5181 if (!IsVariadic) { 5182 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5183 return true; 5184 } 5185 5186 if (LastParam) 5187 *LastParam = Params.empty() ? nullptr : Params.back(); 5188 5189 return false; 5190 } 5191 5192 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5193 /// for validity. Emit an error and return true on failure; return false 5194 /// on success. 5195 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5196 Expr *Fn = TheCall->getCallee(); 5197 5198 if (checkVAStartABI(*this, BuiltinID, Fn)) 5199 return true; 5200 5201 if (TheCall->getNumArgs() > 2) { 5202 Diag(TheCall->getArg(2)->getBeginLoc(), 5203 diag::err_typecheck_call_too_many_args) 5204 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5205 << Fn->getSourceRange() 5206 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5207 (*(TheCall->arg_end() - 1))->getEndLoc()); 5208 return true; 5209 } 5210 5211 if (TheCall->getNumArgs() < 2) { 5212 return Diag(TheCall->getEndLoc(), 5213 diag::err_typecheck_call_too_few_args_at_least) 5214 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5215 } 5216 5217 // Type-check the first argument normally. 5218 if (checkBuiltinArgument(*this, TheCall, 0)) 5219 return true; 5220 5221 // Check that the current function is variadic, and get its last parameter. 5222 ParmVarDecl *LastParam; 5223 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5224 return true; 5225 5226 // Verify that the second argument to the builtin is the last argument of the 5227 // current function or method. 5228 bool SecondArgIsLastNamedArgument = false; 5229 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5230 5231 // These are valid if SecondArgIsLastNamedArgument is false after the next 5232 // block. 5233 QualType Type; 5234 SourceLocation ParamLoc; 5235 bool IsCRegister = false; 5236 5237 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5238 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5239 SecondArgIsLastNamedArgument = PV == LastParam; 5240 5241 Type = PV->getType(); 5242 ParamLoc = PV->getLocation(); 5243 IsCRegister = 5244 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5245 } 5246 } 5247 5248 if (!SecondArgIsLastNamedArgument) 5249 Diag(TheCall->getArg(1)->getBeginLoc(), 5250 diag::warn_second_arg_of_va_start_not_last_named_param); 5251 else if (IsCRegister || Type->isReferenceType() || 5252 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5253 // Promotable integers are UB, but enumerations need a bit of 5254 // extra checking to see what their promotable type actually is. 5255 if (!Type->isPromotableIntegerType()) 5256 return false; 5257 if (!Type->isEnumeralType()) 5258 return true; 5259 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5260 return !(ED && 5261 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5262 }()) { 5263 unsigned Reason = 0; 5264 if (Type->isReferenceType()) Reason = 1; 5265 else if (IsCRegister) Reason = 2; 5266 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5267 Diag(ParamLoc, diag::note_parameter_type) << Type; 5268 } 5269 5270 TheCall->setType(Context.VoidTy); 5271 return false; 5272 } 5273 5274 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5275 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5276 // const char *named_addr); 5277 5278 Expr *Func = Call->getCallee(); 5279 5280 if (Call->getNumArgs() < 3) 5281 return Diag(Call->getEndLoc(), 5282 diag::err_typecheck_call_too_few_args_at_least) 5283 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5284 5285 // Type-check the first argument normally. 5286 if (checkBuiltinArgument(*this, Call, 0)) 5287 return true; 5288 5289 // Check that the current function is variadic. 5290 if (checkVAStartIsInVariadicFunction(*this, Func)) 5291 return true; 5292 5293 // __va_start on Windows does not validate the parameter qualifiers 5294 5295 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5296 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5297 5298 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5299 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5300 5301 const QualType &ConstCharPtrTy = 5302 Context.getPointerType(Context.CharTy.withConst()); 5303 if (!Arg1Ty->isPointerType() || 5304 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5305 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5306 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5307 << 0 /* qualifier difference */ 5308 << 3 /* parameter mismatch */ 5309 << 2 << Arg1->getType() << ConstCharPtrTy; 5310 5311 const QualType SizeTy = Context.getSizeType(); 5312 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5313 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5314 << Arg2->getType() << SizeTy << 1 /* different class */ 5315 << 0 /* qualifier difference */ 5316 << 3 /* parameter mismatch */ 5317 << 3 << Arg2->getType() << SizeTy; 5318 5319 return false; 5320 } 5321 5322 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5323 /// friends. This is declared to take (...), so we have to check everything. 5324 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5325 if (TheCall->getNumArgs() < 2) 5326 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5327 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5328 if (TheCall->getNumArgs() > 2) 5329 return Diag(TheCall->getArg(2)->getBeginLoc(), 5330 diag::err_typecheck_call_too_many_args) 5331 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5332 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5333 (*(TheCall->arg_end() - 1))->getEndLoc()); 5334 5335 ExprResult OrigArg0 = TheCall->getArg(0); 5336 ExprResult OrigArg1 = TheCall->getArg(1); 5337 5338 // Do standard promotions between the two arguments, returning their common 5339 // type. 5340 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5341 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5342 return true; 5343 5344 // Make sure any conversions are pushed back into the call; this is 5345 // type safe since unordered compare builtins are declared as "_Bool 5346 // foo(...)". 5347 TheCall->setArg(0, OrigArg0.get()); 5348 TheCall->setArg(1, OrigArg1.get()); 5349 5350 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5351 return false; 5352 5353 // If the common type isn't a real floating type, then the arguments were 5354 // invalid for this operation. 5355 if (Res.isNull() || !Res->isRealFloatingType()) 5356 return Diag(OrigArg0.get()->getBeginLoc(), 5357 diag::err_typecheck_call_invalid_ordered_compare) 5358 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5359 << SourceRange(OrigArg0.get()->getBeginLoc(), 5360 OrigArg1.get()->getEndLoc()); 5361 5362 return false; 5363 } 5364 5365 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5366 /// __builtin_isnan and friends. This is declared to take (...), so we have 5367 /// to check everything. We expect the last argument to be a floating point 5368 /// value. 5369 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5370 if (TheCall->getNumArgs() < NumArgs) 5371 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5372 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5373 if (TheCall->getNumArgs() > NumArgs) 5374 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5375 diag::err_typecheck_call_too_many_args) 5376 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5377 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5378 (*(TheCall->arg_end() - 1))->getEndLoc()); 5379 5380 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5381 5382 if (OrigArg->isTypeDependent()) 5383 return false; 5384 5385 // This operation requires a non-_Complex floating-point number. 5386 if (!OrigArg->getType()->isRealFloatingType()) 5387 return Diag(OrigArg->getBeginLoc(), 5388 diag::err_typecheck_call_invalid_unary_fp) 5389 << OrigArg->getType() << OrigArg->getSourceRange(); 5390 5391 // If this is an implicit conversion from float -> float, double, or 5392 // long double, remove it. 5393 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5394 // Only remove standard FloatCasts, leaving other casts inplace 5395 if (Cast->getCastKind() == CK_FloatingCast) { 5396 Expr *CastArg = Cast->getSubExpr(); 5397 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5398 assert( 5399 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5400 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5401 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5402 "promotion from float to either float, double, or long double is " 5403 "the only expected cast here"); 5404 Cast->setSubExpr(nullptr); 5405 TheCall->setArg(NumArgs-1, CastArg); 5406 } 5407 } 5408 } 5409 5410 return false; 5411 } 5412 5413 // Customized Sema Checking for VSX builtins that have the following signature: 5414 // vector [...] builtinName(vector [...], vector [...], const int); 5415 // Which takes the same type of vectors (any legal vector type) for the first 5416 // two arguments and takes compile time constant for the third argument. 5417 // Example builtins are : 5418 // vector double vec_xxpermdi(vector double, vector double, int); 5419 // vector short vec_xxsldwi(vector short, vector short, int); 5420 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5421 unsigned ExpectedNumArgs = 3; 5422 if (TheCall->getNumArgs() < ExpectedNumArgs) 5423 return Diag(TheCall->getEndLoc(), 5424 diag::err_typecheck_call_too_few_args_at_least) 5425 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5426 << TheCall->getSourceRange(); 5427 5428 if (TheCall->getNumArgs() > ExpectedNumArgs) 5429 return Diag(TheCall->getEndLoc(), 5430 diag::err_typecheck_call_too_many_args_at_most) 5431 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5432 << TheCall->getSourceRange(); 5433 5434 // Check the third argument is a compile time constant 5435 llvm::APSInt Value; 5436 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5437 return Diag(TheCall->getBeginLoc(), 5438 diag::err_vsx_builtin_nonconstant_argument) 5439 << 3 /* argument index */ << TheCall->getDirectCallee() 5440 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5441 TheCall->getArg(2)->getEndLoc()); 5442 5443 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5444 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5445 5446 // Check the type of argument 1 and argument 2 are vectors. 5447 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5448 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5449 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5450 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5451 << TheCall->getDirectCallee() 5452 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5453 TheCall->getArg(1)->getEndLoc()); 5454 } 5455 5456 // Check the first two arguments are the same type. 5457 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5458 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5459 << TheCall->getDirectCallee() 5460 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5461 TheCall->getArg(1)->getEndLoc()); 5462 } 5463 5464 // When default clang type checking is turned off and the customized type 5465 // checking is used, the returning type of the function must be explicitly 5466 // set. Otherwise it is _Bool by default. 5467 TheCall->setType(Arg1Ty); 5468 5469 return false; 5470 } 5471 5472 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5473 // This is declared to take (...), so we have to check everything. 5474 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5475 if (TheCall->getNumArgs() < 2) 5476 return ExprError(Diag(TheCall->getEndLoc(), 5477 diag::err_typecheck_call_too_few_args_at_least) 5478 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5479 << TheCall->getSourceRange()); 5480 5481 // Determine which of the following types of shufflevector we're checking: 5482 // 1) unary, vector mask: (lhs, mask) 5483 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5484 QualType resType = TheCall->getArg(0)->getType(); 5485 unsigned numElements = 0; 5486 5487 if (!TheCall->getArg(0)->isTypeDependent() && 5488 !TheCall->getArg(1)->isTypeDependent()) { 5489 QualType LHSType = TheCall->getArg(0)->getType(); 5490 QualType RHSType = TheCall->getArg(1)->getType(); 5491 5492 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5493 return ExprError( 5494 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5495 << TheCall->getDirectCallee() 5496 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5497 TheCall->getArg(1)->getEndLoc())); 5498 5499 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5500 unsigned numResElements = TheCall->getNumArgs() - 2; 5501 5502 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5503 // with mask. If so, verify that RHS is an integer vector type with the 5504 // same number of elts as lhs. 5505 if (TheCall->getNumArgs() == 2) { 5506 if (!RHSType->hasIntegerRepresentation() || 5507 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5508 return ExprError(Diag(TheCall->getBeginLoc(), 5509 diag::err_vec_builtin_incompatible_vector) 5510 << TheCall->getDirectCallee() 5511 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5512 TheCall->getArg(1)->getEndLoc())); 5513 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5514 return ExprError(Diag(TheCall->getBeginLoc(), 5515 diag::err_vec_builtin_incompatible_vector) 5516 << TheCall->getDirectCallee() 5517 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5518 TheCall->getArg(1)->getEndLoc())); 5519 } else if (numElements != numResElements) { 5520 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5521 resType = Context.getVectorType(eltType, numResElements, 5522 VectorType::GenericVector); 5523 } 5524 } 5525 5526 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5527 if (TheCall->getArg(i)->isTypeDependent() || 5528 TheCall->getArg(i)->isValueDependent()) 5529 continue; 5530 5531 llvm::APSInt Result(32); 5532 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5533 return ExprError(Diag(TheCall->getBeginLoc(), 5534 diag::err_shufflevector_nonconstant_argument) 5535 << TheCall->getArg(i)->getSourceRange()); 5536 5537 // Allow -1 which will be translated to undef in the IR. 5538 if (Result.isSigned() && Result.isAllOnesValue()) 5539 continue; 5540 5541 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5542 return ExprError(Diag(TheCall->getBeginLoc(), 5543 diag::err_shufflevector_argument_too_large) 5544 << TheCall->getArg(i)->getSourceRange()); 5545 } 5546 5547 SmallVector<Expr*, 32> exprs; 5548 5549 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5550 exprs.push_back(TheCall->getArg(i)); 5551 TheCall->setArg(i, nullptr); 5552 } 5553 5554 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5555 TheCall->getCallee()->getBeginLoc(), 5556 TheCall->getRParenLoc()); 5557 } 5558 5559 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5560 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5561 SourceLocation BuiltinLoc, 5562 SourceLocation RParenLoc) { 5563 ExprValueKind VK = VK_RValue; 5564 ExprObjectKind OK = OK_Ordinary; 5565 QualType DstTy = TInfo->getType(); 5566 QualType SrcTy = E->getType(); 5567 5568 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5569 return ExprError(Diag(BuiltinLoc, 5570 diag::err_convertvector_non_vector) 5571 << E->getSourceRange()); 5572 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5573 return ExprError(Diag(BuiltinLoc, 5574 diag::err_convertvector_non_vector_type)); 5575 5576 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5577 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5578 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5579 if (SrcElts != DstElts) 5580 return ExprError(Diag(BuiltinLoc, 5581 diag::err_convertvector_incompatible_vector) 5582 << E->getSourceRange()); 5583 } 5584 5585 return new (Context) 5586 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5587 } 5588 5589 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5590 // This is declared to take (const void*, ...) and can take two 5591 // optional constant int args. 5592 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5593 unsigned NumArgs = TheCall->getNumArgs(); 5594 5595 if (NumArgs > 3) 5596 return Diag(TheCall->getEndLoc(), 5597 diag::err_typecheck_call_too_many_args_at_most) 5598 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5599 5600 // Argument 0 is checked for us and the remaining arguments must be 5601 // constant integers. 5602 for (unsigned i = 1; i != NumArgs; ++i) 5603 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5604 return true; 5605 5606 return false; 5607 } 5608 5609 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5610 // __assume does not evaluate its arguments, and should warn if its argument 5611 // has side effects. 5612 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5613 Expr *Arg = TheCall->getArg(0); 5614 if (Arg->isInstantiationDependent()) return false; 5615 5616 if (Arg->HasSideEffects(Context)) 5617 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5618 << Arg->getSourceRange() 5619 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5620 5621 return false; 5622 } 5623 5624 /// Handle __builtin_alloca_with_align. This is declared 5625 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5626 /// than 8. 5627 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5628 // The alignment must be a constant integer. 5629 Expr *Arg = TheCall->getArg(1); 5630 5631 // We can't check the value of a dependent argument. 5632 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5633 if (const auto *UE = 5634 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5635 if (UE->getKind() == UETT_AlignOf) 5636 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5637 << Arg->getSourceRange(); 5638 5639 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5640 5641 if (!Result.isPowerOf2()) 5642 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5643 << Arg->getSourceRange(); 5644 5645 if (Result < Context.getCharWidth()) 5646 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5647 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5648 5649 if (Result > std::numeric_limits<int32_t>::max()) 5650 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5651 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5652 } 5653 5654 return false; 5655 } 5656 5657 /// Handle __builtin_assume_aligned. This is declared 5658 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5659 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5660 unsigned NumArgs = TheCall->getNumArgs(); 5661 5662 if (NumArgs > 3) 5663 return Diag(TheCall->getEndLoc(), 5664 diag::err_typecheck_call_too_many_args_at_most) 5665 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5666 5667 // The alignment must be a constant integer. 5668 Expr *Arg = TheCall->getArg(1); 5669 5670 // We can't check the value of a dependent argument. 5671 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5672 llvm::APSInt Result; 5673 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5674 return true; 5675 5676 if (!Result.isPowerOf2()) 5677 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5678 << Arg->getSourceRange(); 5679 } 5680 5681 if (NumArgs > 2) { 5682 ExprResult Arg(TheCall->getArg(2)); 5683 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5684 Context.getSizeType(), false); 5685 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5686 if (Arg.isInvalid()) return true; 5687 TheCall->setArg(2, Arg.get()); 5688 } 5689 5690 return false; 5691 } 5692 5693 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5694 unsigned BuiltinID = 5695 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5696 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5697 5698 unsigned NumArgs = TheCall->getNumArgs(); 5699 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5700 if (NumArgs < NumRequiredArgs) { 5701 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5702 << 0 /* function call */ << NumRequiredArgs << NumArgs 5703 << TheCall->getSourceRange(); 5704 } 5705 if (NumArgs >= NumRequiredArgs + 0x100) { 5706 return Diag(TheCall->getEndLoc(), 5707 diag::err_typecheck_call_too_many_args_at_most) 5708 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5709 << TheCall->getSourceRange(); 5710 } 5711 unsigned i = 0; 5712 5713 // For formatting call, check buffer arg. 5714 if (!IsSizeCall) { 5715 ExprResult Arg(TheCall->getArg(i)); 5716 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5717 Context, Context.VoidPtrTy, false); 5718 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5719 if (Arg.isInvalid()) 5720 return true; 5721 TheCall->setArg(i, Arg.get()); 5722 i++; 5723 } 5724 5725 // Check string literal arg. 5726 unsigned FormatIdx = i; 5727 { 5728 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5729 if (Arg.isInvalid()) 5730 return true; 5731 TheCall->setArg(i, Arg.get()); 5732 i++; 5733 } 5734 5735 // Make sure variadic args are scalar. 5736 unsigned FirstDataArg = i; 5737 while (i < NumArgs) { 5738 ExprResult Arg = DefaultVariadicArgumentPromotion( 5739 TheCall->getArg(i), VariadicFunction, nullptr); 5740 if (Arg.isInvalid()) 5741 return true; 5742 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5743 if (ArgSize.getQuantity() >= 0x100) { 5744 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5745 << i << (int)ArgSize.getQuantity() << 0xff 5746 << TheCall->getSourceRange(); 5747 } 5748 TheCall->setArg(i, Arg.get()); 5749 i++; 5750 } 5751 5752 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5753 // call to avoid duplicate diagnostics. 5754 if (!IsSizeCall) { 5755 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5756 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5757 bool Success = CheckFormatArguments( 5758 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5759 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5760 CheckedVarArgs); 5761 if (!Success) 5762 return true; 5763 } 5764 5765 if (IsSizeCall) { 5766 TheCall->setType(Context.getSizeType()); 5767 } else { 5768 TheCall->setType(Context.VoidPtrTy); 5769 } 5770 return false; 5771 } 5772 5773 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5774 /// TheCall is a constant expression. 5775 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5776 llvm::APSInt &Result) { 5777 Expr *Arg = TheCall->getArg(ArgNum); 5778 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5779 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5780 5781 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5782 5783 if (!Arg->isIntegerConstantExpr(Result, Context)) 5784 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5785 << FDecl->getDeclName() << Arg->getSourceRange(); 5786 5787 return false; 5788 } 5789 5790 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5791 /// TheCall is a constant expression in the range [Low, High]. 5792 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5793 int Low, int High, bool RangeIsError) { 5794 llvm::APSInt Result; 5795 5796 // We can't check the value of a dependent argument. 5797 Expr *Arg = TheCall->getArg(ArgNum); 5798 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5799 return false; 5800 5801 // Check constant-ness first. 5802 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5803 return true; 5804 5805 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5806 if (RangeIsError) 5807 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5808 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5809 else 5810 // Defer the warning until we know if the code will be emitted so that 5811 // dead code can ignore this. 5812 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5813 PDiag(diag::warn_argument_invalid_range) 5814 << Result.toString(10) << Low << High 5815 << Arg->getSourceRange()); 5816 } 5817 5818 return false; 5819 } 5820 5821 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5822 /// TheCall is a constant expression is a multiple of Num.. 5823 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5824 unsigned Num) { 5825 llvm::APSInt Result; 5826 5827 // We can't check the value of a dependent argument. 5828 Expr *Arg = TheCall->getArg(ArgNum); 5829 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5830 return false; 5831 5832 // Check constant-ness first. 5833 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5834 return true; 5835 5836 if (Result.getSExtValue() % Num != 0) 5837 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5838 << Num << Arg->getSourceRange(); 5839 5840 return false; 5841 } 5842 5843 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 5844 /// TheCall is an ARM/AArch64 special register string literal. 5845 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 5846 int ArgNum, unsigned ExpectedFieldNum, 5847 bool AllowName) { 5848 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 5849 BuiltinID == ARM::BI__builtin_arm_wsr64 || 5850 BuiltinID == ARM::BI__builtin_arm_rsr || 5851 BuiltinID == ARM::BI__builtin_arm_rsrp || 5852 BuiltinID == ARM::BI__builtin_arm_wsr || 5853 BuiltinID == ARM::BI__builtin_arm_wsrp; 5854 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 5855 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 5856 BuiltinID == AArch64::BI__builtin_arm_rsr || 5857 BuiltinID == AArch64::BI__builtin_arm_rsrp || 5858 BuiltinID == AArch64::BI__builtin_arm_wsr || 5859 BuiltinID == AArch64::BI__builtin_arm_wsrp; 5860 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 5861 5862 // We can't check the value of a dependent argument. 5863 Expr *Arg = TheCall->getArg(ArgNum); 5864 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5865 return false; 5866 5867 // Check if the argument is a string literal. 5868 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 5869 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 5870 << Arg->getSourceRange(); 5871 5872 // Check the type of special register given. 5873 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 5874 SmallVector<StringRef, 6> Fields; 5875 Reg.split(Fields, ":"); 5876 5877 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 5878 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 5879 << Arg->getSourceRange(); 5880 5881 // If the string is the name of a register then we cannot check that it is 5882 // valid here but if the string is of one the forms described in ACLE then we 5883 // can check that the supplied fields are integers and within the valid 5884 // ranges. 5885 if (Fields.size() > 1) { 5886 bool FiveFields = Fields.size() == 5; 5887 5888 bool ValidString = true; 5889 if (IsARMBuiltin) { 5890 ValidString &= Fields[0].startswith_lower("cp") || 5891 Fields[0].startswith_lower("p"); 5892 if (ValidString) 5893 Fields[0] = 5894 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 5895 5896 ValidString &= Fields[2].startswith_lower("c"); 5897 if (ValidString) 5898 Fields[2] = Fields[2].drop_front(1); 5899 5900 if (FiveFields) { 5901 ValidString &= Fields[3].startswith_lower("c"); 5902 if (ValidString) 5903 Fields[3] = Fields[3].drop_front(1); 5904 } 5905 } 5906 5907 SmallVector<int, 5> Ranges; 5908 if (FiveFields) 5909 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 5910 else 5911 Ranges.append({15, 7, 15}); 5912 5913 for (unsigned i=0; i<Fields.size(); ++i) { 5914 int IntField; 5915 ValidString &= !Fields[i].getAsInteger(10, IntField); 5916 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 5917 } 5918 5919 if (!ValidString) 5920 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 5921 << Arg->getSourceRange(); 5922 } else if (IsAArch64Builtin && Fields.size() == 1) { 5923 // If the register name is one of those that appear in the condition below 5924 // and the special register builtin being used is one of the write builtins, 5925 // then we require that the argument provided for writing to the register 5926 // is an integer constant expression. This is because it will be lowered to 5927 // an MSR (immediate) instruction, so we need to know the immediate at 5928 // compile time. 5929 if (TheCall->getNumArgs() != 2) 5930 return false; 5931 5932 std::string RegLower = Reg.lower(); 5933 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 5934 RegLower != "pan" && RegLower != "uao") 5935 return false; 5936 5937 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 5938 } 5939 5940 return false; 5941 } 5942 5943 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 5944 /// This checks that the target supports __builtin_longjmp and 5945 /// that val is a constant 1. 5946 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 5947 if (!Context.getTargetInfo().hasSjLjLowering()) 5948 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 5949 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 5950 5951 Expr *Arg = TheCall->getArg(1); 5952 llvm::APSInt Result; 5953 5954 // TODO: This is less than ideal. Overload this to take a value. 5955 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5956 return true; 5957 5958 if (Result != 1) 5959 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 5960 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 5961 5962 return false; 5963 } 5964 5965 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 5966 /// This checks that the target supports __builtin_setjmp. 5967 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 5968 if (!Context.getTargetInfo().hasSjLjLowering()) 5969 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 5970 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 5971 return false; 5972 } 5973 5974 namespace { 5975 5976 class UncoveredArgHandler { 5977 enum { Unknown = -1, AllCovered = -2 }; 5978 5979 signed FirstUncoveredArg = Unknown; 5980 SmallVector<const Expr *, 4> DiagnosticExprs; 5981 5982 public: 5983 UncoveredArgHandler() = default; 5984 5985 bool hasUncoveredArg() const { 5986 return (FirstUncoveredArg >= 0); 5987 } 5988 5989 unsigned getUncoveredArg() const { 5990 assert(hasUncoveredArg() && "no uncovered argument"); 5991 return FirstUncoveredArg; 5992 } 5993 5994 void setAllCovered() { 5995 // A string has been found with all arguments covered, so clear out 5996 // the diagnostics. 5997 DiagnosticExprs.clear(); 5998 FirstUncoveredArg = AllCovered; 5999 } 6000 6001 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6002 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6003 6004 // Don't update if a previous string covers all arguments. 6005 if (FirstUncoveredArg == AllCovered) 6006 return; 6007 6008 // UncoveredArgHandler tracks the highest uncovered argument index 6009 // and with it all the strings that match this index. 6010 if (NewFirstUncoveredArg == FirstUncoveredArg) 6011 DiagnosticExprs.push_back(StrExpr); 6012 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6013 DiagnosticExprs.clear(); 6014 DiagnosticExprs.push_back(StrExpr); 6015 FirstUncoveredArg = NewFirstUncoveredArg; 6016 } 6017 } 6018 6019 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6020 }; 6021 6022 enum StringLiteralCheckType { 6023 SLCT_NotALiteral, 6024 SLCT_UncheckedLiteral, 6025 SLCT_CheckedLiteral 6026 }; 6027 6028 } // namespace 6029 6030 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6031 BinaryOperatorKind BinOpKind, 6032 bool AddendIsRight) { 6033 unsigned BitWidth = Offset.getBitWidth(); 6034 unsigned AddendBitWidth = Addend.getBitWidth(); 6035 // There might be negative interim results. 6036 if (Addend.isUnsigned()) { 6037 Addend = Addend.zext(++AddendBitWidth); 6038 Addend.setIsSigned(true); 6039 } 6040 // Adjust the bit width of the APSInts. 6041 if (AddendBitWidth > BitWidth) { 6042 Offset = Offset.sext(AddendBitWidth); 6043 BitWidth = AddendBitWidth; 6044 } else if (BitWidth > AddendBitWidth) { 6045 Addend = Addend.sext(BitWidth); 6046 } 6047 6048 bool Ov = false; 6049 llvm::APSInt ResOffset = Offset; 6050 if (BinOpKind == BO_Add) 6051 ResOffset = Offset.sadd_ov(Addend, Ov); 6052 else { 6053 assert(AddendIsRight && BinOpKind == BO_Sub && 6054 "operator must be add or sub with addend on the right"); 6055 ResOffset = Offset.ssub_ov(Addend, Ov); 6056 } 6057 6058 // We add an offset to a pointer here so we should support an offset as big as 6059 // possible. 6060 if (Ov) { 6061 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6062 "index (intermediate) result too big"); 6063 Offset = Offset.sext(2 * BitWidth); 6064 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6065 return; 6066 } 6067 6068 Offset = ResOffset; 6069 } 6070 6071 namespace { 6072 6073 // This is a wrapper class around StringLiteral to support offsetted string 6074 // literals as format strings. It takes the offset into account when returning 6075 // the string and its length or the source locations to display notes correctly. 6076 class FormatStringLiteral { 6077 const StringLiteral *FExpr; 6078 int64_t Offset; 6079 6080 public: 6081 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6082 : FExpr(fexpr), Offset(Offset) {} 6083 6084 StringRef getString() const { 6085 return FExpr->getString().drop_front(Offset); 6086 } 6087 6088 unsigned getByteLength() const { 6089 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6090 } 6091 6092 unsigned getLength() const { return FExpr->getLength() - Offset; } 6093 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6094 6095 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6096 6097 QualType getType() const { return FExpr->getType(); } 6098 6099 bool isAscii() const { return FExpr->isAscii(); } 6100 bool isWide() const { return FExpr->isWide(); } 6101 bool isUTF8() const { return FExpr->isUTF8(); } 6102 bool isUTF16() const { return FExpr->isUTF16(); } 6103 bool isUTF32() const { return FExpr->isUTF32(); } 6104 bool isPascal() const { return FExpr->isPascal(); } 6105 6106 SourceLocation getLocationOfByte( 6107 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6108 const TargetInfo &Target, unsigned *StartToken = nullptr, 6109 unsigned *StartTokenByteOffset = nullptr) const { 6110 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6111 StartToken, StartTokenByteOffset); 6112 } 6113 6114 LLVM_ATTRIBUTE_DEPRECATED(SourceLocation getLocStart() const LLVM_READONLY, 6115 "Use getBeginLoc instead") { 6116 return getBeginLoc(); 6117 } 6118 SourceLocation getBeginLoc() const LLVM_READONLY { 6119 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6120 } 6121 6122 LLVM_ATTRIBUTE_DEPRECATED(SourceLocation getLocEnd() const LLVM_READONLY, 6123 "Use getEndLoc instead") { 6124 return getEndLoc(); 6125 } 6126 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6127 }; 6128 6129 } // namespace 6130 6131 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6132 const Expr *OrigFormatExpr, 6133 ArrayRef<const Expr *> Args, 6134 bool HasVAListArg, unsigned format_idx, 6135 unsigned firstDataArg, 6136 Sema::FormatStringType Type, 6137 bool inFunctionCall, 6138 Sema::VariadicCallType CallType, 6139 llvm::SmallBitVector &CheckedVarArgs, 6140 UncoveredArgHandler &UncoveredArg); 6141 6142 // Determine if an expression is a string literal or constant string. 6143 // If this function returns false on the arguments to a function expecting a 6144 // format string, we will usually need to emit a warning. 6145 // True string literals are then checked by CheckFormatString. 6146 static StringLiteralCheckType 6147 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6148 bool HasVAListArg, unsigned format_idx, 6149 unsigned firstDataArg, Sema::FormatStringType Type, 6150 Sema::VariadicCallType CallType, bool InFunctionCall, 6151 llvm::SmallBitVector &CheckedVarArgs, 6152 UncoveredArgHandler &UncoveredArg, 6153 llvm::APSInt Offset) { 6154 tryAgain: 6155 assert(Offset.isSigned() && "invalid offset"); 6156 6157 if (E->isTypeDependent() || E->isValueDependent()) 6158 return SLCT_NotALiteral; 6159 6160 E = E->IgnoreParenCasts(); 6161 6162 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6163 // Technically -Wformat-nonliteral does not warn about this case. 6164 // The behavior of printf and friends in this case is implementation 6165 // dependent. Ideally if the format string cannot be null then 6166 // it should have a 'nonnull' attribute in the function prototype. 6167 return SLCT_UncheckedLiteral; 6168 6169 switch (E->getStmtClass()) { 6170 case Stmt::BinaryConditionalOperatorClass: 6171 case Stmt::ConditionalOperatorClass: { 6172 // The expression is a literal if both sub-expressions were, and it was 6173 // completely checked only if both sub-expressions were checked. 6174 const AbstractConditionalOperator *C = 6175 cast<AbstractConditionalOperator>(E); 6176 6177 // Determine whether it is necessary to check both sub-expressions, for 6178 // example, because the condition expression is a constant that can be 6179 // evaluated at compile time. 6180 bool CheckLeft = true, CheckRight = true; 6181 6182 bool Cond; 6183 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 6184 if (Cond) 6185 CheckRight = false; 6186 else 6187 CheckLeft = false; 6188 } 6189 6190 // We need to maintain the offsets for the right and the left hand side 6191 // separately to check if every possible indexed expression is a valid 6192 // string literal. They might have different offsets for different string 6193 // literals in the end. 6194 StringLiteralCheckType Left; 6195 if (!CheckLeft) 6196 Left = SLCT_UncheckedLiteral; 6197 else { 6198 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6199 HasVAListArg, format_idx, firstDataArg, 6200 Type, CallType, InFunctionCall, 6201 CheckedVarArgs, UncoveredArg, Offset); 6202 if (Left == SLCT_NotALiteral || !CheckRight) { 6203 return Left; 6204 } 6205 } 6206 6207 StringLiteralCheckType Right = 6208 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6209 HasVAListArg, format_idx, firstDataArg, 6210 Type, CallType, InFunctionCall, CheckedVarArgs, 6211 UncoveredArg, Offset); 6212 6213 return (CheckLeft && Left < Right) ? Left : Right; 6214 } 6215 6216 case Stmt::ImplicitCastExprClass: 6217 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6218 goto tryAgain; 6219 6220 case Stmt::OpaqueValueExprClass: 6221 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6222 E = src; 6223 goto tryAgain; 6224 } 6225 return SLCT_NotALiteral; 6226 6227 case Stmt::PredefinedExprClass: 6228 // While __func__, etc., are technically not string literals, they 6229 // cannot contain format specifiers and thus are not a security 6230 // liability. 6231 return SLCT_UncheckedLiteral; 6232 6233 case Stmt::DeclRefExprClass: { 6234 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6235 6236 // As an exception, do not flag errors for variables binding to 6237 // const string literals. 6238 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6239 bool isConstant = false; 6240 QualType T = DR->getType(); 6241 6242 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6243 isConstant = AT->getElementType().isConstant(S.Context); 6244 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6245 isConstant = T.isConstant(S.Context) && 6246 PT->getPointeeType().isConstant(S.Context); 6247 } else if (T->isObjCObjectPointerType()) { 6248 // In ObjC, there is usually no "const ObjectPointer" type, 6249 // so don't check if the pointee type is constant. 6250 isConstant = T.isConstant(S.Context); 6251 } 6252 6253 if (isConstant) { 6254 if (const Expr *Init = VD->getAnyInitializer()) { 6255 // Look through initializers like const char c[] = { "foo" } 6256 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6257 if (InitList->isStringLiteralInit()) 6258 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6259 } 6260 return checkFormatStringExpr(S, Init, Args, 6261 HasVAListArg, format_idx, 6262 firstDataArg, Type, CallType, 6263 /*InFunctionCall*/ false, CheckedVarArgs, 6264 UncoveredArg, Offset); 6265 } 6266 } 6267 6268 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6269 // special check to see if the format string is a function parameter 6270 // of the function calling the printf function. If the function 6271 // has an attribute indicating it is a printf-like function, then we 6272 // should suppress warnings concerning non-literals being used in a call 6273 // to a vprintf function. For example: 6274 // 6275 // void 6276 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6277 // va_list ap; 6278 // va_start(ap, fmt); 6279 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6280 // ... 6281 // } 6282 if (HasVAListArg) { 6283 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6284 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6285 int PVIndex = PV->getFunctionScopeIndex() + 1; 6286 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6287 // adjust for implicit parameter 6288 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6289 if (MD->isInstance()) 6290 ++PVIndex; 6291 // We also check if the formats are compatible. 6292 // We can't pass a 'scanf' string to a 'printf' function. 6293 if (PVIndex == PVFormat->getFormatIdx() && 6294 Type == S.GetFormatStringType(PVFormat)) 6295 return SLCT_UncheckedLiteral; 6296 } 6297 } 6298 } 6299 } 6300 } 6301 6302 return SLCT_NotALiteral; 6303 } 6304 6305 case Stmt::CallExprClass: 6306 case Stmt::CXXMemberCallExprClass: { 6307 const CallExpr *CE = cast<CallExpr>(E); 6308 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6309 bool IsFirst = true; 6310 StringLiteralCheckType CommonResult; 6311 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6312 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6313 StringLiteralCheckType Result = checkFormatStringExpr( 6314 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6315 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6316 if (IsFirst) { 6317 CommonResult = Result; 6318 IsFirst = false; 6319 } 6320 } 6321 if (!IsFirst) 6322 return CommonResult; 6323 6324 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6325 unsigned BuiltinID = FD->getBuiltinID(); 6326 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6327 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6328 const Expr *Arg = CE->getArg(0); 6329 return checkFormatStringExpr(S, Arg, Args, 6330 HasVAListArg, format_idx, 6331 firstDataArg, Type, CallType, 6332 InFunctionCall, CheckedVarArgs, 6333 UncoveredArg, Offset); 6334 } 6335 } 6336 } 6337 6338 return SLCT_NotALiteral; 6339 } 6340 case Stmt::ObjCMessageExprClass: { 6341 const auto *ME = cast<ObjCMessageExpr>(E); 6342 if (const auto *ND = ME->getMethodDecl()) { 6343 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6344 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6345 return checkFormatStringExpr( 6346 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6347 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6348 } 6349 } 6350 6351 return SLCT_NotALiteral; 6352 } 6353 case Stmt::ObjCStringLiteralClass: 6354 case Stmt::StringLiteralClass: { 6355 const StringLiteral *StrE = nullptr; 6356 6357 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6358 StrE = ObjCFExpr->getString(); 6359 else 6360 StrE = cast<StringLiteral>(E); 6361 6362 if (StrE) { 6363 if (Offset.isNegative() || Offset > StrE->getLength()) { 6364 // TODO: It would be better to have an explicit warning for out of 6365 // bounds literals. 6366 return SLCT_NotALiteral; 6367 } 6368 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6369 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6370 firstDataArg, Type, InFunctionCall, CallType, 6371 CheckedVarArgs, UncoveredArg); 6372 return SLCT_CheckedLiteral; 6373 } 6374 6375 return SLCT_NotALiteral; 6376 } 6377 case Stmt::BinaryOperatorClass: { 6378 llvm::APSInt LResult; 6379 llvm::APSInt RResult; 6380 6381 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6382 6383 // A string literal + an int offset is still a string literal. 6384 if (BinOp->isAdditiveOp()) { 6385 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 6386 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 6387 6388 if (LIsInt != RIsInt) { 6389 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6390 6391 if (LIsInt) { 6392 if (BinOpKind == BO_Add) { 6393 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 6394 E = BinOp->getRHS(); 6395 goto tryAgain; 6396 } 6397 } else { 6398 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 6399 E = BinOp->getLHS(); 6400 goto tryAgain; 6401 } 6402 } 6403 } 6404 6405 return SLCT_NotALiteral; 6406 } 6407 case Stmt::UnaryOperatorClass: { 6408 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6409 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6410 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6411 llvm::APSInt IndexResult; 6412 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 6413 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 6414 E = ASE->getBase(); 6415 goto tryAgain; 6416 } 6417 } 6418 6419 return SLCT_NotALiteral; 6420 } 6421 6422 default: 6423 return SLCT_NotALiteral; 6424 } 6425 } 6426 6427 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6428 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6429 .Case("scanf", FST_Scanf) 6430 .Cases("printf", "printf0", FST_Printf) 6431 .Cases("NSString", "CFString", FST_NSString) 6432 .Case("strftime", FST_Strftime) 6433 .Case("strfmon", FST_Strfmon) 6434 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6435 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6436 .Case("os_trace", FST_OSLog) 6437 .Case("os_log", FST_OSLog) 6438 .Default(FST_Unknown); 6439 } 6440 6441 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6442 /// functions) for correct use of format strings. 6443 /// Returns true if a format string has been fully checked. 6444 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6445 ArrayRef<const Expr *> Args, 6446 bool IsCXXMember, 6447 VariadicCallType CallType, 6448 SourceLocation Loc, SourceRange Range, 6449 llvm::SmallBitVector &CheckedVarArgs) { 6450 FormatStringInfo FSI; 6451 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6452 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6453 FSI.FirstDataArg, GetFormatStringType(Format), 6454 CallType, Loc, Range, CheckedVarArgs); 6455 return false; 6456 } 6457 6458 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6459 bool HasVAListArg, unsigned format_idx, 6460 unsigned firstDataArg, FormatStringType Type, 6461 VariadicCallType CallType, 6462 SourceLocation Loc, SourceRange Range, 6463 llvm::SmallBitVector &CheckedVarArgs) { 6464 // CHECK: printf/scanf-like function is called with no format string. 6465 if (format_idx >= Args.size()) { 6466 Diag(Loc, diag::warn_missing_format_string) << Range; 6467 return false; 6468 } 6469 6470 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6471 6472 // CHECK: format string is not a string literal. 6473 // 6474 // Dynamically generated format strings are difficult to 6475 // automatically vet at compile time. Requiring that format strings 6476 // are string literals: (1) permits the checking of format strings by 6477 // the compiler and thereby (2) can practically remove the source of 6478 // many format string exploits. 6479 6480 // Format string can be either ObjC string (e.g. @"%d") or 6481 // C string (e.g. "%d") 6482 // ObjC string uses the same format specifiers as C string, so we can use 6483 // the same format string checking logic for both ObjC and C strings. 6484 UncoveredArgHandler UncoveredArg; 6485 StringLiteralCheckType CT = 6486 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6487 format_idx, firstDataArg, Type, CallType, 6488 /*IsFunctionCall*/ true, CheckedVarArgs, 6489 UncoveredArg, 6490 /*no string offset*/ llvm::APSInt(64, false) = 0); 6491 6492 // Generate a diagnostic where an uncovered argument is detected. 6493 if (UncoveredArg.hasUncoveredArg()) { 6494 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6495 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6496 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6497 } 6498 6499 if (CT != SLCT_NotALiteral) 6500 // Literal format string found, check done! 6501 return CT == SLCT_CheckedLiteral; 6502 6503 // Strftime is particular as it always uses a single 'time' argument, 6504 // so it is safe to pass a non-literal string. 6505 if (Type == FST_Strftime) 6506 return false; 6507 6508 // Do not emit diag when the string param is a macro expansion and the 6509 // format is either NSString or CFString. This is a hack to prevent 6510 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6511 // which are usually used in place of NS and CF string literals. 6512 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6513 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6514 return false; 6515 6516 // If there are no arguments specified, warn with -Wformat-security, otherwise 6517 // warn only with -Wformat-nonliteral. 6518 if (Args.size() == firstDataArg) { 6519 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6520 << OrigFormatExpr->getSourceRange(); 6521 switch (Type) { 6522 default: 6523 break; 6524 case FST_Kprintf: 6525 case FST_FreeBSDKPrintf: 6526 case FST_Printf: 6527 Diag(FormatLoc, diag::note_format_security_fixit) 6528 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6529 break; 6530 case FST_NSString: 6531 Diag(FormatLoc, diag::note_format_security_fixit) 6532 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6533 break; 6534 } 6535 } else { 6536 Diag(FormatLoc, diag::warn_format_nonliteral) 6537 << OrigFormatExpr->getSourceRange(); 6538 } 6539 return false; 6540 } 6541 6542 namespace { 6543 6544 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6545 protected: 6546 Sema &S; 6547 const FormatStringLiteral *FExpr; 6548 const Expr *OrigFormatExpr; 6549 const Sema::FormatStringType FSType; 6550 const unsigned FirstDataArg; 6551 const unsigned NumDataArgs; 6552 const char *Beg; // Start of format string. 6553 const bool HasVAListArg; 6554 ArrayRef<const Expr *> Args; 6555 unsigned FormatIdx; 6556 llvm::SmallBitVector CoveredArgs; 6557 bool usesPositionalArgs = false; 6558 bool atFirstArg = true; 6559 bool inFunctionCall; 6560 Sema::VariadicCallType CallType; 6561 llvm::SmallBitVector &CheckedVarArgs; 6562 UncoveredArgHandler &UncoveredArg; 6563 6564 public: 6565 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6566 const Expr *origFormatExpr, 6567 const Sema::FormatStringType type, unsigned firstDataArg, 6568 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6569 ArrayRef<const Expr *> Args, unsigned formatIdx, 6570 bool inFunctionCall, Sema::VariadicCallType callType, 6571 llvm::SmallBitVector &CheckedVarArgs, 6572 UncoveredArgHandler &UncoveredArg) 6573 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6574 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6575 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6576 inFunctionCall(inFunctionCall), CallType(callType), 6577 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6578 CoveredArgs.resize(numDataArgs); 6579 CoveredArgs.reset(); 6580 } 6581 6582 void DoneProcessing(); 6583 6584 void HandleIncompleteSpecifier(const char *startSpecifier, 6585 unsigned specifierLen) override; 6586 6587 void HandleInvalidLengthModifier( 6588 const analyze_format_string::FormatSpecifier &FS, 6589 const analyze_format_string::ConversionSpecifier &CS, 6590 const char *startSpecifier, unsigned specifierLen, 6591 unsigned DiagID); 6592 6593 void HandleNonStandardLengthModifier( 6594 const analyze_format_string::FormatSpecifier &FS, 6595 const char *startSpecifier, unsigned specifierLen); 6596 6597 void HandleNonStandardConversionSpecifier( 6598 const analyze_format_string::ConversionSpecifier &CS, 6599 const char *startSpecifier, unsigned specifierLen); 6600 6601 void HandlePosition(const char *startPos, unsigned posLen) override; 6602 6603 void HandleInvalidPosition(const char *startSpecifier, 6604 unsigned specifierLen, 6605 analyze_format_string::PositionContext p) override; 6606 6607 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6608 6609 void HandleNullChar(const char *nullCharacter) override; 6610 6611 template <typename Range> 6612 static void 6613 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6614 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6615 bool IsStringLocation, Range StringRange, 6616 ArrayRef<FixItHint> Fixit = None); 6617 6618 protected: 6619 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6620 const char *startSpec, 6621 unsigned specifierLen, 6622 const char *csStart, unsigned csLen); 6623 6624 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6625 const char *startSpec, 6626 unsigned specifierLen); 6627 6628 SourceRange getFormatStringRange(); 6629 CharSourceRange getSpecifierRange(const char *startSpecifier, 6630 unsigned specifierLen); 6631 SourceLocation getLocationOfByte(const char *x); 6632 6633 const Expr *getDataArg(unsigned i) const; 6634 6635 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6636 const analyze_format_string::ConversionSpecifier &CS, 6637 const char *startSpecifier, unsigned specifierLen, 6638 unsigned argIndex); 6639 6640 template <typename Range> 6641 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6642 bool IsStringLocation, Range StringRange, 6643 ArrayRef<FixItHint> Fixit = None); 6644 }; 6645 6646 } // namespace 6647 6648 SourceRange CheckFormatHandler::getFormatStringRange() { 6649 return OrigFormatExpr->getSourceRange(); 6650 } 6651 6652 CharSourceRange CheckFormatHandler:: 6653 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6654 SourceLocation Start = getLocationOfByte(startSpecifier); 6655 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6656 6657 // Advance the end SourceLocation by one due to half-open ranges. 6658 End = End.getLocWithOffset(1); 6659 6660 return CharSourceRange::getCharRange(Start, End); 6661 } 6662 6663 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6664 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6665 S.getLangOpts(), S.Context.getTargetInfo()); 6666 } 6667 6668 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6669 unsigned specifierLen){ 6670 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6671 getLocationOfByte(startSpecifier), 6672 /*IsStringLocation*/true, 6673 getSpecifierRange(startSpecifier, specifierLen)); 6674 } 6675 6676 void CheckFormatHandler::HandleInvalidLengthModifier( 6677 const analyze_format_string::FormatSpecifier &FS, 6678 const analyze_format_string::ConversionSpecifier &CS, 6679 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6680 using namespace analyze_format_string; 6681 6682 const LengthModifier &LM = FS.getLengthModifier(); 6683 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6684 6685 // See if we know how to fix this length modifier. 6686 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6687 if (FixedLM) { 6688 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6689 getLocationOfByte(LM.getStart()), 6690 /*IsStringLocation*/true, 6691 getSpecifierRange(startSpecifier, specifierLen)); 6692 6693 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6694 << FixedLM->toString() 6695 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6696 6697 } else { 6698 FixItHint Hint; 6699 if (DiagID == diag::warn_format_nonsensical_length) 6700 Hint = FixItHint::CreateRemoval(LMRange); 6701 6702 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6703 getLocationOfByte(LM.getStart()), 6704 /*IsStringLocation*/true, 6705 getSpecifierRange(startSpecifier, specifierLen), 6706 Hint); 6707 } 6708 } 6709 6710 void CheckFormatHandler::HandleNonStandardLengthModifier( 6711 const analyze_format_string::FormatSpecifier &FS, 6712 const char *startSpecifier, unsigned specifierLen) { 6713 using namespace analyze_format_string; 6714 6715 const LengthModifier &LM = FS.getLengthModifier(); 6716 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6717 6718 // See if we know how to fix this length modifier. 6719 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6720 if (FixedLM) { 6721 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6722 << LM.toString() << 0, 6723 getLocationOfByte(LM.getStart()), 6724 /*IsStringLocation*/true, 6725 getSpecifierRange(startSpecifier, specifierLen)); 6726 6727 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6728 << FixedLM->toString() 6729 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6730 6731 } else { 6732 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6733 << LM.toString() << 0, 6734 getLocationOfByte(LM.getStart()), 6735 /*IsStringLocation*/true, 6736 getSpecifierRange(startSpecifier, specifierLen)); 6737 } 6738 } 6739 6740 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6741 const analyze_format_string::ConversionSpecifier &CS, 6742 const char *startSpecifier, unsigned specifierLen) { 6743 using namespace analyze_format_string; 6744 6745 // See if we know how to fix this conversion specifier. 6746 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 6747 if (FixedCS) { 6748 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6749 << CS.toString() << /*conversion specifier*/1, 6750 getLocationOfByte(CS.getStart()), 6751 /*IsStringLocation*/true, 6752 getSpecifierRange(startSpecifier, specifierLen)); 6753 6754 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 6755 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 6756 << FixedCS->toString() 6757 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 6758 } else { 6759 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6760 << CS.toString() << /*conversion specifier*/1, 6761 getLocationOfByte(CS.getStart()), 6762 /*IsStringLocation*/true, 6763 getSpecifierRange(startSpecifier, specifierLen)); 6764 } 6765 } 6766 6767 void CheckFormatHandler::HandlePosition(const char *startPos, 6768 unsigned posLen) { 6769 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 6770 getLocationOfByte(startPos), 6771 /*IsStringLocation*/true, 6772 getSpecifierRange(startPos, posLen)); 6773 } 6774 6775 void 6776 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 6777 analyze_format_string::PositionContext p) { 6778 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 6779 << (unsigned) p, 6780 getLocationOfByte(startPos), /*IsStringLocation*/true, 6781 getSpecifierRange(startPos, posLen)); 6782 } 6783 6784 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 6785 unsigned posLen) { 6786 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 6787 getLocationOfByte(startPos), 6788 /*IsStringLocation*/true, 6789 getSpecifierRange(startPos, posLen)); 6790 } 6791 6792 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 6793 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 6794 // The presence of a null character is likely an error. 6795 EmitFormatDiagnostic( 6796 S.PDiag(diag::warn_printf_format_string_contains_null_char), 6797 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 6798 getFormatStringRange()); 6799 } 6800 } 6801 6802 // Note that this may return NULL if there was an error parsing or building 6803 // one of the argument expressions. 6804 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 6805 return Args[FirstDataArg + i]; 6806 } 6807 6808 void CheckFormatHandler::DoneProcessing() { 6809 // Does the number of data arguments exceed the number of 6810 // format conversions in the format string? 6811 if (!HasVAListArg) { 6812 // Find any arguments that weren't covered. 6813 CoveredArgs.flip(); 6814 signed notCoveredArg = CoveredArgs.find_first(); 6815 if (notCoveredArg >= 0) { 6816 assert((unsigned)notCoveredArg < NumDataArgs); 6817 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 6818 } else { 6819 UncoveredArg.setAllCovered(); 6820 } 6821 } 6822 } 6823 6824 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 6825 const Expr *ArgExpr) { 6826 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 6827 "Invalid state"); 6828 6829 if (!ArgExpr) 6830 return; 6831 6832 SourceLocation Loc = ArgExpr->getBeginLoc(); 6833 6834 if (S.getSourceManager().isInSystemMacro(Loc)) 6835 return; 6836 6837 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 6838 for (auto E : DiagnosticExprs) 6839 PDiag << E->getSourceRange(); 6840 6841 CheckFormatHandler::EmitFormatDiagnostic( 6842 S, IsFunctionCall, DiagnosticExprs[0], 6843 PDiag, Loc, /*IsStringLocation*/false, 6844 DiagnosticExprs[0]->getSourceRange()); 6845 } 6846 6847 bool 6848 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 6849 SourceLocation Loc, 6850 const char *startSpec, 6851 unsigned specifierLen, 6852 const char *csStart, 6853 unsigned csLen) { 6854 bool keepGoing = true; 6855 if (argIndex < NumDataArgs) { 6856 // Consider the argument coverered, even though the specifier doesn't 6857 // make sense. 6858 CoveredArgs.set(argIndex); 6859 } 6860 else { 6861 // If argIndex exceeds the number of data arguments we 6862 // don't issue a warning because that is just a cascade of warnings (and 6863 // they may have intended '%%' anyway). We don't want to continue processing 6864 // the format string after this point, however, as we will like just get 6865 // gibberish when trying to match arguments. 6866 keepGoing = false; 6867 } 6868 6869 StringRef Specifier(csStart, csLen); 6870 6871 // If the specifier in non-printable, it could be the first byte of a UTF-8 6872 // sequence. In that case, print the UTF-8 code point. If not, print the byte 6873 // hex value. 6874 std::string CodePointStr; 6875 if (!llvm::sys::locale::isPrint(*csStart)) { 6876 llvm::UTF32 CodePoint; 6877 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 6878 const llvm::UTF8 *E = 6879 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 6880 llvm::ConversionResult Result = 6881 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 6882 6883 if (Result != llvm::conversionOK) { 6884 unsigned char FirstChar = *csStart; 6885 CodePoint = (llvm::UTF32)FirstChar; 6886 } 6887 6888 llvm::raw_string_ostream OS(CodePointStr); 6889 if (CodePoint < 256) 6890 OS << "\\x" << llvm::format("%02x", CodePoint); 6891 else if (CodePoint <= 0xFFFF) 6892 OS << "\\u" << llvm::format("%04x", CodePoint); 6893 else 6894 OS << "\\U" << llvm::format("%08x", CodePoint); 6895 OS.flush(); 6896 Specifier = CodePointStr; 6897 } 6898 6899 EmitFormatDiagnostic( 6900 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 6901 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 6902 6903 return keepGoing; 6904 } 6905 6906 void 6907 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 6908 const char *startSpec, 6909 unsigned specifierLen) { 6910 EmitFormatDiagnostic( 6911 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 6912 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 6913 } 6914 6915 bool 6916 CheckFormatHandler::CheckNumArgs( 6917 const analyze_format_string::FormatSpecifier &FS, 6918 const analyze_format_string::ConversionSpecifier &CS, 6919 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 6920 6921 if (argIndex >= NumDataArgs) { 6922 PartialDiagnostic PDiag = FS.usesPositionalArg() 6923 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 6924 << (argIndex+1) << NumDataArgs) 6925 : S.PDiag(diag::warn_printf_insufficient_data_args); 6926 EmitFormatDiagnostic( 6927 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 6928 getSpecifierRange(startSpecifier, specifierLen)); 6929 6930 // Since more arguments than conversion tokens are given, by extension 6931 // all arguments are covered, so mark this as so. 6932 UncoveredArg.setAllCovered(); 6933 return false; 6934 } 6935 return true; 6936 } 6937 6938 template<typename Range> 6939 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 6940 SourceLocation Loc, 6941 bool IsStringLocation, 6942 Range StringRange, 6943 ArrayRef<FixItHint> FixIt) { 6944 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 6945 Loc, IsStringLocation, StringRange, FixIt); 6946 } 6947 6948 /// If the format string is not within the function call, emit a note 6949 /// so that the function call and string are in diagnostic messages. 6950 /// 6951 /// \param InFunctionCall if true, the format string is within the function 6952 /// call and only one diagnostic message will be produced. Otherwise, an 6953 /// extra note will be emitted pointing to location of the format string. 6954 /// 6955 /// \param ArgumentExpr the expression that is passed as the format string 6956 /// argument in the function call. Used for getting locations when two 6957 /// diagnostics are emitted. 6958 /// 6959 /// \param PDiag the callee should already have provided any strings for the 6960 /// diagnostic message. This function only adds locations and fixits 6961 /// to diagnostics. 6962 /// 6963 /// \param Loc primary location for diagnostic. If two diagnostics are 6964 /// required, one will be at Loc and a new SourceLocation will be created for 6965 /// the other one. 6966 /// 6967 /// \param IsStringLocation if true, Loc points to the format string should be 6968 /// used for the note. Otherwise, Loc points to the argument list and will 6969 /// be used with PDiag. 6970 /// 6971 /// \param StringRange some or all of the string to highlight. This is 6972 /// templated so it can accept either a CharSourceRange or a SourceRange. 6973 /// 6974 /// \param FixIt optional fix it hint for the format string. 6975 template <typename Range> 6976 void CheckFormatHandler::EmitFormatDiagnostic( 6977 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 6978 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 6979 Range StringRange, ArrayRef<FixItHint> FixIt) { 6980 if (InFunctionCall) { 6981 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 6982 D << StringRange; 6983 D << FixIt; 6984 } else { 6985 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 6986 << ArgumentExpr->getSourceRange(); 6987 6988 const Sema::SemaDiagnosticBuilder &Note = 6989 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 6990 diag::note_format_string_defined); 6991 6992 Note << StringRange; 6993 Note << FixIt; 6994 } 6995 } 6996 6997 //===--- CHECK: Printf format string checking ------------------------------===// 6998 6999 namespace { 7000 7001 class CheckPrintfHandler : public CheckFormatHandler { 7002 public: 7003 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7004 const Expr *origFormatExpr, 7005 const Sema::FormatStringType type, unsigned firstDataArg, 7006 unsigned numDataArgs, bool isObjC, const char *beg, 7007 bool hasVAListArg, ArrayRef<const Expr *> Args, 7008 unsigned formatIdx, bool inFunctionCall, 7009 Sema::VariadicCallType CallType, 7010 llvm::SmallBitVector &CheckedVarArgs, 7011 UncoveredArgHandler &UncoveredArg) 7012 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7013 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7014 inFunctionCall, CallType, CheckedVarArgs, 7015 UncoveredArg) {} 7016 7017 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7018 7019 /// Returns true if '%@' specifiers are allowed in the format string. 7020 bool allowsObjCArg() const { 7021 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7022 FSType == Sema::FST_OSTrace; 7023 } 7024 7025 bool HandleInvalidPrintfConversionSpecifier( 7026 const analyze_printf::PrintfSpecifier &FS, 7027 const char *startSpecifier, 7028 unsigned specifierLen) override; 7029 7030 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7031 const char *startSpecifier, 7032 unsigned specifierLen) override; 7033 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7034 const char *StartSpecifier, 7035 unsigned SpecifierLen, 7036 const Expr *E); 7037 7038 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7039 const char *startSpecifier, unsigned specifierLen); 7040 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7041 const analyze_printf::OptionalAmount &Amt, 7042 unsigned type, 7043 const char *startSpecifier, unsigned specifierLen); 7044 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7045 const analyze_printf::OptionalFlag &flag, 7046 const char *startSpecifier, unsigned specifierLen); 7047 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7048 const analyze_printf::OptionalFlag &ignoredFlag, 7049 const analyze_printf::OptionalFlag &flag, 7050 const char *startSpecifier, unsigned specifierLen); 7051 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7052 const Expr *E); 7053 7054 void HandleEmptyObjCModifierFlag(const char *startFlag, 7055 unsigned flagLen) override; 7056 7057 void HandleInvalidObjCModifierFlag(const char *startFlag, 7058 unsigned flagLen) override; 7059 7060 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7061 const char *flagsEnd, 7062 const char *conversionPosition) 7063 override; 7064 }; 7065 7066 } // namespace 7067 7068 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7069 const analyze_printf::PrintfSpecifier &FS, 7070 const char *startSpecifier, 7071 unsigned specifierLen) { 7072 const analyze_printf::PrintfConversionSpecifier &CS = 7073 FS.getConversionSpecifier(); 7074 7075 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7076 getLocationOfByte(CS.getStart()), 7077 startSpecifier, specifierLen, 7078 CS.getStart(), CS.getLength()); 7079 } 7080 7081 bool CheckPrintfHandler::HandleAmount( 7082 const analyze_format_string::OptionalAmount &Amt, 7083 unsigned k, const char *startSpecifier, 7084 unsigned specifierLen) { 7085 if (Amt.hasDataArgument()) { 7086 if (!HasVAListArg) { 7087 unsigned argIndex = Amt.getArgIndex(); 7088 if (argIndex >= NumDataArgs) { 7089 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7090 << k, 7091 getLocationOfByte(Amt.getStart()), 7092 /*IsStringLocation*/true, 7093 getSpecifierRange(startSpecifier, specifierLen)); 7094 // Don't do any more checking. We will just emit 7095 // spurious errors. 7096 return false; 7097 } 7098 7099 // Type check the data argument. It should be an 'int'. 7100 // Although not in conformance with C99, we also allow the argument to be 7101 // an 'unsigned int' as that is a reasonably safe case. GCC also 7102 // doesn't emit a warning for that case. 7103 CoveredArgs.set(argIndex); 7104 const Expr *Arg = getDataArg(argIndex); 7105 if (!Arg) 7106 return false; 7107 7108 QualType T = Arg->getType(); 7109 7110 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7111 assert(AT.isValid()); 7112 7113 if (!AT.matchesType(S.Context, T)) { 7114 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7115 << k << AT.getRepresentativeTypeName(S.Context) 7116 << T << Arg->getSourceRange(), 7117 getLocationOfByte(Amt.getStart()), 7118 /*IsStringLocation*/true, 7119 getSpecifierRange(startSpecifier, specifierLen)); 7120 // Don't do any more checking. We will just emit 7121 // spurious errors. 7122 return false; 7123 } 7124 } 7125 } 7126 return true; 7127 } 7128 7129 void CheckPrintfHandler::HandleInvalidAmount( 7130 const analyze_printf::PrintfSpecifier &FS, 7131 const analyze_printf::OptionalAmount &Amt, 7132 unsigned type, 7133 const char *startSpecifier, 7134 unsigned specifierLen) { 7135 const analyze_printf::PrintfConversionSpecifier &CS = 7136 FS.getConversionSpecifier(); 7137 7138 FixItHint fixit = 7139 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7140 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7141 Amt.getConstantLength())) 7142 : FixItHint(); 7143 7144 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7145 << type << CS.toString(), 7146 getLocationOfByte(Amt.getStart()), 7147 /*IsStringLocation*/true, 7148 getSpecifierRange(startSpecifier, specifierLen), 7149 fixit); 7150 } 7151 7152 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7153 const analyze_printf::OptionalFlag &flag, 7154 const char *startSpecifier, 7155 unsigned specifierLen) { 7156 // Warn about pointless flag with a fixit removal. 7157 const analyze_printf::PrintfConversionSpecifier &CS = 7158 FS.getConversionSpecifier(); 7159 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7160 << flag.toString() << CS.toString(), 7161 getLocationOfByte(flag.getPosition()), 7162 /*IsStringLocation*/true, 7163 getSpecifierRange(startSpecifier, specifierLen), 7164 FixItHint::CreateRemoval( 7165 getSpecifierRange(flag.getPosition(), 1))); 7166 } 7167 7168 void CheckPrintfHandler::HandleIgnoredFlag( 7169 const analyze_printf::PrintfSpecifier &FS, 7170 const analyze_printf::OptionalFlag &ignoredFlag, 7171 const analyze_printf::OptionalFlag &flag, 7172 const char *startSpecifier, 7173 unsigned specifierLen) { 7174 // Warn about ignored flag with a fixit removal. 7175 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7176 << ignoredFlag.toString() << flag.toString(), 7177 getLocationOfByte(ignoredFlag.getPosition()), 7178 /*IsStringLocation*/true, 7179 getSpecifierRange(startSpecifier, specifierLen), 7180 FixItHint::CreateRemoval( 7181 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7182 } 7183 7184 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7185 unsigned flagLen) { 7186 // Warn about an empty flag. 7187 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7188 getLocationOfByte(startFlag), 7189 /*IsStringLocation*/true, 7190 getSpecifierRange(startFlag, flagLen)); 7191 } 7192 7193 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7194 unsigned flagLen) { 7195 // Warn about an invalid flag. 7196 auto Range = getSpecifierRange(startFlag, flagLen); 7197 StringRef flag(startFlag, flagLen); 7198 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7199 getLocationOfByte(startFlag), 7200 /*IsStringLocation*/true, 7201 Range, FixItHint::CreateRemoval(Range)); 7202 } 7203 7204 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7205 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7206 // Warn about using '[...]' without a '@' conversion. 7207 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7208 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7209 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7210 getLocationOfByte(conversionPosition), 7211 /*IsStringLocation*/true, 7212 Range, FixItHint::CreateRemoval(Range)); 7213 } 7214 7215 // Determines if the specified is a C++ class or struct containing 7216 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7217 // "c_str()"). 7218 template<typename MemberKind> 7219 static llvm::SmallPtrSet<MemberKind*, 1> 7220 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7221 const RecordType *RT = Ty->getAs<RecordType>(); 7222 llvm::SmallPtrSet<MemberKind*, 1> Results; 7223 7224 if (!RT) 7225 return Results; 7226 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7227 if (!RD || !RD->getDefinition()) 7228 return Results; 7229 7230 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7231 Sema::LookupMemberName); 7232 R.suppressDiagnostics(); 7233 7234 // We just need to include all members of the right kind turned up by the 7235 // filter, at this point. 7236 if (S.LookupQualifiedName(R, RT->getDecl())) 7237 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7238 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7239 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7240 Results.insert(FK); 7241 } 7242 return Results; 7243 } 7244 7245 /// Check if we could call '.c_str()' on an object. 7246 /// 7247 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7248 /// allow the call, or if it would be ambiguous). 7249 bool Sema::hasCStrMethod(const Expr *E) { 7250 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7251 7252 MethodSet Results = 7253 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7254 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7255 MI != ME; ++MI) 7256 if ((*MI)->getMinRequiredArguments() == 0) 7257 return true; 7258 return false; 7259 } 7260 7261 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7262 // better diagnostic if so. AT is assumed to be valid. 7263 // Returns true when a c_str() conversion method is found. 7264 bool CheckPrintfHandler::checkForCStrMembers( 7265 const analyze_printf::ArgType &AT, const Expr *E) { 7266 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7267 7268 MethodSet Results = 7269 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7270 7271 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7272 MI != ME; ++MI) { 7273 const CXXMethodDecl *Method = *MI; 7274 if (Method->getMinRequiredArguments() == 0 && 7275 AT.matchesType(S.Context, Method->getReturnType())) { 7276 // FIXME: Suggest parens if the expression needs them. 7277 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7278 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7279 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7280 return true; 7281 } 7282 } 7283 7284 return false; 7285 } 7286 7287 bool 7288 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7289 &FS, 7290 const char *startSpecifier, 7291 unsigned specifierLen) { 7292 using namespace analyze_format_string; 7293 using namespace analyze_printf; 7294 7295 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7296 7297 if (FS.consumesDataArgument()) { 7298 if (atFirstArg) { 7299 atFirstArg = false; 7300 usesPositionalArgs = FS.usesPositionalArg(); 7301 } 7302 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7303 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7304 startSpecifier, specifierLen); 7305 return false; 7306 } 7307 } 7308 7309 // First check if the field width, precision, and conversion specifier 7310 // have matching data arguments. 7311 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7312 startSpecifier, specifierLen)) { 7313 return false; 7314 } 7315 7316 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7317 startSpecifier, specifierLen)) { 7318 return false; 7319 } 7320 7321 if (!CS.consumesDataArgument()) { 7322 // FIXME: Technically specifying a precision or field width here 7323 // makes no sense. Worth issuing a warning at some point. 7324 return true; 7325 } 7326 7327 // Consume the argument. 7328 unsigned argIndex = FS.getArgIndex(); 7329 if (argIndex < NumDataArgs) { 7330 // The check to see if the argIndex is valid will come later. 7331 // We set the bit here because we may exit early from this 7332 // function if we encounter some other error. 7333 CoveredArgs.set(argIndex); 7334 } 7335 7336 // FreeBSD kernel extensions. 7337 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7338 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7339 // We need at least two arguments. 7340 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7341 return false; 7342 7343 // Claim the second argument. 7344 CoveredArgs.set(argIndex + 1); 7345 7346 // Type check the first argument (int for %b, pointer for %D) 7347 const Expr *Ex = getDataArg(argIndex); 7348 const analyze_printf::ArgType &AT = 7349 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7350 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7351 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7352 EmitFormatDiagnostic( 7353 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7354 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7355 << false << Ex->getSourceRange(), 7356 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7357 getSpecifierRange(startSpecifier, specifierLen)); 7358 7359 // Type check the second argument (char * for both %b and %D) 7360 Ex = getDataArg(argIndex + 1); 7361 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7362 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7363 EmitFormatDiagnostic( 7364 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7365 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7366 << false << Ex->getSourceRange(), 7367 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7368 getSpecifierRange(startSpecifier, specifierLen)); 7369 7370 return true; 7371 } 7372 7373 // Check for using an Objective-C specific conversion specifier 7374 // in a non-ObjC literal. 7375 if (!allowsObjCArg() && CS.isObjCArg()) { 7376 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7377 specifierLen); 7378 } 7379 7380 // %P can only be used with os_log. 7381 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7382 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7383 specifierLen); 7384 } 7385 7386 // %n is not allowed with os_log. 7387 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7388 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7389 getLocationOfByte(CS.getStart()), 7390 /*IsStringLocation*/ false, 7391 getSpecifierRange(startSpecifier, specifierLen)); 7392 7393 return true; 7394 } 7395 7396 // Only scalars are allowed for os_trace. 7397 if (FSType == Sema::FST_OSTrace && 7398 (CS.getKind() == ConversionSpecifier::PArg || 7399 CS.getKind() == ConversionSpecifier::sArg || 7400 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7401 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7402 specifierLen); 7403 } 7404 7405 // Check for use of public/private annotation outside of os_log(). 7406 if (FSType != Sema::FST_OSLog) { 7407 if (FS.isPublic().isSet()) { 7408 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7409 << "public", 7410 getLocationOfByte(FS.isPublic().getPosition()), 7411 /*IsStringLocation*/ false, 7412 getSpecifierRange(startSpecifier, specifierLen)); 7413 } 7414 if (FS.isPrivate().isSet()) { 7415 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7416 << "private", 7417 getLocationOfByte(FS.isPrivate().getPosition()), 7418 /*IsStringLocation*/ false, 7419 getSpecifierRange(startSpecifier, specifierLen)); 7420 } 7421 } 7422 7423 // Check for invalid use of field width 7424 if (!FS.hasValidFieldWidth()) { 7425 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7426 startSpecifier, specifierLen); 7427 } 7428 7429 // Check for invalid use of precision 7430 if (!FS.hasValidPrecision()) { 7431 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7432 startSpecifier, specifierLen); 7433 } 7434 7435 // Precision is mandatory for %P specifier. 7436 if (CS.getKind() == ConversionSpecifier::PArg && 7437 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7438 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7439 getLocationOfByte(startSpecifier), 7440 /*IsStringLocation*/ false, 7441 getSpecifierRange(startSpecifier, specifierLen)); 7442 } 7443 7444 // Check each flag does not conflict with any other component. 7445 if (!FS.hasValidThousandsGroupingPrefix()) 7446 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7447 if (!FS.hasValidLeadingZeros()) 7448 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7449 if (!FS.hasValidPlusPrefix()) 7450 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7451 if (!FS.hasValidSpacePrefix()) 7452 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7453 if (!FS.hasValidAlternativeForm()) 7454 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7455 if (!FS.hasValidLeftJustified()) 7456 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7457 7458 // Check that flags are not ignored by another flag 7459 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7460 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7461 startSpecifier, specifierLen); 7462 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7463 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7464 startSpecifier, specifierLen); 7465 7466 // Check the length modifier is valid with the given conversion specifier. 7467 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7468 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7469 diag::warn_format_nonsensical_length); 7470 else if (!FS.hasStandardLengthModifier()) 7471 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7472 else if (!FS.hasStandardLengthConversionCombination()) 7473 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7474 diag::warn_format_non_standard_conversion_spec); 7475 7476 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7477 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7478 7479 // The remaining checks depend on the data arguments. 7480 if (HasVAListArg) 7481 return true; 7482 7483 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7484 return false; 7485 7486 const Expr *Arg = getDataArg(argIndex); 7487 if (!Arg) 7488 return true; 7489 7490 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7491 } 7492 7493 static bool requiresParensToAddCast(const Expr *E) { 7494 // FIXME: We should have a general way to reason about operator 7495 // precedence and whether parens are actually needed here. 7496 // Take care of a few common cases where they aren't. 7497 const Expr *Inside = E->IgnoreImpCasts(); 7498 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7499 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7500 7501 switch (Inside->getStmtClass()) { 7502 case Stmt::ArraySubscriptExprClass: 7503 case Stmt::CallExprClass: 7504 case Stmt::CharacterLiteralClass: 7505 case Stmt::CXXBoolLiteralExprClass: 7506 case Stmt::DeclRefExprClass: 7507 case Stmt::FloatingLiteralClass: 7508 case Stmt::IntegerLiteralClass: 7509 case Stmt::MemberExprClass: 7510 case Stmt::ObjCArrayLiteralClass: 7511 case Stmt::ObjCBoolLiteralExprClass: 7512 case Stmt::ObjCBoxedExprClass: 7513 case Stmt::ObjCDictionaryLiteralClass: 7514 case Stmt::ObjCEncodeExprClass: 7515 case Stmt::ObjCIvarRefExprClass: 7516 case Stmt::ObjCMessageExprClass: 7517 case Stmt::ObjCPropertyRefExprClass: 7518 case Stmt::ObjCStringLiteralClass: 7519 case Stmt::ObjCSubscriptRefExprClass: 7520 case Stmt::ParenExprClass: 7521 case Stmt::StringLiteralClass: 7522 case Stmt::UnaryOperatorClass: 7523 return false; 7524 default: 7525 return true; 7526 } 7527 } 7528 7529 static std::pair<QualType, StringRef> 7530 shouldNotPrintDirectly(const ASTContext &Context, 7531 QualType IntendedTy, 7532 const Expr *E) { 7533 // Use a 'while' to peel off layers of typedefs. 7534 QualType TyTy = IntendedTy; 7535 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7536 StringRef Name = UserTy->getDecl()->getName(); 7537 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7538 .Case("CFIndex", Context.getNSIntegerType()) 7539 .Case("NSInteger", Context.getNSIntegerType()) 7540 .Case("NSUInteger", Context.getNSUIntegerType()) 7541 .Case("SInt32", Context.IntTy) 7542 .Case("UInt32", Context.UnsignedIntTy) 7543 .Default(QualType()); 7544 7545 if (!CastTy.isNull()) 7546 return std::make_pair(CastTy, Name); 7547 7548 TyTy = UserTy->desugar(); 7549 } 7550 7551 // Strip parens if necessary. 7552 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7553 return shouldNotPrintDirectly(Context, 7554 PE->getSubExpr()->getType(), 7555 PE->getSubExpr()); 7556 7557 // If this is a conditional expression, then its result type is constructed 7558 // via usual arithmetic conversions and thus there might be no necessary 7559 // typedef sugar there. Recurse to operands to check for NSInteger & 7560 // Co. usage condition. 7561 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7562 QualType TrueTy, FalseTy; 7563 StringRef TrueName, FalseName; 7564 7565 std::tie(TrueTy, TrueName) = 7566 shouldNotPrintDirectly(Context, 7567 CO->getTrueExpr()->getType(), 7568 CO->getTrueExpr()); 7569 std::tie(FalseTy, FalseName) = 7570 shouldNotPrintDirectly(Context, 7571 CO->getFalseExpr()->getType(), 7572 CO->getFalseExpr()); 7573 7574 if (TrueTy == FalseTy) 7575 return std::make_pair(TrueTy, TrueName); 7576 else if (TrueTy.isNull()) 7577 return std::make_pair(FalseTy, FalseName); 7578 else if (FalseTy.isNull()) 7579 return std::make_pair(TrueTy, TrueName); 7580 } 7581 7582 return std::make_pair(QualType(), StringRef()); 7583 } 7584 7585 bool 7586 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7587 const char *StartSpecifier, 7588 unsigned SpecifierLen, 7589 const Expr *E) { 7590 using namespace analyze_format_string; 7591 using namespace analyze_printf; 7592 7593 // Now type check the data expression that matches the 7594 // format specifier. 7595 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7596 if (!AT.isValid()) 7597 return true; 7598 7599 QualType ExprTy = E->getType(); 7600 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7601 ExprTy = TET->getUnderlyingExpr()->getType(); 7602 } 7603 7604 const analyze_printf::ArgType::MatchKind Match = 7605 AT.matchesType(S.Context, ExprTy); 7606 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 7607 if (Match == analyze_printf::ArgType::Match) 7608 return true; 7609 7610 // Look through argument promotions for our error message's reported type. 7611 // This includes the integral and floating promotions, but excludes array 7612 // and function pointer decay; seeing that an argument intended to be a 7613 // string has type 'char [6]' is probably more confusing than 'char *'. 7614 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7615 if (ICE->getCastKind() == CK_IntegralCast || 7616 ICE->getCastKind() == CK_FloatingCast) { 7617 E = ICE->getSubExpr(); 7618 ExprTy = E->getType(); 7619 7620 // Check if we didn't match because of an implicit cast from a 'char' 7621 // or 'short' to an 'int'. This is done because printf is a varargs 7622 // function. 7623 if (ICE->getType() == S.Context.IntTy || 7624 ICE->getType() == S.Context.UnsignedIntTy) { 7625 // All further checking is done on the subexpression. 7626 if (AT.matchesType(S.Context, ExprTy)) 7627 return true; 7628 } 7629 } 7630 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7631 // Special case for 'a', which has type 'int' in C. 7632 // Note, however, that we do /not/ want to treat multibyte constants like 7633 // 'MooV' as characters! This form is deprecated but still exists. 7634 if (ExprTy == S.Context.IntTy) 7635 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 7636 ExprTy = S.Context.CharTy; 7637 } 7638 7639 // Look through enums to their underlying type. 7640 bool IsEnum = false; 7641 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7642 ExprTy = EnumTy->getDecl()->getIntegerType(); 7643 IsEnum = true; 7644 } 7645 7646 // %C in an Objective-C context prints a unichar, not a wchar_t. 7647 // If the argument is an integer of some kind, believe the %C and suggest 7648 // a cast instead of changing the conversion specifier. 7649 QualType IntendedTy = ExprTy; 7650 if (isObjCContext() && 7651 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7652 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7653 !ExprTy->isCharType()) { 7654 // 'unichar' is defined as a typedef of unsigned short, but we should 7655 // prefer using the typedef if it is visible. 7656 IntendedTy = S.Context.UnsignedShortTy; 7657 7658 // While we are here, check if the value is an IntegerLiteral that happens 7659 // to be within the valid range. 7660 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7661 const llvm::APInt &V = IL->getValue(); 7662 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7663 return true; 7664 } 7665 7666 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7667 Sema::LookupOrdinaryName); 7668 if (S.LookupName(Result, S.getCurScope())) { 7669 NamedDecl *ND = Result.getFoundDecl(); 7670 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7671 if (TD->getUnderlyingType() == IntendedTy) 7672 IntendedTy = S.Context.getTypedefType(TD); 7673 } 7674 } 7675 } 7676 7677 // Special-case some of Darwin's platform-independence types by suggesting 7678 // casts to primitive types that are known to be large enough. 7679 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7680 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7681 QualType CastTy; 7682 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7683 if (!CastTy.isNull()) { 7684 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7685 // (long in ASTContext). Only complain to pedants. 7686 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7687 (AT.isSizeT() || AT.isPtrdiffT()) && 7688 AT.matchesType(S.Context, CastTy)) 7689 Pedantic = true; 7690 IntendedTy = CastTy; 7691 ShouldNotPrintDirectly = true; 7692 } 7693 } 7694 7695 // We may be able to offer a FixItHint if it is a supported type. 7696 PrintfSpecifier fixedFS = FS; 7697 bool Success = 7698 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7699 7700 if (Success) { 7701 // Get the fix string from the fixed format specifier 7702 SmallString<16> buf; 7703 llvm::raw_svector_ostream os(buf); 7704 fixedFS.toString(os); 7705 7706 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 7707 7708 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 7709 unsigned Diag = 7710 Pedantic 7711 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7712 : diag::warn_format_conversion_argument_type_mismatch; 7713 // In this case, the specifier is wrong and should be changed to match 7714 // the argument. 7715 EmitFormatDiagnostic(S.PDiag(Diag) 7716 << AT.getRepresentativeTypeName(S.Context) 7717 << IntendedTy << IsEnum << E->getSourceRange(), 7718 E->getBeginLoc(), 7719 /*IsStringLocation*/ false, SpecRange, 7720 FixItHint::CreateReplacement(SpecRange, os.str())); 7721 } else { 7722 // The canonical type for formatting this value is different from the 7723 // actual type of the expression. (This occurs, for example, with Darwin's 7724 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 7725 // should be printed as 'long' for 64-bit compatibility.) 7726 // Rather than emitting a normal format/argument mismatch, we want to 7727 // add a cast to the recommended type (and correct the format string 7728 // if necessary). 7729 SmallString<16> CastBuf; 7730 llvm::raw_svector_ostream CastFix(CastBuf); 7731 CastFix << "("; 7732 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 7733 CastFix << ")"; 7734 7735 SmallVector<FixItHint,4> Hints; 7736 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 7737 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 7738 7739 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 7740 // If there's already a cast present, just replace it. 7741 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 7742 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 7743 7744 } else if (!requiresParensToAddCast(E)) { 7745 // If the expression has high enough precedence, 7746 // just write the C-style cast. 7747 Hints.push_back( 7748 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7749 } else { 7750 // Otherwise, add parens around the expression as well as the cast. 7751 CastFix << "("; 7752 Hints.push_back( 7753 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7754 7755 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 7756 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 7757 } 7758 7759 if (ShouldNotPrintDirectly) { 7760 // The expression has a type that should not be printed directly. 7761 // We extract the name from the typedef because we don't want to show 7762 // the underlying type in the diagnostic. 7763 StringRef Name; 7764 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 7765 Name = TypedefTy->getDecl()->getName(); 7766 else 7767 Name = CastTyName; 7768 unsigned Diag = Pedantic 7769 ? diag::warn_format_argument_needs_cast_pedantic 7770 : diag::warn_format_argument_needs_cast; 7771 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 7772 << E->getSourceRange(), 7773 E->getBeginLoc(), /*IsStringLocation=*/false, 7774 SpecRange, Hints); 7775 } else { 7776 // In this case, the expression could be printed using a different 7777 // specifier, but we've decided that the specifier is probably correct 7778 // and we should cast instead. Just use the normal warning message. 7779 EmitFormatDiagnostic( 7780 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7781 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 7782 << E->getSourceRange(), 7783 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 7784 } 7785 } 7786 } else { 7787 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 7788 SpecifierLen); 7789 // Since the warning for passing non-POD types to variadic functions 7790 // was deferred until now, we emit a warning for non-POD 7791 // arguments here. 7792 switch (S.isValidVarArgType(ExprTy)) { 7793 case Sema::VAK_Valid: 7794 case Sema::VAK_ValidInCXX11: { 7795 unsigned Diag = 7796 Pedantic 7797 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7798 : diag::warn_format_conversion_argument_type_mismatch; 7799 7800 EmitFormatDiagnostic( 7801 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 7802 << IsEnum << CSR << E->getSourceRange(), 7803 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7804 break; 7805 } 7806 case Sema::VAK_Undefined: 7807 case Sema::VAK_MSVCUndefined: 7808 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 7809 << S.getLangOpts().CPlusPlus11 << ExprTy 7810 << CallType 7811 << AT.getRepresentativeTypeName(S.Context) << CSR 7812 << E->getSourceRange(), 7813 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7814 checkForCStrMembers(AT, E); 7815 break; 7816 7817 case Sema::VAK_Invalid: 7818 if (ExprTy->isObjCObjectType()) 7819 EmitFormatDiagnostic( 7820 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 7821 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 7822 << AT.getRepresentativeTypeName(S.Context) << CSR 7823 << E->getSourceRange(), 7824 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7825 else 7826 // FIXME: If this is an initializer list, suggest removing the braces 7827 // or inserting a cast to the target type. 7828 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 7829 << isa<InitListExpr>(E) << ExprTy << CallType 7830 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 7831 break; 7832 } 7833 7834 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 7835 "format string specifier index out of range"); 7836 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 7837 } 7838 7839 return true; 7840 } 7841 7842 //===--- CHECK: Scanf format string checking ------------------------------===// 7843 7844 namespace { 7845 7846 class CheckScanfHandler : public CheckFormatHandler { 7847 public: 7848 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 7849 const Expr *origFormatExpr, Sema::FormatStringType type, 7850 unsigned firstDataArg, unsigned numDataArgs, 7851 const char *beg, bool hasVAListArg, 7852 ArrayRef<const Expr *> Args, unsigned formatIdx, 7853 bool inFunctionCall, Sema::VariadicCallType CallType, 7854 llvm::SmallBitVector &CheckedVarArgs, 7855 UncoveredArgHandler &UncoveredArg) 7856 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7857 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7858 inFunctionCall, CallType, CheckedVarArgs, 7859 UncoveredArg) {} 7860 7861 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 7862 const char *startSpecifier, 7863 unsigned specifierLen) override; 7864 7865 bool HandleInvalidScanfConversionSpecifier( 7866 const analyze_scanf::ScanfSpecifier &FS, 7867 const char *startSpecifier, 7868 unsigned specifierLen) override; 7869 7870 void HandleIncompleteScanList(const char *start, const char *end) override; 7871 }; 7872 7873 } // namespace 7874 7875 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 7876 const char *end) { 7877 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 7878 getLocationOfByte(end), /*IsStringLocation*/true, 7879 getSpecifierRange(start, end - start)); 7880 } 7881 7882 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 7883 const analyze_scanf::ScanfSpecifier &FS, 7884 const char *startSpecifier, 7885 unsigned specifierLen) { 7886 const analyze_scanf::ScanfConversionSpecifier &CS = 7887 FS.getConversionSpecifier(); 7888 7889 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7890 getLocationOfByte(CS.getStart()), 7891 startSpecifier, specifierLen, 7892 CS.getStart(), CS.getLength()); 7893 } 7894 7895 bool CheckScanfHandler::HandleScanfSpecifier( 7896 const analyze_scanf::ScanfSpecifier &FS, 7897 const char *startSpecifier, 7898 unsigned specifierLen) { 7899 using namespace analyze_scanf; 7900 using namespace analyze_format_string; 7901 7902 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 7903 7904 // Handle case where '%' and '*' don't consume an argument. These shouldn't 7905 // be used to decide if we are using positional arguments consistently. 7906 if (FS.consumesDataArgument()) { 7907 if (atFirstArg) { 7908 atFirstArg = false; 7909 usesPositionalArgs = FS.usesPositionalArg(); 7910 } 7911 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7912 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7913 startSpecifier, specifierLen); 7914 return false; 7915 } 7916 } 7917 7918 // Check if the field with is non-zero. 7919 const OptionalAmount &Amt = FS.getFieldWidth(); 7920 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 7921 if (Amt.getConstantAmount() == 0) { 7922 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 7923 Amt.getConstantLength()); 7924 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 7925 getLocationOfByte(Amt.getStart()), 7926 /*IsStringLocation*/true, R, 7927 FixItHint::CreateRemoval(R)); 7928 } 7929 } 7930 7931 if (!FS.consumesDataArgument()) { 7932 // FIXME: Technically specifying a precision or field width here 7933 // makes no sense. Worth issuing a warning at some point. 7934 return true; 7935 } 7936 7937 // Consume the argument. 7938 unsigned argIndex = FS.getArgIndex(); 7939 if (argIndex < NumDataArgs) { 7940 // The check to see if the argIndex is valid will come later. 7941 // We set the bit here because we may exit early from this 7942 // function if we encounter some other error. 7943 CoveredArgs.set(argIndex); 7944 } 7945 7946 // Check the length modifier is valid with the given conversion specifier. 7947 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7948 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7949 diag::warn_format_nonsensical_length); 7950 else if (!FS.hasStandardLengthModifier()) 7951 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7952 else if (!FS.hasStandardLengthConversionCombination()) 7953 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7954 diag::warn_format_non_standard_conversion_spec); 7955 7956 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7957 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7958 7959 // The remaining checks depend on the data arguments. 7960 if (HasVAListArg) 7961 return true; 7962 7963 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7964 return false; 7965 7966 // Check that the argument type matches the format specifier. 7967 const Expr *Ex = getDataArg(argIndex); 7968 if (!Ex) 7969 return true; 7970 7971 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 7972 7973 if (!AT.isValid()) { 7974 return true; 7975 } 7976 7977 analyze_format_string::ArgType::MatchKind Match = 7978 AT.matchesType(S.Context, Ex->getType()); 7979 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 7980 if (Match == analyze_format_string::ArgType::Match) 7981 return true; 7982 7983 ScanfSpecifier fixedFS = FS; 7984 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 7985 S.getLangOpts(), S.Context); 7986 7987 unsigned Diag = 7988 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7989 : diag::warn_format_conversion_argument_type_mismatch; 7990 7991 if (Success) { 7992 // Get the fix string from the fixed format specifier. 7993 SmallString<128> buf; 7994 llvm::raw_svector_ostream os(buf); 7995 fixedFS.toString(os); 7996 7997 EmitFormatDiagnostic( 7998 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 7999 << Ex->getType() << false << Ex->getSourceRange(), 8000 Ex->getBeginLoc(), 8001 /*IsStringLocation*/ false, 8002 getSpecifierRange(startSpecifier, specifierLen), 8003 FixItHint::CreateReplacement( 8004 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8005 } else { 8006 EmitFormatDiagnostic(S.PDiag(Diag) 8007 << AT.getRepresentativeTypeName(S.Context) 8008 << Ex->getType() << false << Ex->getSourceRange(), 8009 Ex->getBeginLoc(), 8010 /*IsStringLocation*/ false, 8011 getSpecifierRange(startSpecifier, specifierLen)); 8012 } 8013 8014 return true; 8015 } 8016 8017 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8018 const Expr *OrigFormatExpr, 8019 ArrayRef<const Expr *> Args, 8020 bool HasVAListArg, unsigned format_idx, 8021 unsigned firstDataArg, 8022 Sema::FormatStringType Type, 8023 bool inFunctionCall, 8024 Sema::VariadicCallType CallType, 8025 llvm::SmallBitVector &CheckedVarArgs, 8026 UncoveredArgHandler &UncoveredArg) { 8027 // CHECK: is the format string a wide literal? 8028 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8029 CheckFormatHandler::EmitFormatDiagnostic( 8030 S, inFunctionCall, Args[format_idx], 8031 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8032 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8033 return; 8034 } 8035 8036 // Str - The format string. NOTE: this is NOT null-terminated! 8037 StringRef StrRef = FExpr->getString(); 8038 const char *Str = StrRef.data(); 8039 // Account for cases where the string literal is truncated in a declaration. 8040 const ConstantArrayType *T = 8041 S.Context.getAsConstantArrayType(FExpr->getType()); 8042 assert(T && "String literal not of constant array type!"); 8043 size_t TypeSize = T->getSize().getZExtValue(); 8044 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8045 const unsigned numDataArgs = Args.size() - firstDataArg; 8046 8047 // Emit a warning if the string literal is truncated and does not contain an 8048 // embedded null character. 8049 if (TypeSize <= StrRef.size() && 8050 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8051 CheckFormatHandler::EmitFormatDiagnostic( 8052 S, inFunctionCall, Args[format_idx], 8053 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8054 FExpr->getBeginLoc(), 8055 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8056 return; 8057 } 8058 8059 // CHECK: empty format string? 8060 if (StrLen == 0 && numDataArgs > 0) { 8061 CheckFormatHandler::EmitFormatDiagnostic( 8062 S, inFunctionCall, Args[format_idx], 8063 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8064 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8065 return; 8066 } 8067 8068 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8069 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8070 Type == Sema::FST_OSTrace) { 8071 CheckPrintfHandler H( 8072 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8073 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8074 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8075 CheckedVarArgs, UncoveredArg); 8076 8077 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8078 S.getLangOpts(), 8079 S.Context.getTargetInfo(), 8080 Type == Sema::FST_FreeBSDKPrintf)) 8081 H.DoneProcessing(); 8082 } else if (Type == Sema::FST_Scanf) { 8083 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8084 numDataArgs, Str, HasVAListArg, Args, format_idx, 8085 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8086 8087 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8088 S.getLangOpts(), 8089 S.Context.getTargetInfo())) 8090 H.DoneProcessing(); 8091 } // TODO: handle other formats 8092 } 8093 8094 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8095 // Str - The format string. NOTE: this is NOT null-terminated! 8096 StringRef StrRef = FExpr->getString(); 8097 const char *Str = StrRef.data(); 8098 // Account for cases where the string literal is truncated in a declaration. 8099 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8100 assert(T && "String literal not of constant array type!"); 8101 size_t TypeSize = T->getSize().getZExtValue(); 8102 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8103 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8104 getLangOpts(), 8105 Context.getTargetInfo()); 8106 } 8107 8108 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8109 8110 // Returns the related absolute value function that is larger, of 0 if one 8111 // does not exist. 8112 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8113 switch (AbsFunction) { 8114 default: 8115 return 0; 8116 8117 case Builtin::BI__builtin_abs: 8118 return Builtin::BI__builtin_labs; 8119 case Builtin::BI__builtin_labs: 8120 return Builtin::BI__builtin_llabs; 8121 case Builtin::BI__builtin_llabs: 8122 return 0; 8123 8124 case Builtin::BI__builtin_fabsf: 8125 return Builtin::BI__builtin_fabs; 8126 case Builtin::BI__builtin_fabs: 8127 return Builtin::BI__builtin_fabsl; 8128 case Builtin::BI__builtin_fabsl: 8129 return 0; 8130 8131 case Builtin::BI__builtin_cabsf: 8132 return Builtin::BI__builtin_cabs; 8133 case Builtin::BI__builtin_cabs: 8134 return Builtin::BI__builtin_cabsl; 8135 case Builtin::BI__builtin_cabsl: 8136 return 0; 8137 8138 case Builtin::BIabs: 8139 return Builtin::BIlabs; 8140 case Builtin::BIlabs: 8141 return Builtin::BIllabs; 8142 case Builtin::BIllabs: 8143 return 0; 8144 8145 case Builtin::BIfabsf: 8146 return Builtin::BIfabs; 8147 case Builtin::BIfabs: 8148 return Builtin::BIfabsl; 8149 case Builtin::BIfabsl: 8150 return 0; 8151 8152 case Builtin::BIcabsf: 8153 return Builtin::BIcabs; 8154 case Builtin::BIcabs: 8155 return Builtin::BIcabsl; 8156 case Builtin::BIcabsl: 8157 return 0; 8158 } 8159 } 8160 8161 // Returns the argument type of the absolute value function. 8162 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8163 unsigned AbsType) { 8164 if (AbsType == 0) 8165 return QualType(); 8166 8167 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8168 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8169 if (Error != ASTContext::GE_None) 8170 return QualType(); 8171 8172 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8173 if (!FT) 8174 return QualType(); 8175 8176 if (FT->getNumParams() != 1) 8177 return QualType(); 8178 8179 return FT->getParamType(0); 8180 } 8181 8182 // Returns the best absolute value function, or zero, based on type and 8183 // current absolute value function. 8184 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8185 unsigned AbsFunctionKind) { 8186 unsigned BestKind = 0; 8187 uint64_t ArgSize = Context.getTypeSize(ArgType); 8188 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8189 Kind = getLargerAbsoluteValueFunction(Kind)) { 8190 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8191 if (Context.getTypeSize(ParamType) >= ArgSize) { 8192 if (BestKind == 0) 8193 BestKind = Kind; 8194 else if (Context.hasSameType(ParamType, ArgType)) { 8195 BestKind = Kind; 8196 break; 8197 } 8198 } 8199 } 8200 return BestKind; 8201 } 8202 8203 enum AbsoluteValueKind { 8204 AVK_Integer, 8205 AVK_Floating, 8206 AVK_Complex 8207 }; 8208 8209 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8210 if (T->isIntegralOrEnumerationType()) 8211 return AVK_Integer; 8212 if (T->isRealFloatingType()) 8213 return AVK_Floating; 8214 if (T->isAnyComplexType()) 8215 return AVK_Complex; 8216 8217 llvm_unreachable("Type not integer, floating, or complex"); 8218 } 8219 8220 // Changes the absolute value function to a different type. Preserves whether 8221 // the function is a builtin. 8222 static unsigned changeAbsFunction(unsigned AbsKind, 8223 AbsoluteValueKind ValueKind) { 8224 switch (ValueKind) { 8225 case AVK_Integer: 8226 switch (AbsKind) { 8227 default: 8228 return 0; 8229 case Builtin::BI__builtin_fabsf: 8230 case Builtin::BI__builtin_fabs: 8231 case Builtin::BI__builtin_fabsl: 8232 case Builtin::BI__builtin_cabsf: 8233 case Builtin::BI__builtin_cabs: 8234 case Builtin::BI__builtin_cabsl: 8235 return Builtin::BI__builtin_abs; 8236 case Builtin::BIfabsf: 8237 case Builtin::BIfabs: 8238 case Builtin::BIfabsl: 8239 case Builtin::BIcabsf: 8240 case Builtin::BIcabs: 8241 case Builtin::BIcabsl: 8242 return Builtin::BIabs; 8243 } 8244 case AVK_Floating: 8245 switch (AbsKind) { 8246 default: 8247 return 0; 8248 case Builtin::BI__builtin_abs: 8249 case Builtin::BI__builtin_labs: 8250 case Builtin::BI__builtin_llabs: 8251 case Builtin::BI__builtin_cabsf: 8252 case Builtin::BI__builtin_cabs: 8253 case Builtin::BI__builtin_cabsl: 8254 return Builtin::BI__builtin_fabsf; 8255 case Builtin::BIabs: 8256 case Builtin::BIlabs: 8257 case Builtin::BIllabs: 8258 case Builtin::BIcabsf: 8259 case Builtin::BIcabs: 8260 case Builtin::BIcabsl: 8261 return Builtin::BIfabsf; 8262 } 8263 case AVK_Complex: 8264 switch (AbsKind) { 8265 default: 8266 return 0; 8267 case Builtin::BI__builtin_abs: 8268 case Builtin::BI__builtin_labs: 8269 case Builtin::BI__builtin_llabs: 8270 case Builtin::BI__builtin_fabsf: 8271 case Builtin::BI__builtin_fabs: 8272 case Builtin::BI__builtin_fabsl: 8273 return Builtin::BI__builtin_cabsf; 8274 case Builtin::BIabs: 8275 case Builtin::BIlabs: 8276 case Builtin::BIllabs: 8277 case Builtin::BIfabsf: 8278 case Builtin::BIfabs: 8279 case Builtin::BIfabsl: 8280 return Builtin::BIcabsf; 8281 } 8282 } 8283 llvm_unreachable("Unable to convert function"); 8284 } 8285 8286 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8287 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8288 if (!FnInfo) 8289 return 0; 8290 8291 switch (FDecl->getBuiltinID()) { 8292 default: 8293 return 0; 8294 case Builtin::BI__builtin_abs: 8295 case Builtin::BI__builtin_fabs: 8296 case Builtin::BI__builtin_fabsf: 8297 case Builtin::BI__builtin_fabsl: 8298 case Builtin::BI__builtin_labs: 8299 case Builtin::BI__builtin_llabs: 8300 case Builtin::BI__builtin_cabs: 8301 case Builtin::BI__builtin_cabsf: 8302 case Builtin::BI__builtin_cabsl: 8303 case Builtin::BIabs: 8304 case Builtin::BIlabs: 8305 case Builtin::BIllabs: 8306 case Builtin::BIfabs: 8307 case Builtin::BIfabsf: 8308 case Builtin::BIfabsl: 8309 case Builtin::BIcabs: 8310 case Builtin::BIcabsf: 8311 case Builtin::BIcabsl: 8312 return FDecl->getBuiltinID(); 8313 } 8314 llvm_unreachable("Unknown Builtin type"); 8315 } 8316 8317 // If the replacement is valid, emit a note with replacement function. 8318 // Additionally, suggest including the proper header if not already included. 8319 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8320 unsigned AbsKind, QualType ArgType) { 8321 bool EmitHeaderHint = true; 8322 const char *HeaderName = nullptr; 8323 const char *FunctionName = nullptr; 8324 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8325 FunctionName = "std::abs"; 8326 if (ArgType->isIntegralOrEnumerationType()) { 8327 HeaderName = "cstdlib"; 8328 } else if (ArgType->isRealFloatingType()) { 8329 HeaderName = "cmath"; 8330 } else { 8331 llvm_unreachable("Invalid Type"); 8332 } 8333 8334 // Lookup all std::abs 8335 if (NamespaceDecl *Std = S.getStdNamespace()) { 8336 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8337 R.suppressDiagnostics(); 8338 S.LookupQualifiedName(R, Std); 8339 8340 for (const auto *I : R) { 8341 const FunctionDecl *FDecl = nullptr; 8342 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8343 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8344 } else { 8345 FDecl = dyn_cast<FunctionDecl>(I); 8346 } 8347 if (!FDecl) 8348 continue; 8349 8350 // Found std::abs(), check that they are the right ones. 8351 if (FDecl->getNumParams() != 1) 8352 continue; 8353 8354 // Check that the parameter type can handle the argument. 8355 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8356 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8357 S.Context.getTypeSize(ArgType) <= 8358 S.Context.getTypeSize(ParamType)) { 8359 // Found a function, don't need the header hint. 8360 EmitHeaderHint = false; 8361 break; 8362 } 8363 } 8364 } 8365 } else { 8366 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8367 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8368 8369 if (HeaderName) { 8370 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8371 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8372 R.suppressDiagnostics(); 8373 S.LookupName(R, S.getCurScope()); 8374 8375 if (R.isSingleResult()) { 8376 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8377 if (FD && FD->getBuiltinID() == AbsKind) { 8378 EmitHeaderHint = false; 8379 } else { 8380 return; 8381 } 8382 } else if (!R.empty()) { 8383 return; 8384 } 8385 } 8386 } 8387 8388 S.Diag(Loc, diag::note_replace_abs_function) 8389 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8390 8391 if (!HeaderName) 8392 return; 8393 8394 if (!EmitHeaderHint) 8395 return; 8396 8397 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8398 << FunctionName; 8399 } 8400 8401 template <std::size_t StrLen> 8402 static bool IsStdFunction(const FunctionDecl *FDecl, 8403 const char (&Str)[StrLen]) { 8404 if (!FDecl) 8405 return false; 8406 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8407 return false; 8408 if (!FDecl->isInStdNamespace()) 8409 return false; 8410 8411 return true; 8412 } 8413 8414 // Warn when using the wrong abs() function. 8415 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8416 const FunctionDecl *FDecl) { 8417 if (Call->getNumArgs() != 1) 8418 return; 8419 8420 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8421 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8422 if (AbsKind == 0 && !IsStdAbs) 8423 return; 8424 8425 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8426 QualType ParamType = Call->getArg(0)->getType(); 8427 8428 // Unsigned types cannot be negative. Suggest removing the absolute value 8429 // function call. 8430 if (ArgType->isUnsignedIntegerType()) { 8431 const char *FunctionName = 8432 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8433 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8434 Diag(Call->getExprLoc(), diag::note_remove_abs) 8435 << FunctionName 8436 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8437 return; 8438 } 8439 8440 // Taking the absolute value of a pointer is very suspicious, they probably 8441 // wanted to index into an array, dereference a pointer, call a function, etc. 8442 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8443 unsigned DiagType = 0; 8444 if (ArgType->isFunctionType()) 8445 DiagType = 1; 8446 else if (ArgType->isArrayType()) 8447 DiagType = 2; 8448 8449 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8450 return; 8451 } 8452 8453 // std::abs has overloads which prevent most of the absolute value problems 8454 // from occurring. 8455 if (IsStdAbs) 8456 return; 8457 8458 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8459 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8460 8461 // The argument and parameter are the same kind. Check if they are the right 8462 // size. 8463 if (ArgValueKind == ParamValueKind) { 8464 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8465 return; 8466 8467 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8468 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8469 << FDecl << ArgType << ParamType; 8470 8471 if (NewAbsKind == 0) 8472 return; 8473 8474 emitReplacement(*this, Call->getExprLoc(), 8475 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8476 return; 8477 } 8478 8479 // ArgValueKind != ParamValueKind 8480 // The wrong type of absolute value function was used. Attempt to find the 8481 // proper one. 8482 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8483 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8484 if (NewAbsKind == 0) 8485 return; 8486 8487 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8488 << FDecl << ParamValueKind << ArgValueKind; 8489 8490 emitReplacement(*this, Call->getExprLoc(), 8491 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8492 } 8493 8494 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8495 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8496 const FunctionDecl *FDecl) { 8497 if (!Call || !FDecl) return; 8498 8499 // Ignore template specializations and macros. 8500 if (inTemplateInstantiation()) return; 8501 if (Call->getExprLoc().isMacroID()) return; 8502 8503 // Only care about the one template argument, two function parameter std::max 8504 if (Call->getNumArgs() != 2) return; 8505 if (!IsStdFunction(FDecl, "max")) return; 8506 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8507 if (!ArgList) return; 8508 if (ArgList->size() != 1) return; 8509 8510 // Check that template type argument is unsigned integer. 8511 const auto& TA = ArgList->get(0); 8512 if (TA.getKind() != TemplateArgument::Type) return; 8513 QualType ArgType = TA.getAsType(); 8514 if (!ArgType->isUnsignedIntegerType()) return; 8515 8516 // See if either argument is a literal zero. 8517 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8518 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8519 if (!MTE) return false; 8520 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8521 if (!Num) return false; 8522 if (Num->getValue() != 0) return false; 8523 return true; 8524 }; 8525 8526 const Expr *FirstArg = Call->getArg(0); 8527 const Expr *SecondArg = Call->getArg(1); 8528 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8529 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8530 8531 // Only warn when exactly one argument is zero. 8532 if (IsFirstArgZero == IsSecondArgZero) return; 8533 8534 SourceRange FirstRange = FirstArg->getSourceRange(); 8535 SourceRange SecondRange = SecondArg->getSourceRange(); 8536 8537 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8538 8539 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8540 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8541 8542 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8543 SourceRange RemovalRange; 8544 if (IsFirstArgZero) { 8545 RemovalRange = SourceRange(FirstRange.getBegin(), 8546 SecondRange.getBegin().getLocWithOffset(-1)); 8547 } else { 8548 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8549 SecondRange.getEnd()); 8550 } 8551 8552 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8553 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8554 << FixItHint::CreateRemoval(RemovalRange); 8555 } 8556 8557 //===--- CHECK: Standard memory functions ---------------------------------===// 8558 8559 /// Takes the expression passed to the size_t parameter of functions 8560 /// such as memcmp, strncat, etc and warns if it's a comparison. 8561 /// 8562 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8563 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8564 IdentifierInfo *FnName, 8565 SourceLocation FnLoc, 8566 SourceLocation RParenLoc) { 8567 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8568 if (!Size) 8569 return false; 8570 8571 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8572 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8573 return false; 8574 8575 SourceRange SizeRange = Size->getSourceRange(); 8576 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8577 << SizeRange << FnName; 8578 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8579 << FnName 8580 << FixItHint::CreateInsertion( 8581 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8582 << FixItHint::CreateRemoval(RParenLoc); 8583 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8584 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8585 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8586 ")"); 8587 8588 return true; 8589 } 8590 8591 /// Determine whether the given type is or contains a dynamic class type 8592 /// (e.g., whether it has a vtable). 8593 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8594 bool &IsContained) { 8595 // Look through array types while ignoring qualifiers. 8596 const Type *Ty = T->getBaseElementTypeUnsafe(); 8597 IsContained = false; 8598 8599 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8600 RD = RD ? RD->getDefinition() : nullptr; 8601 if (!RD || RD->isInvalidDecl()) 8602 return nullptr; 8603 8604 if (RD->isDynamicClass()) 8605 return RD; 8606 8607 // Check all the fields. If any bases were dynamic, the class is dynamic. 8608 // It's impossible for a class to transitively contain itself by value, so 8609 // infinite recursion is impossible. 8610 for (auto *FD : RD->fields()) { 8611 bool SubContained; 8612 if (const CXXRecordDecl *ContainedRD = 8613 getContainedDynamicClass(FD->getType(), SubContained)) { 8614 IsContained = true; 8615 return ContainedRD; 8616 } 8617 } 8618 8619 return nullptr; 8620 } 8621 8622 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8623 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8624 if (Unary->getKind() == UETT_SizeOf) 8625 return Unary; 8626 return nullptr; 8627 } 8628 8629 /// If E is a sizeof expression, returns its argument expression, 8630 /// otherwise returns NULL. 8631 static const Expr *getSizeOfExprArg(const Expr *E) { 8632 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8633 if (!SizeOf->isArgumentType()) 8634 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8635 return nullptr; 8636 } 8637 8638 /// If E is a sizeof expression, returns its argument type. 8639 static QualType getSizeOfArgType(const Expr *E) { 8640 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8641 return SizeOf->getTypeOfArgument(); 8642 return QualType(); 8643 } 8644 8645 namespace { 8646 8647 struct SearchNonTrivialToInitializeField 8648 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8649 using Super = 8650 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8651 8652 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8653 8654 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8655 SourceLocation SL) { 8656 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8657 asDerived().visitArray(PDIK, AT, SL); 8658 return; 8659 } 8660 8661 Super::visitWithKind(PDIK, FT, SL); 8662 } 8663 8664 void visitARCStrong(QualType FT, SourceLocation SL) { 8665 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8666 } 8667 void visitARCWeak(QualType FT, SourceLocation SL) { 8668 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8669 } 8670 void visitStruct(QualType FT, SourceLocation SL) { 8671 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8672 visit(FD->getType(), FD->getLocation()); 8673 } 8674 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8675 const ArrayType *AT, SourceLocation SL) { 8676 visit(getContext().getBaseElementType(AT), SL); 8677 } 8678 void visitTrivial(QualType FT, SourceLocation SL) {} 8679 8680 static void diag(QualType RT, const Expr *E, Sema &S) { 8681 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 8682 } 8683 8684 ASTContext &getContext() { return S.getASTContext(); } 8685 8686 const Expr *E; 8687 Sema &S; 8688 }; 8689 8690 struct SearchNonTrivialToCopyField 8691 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 8692 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 8693 8694 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 8695 8696 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 8697 SourceLocation SL) { 8698 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8699 asDerived().visitArray(PCK, AT, SL); 8700 return; 8701 } 8702 8703 Super::visitWithKind(PCK, FT, SL); 8704 } 8705 8706 void visitARCStrong(QualType FT, SourceLocation SL) { 8707 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8708 } 8709 void visitARCWeak(QualType FT, SourceLocation SL) { 8710 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8711 } 8712 void visitStruct(QualType FT, SourceLocation SL) { 8713 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8714 visit(FD->getType(), FD->getLocation()); 8715 } 8716 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 8717 SourceLocation SL) { 8718 visit(getContext().getBaseElementType(AT), SL); 8719 } 8720 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 8721 SourceLocation SL) {} 8722 void visitTrivial(QualType FT, SourceLocation SL) {} 8723 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 8724 8725 static void diag(QualType RT, const Expr *E, Sema &S) { 8726 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 8727 } 8728 8729 ASTContext &getContext() { return S.getASTContext(); } 8730 8731 const Expr *E; 8732 Sema &S; 8733 }; 8734 8735 } 8736 8737 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 8738 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 8739 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 8740 8741 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 8742 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 8743 return false; 8744 8745 return doesExprLikelyComputeSize(BO->getLHS()) || 8746 doesExprLikelyComputeSize(BO->getRHS()); 8747 } 8748 8749 return getAsSizeOfExpr(SizeofExpr) != nullptr; 8750 } 8751 8752 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 8753 /// 8754 /// \code 8755 /// #define MACRO 0 8756 /// foo(MACRO); 8757 /// foo(0); 8758 /// \endcode 8759 /// 8760 /// This should return true for the first call to foo, but not for the second 8761 /// (regardless of whether foo is a macro or function). 8762 static bool isArgumentExpandedFromMacro(SourceManager &SM, 8763 SourceLocation CallLoc, 8764 SourceLocation ArgLoc) { 8765 if (!CallLoc.isMacroID()) 8766 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 8767 8768 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 8769 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 8770 } 8771 8772 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 8773 /// last two arguments transposed. 8774 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 8775 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 8776 return; 8777 8778 const Expr *SizeArg = 8779 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 8780 8781 auto isLiteralZero = [](const Expr *E) { 8782 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 8783 }; 8784 8785 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 8786 SourceLocation CallLoc = Call->getRParenLoc(); 8787 SourceManager &SM = S.getSourceManager(); 8788 if (isLiteralZero(SizeArg) && 8789 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 8790 8791 SourceLocation DiagLoc = SizeArg->getExprLoc(); 8792 8793 // Some platforms #define bzero to __builtin_memset. See if this is the 8794 // case, and if so, emit a better diagnostic. 8795 if (BId == Builtin::BIbzero || 8796 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 8797 CallLoc, SM, S.getLangOpts()) == "bzero")) { 8798 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 8799 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 8800 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 8801 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 8802 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 8803 } 8804 return; 8805 } 8806 8807 // If the second argument to a memset is a sizeof expression and the third 8808 // isn't, this is also likely an error. This should catch 8809 // 'memset(buf, sizeof(buf), 0xff)'. 8810 if (BId == Builtin::BImemset && 8811 doesExprLikelyComputeSize(Call->getArg(1)) && 8812 !doesExprLikelyComputeSize(Call->getArg(2))) { 8813 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 8814 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 8815 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 8816 return; 8817 } 8818 } 8819 8820 /// Check for dangerous or invalid arguments to memset(). 8821 /// 8822 /// This issues warnings on known problematic, dangerous or unspecified 8823 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 8824 /// function calls. 8825 /// 8826 /// \param Call The call expression to diagnose. 8827 void Sema::CheckMemaccessArguments(const CallExpr *Call, 8828 unsigned BId, 8829 IdentifierInfo *FnName) { 8830 assert(BId != 0); 8831 8832 // It is possible to have a non-standard definition of memset. Validate 8833 // we have enough arguments, and if not, abort further checking. 8834 unsigned ExpectedNumArgs = 8835 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 8836 if (Call->getNumArgs() < ExpectedNumArgs) 8837 return; 8838 8839 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 8840 BId == Builtin::BIstrndup ? 1 : 2); 8841 unsigned LenArg = 8842 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 8843 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 8844 8845 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 8846 Call->getBeginLoc(), Call->getRParenLoc())) 8847 return; 8848 8849 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 8850 CheckMemaccessSize(*this, BId, Call); 8851 8852 // We have special checking when the length is a sizeof expression. 8853 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 8854 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 8855 llvm::FoldingSetNodeID SizeOfArgID; 8856 8857 // Although widely used, 'bzero' is not a standard function. Be more strict 8858 // with the argument types before allowing diagnostics and only allow the 8859 // form bzero(ptr, sizeof(...)). 8860 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8861 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 8862 return; 8863 8864 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 8865 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 8866 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 8867 8868 QualType DestTy = Dest->getType(); 8869 QualType PointeeTy; 8870 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 8871 PointeeTy = DestPtrTy->getPointeeType(); 8872 8873 // Never warn about void type pointers. This can be used to suppress 8874 // false positives. 8875 if (PointeeTy->isVoidType()) 8876 continue; 8877 8878 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 8879 // actually comparing the expressions for equality. Because computing the 8880 // expression IDs can be expensive, we only do this if the diagnostic is 8881 // enabled. 8882 if (SizeOfArg && 8883 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 8884 SizeOfArg->getExprLoc())) { 8885 // We only compute IDs for expressions if the warning is enabled, and 8886 // cache the sizeof arg's ID. 8887 if (SizeOfArgID == llvm::FoldingSetNodeID()) 8888 SizeOfArg->Profile(SizeOfArgID, Context, true); 8889 llvm::FoldingSetNodeID DestID; 8890 Dest->Profile(DestID, Context, true); 8891 if (DestID == SizeOfArgID) { 8892 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 8893 // over sizeof(src) as well. 8894 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 8895 StringRef ReadableName = FnName->getName(); 8896 8897 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 8898 if (UnaryOp->getOpcode() == UO_AddrOf) 8899 ActionIdx = 1; // If its an address-of operator, just remove it. 8900 if (!PointeeTy->isIncompleteType() && 8901 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 8902 ActionIdx = 2; // If the pointee's size is sizeof(char), 8903 // suggest an explicit length. 8904 8905 // If the function is defined as a builtin macro, do not show macro 8906 // expansion. 8907 SourceLocation SL = SizeOfArg->getExprLoc(); 8908 SourceRange DSR = Dest->getSourceRange(); 8909 SourceRange SSR = SizeOfArg->getSourceRange(); 8910 SourceManager &SM = getSourceManager(); 8911 8912 if (SM.isMacroArgExpansion(SL)) { 8913 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 8914 SL = SM.getSpellingLoc(SL); 8915 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 8916 SM.getSpellingLoc(DSR.getEnd())); 8917 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 8918 SM.getSpellingLoc(SSR.getEnd())); 8919 } 8920 8921 DiagRuntimeBehavior(SL, SizeOfArg, 8922 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 8923 << ReadableName 8924 << PointeeTy 8925 << DestTy 8926 << DSR 8927 << SSR); 8928 DiagRuntimeBehavior(SL, SizeOfArg, 8929 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 8930 << ActionIdx 8931 << SSR); 8932 8933 break; 8934 } 8935 } 8936 8937 // Also check for cases where the sizeof argument is the exact same 8938 // type as the memory argument, and where it points to a user-defined 8939 // record type. 8940 if (SizeOfArgTy != QualType()) { 8941 if (PointeeTy->isRecordType() && 8942 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 8943 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 8944 PDiag(diag::warn_sizeof_pointer_type_memaccess) 8945 << FnName << SizeOfArgTy << ArgIdx 8946 << PointeeTy << Dest->getSourceRange() 8947 << LenExpr->getSourceRange()); 8948 break; 8949 } 8950 } 8951 } else if (DestTy->isArrayType()) { 8952 PointeeTy = DestTy; 8953 } 8954 8955 if (PointeeTy == QualType()) 8956 continue; 8957 8958 // Always complain about dynamic classes. 8959 bool IsContained; 8960 if (const CXXRecordDecl *ContainedRD = 8961 getContainedDynamicClass(PointeeTy, IsContained)) { 8962 8963 unsigned OperationType = 0; 8964 // "overwritten" if we're warning about the destination for any call 8965 // but memcmp; otherwise a verb appropriate to the call. 8966 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 8967 if (BId == Builtin::BImemcpy) 8968 OperationType = 1; 8969 else if(BId == Builtin::BImemmove) 8970 OperationType = 2; 8971 else if (BId == Builtin::BImemcmp) 8972 OperationType = 3; 8973 } 8974 8975 DiagRuntimeBehavior( 8976 Dest->getExprLoc(), Dest, 8977 PDiag(diag::warn_dyn_class_memaccess) 8978 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 8979 << FnName << IsContained << ContainedRD << OperationType 8980 << Call->getCallee()->getSourceRange()); 8981 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 8982 BId != Builtin::BImemset) 8983 DiagRuntimeBehavior( 8984 Dest->getExprLoc(), Dest, 8985 PDiag(diag::warn_arc_object_memaccess) 8986 << ArgIdx << FnName << PointeeTy 8987 << Call->getCallee()->getSourceRange()); 8988 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 8989 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 8990 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 8991 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 8992 PDiag(diag::warn_cstruct_memaccess) 8993 << ArgIdx << FnName << PointeeTy << 0); 8994 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 8995 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 8996 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 8997 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 8998 PDiag(diag::warn_cstruct_memaccess) 8999 << ArgIdx << FnName << PointeeTy << 1); 9000 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9001 } else { 9002 continue; 9003 } 9004 } else 9005 continue; 9006 9007 DiagRuntimeBehavior( 9008 Dest->getExprLoc(), Dest, 9009 PDiag(diag::note_bad_memaccess_silence) 9010 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9011 break; 9012 } 9013 } 9014 9015 // A little helper routine: ignore addition and subtraction of integer literals. 9016 // This intentionally does not ignore all integer constant expressions because 9017 // we don't want to remove sizeof(). 9018 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9019 Ex = Ex->IgnoreParenCasts(); 9020 9021 while (true) { 9022 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9023 if (!BO || !BO->isAdditiveOp()) 9024 break; 9025 9026 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9027 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9028 9029 if (isa<IntegerLiteral>(RHS)) 9030 Ex = LHS; 9031 else if (isa<IntegerLiteral>(LHS)) 9032 Ex = RHS; 9033 else 9034 break; 9035 } 9036 9037 return Ex; 9038 } 9039 9040 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9041 ASTContext &Context) { 9042 // Only handle constant-sized or VLAs, but not flexible members. 9043 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9044 // Only issue the FIXIT for arrays of size > 1. 9045 if (CAT->getSize().getSExtValue() <= 1) 9046 return false; 9047 } else if (!Ty->isVariableArrayType()) { 9048 return false; 9049 } 9050 return true; 9051 } 9052 9053 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9054 // be the size of the source, instead of the destination. 9055 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9056 IdentifierInfo *FnName) { 9057 9058 // Don't crash if the user has the wrong number of arguments 9059 unsigned NumArgs = Call->getNumArgs(); 9060 if ((NumArgs != 3) && (NumArgs != 4)) 9061 return; 9062 9063 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9064 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9065 const Expr *CompareWithSrc = nullptr; 9066 9067 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9068 Call->getBeginLoc(), Call->getRParenLoc())) 9069 return; 9070 9071 // Look for 'strlcpy(dst, x, sizeof(x))' 9072 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9073 CompareWithSrc = Ex; 9074 else { 9075 // Look for 'strlcpy(dst, x, strlen(x))' 9076 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9077 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9078 SizeCall->getNumArgs() == 1) 9079 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9080 } 9081 } 9082 9083 if (!CompareWithSrc) 9084 return; 9085 9086 // Determine if the argument to sizeof/strlen is equal to the source 9087 // argument. In principle there's all kinds of things you could do 9088 // here, for instance creating an == expression and evaluating it with 9089 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9090 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9091 if (!SrcArgDRE) 9092 return; 9093 9094 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9095 if (!CompareWithSrcDRE || 9096 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9097 return; 9098 9099 const Expr *OriginalSizeArg = Call->getArg(2); 9100 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9101 << OriginalSizeArg->getSourceRange() << FnName; 9102 9103 // Output a FIXIT hint if the destination is an array (rather than a 9104 // pointer to an array). This could be enhanced to handle some 9105 // pointers if we know the actual size, like if DstArg is 'array+2' 9106 // we could say 'sizeof(array)-2'. 9107 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9108 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9109 return; 9110 9111 SmallString<128> sizeString; 9112 llvm::raw_svector_ostream OS(sizeString); 9113 OS << "sizeof("; 9114 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9115 OS << ")"; 9116 9117 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9118 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9119 OS.str()); 9120 } 9121 9122 /// Check if two expressions refer to the same declaration. 9123 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9124 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9125 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9126 return D1->getDecl() == D2->getDecl(); 9127 return false; 9128 } 9129 9130 static const Expr *getStrlenExprArg(const Expr *E) { 9131 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9132 const FunctionDecl *FD = CE->getDirectCallee(); 9133 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9134 return nullptr; 9135 return CE->getArg(0)->IgnoreParenCasts(); 9136 } 9137 return nullptr; 9138 } 9139 9140 // Warn on anti-patterns as the 'size' argument to strncat. 9141 // The correct size argument should look like following: 9142 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9143 void Sema::CheckStrncatArguments(const CallExpr *CE, 9144 IdentifierInfo *FnName) { 9145 // Don't crash if the user has the wrong number of arguments. 9146 if (CE->getNumArgs() < 3) 9147 return; 9148 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9149 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9150 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9151 9152 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9153 CE->getRParenLoc())) 9154 return; 9155 9156 // Identify common expressions, which are wrongly used as the size argument 9157 // to strncat and may lead to buffer overflows. 9158 unsigned PatternType = 0; 9159 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9160 // - sizeof(dst) 9161 if (referToTheSameDecl(SizeOfArg, DstArg)) 9162 PatternType = 1; 9163 // - sizeof(src) 9164 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9165 PatternType = 2; 9166 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9167 if (BE->getOpcode() == BO_Sub) { 9168 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9169 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9170 // - sizeof(dst) - strlen(dst) 9171 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9172 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9173 PatternType = 1; 9174 // - sizeof(src) - (anything) 9175 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9176 PatternType = 2; 9177 } 9178 } 9179 9180 if (PatternType == 0) 9181 return; 9182 9183 // Generate the diagnostic. 9184 SourceLocation SL = LenArg->getBeginLoc(); 9185 SourceRange SR = LenArg->getSourceRange(); 9186 SourceManager &SM = getSourceManager(); 9187 9188 // If the function is defined as a builtin macro, do not show macro expansion. 9189 if (SM.isMacroArgExpansion(SL)) { 9190 SL = SM.getSpellingLoc(SL); 9191 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9192 SM.getSpellingLoc(SR.getEnd())); 9193 } 9194 9195 // Check if the destination is an array (rather than a pointer to an array). 9196 QualType DstTy = DstArg->getType(); 9197 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9198 Context); 9199 if (!isKnownSizeArray) { 9200 if (PatternType == 1) 9201 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9202 else 9203 Diag(SL, diag::warn_strncat_src_size) << SR; 9204 return; 9205 } 9206 9207 if (PatternType == 1) 9208 Diag(SL, diag::warn_strncat_large_size) << SR; 9209 else 9210 Diag(SL, diag::warn_strncat_src_size) << SR; 9211 9212 SmallString<128> sizeString; 9213 llvm::raw_svector_ostream OS(sizeString); 9214 OS << "sizeof("; 9215 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9216 OS << ") - "; 9217 OS << "strlen("; 9218 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9219 OS << ") - 1"; 9220 9221 Diag(SL, diag::note_strncat_wrong_size) 9222 << FixItHint::CreateReplacement(SR, OS.str()); 9223 } 9224 9225 void 9226 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9227 SourceLocation ReturnLoc, 9228 bool isObjCMethod, 9229 const AttrVec *Attrs, 9230 const FunctionDecl *FD) { 9231 // Check if the return value is null but should not be. 9232 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9233 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9234 CheckNonNullExpr(*this, RetValExp)) 9235 Diag(ReturnLoc, diag::warn_null_ret) 9236 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9237 9238 // C++11 [basic.stc.dynamic.allocation]p4: 9239 // If an allocation function declared with a non-throwing 9240 // exception-specification fails to allocate storage, it shall return 9241 // a null pointer. Any other allocation function that fails to allocate 9242 // storage shall indicate failure only by throwing an exception [...] 9243 if (FD) { 9244 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9245 if (Op == OO_New || Op == OO_Array_New) { 9246 const FunctionProtoType *Proto 9247 = FD->getType()->castAs<FunctionProtoType>(); 9248 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9249 CheckNonNullExpr(*this, RetValExp)) 9250 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9251 << FD << getLangOpts().CPlusPlus11; 9252 } 9253 } 9254 } 9255 9256 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9257 9258 /// Check for comparisons of floating point operands using != and ==. 9259 /// Issue a warning if these are no self-comparisons, as they are not likely 9260 /// to do what the programmer intended. 9261 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9262 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9263 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9264 9265 // Special case: check for x == x (which is OK). 9266 // Do not emit warnings for such cases. 9267 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9268 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9269 if (DRL->getDecl() == DRR->getDecl()) 9270 return; 9271 9272 // Special case: check for comparisons against literals that can be exactly 9273 // represented by APFloat. In such cases, do not emit a warning. This 9274 // is a heuristic: often comparison against such literals are used to 9275 // detect if a value in a variable has not changed. This clearly can 9276 // lead to false negatives. 9277 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9278 if (FLL->isExact()) 9279 return; 9280 } else 9281 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9282 if (FLR->isExact()) 9283 return; 9284 9285 // Check for comparisons with builtin types. 9286 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9287 if (CL->getBuiltinCallee()) 9288 return; 9289 9290 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9291 if (CR->getBuiltinCallee()) 9292 return; 9293 9294 // Emit the diagnostic. 9295 Diag(Loc, diag::warn_floatingpoint_eq) 9296 << LHS->getSourceRange() << RHS->getSourceRange(); 9297 } 9298 9299 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9300 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9301 9302 namespace { 9303 9304 /// Structure recording the 'active' range of an integer-valued 9305 /// expression. 9306 struct IntRange { 9307 /// The number of bits active in the int. 9308 unsigned Width; 9309 9310 /// True if the int is known not to have negative values. 9311 bool NonNegative; 9312 9313 IntRange(unsigned Width, bool NonNegative) 9314 : Width(Width), NonNegative(NonNegative) {} 9315 9316 /// Returns the range of the bool type. 9317 static IntRange forBoolType() { 9318 return IntRange(1, true); 9319 } 9320 9321 /// Returns the range of an opaque value of the given integral type. 9322 static IntRange forValueOfType(ASTContext &C, QualType T) { 9323 return forValueOfCanonicalType(C, 9324 T->getCanonicalTypeInternal().getTypePtr()); 9325 } 9326 9327 /// Returns the range of an opaque value of a canonical integral type. 9328 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9329 assert(T->isCanonicalUnqualified()); 9330 9331 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9332 T = VT->getElementType().getTypePtr(); 9333 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9334 T = CT->getElementType().getTypePtr(); 9335 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9336 T = AT->getValueType().getTypePtr(); 9337 9338 if (!C.getLangOpts().CPlusPlus) { 9339 // For enum types in C code, use the underlying datatype. 9340 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9341 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9342 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9343 // For enum types in C++, use the known bit width of the enumerators. 9344 EnumDecl *Enum = ET->getDecl(); 9345 // In C++11, enums can have a fixed underlying type. Use this type to 9346 // compute the range. 9347 if (Enum->isFixed()) { 9348 return IntRange(C.getIntWidth(QualType(T, 0)), 9349 !ET->isSignedIntegerOrEnumerationType()); 9350 } 9351 9352 unsigned NumPositive = Enum->getNumPositiveBits(); 9353 unsigned NumNegative = Enum->getNumNegativeBits(); 9354 9355 if (NumNegative == 0) 9356 return IntRange(NumPositive, true/*NonNegative*/); 9357 else 9358 return IntRange(std::max(NumPositive + 1, NumNegative), 9359 false/*NonNegative*/); 9360 } 9361 9362 const BuiltinType *BT = cast<BuiltinType>(T); 9363 assert(BT->isInteger()); 9364 9365 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9366 } 9367 9368 /// Returns the "target" range of a canonical integral type, i.e. 9369 /// the range of values expressible in the type. 9370 /// 9371 /// This matches forValueOfCanonicalType except that enums have the 9372 /// full range of their type, not the range of their enumerators. 9373 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9374 assert(T->isCanonicalUnqualified()); 9375 9376 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9377 T = VT->getElementType().getTypePtr(); 9378 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9379 T = CT->getElementType().getTypePtr(); 9380 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9381 T = AT->getValueType().getTypePtr(); 9382 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9383 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9384 9385 const BuiltinType *BT = cast<BuiltinType>(T); 9386 assert(BT->isInteger()); 9387 9388 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9389 } 9390 9391 /// Returns the supremum of two ranges: i.e. their conservative merge. 9392 static IntRange join(IntRange L, IntRange R) { 9393 return IntRange(std::max(L.Width, R.Width), 9394 L.NonNegative && R.NonNegative); 9395 } 9396 9397 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9398 static IntRange meet(IntRange L, IntRange R) { 9399 return IntRange(std::min(L.Width, R.Width), 9400 L.NonNegative || R.NonNegative); 9401 } 9402 }; 9403 9404 } // namespace 9405 9406 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9407 unsigned MaxWidth) { 9408 if (value.isSigned() && value.isNegative()) 9409 return IntRange(value.getMinSignedBits(), false); 9410 9411 if (value.getBitWidth() > MaxWidth) 9412 value = value.trunc(MaxWidth); 9413 9414 // isNonNegative() just checks the sign bit without considering 9415 // signedness. 9416 return IntRange(value.getActiveBits(), true); 9417 } 9418 9419 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9420 unsigned MaxWidth) { 9421 if (result.isInt()) 9422 return GetValueRange(C, result.getInt(), MaxWidth); 9423 9424 if (result.isVector()) { 9425 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9426 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9427 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9428 R = IntRange::join(R, El); 9429 } 9430 return R; 9431 } 9432 9433 if (result.isComplexInt()) { 9434 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9435 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9436 return IntRange::join(R, I); 9437 } 9438 9439 // This can happen with lossless casts to intptr_t of "based" lvalues. 9440 // Assume it might use arbitrary bits. 9441 // FIXME: The only reason we need to pass the type in here is to get 9442 // the sign right on this one case. It would be nice if APValue 9443 // preserved this. 9444 assert(result.isLValue() || result.isAddrLabelDiff()); 9445 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9446 } 9447 9448 static QualType GetExprType(const Expr *E) { 9449 QualType Ty = E->getType(); 9450 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9451 Ty = AtomicRHS->getValueType(); 9452 return Ty; 9453 } 9454 9455 /// Pseudo-evaluate the given integer expression, estimating the 9456 /// range of values it might take. 9457 /// 9458 /// \param MaxWidth - the width to which the value will be truncated 9459 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 9460 E = E->IgnoreParens(); 9461 9462 // Try a full evaluation first. 9463 Expr::EvalResult result; 9464 if (E->EvaluateAsRValue(result, C)) 9465 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9466 9467 // I think we only want to look through implicit casts here; if the 9468 // user has an explicit widening cast, we should treat the value as 9469 // being of the new, wider type. 9470 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9471 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9472 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 9473 9474 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9475 9476 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9477 CE->getCastKind() == CK_BooleanToSignedIntegral; 9478 9479 // Assume that non-integer casts can span the full range of the type. 9480 if (!isIntegerCast) 9481 return OutputTypeRange; 9482 9483 IntRange SubRange 9484 = GetExprRange(C, CE->getSubExpr(), 9485 std::min(MaxWidth, OutputTypeRange.Width)); 9486 9487 // Bail out if the subexpr's range is as wide as the cast type. 9488 if (SubRange.Width >= OutputTypeRange.Width) 9489 return OutputTypeRange; 9490 9491 // Otherwise, we take the smaller width, and we're non-negative if 9492 // either the output type or the subexpr is. 9493 return IntRange(SubRange.Width, 9494 SubRange.NonNegative || OutputTypeRange.NonNegative); 9495 } 9496 9497 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9498 // If we can fold the condition, just take that operand. 9499 bool CondResult; 9500 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9501 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9502 : CO->getFalseExpr(), 9503 MaxWidth); 9504 9505 // Otherwise, conservatively merge. 9506 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9507 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9508 return IntRange::join(L, R); 9509 } 9510 9511 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9512 switch (BO->getOpcode()) { 9513 case BO_Cmp: 9514 llvm_unreachable("builtin <=> should have class type"); 9515 9516 // Boolean-valued operations are single-bit and positive. 9517 case BO_LAnd: 9518 case BO_LOr: 9519 case BO_LT: 9520 case BO_GT: 9521 case BO_LE: 9522 case BO_GE: 9523 case BO_EQ: 9524 case BO_NE: 9525 return IntRange::forBoolType(); 9526 9527 // The type of the assignments is the type of the LHS, so the RHS 9528 // is not necessarily the same type. 9529 case BO_MulAssign: 9530 case BO_DivAssign: 9531 case BO_RemAssign: 9532 case BO_AddAssign: 9533 case BO_SubAssign: 9534 case BO_XorAssign: 9535 case BO_OrAssign: 9536 // TODO: bitfields? 9537 return IntRange::forValueOfType(C, GetExprType(E)); 9538 9539 // Simple assignments just pass through the RHS, which will have 9540 // been coerced to the LHS type. 9541 case BO_Assign: 9542 // TODO: bitfields? 9543 return GetExprRange(C, BO->getRHS(), MaxWidth); 9544 9545 // Operations with opaque sources are black-listed. 9546 case BO_PtrMemD: 9547 case BO_PtrMemI: 9548 return IntRange::forValueOfType(C, GetExprType(E)); 9549 9550 // Bitwise-and uses the *infinum* of the two source ranges. 9551 case BO_And: 9552 case BO_AndAssign: 9553 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9554 GetExprRange(C, BO->getRHS(), MaxWidth)); 9555 9556 // Left shift gets black-listed based on a judgement call. 9557 case BO_Shl: 9558 // ...except that we want to treat '1 << (blah)' as logically 9559 // positive. It's an important idiom. 9560 if (IntegerLiteral *I 9561 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9562 if (I->getValue() == 1) { 9563 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9564 return IntRange(R.Width, /*NonNegative*/ true); 9565 } 9566 } 9567 LLVM_FALLTHROUGH; 9568 9569 case BO_ShlAssign: 9570 return IntRange::forValueOfType(C, GetExprType(E)); 9571 9572 // Right shift by a constant can narrow its left argument. 9573 case BO_Shr: 9574 case BO_ShrAssign: { 9575 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9576 9577 // If the shift amount is a positive constant, drop the width by 9578 // that much. 9579 llvm::APSInt shift; 9580 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9581 shift.isNonNegative()) { 9582 unsigned zext = shift.getZExtValue(); 9583 if (zext >= L.Width) 9584 L.Width = (L.NonNegative ? 0 : 1); 9585 else 9586 L.Width -= zext; 9587 } 9588 9589 return L; 9590 } 9591 9592 // Comma acts as its right operand. 9593 case BO_Comma: 9594 return GetExprRange(C, BO->getRHS(), MaxWidth); 9595 9596 // Black-list pointer subtractions. 9597 case BO_Sub: 9598 if (BO->getLHS()->getType()->isPointerType()) 9599 return IntRange::forValueOfType(C, GetExprType(E)); 9600 break; 9601 9602 // The width of a division result is mostly determined by the size 9603 // of the LHS. 9604 case BO_Div: { 9605 // Don't 'pre-truncate' the operands. 9606 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9607 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9608 9609 // If the divisor is constant, use that. 9610 llvm::APSInt divisor; 9611 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9612 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9613 if (log2 >= L.Width) 9614 L.Width = (L.NonNegative ? 0 : 1); 9615 else 9616 L.Width = std::min(L.Width - log2, MaxWidth); 9617 return L; 9618 } 9619 9620 // Otherwise, just use the LHS's width. 9621 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9622 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9623 } 9624 9625 // The result of a remainder can't be larger than the result of 9626 // either side. 9627 case BO_Rem: { 9628 // Don't 'pre-truncate' the operands. 9629 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9630 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9631 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9632 9633 IntRange meet = IntRange::meet(L, R); 9634 meet.Width = std::min(meet.Width, MaxWidth); 9635 return meet; 9636 } 9637 9638 // The default behavior is okay for these. 9639 case BO_Mul: 9640 case BO_Add: 9641 case BO_Xor: 9642 case BO_Or: 9643 break; 9644 } 9645 9646 // The default case is to treat the operation as if it were closed 9647 // on the narrowest type that encompasses both operands. 9648 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9649 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9650 return IntRange::join(L, R); 9651 } 9652 9653 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9654 switch (UO->getOpcode()) { 9655 // Boolean-valued operations are white-listed. 9656 case UO_LNot: 9657 return IntRange::forBoolType(); 9658 9659 // Operations with opaque sources are black-listed. 9660 case UO_Deref: 9661 case UO_AddrOf: // should be impossible 9662 return IntRange::forValueOfType(C, GetExprType(E)); 9663 9664 default: 9665 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9666 } 9667 } 9668 9669 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9670 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9671 9672 if (const auto *BitField = E->getSourceBitField()) 9673 return IntRange(BitField->getBitWidthValue(C), 9674 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9675 9676 return IntRange::forValueOfType(C, GetExprType(E)); 9677 } 9678 9679 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9680 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9681 } 9682 9683 /// Checks whether the given value, which currently has the given 9684 /// source semantics, has the same value when coerced through the 9685 /// target semantics. 9686 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9687 const llvm::fltSemantics &Src, 9688 const llvm::fltSemantics &Tgt) { 9689 llvm::APFloat truncated = value; 9690 9691 bool ignored; 9692 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9693 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9694 9695 return truncated.bitwiseIsEqual(value); 9696 } 9697 9698 /// Checks whether the given value, which currently has the given 9699 /// source semantics, has the same value when coerced through the 9700 /// target semantics. 9701 /// 9702 /// The value might be a vector of floats (or a complex number). 9703 static bool IsSameFloatAfterCast(const APValue &value, 9704 const llvm::fltSemantics &Src, 9705 const llvm::fltSemantics &Tgt) { 9706 if (value.isFloat()) 9707 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9708 9709 if (value.isVector()) { 9710 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9711 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9712 return false; 9713 return true; 9714 } 9715 9716 assert(value.isComplexFloat()); 9717 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9718 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9719 } 9720 9721 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9722 9723 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9724 // Suppress cases where we are comparing against an enum constant. 9725 if (const DeclRefExpr *DR = 9726 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9727 if (isa<EnumConstantDecl>(DR->getDecl())) 9728 return true; 9729 9730 // Suppress cases where the '0' value is expanded from a macro. 9731 if (E->getBeginLoc().isMacroID()) 9732 return true; 9733 9734 return false; 9735 } 9736 9737 static bool isKnownToHaveUnsignedValue(Expr *E) { 9738 return E->getType()->isIntegerType() && 9739 (!E->getType()->isSignedIntegerType() || 9740 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9741 } 9742 9743 namespace { 9744 /// The promoted range of values of a type. In general this has the 9745 /// following structure: 9746 /// 9747 /// |-----------| . . . |-----------| 9748 /// ^ ^ ^ ^ 9749 /// Min HoleMin HoleMax Max 9750 /// 9751 /// ... where there is only a hole if a signed type is promoted to unsigned 9752 /// (in which case Min and Max are the smallest and largest representable 9753 /// values). 9754 struct PromotedRange { 9755 // Min, or HoleMax if there is a hole. 9756 llvm::APSInt PromotedMin; 9757 // Max, or HoleMin if there is a hole. 9758 llvm::APSInt PromotedMax; 9759 9760 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9761 if (R.Width == 0) 9762 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9763 else if (R.Width >= BitWidth && !Unsigned) { 9764 // Promotion made the type *narrower*. This happens when promoting 9765 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9766 // Treat all values of 'signed int' as being in range for now. 9767 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9768 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9769 } else { 9770 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9771 .extOrTrunc(BitWidth); 9772 PromotedMin.setIsUnsigned(Unsigned); 9773 9774 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9775 .extOrTrunc(BitWidth); 9776 PromotedMax.setIsUnsigned(Unsigned); 9777 } 9778 } 9779 9780 // Determine whether this range is contiguous (has no hole). 9781 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9782 9783 // Where a constant value is within the range. 9784 enum ComparisonResult { 9785 LT = 0x1, 9786 LE = 0x2, 9787 GT = 0x4, 9788 GE = 0x8, 9789 EQ = 0x10, 9790 NE = 0x20, 9791 InRangeFlag = 0x40, 9792 9793 Less = LE | LT | NE, 9794 Min = LE | InRangeFlag, 9795 InRange = InRangeFlag, 9796 Max = GE | InRangeFlag, 9797 Greater = GE | GT | NE, 9798 9799 OnlyValue = LE | GE | EQ | InRangeFlag, 9800 InHole = NE 9801 }; 9802 9803 ComparisonResult compare(const llvm::APSInt &Value) const { 9804 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 9805 Value.isUnsigned() == PromotedMin.isUnsigned()); 9806 if (!isContiguous()) { 9807 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 9808 if (Value.isMinValue()) return Min; 9809 if (Value.isMaxValue()) return Max; 9810 if (Value >= PromotedMin) return InRange; 9811 if (Value <= PromotedMax) return InRange; 9812 return InHole; 9813 } 9814 9815 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 9816 case -1: return Less; 9817 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 9818 case 1: 9819 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 9820 case -1: return InRange; 9821 case 0: return Max; 9822 case 1: return Greater; 9823 } 9824 } 9825 9826 llvm_unreachable("impossible compare result"); 9827 } 9828 9829 static llvm::Optional<StringRef> 9830 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 9831 if (Op == BO_Cmp) { 9832 ComparisonResult LTFlag = LT, GTFlag = GT; 9833 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 9834 9835 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 9836 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 9837 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 9838 return llvm::None; 9839 } 9840 9841 ComparisonResult TrueFlag, FalseFlag; 9842 if (Op == BO_EQ) { 9843 TrueFlag = EQ; 9844 FalseFlag = NE; 9845 } else if (Op == BO_NE) { 9846 TrueFlag = NE; 9847 FalseFlag = EQ; 9848 } else { 9849 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 9850 TrueFlag = LT; 9851 FalseFlag = GE; 9852 } else { 9853 TrueFlag = GT; 9854 FalseFlag = LE; 9855 } 9856 if (Op == BO_GE || Op == BO_LE) 9857 std::swap(TrueFlag, FalseFlag); 9858 } 9859 if (R & TrueFlag) 9860 return StringRef("true"); 9861 if (R & FalseFlag) 9862 return StringRef("false"); 9863 return llvm::None; 9864 } 9865 }; 9866 } 9867 9868 static bool HasEnumType(Expr *E) { 9869 // Strip off implicit integral promotions. 9870 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9871 if (ICE->getCastKind() != CK_IntegralCast && 9872 ICE->getCastKind() != CK_NoOp) 9873 break; 9874 E = ICE->getSubExpr(); 9875 } 9876 9877 return E->getType()->isEnumeralType(); 9878 } 9879 9880 static int classifyConstantValue(Expr *Constant) { 9881 // The values of this enumeration are used in the diagnostics 9882 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 9883 enum ConstantValueKind { 9884 Miscellaneous = 0, 9885 LiteralTrue, 9886 LiteralFalse 9887 }; 9888 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 9889 return BL->getValue() ? ConstantValueKind::LiteralTrue 9890 : ConstantValueKind::LiteralFalse; 9891 return ConstantValueKind::Miscellaneous; 9892 } 9893 9894 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 9895 Expr *Constant, Expr *Other, 9896 const llvm::APSInt &Value, 9897 bool RhsConstant) { 9898 if (S.inTemplateInstantiation()) 9899 return false; 9900 9901 Expr *OriginalOther = Other; 9902 9903 Constant = Constant->IgnoreParenImpCasts(); 9904 Other = Other->IgnoreParenImpCasts(); 9905 9906 // Suppress warnings on tautological comparisons between values of the same 9907 // enumeration type. There are only two ways we could warn on this: 9908 // - If the constant is outside the range of representable values of 9909 // the enumeration. In such a case, we should warn about the cast 9910 // to enumeration type, not about the comparison. 9911 // - If the constant is the maximum / minimum in-range value. For an 9912 // enumeratin type, such comparisons can be meaningful and useful. 9913 if (Constant->getType()->isEnumeralType() && 9914 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 9915 return false; 9916 9917 // TODO: Investigate using GetExprRange() to get tighter bounds 9918 // on the bit ranges. 9919 QualType OtherT = Other->getType(); 9920 if (const auto *AT = OtherT->getAs<AtomicType>()) 9921 OtherT = AT->getValueType(); 9922 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 9923 9924 // Whether we're treating Other as being a bool because of the form of 9925 // expression despite it having another type (typically 'int' in C). 9926 bool OtherIsBooleanDespiteType = 9927 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 9928 if (OtherIsBooleanDespiteType) 9929 OtherRange = IntRange::forBoolType(); 9930 9931 // Determine the promoted range of the other type and see if a comparison of 9932 // the constant against that range is tautological. 9933 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 9934 Value.isUnsigned()); 9935 auto Cmp = OtherPromotedRange.compare(Value); 9936 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 9937 if (!Result) 9938 return false; 9939 9940 // Suppress the diagnostic for an in-range comparison if the constant comes 9941 // from a macro or enumerator. We don't want to diagnose 9942 // 9943 // some_long_value <= INT_MAX 9944 // 9945 // when sizeof(int) == sizeof(long). 9946 bool InRange = Cmp & PromotedRange::InRangeFlag; 9947 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 9948 return false; 9949 9950 // If this is a comparison to an enum constant, include that 9951 // constant in the diagnostic. 9952 const EnumConstantDecl *ED = nullptr; 9953 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 9954 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 9955 9956 // Should be enough for uint128 (39 decimal digits) 9957 SmallString<64> PrettySourceValue; 9958 llvm::raw_svector_ostream OS(PrettySourceValue); 9959 if (ED) 9960 OS << '\'' << *ED << "' (" << Value << ")"; 9961 else 9962 OS << Value; 9963 9964 // FIXME: We use a somewhat different formatting for the in-range cases and 9965 // cases involving boolean values for historical reasons. We should pick a 9966 // consistent way of presenting these diagnostics. 9967 if (!InRange || Other->isKnownToHaveBooleanValue()) { 9968 S.DiagRuntimeBehavior( 9969 E->getOperatorLoc(), E, 9970 S.PDiag(!InRange ? diag::warn_out_of_range_compare 9971 : diag::warn_tautological_bool_compare) 9972 << OS.str() << classifyConstantValue(Constant) 9973 << OtherT << OtherIsBooleanDespiteType << *Result 9974 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 9975 } else { 9976 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 9977 ? (HasEnumType(OriginalOther) 9978 ? diag::warn_unsigned_enum_always_true_comparison 9979 : diag::warn_unsigned_always_true_comparison) 9980 : diag::warn_tautological_constant_compare; 9981 9982 S.Diag(E->getOperatorLoc(), Diag) 9983 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 9984 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 9985 } 9986 9987 return true; 9988 } 9989 9990 /// Analyze the operands of the given comparison. Implements the 9991 /// fallback case from AnalyzeComparison. 9992 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 9993 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9994 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9995 } 9996 9997 /// Implements -Wsign-compare. 9998 /// 9999 /// \param E the binary operator to check for warnings 10000 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10001 // The type the comparison is being performed in. 10002 QualType T = E->getLHS()->getType(); 10003 10004 // Only analyze comparison operators where both sides have been converted to 10005 // the same type. 10006 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10007 return AnalyzeImpConvsInComparison(S, E); 10008 10009 // Don't analyze value-dependent comparisons directly. 10010 if (E->isValueDependent()) 10011 return AnalyzeImpConvsInComparison(S, E); 10012 10013 Expr *LHS = E->getLHS(); 10014 Expr *RHS = E->getRHS(); 10015 10016 if (T->isIntegralType(S.Context)) { 10017 llvm::APSInt RHSValue; 10018 llvm::APSInt LHSValue; 10019 10020 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10021 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10022 10023 // We don't care about expressions whose result is a constant. 10024 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10025 return AnalyzeImpConvsInComparison(S, E); 10026 10027 // We only care about expressions where just one side is literal 10028 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10029 // Is the constant on the RHS or LHS? 10030 const bool RhsConstant = IsRHSIntegralLiteral; 10031 Expr *Const = RhsConstant ? RHS : LHS; 10032 Expr *Other = RhsConstant ? LHS : RHS; 10033 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10034 10035 // Check whether an integer constant comparison results in a value 10036 // of 'true' or 'false'. 10037 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10038 return AnalyzeImpConvsInComparison(S, E); 10039 } 10040 } 10041 10042 if (!T->hasUnsignedIntegerRepresentation()) { 10043 // We don't do anything special if this isn't an unsigned integral 10044 // comparison: we're only interested in integral comparisons, and 10045 // signed comparisons only happen in cases we don't care to warn about. 10046 return AnalyzeImpConvsInComparison(S, E); 10047 } 10048 10049 LHS = LHS->IgnoreParenImpCasts(); 10050 RHS = RHS->IgnoreParenImpCasts(); 10051 10052 if (!S.getLangOpts().CPlusPlus) { 10053 // Avoid warning about comparison of integers with different signs when 10054 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10055 // the type of `E`. 10056 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10057 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10058 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10059 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10060 } 10061 10062 // Check to see if one of the (unmodified) operands is of different 10063 // signedness. 10064 Expr *signedOperand, *unsignedOperand; 10065 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10066 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10067 "unsigned comparison between two signed integer expressions?"); 10068 signedOperand = LHS; 10069 unsignedOperand = RHS; 10070 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10071 signedOperand = RHS; 10072 unsignedOperand = LHS; 10073 } else { 10074 return AnalyzeImpConvsInComparison(S, E); 10075 } 10076 10077 // Otherwise, calculate the effective range of the signed operand. 10078 IntRange signedRange = GetExprRange(S.Context, signedOperand); 10079 10080 // Go ahead and analyze implicit conversions in the operands. Note 10081 // that we skip the implicit conversions on both sides. 10082 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10083 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10084 10085 // If the signed range is non-negative, -Wsign-compare won't fire. 10086 if (signedRange.NonNegative) 10087 return; 10088 10089 // For (in)equality comparisons, if the unsigned operand is a 10090 // constant which cannot collide with a overflowed signed operand, 10091 // then reinterpreting the signed operand as unsigned will not 10092 // change the result of the comparison. 10093 if (E->isEqualityOp()) { 10094 unsigned comparisonWidth = S.Context.getIntWidth(T); 10095 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 10096 10097 // We should never be unable to prove that the unsigned operand is 10098 // non-negative. 10099 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10100 10101 if (unsignedRange.Width < comparisonWidth) 10102 return; 10103 } 10104 10105 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10106 S.PDiag(diag::warn_mixed_sign_comparison) 10107 << LHS->getType() << RHS->getType() 10108 << LHS->getSourceRange() << RHS->getSourceRange()); 10109 } 10110 10111 /// Analyzes an attempt to assign the given value to a bitfield. 10112 /// 10113 /// Returns true if there was something fishy about the attempt. 10114 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10115 SourceLocation InitLoc) { 10116 assert(Bitfield->isBitField()); 10117 if (Bitfield->isInvalidDecl()) 10118 return false; 10119 10120 // White-list bool bitfields. 10121 QualType BitfieldType = Bitfield->getType(); 10122 if (BitfieldType->isBooleanType()) 10123 return false; 10124 10125 if (BitfieldType->isEnumeralType()) { 10126 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10127 // If the underlying enum type was not explicitly specified as an unsigned 10128 // type and the enum contain only positive values, MSVC++ will cause an 10129 // inconsistency by storing this as a signed type. 10130 if (S.getLangOpts().CPlusPlus11 && 10131 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10132 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10133 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10134 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10135 << BitfieldEnumDecl->getNameAsString(); 10136 } 10137 } 10138 10139 if (Bitfield->getType()->isBooleanType()) 10140 return false; 10141 10142 // Ignore value- or type-dependent expressions. 10143 if (Bitfield->getBitWidth()->isValueDependent() || 10144 Bitfield->getBitWidth()->isTypeDependent() || 10145 Init->isValueDependent() || 10146 Init->isTypeDependent()) 10147 return false; 10148 10149 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10150 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10151 10152 llvm::APSInt Value; 10153 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 10154 Expr::SE_AllowSideEffects)) { 10155 // The RHS is not constant. If the RHS has an enum type, make sure the 10156 // bitfield is wide enough to hold all the values of the enum without 10157 // truncation. 10158 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10159 EnumDecl *ED = EnumTy->getDecl(); 10160 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10161 10162 // Enum types are implicitly signed on Windows, so check if there are any 10163 // negative enumerators to see if the enum was intended to be signed or 10164 // not. 10165 bool SignedEnum = ED->getNumNegativeBits() > 0; 10166 10167 // Check for surprising sign changes when assigning enum values to a 10168 // bitfield of different signedness. If the bitfield is signed and we 10169 // have exactly the right number of bits to store this unsigned enum, 10170 // suggest changing the enum to an unsigned type. This typically happens 10171 // on Windows where unfixed enums always use an underlying type of 'int'. 10172 unsigned DiagID = 0; 10173 if (SignedEnum && !SignedBitfield) { 10174 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10175 } else if (SignedBitfield && !SignedEnum && 10176 ED->getNumPositiveBits() == FieldWidth) { 10177 DiagID = diag::warn_signed_bitfield_enum_conversion; 10178 } 10179 10180 if (DiagID) { 10181 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10182 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10183 SourceRange TypeRange = 10184 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10185 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10186 << SignedEnum << TypeRange; 10187 } 10188 10189 // Compute the required bitwidth. If the enum has negative values, we need 10190 // one more bit than the normal number of positive bits to represent the 10191 // sign bit. 10192 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10193 ED->getNumNegativeBits()) 10194 : ED->getNumPositiveBits(); 10195 10196 // Check the bitwidth. 10197 if (BitsNeeded > FieldWidth) { 10198 Expr *WidthExpr = Bitfield->getBitWidth(); 10199 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10200 << Bitfield << ED; 10201 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10202 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10203 } 10204 } 10205 10206 return false; 10207 } 10208 10209 unsigned OriginalWidth = Value.getBitWidth(); 10210 10211 if (!Value.isSigned() || Value.isNegative()) 10212 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10213 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10214 OriginalWidth = Value.getMinSignedBits(); 10215 10216 if (OriginalWidth <= FieldWidth) 10217 return false; 10218 10219 // Compute the value which the bitfield will contain. 10220 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10221 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10222 10223 // Check whether the stored value is equal to the original value. 10224 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10225 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10226 return false; 10227 10228 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10229 // therefore don't strictly fit into a signed bitfield of width 1. 10230 if (FieldWidth == 1 && Value == 1) 10231 return false; 10232 10233 std::string PrettyValue = Value.toString(10); 10234 std::string PrettyTrunc = TruncatedValue.toString(10); 10235 10236 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10237 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10238 << Init->getSourceRange(); 10239 10240 return true; 10241 } 10242 10243 /// Analyze the given simple or compound assignment for warning-worthy 10244 /// operations. 10245 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10246 // Just recurse on the LHS. 10247 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10248 10249 // We want to recurse on the RHS as normal unless we're assigning to 10250 // a bitfield. 10251 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10252 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10253 E->getOperatorLoc())) { 10254 // Recurse, ignoring any implicit conversions on the RHS. 10255 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10256 E->getOperatorLoc()); 10257 } 10258 } 10259 10260 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10261 } 10262 10263 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10264 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10265 SourceLocation CContext, unsigned diag, 10266 bool pruneControlFlow = false) { 10267 if (pruneControlFlow) { 10268 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10269 S.PDiag(diag) 10270 << SourceType << T << E->getSourceRange() 10271 << SourceRange(CContext)); 10272 return; 10273 } 10274 S.Diag(E->getExprLoc(), diag) 10275 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10276 } 10277 10278 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10279 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10280 SourceLocation CContext, 10281 unsigned diag, bool pruneControlFlow = false) { 10282 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10283 } 10284 10285 /// Analyze the given compound assignment for the possible losing of 10286 /// floating-point precision. 10287 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10288 assert(isa<CompoundAssignOperator>(E) && 10289 "Must be compound assignment operation"); 10290 // Recurse on the LHS and RHS in here 10291 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10292 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10293 10294 // Now check the outermost expression 10295 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10296 const auto *RBT = cast<CompoundAssignOperator>(E) 10297 ->getComputationResultType() 10298 ->getAs<BuiltinType>(); 10299 10300 // If both source and target are floating points. 10301 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint()) 10302 // Builtin FP kinds are ordered by increasing FP rank. 10303 if (ResultBT->getKind() < RBT->getKind()) 10304 // We don't want to warn for system macro. 10305 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10306 // warn about dropping FP rank. 10307 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), 10308 E->getOperatorLoc(), 10309 diag::warn_impcast_float_result_precision); 10310 } 10311 10312 /// Diagnose an implicit cast from a floating point value to an integer value. 10313 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10314 SourceLocation CContext) { 10315 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10316 const bool PruneWarnings = S.inTemplateInstantiation(); 10317 10318 Expr *InnerE = E->IgnoreParenImpCasts(); 10319 // We also want to warn on, e.g., "int i = -1.234" 10320 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10321 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10322 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10323 10324 const bool IsLiteral = 10325 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10326 10327 llvm::APFloat Value(0.0); 10328 bool IsConstant = 10329 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10330 if (!IsConstant) { 10331 return DiagnoseImpCast(S, E, T, CContext, 10332 diag::warn_impcast_float_integer, PruneWarnings); 10333 } 10334 10335 bool isExact = false; 10336 10337 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10338 T->hasUnsignedIntegerRepresentation()); 10339 llvm::APFloat::opStatus Result = Value.convertToInteger( 10340 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10341 10342 if (Result == llvm::APFloat::opOK && isExact) { 10343 if (IsLiteral) return; 10344 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10345 PruneWarnings); 10346 } 10347 10348 // Conversion of a floating-point value to a non-bool integer where the 10349 // integral part cannot be represented by the integer type is undefined. 10350 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10351 return DiagnoseImpCast( 10352 S, E, T, CContext, 10353 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10354 : diag::warn_impcast_float_to_integer_out_of_range, 10355 PruneWarnings); 10356 10357 unsigned DiagID = 0; 10358 if (IsLiteral) { 10359 // Warn on floating point literal to integer. 10360 DiagID = diag::warn_impcast_literal_float_to_integer; 10361 } else if (IntegerValue == 0) { 10362 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10363 return DiagnoseImpCast(S, E, T, CContext, 10364 diag::warn_impcast_float_integer, PruneWarnings); 10365 } 10366 // Warn on non-zero to zero conversion. 10367 DiagID = diag::warn_impcast_float_to_integer_zero; 10368 } else { 10369 if (IntegerValue.isUnsigned()) { 10370 if (!IntegerValue.isMaxValue()) { 10371 return DiagnoseImpCast(S, E, T, CContext, 10372 diag::warn_impcast_float_integer, PruneWarnings); 10373 } 10374 } else { // IntegerValue.isSigned() 10375 if (!IntegerValue.isMaxSignedValue() && 10376 !IntegerValue.isMinSignedValue()) { 10377 return DiagnoseImpCast(S, E, T, CContext, 10378 diag::warn_impcast_float_integer, PruneWarnings); 10379 } 10380 } 10381 // Warn on evaluatable floating point expression to integer conversion. 10382 DiagID = diag::warn_impcast_float_to_integer; 10383 } 10384 10385 // FIXME: Force the precision of the source value down so we don't print 10386 // digits which are usually useless (we don't really care here if we 10387 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10388 // would automatically print the shortest representation, but it's a bit 10389 // tricky to implement. 10390 SmallString<16> PrettySourceValue; 10391 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10392 precision = (precision * 59 + 195) / 196; 10393 Value.toString(PrettySourceValue, precision); 10394 10395 SmallString<16> PrettyTargetValue; 10396 if (IsBool) 10397 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10398 else 10399 IntegerValue.toString(PrettyTargetValue); 10400 10401 if (PruneWarnings) { 10402 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10403 S.PDiag(DiagID) 10404 << E->getType() << T.getUnqualifiedType() 10405 << PrettySourceValue << PrettyTargetValue 10406 << E->getSourceRange() << SourceRange(CContext)); 10407 } else { 10408 S.Diag(E->getExprLoc(), DiagID) 10409 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10410 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10411 } 10412 } 10413 10414 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10415 IntRange Range) { 10416 if (!Range.Width) return "0"; 10417 10418 llvm::APSInt ValueInRange = Value; 10419 ValueInRange.setIsSigned(!Range.NonNegative); 10420 ValueInRange = ValueInRange.trunc(Range.Width); 10421 return ValueInRange.toString(10); 10422 } 10423 10424 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10425 if (!isa<ImplicitCastExpr>(Ex)) 10426 return false; 10427 10428 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10429 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10430 const Type *Source = 10431 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10432 if (Target->isDependentType()) 10433 return false; 10434 10435 const BuiltinType *FloatCandidateBT = 10436 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10437 const Type *BoolCandidateType = ToBool ? Target : Source; 10438 10439 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10440 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10441 } 10442 10443 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10444 SourceLocation CC) { 10445 unsigned NumArgs = TheCall->getNumArgs(); 10446 for (unsigned i = 0; i < NumArgs; ++i) { 10447 Expr *CurrA = TheCall->getArg(i); 10448 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10449 continue; 10450 10451 bool IsSwapped = ((i > 0) && 10452 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10453 IsSwapped |= ((i < (NumArgs - 1)) && 10454 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10455 if (IsSwapped) { 10456 // Warn on this floating-point to bool conversion. 10457 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10458 CurrA->getType(), CC, 10459 diag::warn_impcast_floating_point_to_bool); 10460 } 10461 } 10462 } 10463 10464 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10465 SourceLocation CC) { 10466 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10467 E->getExprLoc())) 10468 return; 10469 10470 // Don't warn on functions which have return type nullptr_t. 10471 if (isa<CallExpr>(E)) 10472 return; 10473 10474 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10475 const Expr::NullPointerConstantKind NullKind = 10476 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10477 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10478 return; 10479 10480 // Return if target type is a safe conversion. 10481 if (T->isAnyPointerType() || T->isBlockPointerType() || 10482 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10483 return; 10484 10485 SourceLocation Loc = E->getSourceRange().getBegin(); 10486 10487 // Venture through the macro stacks to get to the source of macro arguments. 10488 // The new location is a better location than the complete location that was 10489 // passed in. 10490 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10491 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10492 10493 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10494 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10495 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10496 Loc, S.SourceMgr, S.getLangOpts()); 10497 if (MacroName == "NULL") 10498 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10499 } 10500 10501 // Only warn if the null and context location are in the same macro expansion. 10502 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10503 return; 10504 10505 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10506 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10507 << FixItHint::CreateReplacement(Loc, 10508 S.getFixItZeroLiteralForType(T, Loc)); 10509 } 10510 10511 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10512 ObjCArrayLiteral *ArrayLiteral); 10513 10514 static void 10515 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10516 ObjCDictionaryLiteral *DictionaryLiteral); 10517 10518 /// Check a single element within a collection literal against the 10519 /// target element type. 10520 static void checkObjCCollectionLiteralElement(Sema &S, 10521 QualType TargetElementType, 10522 Expr *Element, 10523 unsigned ElementKind) { 10524 // Skip a bitcast to 'id' or qualified 'id'. 10525 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10526 if (ICE->getCastKind() == CK_BitCast && 10527 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10528 Element = ICE->getSubExpr(); 10529 } 10530 10531 QualType ElementType = Element->getType(); 10532 ExprResult ElementResult(Element); 10533 if (ElementType->getAs<ObjCObjectPointerType>() && 10534 S.CheckSingleAssignmentConstraints(TargetElementType, 10535 ElementResult, 10536 false, false) 10537 != Sema::Compatible) { 10538 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 10539 << ElementType << ElementKind << TargetElementType 10540 << Element->getSourceRange(); 10541 } 10542 10543 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10544 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10545 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10546 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10547 } 10548 10549 /// Check an Objective-C array literal being converted to the given 10550 /// target type. 10551 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10552 ObjCArrayLiteral *ArrayLiteral) { 10553 if (!S.NSArrayDecl) 10554 return; 10555 10556 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10557 if (!TargetObjCPtr) 10558 return; 10559 10560 if (TargetObjCPtr->isUnspecialized() || 10561 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10562 != S.NSArrayDecl->getCanonicalDecl()) 10563 return; 10564 10565 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10566 if (TypeArgs.size() != 1) 10567 return; 10568 10569 QualType TargetElementType = TypeArgs[0]; 10570 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10571 checkObjCCollectionLiteralElement(S, TargetElementType, 10572 ArrayLiteral->getElement(I), 10573 0); 10574 } 10575 } 10576 10577 /// Check an Objective-C dictionary literal being converted to the given 10578 /// target type. 10579 static void 10580 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10581 ObjCDictionaryLiteral *DictionaryLiteral) { 10582 if (!S.NSDictionaryDecl) 10583 return; 10584 10585 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10586 if (!TargetObjCPtr) 10587 return; 10588 10589 if (TargetObjCPtr->isUnspecialized() || 10590 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10591 != S.NSDictionaryDecl->getCanonicalDecl()) 10592 return; 10593 10594 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10595 if (TypeArgs.size() != 2) 10596 return; 10597 10598 QualType TargetKeyType = TypeArgs[0]; 10599 QualType TargetObjectType = TypeArgs[1]; 10600 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10601 auto Element = DictionaryLiteral->getKeyValueElement(I); 10602 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10603 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10604 } 10605 } 10606 10607 // Helper function to filter out cases for constant width constant conversion. 10608 // Don't warn on char array initialization or for non-decimal values. 10609 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10610 SourceLocation CC) { 10611 // If initializing from a constant, and the constant starts with '0', 10612 // then it is a binary, octal, or hexadecimal. Allow these constants 10613 // to fill all the bits, even if there is a sign change. 10614 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10615 const char FirstLiteralCharacter = 10616 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 10617 if (FirstLiteralCharacter == '0') 10618 return false; 10619 } 10620 10621 // If the CC location points to a '{', and the type is char, then assume 10622 // assume it is an array initialization. 10623 if (CC.isValid() && T->isCharType()) { 10624 const char FirstContextCharacter = 10625 S.getSourceManager().getCharacterData(CC)[0]; 10626 if (FirstContextCharacter == '{') 10627 return false; 10628 } 10629 10630 return true; 10631 } 10632 10633 static void 10634 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10635 bool *ICContext = nullptr) { 10636 if (E->isTypeDependent() || E->isValueDependent()) return; 10637 10638 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10639 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10640 if (Source == Target) return; 10641 if (Target->isDependentType()) return; 10642 10643 // If the conversion context location is invalid don't complain. We also 10644 // don't want to emit a warning if the issue occurs from the expansion of 10645 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10646 // delay this check as long as possible. Once we detect we are in that 10647 // scenario, we just return. 10648 if (CC.isInvalid()) 10649 return; 10650 10651 // Diagnose implicit casts to bool. 10652 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10653 if (isa<StringLiteral>(E)) 10654 // Warn on string literal to bool. Checks for string literals in logical 10655 // and expressions, for instance, assert(0 && "error here"), are 10656 // prevented by a check in AnalyzeImplicitConversions(). 10657 return DiagnoseImpCast(S, E, T, CC, 10658 diag::warn_impcast_string_literal_to_bool); 10659 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10660 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10661 // This covers the literal expressions that evaluate to Objective-C 10662 // objects. 10663 return DiagnoseImpCast(S, E, T, CC, 10664 diag::warn_impcast_objective_c_literal_to_bool); 10665 } 10666 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10667 // Warn on pointer to bool conversion that is always true. 10668 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10669 SourceRange(CC)); 10670 } 10671 } 10672 10673 // Check implicit casts from Objective-C collection literals to specialized 10674 // collection types, e.g., NSArray<NSString *> *. 10675 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10676 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10677 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10678 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10679 10680 // Strip vector types. 10681 if (isa<VectorType>(Source)) { 10682 if (!isa<VectorType>(Target)) { 10683 if (S.SourceMgr.isInSystemMacro(CC)) 10684 return; 10685 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10686 } 10687 10688 // If the vector cast is cast between two vectors of the same size, it is 10689 // a bitcast, not a conversion. 10690 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10691 return; 10692 10693 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10694 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10695 } 10696 if (auto VecTy = dyn_cast<VectorType>(Target)) 10697 Target = VecTy->getElementType().getTypePtr(); 10698 10699 // Strip complex types. 10700 if (isa<ComplexType>(Source)) { 10701 if (!isa<ComplexType>(Target)) { 10702 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10703 return; 10704 10705 return DiagnoseImpCast(S, E, T, CC, 10706 S.getLangOpts().CPlusPlus 10707 ? diag::err_impcast_complex_scalar 10708 : diag::warn_impcast_complex_scalar); 10709 } 10710 10711 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10712 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10713 } 10714 10715 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10716 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10717 10718 // If the source is floating point... 10719 if (SourceBT && SourceBT->isFloatingPoint()) { 10720 // ...and the target is floating point... 10721 if (TargetBT && TargetBT->isFloatingPoint()) { 10722 // ...then warn if we're dropping FP rank. 10723 10724 // Builtin FP kinds are ordered by increasing FP rank. 10725 if (SourceBT->getKind() > TargetBT->getKind()) { 10726 // Don't warn about float constants that are precisely 10727 // representable in the target type. 10728 Expr::EvalResult result; 10729 if (E->EvaluateAsRValue(result, S.Context)) { 10730 // Value might be a float, a float vector, or a float complex. 10731 if (IsSameFloatAfterCast(result.Val, 10732 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10733 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10734 return; 10735 } 10736 10737 if (S.SourceMgr.isInSystemMacro(CC)) 10738 return; 10739 10740 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10741 } 10742 // ... or possibly if we're increasing rank, too 10743 else if (TargetBT->getKind() > SourceBT->getKind()) { 10744 if (S.SourceMgr.isInSystemMacro(CC)) 10745 return; 10746 10747 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10748 } 10749 return; 10750 } 10751 10752 // If the target is integral, always warn. 10753 if (TargetBT && TargetBT->isInteger()) { 10754 if (S.SourceMgr.isInSystemMacro(CC)) 10755 return; 10756 10757 DiagnoseFloatingImpCast(S, E, T, CC); 10758 } 10759 10760 // Detect the case where a call result is converted from floating-point to 10761 // to bool, and the final argument to the call is converted from bool, to 10762 // discover this typo: 10763 // 10764 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10765 // 10766 // FIXME: This is an incredibly special case; is there some more general 10767 // way to detect this class of misplaced-parentheses bug? 10768 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10769 // Check last argument of function call to see if it is an 10770 // implicit cast from a type matching the type the result 10771 // is being cast to. 10772 CallExpr *CEx = cast<CallExpr>(E); 10773 if (unsigned NumArgs = CEx->getNumArgs()) { 10774 Expr *LastA = CEx->getArg(NumArgs - 1); 10775 Expr *InnerE = LastA->IgnoreParenImpCasts(); 10776 if (isa<ImplicitCastExpr>(LastA) && 10777 InnerE->getType()->isBooleanType()) { 10778 // Warn on this floating-point to bool conversion 10779 DiagnoseImpCast(S, E, T, CC, 10780 diag::warn_impcast_floating_point_to_bool); 10781 } 10782 } 10783 } 10784 return; 10785 } 10786 10787 DiagnoseNullConversion(S, E, T, CC); 10788 10789 S.DiscardMisalignedMemberAddress(Target, E); 10790 10791 if (!Source->isIntegerType() || !Target->isIntegerType()) 10792 return; 10793 10794 // TODO: remove this early return once the false positives for constant->bool 10795 // in templates, macros, etc, are reduced or removed. 10796 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 10797 return; 10798 10799 IntRange SourceRange = GetExprRange(S.Context, E); 10800 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 10801 10802 if (SourceRange.Width > TargetRange.Width) { 10803 // If the source is a constant, use a default-on diagnostic. 10804 // TODO: this should happen for bitfield stores, too. 10805 llvm::APSInt Value(32); 10806 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 10807 if (S.SourceMgr.isInSystemMacro(CC)) 10808 return; 10809 10810 std::string PrettySourceValue = Value.toString(10); 10811 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10812 10813 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10814 S.PDiag(diag::warn_impcast_integer_precision_constant) 10815 << PrettySourceValue << PrettyTargetValue 10816 << E->getType() << T << E->getSourceRange() 10817 << clang::SourceRange(CC)); 10818 return; 10819 } 10820 10821 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 10822 if (S.SourceMgr.isInSystemMacro(CC)) 10823 return; 10824 10825 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 10826 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 10827 /* pruneControlFlow */ true); 10828 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 10829 } 10830 10831 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 10832 SourceRange.NonNegative && Source->isSignedIntegerType()) { 10833 // Warn when doing a signed to signed conversion, warn if the positive 10834 // source value is exactly the width of the target type, which will 10835 // cause a negative value to be stored. 10836 10837 llvm::APSInt Value; 10838 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 10839 !S.SourceMgr.isInSystemMacro(CC)) { 10840 if (isSameWidthConstantConversion(S, E, T, CC)) { 10841 std::string PrettySourceValue = Value.toString(10); 10842 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10843 10844 S.DiagRuntimeBehavior( 10845 E->getExprLoc(), E, 10846 S.PDiag(diag::warn_impcast_integer_precision_constant) 10847 << PrettySourceValue << PrettyTargetValue << E->getType() << T 10848 << E->getSourceRange() << clang::SourceRange(CC)); 10849 return; 10850 } 10851 } 10852 10853 // Fall through for non-constants to give a sign conversion warning. 10854 } 10855 10856 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 10857 (!TargetRange.NonNegative && SourceRange.NonNegative && 10858 SourceRange.Width == TargetRange.Width)) { 10859 if (S.SourceMgr.isInSystemMacro(CC)) 10860 return; 10861 10862 unsigned DiagID = diag::warn_impcast_integer_sign; 10863 10864 // Traditionally, gcc has warned about this under -Wsign-compare. 10865 // We also want to warn about it in -Wconversion. 10866 // So if -Wconversion is off, use a completely identical diagnostic 10867 // in the sign-compare group. 10868 // The conditional-checking code will 10869 if (ICContext) { 10870 DiagID = diag::warn_impcast_integer_sign_conditional; 10871 *ICContext = true; 10872 } 10873 10874 return DiagnoseImpCast(S, E, T, CC, DiagID); 10875 } 10876 10877 // Diagnose conversions between different enumeration types. 10878 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 10879 // type, to give us better diagnostics. 10880 QualType SourceType = E->getType(); 10881 if (!S.getLangOpts().CPlusPlus) { 10882 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10883 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 10884 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 10885 SourceType = S.Context.getTypeDeclType(Enum); 10886 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 10887 } 10888 } 10889 10890 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 10891 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 10892 if (SourceEnum->getDecl()->hasNameForLinkage() && 10893 TargetEnum->getDecl()->hasNameForLinkage() && 10894 SourceEnum != TargetEnum) { 10895 if (S.SourceMgr.isInSystemMacro(CC)) 10896 return; 10897 10898 return DiagnoseImpCast(S, E, SourceType, T, CC, 10899 diag::warn_impcast_different_enum_types); 10900 } 10901 } 10902 10903 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10904 SourceLocation CC, QualType T); 10905 10906 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 10907 SourceLocation CC, bool &ICContext) { 10908 E = E->IgnoreParenImpCasts(); 10909 10910 if (isa<ConditionalOperator>(E)) 10911 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 10912 10913 AnalyzeImplicitConversions(S, E, CC); 10914 if (E->getType() != T) 10915 return CheckImplicitConversion(S, E, T, CC, &ICContext); 10916 } 10917 10918 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10919 SourceLocation CC, QualType T) { 10920 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 10921 10922 bool Suspicious = false; 10923 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 10924 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 10925 10926 // If -Wconversion would have warned about either of the candidates 10927 // for a signedness conversion to the context type... 10928 if (!Suspicious) return; 10929 10930 // ...but it's currently ignored... 10931 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 10932 return; 10933 10934 // ...then check whether it would have warned about either of the 10935 // candidates for a signedness conversion to the condition type. 10936 if (E->getType() == T) return; 10937 10938 Suspicious = false; 10939 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 10940 E->getType(), CC, &Suspicious); 10941 if (!Suspicious) 10942 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 10943 E->getType(), CC, &Suspicious); 10944 } 10945 10946 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10947 /// Input argument E is a logical expression. 10948 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 10949 if (S.getLangOpts().Bool) 10950 return; 10951 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 10952 } 10953 10954 /// AnalyzeImplicitConversions - Find and report any interesting 10955 /// implicit conversions in the given expression. There are a couple 10956 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 10957 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 10958 SourceLocation CC) { 10959 QualType T = OrigE->getType(); 10960 Expr *E = OrigE->IgnoreParenImpCasts(); 10961 10962 if (E->isTypeDependent() || E->isValueDependent()) 10963 return; 10964 10965 // For conditional operators, we analyze the arguments as if they 10966 // were being fed directly into the output. 10967 if (isa<ConditionalOperator>(E)) { 10968 ConditionalOperator *CO = cast<ConditionalOperator>(E); 10969 CheckConditionalOperator(S, CO, CC, T); 10970 return; 10971 } 10972 10973 // Check implicit argument conversions for function calls. 10974 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 10975 CheckImplicitArgumentConversions(S, Call, CC); 10976 10977 // Go ahead and check any implicit conversions we might have skipped. 10978 // The non-canonical typecheck is just an optimization; 10979 // CheckImplicitConversion will filter out dead implicit conversions. 10980 if (E->getType() != T) 10981 CheckImplicitConversion(S, E, T, CC); 10982 10983 // Now continue drilling into this expression. 10984 10985 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 10986 // The bound subexpressions in a PseudoObjectExpr are not reachable 10987 // as transitive children. 10988 // FIXME: Use a more uniform representation for this. 10989 for (auto *SE : POE->semantics()) 10990 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 10991 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 10992 } 10993 10994 // Skip past explicit casts. 10995 if (isa<ExplicitCastExpr>(E)) { 10996 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 10997 return AnalyzeImplicitConversions(S, E, CC); 10998 } 10999 11000 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11001 // Do a somewhat different check with comparison operators. 11002 if (BO->isComparisonOp()) 11003 return AnalyzeComparison(S, BO); 11004 11005 // And with simple assignments. 11006 if (BO->getOpcode() == BO_Assign) 11007 return AnalyzeAssignment(S, BO); 11008 // And with compound assignments. 11009 if (BO->isAssignmentOp()) 11010 return AnalyzeCompoundAssignment(S, BO); 11011 } 11012 11013 // These break the otherwise-useful invariant below. Fortunately, 11014 // we don't really need to recurse into them, because any internal 11015 // expressions should have been analyzed already when they were 11016 // built into statements. 11017 if (isa<StmtExpr>(E)) return; 11018 11019 // Don't descend into unevaluated contexts. 11020 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11021 11022 // Now just recurse over the expression's children. 11023 CC = E->getExprLoc(); 11024 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11025 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11026 for (Stmt *SubStmt : E->children()) { 11027 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11028 if (!ChildExpr) 11029 continue; 11030 11031 if (IsLogicalAndOperator && 11032 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11033 // Ignore checking string literals that are in logical and operators. 11034 // This is a common pattern for asserts. 11035 continue; 11036 AnalyzeImplicitConversions(S, ChildExpr, CC); 11037 } 11038 11039 if (BO && BO->isLogicalOp()) { 11040 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11041 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11042 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11043 11044 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11045 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11046 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11047 } 11048 11049 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 11050 if (U->getOpcode() == UO_LNot) 11051 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11052 } 11053 11054 /// Diagnose integer type and any valid implicit conversion to it. 11055 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11056 // Taking into account implicit conversions, 11057 // allow any integer. 11058 if (!E->getType()->isIntegerType()) { 11059 S.Diag(E->getBeginLoc(), 11060 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11061 return true; 11062 } 11063 // Potentially emit standard warnings for implicit conversions if enabled 11064 // using -Wconversion. 11065 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11066 return false; 11067 } 11068 11069 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11070 // Returns true when emitting a warning about taking the address of a reference. 11071 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11072 const PartialDiagnostic &PD) { 11073 E = E->IgnoreParenImpCasts(); 11074 11075 const FunctionDecl *FD = nullptr; 11076 11077 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11078 if (!DRE->getDecl()->getType()->isReferenceType()) 11079 return false; 11080 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11081 if (!M->getMemberDecl()->getType()->isReferenceType()) 11082 return false; 11083 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11084 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11085 return false; 11086 FD = Call->getDirectCallee(); 11087 } else { 11088 return false; 11089 } 11090 11091 SemaRef.Diag(E->getExprLoc(), PD); 11092 11093 // If possible, point to location of function. 11094 if (FD) { 11095 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11096 } 11097 11098 return true; 11099 } 11100 11101 // Returns true if the SourceLocation is expanded from any macro body. 11102 // Returns false if the SourceLocation is invalid, is from not in a macro 11103 // expansion, or is from expanded from a top-level macro argument. 11104 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11105 if (Loc.isInvalid()) 11106 return false; 11107 11108 while (Loc.isMacroID()) { 11109 if (SM.isMacroBodyExpansion(Loc)) 11110 return true; 11111 Loc = SM.getImmediateMacroCallerLoc(Loc); 11112 } 11113 11114 return false; 11115 } 11116 11117 /// Diagnose pointers that are always non-null. 11118 /// \param E the expression containing the pointer 11119 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11120 /// compared to a null pointer 11121 /// \param IsEqual True when the comparison is equal to a null pointer 11122 /// \param Range Extra SourceRange to highlight in the diagnostic 11123 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11124 Expr::NullPointerConstantKind NullKind, 11125 bool IsEqual, SourceRange Range) { 11126 if (!E) 11127 return; 11128 11129 // Don't warn inside macros. 11130 if (E->getExprLoc().isMacroID()) { 11131 const SourceManager &SM = getSourceManager(); 11132 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11133 IsInAnyMacroBody(SM, Range.getBegin())) 11134 return; 11135 } 11136 E = E->IgnoreImpCasts(); 11137 11138 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11139 11140 if (isa<CXXThisExpr>(E)) { 11141 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11142 : diag::warn_this_bool_conversion; 11143 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11144 return; 11145 } 11146 11147 bool IsAddressOf = false; 11148 11149 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11150 if (UO->getOpcode() != UO_AddrOf) 11151 return; 11152 IsAddressOf = true; 11153 E = UO->getSubExpr(); 11154 } 11155 11156 if (IsAddressOf) { 11157 unsigned DiagID = IsCompare 11158 ? diag::warn_address_of_reference_null_compare 11159 : diag::warn_address_of_reference_bool_conversion; 11160 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11161 << IsEqual; 11162 if (CheckForReference(*this, E, PD)) { 11163 return; 11164 } 11165 } 11166 11167 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11168 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11169 std::string Str; 11170 llvm::raw_string_ostream S(Str); 11171 E->printPretty(S, nullptr, getPrintingPolicy()); 11172 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11173 : diag::warn_cast_nonnull_to_bool; 11174 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11175 << E->getSourceRange() << Range << IsEqual; 11176 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11177 }; 11178 11179 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11180 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11181 if (auto *Callee = Call->getDirectCallee()) { 11182 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11183 ComplainAboutNonnullParamOrCall(A); 11184 return; 11185 } 11186 } 11187 } 11188 11189 // Expect to find a single Decl. Skip anything more complicated. 11190 ValueDecl *D = nullptr; 11191 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11192 D = R->getDecl(); 11193 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11194 D = M->getMemberDecl(); 11195 } 11196 11197 // Weak Decls can be null. 11198 if (!D || D->isWeak()) 11199 return; 11200 11201 // Check for parameter decl with nonnull attribute 11202 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11203 if (getCurFunction() && 11204 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11205 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11206 ComplainAboutNonnullParamOrCall(A); 11207 return; 11208 } 11209 11210 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11211 auto ParamIter = llvm::find(FD->parameters(), PV); 11212 assert(ParamIter != FD->param_end()); 11213 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11214 11215 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11216 if (!NonNull->args_size()) { 11217 ComplainAboutNonnullParamOrCall(NonNull); 11218 return; 11219 } 11220 11221 for (const ParamIdx &ArgNo : NonNull->args()) { 11222 if (ArgNo.getASTIndex() == ParamNo) { 11223 ComplainAboutNonnullParamOrCall(NonNull); 11224 return; 11225 } 11226 } 11227 } 11228 } 11229 } 11230 } 11231 11232 QualType T = D->getType(); 11233 const bool IsArray = T->isArrayType(); 11234 const bool IsFunction = T->isFunctionType(); 11235 11236 // Address of function is used to silence the function warning. 11237 if (IsAddressOf && IsFunction) { 11238 return; 11239 } 11240 11241 // Found nothing. 11242 if (!IsAddressOf && !IsFunction && !IsArray) 11243 return; 11244 11245 // Pretty print the expression for the diagnostic. 11246 std::string Str; 11247 llvm::raw_string_ostream S(Str); 11248 E->printPretty(S, nullptr, getPrintingPolicy()); 11249 11250 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11251 : diag::warn_impcast_pointer_to_bool; 11252 enum { 11253 AddressOf, 11254 FunctionPointer, 11255 ArrayPointer 11256 } DiagType; 11257 if (IsAddressOf) 11258 DiagType = AddressOf; 11259 else if (IsFunction) 11260 DiagType = FunctionPointer; 11261 else if (IsArray) 11262 DiagType = ArrayPointer; 11263 else 11264 llvm_unreachable("Could not determine diagnostic."); 11265 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11266 << Range << IsEqual; 11267 11268 if (!IsFunction) 11269 return; 11270 11271 // Suggest '&' to silence the function warning. 11272 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11273 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11274 11275 // Check to see if '()' fixit should be emitted. 11276 QualType ReturnType; 11277 UnresolvedSet<4> NonTemplateOverloads; 11278 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11279 if (ReturnType.isNull()) 11280 return; 11281 11282 if (IsCompare) { 11283 // There are two cases here. If there is null constant, the only suggest 11284 // for a pointer return type. If the null is 0, then suggest if the return 11285 // type is a pointer or an integer type. 11286 if (!ReturnType->isPointerType()) { 11287 if (NullKind == Expr::NPCK_ZeroExpression || 11288 NullKind == Expr::NPCK_ZeroLiteral) { 11289 if (!ReturnType->isIntegerType()) 11290 return; 11291 } else { 11292 return; 11293 } 11294 } 11295 } else { // !IsCompare 11296 // For function to bool, only suggest if the function pointer has bool 11297 // return type. 11298 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11299 return; 11300 } 11301 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11302 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11303 } 11304 11305 /// Diagnoses "dangerous" implicit conversions within the given 11306 /// expression (which is a full expression). Implements -Wconversion 11307 /// and -Wsign-compare. 11308 /// 11309 /// \param CC the "context" location of the implicit conversion, i.e. 11310 /// the most location of the syntactic entity requiring the implicit 11311 /// conversion 11312 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11313 // Don't diagnose in unevaluated contexts. 11314 if (isUnevaluatedContext()) 11315 return; 11316 11317 // Don't diagnose for value- or type-dependent expressions. 11318 if (E->isTypeDependent() || E->isValueDependent()) 11319 return; 11320 11321 // Check for array bounds violations in cases where the check isn't triggered 11322 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11323 // ArraySubscriptExpr is on the RHS of a variable initialization. 11324 CheckArrayAccess(E); 11325 11326 // This is not the right CC for (e.g.) a variable initialization. 11327 AnalyzeImplicitConversions(*this, E, CC); 11328 } 11329 11330 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11331 /// Input argument E is a logical expression. 11332 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11333 ::CheckBoolLikeConversion(*this, E, CC); 11334 } 11335 11336 /// Diagnose when expression is an integer constant expression and its evaluation 11337 /// results in integer overflow 11338 void Sema::CheckForIntOverflow (Expr *E) { 11339 // Use a work list to deal with nested struct initializers. 11340 SmallVector<Expr *, 2> Exprs(1, E); 11341 11342 do { 11343 Expr *OriginalE = Exprs.pop_back_val(); 11344 Expr *E = OriginalE->IgnoreParenCasts(); 11345 11346 if (isa<BinaryOperator>(E)) { 11347 E->EvaluateForOverflow(Context); 11348 continue; 11349 } 11350 11351 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11352 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11353 else if (isa<ObjCBoxedExpr>(OriginalE)) 11354 E->EvaluateForOverflow(Context); 11355 else if (auto Call = dyn_cast<CallExpr>(E)) 11356 Exprs.append(Call->arg_begin(), Call->arg_end()); 11357 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 11358 Exprs.append(Message->arg_begin(), Message->arg_end()); 11359 } while (!Exprs.empty()); 11360 } 11361 11362 namespace { 11363 11364 /// Visitor for expressions which looks for unsequenced operations on the 11365 /// same object. 11366 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 11367 using Base = EvaluatedExprVisitor<SequenceChecker>; 11368 11369 /// A tree of sequenced regions within an expression. Two regions are 11370 /// unsequenced if one is an ancestor or a descendent of the other. When we 11371 /// finish processing an expression with sequencing, such as a comma 11372 /// expression, we fold its tree nodes into its parent, since they are 11373 /// unsequenced with respect to nodes we will visit later. 11374 class SequenceTree { 11375 struct Value { 11376 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 11377 unsigned Parent : 31; 11378 unsigned Merged : 1; 11379 }; 11380 SmallVector<Value, 8> Values; 11381 11382 public: 11383 /// A region within an expression which may be sequenced with respect 11384 /// to some other region. 11385 class Seq { 11386 friend class SequenceTree; 11387 11388 unsigned Index = 0; 11389 11390 explicit Seq(unsigned N) : Index(N) {} 11391 11392 public: 11393 Seq() = default; 11394 }; 11395 11396 SequenceTree() { Values.push_back(Value(0)); } 11397 Seq root() const { return Seq(0); } 11398 11399 /// Create a new sequence of operations, which is an unsequenced 11400 /// subset of \p Parent. This sequence of operations is sequenced with 11401 /// respect to other children of \p Parent. 11402 Seq allocate(Seq Parent) { 11403 Values.push_back(Value(Parent.Index)); 11404 return Seq(Values.size() - 1); 11405 } 11406 11407 /// Merge a sequence of operations into its parent. 11408 void merge(Seq S) { 11409 Values[S.Index].Merged = true; 11410 } 11411 11412 /// Determine whether two operations are unsequenced. This operation 11413 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 11414 /// should have been merged into its parent as appropriate. 11415 bool isUnsequenced(Seq Cur, Seq Old) { 11416 unsigned C = representative(Cur.Index); 11417 unsigned Target = representative(Old.Index); 11418 while (C >= Target) { 11419 if (C == Target) 11420 return true; 11421 C = Values[C].Parent; 11422 } 11423 return false; 11424 } 11425 11426 private: 11427 /// Pick a representative for a sequence. 11428 unsigned representative(unsigned K) { 11429 if (Values[K].Merged) 11430 // Perform path compression as we go. 11431 return Values[K].Parent = representative(Values[K].Parent); 11432 return K; 11433 } 11434 }; 11435 11436 /// An object for which we can track unsequenced uses. 11437 using Object = NamedDecl *; 11438 11439 /// Different flavors of object usage which we track. We only track the 11440 /// least-sequenced usage of each kind. 11441 enum UsageKind { 11442 /// A read of an object. Multiple unsequenced reads are OK. 11443 UK_Use, 11444 11445 /// A modification of an object which is sequenced before the value 11446 /// computation of the expression, such as ++n in C++. 11447 UK_ModAsValue, 11448 11449 /// A modification of an object which is not sequenced before the value 11450 /// computation of the expression, such as n++. 11451 UK_ModAsSideEffect, 11452 11453 UK_Count = UK_ModAsSideEffect + 1 11454 }; 11455 11456 struct Usage { 11457 Expr *Use = nullptr; 11458 SequenceTree::Seq Seq; 11459 11460 Usage() = default; 11461 }; 11462 11463 struct UsageInfo { 11464 Usage Uses[UK_Count]; 11465 11466 /// Have we issued a diagnostic for this variable already? 11467 bool Diagnosed = false; 11468 11469 UsageInfo() = default; 11470 }; 11471 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 11472 11473 Sema &SemaRef; 11474 11475 /// Sequenced regions within the expression. 11476 SequenceTree Tree; 11477 11478 /// Declaration modifications and references which we have seen. 11479 UsageInfoMap UsageMap; 11480 11481 /// The region we are currently within. 11482 SequenceTree::Seq Region; 11483 11484 /// Filled in with declarations which were modified as a side-effect 11485 /// (that is, post-increment operations). 11486 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 11487 11488 /// Expressions to check later. We defer checking these to reduce 11489 /// stack usage. 11490 SmallVectorImpl<Expr *> &WorkList; 11491 11492 /// RAII object wrapping the visitation of a sequenced subexpression of an 11493 /// expression. At the end of this process, the side-effects of the evaluation 11494 /// become sequenced with respect to the value computation of the result, so 11495 /// we downgrade any UK_ModAsSideEffect within the evaluation to 11496 /// UK_ModAsValue. 11497 struct SequencedSubexpression { 11498 SequencedSubexpression(SequenceChecker &Self) 11499 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11500 Self.ModAsSideEffect = &ModAsSideEffect; 11501 } 11502 11503 ~SequencedSubexpression() { 11504 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11505 UsageInfo &U = Self.UsageMap[M.first]; 11506 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11507 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11508 SideEffectUsage = M.second; 11509 } 11510 Self.ModAsSideEffect = OldModAsSideEffect; 11511 } 11512 11513 SequenceChecker &Self; 11514 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11515 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11516 }; 11517 11518 /// RAII object wrapping the visitation of a subexpression which we might 11519 /// choose to evaluate as a constant. If any subexpression is evaluated and 11520 /// found to be non-constant, this allows us to suppress the evaluation of 11521 /// the outer expression. 11522 class EvaluationTracker { 11523 public: 11524 EvaluationTracker(SequenceChecker &Self) 11525 : Self(Self), Prev(Self.EvalTracker) { 11526 Self.EvalTracker = this; 11527 } 11528 11529 ~EvaluationTracker() { 11530 Self.EvalTracker = Prev; 11531 if (Prev) 11532 Prev->EvalOK &= EvalOK; 11533 } 11534 11535 bool evaluate(const Expr *E, bool &Result) { 11536 if (!EvalOK || E->isValueDependent()) 11537 return false; 11538 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11539 return EvalOK; 11540 } 11541 11542 private: 11543 SequenceChecker &Self; 11544 EvaluationTracker *Prev; 11545 bool EvalOK = true; 11546 } *EvalTracker = nullptr; 11547 11548 /// Find the object which is produced by the specified expression, 11549 /// if any. 11550 Object getObject(Expr *E, bool Mod) const { 11551 E = E->IgnoreParenCasts(); 11552 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11553 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11554 return getObject(UO->getSubExpr(), Mod); 11555 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11556 if (BO->getOpcode() == BO_Comma) 11557 return getObject(BO->getRHS(), Mod); 11558 if (Mod && BO->isAssignmentOp()) 11559 return getObject(BO->getLHS(), Mod); 11560 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11561 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11562 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11563 return ME->getMemberDecl(); 11564 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11565 // FIXME: If this is a reference, map through to its value. 11566 return DRE->getDecl(); 11567 return nullptr; 11568 } 11569 11570 /// Note that an object was modified or used by an expression. 11571 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11572 Usage &U = UI.Uses[UK]; 11573 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11574 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11575 ModAsSideEffect->push_back(std::make_pair(O, U)); 11576 U.Use = Ref; 11577 U.Seq = Region; 11578 } 11579 } 11580 11581 /// Check whether a modification or use conflicts with a prior usage. 11582 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11583 bool IsModMod) { 11584 if (UI.Diagnosed) 11585 return; 11586 11587 const Usage &U = UI.Uses[OtherKind]; 11588 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11589 return; 11590 11591 Expr *Mod = U.Use; 11592 Expr *ModOrUse = Ref; 11593 if (OtherKind == UK_Use) 11594 std::swap(Mod, ModOrUse); 11595 11596 SemaRef.Diag(Mod->getExprLoc(), 11597 IsModMod ? diag::warn_unsequenced_mod_mod 11598 : diag::warn_unsequenced_mod_use) 11599 << O << SourceRange(ModOrUse->getExprLoc()); 11600 UI.Diagnosed = true; 11601 } 11602 11603 void notePreUse(Object O, Expr *Use) { 11604 UsageInfo &U = UsageMap[O]; 11605 // Uses conflict with other modifications. 11606 checkUsage(O, U, Use, UK_ModAsValue, false); 11607 } 11608 11609 void notePostUse(Object O, Expr *Use) { 11610 UsageInfo &U = UsageMap[O]; 11611 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 11612 addUsage(U, O, Use, UK_Use); 11613 } 11614 11615 void notePreMod(Object O, Expr *Mod) { 11616 UsageInfo &U = UsageMap[O]; 11617 // Modifications conflict with other modifications and with uses. 11618 checkUsage(O, U, Mod, UK_ModAsValue, true); 11619 checkUsage(O, U, Mod, UK_Use, false); 11620 } 11621 11622 void notePostMod(Object O, Expr *Use, UsageKind UK) { 11623 UsageInfo &U = UsageMap[O]; 11624 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 11625 addUsage(U, O, Use, UK); 11626 } 11627 11628 public: 11629 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 11630 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 11631 Visit(E); 11632 } 11633 11634 void VisitStmt(Stmt *S) { 11635 // Skip all statements which aren't expressions for now. 11636 } 11637 11638 void VisitExpr(Expr *E) { 11639 // By default, just recurse to evaluated subexpressions. 11640 Base::VisitStmt(E); 11641 } 11642 11643 void VisitCastExpr(CastExpr *E) { 11644 Object O = Object(); 11645 if (E->getCastKind() == CK_LValueToRValue) 11646 O = getObject(E->getSubExpr(), false); 11647 11648 if (O) 11649 notePreUse(O, E); 11650 VisitExpr(E); 11651 if (O) 11652 notePostUse(O, E); 11653 } 11654 11655 void VisitBinComma(BinaryOperator *BO) { 11656 // C++11 [expr.comma]p1: 11657 // Every value computation and side effect associated with the left 11658 // expression is sequenced before every value computation and side 11659 // effect associated with the right expression. 11660 SequenceTree::Seq LHS = Tree.allocate(Region); 11661 SequenceTree::Seq RHS = Tree.allocate(Region); 11662 SequenceTree::Seq OldRegion = Region; 11663 11664 { 11665 SequencedSubexpression SeqLHS(*this); 11666 Region = LHS; 11667 Visit(BO->getLHS()); 11668 } 11669 11670 Region = RHS; 11671 Visit(BO->getRHS()); 11672 11673 Region = OldRegion; 11674 11675 // Forget that LHS and RHS are sequenced. They are both unsequenced 11676 // with respect to other stuff. 11677 Tree.merge(LHS); 11678 Tree.merge(RHS); 11679 } 11680 11681 void VisitBinAssign(BinaryOperator *BO) { 11682 // The modification is sequenced after the value computation of the LHS 11683 // and RHS, so check it before inspecting the operands and update the 11684 // map afterwards. 11685 Object O = getObject(BO->getLHS(), true); 11686 if (!O) 11687 return VisitExpr(BO); 11688 11689 notePreMod(O, BO); 11690 11691 // C++11 [expr.ass]p7: 11692 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11693 // only once. 11694 // 11695 // Therefore, for a compound assignment operator, O is considered used 11696 // everywhere except within the evaluation of E1 itself. 11697 if (isa<CompoundAssignOperator>(BO)) 11698 notePreUse(O, BO); 11699 11700 Visit(BO->getLHS()); 11701 11702 if (isa<CompoundAssignOperator>(BO)) 11703 notePostUse(O, BO); 11704 11705 Visit(BO->getRHS()); 11706 11707 // C++11 [expr.ass]p1: 11708 // the assignment is sequenced [...] before the value computation of the 11709 // assignment expression. 11710 // C11 6.5.16/3 has no such rule. 11711 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11712 : UK_ModAsSideEffect); 11713 } 11714 11715 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11716 VisitBinAssign(CAO); 11717 } 11718 11719 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11720 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11721 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11722 Object O = getObject(UO->getSubExpr(), true); 11723 if (!O) 11724 return VisitExpr(UO); 11725 11726 notePreMod(O, UO); 11727 Visit(UO->getSubExpr()); 11728 // C++11 [expr.pre.incr]p1: 11729 // the expression ++x is equivalent to x+=1 11730 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11731 : UK_ModAsSideEffect); 11732 } 11733 11734 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11735 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11736 void VisitUnaryPostIncDec(UnaryOperator *UO) { 11737 Object O = getObject(UO->getSubExpr(), true); 11738 if (!O) 11739 return VisitExpr(UO); 11740 11741 notePreMod(O, UO); 11742 Visit(UO->getSubExpr()); 11743 notePostMod(O, UO, UK_ModAsSideEffect); 11744 } 11745 11746 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 11747 void VisitBinLOr(BinaryOperator *BO) { 11748 // The side-effects of the LHS of an '&&' are sequenced before the 11749 // value computation of the RHS, and hence before the value computation 11750 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 11751 // as if they were unconditionally sequenced. 11752 EvaluationTracker Eval(*this); 11753 { 11754 SequencedSubexpression Sequenced(*this); 11755 Visit(BO->getLHS()); 11756 } 11757 11758 bool Result; 11759 if (Eval.evaluate(BO->getLHS(), Result)) { 11760 if (!Result) 11761 Visit(BO->getRHS()); 11762 } else { 11763 // Check for unsequenced operations in the RHS, treating it as an 11764 // entirely separate evaluation. 11765 // 11766 // FIXME: If there are operations in the RHS which are unsequenced 11767 // with respect to operations outside the RHS, and those operations 11768 // are unconditionally evaluated, diagnose them. 11769 WorkList.push_back(BO->getRHS()); 11770 } 11771 } 11772 void VisitBinLAnd(BinaryOperator *BO) { 11773 EvaluationTracker Eval(*this); 11774 { 11775 SequencedSubexpression Sequenced(*this); 11776 Visit(BO->getLHS()); 11777 } 11778 11779 bool Result; 11780 if (Eval.evaluate(BO->getLHS(), Result)) { 11781 if (Result) 11782 Visit(BO->getRHS()); 11783 } else { 11784 WorkList.push_back(BO->getRHS()); 11785 } 11786 } 11787 11788 // Only visit the condition, unless we can be sure which subexpression will 11789 // be chosen. 11790 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 11791 EvaluationTracker Eval(*this); 11792 { 11793 SequencedSubexpression Sequenced(*this); 11794 Visit(CO->getCond()); 11795 } 11796 11797 bool Result; 11798 if (Eval.evaluate(CO->getCond(), Result)) 11799 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 11800 else { 11801 WorkList.push_back(CO->getTrueExpr()); 11802 WorkList.push_back(CO->getFalseExpr()); 11803 } 11804 } 11805 11806 void VisitCallExpr(CallExpr *CE) { 11807 // C++11 [intro.execution]p15: 11808 // When calling a function [...], every value computation and side effect 11809 // associated with any argument expression, or with the postfix expression 11810 // designating the called function, is sequenced before execution of every 11811 // expression or statement in the body of the function [and thus before 11812 // the value computation of its result]. 11813 SequencedSubexpression Sequenced(*this); 11814 Base::VisitCallExpr(CE); 11815 11816 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 11817 } 11818 11819 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 11820 // This is a call, so all subexpressions are sequenced before the result. 11821 SequencedSubexpression Sequenced(*this); 11822 11823 if (!CCE->isListInitialization()) 11824 return VisitExpr(CCE); 11825 11826 // In C++11, list initializations are sequenced. 11827 SmallVector<SequenceTree::Seq, 32> Elts; 11828 SequenceTree::Seq Parent = Region; 11829 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 11830 E = CCE->arg_end(); 11831 I != E; ++I) { 11832 Region = Tree.allocate(Parent); 11833 Elts.push_back(Region); 11834 Visit(*I); 11835 } 11836 11837 // Forget that the initializers are sequenced. 11838 Region = Parent; 11839 for (unsigned I = 0; I < Elts.size(); ++I) 11840 Tree.merge(Elts[I]); 11841 } 11842 11843 void VisitInitListExpr(InitListExpr *ILE) { 11844 if (!SemaRef.getLangOpts().CPlusPlus11) 11845 return VisitExpr(ILE); 11846 11847 // In C++11, list initializations are sequenced. 11848 SmallVector<SequenceTree::Seq, 32> Elts; 11849 SequenceTree::Seq Parent = Region; 11850 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 11851 Expr *E = ILE->getInit(I); 11852 if (!E) continue; 11853 Region = Tree.allocate(Parent); 11854 Elts.push_back(Region); 11855 Visit(E); 11856 } 11857 11858 // Forget that the initializers are sequenced. 11859 Region = Parent; 11860 for (unsigned I = 0; I < Elts.size(); ++I) 11861 Tree.merge(Elts[I]); 11862 } 11863 }; 11864 11865 } // namespace 11866 11867 void Sema::CheckUnsequencedOperations(Expr *E) { 11868 SmallVector<Expr *, 8> WorkList; 11869 WorkList.push_back(E); 11870 while (!WorkList.empty()) { 11871 Expr *Item = WorkList.pop_back_val(); 11872 SequenceChecker(*this, Item, WorkList); 11873 } 11874 } 11875 11876 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 11877 bool IsConstexpr) { 11878 CheckImplicitConversions(E, CheckLoc); 11879 if (!E->isInstantiationDependent()) 11880 CheckUnsequencedOperations(E); 11881 if (!IsConstexpr && !E->isValueDependent()) 11882 CheckForIntOverflow(E); 11883 DiagnoseMisalignedMembers(); 11884 } 11885 11886 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 11887 FieldDecl *BitField, 11888 Expr *Init) { 11889 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 11890 } 11891 11892 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 11893 SourceLocation Loc) { 11894 if (!PType->isVariablyModifiedType()) 11895 return; 11896 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 11897 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 11898 return; 11899 } 11900 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 11901 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 11902 return; 11903 } 11904 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 11905 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 11906 return; 11907 } 11908 11909 const ArrayType *AT = S.Context.getAsArrayType(PType); 11910 if (!AT) 11911 return; 11912 11913 if (AT->getSizeModifier() != ArrayType::Star) { 11914 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 11915 return; 11916 } 11917 11918 S.Diag(Loc, diag::err_array_star_in_function_definition); 11919 } 11920 11921 /// CheckParmsForFunctionDef - Check that the parameters of the given 11922 /// function are appropriate for the definition of a function. This 11923 /// takes care of any checks that cannot be performed on the 11924 /// declaration itself, e.g., that the types of each of the function 11925 /// parameters are complete. 11926 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 11927 bool CheckParameterNames) { 11928 bool HasInvalidParm = false; 11929 for (ParmVarDecl *Param : Parameters) { 11930 // C99 6.7.5.3p4: the parameters in a parameter type list in a 11931 // function declarator that is part of a function definition of 11932 // that function shall not have incomplete type. 11933 // 11934 // This is also C++ [dcl.fct]p6. 11935 if (!Param->isInvalidDecl() && 11936 RequireCompleteType(Param->getLocation(), Param->getType(), 11937 diag::err_typecheck_decl_incomplete_type)) { 11938 Param->setInvalidDecl(); 11939 HasInvalidParm = true; 11940 } 11941 11942 // C99 6.9.1p5: If the declarator includes a parameter type list, the 11943 // declaration of each parameter shall include an identifier. 11944 if (CheckParameterNames && 11945 Param->getIdentifier() == nullptr && 11946 !Param->isImplicit() && 11947 !getLangOpts().CPlusPlus) 11948 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11949 11950 // C99 6.7.5.3p12: 11951 // If the function declarator is not part of a definition of that 11952 // function, parameters may have incomplete type and may use the [*] 11953 // notation in their sequences of declarator specifiers to specify 11954 // variable length array types. 11955 QualType PType = Param->getOriginalType(); 11956 // FIXME: This diagnostic should point the '[*]' if source-location 11957 // information is added for it. 11958 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 11959 11960 // If the parameter is a c++ class type and it has to be destructed in the 11961 // callee function, declare the destructor so that it can be called by the 11962 // callee function. Do not perform any direct access check on the dtor here. 11963 if (!Param->isInvalidDecl()) { 11964 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 11965 if (!ClassDecl->isInvalidDecl() && 11966 !ClassDecl->hasIrrelevantDestructor() && 11967 !ClassDecl->isDependentContext() && 11968 ClassDecl->isParamDestroyedInCallee()) { 11969 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11970 MarkFunctionReferenced(Param->getLocation(), Destructor); 11971 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 11972 } 11973 } 11974 } 11975 11976 // Parameters with the pass_object_size attribute only need to be marked 11977 // constant at function definitions. Because we lack information about 11978 // whether we're on a declaration or definition when we're instantiating the 11979 // attribute, we need to check for constness here. 11980 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 11981 if (!Param->getType().isConstQualified()) 11982 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 11983 << Attr->getSpelling() << 1; 11984 } 11985 11986 return HasInvalidParm; 11987 } 11988 11989 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 11990 /// or MemberExpr. 11991 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 11992 ASTContext &Context) { 11993 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 11994 return Context.getDeclAlign(DRE->getDecl()); 11995 11996 if (const auto *ME = dyn_cast<MemberExpr>(E)) 11997 return Context.getDeclAlign(ME->getMemberDecl()); 11998 11999 return TypeAlign; 12000 } 12001 12002 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12003 /// pointer cast increases the alignment requirements. 12004 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12005 // This is actually a lot of work to potentially be doing on every 12006 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12007 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12008 return; 12009 12010 // Ignore dependent types. 12011 if (T->isDependentType() || Op->getType()->isDependentType()) 12012 return; 12013 12014 // Require that the destination be a pointer type. 12015 const PointerType *DestPtr = T->getAs<PointerType>(); 12016 if (!DestPtr) return; 12017 12018 // If the destination has alignment 1, we're done. 12019 QualType DestPointee = DestPtr->getPointeeType(); 12020 if (DestPointee->isIncompleteType()) return; 12021 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12022 if (DestAlign.isOne()) return; 12023 12024 // Require that the source be a pointer type. 12025 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12026 if (!SrcPtr) return; 12027 QualType SrcPointee = SrcPtr->getPointeeType(); 12028 12029 // Whitelist casts from cv void*. We already implicitly 12030 // whitelisted casts to cv void*, since they have alignment 1. 12031 // Also whitelist casts involving incomplete types, which implicitly 12032 // includes 'void'. 12033 if (SrcPointee->isIncompleteType()) return; 12034 12035 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12036 12037 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12038 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12039 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12040 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12041 if (UO->getOpcode() == UO_AddrOf) 12042 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12043 } 12044 12045 if (SrcAlign >= DestAlign) return; 12046 12047 Diag(TRange.getBegin(), diag::warn_cast_align) 12048 << Op->getType() << T 12049 << static_cast<unsigned>(SrcAlign.getQuantity()) 12050 << static_cast<unsigned>(DestAlign.getQuantity()) 12051 << TRange << Op->getSourceRange(); 12052 } 12053 12054 /// Check whether this array fits the idiom of a size-one tail padded 12055 /// array member of a struct. 12056 /// 12057 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12058 /// commonly used to emulate flexible arrays in C89 code. 12059 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12060 const NamedDecl *ND) { 12061 if (Size != 1 || !ND) return false; 12062 12063 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12064 if (!FD) return false; 12065 12066 // Don't consider sizes resulting from macro expansions or template argument 12067 // substitution to form C89 tail-padded arrays. 12068 12069 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12070 while (TInfo) { 12071 TypeLoc TL = TInfo->getTypeLoc(); 12072 // Look through typedefs. 12073 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12074 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12075 TInfo = TDL->getTypeSourceInfo(); 12076 continue; 12077 } 12078 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12079 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12080 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12081 return false; 12082 } 12083 break; 12084 } 12085 12086 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12087 if (!RD) return false; 12088 if (RD->isUnion()) return false; 12089 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12090 if (!CRD->isStandardLayout()) return false; 12091 } 12092 12093 // See if this is the last field decl in the record. 12094 const Decl *D = FD; 12095 while ((D = D->getNextDeclInContext())) 12096 if (isa<FieldDecl>(D)) 12097 return false; 12098 return true; 12099 } 12100 12101 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12102 const ArraySubscriptExpr *ASE, 12103 bool AllowOnePastEnd, bool IndexNegated) { 12104 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12105 if (IndexExpr->isValueDependent()) 12106 return; 12107 12108 const Type *EffectiveType = 12109 BaseExpr->getType()->getPointeeOrArrayElementType(); 12110 BaseExpr = BaseExpr->IgnoreParenCasts(); 12111 const ConstantArrayType *ArrayTy = 12112 Context.getAsConstantArrayType(BaseExpr->getType()); 12113 if (!ArrayTy) 12114 return; 12115 12116 llvm::APSInt index; 12117 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 12118 return; 12119 if (IndexNegated) 12120 index = -index; 12121 12122 const NamedDecl *ND = nullptr; 12123 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12124 ND = DRE->getDecl(); 12125 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12126 ND = ME->getMemberDecl(); 12127 12128 if (index.isUnsigned() || !index.isNegative()) { 12129 llvm::APInt size = ArrayTy->getSize(); 12130 if (!size.isStrictlyPositive()) 12131 return; 12132 12133 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 12134 if (BaseType != EffectiveType) { 12135 // Make sure we're comparing apples to apples when comparing index to size 12136 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12137 uint64_t array_typesize = Context.getTypeSize(BaseType); 12138 // Handle ptrarith_typesize being zero, such as when casting to void* 12139 if (!ptrarith_typesize) ptrarith_typesize = 1; 12140 if (ptrarith_typesize != array_typesize) { 12141 // There's a cast to a different size type involved 12142 uint64_t ratio = array_typesize / ptrarith_typesize; 12143 // TODO: Be smarter about handling cases where array_typesize is not a 12144 // multiple of ptrarith_typesize 12145 if (ptrarith_typesize * ratio == array_typesize) 12146 size *= llvm::APInt(size.getBitWidth(), ratio); 12147 } 12148 } 12149 12150 if (size.getBitWidth() > index.getBitWidth()) 12151 index = index.zext(size.getBitWidth()); 12152 else if (size.getBitWidth() < index.getBitWidth()) 12153 size = size.zext(index.getBitWidth()); 12154 12155 // For array subscripting the index must be less than size, but for pointer 12156 // arithmetic also allow the index (offset) to be equal to size since 12157 // computing the next address after the end of the array is legal and 12158 // commonly done e.g. in C++ iterators and range-based for loops. 12159 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12160 return; 12161 12162 // Also don't warn for arrays of size 1 which are members of some 12163 // structure. These are often used to approximate flexible arrays in C89 12164 // code. 12165 if (IsTailPaddedMemberArray(*this, size, ND)) 12166 return; 12167 12168 // Suppress the warning if the subscript expression (as identified by the 12169 // ']' location) and the index expression are both from macro expansions 12170 // within a system header. 12171 if (ASE) { 12172 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12173 ASE->getRBracketLoc()); 12174 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12175 SourceLocation IndexLoc = 12176 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12177 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12178 return; 12179 } 12180 } 12181 12182 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12183 if (ASE) 12184 DiagID = diag::warn_array_index_exceeds_bounds; 12185 12186 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12187 PDiag(DiagID) << index.toString(10, true) 12188 << size.toString(10, true) 12189 << (unsigned)size.getLimitedValue(~0U) 12190 << IndexExpr->getSourceRange()); 12191 } else { 12192 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12193 if (!ASE) { 12194 DiagID = diag::warn_ptr_arith_precedes_bounds; 12195 if (index.isNegative()) index = -index; 12196 } 12197 12198 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12199 PDiag(DiagID) << index.toString(10, true) 12200 << IndexExpr->getSourceRange()); 12201 } 12202 12203 if (!ND) { 12204 // Try harder to find a NamedDecl to point at in the note. 12205 while (const ArraySubscriptExpr *ASE = 12206 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12207 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12208 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12209 ND = DRE->getDecl(); 12210 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12211 ND = ME->getMemberDecl(); 12212 } 12213 12214 if (ND) 12215 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12216 PDiag(diag::note_array_index_out_of_bounds) 12217 << ND->getDeclName()); 12218 } 12219 12220 void Sema::CheckArrayAccess(const Expr *expr) { 12221 int AllowOnePastEnd = 0; 12222 while (expr) { 12223 expr = expr->IgnoreParenImpCasts(); 12224 switch (expr->getStmtClass()) { 12225 case Stmt::ArraySubscriptExprClass: { 12226 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12227 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12228 AllowOnePastEnd > 0); 12229 expr = ASE->getBase(); 12230 break; 12231 } 12232 case Stmt::MemberExprClass: { 12233 expr = cast<MemberExpr>(expr)->getBase(); 12234 break; 12235 } 12236 case Stmt::OMPArraySectionExprClass: { 12237 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12238 if (ASE->getLowerBound()) 12239 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12240 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12241 return; 12242 } 12243 case Stmt::UnaryOperatorClass: { 12244 // Only unwrap the * and & unary operators 12245 const UnaryOperator *UO = cast<UnaryOperator>(expr); 12246 expr = UO->getSubExpr(); 12247 switch (UO->getOpcode()) { 12248 case UO_AddrOf: 12249 AllowOnePastEnd++; 12250 break; 12251 case UO_Deref: 12252 AllowOnePastEnd--; 12253 break; 12254 default: 12255 return; 12256 } 12257 break; 12258 } 12259 case Stmt::ConditionalOperatorClass: { 12260 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 12261 if (const Expr *lhs = cond->getLHS()) 12262 CheckArrayAccess(lhs); 12263 if (const Expr *rhs = cond->getRHS()) 12264 CheckArrayAccess(rhs); 12265 return; 12266 } 12267 case Stmt::CXXOperatorCallExprClass: { 12268 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 12269 for (const auto *Arg : OCE->arguments()) 12270 CheckArrayAccess(Arg); 12271 return; 12272 } 12273 default: 12274 return; 12275 } 12276 } 12277 } 12278 12279 //===--- CHECK: Objective-C retain cycles ----------------------------------// 12280 12281 namespace { 12282 12283 struct RetainCycleOwner { 12284 VarDecl *Variable = nullptr; 12285 SourceRange Range; 12286 SourceLocation Loc; 12287 bool Indirect = false; 12288 12289 RetainCycleOwner() = default; 12290 12291 void setLocsFrom(Expr *e) { 12292 Loc = e->getExprLoc(); 12293 Range = e->getSourceRange(); 12294 } 12295 }; 12296 12297 } // namespace 12298 12299 /// Consider whether capturing the given variable can possibly lead to 12300 /// a retain cycle. 12301 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 12302 // In ARC, it's captured strongly iff the variable has __strong 12303 // lifetime. In MRR, it's captured strongly if the variable is 12304 // __block and has an appropriate type. 12305 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12306 return false; 12307 12308 owner.Variable = var; 12309 if (ref) 12310 owner.setLocsFrom(ref); 12311 return true; 12312 } 12313 12314 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 12315 while (true) { 12316 e = e->IgnoreParens(); 12317 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 12318 switch (cast->getCastKind()) { 12319 case CK_BitCast: 12320 case CK_LValueBitCast: 12321 case CK_LValueToRValue: 12322 case CK_ARCReclaimReturnedObject: 12323 e = cast->getSubExpr(); 12324 continue; 12325 12326 default: 12327 return false; 12328 } 12329 } 12330 12331 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 12332 ObjCIvarDecl *ivar = ref->getDecl(); 12333 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12334 return false; 12335 12336 // Try to find a retain cycle in the base. 12337 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 12338 return false; 12339 12340 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 12341 owner.Indirect = true; 12342 return true; 12343 } 12344 12345 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 12346 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 12347 if (!var) return false; 12348 return considerVariable(var, ref, owner); 12349 } 12350 12351 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 12352 if (member->isArrow()) return false; 12353 12354 // Don't count this as an indirect ownership. 12355 e = member->getBase(); 12356 continue; 12357 } 12358 12359 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 12360 // Only pay attention to pseudo-objects on property references. 12361 ObjCPropertyRefExpr *pre 12362 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 12363 ->IgnoreParens()); 12364 if (!pre) return false; 12365 if (pre->isImplicitProperty()) return false; 12366 ObjCPropertyDecl *property = pre->getExplicitProperty(); 12367 if (!property->isRetaining() && 12368 !(property->getPropertyIvarDecl() && 12369 property->getPropertyIvarDecl()->getType() 12370 .getObjCLifetime() == Qualifiers::OCL_Strong)) 12371 return false; 12372 12373 owner.Indirect = true; 12374 if (pre->isSuperReceiver()) { 12375 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 12376 if (!owner.Variable) 12377 return false; 12378 owner.Loc = pre->getLocation(); 12379 owner.Range = pre->getSourceRange(); 12380 return true; 12381 } 12382 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 12383 ->getSourceExpr()); 12384 continue; 12385 } 12386 12387 // Array ivars? 12388 12389 return false; 12390 } 12391 } 12392 12393 namespace { 12394 12395 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 12396 ASTContext &Context; 12397 VarDecl *Variable; 12398 Expr *Capturer = nullptr; 12399 bool VarWillBeReased = false; 12400 12401 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 12402 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 12403 Context(Context), Variable(variable) {} 12404 12405 void VisitDeclRefExpr(DeclRefExpr *ref) { 12406 if (ref->getDecl() == Variable && !Capturer) 12407 Capturer = ref; 12408 } 12409 12410 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 12411 if (Capturer) return; 12412 Visit(ref->getBase()); 12413 if (Capturer && ref->isFreeIvar()) 12414 Capturer = ref; 12415 } 12416 12417 void VisitBlockExpr(BlockExpr *block) { 12418 // Look inside nested blocks 12419 if (block->getBlockDecl()->capturesVariable(Variable)) 12420 Visit(block->getBlockDecl()->getBody()); 12421 } 12422 12423 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 12424 if (Capturer) return; 12425 if (OVE->getSourceExpr()) 12426 Visit(OVE->getSourceExpr()); 12427 } 12428 12429 void VisitBinaryOperator(BinaryOperator *BinOp) { 12430 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 12431 return; 12432 Expr *LHS = BinOp->getLHS(); 12433 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 12434 if (DRE->getDecl() != Variable) 12435 return; 12436 if (Expr *RHS = BinOp->getRHS()) { 12437 RHS = RHS->IgnoreParenCasts(); 12438 llvm::APSInt Value; 12439 VarWillBeReased = 12440 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 12441 } 12442 } 12443 } 12444 }; 12445 12446 } // namespace 12447 12448 /// Check whether the given argument is a block which captures a 12449 /// variable. 12450 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 12451 assert(owner.Variable && owner.Loc.isValid()); 12452 12453 e = e->IgnoreParenCasts(); 12454 12455 // Look through [^{...} copy] and Block_copy(^{...}). 12456 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 12457 Selector Cmd = ME->getSelector(); 12458 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 12459 e = ME->getInstanceReceiver(); 12460 if (!e) 12461 return nullptr; 12462 e = e->IgnoreParenCasts(); 12463 } 12464 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 12465 if (CE->getNumArgs() == 1) { 12466 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 12467 if (Fn) { 12468 const IdentifierInfo *FnI = Fn->getIdentifier(); 12469 if (FnI && FnI->isStr("_Block_copy")) { 12470 e = CE->getArg(0)->IgnoreParenCasts(); 12471 } 12472 } 12473 } 12474 } 12475 12476 BlockExpr *block = dyn_cast<BlockExpr>(e); 12477 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 12478 return nullptr; 12479 12480 FindCaptureVisitor visitor(S.Context, owner.Variable); 12481 visitor.Visit(block->getBlockDecl()->getBody()); 12482 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 12483 } 12484 12485 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 12486 RetainCycleOwner &owner) { 12487 assert(capturer); 12488 assert(owner.Variable && owner.Loc.isValid()); 12489 12490 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 12491 << owner.Variable << capturer->getSourceRange(); 12492 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 12493 << owner.Indirect << owner.Range; 12494 } 12495 12496 /// Check for a keyword selector that starts with the word 'add' or 12497 /// 'set'. 12498 static bool isSetterLikeSelector(Selector sel) { 12499 if (sel.isUnarySelector()) return false; 12500 12501 StringRef str = sel.getNameForSlot(0); 12502 while (!str.empty() && str.front() == '_') str = str.substr(1); 12503 if (str.startswith("set")) 12504 str = str.substr(3); 12505 else if (str.startswith("add")) { 12506 // Specially whitelist 'addOperationWithBlock:'. 12507 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12508 return false; 12509 str = str.substr(3); 12510 } 12511 else 12512 return false; 12513 12514 if (str.empty()) return true; 12515 return !isLowercase(str.front()); 12516 } 12517 12518 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12519 ObjCMessageExpr *Message) { 12520 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12521 Message->getReceiverInterface(), 12522 NSAPI::ClassId_NSMutableArray); 12523 if (!IsMutableArray) { 12524 return None; 12525 } 12526 12527 Selector Sel = Message->getSelector(); 12528 12529 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12530 S.NSAPIObj->getNSArrayMethodKind(Sel); 12531 if (!MKOpt) { 12532 return None; 12533 } 12534 12535 NSAPI::NSArrayMethodKind MK = *MKOpt; 12536 12537 switch (MK) { 12538 case NSAPI::NSMutableArr_addObject: 12539 case NSAPI::NSMutableArr_insertObjectAtIndex: 12540 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12541 return 0; 12542 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12543 return 1; 12544 12545 default: 12546 return None; 12547 } 12548 12549 return None; 12550 } 12551 12552 static 12553 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12554 ObjCMessageExpr *Message) { 12555 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12556 Message->getReceiverInterface(), 12557 NSAPI::ClassId_NSMutableDictionary); 12558 if (!IsMutableDictionary) { 12559 return None; 12560 } 12561 12562 Selector Sel = Message->getSelector(); 12563 12564 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 12565 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 12566 if (!MKOpt) { 12567 return None; 12568 } 12569 12570 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 12571 12572 switch (MK) { 12573 case NSAPI::NSMutableDict_setObjectForKey: 12574 case NSAPI::NSMutableDict_setValueForKey: 12575 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 12576 return 0; 12577 12578 default: 12579 return None; 12580 } 12581 12582 return None; 12583 } 12584 12585 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 12586 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 12587 Message->getReceiverInterface(), 12588 NSAPI::ClassId_NSMutableSet); 12589 12590 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 12591 Message->getReceiverInterface(), 12592 NSAPI::ClassId_NSMutableOrderedSet); 12593 if (!IsMutableSet && !IsMutableOrderedSet) { 12594 return None; 12595 } 12596 12597 Selector Sel = Message->getSelector(); 12598 12599 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 12600 if (!MKOpt) { 12601 return None; 12602 } 12603 12604 NSAPI::NSSetMethodKind MK = *MKOpt; 12605 12606 switch (MK) { 12607 case NSAPI::NSMutableSet_addObject: 12608 case NSAPI::NSOrderedSet_setObjectAtIndex: 12609 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 12610 case NSAPI::NSOrderedSet_insertObjectAtIndex: 12611 return 0; 12612 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 12613 return 1; 12614 } 12615 12616 return None; 12617 } 12618 12619 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 12620 if (!Message->isInstanceMessage()) { 12621 return; 12622 } 12623 12624 Optional<int> ArgOpt; 12625 12626 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 12627 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 12628 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 12629 return; 12630 } 12631 12632 int ArgIndex = *ArgOpt; 12633 12634 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 12635 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 12636 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 12637 } 12638 12639 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 12640 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12641 if (ArgRE->isObjCSelfExpr()) { 12642 Diag(Message->getSourceRange().getBegin(), 12643 diag::warn_objc_circular_container) 12644 << ArgRE->getDecl() << StringRef("'super'"); 12645 } 12646 } 12647 } else { 12648 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 12649 12650 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 12651 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 12652 } 12653 12654 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 12655 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12656 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 12657 ValueDecl *Decl = ReceiverRE->getDecl(); 12658 Diag(Message->getSourceRange().getBegin(), 12659 diag::warn_objc_circular_container) 12660 << Decl << Decl; 12661 if (!ArgRE->isObjCSelfExpr()) { 12662 Diag(Decl->getLocation(), 12663 diag::note_objc_circular_container_declared_here) 12664 << Decl; 12665 } 12666 } 12667 } 12668 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12669 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12670 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12671 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12672 Diag(Message->getSourceRange().getBegin(), 12673 diag::warn_objc_circular_container) 12674 << Decl << Decl; 12675 Diag(Decl->getLocation(), 12676 diag::note_objc_circular_container_declared_here) 12677 << Decl; 12678 } 12679 } 12680 } 12681 } 12682 } 12683 12684 /// Check a message send to see if it's likely to cause a retain cycle. 12685 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 12686 // Only check instance methods whose selector looks like a setter. 12687 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12688 return; 12689 12690 // Try to find a variable that the receiver is strongly owned by. 12691 RetainCycleOwner owner; 12692 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12693 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12694 return; 12695 } else { 12696 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12697 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12698 owner.Loc = msg->getSuperLoc(); 12699 owner.Range = msg->getSuperLoc(); 12700 } 12701 12702 // Check whether the receiver is captured by any of the arguments. 12703 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12704 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12705 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12706 // noescape blocks should not be retained by the method. 12707 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 12708 continue; 12709 return diagnoseRetainCycle(*this, capturer, owner); 12710 } 12711 } 12712 } 12713 12714 /// Check a property assign to see if it's likely to cause a retain cycle. 12715 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 12716 RetainCycleOwner owner; 12717 if (!findRetainCycleOwner(*this, receiver, owner)) 12718 return; 12719 12720 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 12721 diagnoseRetainCycle(*this, capturer, owner); 12722 } 12723 12724 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 12725 RetainCycleOwner Owner; 12726 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 12727 return; 12728 12729 // Because we don't have an expression for the variable, we have to set the 12730 // location explicitly here. 12731 Owner.Loc = Var->getLocation(); 12732 Owner.Range = Var->getSourceRange(); 12733 12734 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 12735 diagnoseRetainCycle(*this, Capturer, Owner); 12736 } 12737 12738 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 12739 Expr *RHS, bool isProperty) { 12740 // Check if RHS is an Objective-C object literal, which also can get 12741 // immediately zapped in a weak reference. Note that we explicitly 12742 // allow ObjCStringLiterals, since those are designed to never really die. 12743 RHS = RHS->IgnoreParenImpCasts(); 12744 12745 // This enum needs to match with the 'select' in 12746 // warn_objc_arc_literal_assign (off-by-1). 12747 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 12748 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 12749 return false; 12750 12751 S.Diag(Loc, diag::warn_arc_literal_assign) 12752 << (unsigned) Kind 12753 << (isProperty ? 0 : 1) 12754 << RHS->getSourceRange(); 12755 12756 return true; 12757 } 12758 12759 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 12760 Qualifiers::ObjCLifetime LT, 12761 Expr *RHS, bool isProperty) { 12762 // Strip off any implicit cast added to get to the one ARC-specific. 12763 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12764 if (cast->getCastKind() == CK_ARCConsumeObject) { 12765 S.Diag(Loc, diag::warn_arc_retained_assign) 12766 << (LT == Qualifiers::OCL_ExplicitNone) 12767 << (isProperty ? 0 : 1) 12768 << RHS->getSourceRange(); 12769 return true; 12770 } 12771 RHS = cast->getSubExpr(); 12772 } 12773 12774 if (LT == Qualifiers::OCL_Weak && 12775 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 12776 return true; 12777 12778 return false; 12779 } 12780 12781 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 12782 QualType LHS, Expr *RHS) { 12783 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 12784 12785 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 12786 return false; 12787 12788 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 12789 return true; 12790 12791 return false; 12792 } 12793 12794 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 12795 Expr *LHS, Expr *RHS) { 12796 QualType LHSType; 12797 // PropertyRef on LHS type need be directly obtained from 12798 // its declaration as it has a PseudoType. 12799 ObjCPropertyRefExpr *PRE 12800 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 12801 if (PRE && !PRE->isImplicitProperty()) { 12802 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12803 if (PD) 12804 LHSType = PD->getType(); 12805 } 12806 12807 if (LHSType.isNull()) 12808 LHSType = LHS->getType(); 12809 12810 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 12811 12812 if (LT == Qualifiers::OCL_Weak) { 12813 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 12814 getCurFunction()->markSafeWeakUse(LHS); 12815 } 12816 12817 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 12818 return; 12819 12820 // FIXME. Check for other life times. 12821 if (LT != Qualifiers::OCL_None) 12822 return; 12823 12824 if (PRE) { 12825 if (PRE->isImplicitProperty()) 12826 return; 12827 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12828 if (!PD) 12829 return; 12830 12831 unsigned Attributes = PD->getPropertyAttributes(); 12832 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 12833 // when 'assign' attribute was not explicitly specified 12834 // by user, ignore it and rely on property type itself 12835 // for lifetime info. 12836 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 12837 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 12838 LHSType->isObjCRetainableType()) 12839 return; 12840 12841 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12842 if (cast->getCastKind() == CK_ARCConsumeObject) { 12843 Diag(Loc, diag::warn_arc_retained_property_assign) 12844 << RHS->getSourceRange(); 12845 return; 12846 } 12847 RHS = cast->getSubExpr(); 12848 } 12849 } 12850 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 12851 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 12852 return; 12853 } 12854 } 12855 } 12856 12857 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 12858 12859 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 12860 SourceLocation StmtLoc, 12861 const NullStmt *Body) { 12862 // Do not warn if the body is a macro that expands to nothing, e.g: 12863 // 12864 // #define CALL(x) 12865 // if (condition) 12866 // CALL(0); 12867 if (Body->hasLeadingEmptyMacro()) 12868 return false; 12869 12870 // Get line numbers of statement and body. 12871 bool StmtLineInvalid; 12872 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 12873 &StmtLineInvalid); 12874 if (StmtLineInvalid) 12875 return false; 12876 12877 bool BodyLineInvalid; 12878 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 12879 &BodyLineInvalid); 12880 if (BodyLineInvalid) 12881 return false; 12882 12883 // Warn if null statement and body are on the same line. 12884 if (StmtLine != BodyLine) 12885 return false; 12886 12887 return true; 12888 } 12889 12890 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 12891 const Stmt *Body, 12892 unsigned DiagID) { 12893 // Since this is a syntactic check, don't emit diagnostic for template 12894 // instantiations, this just adds noise. 12895 if (CurrentInstantiationScope) 12896 return; 12897 12898 // The body should be a null statement. 12899 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12900 if (!NBody) 12901 return; 12902 12903 // Do the usual checks. 12904 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12905 return; 12906 12907 Diag(NBody->getSemiLoc(), DiagID); 12908 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12909 } 12910 12911 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 12912 const Stmt *PossibleBody) { 12913 assert(!CurrentInstantiationScope); // Ensured by caller 12914 12915 SourceLocation StmtLoc; 12916 const Stmt *Body; 12917 unsigned DiagID; 12918 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 12919 StmtLoc = FS->getRParenLoc(); 12920 Body = FS->getBody(); 12921 DiagID = diag::warn_empty_for_body; 12922 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 12923 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 12924 Body = WS->getBody(); 12925 DiagID = diag::warn_empty_while_body; 12926 } else 12927 return; // Neither `for' nor `while'. 12928 12929 // The body should be a null statement. 12930 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12931 if (!NBody) 12932 return; 12933 12934 // Skip expensive checks if diagnostic is disabled. 12935 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 12936 return; 12937 12938 // Do the usual checks. 12939 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12940 return; 12941 12942 // `for(...);' and `while(...);' are popular idioms, so in order to keep 12943 // noise level low, emit diagnostics only if for/while is followed by a 12944 // CompoundStmt, e.g.: 12945 // for (int i = 0; i < n; i++); 12946 // { 12947 // a(i); 12948 // } 12949 // or if for/while is followed by a statement with more indentation 12950 // than for/while itself: 12951 // for (int i = 0; i < n; i++); 12952 // a(i); 12953 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 12954 if (!ProbableTypo) { 12955 bool BodyColInvalid; 12956 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 12957 PossibleBody->getBeginLoc(), &BodyColInvalid); 12958 if (BodyColInvalid) 12959 return; 12960 12961 bool StmtColInvalid; 12962 unsigned StmtCol = 12963 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 12964 if (StmtColInvalid) 12965 return; 12966 12967 if (BodyCol > StmtCol) 12968 ProbableTypo = true; 12969 } 12970 12971 if (ProbableTypo) { 12972 Diag(NBody->getSemiLoc(), DiagID); 12973 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12974 } 12975 } 12976 12977 //===--- CHECK: Warn on self move with std::move. -------------------------===// 12978 12979 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 12980 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 12981 SourceLocation OpLoc) { 12982 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 12983 return; 12984 12985 if (inTemplateInstantiation()) 12986 return; 12987 12988 // Strip parens and casts away. 12989 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12990 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12991 12992 // Check for a call expression 12993 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 12994 if (!CE || CE->getNumArgs() != 1) 12995 return; 12996 12997 // Check for a call to std::move 12998 if (!CE->isCallToStdMove()) 12999 return; 13000 13001 // Get argument from std::move 13002 RHSExpr = CE->getArg(0); 13003 13004 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13005 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13006 13007 // Two DeclRefExpr's, check that the decls are the same. 13008 if (LHSDeclRef && RHSDeclRef) { 13009 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13010 return; 13011 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13012 RHSDeclRef->getDecl()->getCanonicalDecl()) 13013 return; 13014 13015 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13016 << LHSExpr->getSourceRange() 13017 << RHSExpr->getSourceRange(); 13018 return; 13019 } 13020 13021 // Member variables require a different approach to check for self moves. 13022 // MemberExpr's are the same if every nested MemberExpr refers to the same 13023 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13024 // the base Expr's are CXXThisExpr's. 13025 const Expr *LHSBase = LHSExpr; 13026 const Expr *RHSBase = RHSExpr; 13027 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13028 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13029 if (!LHSME || !RHSME) 13030 return; 13031 13032 while (LHSME && RHSME) { 13033 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13034 RHSME->getMemberDecl()->getCanonicalDecl()) 13035 return; 13036 13037 LHSBase = LHSME->getBase(); 13038 RHSBase = RHSME->getBase(); 13039 LHSME = dyn_cast<MemberExpr>(LHSBase); 13040 RHSME = dyn_cast<MemberExpr>(RHSBase); 13041 } 13042 13043 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13044 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13045 if (LHSDeclRef && RHSDeclRef) { 13046 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13047 return; 13048 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13049 RHSDeclRef->getDecl()->getCanonicalDecl()) 13050 return; 13051 13052 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13053 << LHSExpr->getSourceRange() 13054 << RHSExpr->getSourceRange(); 13055 return; 13056 } 13057 13058 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13059 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13060 << LHSExpr->getSourceRange() 13061 << RHSExpr->getSourceRange(); 13062 } 13063 13064 //===--- Layout compatibility ----------------------------------------------// 13065 13066 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13067 13068 /// Check if two enumeration types are layout-compatible. 13069 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13070 // C++11 [dcl.enum] p8: 13071 // Two enumeration types are layout-compatible if they have the same 13072 // underlying type. 13073 return ED1->isComplete() && ED2->isComplete() && 13074 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13075 } 13076 13077 /// Check if two fields are layout-compatible. 13078 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13079 FieldDecl *Field2) { 13080 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13081 return false; 13082 13083 if (Field1->isBitField() != Field2->isBitField()) 13084 return false; 13085 13086 if (Field1->isBitField()) { 13087 // Make sure that the bit-fields are the same length. 13088 unsigned Bits1 = Field1->getBitWidthValue(C); 13089 unsigned Bits2 = Field2->getBitWidthValue(C); 13090 13091 if (Bits1 != Bits2) 13092 return false; 13093 } 13094 13095 return true; 13096 } 13097 13098 /// Check if two standard-layout structs are layout-compatible. 13099 /// (C++11 [class.mem] p17) 13100 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13101 RecordDecl *RD2) { 13102 // If both records are C++ classes, check that base classes match. 13103 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13104 // If one of records is a CXXRecordDecl we are in C++ mode, 13105 // thus the other one is a CXXRecordDecl, too. 13106 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13107 // Check number of base classes. 13108 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13109 return false; 13110 13111 // Check the base classes. 13112 for (CXXRecordDecl::base_class_const_iterator 13113 Base1 = D1CXX->bases_begin(), 13114 BaseEnd1 = D1CXX->bases_end(), 13115 Base2 = D2CXX->bases_begin(); 13116 Base1 != BaseEnd1; 13117 ++Base1, ++Base2) { 13118 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13119 return false; 13120 } 13121 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13122 // If only RD2 is a C++ class, it should have zero base classes. 13123 if (D2CXX->getNumBases() > 0) 13124 return false; 13125 } 13126 13127 // Check the fields. 13128 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13129 Field2End = RD2->field_end(), 13130 Field1 = RD1->field_begin(), 13131 Field1End = RD1->field_end(); 13132 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13133 if (!isLayoutCompatible(C, *Field1, *Field2)) 13134 return false; 13135 } 13136 if (Field1 != Field1End || Field2 != Field2End) 13137 return false; 13138 13139 return true; 13140 } 13141 13142 /// Check if two standard-layout unions are layout-compatible. 13143 /// (C++11 [class.mem] p18) 13144 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13145 RecordDecl *RD2) { 13146 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13147 for (auto *Field2 : RD2->fields()) 13148 UnmatchedFields.insert(Field2); 13149 13150 for (auto *Field1 : RD1->fields()) { 13151 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13152 I = UnmatchedFields.begin(), 13153 E = UnmatchedFields.end(); 13154 13155 for ( ; I != E; ++I) { 13156 if (isLayoutCompatible(C, Field1, *I)) { 13157 bool Result = UnmatchedFields.erase(*I); 13158 (void) Result; 13159 assert(Result); 13160 break; 13161 } 13162 } 13163 if (I == E) 13164 return false; 13165 } 13166 13167 return UnmatchedFields.empty(); 13168 } 13169 13170 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13171 RecordDecl *RD2) { 13172 if (RD1->isUnion() != RD2->isUnion()) 13173 return false; 13174 13175 if (RD1->isUnion()) 13176 return isLayoutCompatibleUnion(C, RD1, RD2); 13177 else 13178 return isLayoutCompatibleStruct(C, RD1, RD2); 13179 } 13180 13181 /// Check if two types are layout-compatible in C++11 sense. 13182 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13183 if (T1.isNull() || T2.isNull()) 13184 return false; 13185 13186 // C++11 [basic.types] p11: 13187 // If two types T1 and T2 are the same type, then T1 and T2 are 13188 // layout-compatible types. 13189 if (C.hasSameType(T1, T2)) 13190 return true; 13191 13192 T1 = T1.getCanonicalType().getUnqualifiedType(); 13193 T2 = T2.getCanonicalType().getUnqualifiedType(); 13194 13195 const Type::TypeClass TC1 = T1->getTypeClass(); 13196 const Type::TypeClass TC2 = T2->getTypeClass(); 13197 13198 if (TC1 != TC2) 13199 return false; 13200 13201 if (TC1 == Type::Enum) { 13202 return isLayoutCompatible(C, 13203 cast<EnumType>(T1)->getDecl(), 13204 cast<EnumType>(T2)->getDecl()); 13205 } else if (TC1 == Type::Record) { 13206 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13207 return false; 13208 13209 return isLayoutCompatible(C, 13210 cast<RecordType>(T1)->getDecl(), 13211 cast<RecordType>(T2)->getDecl()); 13212 } 13213 13214 return false; 13215 } 13216 13217 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13218 13219 /// Given a type tag expression find the type tag itself. 13220 /// 13221 /// \param TypeExpr Type tag expression, as it appears in user's code. 13222 /// 13223 /// \param VD Declaration of an identifier that appears in a type tag. 13224 /// 13225 /// \param MagicValue Type tag magic value. 13226 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13227 const ValueDecl **VD, uint64_t *MagicValue) { 13228 while(true) { 13229 if (!TypeExpr) 13230 return false; 13231 13232 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13233 13234 switch (TypeExpr->getStmtClass()) { 13235 case Stmt::UnaryOperatorClass: { 13236 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13237 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13238 TypeExpr = UO->getSubExpr(); 13239 continue; 13240 } 13241 return false; 13242 } 13243 13244 case Stmt::DeclRefExprClass: { 13245 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 13246 *VD = DRE->getDecl(); 13247 return true; 13248 } 13249 13250 case Stmt::IntegerLiteralClass: { 13251 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 13252 llvm::APInt MagicValueAPInt = IL->getValue(); 13253 if (MagicValueAPInt.getActiveBits() <= 64) { 13254 *MagicValue = MagicValueAPInt.getZExtValue(); 13255 return true; 13256 } else 13257 return false; 13258 } 13259 13260 case Stmt::BinaryConditionalOperatorClass: 13261 case Stmt::ConditionalOperatorClass: { 13262 const AbstractConditionalOperator *ACO = 13263 cast<AbstractConditionalOperator>(TypeExpr); 13264 bool Result; 13265 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 13266 if (Result) 13267 TypeExpr = ACO->getTrueExpr(); 13268 else 13269 TypeExpr = ACO->getFalseExpr(); 13270 continue; 13271 } 13272 return false; 13273 } 13274 13275 case Stmt::BinaryOperatorClass: { 13276 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 13277 if (BO->getOpcode() == BO_Comma) { 13278 TypeExpr = BO->getRHS(); 13279 continue; 13280 } 13281 return false; 13282 } 13283 13284 default: 13285 return false; 13286 } 13287 } 13288 } 13289 13290 /// Retrieve the C type corresponding to type tag TypeExpr. 13291 /// 13292 /// \param TypeExpr Expression that specifies a type tag. 13293 /// 13294 /// \param MagicValues Registered magic values. 13295 /// 13296 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 13297 /// kind. 13298 /// 13299 /// \param TypeInfo Information about the corresponding C type. 13300 /// 13301 /// \returns true if the corresponding C type was found. 13302 static bool GetMatchingCType( 13303 const IdentifierInfo *ArgumentKind, 13304 const Expr *TypeExpr, const ASTContext &Ctx, 13305 const llvm::DenseMap<Sema::TypeTagMagicValue, 13306 Sema::TypeTagData> *MagicValues, 13307 bool &FoundWrongKind, 13308 Sema::TypeTagData &TypeInfo) { 13309 FoundWrongKind = false; 13310 13311 // Variable declaration that has type_tag_for_datatype attribute. 13312 const ValueDecl *VD = nullptr; 13313 13314 uint64_t MagicValue; 13315 13316 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 13317 return false; 13318 13319 if (VD) { 13320 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 13321 if (I->getArgumentKind() != ArgumentKind) { 13322 FoundWrongKind = true; 13323 return false; 13324 } 13325 TypeInfo.Type = I->getMatchingCType(); 13326 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 13327 TypeInfo.MustBeNull = I->getMustBeNull(); 13328 return true; 13329 } 13330 return false; 13331 } 13332 13333 if (!MagicValues) 13334 return false; 13335 13336 llvm::DenseMap<Sema::TypeTagMagicValue, 13337 Sema::TypeTagData>::const_iterator I = 13338 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 13339 if (I == MagicValues->end()) 13340 return false; 13341 13342 TypeInfo = I->second; 13343 return true; 13344 } 13345 13346 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 13347 uint64_t MagicValue, QualType Type, 13348 bool LayoutCompatible, 13349 bool MustBeNull) { 13350 if (!TypeTagForDatatypeMagicValues) 13351 TypeTagForDatatypeMagicValues.reset( 13352 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 13353 13354 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 13355 (*TypeTagForDatatypeMagicValues)[Magic] = 13356 TypeTagData(Type, LayoutCompatible, MustBeNull); 13357 } 13358 13359 static bool IsSameCharType(QualType T1, QualType T2) { 13360 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 13361 if (!BT1) 13362 return false; 13363 13364 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 13365 if (!BT2) 13366 return false; 13367 13368 BuiltinType::Kind T1Kind = BT1->getKind(); 13369 BuiltinType::Kind T2Kind = BT2->getKind(); 13370 13371 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 13372 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 13373 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 13374 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 13375 } 13376 13377 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 13378 const ArrayRef<const Expr *> ExprArgs, 13379 SourceLocation CallSiteLoc) { 13380 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 13381 bool IsPointerAttr = Attr->getIsPointer(); 13382 13383 // Retrieve the argument representing the 'type_tag'. 13384 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 13385 if (TypeTagIdxAST >= ExprArgs.size()) { 13386 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13387 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 13388 return; 13389 } 13390 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 13391 bool FoundWrongKind; 13392 TypeTagData TypeInfo; 13393 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 13394 TypeTagForDatatypeMagicValues.get(), 13395 FoundWrongKind, TypeInfo)) { 13396 if (FoundWrongKind) 13397 Diag(TypeTagExpr->getExprLoc(), 13398 diag::warn_type_tag_for_datatype_wrong_kind) 13399 << TypeTagExpr->getSourceRange(); 13400 return; 13401 } 13402 13403 // Retrieve the argument representing the 'arg_idx'. 13404 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 13405 if (ArgumentIdxAST >= ExprArgs.size()) { 13406 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13407 << 1 << Attr->getArgumentIdx().getSourceIndex(); 13408 return; 13409 } 13410 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 13411 if (IsPointerAttr) { 13412 // Skip implicit cast of pointer to `void *' (as a function argument). 13413 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 13414 if (ICE->getType()->isVoidPointerType() && 13415 ICE->getCastKind() == CK_BitCast) 13416 ArgumentExpr = ICE->getSubExpr(); 13417 } 13418 QualType ArgumentType = ArgumentExpr->getType(); 13419 13420 // Passing a `void*' pointer shouldn't trigger a warning. 13421 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 13422 return; 13423 13424 if (TypeInfo.MustBeNull) { 13425 // Type tag with matching void type requires a null pointer. 13426 if (!ArgumentExpr->isNullPointerConstant(Context, 13427 Expr::NPC_ValueDependentIsNotNull)) { 13428 Diag(ArgumentExpr->getExprLoc(), 13429 diag::warn_type_safety_null_pointer_required) 13430 << ArgumentKind->getName() 13431 << ArgumentExpr->getSourceRange() 13432 << TypeTagExpr->getSourceRange(); 13433 } 13434 return; 13435 } 13436 13437 QualType RequiredType = TypeInfo.Type; 13438 if (IsPointerAttr) 13439 RequiredType = Context.getPointerType(RequiredType); 13440 13441 bool mismatch = false; 13442 if (!TypeInfo.LayoutCompatible) { 13443 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 13444 13445 // C++11 [basic.fundamental] p1: 13446 // Plain char, signed char, and unsigned char are three distinct types. 13447 // 13448 // But we treat plain `char' as equivalent to `signed char' or `unsigned 13449 // char' depending on the current char signedness mode. 13450 if (mismatch) 13451 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 13452 RequiredType->getPointeeType())) || 13453 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 13454 mismatch = false; 13455 } else 13456 if (IsPointerAttr) 13457 mismatch = !isLayoutCompatible(Context, 13458 ArgumentType->getPointeeType(), 13459 RequiredType->getPointeeType()); 13460 else 13461 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 13462 13463 if (mismatch) 13464 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 13465 << ArgumentType << ArgumentKind 13466 << TypeInfo.LayoutCompatible << RequiredType 13467 << ArgumentExpr->getSourceRange() 13468 << TypeTagExpr->getSourceRange(); 13469 } 13470 13471 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 13472 CharUnits Alignment) { 13473 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 13474 } 13475 13476 void Sema::DiagnoseMisalignedMembers() { 13477 for (MisalignedMember &m : MisalignedMembers) { 13478 const NamedDecl *ND = m.RD; 13479 if (ND->getName().empty()) { 13480 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 13481 ND = TD; 13482 } 13483 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 13484 << m.MD << ND << m.E->getSourceRange(); 13485 } 13486 MisalignedMembers.clear(); 13487 } 13488 13489 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 13490 E = E->IgnoreParens(); 13491 if (!T->isPointerType() && !T->isIntegerType()) 13492 return; 13493 if (isa<UnaryOperator>(E) && 13494 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13495 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13496 if (isa<MemberExpr>(Op)) { 13497 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 13498 MisalignedMember(Op)); 13499 if (MA != MisalignedMembers.end() && 13500 (T->isIntegerType() || 13501 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13502 Context.getTypeAlignInChars( 13503 T->getPointeeType()) <= MA->Alignment)))) 13504 MisalignedMembers.erase(MA); 13505 } 13506 } 13507 } 13508 13509 void Sema::RefersToMemberWithReducedAlignment( 13510 Expr *E, 13511 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13512 Action) { 13513 const auto *ME = dyn_cast<MemberExpr>(E); 13514 if (!ME) 13515 return; 13516 13517 // No need to check expressions with an __unaligned-qualified type. 13518 if (E->getType().getQualifiers().hasUnaligned()) 13519 return; 13520 13521 // For a chain of MemberExpr like "a.b.c.d" this list 13522 // will keep FieldDecl's like [d, c, b]. 13523 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13524 const MemberExpr *TopME = nullptr; 13525 bool AnyIsPacked = false; 13526 do { 13527 QualType BaseType = ME->getBase()->getType(); 13528 if (ME->isArrow()) 13529 BaseType = BaseType->getPointeeType(); 13530 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13531 if (RD->isInvalidDecl()) 13532 return; 13533 13534 ValueDecl *MD = ME->getMemberDecl(); 13535 auto *FD = dyn_cast<FieldDecl>(MD); 13536 // We do not care about non-data members. 13537 if (!FD || FD->isInvalidDecl()) 13538 return; 13539 13540 AnyIsPacked = 13541 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13542 ReverseMemberChain.push_back(FD); 13543 13544 TopME = ME; 13545 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13546 } while (ME); 13547 assert(TopME && "We did not compute a topmost MemberExpr!"); 13548 13549 // Not the scope of this diagnostic. 13550 if (!AnyIsPacked) 13551 return; 13552 13553 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13554 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13555 // TODO: The innermost base of the member expression may be too complicated. 13556 // For now, just disregard these cases. This is left for future 13557 // improvement. 13558 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13559 return; 13560 13561 // Alignment expected by the whole expression. 13562 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13563 13564 // No need to do anything else with this case. 13565 if (ExpectedAlignment.isOne()) 13566 return; 13567 13568 // Synthesize offset of the whole access. 13569 CharUnits Offset; 13570 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 13571 I++) { 13572 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 13573 } 13574 13575 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 13576 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 13577 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 13578 13579 // The base expression of the innermost MemberExpr may give 13580 // stronger guarantees than the class containing the member. 13581 if (DRE && !TopME->isArrow()) { 13582 const ValueDecl *VD = DRE->getDecl(); 13583 if (!VD->getType()->isReferenceType()) 13584 CompleteObjectAlignment = 13585 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 13586 } 13587 13588 // Check if the synthesized offset fulfills the alignment. 13589 if (Offset % ExpectedAlignment != 0 || 13590 // It may fulfill the offset it but the effective alignment may still be 13591 // lower than the expected expression alignment. 13592 CompleteObjectAlignment < ExpectedAlignment) { 13593 // If this happens, we want to determine a sensible culprit of this. 13594 // Intuitively, watching the chain of member expressions from right to 13595 // left, we start with the required alignment (as required by the field 13596 // type) but some packed attribute in that chain has reduced the alignment. 13597 // It may happen that another packed structure increases it again. But if 13598 // we are here such increase has not been enough. So pointing the first 13599 // FieldDecl that either is packed or else its RecordDecl is, 13600 // seems reasonable. 13601 FieldDecl *FD = nullptr; 13602 CharUnits Alignment; 13603 for (FieldDecl *FDI : ReverseMemberChain) { 13604 if (FDI->hasAttr<PackedAttr>() || 13605 FDI->getParent()->hasAttr<PackedAttr>()) { 13606 FD = FDI; 13607 Alignment = std::min( 13608 Context.getTypeAlignInChars(FD->getType()), 13609 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 13610 break; 13611 } 13612 } 13613 assert(FD && "We did not find a packed FieldDecl!"); 13614 Action(E, FD->getParent(), FD, Alignment); 13615 } 13616 } 13617 13618 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 13619 using namespace std::placeholders; 13620 13621 RefersToMemberWithReducedAlignment( 13622 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 13623 _2, _3, _4)); 13624 } 13625