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 StringRef LikelyMacroName) { 243 if (TheCall->getNumArgs() <= SizeIdx || 244 TheCall->getNumArgs() <= DstSizeIdx) 245 return; 246 247 const Expr *SizeArg = TheCall->getArg(SizeIdx); 248 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 249 250 llvm::APSInt Size, DstSize; 251 252 // find out if both sizes are known at compile time 253 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 254 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 255 return; 256 257 if (Size.ule(DstSize)) 258 return; 259 260 // Confirmed overflow, so generate the diagnostic. 261 StringRef FunctionName = FDecl->getName(); 262 SourceLocation SL = TheCall->getBeginLoc(); 263 SourceManager &SM = S.getSourceManager(); 264 // If we're in an expansion of a macro whose name corresponds to this builtin, 265 // use the simple macro name and location. 266 if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) == 267 LikelyMacroName) { 268 FunctionName = LikelyMacroName; 269 SL = SM.getImmediateMacroCallerLoc(SL); 270 } 271 272 S.Diag(SL, diag::warn_memcpy_chk_overflow) 273 << FunctionName << DstSize.toString(/*Radix=*/10) 274 << Size.toString(/*Radix=*/10); 275 } 276 277 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 278 if (checkArgCount(S, BuiltinCall, 2)) 279 return true; 280 281 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 282 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 283 Expr *Call = BuiltinCall->getArg(0); 284 Expr *Chain = BuiltinCall->getArg(1); 285 286 if (Call->getStmtClass() != Stmt::CallExprClass) { 287 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 288 << Call->getSourceRange(); 289 return true; 290 } 291 292 auto CE = cast<CallExpr>(Call); 293 if (CE->getCallee()->getType()->isBlockPointerType()) { 294 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 295 << Call->getSourceRange(); 296 return true; 297 } 298 299 const Decl *TargetDecl = CE->getCalleeDecl(); 300 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 301 if (FD->getBuiltinID()) { 302 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 303 << Call->getSourceRange(); 304 return true; 305 } 306 307 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 308 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 309 << Call->getSourceRange(); 310 return true; 311 } 312 313 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 314 if (ChainResult.isInvalid()) 315 return true; 316 if (!ChainResult.get()->getType()->isPointerType()) { 317 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 318 << Chain->getSourceRange(); 319 return true; 320 } 321 322 QualType ReturnTy = CE->getCallReturnType(S.Context); 323 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 324 QualType BuiltinTy = S.Context.getFunctionType( 325 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 326 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 327 328 Builtin = 329 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 330 331 BuiltinCall->setType(CE->getType()); 332 BuiltinCall->setValueKind(CE->getValueKind()); 333 BuiltinCall->setObjectKind(CE->getObjectKind()); 334 BuiltinCall->setCallee(Builtin); 335 BuiltinCall->setArg(1, ChainResult.get()); 336 337 return false; 338 } 339 340 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 341 Scope::ScopeFlags NeededScopeFlags, 342 unsigned DiagID) { 343 // Scopes aren't available during instantiation. Fortunately, builtin 344 // functions cannot be template args so they cannot be formed through template 345 // instantiation. Therefore checking once during the parse is sufficient. 346 if (SemaRef.inTemplateInstantiation()) 347 return false; 348 349 Scope *S = SemaRef.getCurScope(); 350 while (S && !S->isSEHExceptScope()) 351 S = S->getParent(); 352 if (!S || !(S->getFlags() & NeededScopeFlags)) { 353 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 354 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 355 << DRE->getDecl()->getIdentifier(); 356 return true; 357 } 358 359 return false; 360 } 361 362 static inline bool isBlockPointer(Expr *Arg) { 363 return Arg->getType()->isBlockPointerType(); 364 } 365 366 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 367 /// void*, which is a requirement of device side enqueue. 368 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 369 const BlockPointerType *BPT = 370 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 371 ArrayRef<QualType> Params = 372 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 373 unsigned ArgCounter = 0; 374 bool IllegalParams = false; 375 // Iterate through the block parameters until either one is found that is not 376 // a local void*, or the block is valid. 377 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 378 I != E; ++I, ++ArgCounter) { 379 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 380 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 381 LangAS::opencl_local) { 382 // Get the location of the error. If a block literal has been passed 383 // (BlockExpr) then we can point straight to the offending argument, 384 // else we just point to the variable reference. 385 SourceLocation ErrorLoc; 386 if (isa<BlockExpr>(BlockArg)) { 387 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 388 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 389 } else if (isa<DeclRefExpr>(BlockArg)) { 390 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 391 } 392 S.Diag(ErrorLoc, 393 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 394 IllegalParams = true; 395 } 396 } 397 398 return IllegalParams; 399 } 400 401 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 402 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 403 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 404 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 405 return true; 406 } 407 return false; 408 } 409 410 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 411 if (checkArgCount(S, TheCall, 2)) 412 return true; 413 414 if (checkOpenCLSubgroupExt(S, TheCall)) 415 return true; 416 417 // First argument is an ndrange_t type. 418 Expr *NDRangeArg = TheCall->getArg(0); 419 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 420 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 421 << TheCall->getDirectCallee() << "'ndrange_t'"; 422 return true; 423 } 424 425 Expr *BlockArg = TheCall->getArg(1); 426 if (!isBlockPointer(BlockArg)) { 427 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 428 << TheCall->getDirectCallee() << "block"; 429 return true; 430 } 431 return checkOpenCLBlockArgs(S, BlockArg); 432 } 433 434 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 435 /// get_kernel_work_group_size 436 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 437 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 438 if (checkArgCount(S, TheCall, 1)) 439 return true; 440 441 Expr *BlockArg = TheCall->getArg(0); 442 if (!isBlockPointer(BlockArg)) { 443 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 444 << TheCall->getDirectCallee() << "block"; 445 return true; 446 } 447 return checkOpenCLBlockArgs(S, BlockArg); 448 } 449 450 /// Diagnose integer type and any valid implicit conversion to it. 451 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 452 const QualType &IntType); 453 454 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 455 unsigned Start, unsigned End) { 456 bool IllegalParams = false; 457 for (unsigned I = Start; I <= End; ++I) 458 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 459 S.Context.getSizeType()); 460 return IllegalParams; 461 } 462 463 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 464 /// 'local void*' parameter of passed block. 465 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 466 Expr *BlockArg, 467 unsigned NumNonVarArgs) { 468 const BlockPointerType *BPT = 469 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 470 unsigned NumBlockParams = 471 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 472 unsigned TotalNumArgs = TheCall->getNumArgs(); 473 474 // For each argument passed to the block, a corresponding uint needs to 475 // be passed to describe the size of the local memory. 476 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 477 S.Diag(TheCall->getBeginLoc(), 478 diag::err_opencl_enqueue_kernel_local_size_args); 479 return true; 480 } 481 482 // Check that the sizes of the local memory are specified by integers. 483 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 484 TotalNumArgs - 1); 485 } 486 487 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 488 /// overload formats specified in Table 6.13.17.1. 489 /// int enqueue_kernel(queue_t queue, 490 /// kernel_enqueue_flags_t flags, 491 /// const ndrange_t ndrange, 492 /// void (^block)(void)) 493 /// int enqueue_kernel(queue_t queue, 494 /// kernel_enqueue_flags_t flags, 495 /// const ndrange_t ndrange, 496 /// uint num_events_in_wait_list, 497 /// clk_event_t *event_wait_list, 498 /// clk_event_t *event_ret, 499 /// void (^block)(void)) 500 /// int enqueue_kernel(queue_t queue, 501 /// kernel_enqueue_flags_t flags, 502 /// const ndrange_t ndrange, 503 /// void (^block)(local void*, ...), 504 /// uint size0, ...) 505 /// int enqueue_kernel(queue_t queue, 506 /// kernel_enqueue_flags_t flags, 507 /// const ndrange_t ndrange, 508 /// uint num_events_in_wait_list, 509 /// clk_event_t *event_wait_list, 510 /// clk_event_t *event_ret, 511 /// void (^block)(local void*, ...), 512 /// uint size0, ...) 513 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 514 unsigned NumArgs = TheCall->getNumArgs(); 515 516 if (NumArgs < 4) { 517 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args); 518 return true; 519 } 520 521 Expr *Arg0 = TheCall->getArg(0); 522 Expr *Arg1 = TheCall->getArg(1); 523 Expr *Arg2 = TheCall->getArg(2); 524 Expr *Arg3 = TheCall->getArg(3); 525 526 // First argument always needs to be a queue_t type. 527 if (!Arg0->getType()->isQueueT()) { 528 S.Diag(TheCall->getArg(0)->getBeginLoc(), 529 diag::err_opencl_builtin_expected_type) 530 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 531 return true; 532 } 533 534 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 535 if (!Arg1->getType()->isIntegerType()) { 536 S.Diag(TheCall->getArg(1)->getBeginLoc(), 537 diag::err_opencl_builtin_expected_type) 538 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 539 return true; 540 } 541 542 // Third argument is always an ndrange_t type. 543 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 544 S.Diag(TheCall->getArg(2)->getBeginLoc(), 545 diag::err_opencl_builtin_expected_type) 546 << TheCall->getDirectCallee() << "'ndrange_t'"; 547 return true; 548 } 549 550 // With four arguments, there is only one form that the function could be 551 // called in: no events and no variable arguments. 552 if (NumArgs == 4) { 553 // check that the last argument is the right block type. 554 if (!isBlockPointer(Arg3)) { 555 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 556 << TheCall->getDirectCallee() << "block"; 557 return true; 558 } 559 // we have a block type, check the prototype 560 const BlockPointerType *BPT = 561 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 562 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 563 S.Diag(Arg3->getBeginLoc(), 564 diag::err_opencl_enqueue_kernel_blocks_no_args); 565 return true; 566 } 567 return false; 568 } 569 // we can have block + varargs. 570 if (isBlockPointer(Arg3)) 571 return (checkOpenCLBlockArgs(S, Arg3) || 572 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 573 // last two cases with either exactly 7 args or 7 args and varargs. 574 if (NumArgs >= 7) { 575 // check common block argument. 576 Expr *Arg6 = TheCall->getArg(6); 577 if (!isBlockPointer(Arg6)) { 578 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 579 << TheCall->getDirectCallee() << "block"; 580 return true; 581 } 582 if (checkOpenCLBlockArgs(S, Arg6)) 583 return true; 584 585 // Forth argument has to be any integer type. 586 if (!Arg3->getType()->isIntegerType()) { 587 S.Diag(TheCall->getArg(3)->getBeginLoc(), 588 diag::err_opencl_builtin_expected_type) 589 << TheCall->getDirectCallee() << "integer"; 590 return true; 591 } 592 // check remaining common arguments. 593 Expr *Arg4 = TheCall->getArg(4); 594 Expr *Arg5 = TheCall->getArg(5); 595 596 // Fifth argument is always passed as a pointer to clk_event_t. 597 if (!Arg4->isNullPointerConstant(S.Context, 598 Expr::NPC_ValueDependentIsNotNull) && 599 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 600 S.Diag(TheCall->getArg(4)->getBeginLoc(), 601 diag::err_opencl_builtin_expected_type) 602 << TheCall->getDirectCallee() 603 << S.Context.getPointerType(S.Context.OCLClkEventTy); 604 return true; 605 } 606 607 // Sixth argument is always passed as a pointer to clk_event_t. 608 if (!Arg5->isNullPointerConstant(S.Context, 609 Expr::NPC_ValueDependentIsNotNull) && 610 !(Arg5->getType()->isPointerType() && 611 Arg5->getType()->getPointeeType()->isClkEventT())) { 612 S.Diag(TheCall->getArg(5)->getBeginLoc(), 613 diag::err_opencl_builtin_expected_type) 614 << TheCall->getDirectCallee() 615 << S.Context.getPointerType(S.Context.OCLClkEventTy); 616 return true; 617 } 618 619 if (NumArgs == 7) 620 return false; 621 622 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 623 } 624 625 // None of the specific case has been detected, give generic error 626 S.Diag(TheCall->getBeginLoc(), 627 diag::err_opencl_enqueue_kernel_incorrect_args); 628 return true; 629 } 630 631 /// Returns OpenCL access qual. 632 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 633 return D->getAttr<OpenCLAccessAttr>(); 634 } 635 636 /// Returns true if pipe element type is different from the pointer. 637 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 638 const Expr *Arg0 = Call->getArg(0); 639 // First argument type should always be pipe. 640 if (!Arg0->getType()->isPipeType()) { 641 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 642 << Call->getDirectCallee() << Arg0->getSourceRange(); 643 return true; 644 } 645 OpenCLAccessAttr *AccessQual = 646 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 647 // Validates the access qualifier is compatible with the call. 648 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 649 // read_only and write_only, and assumed to be read_only if no qualifier is 650 // specified. 651 switch (Call->getDirectCallee()->getBuiltinID()) { 652 case Builtin::BIread_pipe: 653 case Builtin::BIreserve_read_pipe: 654 case Builtin::BIcommit_read_pipe: 655 case Builtin::BIwork_group_reserve_read_pipe: 656 case Builtin::BIsub_group_reserve_read_pipe: 657 case Builtin::BIwork_group_commit_read_pipe: 658 case Builtin::BIsub_group_commit_read_pipe: 659 if (!(!AccessQual || AccessQual->isReadOnly())) { 660 S.Diag(Arg0->getBeginLoc(), 661 diag::err_opencl_builtin_pipe_invalid_access_modifier) 662 << "read_only" << Arg0->getSourceRange(); 663 return true; 664 } 665 break; 666 case Builtin::BIwrite_pipe: 667 case Builtin::BIreserve_write_pipe: 668 case Builtin::BIcommit_write_pipe: 669 case Builtin::BIwork_group_reserve_write_pipe: 670 case Builtin::BIsub_group_reserve_write_pipe: 671 case Builtin::BIwork_group_commit_write_pipe: 672 case Builtin::BIsub_group_commit_write_pipe: 673 if (!(AccessQual && AccessQual->isWriteOnly())) { 674 S.Diag(Arg0->getBeginLoc(), 675 diag::err_opencl_builtin_pipe_invalid_access_modifier) 676 << "write_only" << Arg0->getSourceRange(); 677 return true; 678 } 679 break; 680 default: 681 break; 682 } 683 return false; 684 } 685 686 /// Returns true if pipe element type is different from the pointer. 687 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 688 const Expr *Arg0 = Call->getArg(0); 689 const Expr *ArgIdx = Call->getArg(Idx); 690 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 691 const QualType EltTy = PipeTy->getElementType(); 692 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 693 // The Idx argument should be a pointer and the type of the pointer and 694 // the type of pipe element should also be the same. 695 if (!ArgTy || 696 !S.Context.hasSameType( 697 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 698 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 699 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 700 << ArgIdx->getType() << ArgIdx->getSourceRange(); 701 return true; 702 } 703 return false; 704 } 705 706 // Performs semantic analysis for the read/write_pipe call. 707 // \param S Reference to the semantic analyzer. 708 // \param Call A pointer to the builtin call. 709 // \return True if a semantic error has been found, false otherwise. 710 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 711 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 712 // functions have two forms. 713 switch (Call->getNumArgs()) { 714 case 2: 715 if (checkOpenCLPipeArg(S, Call)) 716 return true; 717 // The call with 2 arguments should be 718 // read/write_pipe(pipe T, T*). 719 // Check packet type T. 720 if (checkOpenCLPipePacketType(S, Call, 1)) 721 return true; 722 break; 723 724 case 4: { 725 if (checkOpenCLPipeArg(S, Call)) 726 return true; 727 // The call with 4 arguments should be 728 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 729 // Check reserve_id_t. 730 if (!Call->getArg(1)->getType()->isReserveIDT()) { 731 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 732 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 733 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 734 return true; 735 } 736 737 // Check the index. 738 const Expr *Arg2 = Call->getArg(2); 739 if (!Arg2->getType()->isIntegerType() && 740 !Arg2->getType()->isUnsignedIntegerType()) { 741 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 742 << Call->getDirectCallee() << S.Context.UnsignedIntTy 743 << Arg2->getType() << Arg2->getSourceRange(); 744 return true; 745 } 746 747 // Check packet type T. 748 if (checkOpenCLPipePacketType(S, Call, 3)) 749 return true; 750 } break; 751 default: 752 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 753 << Call->getDirectCallee() << Call->getSourceRange(); 754 return true; 755 } 756 757 return false; 758 } 759 760 // Performs a semantic analysis on the {work_group_/sub_group_ 761 // /_}reserve_{read/write}_pipe 762 // \param S Reference to the semantic analyzer. 763 // \param Call The call to the builtin function to be analyzed. 764 // \return True if a semantic error was found, false otherwise. 765 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 766 if (checkArgCount(S, Call, 2)) 767 return true; 768 769 if (checkOpenCLPipeArg(S, Call)) 770 return true; 771 772 // Check the reserve size. 773 if (!Call->getArg(1)->getType()->isIntegerType() && 774 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 775 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 776 << Call->getDirectCallee() << S.Context.UnsignedIntTy 777 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 778 return true; 779 } 780 781 // Since return type of reserve_read/write_pipe built-in function is 782 // reserve_id_t, which is not defined in the builtin def file , we used int 783 // as return type and need to override the return type of these functions. 784 Call->setType(S.Context.OCLReserveIDTy); 785 786 return false; 787 } 788 789 // Performs a semantic analysis on {work_group_/sub_group_ 790 // /_}commit_{read/write}_pipe 791 // \param S Reference to the semantic analyzer. 792 // \param Call The call to the builtin function to be analyzed. 793 // \return True if a semantic error was found, false otherwise. 794 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 795 if (checkArgCount(S, Call, 2)) 796 return true; 797 798 if (checkOpenCLPipeArg(S, Call)) 799 return true; 800 801 // Check reserve_id_t. 802 if (!Call->getArg(1)->getType()->isReserveIDT()) { 803 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 804 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 805 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 806 return true; 807 } 808 809 return false; 810 } 811 812 // Performs a semantic analysis on the call to built-in Pipe 813 // Query Functions. 814 // \param S Reference to the semantic analyzer. 815 // \param Call The call to the builtin function to be analyzed. 816 // \return True if a semantic error was found, false otherwise. 817 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 818 if (checkArgCount(S, Call, 1)) 819 return true; 820 821 if (!Call->getArg(0)->getType()->isPipeType()) { 822 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 823 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 824 return true; 825 } 826 827 return false; 828 } 829 830 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 831 // Performs semantic analysis for the to_global/local/private call. 832 // \param S Reference to the semantic analyzer. 833 // \param BuiltinID ID of the builtin function. 834 // \param Call A pointer to the builtin call. 835 // \return True if a semantic error has been found, false otherwise. 836 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 837 CallExpr *Call) { 838 if (Call->getNumArgs() != 1) { 839 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 840 << Call->getDirectCallee() << Call->getSourceRange(); 841 return true; 842 } 843 844 auto RT = Call->getArg(0)->getType(); 845 if (!RT->isPointerType() || RT->getPointeeType() 846 .getAddressSpace() == LangAS::opencl_constant) { 847 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 848 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 849 return true; 850 } 851 852 RT = RT->getPointeeType(); 853 auto Qual = RT.getQualifiers(); 854 switch (BuiltinID) { 855 case Builtin::BIto_global: 856 Qual.setAddressSpace(LangAS::opencl_global); 857 break; 858 case Builtin::BIto_local: 859 Qual.setAddressSpace(LangAS::opencl_local); 860 break; 861 case Builtin::BIto_private: 862 Qual.setAddressSpace(LangAS::opencl_private); 863 break; 864 default: 865 llvm_unreachable("Invalid builtin function"); 866 } 867 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 868 RT.getUnqualifiedType(), Qual))); 869 870 return false; 871 } 872 873 // Emit an error and return true if the current architecture is not in the list 874 // of supported architectures. 875 static bool 876 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 877 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 878 llvm::Triple::ArchType CurArch = 879 S.getASTContext().getTargetInfo().getTriple().getArch(); 880 if (llvm::is_contained(SupportedArchs, CurArch)) 881 return false; 882 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 883 << TheCall->getSourceRange(); 884 return true; 885 } 886 887 ExprResult 888 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 889 CallExpr *TheCall) { 890 ExprResult TheCallResult(TheCall); 891 892 // Find out if any arguments are required to be integer constant expressions. 893 unsigned ICEArguments = 0; 894 ASTContext::GetBuiltinTypeError Error; 895 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 896 if (Error != ASTContext::GE_None) 897 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 898 899 // If any arguments are required to be ICE's, check and diagnose. 900 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 901 // Skip arguments not required to be ICE's. 902 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 903 904 llvm::APSInt Result; 905 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 906 return true; 907 ICEArguments &= ~(1 << ArgNo); 908 } 909 910 switch (BuiltinID) { 911 case Builtin::BI__builtin___CFStringMakeConstantString: 912 assert(TheCall->getNumArgs() == 1 && 913 "Wrong # arguments to builtin CFStringMakeConstantString"); 914 if (CheckObjCString(TheCall->getArg(0))) 915 return ExprError(); 916 break; 917 case Builtin::BI__builtin_ms_va_start: 918 case Builtin::BI__builtin_stdarg_start: 919 case Builtin::BI__builtin_va_start: 920 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 921 return ExprError(); 922 break; 923 case Builtin::BI__va_start: { 924 switch (Context.getTargetInfo().getTriple().getArch()) { 925 case llvm::Triple::arm: 926 case llvm::Triple::thumb: 927 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 928 return ExprError(); 929 break; 930 default: 931 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 932 return ExprError(); 933 break; 934 } 935 break; 936 } 937 938 // The acquire, release, and no fence variants are ARM and AArch64 only. 939 case Builtin::BI_interlockedbittestandset_acq: 940 case Builtin::BI_interlockedbittestandset_rel: 941 case Builtin::BI_interlockedbittestandset_nf: 942 case Builtin::BI_interlockedbittestandreset_acq: 943 case Builtin::BI_interlockedbittestandreset_rel: 944 case Builtin::BI_interlockedbittestandreset_nf: 945 if (CheckBuiltinTargetSupport( 946 *this, BuiltinID, TheCall, 947 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 948 return ExprError(); 949 break; 950 951 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 952 case Builtin::BI_bittest64: 953 case Builtin::BI_bittestandcomplement64: 954 case Builtin::BI_bittestandreset64: 955 case Builtin::BI_bittestandset64: 956 case Builtin::BI_interlockedbittestandreset64: 957 case Builtin::BI_interlockedbittestandset64: 958 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 959 {llvm::Triple::x86_64, llvm::Triple::arm, 960 llvm::Triple::thumb, llvm::Triple::aarch64})) 961 return ExprError(); 962 break; 963 964 case Builtin::BI__builtin_isgreater: 965 case Builtin::BI__builtin_isgreaterequal: 966 case Builtin::BI__builtin_isless: 967 case Builtin::BI__builtin_islessequal: 968 case Builtin::BI__builtin_islessgreater: 969 case Builtin::BI__builtin_isunordered: 970 if (SemaBuiltinUnorderedCompare(TheCall)) 971 return ExprError(); 972 break; 973 case Builtin::BI__builtin_fpclassify: 974 if (SemaBuiltinFPClassification(TheCall, 6)) 975 return ExprError(); 976 break; 977 case Builtin::BI__builtin_isfinite: 978 case Builtin::BI__builtin_isinf: 979 case Builtin::BI__builtin_isinf_sign: 980 case Builtin::BI__builtin_isnan: 981 case Builtin::BI__builtin_isnormal: 982 case Builtin::BI__builtin_signbit: 983 case Builtin::BI__builtin_signbitf: 984 case Builtin::BI__builtin_signbitl: 985 if (SemaBuiltinFPClassification(TheCall, 1)) 986 return ExprError(); 987 break; 988 case Builtin::BI__builtin_shufflevector: 989 return SemaBuiltinShuffleVector(TheCall); 990 // TheCall will be freed by the smart pointer here, but that's fine, since 991 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 992 case Builtin::BI__builtin_prefetch: 993 if (SemaBuiltinPrefetch(TheCall)) 994 return ExprError(); 995 break; 996 case Builtin::BI__builtin_alloca_with_align: 997 if (SemaBuiltinAllocaWithAlign(TheCall)) 998 return ExprError(); 999 break; 1000 case Builtin::BI__assume: 1001 case Builtin::BI__builtin_assume: 1002 if (SemaBuiltinAssume(TheCall)) 1003 return ExprError(); 1004 break; 1005 case Builtin::BI__builtin_assume_aligned: 1006 if (SemaBuiltinAssumeAligned(TheCall)) 1007 return ExprError(); 1008 break; 1009 case Builtin::BI__builtin_object_size: 1010 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1011 return ExprError(); 1012 break; 1013 case Builtin::BI__builtin_longjmp: 1014 if (SemaBuiltinLongjmp(TheCall)) 1015 return ExprError(); 1016 break; 1017 case Builtin::BI__builtin_setjmp: 1018 if (SemaBuiltinSetjmp(TheCall)) 1019 return ExprError(); 1020 break; 1021 case Builtin::BI_setjmp: 1022 case Builtin::BI_setjmpex: 1023 if (checkArgCount(*this, TheCall, 1)) 1024 return true; 1025 break; 1026 case Builtin::BI__builtin_classify_type: 1027 if (checkArgCount(*this, TheCall, 1)) return true; 1028 TheCall->setType(Context.IntTy); 1029 break; 1030 case Builtin::BI__builtin_constant_p: 1031 if (checkArgCount(*this, TheCall, 1)) return true; 1032 TheCall->setType(Context.IntTy); 1033 break; 1034 case Builtin::BI__sync_fetch_and_add: 1035 case Builtin::BI__sync_fetch_and_add_1: 1036 case Builtin::BI__sync_fetch_and_add_2: 1037 case Builtin::BI__sync_fetch_and_add_4: 1038 case Builtin::BI__sync_fetch_and_add_8: 1039 case Builtin::BI__sync_fetch_and_add_16: 1040 case Builtin::BI__sync_fetch_and_sub: 1041 case Builtin::BI__sync_fetch_and_sub_1: 1042 case Builtin::BI__sync_fetch_and_sub_2: 1043 case Builtin::BI__sync_fetch_and_sub_4: 1044 case Builtin::BI__sync_fetch_and_sub_8: 1045 case Builtin::BI__sync_fetch_and_sub_16: 1046 case Builtin::BI__sync_fetch_and_or: 1047 case Builtin::BI__sync_fetch_and_or_1: 1048 case Builtin::BI__sync_fetch_and_or_2: 1049 case Builtin::BI__sync_fetch_and_or_4: 1050 case Builtin::BI__sync_fetch_and_or_8: 1051 case Builtin::BI__sync_fetch_and_or_16: 1052 case Builtin::BI__sync_fetch_and_and: 1053 case Builtin::BI__sync_fetch_and_and_1: 1054 case Builtin::BI__sync_fetch_and_and_2: 1055 case Builtin::BI__sync_fetch_and_and_4: 1056 case Builtin::BI__sync_fetch_and_and_8: 1057 case Builtin::BI__sync_fetch_and_and_16: 1058 case Builtin::BI__sync_fetch_and_xor: 1059 case Builtin::BI__sync_fetch_and_xor_1: 1060 case Builtin::BI__sync_fetch_and_xor_2: 1061 case Builtin::BI__sync_fetch_and_xor_4: 1062 case Builtin::BI__sync_fetch_and_xor_8: 1063 case Builtin::BI__sync_fetch_and_xor_16: 1064 case Builtin::BI__sync_fetch_and_nand: 1065 case Builtin::BI__sync_fetch_and_nand_1: 1066 case Builtin::BI__sync_fetch_and_nand_2: 1067 case Builtin::BI__sync_fetch_and_nand_4: 1068 case Builtin::BI__sync_fetch_and_nand_8: 1069 case Builtin::BI__sync_fetch_and_nand_16: 1070 case Builtin::BI__sync_add_and_fetch: 1071 case Builtin::BI__sync_add_and_fetch_1: 1072 case Builtin::BI__sync_add_and_fetch_2: 1073 case Builtin::BI__sync_add_and_fetch_4: 1074 case Builtin::BI__sync_add_and_fetch_8: 1075 case Builtin::BI__sync_add_and_fetch_16: 1076 case Builtin::BI__sync_sub_and_fetch: 1077 case Builtin::BI__sync_sub_and_fetch_1: 1078 case Builtin::BI__sync_sub_and_fetch_2: 1079 case Builtin::BI__sync_sub_and_fetch_4: 1080 case Builtin::BI__sync_sub_and_fetch_8: 1081 case Builtin::BI__sync_sub_and_fetch_16: 1082 case Builtin::BI__sync_and_and_fetch: 1083 case Builtin::BI__sync_and_and_fetch_1: 1084 case Builtin::BI__sync_and_and_fetch_2: 1085 case Builtin::BI__sync_and_and_fetch_4: 1086 case Builtin::BI__sync_and_and_fetch_8: 1087 case Builtin::BI__sync_and_and_fetch_16: 1088 case Builtin::BI__sync_or_and_fetch: 1089 case Builtin::BI__sync_or_and_fetch_1: 1090 case Builtin::BI__sync_or_and_fetch_2: 1091 case Builtin::BI__sync_or_and_fetch_4: 1092 case Builtin::BI__sync_or_and_fetch_8: 1093 case Builtin::BI__sync_or_and_fetch_16: 1094 case Builtin::BI__sync_xor_and_fetch: 1095 case Builtin::BI__sync_xor_and_fetch_1: 1096 case Builtin::BI__sync_xor_and_fetch_2: 1097 case Builtin::BI__sync_xor_and_fetch_4: 1098 case Builtin::BI__sync_xor_and_fetch_8: 1099 case Builtin::BI__sync_xor_and_fetch_16: 1100 case Builtin::BI__sync_nand_and_fetch: 1101 case Builtin::BI__sync_nand_and_fetch_1: 1102 case Builtin::BI__sync_nand_and_fetch_2: 1103 case Builtin::BI__sync_nand_and_fetch_4: 1104 case Builtin::BI__sync_nand_and_fetch_8: 1105 case Builtin::BI__sync_nand_and_fetch_16: 1106 case Builtin::BI__sync_val_compare_and_swap: 1107 case Builtin::BI__sync_val_compare_and_swap_1: 1108 case Builtin::BI__sync_val_compare_and_swap_2: 1109 case Builtin::BI__sync_val_compare_and_swap_4: 1110 case Builtin::BI__sync_val_compare_and_swap_8: 1111 case Builtin::BI__sync_val_compare_and_swap_16: 1112 case Builtin::BI__sync_bool_compare_and_swap: 1113 case Builtin::BI__sync_bool_compare_and_swap_1: 1114 case Builtin::BI__sync_bool_compare_and_swap_2: 1115 case Builtin::BI__sync_bool_compare_and_swap_4: 1116 case Builtin::BI__sync_bool_compare_and_swap_8: 1117 case Builtin::BI__sync_bool_compare_and_swap_16: 1118 case Builtin::BI__sync_lock_test_and_set: 1119 case Builtin::BI__sync_lock_test_and_set_1: 1120 case Builtin::BI__sync_lock_test_and_set_2: 1121 case Builtin::BI__sync_lock_test_and_set_4: 1122 case Builtin::BI__sync_lock_test_and_set_8: 1123 case Builtin::BI__sync_lock_test_and_set_16: 1124 case Builtin::BI__sync_lock_release: 1125 case Builtin::BI__sync_lock_release_1: 1126 case Builtin::BI__sync_lock_release_2: 1127 case Builtin::BI__sync_lock_release_4: 1128 case Builtin::BI__sync_lock_release_8: 1129 case Builtin::BI__sync_lock_release_16: 1130 case Builtin::BI__sync_swap: 1131 case Builtin::BI__sync_swap_1: 1132 case Builtin::BI__sync_swap_2: 1133 case Builtin::BI__sync_swap_4: 1134 case Builtin::BI__sync_swap_8: 1135 case Builtin::BI__sync_swap_16: 1136 return SemaBuiltinAtomicOverloaded(TheCallResult); 1137 case Builtin::BI__sync_synchronize: 1138 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1139 << TheCall->getCallee()->getSourceRange(); 1140 break; 1141 case Builtin::BI__builtin_nontemporal_load: 1142 case Builtin::BI__builtin_nontemporal_store: 1143 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1144 #define BUILTIN(ID, TYPE, ATTRS) 1145 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1146 case Builtin::BI##ID: \ 1147 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1148 #include "clang/Basic/Builtins.def" 1149 case Builtin::BI__annotation: 1150 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1151 return ExprError(); 1152 break; 1153 case Builtin::BI__builtin_annotation: 1154 if (SemaBuiltinAnnotation(*this, TheCall)) 1155 return ExprError(); 1156 break; 1157 case Builtin::BI__builtin_addressof: 1158 if (SemaBuiltinAddressof(*this, TheCall)) 1159 return ExprError(); 1160 break; 1161 case Builtin::BI__builtin_add_overflow: 1162 case Builtin::BI__builtin_sub_overflow: 1163 case Builtin::BI__builtin_mul_overflow: 1164 if (SemaBuiltinOverflow(*this, TheCall)) 1165 return ExprError(); 1166 break; 1167 case Builtin::BI__builtin_operator_new: 1168 case Builtin::BI__builtin_operator_delete: { 1169 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1170 ExprResult Res = 1171 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1172 if (Res.isInvalid()) 1173 CorrectDelayedTyposInExpr(TheCallResult.get()); 1174 return Res; 1175 } 1176 case Builtin::BI__builtin_dump_struct: { 1177 // We first want to ensure we are called with 2 arguments 1178 if (checkArgCount(*this, TheCall, 2)) 1179 return ExprError(); 1180 // Ensure that the first argument is of type 'struct XX *' 1181 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1182 const QualType PtrArgType = PtrArg->getType(); 1183 if (!PtrArgType->isPointerType() || 1184 !PtrArgType->getPointeeType()->isRecordType()) { 1185 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1186 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1187 << "structure pointer"; 1188 return ExprError(); 1189 } 1190 1191 // Ensure that the second argument is of type 'FunctionType' 1192 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1193 const QualType FnPtrArgType = FnPtrArg->getType(); 1194 if (!FnPtrArgType->isPointerType()) { 1195 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1196 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1197 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1198 return ExprError(); 1199 } 1200 1201 const auto *FuncType = 1202 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1203 1204 if (!FuncType) { 1205 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1206 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1207 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1208 return ExprError(); 1209 } 1210 1211 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1212 if (!FT->getNumParams()) { 1213 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1214 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1215 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1216 return ExprError(); 1217 } 1218 QualType PT = FT->getParamType(0); 1219 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1220 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1221 !PT->getPointeeType().isConstQualified()) { 1222 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1223 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1224 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1225 return ExprError(); 1226 } 1227 } 1228 1229 TheCall->setType(Context.IntTy); 1230 break; 1231 } 1232 1233 // check secure string manipulation functions where overflows 1234 // are detectable at compile time 1235 case Builtin::BI__builtin___memcpy_chk: 1236 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy"); 1237 break; 1238 case Builtin::BI__builtin___memmove_chk: 1239 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove"); 1240 break; 1241 case Builtin::BI__builtin___memset_chk: 1242 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset"); 1243 break; 1244 case Builtin::BI__builtin___strlcat_chk: 1245 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat"); 1246 break; 1247 case Builtin::BI__builtin___strlcpy_chk: 1248 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy"); 1249 break; 1250 case Builtin::BI__builtin___strncat_chk: 1251 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat"); 1252 break; 1253 case Builtin::BI__builtin___strncpy_chk: 1254 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy"); 1255 break; 1256 case Builtin::BI__builtin___stpncpy_chk: 1257 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy"); 1258 break; 1259 case Builtin::BI__builtin___memccpy_chk: 1260 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy"); 1261 break; 1262 case Builtin::BI__builtin___snprintf_chk: 1263 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf"); 1264 break; 1265 case Builtin::BI__builtin___vsnprintf_chk: 1266 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf"); 1267 break; 1268 case Builtin::BI__builtin_call_with_static_chain: 1269 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1270 return ExprError(); 1271 break; 1272 case Builtin::BI__exception_code: 1273 case Builtin::BI_exception_code: 1274 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1275 diag::err_seh___except_block)) 1276 return ExprError(); 1277 break; 1278 case Builtin::BI__exception_info: 1279 case Builtin::BI_exception_info: 1280 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1281 diag::err_seh___except_filter)) 1282 return ExprError(); 1283 break; 1284 case Builtin::BI__GetExceptionInfo: 1285 if (checkArgCount(*this, TheCall, 1)) 1286 return ExprError(); 1287 1288 if (CheckCXXThrowOperand( 1289 TheCall->getBeginLoc(), 1290 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1291 TheCall)) 1292 return ExprError(); 1293 1294 TheCall->setType(Context.VoidPtrTy); 1295 break; 1296 // OpenCL v2.0, s6.13.16 - Pipe functions 1297 case Builtin::BIread_pipe: 1298 case Builtin::BIwrite_pipe: 1299 // Since those two functions are declared with var args, we need a semantic 1300 // check for the argument. 1301 if (SemaBuiltinRWPipe(*this, TheCall)) 1302 return ExprError(); 1303 TheCall->setType(Context.IntTy); 1304 break; 1305 case Builtin::BIreserve_read_pipe: 1306 case Builtin::BIreserve_write_pipe: 1307 case Builtin::BIwork_group_reserve_read_pipe: 1308 case Builtin::BIwork_group_reserve_write_pipe: 1309 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1310 return ExprError(); 1311 break; 1312 case Builtin::BIsub_group_reserve_read_pipe: 1313 case Builtin::BIsub_group_reserve_write_pipe: 1314 if (checkOpenCLSubgroupExt(*this, TheCall) || 1315 SemaBuiltinReserveRWPipe(*this, TheCall)) 1316 return ExprError(); 1317 break; 1318 case Builtin::BIcommit_read_pipe: 1319 case Builtin::BIcommit_write_pipe: 1320 case Builtin::BIwork_group_commit_read_pipe: 1321 case Builtin::BIwork_group_commit_write_pipe: 1322 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1323 return ExprError(); 1324 break; 1325 case Builtin::BIsub_group_commit_read_pipe: 1326 case Builtin::BIsub_group_commit_write_pipe: 1327 if (checkOpenCLSubgroupExt(*this, TheCall) || 1328 SemaBuiltinCommitRWPipe(*this, TheCall)) 1329 return ExprError(); 1330 break; 1331 case Builtin::BIget_pipe_num_packets: 1332 case Builtin::BIget_pipe_max_packets: 1333 if (SemaBuiltinPipePackets(*this, TheCall)) 1334 return ExprError(); 1335 TheCall->setType(Context.UnsignedIntTy); 1336 break; 1337 case Builtin::BIto_global: 1338 case Builtin::BIto_local: 1339 case Builtin::BIto_private: 1340 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1341 return ExprError(); 1342 break; 1343 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1344 case Builtin::BIenqueue_kernel: 1345 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1346 return ExprError(); 1347 break; 1348 case Builtin::BIget_kernel_work_group_size: 1349 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1350 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1351 return ExprError(); 1352 break; 1353 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1354 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1355 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1356 return ExprError(); 1357 break; 1358 case Builtin::BI__builtin_os_log_format: 1359 case Builtin::BI__builtin_os_log_format_buffer_size: 1360 if (SemaBuiltinOSLogFormat(TheCall)) 1361 return ExprError(); 1362 break; 1363 } 1364 1365 // Since the target specific builtins for each arch overlap, only check those 1366 // of the arch we are compiling for. 1367 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1368 switch (Context.getTargetInfo().getTriple().getArch()) { 1369 case llvm::Triple::arm: 1370 case llvm::Triple::armeb: 1371 case llvm::Triple::thumb: 1372 case llvm::Triple::thumbeb: 1373 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1374 return ExprError(); 1375 break; 1376 case llvm::Triple::aarch64: 1377 case llvm::Triple::aarch64_be: 1378 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1379 return ExprError(); 1380 break; 1381 case llvm::Triple::hexagon: 1382 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1383 return ExprError(); 1384 break; 1385 case llvm::Triple::mips: 1386 case llvm::Triple::mipsel: 1387 case llvm::Triple::mips64: 1388 case llvm::Triple::mips64el: 1389 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1390 return ExprError(); 1391 break; 1392 case llvm::Triple::systemz: 1393 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1394 return ExprError(); 1395 break; 1396 case llvm::Triple::x86: 1397 case llvm::Triple::x86_64: 1398 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1399 return ExprError(); 1400 break; 1401 case llvm::Triple::ppc: 1402 case llvm::Triple::ppc64: 1403 case llvm::Triple::ppc64le: 1404 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1405 return ExprError(); 1406 break; 1407 default: 1408 break; 1409 } 1410 } 1411 1412 return TheCallResult; 1413 } 1414 1415 // Get the valid immediate range for the specified NEON type code. 1416 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1417 NeonTypeFlags Type(t); 1418 int IsQuad = ForceQuad ? true : Type.isQuad(); 1419 switch (Type.getEltType()) { 1420 case NeonTypeFlags::Int8: 1421 case NeonTypeFlags::Poly8: 1422 return shift ? 7 : (8 << IsQuad) - 1; 1423 case NeonTypeFlags::Int16: 1424 case NeonTypeFlags::Poly16: 1425 return shift ? 15 : (4 << IsQuad) - 1; 1426 case NeonTypeFlags::Int32: 1427 return shift ? 31 : (2 << IsQuad) - 1; 1428 case NeonTypeFlags::Int64: 1429 case NeonTypeFlags::Poly64: 1430 return shift ? 63 : (1 << IsQuad) - 1; 1431 case NeonTypeFlags::Poly128: 1432 return shift ? 127 : (1 << IsQuad) - 1; 1433 case NeonTypeFlags::Float16: 1434 assert(!shift && "cannot shift float types!"); 1435 return (4 << IsQuad) - 1; 1436 case NeonTypeFlags::Float32: 1437 assert(!shift && "cannot shift float types!"); 1438 return (2 << IsQuad) - 1; 1439 case NeonTypeFlags::Float64: 1440 assert(!shift && "cannot shift float types!"); 1441 return (1 << IsQuad) - 1; 1442 } 1443 llvm_unreachable("Invalid NeonTypeFlag!"); 1444 } 1445 1446 /// getNeonEltType - Return the QualType corresponding to the elements of 1447 /// the vector type specified by the NeonTypeFlags. This is used to check 1448 /// the pointer arguments for Neon load/store intrinsics. 1449 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1450 bool IsPolyUnsigned, bool IsInt64Long) { 1451 switch (Flags.getEltType()) { 1452 case NeonTypeFlags::Int8: 1453 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1454 case NeonTypeFlags::Int16: 1455 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1456 case NeonTypeFlags::Int32: 1457 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1458 case NeonTypeFlags::Int64: 1459 if (IsInt64Long) 1460 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1461 else 1462 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1463 : Context.LongLongTy; 1464 case NeonTypeFlags::Poly8: 1465 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1466 case NeonTypeFlags::Poly16: 1467 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1468 case NeonTypeFlags::Poly64: 1469 if (IsInt64Long) 1470 return Context.UnsignedLongTy; 1471 else 1472 return Context.UnsignedLongLongTy; 1473 case NeonTypeFlags::Poly128: 1474 break; 1475 case NeonTypeFlags::Float16: 1476 return Context.HalfTy; 1477 case NeonTypeFlags::Float32: 1478 return Context.FloatTy; 1479 case NeonTypeFlags::Float64: 1480 return Context.DoubleTy; 1481 } 1482 llvm_unreachable("Invalid NeonTypeFlag!"); 1483 } 1484 1485 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1486 llvm::APSInt Result; 1487 uint64_t mask = 0; 1488 unsigned TV = 0; 1489 int PtrArgNum = -1; 1490 bool HasConstPtr = false; 1491 switch (BuiltinID) { 1492 #define GET_NEON_OVERLOAD_CHECK 1493 #include "clang/Basic/arm_neon.inc" 1494 #include "clang/Basic/arm_fp16.inc" 1495 #undef GET_NEON_OVERLOAD_CHECK 1496 } 1497 1498 // For NEON intrinsics which are overloaded on vector element type, validate 1499 // the immediate which specifies which variant to emit. 1500 unsigned ImmArg = TheCall->getNumArgs()-1; 1501 if (mask) { 1502 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1503 return true; 1504 1505 TV = Result.getLimitedValue(64); 1506 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1507 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1508 << TheCall->getArg(ImmArg)->getSourceRange(); 1509 } 1510 1511 if (PtrArgNum >= 0) { 1512 // Check that pointer arguments have the specified type. 1513 Expr *Arg = TheCall->getArg(PtrArgNum); 1514 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1515 Arg = ICE->getSubExpr(); 1516 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1517 QualType RHSTy = RHS.get()->getType(); 1518 1519 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1520 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1521 Arch == llvm::Triple::aarch64_be; 1522 bool IsInt64Long = 1523 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1524 QualType EltTy = 1525 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1526 if (HasConstPtr) 1527 EltTy = EltTy.withConst(); 1528 QualType LHSTy = Context.getPointerType(EltTy); 1529 AssignConvertType ConvTy; 1530 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1531 if (RHS.isInvalid()) 1532 return true; 1533 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1534 RHS.get(), AA_Assigning)) 1535 return true; 1536 } 1537 1538 // For NEON intrinsics which take an immediate value as part of the 1539 // instruction, range check them here. 1540 unsigned i = 0, l = 0, u = 0; 1541 switch (BuiltinID) { 1542 default: 1543 return false; 1544 #define GET_NEON_IMMEDIATE_CHECK 1545 #include "clang/Basic/arm_neon.inc" 1546 #include "clang/Basic/arm_fp16.inc" 1547 #undef GET_NEON_IMMEDIATE_CHECK 1548 } 1549 1550 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1551 } 1552 1553 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1554 unsigned MaxWidth) { 1555 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1556 BuiltinID == ARM::BI__builtin_arm_ldaex || 1557 BuiltinID == ARM::BI__builtin_arm_strex || 1558 BuiltinID == ARM::BI__builtin_arm_stlex || 1559 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1560 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1561 BuiltinID == AArch64::BI__builtin_arm_strex || 1562 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1563 "unexpected ARM builtin"); 1564 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1565 BuiltinID == ARM::BI__builtin_arm_ldaex || 1566 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1567 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1568 1569 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1570 1571 // Ensure that we have the proper number of arguments. 1572 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1573 return true; 1574 1575 // Inspect the pointer argument of the atomic builtin. This should always be 1576 // a pointer type, whose element is an integral scalar or pointer type. 1577 // Because it is a pointer type, we don't have to worry about any implicit 1578 // casts here. 1579 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1580 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1581 if (PointerArgRes.isInvalid()) 1582 return true; 1583 PointerArg = PointerArgRes.get(); 1584 1585 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1586 if (!pointerType) { 1587 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1588 << PointerArg->getType() << PointerArg->getSourceRange(); 1589 return true; 1590 } 1591 1592 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1593 // task is to insert the appropriate casts into the AST. First work out just 1594 // what the appropriate type is. 1595 QualType ValType = pointerType->getPointeeType(); 1596 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1597 if (IsLdrex) 1598 AddrType.addConst(); 1599 1600 // Issue a warning if the cast is dodgy. 1601 CastKind CastNeeded = CK_NoOp; 1602 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1603 CastNeeded = CK_BitCast; 1604 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1605 << PointerArg->getType() << Context.getPointerType(AddrType) 1606 << AA_Passing << PointerArg->getSourceRange(); 1607 } 1608 1609 // Finally, do the cast and replace the argument with the corrected version. 1610 AddrType = Context.getPointerType(AddrType); 1611 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1612 if (PointerArgRes.isInvalid()) 1613 return true; 1614 PointerArg = PointerArgRes.get(); 1615 1616 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1617 1618 // In general, we allow ints, floats and pointers to be loaded and stored. 1619 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1620 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1621 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1622 << PointerArg->getType() << PointerArg->getSourceRange(); 1623 return true; 1624 } 1625 1626 // But ARM doesn't have instructions to deal with 128-bit versions. 1627 if (Context.getTypeSize(ValType) > MaxWidth) { 1628 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1629 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1630 << PointerArg->getType() << PointerArg->getSourceRange(); 1631 return true; 1632 } 1633 1634 switch (ValType.getObjCLifetime()) { 1635 case Qualifiers::OCL_None: 1636 case Qualifiers::OCL_ExplicitNone: 1637 // okay 1638 break; 1639 1640 case Qualifiers::OCL_Weak: 1641 case Qualifiers::OCL_Strong: 1642 case Qualifiers::OCL_Autoreleasing: 1643 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1644 << ValType << PointerArg->getSourceRange(); 1645 return true; 1646 } 1647 1648 if (IsLdrex) { 1649 TheCall->setType(ValType); 1650 return false; 1651 } 1652 1653 // Initialize the argument to be stored. 1654 ExprResult ValArg = TheCall->getArg(0); 1655 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1656 Context, ValType, /*consume*/ false); 1657 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1658 if (ValArg.isInvalid()) 1659 return true; 1660 TheCall->setArg(0, ValArg.get()); 1661 1662 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1663 // but the custom checker bypasses all default analysis. 1664 TheCall->setType(Context.IntTy); 1665 return false; 1666 } 1667 1668 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1669 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1670 BuiltinID == ARM::BI__builtin_arm_ldaex || 1671 BuiltinID == ARM::BI__builtin_arm_strex || 1672 BuiltinID == ARM::BI__builtin_arm_stlex) { 1673 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1674 } 1675 1676 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1677 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1678 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1679 } 1680 1681 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1682 BuiltinID == ARM::BI__builtin_arm_wsr64) 1683 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1684 1685 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1686 BuiltinID == ARM::BI__builtin_arm_rsrp || 1687 BuiltinID == ARM::BI__builtin_arm_wsr || 1688 BuiltinID == ARM::BI__builtin_arm_wsrp) 1689 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1690 1691 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1692 return true; 1693 1694 // For intrinsics which take an immediate value as part of the instruction, 1695 // range check them here. 1696 // FIXME: VFP Intrinsics should error if VFP not present. 1697 switch (BuiltinID) { 1698 default: return false; 1699 case ARM::BI__builtin_arm_ssat: 1700 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1701 case ARM::BI__builtin_arm_usat: 1702 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1703 case ARM::BI__builtin_arm_ssat16: 1704 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1705 case ARM::BI__builtin_arm_usat16: 1706 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1707 case ARM::BI__builtin_arm_vcvtr_f: 1708 case ARM::BI__builtin_arm_vcvtr_d: 1709 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1710 case ARM::BI__builtin_arm_dmb: 1711 case ARM::BI__builtin_arm_dsb: 1712 case ARM::BI__builtin_arm_isb: 1713 case ARM::BI__builtin_arm_dbg: 1714 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1715 } 1716 } 1717 1718 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1719 CallExpr *TheCall) { 1720 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1721 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1722 BuiltinID == AArch64::BI__builtin_arm_strex || 1723 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1724 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1725 } 1726 1727 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1728 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1729 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1730 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1731 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1732 } 1733 1734 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1735 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1736 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1737 1738 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1739 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1740 BuiltinID == AArch64::BI__builtin_arm_wsr || 1741 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1742 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1743 1744 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1745 return true; 1746 1747 // For intrinsics which take an immediate value as part of the instruction, 1748 // range check them here. 1749 unsigned i = 0, l = 0, u = 0; 1750 switch (BuiltinID) { 1751 default: return false; 1752 case AArch64::BI__builtin_arm_dmb: 1753 case AArch64::BI__builtin_arm_dsb: 1754 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1755 } 1756 1757 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1758 } 1759 1760 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1761 static const std::map<unsigned, std::vector<StringRef>> ValidCPU = { 1762 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, {"v65"} }, 1763 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, {"v62", "v65"} }, 1764 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, {"v62", "v65"} }, 1765 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, {"v62", "v65"} }, 1766 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {"v60", "v62", "v65"} }, 1767 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {"v60", "v62", "v65"} }, 1768 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {"v60", "v62", "v65"} }, 1769 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {"v60", "v62", "v65"} }, 1770 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {"v60", "v62", "v65"} }, 1771 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {"v60", "v62", "v65"} }, 1772 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {"v60", "v62", "v65"} }, 1773 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {"v60", "v62", "v65"} }, 1774 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {"v60", "v62", "v65"} }, 1775 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {"v60", "v62", "v65"} }, 1776 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {"v60", "v62", "v65"} }, 1777 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {"v60", "v62", "v65"} }, 1778 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, {"v62", "v65"} }, 1779 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, {"v62", "v65"} }, 1780 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, {"v62", "v65"} }, 1781 }; 1782 1783 static const std::map<unsigned, std::vector<StringRef>> ValidHVX = { 1784 { Hexagon::BI__builtin_HEXAGON_V6_extractw, {"v60", "v62", "v65"} }, 1785 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, {"v60", "v62", "v65"} }, 1786 { Hexagon::BI__builtin_HEXAGON_V6_hi, {"v60", "v62", "v65"} }, 1787 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, {"v60", "v62", "v65"} }, 1788 { Hexagon::BI__builtin_HEXAGON_V6_lo, {"v60", "v62", "v65"} }, 1789 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, {"v60", "v62", "v65"} }, 1790 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, {"v62", "v65"} }, 1791 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, {"v62", "v65"} }, 1792 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, {"v62", "v65"} }, 1793 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, {"v62", "v65"} }, 1794 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, {"v60", "v62", "v65"} }, 1795 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, {"v60", "v62", "v65"} }, 1796 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, {"v60", "v62", "v65"} }, 1797 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, {"v60", "v62", "v65"} }, 1798 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, {"v60", "v62", "v65"} }, 1799 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, {"v60", "v62", "v65"} }, 1800 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, {"v60", "v62", "v65"} }, 1801 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, {"v60", "v62", "v65"} }, 1802 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, {"v60", "v62", "v65"} }, 1803 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, {"v60", "v62", "v65"} }, 1804 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, {"v60", "v62", "v65"} }, 1805 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, {"v60", "v62", "v65"} }, 1806 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, {"v60", "v62", "v65"} }, 1807 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, {"v60", "v62", "v65"} }, 1808 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, {"v62", "v65"} }, 1809 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, {"v62", "v65"} }, 1810 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, {"v60", "v62", "v65"} }, 1811 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, {"v60", "v62", "v65"} }, 1812 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, {"v62", "v65"} }, 1813 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, {"v62", "v65"} }, 1814 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, {"v62", "v65"} }, 1815 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, {"v62", "v65"} }, 1816 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, {"v65"} }, 1817 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, {"v65"} }, 1818 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, {"v65"} }, 1819 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, {"v65"} }, 1820 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, {"v60", "v62", "v65"} }, 1821 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, {"v60", "v62", "v65"} }, 1822 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, {"v60", "v62", "v65"} }, 1823 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, {"v60", "v62", "v65"} }, 1824 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, {"v60", "v62", "v65"} }, 1825 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, {"v60", "v62", "v65"} }, 1826 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, {"v60", "v62", "v65"} }, 1827 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, {"v60", "v62", "v65"} }, 1828 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, {"v60", "v62", "v65"} }, 1829 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, {"v60", "v62", "v65"} }, 1830 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, {"v60", "v62", "v65"} }, 1831 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, {"v60", "v62", "v65"} }, 1832 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, {"v60", "v62", "v65"} }, 1833 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, {"v60", "v62", "v65"} }, 1834 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, {"v60", "v62", "v65"} }, 1835 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, {"v60", "v62", "v65"} }, 1836 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, {"v60", "v62", "v65"} }, 1837 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, {"v60", "v62", "v65"} }, 1838 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, {"v60", "v62", "v65"} }, 1839 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, {"v60", "v62", "v65"} }, 1840 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, {"v62", "v65"} }, 1841 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, {"v62", "v65"} }, 1842 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, {"v62", "v65"} }, 1843 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, {"v62", "v65"} }, 1844 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, {"v62", "v65"} }, 1845 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, {"v62", "v65"} }, 1846 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, {"v62", "v65"} }, 1847 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, {"v62", "v65"} }, 1848 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, {"v62", "v65"} }, 1849 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, {"v62", "v65"} }, 1850 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, {"v60", "v62", "v65"} }, 1851 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, {"v60", "v62", "v65"} }, 1852 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, {"v60", "v62", "v65"} }, 1853 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, {"v60", "v62", "v65"} }, 1854 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, {"v60", "v62", "v65"} }, 1855 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, {"v60", "v62", "v65"} }, 1856 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, {"v60", "v62", "v65"} }, 1857 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, {"v60", "v62", "v65"} }, 1858 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, {"v60", "v62", "v65"} }, 1859 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, {"v60", "v62", "v65"} }, 1860 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, {"v62", "v65"} }, 1861 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, {"v62", "v65"} }, 1862 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, {"v60", "v62", "v65"} }, 1863 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, {"v60", "v62", "v65"} }, 1864 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, {"v62", "v65"} }, 1865 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, {"v62", "v65"} }, 1866 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, {"v60", "v62", "v65"} }, 1867 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, {"v60", "v62", "v65"} }, 1868 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, {"v60", "v62", "v65"} }, 1869 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, {"v60", "v62", "v65"} }, 1870 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, {"v62", "v65"} }, 1871 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, {"v62", "v65"} }, 1872 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, {"v60", "v62", "v65"} }, 1873 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, {"v60", "v62", "v65"} }, 1874 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, {"v60", "v62", "v65"} }, 1875 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, {"v60", "v62", "v65"} }, 1876 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, {"v60", "v62", "v65"} }, 1877 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, {"v60", "v62", "v65"} }, 1878 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, {"v62", "v65"} }, 1879 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, {"v62", "v65"} }, 1880 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, {"v62", "v65"} }, 1881 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, {"v62", "v65"} }, 1882 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, {"v62", "v65"} }, 1883 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, {"v62", "v65"} }, 1884 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, {"v60", "v62", "v65"} }, 1885 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, {"v60", "v62", "v65"} }, 1886 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, {"v60", "v62", "v65"} }, 1887 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, {"v60", "v62", "v65"} }, 1888 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, {"v60", "v62", "v65"} }, 1889 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, {"v60", "v62", "v65"} }, 1890 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, {"v60", "v62", "v65"} }, 1891 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, {"v60", "v62", "v65"} }, 1892 { Hexagon::BI__builtin_HEXAGON_V6_valignb, {"v60", "v62", "v65"} }, 1893 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, {"v60", "v62", "v65"} }, 1894 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {"v60", "v62", "v65"} }, 1895 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {"v60", "v62", "v65"} }, 1896 { Hexagon::BI__builtin_HEXAGON_V6_vand, {"v60", "v62", "v65"} }, 1897 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, {"v60", "v62", "v65"} }, 1898 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, {"v62", "v65"} }, 1899 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, {"v62", "v65"} }, 1900 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, {"v62", "v65"} }, 1901 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, {"v62", "v65"} }, 1902 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, {"v60", "v62", "v65"} }, 1903 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, {"v60", "v62", "v65"} }, 1904 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, {"v60", "v62", "v65"} }, 1905 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, {"v60", "v62", "v65"} }, 1906 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, {"v62", "v65"} }, 1907 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, {"v62", "v65"} }, 1908 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, {"v62", "v65"} }, 1909 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, {"v62", "v65"} }, 1910 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, {"v60", "v62", "v65"} }, 1911 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, {"v60", "v62", "v65"} }, 1912 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, {"v60", "v62", "v65"} }, 1913 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, {"v60", "v62", "v65"} }, 1914 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, {"v60", "v62", "v65"} }, 1915 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, {"v60", "v62", "v65"} }, 1916 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, {"v65"} }, 1917 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, {"v65"} }, 1918 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, {"v60", "v62", "v65"} }, 1919 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, {"v60", "v62", "v65"} }, 1920 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, {"v60", "v62", "v65"} }, 1921 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, {"v60", "v62", "v65"} }, 1922 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, {"v60", "v62", "v65"} }, 1923 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, {"v60", "v62", "v65"} }, 1924 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, {"v60", "v62", "v65"} }, 1925 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, {"v60", "v62", "v65"} }, 1926 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, {"v60", "v62", "v65"} }, 1927 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, {"v60", "v62", "v65"} }, 1928 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, {"v65"} }, 1929 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, {"v65"} }, 1930 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, {"v60", "v62", "v65"} }, 1931 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, {"v60", "v62", "v65"} }, 1932 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, {"v62", "v65"} }, 1933 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, {"v62", "v65"} }, 1934 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, {"v60", "v62", "v65"} }, 1935 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, {"v60", "v62", "v65"} }, 1936 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, {"v60", "v62", "v65"} }, 1937 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, {"v60", "v62", "v65"} }, 1938 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, {"v60", "v62", "v65"} }, 1939 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, {"v60", "v62", "v65"} }, 1940 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, {"v65"} }, 1941 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, {"v65"} }, 1942 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, {"v65"} }, 1943 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, {"v65"} }, 1944 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, {"v62", "v65"} }, 1945 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, {"v62", "v65"} }, 1946 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, {"v65"} }, 1947 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, {"v65"} }, 1948 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, {"v60", "v62", "v65"} }, 1949 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, {"v60", "v62", "v65"} }, 1950 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, {"v60", "v62", "v65"} }, 1951 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, {"v60", "v62", "v65"} }, 1952 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, {"v60", "v62", "v65"} }, 1953 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, {"v60", "v62", "v65"} }, 1954 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, {"v60", "v62", "v65"} }, 1955 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, {"v60", "v62", "v65"} }, 1956 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, {"v60", "v62", "v65"} }, 1957 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, {"v60", "v62", "v65"} }, 1958 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, {"v62", "v65"} }, 1959 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, {"v62", "v65"} }, 1960 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, {"v60", "v62", "v65"} }, 1961 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, {"v60", "v62", "v65"} }, 1962 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, {"v60", "v62", "v65"} }, 1963 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, {"v60", "v62", "v65"} }, 1964 { Hexagon::BI__builtin_HEXAGON_V6_vassign, {"v60", "v62", "v65"} }, 1965 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, {"v60", "v62", "v65"} }, 1966 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, {"v60", "v62", "v65"} }, 1967 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, {"v60", "v62", "v65"} }, 1968 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, {"v65"} }, 1969 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, {"v65"} }, 1970 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, {"v65"} }, 1971 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, {"v65"} }, 1972 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, {"v60", "v62", "v65"} }, 1973 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, {"v60", "v62", "v65"} }, 1974 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, {"v60", "v62", "v65"} }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, {"v60", "v62", "v65"} }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, {"v60", "v62", "v65"} }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, {"v60", "v62", "v65"} }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, {"v60", "v62", "v65"} }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, {"v60", "v62", "v65"} }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, {"v60", "v62", "v65"} }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, {"v60", "v62", "v65"} }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, {"v60", "v62", "v65"} }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, {"v60", "v62", "v65"} }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, {"v65"} }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, {"v65"} }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, {"v65"} }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, {"v65"} }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, {"v60", "v62", "v65"} }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, {"v60", "v62", "v65"} }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, {"v60", "v62", "v65"} }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, {"v60", "v62", "v65"} }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, {"v60", "v62", "v65"} }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, {"v60", "v62", "v65"} }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, {"v60", "v62", "v65"} }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, {"v60", "v62", "v65"} }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, {"v60", "v62", "v65"} }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, {"v60", "v62", "v65"} }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_vd0, {"v60", "v62", "v65"} }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, {"v60", "v62", "v65"} }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, {"v65"} }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, {"v65"} }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, {"v60", "v62", "v65"} }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, {"v60", "v62", "v65"} }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, {"v60", "v62", "v65"} }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, {"v60", "v62", "v65"} }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, {"v60", "v62", "v65"} }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, {"v60", "v62", "v65"} }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, {"v60", "v62", "v65"} }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, {"v60", "v62", "v65"} }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, {"v60", "v62", "v65"} }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, {"v60", "v62", "v65"} }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, {"v60", "v62", "v65"} }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, {"v60", "v62", "v65"} }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, {"v60", "v62", "v65"} }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, {"v60", "v62", "v65"} }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, {"v60", "v62", "v65"} }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, {"v60", "v62", "v65"} }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, {"v60", "v62", "v65"} }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, {"v60", "v62", "v65"} }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, {"v60", "v62", "v65"} }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, {"v60", "v62", "v65"} }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, {"v60", "v62", "v65"} }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, {"v60", "v62", "v65"} }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, {"v60", "v62", "v65"} }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, {"v60", "v62", "v65"} }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, {"v60", "v62", "v65"} }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, {"v60", "v62", "v65"} }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, {"v60", "v62", "v65"} }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, {"v60", "v62", "v65"} }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, {"v60", "v62", "v65"} }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, {"v60", "v62", "v65"} }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, {"v60", "v62", "v65"} }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, {"v60", "v62", "v65"} }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, {"v60", "v62", "v65"} }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, {"v60", "v62", "v65"} }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, {"v60", "v62", "v65"} }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, {"v60", "v62", "v65"} }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, {"v60", "v62", "v65"} }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, {"v60", "v62", "v65"} }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, {"v60", "v62", "v65"} }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, {"v60", "v62", "v65"} }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, {"v60", "v62", "v65"} }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, {"v60", "v62", "v65"} }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, {"v60", "v62", "v65"} }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, {"v60", "v62", "v65"} }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, {"v60", "v62", "v65"} }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, {"v60", "v62", "v65"} }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, {"v60", "v62", "v65"} }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, {"v60", "v62", "v65"} }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, {"v60", "v62", "v65"} }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, {"v60", "v62", "v65"} }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_veqb, {"v60", "v62", "v65"} }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, {"v60", "v62", "v65"} }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, {"v60", "v62", "v65"} }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, {"v60", "v62", "v65"} }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, {"v60", "v62", "v65"} }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, {"v60", "v62", "v65"} }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, {"v60", "v62", "v65"} }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, {"v60", "v62", "v65"} }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_veqh, {"v60", "v62", "v65"} }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, {"v60", "v62", "v65"} }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, {"v60", "v62", "v65"} }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, {"v60", "v62", "v65"} }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, {"v60", "v62", "v65"} }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, {"v60", "v62", "v65"} }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, {"v60", "v62", "v65"} }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, {"v60", "v62", "v65"} }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_veqw, {"v60", "v62", "v65"} }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, {"v60", "v62", "v65"} }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, {"v60", "v62", "v65"} }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, {"v60", "v62", "v65"} }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, {"v60", "v62", "v65"} }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, {"v60", "v62", "v65"} }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, {"v60", "v62", "v65"} }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, {"v60", "v62", "v65"} }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, {"v60", "v62", "v65"} }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, {"v60", "v62", "v65"} }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, {"v60", "v62", "v65"} }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, {"v60", "v62", "v65"} }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, {"v60", "v62", "v65"} }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, {"v60", "v62", "v65"} }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, {"v60", "v62", "v65"} }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, {"v60", "v62", "v65"} }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_vgth, {"v60", "v62", "v65"} }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, {"v60", "v62", "v65"} }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, {"v60", "v62", "v65"} }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, {"v60", "v62", "v65"} }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, {"v60", "v62", "v65"} }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, {"v60", "v62", "v65"} }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, {"v60", "v62", "v65"} }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, {"v60", "v62", "v65"} }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, {"v60", "v62", "v65"} }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, {"v60", "v62", "v65"} }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, {"v60", "v62", "v65"} }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, {"v60", "v62", "v65"} }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, {"v60", "v62", "v65"} }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, {"v60", "v62", "v65"} }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, {"v60", "v62", "v65"} }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, {"v60", "v62", "v65"} }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, {"v60", "v62", "v65"} }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, {"v60", "v62", "v65"} }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, {"v60", "v62", "v65"} }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, {"v60", "v62", "v65"} }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, {"v60", "v62", "v65"} }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, {"v60", "v62", "v65"} }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, {"v60", "v62", "v65"} }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, {"v60", "v62", "v65"} }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, {"v60", "v62", "v65"} }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, {"v60", "v62", "v65"} }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, {"v60", "v62", "v65"} }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, {"v60", "v62", "v65"} }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, {"v60", "v62", "v65"} }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, {"v60", "v62", "v65"} }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, {"v60", "v62", "v65"} }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, {"v60", "v62", "v65"} }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, {"v60", "v62", "v65"} }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, {"v60", "v62", "v65"} }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, {"v60", "v62", "v65"} }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, {"v60", "v62", "v65"} }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, {"v60", "v62", "v65"} }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, {"v60", "v62", "v65"} }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, {"v60", "v62", "v65"} }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, {"v60", "v62", "v65"} }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, {"v60", "v62", "v65"} }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, {"v60", "v62", "v65"} }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, {"v60", "v62", "v65"} }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, {"v60", "v62", "v65"} }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {"v60", "v62", "v65"} }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {"v60", "v62", "v65"} }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, {"v62", "v65"} }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, {"v62", "v65"} }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, {"v60", "v62", "v65"} }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, {"v60", "v62", "v65"} }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, {"v60", "v62", "v65"} }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, {"v60", "v62", "v65"} }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, {"v60", "v62", "v65"} }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, {"v60", "v62", "v65"} }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, {"v60", "v62", "v65"} }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, {"v60", "v62", "v65"} }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, {"v65"} }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, {"v65"} }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, {"v60", "v62", "v65"} }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, {"v60", "v62", "v65"} }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {"v62", "v65"} }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {"v62", "v65"} }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, {"v62", "v65"} }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, {"v62", "v65"} }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, {"v60", "v62", "v65"} }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, {"v60", "v62", "v65"} }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {"v62", "v65"} }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, {"v62", "v65"} }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, {"v60", "v62", "v65"} }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, {"v60", "v62", "v65"} }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {"v62", "v65"} }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {"v62", "v65"} }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, {"v62", "v65"} }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, {"v62", "v65"} }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, {"v60", "v62", "v65"} }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, {"v60", "v62", "v65"} }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {"v62", "v65"} }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, {"v62", "v65"} }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, {"v62", "v65"} }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, {"v62", "v65"} }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, {"v60", "v62", "v65"} }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, {"v60", "v62", "v65"} }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, {"v60", "v62", "v65"} }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, {"v60", "v62", "v65"} }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, {"v60", "v62", "v65"} }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, {"v60", "v62", "v65"} }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, {"v60", "v62", "v65"} }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, {"v60", "v62", "v65"} }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vminb, {"v62", "v65"} }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, {"v62", "v65"} }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vminh, {"v60", "v62", "v65"} }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, {"v60", "v62", "v65"} }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vminub, {"v60", "v62", "v65"} }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, {"v60", "v62", "v65"} }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, {"v60", "v62", "v65"} }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, {"v60", "v62", "v65"} }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vminw, {"v60", "v62", "v65"} }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, {"v60", "v62", "v65"} }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, {"v60", "v62", "v65"} }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, {"v60", "v62", "v65"} }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, {"v60", "v62", "v65"} }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, {"v60", "v62", "v65"} }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, {"v60", "v62", "v65"} }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, {"v60", "v62", "v65"} }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, {"v65"} }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, {"v65"} }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, {"v65"} }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, {"v65"} }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, {"v60", "v62", "v65"} }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, {"v60", "v62", "v65"} }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, {"v60", "v62", "v65"} }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, {"v60", "v62", "v65"} }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, {"v60", "v62", "v65"} }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, {"v60", "v62", "v65"} }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, {"v65"} }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, {"v65"} }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, {"v62", "v65"} }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, {"v62", "v65"} }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, {"v62", "v65"} }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, {"v62", "v65"} }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, {"v65"} }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, {"v65"} }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, {"v65"} }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, {"v65"} }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, {"v60", "v62", "v65"} }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, {"v60", "v62", "v65"} }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, {"v60", "v62", "v65"} }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, {"v60", "v62", "v65"} }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, {"v60", "v62", "v65"} }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, {"v60", "v62", "v65"} }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, {"v60", "v62", "v65"} }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, {"v60", "v62", "v65"} }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, {"v60", "v62", "v65"} }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, {"v60", "v62", "v65"} }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, {"v60", "v62", "v65"} }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, {"v60", "v62", "v65"} }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, {"v60", "v62", "v65"} }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, {"v60", "v62", "v65"} }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, {"v62", "v65"} }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, {"v62", "v65"} }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, {"v60", "v62", "v65"} }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, {"v60", "v62", "v65"} }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, {"v65"} }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, {"v65"} }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, {"v60", "v62", "v65"} }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, {"v60", "v62", "v65"} }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, {"v60", "v62", "v65"} }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, {"v60", "v62", "v65"} }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, {"v60", "v62", "v65"} }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, {"v60", "v62", "v65"} }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, {"v60", "v62", "v65"} }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, {"v60", "v62", "v65"} }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, {"v60", "v62", "v65"} }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, {"v60", "v62", "v65"} }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, {"v60", "v62", "v65"} }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, {"v60", "v62", "v65"} }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, {"v60", "v62", "v65"} }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, {"v60", "v62", "v65"} }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, {"v60", "v62", "v65"} }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, {"v60", "v62", "v65"} }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, {"v60", "v62", "v65"} }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, {"v60", "v62", "v65"} }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, {"v60", "v62", "v65"} }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, {"v60", "v62", "v65"} }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, {"v60", "v62", "v65"} }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, {"v60", "v62", "v65"} }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, {"v60", "v62", "v65"} }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, {"v60", "v62", "v65"} }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, {"v60", "v62", "v65"} }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, {"v60", "v62", "v65"} }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, {"v60", "v62", "v65"} }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, {"v60", "v62", "v65"} }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, {"v60", "v62", "v65"} }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, {"v60", "v62", "v65"} }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, {"v60", "v62", "v65"} }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, {"v60", "v62", "v65"} }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, {"v60", "v62", "v65"} }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, {"v60", "v62", "v65"} }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, {"v60", "v62", "v65"} }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, {"v60", "v62", "v65"} }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, {"v60", "v62", "v65"} }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, {"v60", "v62", "v65"} }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, {"v60", "v62", "v65"} }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, {"v60", "v62", "v65"} }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, {"v60", "v62", "v65"} }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, {"v60", "v62", "v65"} }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, {"v62", "v65"} }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, {"v62", "v65"} }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, {"v62", "v65"} }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, {"v62", "v65"} }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, {"v60", "v62", "v65"} }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, {"v60", "v62", "v65"} }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, {"v62", "v65"} }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, {"v62", "v65"} }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, {"v60", "v62", "v65"} }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, {"v60", "v62", "v65"} }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, {"v60", "v62", "v65"} }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, {"v60", "v62", "v65"} }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, {"v60", "v62", "v65"} }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, {"v60", "v62", "v65"} }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, {"v60", "v62", "v65"} }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, {"v60", "v62", "v65"} }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, {"v60", "v62", "v65"} }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, {"v60", "v62", "v65"} }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, {"v60", "v62", "v65"} }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, {"v60", "v62", "v65"} }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, {"v60", "v62", "v65"} }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, {"v60", "v62", "v65"} }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, {"v60", "v62", "v65"} }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, {"v60", "v62", "v65"} }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, {"v60", "v62", "v65"} }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, {"v60", "v62", "v65"} }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, {"v65"} }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, {"v65"} }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, {"v65"} }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, {"v65"} }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, {"v60", "v62", "v65"} }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, {"v60", "v62", "v65"} }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, {"v60", "v62", "v65"} }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, {"v60", "v62", "v65"} }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vmux, {"v60", "v62", "v65"} }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, {"v60", "v62", "v65"} }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, {"v65"} }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, {"v65"} }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, {"v60", "v62", "v65"} }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, {"v60", "v62", "v65"} }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, {"v60", "v62", "v65"} }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, {"v60", "v62", "v65"} }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, {"v60", "v62", "v65"} }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, {"v60", "v62", "v65"} }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, {"v60", "v62", "v65"} }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, {"v60", "v62", "v65"} }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, {"v60", "v62", "v65"} }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, {"v60", "v62", "v65"} }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vnot, {"v60", "v62", "v65"} }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, {"v60", "v62", "v65"} }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vor, {"v60", "v62", "v65"} }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, {"v60", "v62", "v65"} }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, {"v60", "v62", "v65"} }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, {"v60", "v62", "v65"} }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, {"v60", "v62", "v65"} }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, {"v60", "v62", "v65"} }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, {"v60", "v62", "v65"} }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, {"v60", "v62", "v65"} }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, {"v60", "v62", "v65"} }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, {"v60", "v62", "v65"} }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, {"v60", "v62", "v65"} }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, {"v60", "v62", "v65"} }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, {"v60", "v62", "v65"} }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, {"v60", "v62", "v65"} }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, {"v60", "v62", "v65"} }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, {"v60", "v62", "v65"} }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, {"v60", "v62", "v65"} }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, {"v60", "v62", "v65"} }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, {"v60", "v62", "v65"} }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, {"v60", "v62", "v65"} }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, {"v65"} }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, {"v65"} }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, {"v65"} }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, {"v65"} }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, {"v65"} }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, {"v65"} }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, {"v60", "v62", "v65"} }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, {"v60", "v62", "v65"} }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, {"v65"} }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, {"v65"} }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, {"v65"} }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, {"v65"} }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, {"v60", "v62", "v65"} }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, {"v60", "v62", "v65"} }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, {"v60", "v62", "v65"} }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, {"v60", "v62", "v65"} }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {"v60", "v62", "v65"} }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {"v60", "v62", "v65"} }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {"v60", "v62", "v65"} }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, {"v60", "v62", "v65"} }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, {"v60", "v62", "v65"} }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, {"v60", "v62", "v65"} }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, {"v60", "v62", "v65"} }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, {"v60", "v62", "v65"} }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, {"v60", "v62", "v65"} }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, {"v60", "v62", "v65"} }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, {"v60", "v62", "v65"} }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, {"v60", "v62", "v65"} }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, {"v60", "v62", "v65"} }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, {"v60", "v62", "v65"} }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, {"v60", "v62", "v65"} }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, {"v60", "v62", "v65"} }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {"v60", "v62", "v65"} }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {"v60", "v62", "v65"} }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {"v60", "v62", "v65"} }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, {"v60", "v62", "v65"} }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, {"v65"} }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, {"v65"} }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, {"v65"} }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, {"v65"} }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, {"v60", "v62", "v65"} }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, {"v60", "v62", "v65"} }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, {"v60", "v62", "v65"} }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, {"v60", "v62", "v65"} }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vror, {"v60", "v62", "v65"} }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, {"v60", "v62", "v65"} }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, {"v60", "v62", "v65"} }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, {"v60", "v62", "v65"} }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, {"v60", "v62", "v65"} }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, {"v60", "v62", "v65"} }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, {"v62", "v65"} }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, {"v62", "v65"} }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, {"v62", "v65"} }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, {"v62", "v65"} }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, {"v60", "v62", "v65"} }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, {"v60", "v62", "v65"} }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, {"v60", "v62", "v65"} }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, {"v60", "v62", "v65"} }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {"v60", "v62", "v65"} }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {"v60", "v62", "v65"} }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {"v60", "v62", "v65"} }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, {"v60", "v62", "v65"} }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, {"v60", "v62", "v65"} }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, {"v60", "v62", "v65"} }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, {"v62", "v65"} }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, {"v62", "v65"} }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, {"v60", "v62", "v65"} }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, {"v60", "v62", "v65"} }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vsb, {"v60", "v62", "v65"} }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, {"v60", "v62", "v65"} }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vsh, {"v60", "v62", "v65"} }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, {"v60", "v62", "v65"} }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, {"v60", "v62", "v65"} }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, {"v60", "v62", "v65"} }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, {"v60", "v62", "v65"} }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, {"v60", "v62", "v65"} }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, {"v60", "v62", "v65"} }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, {"v60", "v62", "v65"} }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, {"v60", "v62", "v65"} }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, {"v60", "v62", "v65"} }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, {"v60", "v62", "v65"} }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, {"v60", "v62", "v65"} }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, {"v60", "v62", "v65"} }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, {"v60", "v62", "v65"} }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, {"v60", "v62", "v65"} }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, {"v60", "v62", "v65"} }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, {"v60", "v62", "v65"} }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, {"v60", "v62", "v65"} }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, {"v60", "v62", "v65"} }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, {"v60", "v62", "v65"} }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, {"v60", "v62", "v65"} }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, {"v60", "v62", "v65"} }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, {"v60", "v62", "v65"} }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, {"v60", "v62", "v65"} }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, {"v62", "v65"} }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, {"v62", "v65"} }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, {"v62", "v65"} }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, {"v62", "v65"} }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, {"v62", "v65"} }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, {"v62", "v65"} }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, {"v60", "v62", "v65"} }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, {"v60", "v62", "v65"} }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, {"v60", "v62", "v65"} }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, {"v60", "v62", "v65"} }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, {"v60", "v62", "v65"} }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, {"v60", "v62", "v65"} }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, {"v60", "v62", "v65"} }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, {"v60", "v62", "v65"} }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, {"v60", "v62", "v65"} }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, {"v60", "v62", "v65"} }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, {"v60", "v62", "v65"} }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, {"v60", "v62", "v65"} }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, {"v60", "v62", "v65"} }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, {"v60", "v62", "v65"} }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, {"v60", "v62", "v65"} }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, {"v60", "v62", "v65"} }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, {"v62", "v65"} }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, {"v62", "v65"} }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, {"v60", "v62", "v65"} }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, {"v60", "v62", "v65"} }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, {"v60", "v62", "v65"} }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, {"v60", "v62", "v65"} }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, {"v60", "v62", "v65"} }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, {"v60", "v62", "v65"} }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, {"v62", "v65"} }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, {"v62", "v65"} }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, {"v62", "v65"} }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, {"v62", "v65"} }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, {"v60", "v62", "v65"} }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, {"v60", "v62", "v65"} }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, {"v60", "v62", "v65"} }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, {"v60", "v62", "v65"} }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, {"v60", "v62", "v65"} }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, {"v60", "v62", "v65"} }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, {"v60", "v62", "v65"} }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, {"v60", "v62", "v65"} }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vswap, {"v60", "v62", "v65"} }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, {"v60", "v62", "v65"} }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, {"v60", "v62", "v65"} }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, {"v60", "v62", "v65"} }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, {"v60", "v62", "v65"} }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, {"v60", "v62", "v65"} }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, {"v60", "v62", "v65"} }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, {"v60", "v62", "v65"} }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, {"v60", "v62", "v65"} }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, {"v60", "v62", "v65"} }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, {"v60", "v62", "v65"} }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, {"v60", "v62", "v65"} }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, {"v60", "v62", "v65"} }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, {"v60", "v62", "v65"} }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, {"v60", "v62", "v65"} }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, {"v60", "v62", "v65"} }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, {"v60", "v62", "v65"} }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, {"v60", "v62", "v65"} }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, {"v60", "v62", "v65"} }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, {"v60", "v62", "v65"} }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, {"v60", "v62", "v65"} }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, {"v60", "v62", "v65"} }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, {"v60", "v62", "v65"} }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, {"v60", "v62", "v65"} }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, {"v60", "v62", "v65"} }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, {"v60", "v62", "v65"} }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vxor, {"v60", "v62", "v65"} }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, {"v60", "v62", "v65"} }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vzb, {"v60", "v62", "v65"} }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, {"v60", "v62", "v65"} }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vzh, {"v60", "v62", "v65"} }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, {"v60", "v62", "v65"} }, 2508 }; 2509 2510 const TargetInfo &TI = Context.getTargetInfo(); 2511 2512 auto FC = ValidCPU.find(BuiltinID); 2513 if (FC != ValidCPU.end()) { 2514 const TargetOptions &Opts = TI.getTargetOpts(); 2515 StringRef CPU = Opts.CPU; 2516 if (!CPU.empty()) { 2517 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2518 CPU.consume_front("hexagon"); 2519 if (llvm::none_of(FC->second, [CPU](StringRef S) { return S == CPU; })) 2520 return Diag(TheCall->getBeginLoc(), 2521 diag::err_hexagon_builtin_unsupported_cpu); 2522 } 2523 } 2524 2525 auto FH = ValidHVX.find(BuiltinID); 2526 if (FH != ValidHVX.end()) { 2527 if (!TI.hasFeature("hvx")) 2528 return Diag(TheCall->getBeginLoc(), 2529 diag::err_hexagon_builtin_requires_hvx); 2530 2531 bool IsValid = llvm::any_of(FH->second, 2532 [&TI] (StringRef V) { 2533 std::string F = "hvx" + V.str(); 2534 return TI.hasFeature(F); 2535 }); 2536 if (!IsValid) 2537 return Diag(TheCall->getBeginLoc(), 2538 diag::err_hexagon_builtin_unsupported_hvx); 2539 } 2540 2541 return false; 2542 } 2543 2544 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2545 struct ArgInfo { 2546 ArgInfo(unsigned O, bool S, unsigned W, unsigned A) 2547 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {} 2548 unsigned OpNum = 0; 2549 bool IsSigned = false; 2550 unsigned BitWidth = 0; 2551 unsigned Align = 0; 2552 }; 2553 2554 static const std::map<unsigned, std::vector<ArgInfo>> Infos = { 2555 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2556 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2557 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2558 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2559 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2560 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2561 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2562 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2563 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2564 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2565 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2566 2567 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2568 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2569 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2570 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2571 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2572 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2573 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2574 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2575 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2576 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2577 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2578 2579 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2580 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2581 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2582 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2583 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2584 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2585 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2586 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2587 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2588 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2589 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2590 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2591 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2592 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2593 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2594 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2595 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2596 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2597 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2598 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2599 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2600 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2601 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2602 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2603 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2604 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2605 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2606 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2607 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2608 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2609 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2610 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2611 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2612 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2613 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2614 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2615 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2616 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2617 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2618 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2619 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2620 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2621 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2622 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2623 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2624 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2625 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2626 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2627 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2628 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2629 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2630 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2631 {{ 1, false, 6, 0 }} }, 2632 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2633 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2634 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2635 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2636 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2637 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2639 {{ 1, false, 5, 0 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2641 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2642 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2645 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2646 { 2, false, 5, 0 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2648 { 2, false, 6, 0 }} }, 2649 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2650 { 3, false, 5, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2652 { 3, false, 6, 0 }} }, 2653 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2656 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2657 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2658 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2659 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2660 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2661 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2662 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2663 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2668 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2669 {{ 2, false, 4, 0 }, 2670 { 3, false, 5, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2672 {{ 2, false, 4, 0 }, 2673 { 3, false, 5, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2675 {{ 2, false, 4, 0 }, 2676 { 3, false, 5, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2678 {{ 2, false, 4, 0 }, 2679 { 3, false, 5, 0 }} }, 2680 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2683 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2685 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2686 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2691 { 2, false, 5, 0 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2693 { 2, false, 6, 0 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2697 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2698 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2701 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2703 {{ 1, false, 4, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2706 {{ 1, false, 4, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2709 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2713 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2715 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2716 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2717 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2718 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2719 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2720 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2721 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2722 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2724 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2725 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2727 {{ 3, false, 1, 0 }} }, 2728 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2730 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2731 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2732 {{ 3, false, 1, 0 }} }, 2733 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2737 {{ 3, false, 1, 0 }} }, 2738 }; 2739 2740 auto F = Infos.find(BuiltinID); 2741 if (F == Infos.end()) 2742 return false; 2743 2744 bool Error = false; 2745 2746 for (const ArgInfo &A : F->second) { 2747 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0; 2748 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1; 2749 if (!A.Align) { 2750 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2751 } else { 2752 unsigned M = 1 << A.Align; 2753 Min *= M; 2754 Max *= M; 2755 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2756 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2757 } 2758 } 2759 return Error; 2760 } 2761 2762 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2763 CallExpr *TheCall) { 2764 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2765 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2766 } 2767 2768 2769 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 2770 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2771 // ordering for DSP is unspecified. MSA is ordered by the data format used 2772 // by the underlying instruction i.e., df/m, df/n and then by size. 2773 // 2774 // FIXME: The size tests here should instead be tablegen'd along with the 2775 // definitions from include/clang/Basic/BuiltinsMips.def. 2776 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2777 // be too. 2778 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2779 unsigned i = 0, l = 0, u = 0, m = 0; 2780 switch (BuiltinID) { 2781 default: return false; 2782 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2783 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2784 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2785 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2786 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2787 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2788 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2789 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 2790 // df/m field. 2791 // These intrinsics take an unsigned 3 bit immediate. 2792 case Mips::BI__builtin_msa_bclri_b: 2793 case Mips::BI__builtin_msa_bnegi_b: 2794 case Mips::BI__builtin_msa_bseti_b: 2795 case Mips::BI__builtin_msa_sat_s_b: 2796 case Mips::BI__builtin_msa_sat_u_b: 2797 case Mips::BI__builtin_msa_slli_b: 2798 case Mips::BI__builtin_msa_srai_b: 2799 case Mips::BI__builtin_msa_srari_b: 2800 case Mips::BI__builtin_msa_srli_b: 2801 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2802 case Mips::BI__builtin_msa_binsli_b: 2803 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2804 // These intrinsics take an unsigned 4 bit immediate. 2805 case Mips::BI__builtin_msa_bclri_h: 2806 case Mips::BI__builtin_msa_bnegi_h: 2807 case Mips::BI__builtin_msa_bseti_h: 2808 case Mips::BI__builtin_msa_sat_s_h: 2809 case Mips::BI__builtin_msa_sat_u_h: 2810 case Mips::BI__builtin_msa_slli_h: 2811 case Mips::BI__builtin_msa_srai_h: 2812 case Mips::BI__builtin_msa_srari_h: 2813 case Mips::BI__builtin_msa_srli_h: 2814 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2815 case Mips::BI__builtin_msa_binsli_h: 2816 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2817 // These intrinsics take an unsigned 5 bit immediate. 2818 // The first block of intrinsics actually have an unsigned 5 bit field, 2819 // not a df/n field. 2820 case Mips::BI__builtin_msa_clei_u_b: 2821 case Mips::BI__builtin_msa_clei_u_h: 2822 case Mips::BI__builtin_msa_clei_u_w: 2823 case Mips::BI__builtin_msa_clei_u_d: 2824 case Mips::BI__builtin_msa_clti_u_b: 2825 case Mips::BI__builtin_msa_clti_u_h: 2826 case Mips::BI__builtin_msa_clti_u_w: 2827 case Mips::BI__builtin_msa_clti_u_d: 2828 case Mips::BI__builtin_msa_maxi_u_b: 2829 case Mips::BI__builtin_msa_maxi_u_h: 2830 case Mips::BI__builtin_msa_maxi_u_w: 2831 case Mips::BI__builtin_msa_maxi_u_d: 2832 case Mips::BI__builtin_msa_mini_u_b: 2833 case Mips::BI__builtin_msa_mini_u_h: 2834 case Mips::BI__builtin_msa_mini_u_w: 2835 case Mips::BI__builtin_msa_mini_u_d: 2836 case Mips::BI__builtin_msa_addvi_b: 2837 case Mips::BI__builtin_msa_addvi_h: 2838 case Mips::BI__builtin_msa_addvi_w: 2839 case Mips::BI__builtin_msa_addvi_d: 2840 case Mips::BI__builtin_msa_bclri_w: 2841 case Mips::BI__builtin_msa_bnegi_w: 2842 case Mips::BI__builtin_msa_bseti_w: 2843 case Mips::BI__builtin_msa_sat_s_w: 2844 case Mips::BI__builtin_msa_sat_u_w: 2845 case Mips::BI__builtin_msa_slli_w: 2846 case Mips::BI__builtin_msa_srai_w: 2847 case Mips::BI__builtin_msa_srari_w: 2848 case Mips::BI__builtin_msa_srli_w: 2849 case Mips::BI__builtin_msa_srlri_w: 2850 case Mips::BI__builtin_msa_subvi_b: 2851 case Mips::BI__builtin_msa_subvi_h: 2852 case Mips::BI__builtin_msa_subvi_w: 2853 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2854 case Mips::BI__builtin_msa_binsli_w: 2855 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2856 // These intrinsics take an unsigned 6 bit immediate. 2857 case Mips::BI__builtin_msa_bclri_d: 2858 case Mips::BI__builtin_msa_bnegi_d: 2859 case Mips::BI__builtin_msa_bseti_d: 2860 case Mips::BI__builtin_msa_sat_s_d: 2861 case Mips::BI__builtin_msa_sat_u_d: 2862 case Mips::BI__builtin_msa_slli_d: 2863 case Mips::BI__builtin_msa_srai_d: 2864 case Mips::BI__builtin_msa_srari_d: 2865 case Mips::BI__builtin_msa_srli_d: 2866 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2867 case Mips::BI__builtin_msa_binsli_d: 2868 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2869 // These intrinsics take a signed 5 bit immediate. 2870 case Mips::BI__builtin_msa_ceqi_b: 2871 case Mips::BI__builtin_msa_ceqi_h: 2872 case Mips::BI__builtin_msa_ceqi_w: 2873 case Mips::BI__builtin_msa_ceqi_d: 2874 case Mips::BI__builtin_msa_clti_s_b: 2875 case Mips::BI__builtin_msa_clti_s_h: 2876 case Mips::BI__builtin_msa_clti_s_w: 2877 case Mips::BI__builtin_msa_clti_s_d: 2878 case Mips::BI__builtin_msa_clei_s_b: 2879 case Mips::BI__builtin_msa_clei_s_h: 2880 case Mips::BI__builtin_msa_clei_s_w: 2881 case Mips::BI__builtin_msa_clei_s_d: 2882 case Mips::BI__builtin_msa_maxi_s_b: 2883 case Mips::BI__builtin_msa_maxi_s_h: 2884 case Mips::BI__builtin_msa_maxi_s_w: 2885 case Mips::BI__builtin_msa_maxi_s_d: 2886 case Mips::BI__builtin_msa_mini_s_b: 2887 case Mips::BI__builtin_msa_mini_s_h: 2888 case Mips::BI__builtin_msa_mini_s_w: 2889 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2890 // These intrinsics take an unsigned 8 bit immediate. 2891 case Mips::BI__builtin_msa_andi_b: 2892 case Mips::BI__builtin_msa_nori_b: 2893 case Mips::BI__builtin_msa_ori_b: 2894 case Mips::BI__builtin_msa_shf_b: 2895 case Mips::BI__builtin_msa_shf_h: 2896 case Mips::BI__builtin_msa_shf_w: 2897 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2898 case Mips::BI__builtin_msa_bseli_b: 2899 case Mips::BI__builtin_msa_bmnzi_b: 2900 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2901 // df/n format 2902 // These intrinsics take an unsigned 4 bit immediate. 2903 case Mips::BI__builtin_msa_copy_s_b: 2904 case Mips::BI__builtin_msa_copy_u_b: 2905 case Mips::BI__builtin_msa_insve_b: 2906 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2907 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2908 // These intrinsics take an unsigned 3 bit immediate. 2909 case Mips::BI__builtin_msa_copy_s_h: 2910 case Mips::BI__builtin_msa_copy_u_h: 2911 case Mips::BI__builtin_msa_insve_h: 2912 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2913 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2914 // These intrinsics take an unsigned 2 bit immediate. 2915 case Mips::BI__builtin_msa_copy_s_w: 2916 case Mips::BI__builtin_msa_copy_u_w: 2917 case Mips::BI__builtin_msa_insve_w: 2918 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2919 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2920 // These intrinsics take an unsigned 1 bit immediate. 2921 case Mips::BI__builtin_msa_copy_s_d: 2922 case Mips::BI__builtin_msa_copy_u_d: 2923 case Mips::BI__builtin_msa_insve_d: 2924 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2925 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2926 // Memory offsets and immediate loads. 2927 // These intrinsics take a signed 10 bit immediate. 2928 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2929 case Mips::BI__builtin_msa_ldi_h: 2930 case Mips::BI__builtin_msa_ldi_w: 2931 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2932 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 2933 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 2934 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 2935 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 2936 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 2937 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 2938 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 2939 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 2940 } 2941 2942 if (!m) 2943 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2944 2945 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2946 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2947 } 2948 2949 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2950 unsigned i = 0, l = 0, u = 0; 2951 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2952 BuiltinID == PPC::BI__builtin_divdeu || 2953 BuiltinID == PPC::BI__builtin_bpermd; 2954 bool IsTarget64Bit = Context.getTargetInfo() 2955 .getTypeWidth(Context 2956 .getTargetInfo() 2957 .getIntPtrType()) == 64; 2958 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2959 BuiltinID == PPC::BI__builtin_divweu || 2960 BuiltinID == PPC::BI__builtin_divde || 2961 BuiltinID == PPC::BI__builtin_divdeu; 2962 2963 if (Is64BitBltin && !IsTarget64Bit) 2964 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 2965 << TheCall->getSourceRange(); 2966 2967 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2968 (BuiltinID == PPC::BI__builtin_bpermd && 2969 !Context.getTargetInfo().hasFeature("bpermd"))) 2970 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2971 << TheCall->getSourceRange(); 2972 2973 switch (BuiltinID) { 2974 default: return false; 2975 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 2976 case PPC::BI__builtin_altivec_crypto_vshasigmad: 2977 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2978 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2979 case PPC::BI__builtin_tbegin: 2980 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 2981 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 2982 case PPC::BI__builtin_tabortwc: 2983 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 2984 case PPC::BI__builtin_tabortwci: 2985 case PPC::BI__builtin_tabortdci: 2986 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 2987 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 2988 case PPC::BI__builtin_vsx_xxpermdi: 2989 case PPC::BI__builtin_vsx_xxsldwi: 2990 return SemaBuiltinVSX(TheCall); 2991 } 2992 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2993 } 2994 2995 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 2996 CallExpr *TheCall) { 2997 if (BuiltinID == SystemZ::BI__builtin_tabort) { 2998 Expr *Arg = TheCall->getArg(0); 2999 llvm::APSInt AbortCode(32); 3000 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3001 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3002 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3003 << Arg->getSourceRange(); 3004 } 3005 3006 // For intrinsics which take an immediate value as part of the instruction, 3007 // range check them here. 3008 unsigned i = 0, l = 0, u = 0; 3009 switch (BuiltinID) { 3010 default: return false; 3011 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3012 case SystemZ::BI__builtin_s390_verimb: 3013 case SystemZ::BI__builtin_s390_verimh: 3014 case SystemZ::BI__builtin_s390_verimf: 3015 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3016 case SystemZ::BI__builtin_s390_vfaeb: 3017 case SystemZ::BI__builtin_s390_vfaeh: 3018 case SystemZ::BI__builtin_s390_vfaef: 3019 case SystemZ::BI__builtin_s390_vfaebs: 3020 case SystemZ::BI__builtin_s390_vfaehs: 3021 case SystemZ::BI__builtin_s390_vfaefs: 3022 case SystemZ::BI__builtin_s390_vfaezb: 3023 case SystemZ::BI__builtin_s390_vfaezh: 3024 case SystemZ::BI__builtin_s390_vfaezf: 3025 case SystemZ::BI__builtin_s390_vfaezbs: 3026 case SystemZ::BI__builtin_s390_vfaezhs: 3027 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3028 case SystemZ::BI__builtin_s390_vfisb: 3029 case SystemZ::BI__builtin_s390_vfidb: 3030 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3031 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3032 case SystemZ::BI__builtin_s390_vftcisb: 3033 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3034 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3035 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3036 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3037 case SystemZ::BI__builtin_s390_vstrcb: 3038 case SystemZ::BI__builtin_s390_vstrch: 3039 case SystemZ::BI__builtin_s390_vstrcf: 3040 case SystemZ::BI__builtin_s390_vstrczb: 3041 case SystemZ::BI__builtin_s390_vstrczh: 3042 case SystemZ::BI__builtin_s390_vstrczf: 3043 case SystemZ::BI__builtin_s390_vstrcbs: 3044 case SystemZ::BI__builtin_s390_vstrchs: 3045 case SystemZ::BI__builtin_s390_vstrcfs: 3046 case SystemZ::BI__builtin_s390_vstrczbs: 3047 case SystemZ::BI__builtin_s390_vstrczhs: 3048 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3049 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3050 case SystemZ::BI__builtin_s390_vfminsb: 3051 case SystemZ::BI__builtin_s390_vfmaxsb: 3052 case SystemZ::BI__builtin_s390_vfmindb: 3053 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3054 } 3055 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3056 } 3057 3058 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3059 /// This checks that the target supports __builtin_cpu_supports and 3060 /// that the string argument is constant and valid. 3061 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3062 Expr *Arg = TheCall->getArg(0); 3063 3064 // Check if the argument is a string literal. 3065 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3066 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3067 << Arg->getSourceRange(); 3068 3069 // Check the contents of the string. 3070 StringRef Feature = 3071 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3072 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3073 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3074 << Arg->getSourceRange(); 3075 return false; 3076 } 3077 3078 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3079 /// This checks that the target supports __builtin_cpu_is and 3080 /// that the string argument is constant and valid. 3081 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3082 Expr *Arg = TheCall->getArg(0); 3083 3084 // Check if the argument is a string literal. 3085 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3086 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3087 << Arg->getSourceRange(); 3088 3089 // Check the contents of the string. 3090 StringRef Feature = 3091 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3092 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3093 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3094 << Arg->getSourceRange(); 3095 return false; 3096 } 3097 3098 // Check if the rounding mode is legal. 3099 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3100 // Indicates if this instruction has rounding control or just SAE. 3101 bool HasRC = false; 3102 3103 unsigned ArgNum = 0; 3104 switch (BuiltinID) { 3105 default: 3106 return false; 3107 case X86::BI__builtin_ia32_vcvttsd2si32: 3108 case X86::BI__builtin_ia32_vcvttsd2si64: 3109 case X86::BI__builtin_ia32_vcvttsd2usi32: 3110 case X86::BI__builtin_ia32_vcvttsd2usi64: 3111 case X86::BI__builtin_ia32_vcvttss2si32: 3112 case X86::BI__builtin_ia32_vcvttss2si64: 3113 case X86::BI__builtin_ia32_vcvttss2usi32: 3114 case X86::BI__builtin_ia32_vcvttss2usi64: 3115 ArgNum = 1; 3116 break; 3117 case X86::BI__builtin_ia32_maxpd512: 3118 case X86::BI__builtin_ia32_maxps512: 3119 case X86::BI__builtin_ia32_minpd512: 3120 case X86::BI__builtin_ia32_minps512: 3121 ArgNum = 2; 3122 break; 3123 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3124 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3125 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3126 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3127 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3128 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3129 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3130 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3131 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3132 case X86::BI__builtin_ia32_exp2pd_mask: 3133 case X86::BI__builtin_ia32_exp2ps_mask: 3134 case X86::BI__builtin_ia32_getexppd512_mask: 3135 case X86::BI__builtin_ia32_getexpps512_mask: 3136 case X86::BI__builtin_ia32_rcp28pd_mask: 3137 case X86::BI__builtin_ia32_rcp28ps_mask: 3138 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3139 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3140 case X86::BI__builtin_ia32_vcomisd: 3141 case X86::BI__builtin_ia32_vcomiss: 3142 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3143 ArgNum = 3; 3144 break; 3145 case X86::BI__builtin_ia32_cmppd512_mask: 3146 case X86::BI__builtin_ia32_cmpps512_mask: 3147 case X86::BI__builtin_ia32_cmpsd_mask: 3148 case X86::BI__builtin_ia32_cmpss_mask: 3149 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3150 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3151 case X86::BI__builtin_ia32_getexpss128_round_mask: 3152 case X86::BI__builtin_ia32_maxsd_round_mask: 3153 case X86::BI__builtin_ia32_maxss_round_mask: 3154 case X86::BI__builtin_ia32_minsd_round_mask: 3155 case X86::BI__builtin_ia32_minss_round_mask: 3156 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3157 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3158 case X86::BI__builtin_ia32_reducepd512_mask: 3159 case X86::BI__builtin_ia32_reduceps512_mask: 3160 case X86::BI__builtin_ia32_rndscalepd_mask: 3161 case X86::BI__builtin_ia32_rndscaleps_mask: 3162 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3163 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3164 ArgNum = 4; 3165 break; 3166 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3167 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3168 case X86::BI__builtin_ia32_fixupimmps512_mask: 3169 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3170 case X86::BI__builtin_ia32_fixupimmsd_mask: 3171 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3172 case X86::BI__builtin_ia32_fixupimmss_mask: 3173 case X86::BI__builtin_ia32_fixupimmss_maskz: 3174 case X86::BI__builtin_ia32_rangepd512_mask: 3175 case X86::BI__builtin_ia32_rangeps512_mask: 3176 case X86::BI__builtin_ia32_rangesd128_round_mask: 3177 case X86::BI__builtin_ia32_rangess128_round_mask: 3178 case X86::BI__builtin_ia32_reducesd_mask: 3179 case X86::BI__builtin_ia32_reducess_mask: 3180 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3181 case X86::BI__builtin_ia32_rndscaless_round_mask: 3182 ArgNum = 5; 3183 break; 3184 case X86::BI__builtin_ia32_vcvtsd2si64: 3185 case X86::BI__builtin_ia32_vcvtsd2si32: 3186 case X86::BI__builtin_ia32_vcvtsd2usi32: 3187 case X86::BI__builtin_ia32_vcvtsd2usi64: 3188 case X86::BI__builtin_ia32_vcvtss2si32: 3189 case X86::BI__builtin_ia32_vcvtss2si64: 3190 case X86::BI__builtin_ia32_vcvtss2usi32: 3191 case X86::BI__builtin_ia32_vcvtss2usi64: 3192 case X86::BI__builtin_ia32_sqrtpd512: 3193 case X86::BI__builtin_ia32_sqrtps512: 3194 ArgNum = 1; 3195 HasRC = true; 3196 break; 3197 case X86::BI__builtin_ia32_addpd512: 3198 case X86::BI__builtin_ia32_addps512: 3199 case X86::BI__builtin_ia32_divpd512: 3200 case X86::BI__builtin_ia32_divps512: 3201 case X86::BI__builtin_ia32_mulpd512: 3202 case X86::BI__builtin_ia32_mulps512: 3203 case X86::BI__builtin_ia32_subpd512: 3204 case X86::BI__builtin_ia32_subps512: 3205 case X86::BI__builtin_ia32_cvtsi2sd64: 3206 case X86::BI__builtin_ia32_cvtsi2ss32: 3207 case X86::BI__builtin_ia32_cvtsi2ss64: 3208 case X86::BI__builtin_ia32_cvtusi2sd64: 3209 case X86::BI__builtin_ia32_cvtusi2ss32: 3210 case X86::BI__builtin_ia32_cvtusi2ss64: 3211 ArgNum = 2; 3212 HasRC = true; 3213 break; 3214 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3215 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3216 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3217 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3218 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3219 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3220 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3221 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3222 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3223 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3224 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3225 ArgNum = 3; 3226 HasRC = true; 3227 break; 3228 case X86::BI__builtin_ia32_addss_round_mask: 3229 case X86::BI__builtin_ia32_addsd_round_mask: 3230 case X86::BI__builtin_ia32_divss_round_mask: 3231 case X86::BI__builtin_ia32_divsd_round_mask: 3232 case X86::BI__builtin_ia32_mulss_round_mask: 3233 case X86::BI__builtin_ia32_mulsd_round_mask: 3234 case X86::BI__builtin_ia32_subss_round_mask: 3235 case X86::BI__builtin_ia32_subsd_round_mask: 3236 case X86::BI__builtin_ia32_scalefpd512_mask: 3237 case X86::BI__builtin_ia32_scalefps512_mask: 3238 case X86::BI__builtin_ia32_scalefsd_round_mask: 3239 case X86::BI__builtin_ia32_scalefss_round_mask: 3240 case X86::BI__builtin_ia32_getmantpd512_mask: 3241 case X86::BI__builtin_ia32_getmantps512_mask: 3242 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3243 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3244 case X86::BI__builtin_ia32_sqrtss_round_mask: 3245 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3246 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3247 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3248 case X86::BI__builtin_ia32_vfmaddss3_mask: 3249 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3250 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3251 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3252 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3253 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3254 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3255 case X86::BI__builtin_ia32_vfmaddps512_mask: 3256 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3257 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3258 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3259 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3260 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3261 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3262 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3263 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3264 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3265 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3266 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3267 ArgNum = 4; 3268 HasRC = true; 3269 break; 3270 case X86::BI__builtin_ia32_getmantsd_round_mask: 3271 case X86::BI__builtin_ia32_getmantss_round_mask: 3272 ArgNum = 5; 3273 HasRC = true; 3274 break; 3275 } 3276 3277 llvm::APSInt Result; 3278 3279 // We can't check the value of a dependent argument. 3280 Expr *Arg = TheCall->getArg(ArgNum); 3281 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3282 return false; 3283 3284 // Check constant-ness first. 3285 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3286 return true; 3287 3288 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3289 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3290 // combined with ROUND_NO_EXC. 3291 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3292 Result == 8/*ROUND_NO_EXC*/ || 3293 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3294 return false; 3295 3296 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3297 << Arg->getSourceRange(); 3298 } 3299 3300 // Check if the gather/scatter scale is legal. 3301 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3302 CallExpr *TheCall) { 3303 unsigned ArgNum = 0; 3304 switch (BuiltinID) { 3305 default: 3306 return false; 3307 case X86::BI__builtin_ia32_gatherpfdpd: 3308 case X86::BI__builtin_ia32_gatherpfdps: 3309 case X86::BI__builtin_ia32_gatherpfqpd: 3310 case X86::BI__builtin_ia32_gatherpfqps: 3311 case X86::BI__builtin_ia32_scatterpfdpd: 3312 case X86::BI__builtin_ia32_scatterpfdps: 3313 case X86::BI__builtin_ia32_scatterpfqpd: 3314 case X86::BI__builtin_ia32_scatterpfqps: 3315 ArgNum = 3; 3316 break; 3317 case X86::BI__builtin_ia32_gatherd_pd: 3318 case X86::BI__builtin_ia32_gatherd_pd256: 3319 case X86::BI__builtin_ia32_gatherq_pd: 3320 case X86::BI__builtin_ia32_gatherq_pd256: 3321 case X86::BI__builtin_ia32_gatherd_ps: 3322 case X86::BI__builtin_ia32_gatherd_ps256: 3323 case X86::BI__builtin_ia32_gatherq_ps: 3324 case X86::BI__builtin_ia32_gatherq_ps256: 3325 case X86::BI__builtin_ia32_gatherd_q: 3326 case X86::BI__builtin_ia32_gatherd_q256: 3327 case X86::BI__builtin_ia32_gatherq_q: 3328 case X86::BI__builtin_ia32_gatherq_q256: 3329 case X86::BI__builtin_ia32_gatherd_d: 3330 case X86::BI__builtin_ia32_gatherd_d256: 3331 case X86::BI__builtin_ia32_gatherq_d: 3332 case X86::BI__builtin_ia32_gatherq_d256: 3333 case X86::BI__builtin_ia32_gather3div2df: 3334 case X86::BI__builtin_ia32_gather3div2di: 3335 case X86::BI__builtin_ia32_gather3div4df: 3336 case X86::BI__builtin_ia32_gather3div4di: 3337 case X86::BI__builtin_ia32_gather3div4sf: 3338 case X86::BI__builtin_ia32_gather3div4si: 3339 case X86::BI__builtin_ia32_gather3div8sf: 3340 case X86::BI__builtin_ia32_gather3div8si: 3341 case X86::BI__builtin_ia32_gather3siv2df: 3342 case X86::BI__builtin_ia32_gather3siv2di: 3343 case X86::BI__builtin_ia32_gather3siv4df: 3344 case X86::BI__builtin_ia32_gather3siv4di: 3345 case X86::BI__builtin_ia32_gather3siv4sf: 3346 case X86::BI__builtin_ia32_gather3siv4si: 3347 case X86::BI__builtin_ia32_gather3siv8sf: 3348 case X86::BI__builtin_ia32_gather3siv8si: 3349 case X86::BI__builtin_ia32_gathersiv8df: 3350 case X86::BI__builtin_ia32_gathersiv16sf: 3351 case X86::BI__builtin_ia32_gatherdiv8df: 3352 case X86::BI__builtin_ia32_gatherdiv16sf: 3353 case X86::BI__builtin_ia32_gathersiv8di: 3354 case X86::BI__builtin_ia32_gathersiv16si: 3355 case X86::BI__builtin_ia32_gatherdiv8di: 3356 case X86::BI__builtin_ia32_gatherdiv16si: 3357 case X86::BI__builtin_ia32_scatterdiv2df: 3358 case X86::BI__builtin_ia32_scatterdiv2di: 3359 case X86::BI__builtin_ia32_scatterdiv4df: 3360 case X86::BI__builtin_ia32_scatterdiv4di: 3361 case X86::BI__builtin_ia32_scatterdiv4sf: 3362 case X86::BI__builtin_ia32_scatterdiv4si: 3363 case X86::BI__builtin_ia32_scatterdiv8sf: 3364 case X86::BI__builtin_ia32_scatterdiv8si: 3365 case X86::BI__builtin_ia32_scattersiv2df: 3366 case X86::BI__builtin_ia32_scattersiv2di: 3367 case X86::BI__builtin_ia32_scattersiv4df: 3368 case X86::BI__builtin_ia32_scattersiv4di: 3369 case X86::BI__builtin_ia32_scattersiv4sf: 3370 case X86::BI__builtin_ia32_scattersiv4si: 3371 case X86::BI__builtin_ia32_scattersiv8sf: 3372 case X86::BI__builtin_ia32_scattersiv8si: 3373 case X86::BI__builtin_ia32_scattersiv8df: 3374 case X86::BI__builtin_ia32_scattersiv16sf: 3375 case X86::BI__builtin_ia32_scatterdiv8df: 3376 case X86::BI__builtin_ia32_scatterdiv16sf: 3377 case X86::BI__builtin_ia32_scattersiv8di: 3378 case X86::BI__builtin_ia32_scattersiv16si: 3379 case X86::BI__builtin_ia32_scatterdiv8di: 3380 case X86::BI__builtin_ia32_scatterdiv16si: 3381 ArgNum = 4; 3382 break; 3383 } 3384 3385 llvm::APSInt Result; 3386 3387 // We can't check the value of a dependent argument. 3388 Expr *Arg = TheCall->getArg(ArgNum); 3389 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3390 return false; 3391 3392 // Check constant-ness first. 3393 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3394 return true; 3395 3396 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3397 return false; 3398 3399 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3400 << Arg->getSourceRange(); 3401 } 3402 3403 static bool isX86_32Builtin(unsigned BuiltinID) { 3404 // These builtins only work on x86-32 targets. 3405 switch (BuiltinID) { 3406 case X86::BI__builtin_ia32_readeflags_u32: 3407 case X86::BI__builtin_ia32_writeeflags_u32: 3408 return true; 3409 } 3410 3411 return false; 3412 } 3413 3414 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3415 if (BuiltinID == X86::BI__builtin_cpu_supports) 3416 return SemaBuiltinCpuSupports(*this, TheCall); 3417 3418 if (BuiltinID == X86::BI__builtin_cpu_is) 3419 return SemaBuiltinCpuIs(*this, TheCall); 3420 3421 // Check for 32-bit only builtins on a 64-bit target. 3422 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3423 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3424 return Diag(TheCall->getCallee()->getBeginLoc(), 3425 diag::err_32_bit_builtin_64_bit_tgt); 3426 3427 // If the intrinsic has rounding or SAE make sure its valid. 3428 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3429 return true; 3430 3431 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3432 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3433 return true; 3434 3435 // For intrinsics which take an immediate value as part of the instruction, 3436 // range check them here. 3437 int i = 0, l = 0, u = 0; 3438 switch (BuiltinID) { 3439 default: 3440 return false; 3441 case X86::BI__builtin_ia32_vec_ext_v2si: 3442 case X86::BI__builtin_ia32_vec_ext_v2di: 3443 case X86::BI__builtin_ia32_vextractf128_pd256: 3444 case X86::BI__builtin_ia32_vextractf128_ps256: 3445 case X86::BI__builtin_ia32_vextractf128_si256: 3446 case X86::BI__builtin_ia32_extract128i256: 3447 case X86::BI__builtin_ia32_extractf64x4_mask: 3448 case X86::BI__builtin_ia32_extracti64x4_mask: 3449 case X86::BI__builtin_ia32_extractf32x8_mask: 3450 case X86::BI__builtin_ia32_extracti32x8_mask: 3451 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3452 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3453 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3454 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3455 i = 1; l = 0; u = 1; 3456 break; 3457 case X86::BI__builtin_ia32_vec_set_v2di: 3458 case X86::BI__builtin_ia32_vinsertf128_pd256: 3459 case X86::BI__builtin_ia32_vinsertf128_ps256: 3460 case X86::BI__builtin_ia32_vinsertf128_si256: 3461 case X86::BI__builtin_ia32_insert128i256: 3462 case X86::BI__builtin_ia32_insertf32x8: 3463 case X86::BI__builtin_ia32_inserti32x8: 3464 case X86::BI__builtin_ia32_insertf64x4: 3465 case X86::BI__builtin_ia32_inserti64x4: 3466 case X86::BI__builtin_ia32_insertf64x2_256: 3467 case X86::BI__builtin_ia32_inserti64x2_256: 3468 case X86::BI__builtin_ia32_insertf32x4_256: 3469 case X86::BI__builtin_ia32_inserti32x4_256: 3470 i = 2; l = 0; u = 1; 3471 break; 3472 case X86::BI__builtin_ia32_vpermilpd: 3473 case X86::BI__builtin_ia32_vec_ext_v4hi: 3474 case X86::BI__builtin_ia32_vec_ext_v4si: 3475 case X86::BI__builtin_ia32_vec_ext_v4sf: 3476 case X86::BI__builtin_ia32_vec_ext_v4di: 3477 case X86::BI__builtin_ia32_extractf32x4_mask: 3478 case X86::BI__builtin_ia32_extracti32x4_mask: 3479 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3480 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3481 i = 1; l = 0; u = 3; 3482 break; 3483 case X86::BI_mm_prefetch: 3484 case X86::BI__builtin_ia32_vec_ext_v8hi: 3485 case X86::BI__builtin_ia32_vec_ext_v8si: 3486 i = 1; l = 0; u = 7; 3487 break; 3488 case X86::BI__builtin_ia32_sha1rnds4: 3489 case X86::BI__builtin_ia32_blendpd: 3490 case X86::BI__builtin_ia32_shufpd: 3491 case X86::BI__builtin_ia32_vec_set_v4hi: 3492 case X86::BI__builtin_ia32_vec_set_v4si: 3493 case X86::BI__builtin_ia32_vec_set_v4di: 3494 case X86::BI__builtin_ia32_shuf_f32x4_256: 3495 case X86::BI__builtin_ia32_shuf_f64x2_256: 3496 case X86::BI__builtin_ia32_shuf_i32x4_256: 3497 case X86::BI__builtin_ia32_shuf_i64x2_256: 3498 case X86::BI__builtin_ia32_insertf64x2_512: 3499 case X86::BI__builtin_ia32_inserti64x2_512: 3500 case X86::BI__builtin_ia32_insertf32x4: 3501 case X86::BI__builtin_ia32_inserti32x4: 3502 i = 2; l = 0; u = 3; 3503 break; 3504 case X86::BI__builtin_ia32_vpermil2pd: 3505 case X86::BI__builtin_ia32_vpermil2pd256: 3506 case X86::BI__builtin_ia32_vpermil2ps: 3507 case X86::BI__builtin_ia32_vpermil2ps256: 3508 i = 3; l = 0; u = 3; 3509 break; 3510 case X86::BI__builtin_ia32_cmpb128_mask: 3511 case X86::BI__builtin_ia32_cmpw128_mask: 3512 case X86::BI__builtin_ia32_cmpd128_mask: 3513 case X86::BI__builtin_ia32_cmpq128_mask: 3514 case X86::BI__builtin_ia32_cmpb256_mask: 3515 case X86::BI__builtin_ia32_cmpw256_mask: 3516 case X86::BI__builtin_ia32_cmpd256_mask: 3517 case X86::BI__builtin_ia32_cmpq256_mask: 3518 case X86::BI__builtin_ia32_cmpb512_mask: 3519 case X86::BI__builtin_ia32_cmpw512_mask: 3520 case X86::BI__builtin_ia32_cmpd512_mask: 3521 case X86::BI__builtin_ia32_cmpq512_mask: 3522 case X86::BI__builtin_ia32_ucmpb128_mask: 3523 case X86::BI__builtin_ia32_ucmpw128_mask: 3524 case X86::BI__builtin_ia32_ucmpd128_mask: 3525 case X86::BI__builtin_ia32_ucmpq128_mask: 3526 case X86::BI__builtin_ia32_ucmpb256_mask: 3527 case X86::BI__builtin_ia32_ucmpw256_mask: 3528 case X86::BI__builtin_ia32_ucmpd256_mask: 3529 case X86::BI__builtin_ia32_ucmpq256_mask: 3530 case X86::BI__builtin_ia32_ucmpb512_mask: 3531 case X86::BI__builtin_ia32_ucmpw512_mask: 3532 case X86::BI__builtin_ia32_ucmpd512_mask: 3533 case X86::BI__builtin_ia32_ucmpq512_mask: 3534 case X86::BI__builtin_ia32_vpcomub: 3535 case X86::BI__builtin_ia32_vpcomuw: 3536 case X86::BI__builtin_ia32_vpcomud: 3537 case X86::BI__builtin_ia32_vpcomuq: 3538 case X86::BI__builtin_ia32_vpcomb: 3539 case X86::BI__builtin_ia32_vpcomw: 3540 case X86::BI__builtin_ia32_vpcomd: 3541 case X86::BI__builtin_ia32_vpcomq: 3542 case X86::BI__builtin_ia32_vec_set_v8hi: 3543 case X86::BI__builtin_ia32_vec_set_v8si: 3544 i = 2; l = 0; u = 7; 3545 break; 3546 case X86::BI__builtin_ia32_vpermilpd256: 3547 case X86::BI__builtin_ia32_roundps: 3548 case X86::BI__builtin_ia32_roundpd: 3549 case X86::BI__builtin_ia32_roundps256: 3550 case X86::BI__builtin_ia32_roundpd256: 3551 case X86::BI__builtin_ia32_getmantpd128_mask: 3552 case X86::BI__builtin_ia32_getmantpd256_mask: 3553 case X86::BI__builtin_ia32_getmantps128_mask: 3554 case X86::BI__builtin_ia32_getmantps256_mask: 3555 case X86::BI__builtin_ia32_getmantpd512_mask: 3556 case X86::BI__builtin_ia32_getmantps512_mask: 3557 case X86::BI__builtin_ia32_vec_ext_v16qi: 3558 case X86::BI__builtin_ia32_vec_ext_v16hi: 3559 i = 1; l = 0; u = 15; 3560 break; 3561 case X86::BI__builtin_ia32_pblendd128: 3562 case X86::BI__builtin_ia32_blendps: 3563 case X86::BI__builtin_ia32_blendpd256: 3564 case X86::BI__builtin_ia32_shufpd256: 3565 case X86::BI__builtin_ia32_roundss: 3566 case X86::BI__builtin_ia32_roundsd: 3567 case X86::BI__builtin_ia32_rangepd128_mask: 3568 case X86::BI__builtin_ia32_rangepd256_mask: 3569 case X86::BI__builtin_ia32_rangepd512_mask: 3570 case X86::BI__builtin_ia32_rangeps128_mask: 3571 case X86::BI__builtin_ia32_rangeps256_mask: 3572 case X86::BI__builtin_ia32_rangeps512_mask: 3573 case X86::BI__builtin_ia32_getmantsd_round_mask: 3574 case X86::BI__builtin_ia32_getmantss_round_mask: 3575 case X86::BI__builtin_ia32_vec_set_v16qi: 3576 case X86::BI__builtin_ia32_vec_set_v16hi: 3577 i = 2; l = 0; u = 15; 3578 break; 3579 case X86::BI__builtin_ia32_vec_ext_v32qi: 3580 i = 1; l = 0; u = 31; 3581 break; 3582 case X86::BI__builtin_ia32_cmpps: 3583 case X86::BI__builtin_ia32_cmpss: 3584 case X86::BI__builtin_ia32_cmppd: 3585 case X86::BI__builtin_ia32_cmpsd: 3586 case X86::BI__builtin_ia32_cmpps256: 3587 case X86::BI__builtin_ia32_cmppd256: 3588 case X86::BI__builtin_ia32_cmpps128_mask: 3589 case X86::BI__builtin_ia32_cmppd128_mask: 3590 case X86::BI__builtin_ia32_cmpps256_mask: 3591 case X86::BI__builtin_ia32_cmppd256_mask: 3592 case X86::BI__builtin_ia32_cmpps512_mask: 3593 case X86::BI__builtin_ia32_cmppd512_mask: 3594 case X86::BI__builtin_ia32_cmpsd_mask: 3595 case X86::BI__builtin_ia32_cmpss_mask: 3596 case X86::BI__builtin_ia32_vec_set_v32qi: 3597 i = 2; l = 0; u = 31; 3598 break; 3599 case X86::BI__builtin_ia32_permdf256: 3600 case X86::BI__builtin_ia32_permdi256: 3601 case X86::BI__builtin_ia32_permdf512: 3602 case X86::BI__builtin_ia32_permdi512: 3603 case X86::BI__builtin_ia32_vpermilps: 3604 case X86::BI__builtin_ia32_vpermilps256: 3605 case X86::BI__builtin_ia32_vpermilpd512: 3606 case X86::BI__builtin_ia32_vpermilps512: 3607 case X86::BI__builtin_ia32_pshufd: 3608 case X86::BI__builtin_ia32_pshufd256: 3609 case X86::BI__builtin_ia32_pshufd512: 3610 case X86::BI__builtin_ia32_pshufhw: 3611 case X86::BI__builtin_ia32_pshufhw256: 3612 case X86::BI__builtin_ia32_pshufhw512: 3613 case X86::BI__builtin_ia32_pshuflw: 3614 case X86::BI__builtin_ia32_pshuflw256: 3615 case X86::BI__builtin_ia32_pshuflw512: 3616 case X86::BI__builtin_ia32_vcvtps2ph: 3617 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3618 case X86::BI__builtin_ia32_vcvtps2ph256: 3619 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3620 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3621 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3622 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3623 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3624 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3625 case X86::BI__builtin_ia32_rndscaleps_mask: 3626 case X86::BI__builtin_ia32_rndscalepd_mask: 3627 case X86::BI__builtin_ia32_reducepd128_mask: 3628 case X86::BI__builtin_ia32_reducepd256_mask: 3629 case X86::BI__builtin_ia32_reducepd512_mask: 3630 case X86::BI__builtin_ia32_reduceps128_mask: 3631 case X86::BI__builtin_ia32_reduceps256_mask: 3632 case X86::BI__builtin_ia32_reduceps512_mask: 3633 case X86::BI__builtin_ia32_prold512: 3634 case X86::BI__builtin_ia32_prolq512: 3635 case X86::BI__builtin_ia32_prold128: 3636 case X86::BI__builtin_ia32_prold256: 3637 case X86::BI__builtin_ia32_prolq128: 3638 case X86::BI__builtin_ia32_prolq256: 3639 case X86::BI__builtin_ia32_prord512: 3640 case X86::BI__builtin_ia32_prorq512: 3641 case X86::BI__builtin_ia32_prord128: 3642 case X86::BI__builtin_ia32_prord256: 3643 case X86::BI__builtin_ia32_prorq128: 3644 case X86::BI__builtin_ia32_prorq256: 3645 case X86::BI__builtin_ia32_fpclasspd128_mask: 3646 case X86::BI__builtin_ia32_fpclasspd256_mask: 3647 case X86::BI__builtin_ia32_fpclassps128_mask: 3648 case X86::BI__builtin_ia32_fpclassps256_mask: 3649 case X86::BI__builtin_ia32_fpclassps512_mask: 3650 case X86::BI__builtin_ia32_fpclasspd512_mask: 3651 case X86::BI__builtin_ia32_fpclasssd_mask: 3652 case X86::BI__builtin_ia32_fpclassss_mask: 3653 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3654 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3655 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3656 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3657 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3658 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3659 case X86::BI__builtin_ia32_kshiftliqi: 3660 case X86::BI__builtin_ia32_kshiftlihi: 3661 case X86::BI__builtin_ia32_kshiftlisi: 3662 case X86::BI__builtin_ia32_kshiftlidi: 3663 case X86::BI__builtin_ia32_kshiftriqi: 3664 case X86::BI__builtin_ia32_kshiftrihi: 3665 case X86::BI__builtin_ia32_kshiftrisi: 3666 case X86::BI__builtin_ia32_kshiftridi: 3667 i = 1; l = 0; u = 255; 3668 break; 3669 case X86::BI__builtin_ia32_vperm2f128_pd256: 3670 case X86::BI__builtin_ia32_vperm2f128_ps256: 3671 case X86::BI__builtin_ia32_vperm2f128_si256: 3672 case X86::BI__builtin_ia32_permti256: 3673 case X86::BI__builtin_ia32_pblendw128: 3674 case X86::BI__builtin_ia32_pblendw256: 3675 case X86::BI__builtin_ia32_blendps256: 3676 case X86::BI__builtin_ia32_pblendd256: 3677 case X86::BI__builtin_ia32_palignr128: 3678 case X86::BI__builtin_ia32_palignr256: 3679 case X86::BI__builtin_ia32_palignr512: 3680 case X86::BI__builtin_ia32_alignq512: 3681 case X86::BI__builtin_ia32_alignd512: 3682 case X86::BI__builtin_ia32_alignd128: 3683 case X86::BI__builtin_ia32_alignd256: 3684 case X86::BI__builtin_ia32_alignq128: 3685 case X86::BI__builtin_ia32_alignq256: 3686 case X86::BI__builtin_ia32_vcomisd: 3687 case X86::BI__builtin_ia32_vcomiss: 3688 case X86::BI__builtin_ia32_shuf_f32x4: 3689 case X86::BI__builtin_ia32_shuf_f64x2: 3690 case X86::BI__builtin_ia32_shuf_i32x4: 3691 case X86::BI__builtin_ia32_shuf_i64x2: 3692 case X86::BI__builtin_ia32_shufpd512: 3693 case X86::BI__builtin_ia32_shufps: 3694 case X86::BI__builtin_ia32_shufps256: 3695 case X86::BI__builtin_ia32_shufps512: 3696 case X86::BI__builtin_ia32_dbpsadbw128: 3697 case X86::BI__builtin_ia32_dbpsadbw256: 3698 case X86::BI__builtin_ia32_dbpsadbw512: 3699 case X86::BI__builtin_ia32_vpshldd128: 3700 case X86::BI__builtin_ia32_vpshldd256: 3701 case X86::BI__builtin_ia32_vpshldd512: 3702 case X86::BI__builtin_ia32_vpshldq128: 3703 case X86::BI__builtin_ia32_vpshldq256: 3704 case X86::BI__builtin_ia32_vpshldq512: 3705 case X86::BI__builtin_ia32_vpshldw128: 3706 case X86::BI__builtin_ia32_vpshldw256: 3707 case X86::BI__builtin_ia32_vpshldw512: 3708 case X86::BI__builtin_ia32_vpshrdd128: 3709 case X86::BI__builtin_ia32_vpshrdd256: 3710 case X86::BI__builtin_ia32_vpshrdd512: 3711 case X86::BI__builtin_ia32_vpshrdq128: 3712 case X86::BI__builtin_ia32_vpshrdq256: 3713 case X86::BI__builtin_ia32_vpshrdq512: 3714 case X86::BI__builtin_ia32_vpshrdw128: 3715 case X86::BI__builtin_ia32_vpshrdw256: 3716 case X86::BI__builtin_ia32_vpshrdw512: 3717 i = 2; l = 0; u = 255; 3718 break; 3719 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3720 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3721 case X86::BI__builtin_ia32_fixupimmps512_mask: 3722 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3723 case X86::BI__builtin_ia32_fixupimmsd_mask: 3724 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3725 case X86::BI__builtin_ia32_fixupimmss_mask: 3726 case X86::BI__builtin_ia32_fixupimmss_maskz: 3727 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3728 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3729 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3730 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3731 case X86::BI__builtin_ia32_fixupimmps128_mask: 3732 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3733 case X86::BI__builtin_ia32_fixupimmps256_mask: 3734 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3735 case X86::BI__builtin_ia32_pternlogd512_mask: 3736 case X86::BI__builtin_ia32_pternlogd512_maskz: 3737 case X86::BI__builtin_ia32_pternlogq512_mask: 3738 case X86::BI__builtin_ia32_pternlogq512_maskz: 3739 case X86::BI__builtin_ia32_pternlogd128_mask: 3740 case X86::BI__builtin_ia32_pternlogd128_maskz: 3741 case X86::BI__builtin_ia32_pternlogd256_mask: 3742 case X86::BI__builtin_ia32_pternlogd256_maskz: 3743 case X86::BI__builtin_ia32_pternlogq128_mask: 3744 case X86::BI__builtin_ia32_pternlogq128_maskz: 3745 case X86::BI__builtin_ia32_pternlogq256_mask: 3746 case X86::BI__builtin_ia32_pternlogq256_maskz: 3747 i = 3; l = 0; u = 255; 3748 break; 3749 case X86::BI__builtin_ia32_gatherpfdpd: 3750 case X86::BI__builtin_ia32_gatherpfdps: 3751 case X86::BI__builtin_ia32_gatherpfqpd: 3752 case X86::BI__builtin_ia32_gatherpfqps: 3753 case X86::BI__builtin_ia32_scatterpfdpd: 3754 case X86::BI__builtin_ia32_scatterpfdps: 3755 case X86::BI__builtin_ia32_scatterpfqpd: 3756 case X86::BI__builtin_ia32_scatterpfqps: 3757 i = 4; l = 2; u = 3; 3758 break; 3759 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3760 case X86::BI__builtin_ia32_rndscaless_round_mask: 3761 i = 4; l = 0; u = 255; 3762 break; 3763 } 3764 3765 // Note that we don't force a hard error on the range check here, allowing 3766 // template-generated or macro-generated dead code to potentially have out-of- 3767 // range values. These need to code generate, but don't need to necessarily 3768 // make any sense. We use a warning that defaults to an error. 3769 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3770 } 3771 3772 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3773 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3774 /// Returns true when the format fits the function and the FormatStringInfo has 3775 /// been populated. 3776 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3777 FormatStringInfo *FSI) { 3778 FSI->HasVAListArg = Format->getFirstArg() == 0; 3779 FSI->FormatIdx = Format->getFormatIdx() - 1; 3780 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3781 3782 // The way the format attribute works in GCC, the implicit this argument 3783 // of member functions is counted. However, it doesn't appear in our own 3784 // lists, so decrement format_idx in that case. 3785 if (IsCXXMember) { 3786 if(FSI->FormatIdx == 0) 3787 return false; 3788 --FSI->FormatIdx; 3789 if (FSI->FirstDataArg != 0) 3790 --FSI->FirstDataArg; 3791 } 3792 return true; 3793 } 3794 3795 /// Checks if a the given expression evaluates to null. 3796 /// 3797 /// Returns true if the value evaluates to null. 3798 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3799 // If the expression has non-null type, it doesn't evaluate to null. 3800 if (auto nullability 3801 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3802 if (*nullability == NullabilityKind::NonNull) 3803 return false; 3804 } 3805 3806 // As a special case, transparent unions initialized with zero are 3807 // considered null for the purposes of the nonnull attribute. 3808 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3809 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3810 if (const CompoundLiteralExpr *CLE = 3811 dyn_cast<CompoundLiteralExpr>(Expr)) 3812 if (const InitListExpr *ILE = 3813 dyn_cast<InitListExpr>(CLE->getInitializer())) 3814 Expr = ILE->getInit(0); 3815 } 3816 3817 bool Result; 3818 return (!Expr->isValueDependent() && 3819 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3820 !Result); 3821 } 3822 3823 static void CheckNonNullArgument(Sema &S, 3824 const Expr *ArgExpr, 3825 SourceLocation CallSiteLoc) { 3826 if (CheckNonNullExpr(S, ArgExpr)) 3827 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3828 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 3829 } 3830 3831 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3832 FormatStringInfo FSI; 3833 if ((GetFormatStringType(Format) == FST_NSString) && 3834 getFormatStringInfo(Format, false, &FSI)) { 3835 Idx = FSI.FormatIdx; 3836 return true; 3837 } 3838 return false; 3839 } 3840 3841 /// Diagnose use of %s directive in an NSString which is being passed 3842 /// as formatting string to formatting method. 3843 static void 3844 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3845 const NamedDecl *FDecl, 3846 Expr **Args, 3847 unsigned NumArgs) { 3848 unsigned Idx = 0; 3849 bool Format = false; 3850 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3851 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3852 Idx = 2; 3853 Format = true; 3854 } 3855 else 3856 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3857 if (S.GetFormatNSStringIdx(I, Idx)) { 3858 Format = true; 3859 break; 3860 } 3861 } 3862 if (!Format || NumArgs <= Idx) 3863 return; 3864 const Expr *FormatExpr = Args[Idx]; 3865 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3866 FormatExpr = CSCE->getSubExpr(); 3867 const StringLiteral *FormatString; 3868 if (const ObjCStringLiteral *OSL = 3869 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3870 FormatString = OSL->getString(); 3871 else 3872 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3873 if (!FormatString) 3874 return; 3875 if (S.FormatStringHasSArg(FormatString)) { 3876 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3877 << "%s" << 1 << 1; 3878 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3879 << FDecl->getDeclName(); 3880 } 3881 } 3882 3883 /// Determine whether the given type has a non-null nullability annotation. 3884 static bool isNonNullType(ASTContext &ctx, QualType type) { 3885 if (auto nullability = type->getNullability(ctx)) 3886 return *nullability == NullabilityKind::NonNull; 3887 3888 return false; 3889 } 3890 3891 static void CheckNonNullArguments(Sema &S, 3892 const NamedDecl *FDecl, 3893 const FunctionProtoType *Proto, 3894 ArrayRef<const Expr *> Args, 3895 SourceLocation CallSiteLoc) { 3896 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3897 3898 // Check the attributes attached to the method/function itself. 3899 llvm::SmallBitVector NonNullArgs; 3900 if (FDecl) { 3901 // Handle the nonnull attribute on the function/method declaration itself. 3902 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3903 if (!NonNull->args_size()) { 3904 // Easy case: all pointer arguments are nonnull. 3905 for (const auto *Arg : Args) 3906 if (S.isValidPointerAttrType(Arg->getType())) 3907 CheckNonNullArgument(S, Arg, CallSiteLoc); 3908 return; 3909 } 3910 3911 for (const ParamIdx &Idx : NonNull->args()) { 3912 unsigned IdxAST = Idx.getASTIndex(); 3913 if (IdxAST >= Args.size()) 3914 continue; 3915 if (NonNullArgs.empty()) 3916 NonNullArgs.resize(Args.size()); 3917 NonNullArgs.set(IdxAST); 3918 } 3919 } 3920 } 3921 3922 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3923 // Handle the nonnull attribute on the parameters of the 3924 // function/method. 3925 ArrayRef<ParmVarDecl*> parms; 3926 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3927 parms = FD->parameters(); 3928 else 3929 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3930 3931 unsigned ParamIndex = 0; 3932 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3933 I != E; ++I, ++ParamIndex) { 3934 const ParmVarDecl *PVD = *I; 3935 if (PVD->hasAttr<NonNullAttr>() || 3936 isNonNullType(S.Context, PVD->getType())) { 3937 if (NonNullArgs.empty()) 3938 NonNullArgs.resize(Args.size()); 3939 3940 NonNullArgs.set(ParamIndex); 3941 } 3942 } 3943 } else { 3944 // If we have a non-function, non-method declaration but no 3945 // function prototype, try to dig out the function prototype. 3946 if (!Proto) { 3947 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3948 QualType type = VD->getType().getNonReferenceType(); 3949 if (auto pointerType = type->getAs<PointerType>()) 3950 type = pointerType->getPointeeType(); 3951 else if (auto blockType = type->getAs<BlockPointerType>()) 3952 type = blockType->getPointeeType(); 3953 // FIXME: data member pointers? 3954 3955 // Dig out the function prototype, if there is one. 3956 Proto = type->getAs<FunctionProtoType>(); 3957 } 3958 } 3959 3960 // Fill in non-null argument information from the nullability 3961 // information on the parameter types (if we have them). 3962 if (Proto) { 3963 unsigned Index = 0; 3964 for (auto paramType : Proto->getParamTypes()) { 3965 if (isNonNullType(S.Context, paramType)) { 3966 if (NonNullArgs.empty()) 3967 NonNullArgs.resize(Args.size()); 3968 3969 NonNullArgs.set(Index); 3970 } 3971 3972 ++Index; 3973 } 3974 } 3975 } 3976 3977 // Check for non-null arguments. 3978 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 3979 ArgIndex != ArgIndexEnd; ++ArgIndex) { 3980 if (NonNullArgs[ArgIndex]) 3981 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 3982 } 3983 } 3984 3985 /// Handles the checks for format strings, non-POD arguments to vararg 3986 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 3987 /// attributes. 3988 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 3989 const Expr *ThisArg, ArrayRef<const Expr *> Args, 3990 bool IsMemberFunction, SourceLocation Loc, 3991 SourceRange Range, VariadicCallType CallType) { 3992 // FIXME: We should check as much as we can in the template definition. 3993 if (CurContext->isDependentContext()) 3994 return; 3995 3996 // Printf and scanf checking. 3997 llvm::SmallBitVector CheckedVarArgs; 3998 if (FDecl) { 3999 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4000 // Only create vector if there are format attributes. 4001 CheckedVarArgs.resize(Args.size()); 4002 4003 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4004 CheckedVarArgs); 4005 } 4006 } 4007 4008 // Refuse POD arguments that weren't caught by the format string 4009 // checks above. 4010 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4011 if (CallType != VariadicDoesNotApply && 4012 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4013 unsigned NumParams = Proto ? Proto->getNumParams() 4014 : FDecl && isa<FunctionDecl>(FDecl) 4015 ? cast<FunctionDecl>(FDecl)->getNumParams() 4016 : FDecl && isa<ObjCMethodDecl>(FDecl) 4017 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4018 : 0; 4019 4020 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4021 // Args[ArgIdx] can be null in malformed code. 4022 if (const Expr *Arg = Args[ArgIdx]) { 4023 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4024 checkVariadicArgument(Arg, CallType); 4025 } 4026 } 4027 } 4028 4029 if (FDecl || Proto) { 4030 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4031 4032 // Type safety checking. 4033 if (FDecl) { 4034 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4035 CheckArgumentWithTypeTag(I, Args, Loc); 4036 } 4037 } 4038 4039 if (FD) 4040 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4041 } 4042 4043 /// CheckConstructorCall - Check a constructor call for correctness and safety 4044 /// properties not enforced by the C type system. 4045 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4046 ArrayRef<const Expr *> Args, 4047 const FunctionProtoType *Proto, 4048 SourceLocation Loc) { 4049 VariadicCallType CallType = 4050 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4051 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4052 Loc, SourceRange(), CallType); 4053 } 4054 4055 /// CheckFunctionCall - Check a direct function call for various correctness 4056 /// and safety properties not strictly enforced by the C type system. 4057 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4058 const FunctionProtoType *Proto) { 4059 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4060 isa<CXXMethodDecl>(FDecl); 4061 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4062 IsMemberOperatorCall; 4063 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4064 TheCall->getCallee()); 4065 Expr** Args = TheCall->getArgs(); 4066 unsigned NumArgs = TheCall->getNumArgs(); 4067 4068 Expr *ImplicitThis = nullptr; 4069 if (IsMemberOperatorCall) { 4070 // If this is a call to a member operator, hide the first argument 4071 // from checkCall. 4072 // FIXME: Our choice of AST representation here is less than ideal. 4073 ImplicitThis = Args[0]; 4074 ++Args; 4075 --NumArgs; 4076 } else if (IsMemberFunction) 4077 ImplicitThis = 4078 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4079 4080 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4081 IsMemberFunction, TheCall->getRParenLoc(), 4082 TheCall->getCallee()->getSourceRange(), CallType); 4083 4084 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4085 // None of the checks below are needed for functions that don't have 4086 // simple names (e.g., C++ conversion functions). 4087 if (!FnInfo) 4088 return false; 4089 4090 CheckAbsoluteValueFunction(TheCall, FDecl); 4091 CheckMaxUnsignedZero(TheCall, FDecl); 4092 4093 if (getLangOpts().ObjC1) 4094 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4095 4096 unsigned CMId = FDecl->getMemoryFunctionKind(); 4097 if (CMId == 0) 4098 return false; 4099 4100 // Handle memory setting and copying functions. 4101 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4102 CheckStrlcpycatArguments(TheCall, FnInfo); 4103 else if (CMId == Builtin::BIstrncat) 4104 CheckStrncatArguments(TheCall, FnInfo); 4105 else 4106 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4107 4108 return false; 4109 } 4110 4111 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4112 ArrayRef<const Expr *> Args) { 4113 VariadicCallType CallType = 4114 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4115 4116 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4117 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4118 CallType); 4119 4120 return false; 4121 } 4122 4123 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4124 const FunctionProtoType *Proto) { 4125 QualType Ty; 4126 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4127 Ty = V->getType().getNonReferenceType(); 4128 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4129 Ty = F->getType().getNonReferenceType(); 4130 else 4131 return false; 4132 4133 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4134 !Ty->isFunctionProtoType()) 4135 return false; 4136 4137 VariadicCallType CallType; 4138 if (!Proto || !Proto->isVariadic()) { 4139 CallType = VariadicDoesNotApply; 4140 } else if (Ty->isBlockPointerType()) { 4141 CallType = VariadicBlock; 4142 } else { // Ty->isFunctionPointerType() 4143 CallType = VariadicFunction; 4144 } 4145 4146 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4147 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4148 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4149 TheCall->getCallee()->getSourceRange(), CallType); 4150 4151 return false; 4152 } 4153 4154 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4155 /// such as function pointers returned from functions. 4156 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4157 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4158 TheCall->getCallee()); 4159 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4160 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4161 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4162 TheCall->getCallee()->getSourceRange(), CallType); 4163 4164 return false; 4165 } 4166 4167 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4168 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4169 return false; 4170 4171 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4172 switch (Op) { 4173 case AtomicExpr::AO__c11_atomic_init: 4174 case AtomicExpr::AO__opencl_atomic_init: 4175 llvm_unreachable("There is no ordering argument for an init"); 4176 4177 case AtomicExpr::AO__c11_atomic_load: 4178 case AtomicExpr::AO__opencl_atomic_load: 4179 case AtomicExpr::AO__atomic_load_n: 4180 case AtomicExpr::AO__atomic_load: 4181 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4182 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4183 4184 case AtomicExpr::AO__c11_atomic_store: 4185 case AtomicExpr::AO__opencl_atomic_store: 4186 case AtomicExpr::AO__atomic_store: 4187 case AtomicExpr::AO__atomic_store_n: 4188 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4189 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4190 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4191 4192 default: 4193 return true; 4194 } 4195 } 4196 4197 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4198 AtomicExpr::AtomicOp Op) { 4199 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4200 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4201 4202 // All the non-OpenCL operations take one of the following forms. 4203 // The OpenCL operations take the __c11 forms with one extra argument for 4204 // synchronization scope. 4205 enum { 4206 // C __c11_atomic_init(A *, C) 4207 Init, 4208 4209 // C __c11_atomic_load(A *, int) 4210 Load, 4211 4212 // void __atomic_load(A *, CP, int) 4213 LoadCopy, 4214 4215 // void __atomic_store(A *, CP, int) 4216 Copy, 4217 4218 // C __c11_atomic_add(A *, M, int) 4219 Arithmetic, 4220 4221 // C __atomic_exchange_n(A *, CP, int) 4222 Xchg, 4223 4224 // void __atomic_exchange(A *, C *, CP, int) 4225 GNUXchg, 4226 4227 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4228 C11CmpXchg, 4229 4230 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4231 GNUCmpXchg 4232 } Form = Init; 4233 4234 const unsigned NumForm = GNUCmpXchg + 1; 4235 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4236 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4237 // where: 4238 // C is an appropriate type, 4239 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4240 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4241 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4242 // the int parameters are for orderings. 4243 4244 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4245 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4246 "need to update code for modified forms"); 4247 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4248 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4249 AtomicExpr::AO__atomic_load, 4250 "need to update code for modified C11 atomics"); 4251 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4252 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4253 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4254 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4255 IsOpenCL; 4256 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4257 Op == AtomicExpr::AO__atomic_store_n || 4258 Op == AtomicExpr::AO__atomic_exchange_n || 4259 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4260 bool IsAddSub = false; 4261 bool IsMinMax = false; 4262 4263 switch (Op) { 4264 case AtomicExpr::AO__c11_atomic_init: 4265 case AtomicExpr::AO__opencl_atomic_init: 4266 Form = Init; 4267 break; 4268 4269 case AtomicExpr::AO__c11_atomic_load: 4270 case AtomicExpr::AO__opencl_atomic_load: 4271 case AtomicExpr::AO__atomic_load_n: 4272 Form = Load; 4273 break; 4274 4275 case AtomicExpr::AO__atomic_load: 4276 Form = LoadCopy; 4277 break; 4278 4279 case AtomicExpr::AO__c11_atomic_store: 4280 case AtomicExpr::AO__opencl_atomic_store: 4281 case AtomicExpr::AO__atomic_store: 4282 case AtomicExpr::AO__atomic_store_n: 4283 Form = Copy; 4284 break; 4285 4286 case AtomicExpr::AO__c11_atomic_fetch_add: 4287 case AtomicExpr::AO__c11_atomic_fetch_sub: 4288 case AtomicExpr::AO__opencl_atomic_fetch_add: 4289 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4290 case AtomicExpr::AO__opencl_atomic_fetch_min: 4291 case AtomicExpr::AO__opencl_atomic_fetch_max: 4292 case AtomicExpr::AO__atomic_fetch_add: 4293 case AtomicExpr::AO__atomic_fetch_sub: 4294 case AtomicExpr::AO__atomic_add_fetch: 4295 case AtomicExpr::AO__atomic_sub_fetch: 4296 IsAddSub = true; 4297 LLVM_FALLTHROUGH; 4298 case AtomicExpr::AO__c11_atomic_fetch_and: 4299 case AtomicExpr::AO__c11_atomic_fetch_or: 4300 case AtomicExpr::AO__c11_atomic_fetch_xor: 4301 case AtomicExpr::AO__opencl_atomic_fetch_and: 4302 case AtomicExpr::AO__opencl_atomic_fetch_or: 4303 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4304 case AtomicExpr::AO__atomic_fetch_and: 4305 case AtomicExpr::AO__atomic_fetch_or: 4306 case AtomicExpr::AO__atomic_fetch_xor: 4307 case AtomicExpr::AO__atomic_fetch_nand: 4308 case AtomicExpr::AO__atomic_and_fetch: 4309 case AtomicExpr::AO__atomic_or_fetch: 4310 case AtomicExpr::AO__atomic_xor_fetch: 4311 case AtomicExpr::AO__atomic_nand_fetch: 4312 Form = Arithmetic; 4313 break; 4314 4315 case AtomicExpr::AO__atomic_fetch_min: 4316 case AtomicExpr::AO__atomic_fetch_max: 4317 IsMinMax = true; 4318 Form = Arithmetic; 4319 break; 4320 4321 case AtomicExpr::AO__c11_atomic_exchange: 4322 case AtomicExpr::AO__opencl_atomic_exchange: 4323 case AtomicExpr::AO__atomic_exchange_n: 4324 Form = Xchg; 4325 break; 4326 4327 case AtomicExpr::AO__atomic_exchange: 4328 Form = GNUXchg; 4329 break; 4330 4331 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4332 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4333 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4334 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4335 Form = C11CmpXchg; 4336 break; 4337 4338 case AtomicExpr::AO__atomic_compare_exchange: 4339 case AtomicExpr::AO__atomic_compare_exchange_n: 4340 Form = GNUCmpXchg; 4341 break; 4342 } 4343 4344 unsigned AdjustedNumArgs = NumArgs[Form]; 4345 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4346 ++AdjustedNumArgs; 4347 // Check we have the right number of arguments. 4348 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4349 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4350 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4351 << TheCall->getCallee()->getSourceRange(); 4352 return ExprError(); 4353 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4354 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4355 diag::err_typecheck_call_too_many_args) 4356 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4357 << TheCall->getCallee()->getSourceRange(); 4358 return ExprError(); 4359 } 4360 4361 // Inspect the first argument of the atomic operation. 4362 Expr *Ptr = TheCall->getArg(0); 4363 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4364 if (ConvertedPtr.isInvalid()) 4365 return ExprError(); 4366 4367 Ptr = ConvertedPtr.get(); 4368 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4369 if (!pointerType) { 4370 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4371 << Ptr->getType() << Ptr->getSourceRange(); 4372 return ExprError(); 4373 } 4374 4375 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4376 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4377 QualType ValType = AtomTy; // 'C' 4378 if (IsC11) { 4379 if (!AtomTy->isAtomicType()) { 4380 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4381 << Ptr->getType() << Ptr->getSourceRange(); 4382 return ExprError(); 4383 } 4384 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4385 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4386 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4387 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4388 << Ptr->getSourceRange(); 4389 return ExprError(); 4390 } 4391 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4392 } else if (Form != Load && Form != LoadCopy) { 4393 if (ValType.isConstQualified()) { 4394 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4395 << Ptr->getType() << Ptr->getSourceRange(); 4396 return ExprError(); 4397 } 4398 } 4399 4400 // For an arithmetic operation, the implied arithmetic must be well-formed. 4401 if (Form == Arithmetic) { 4402 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4403 if (IsAddSub && !ValType->isIntegerType() 4404 && !ValType->isPointerType()) { 4405 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4406 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4407 return ExprError(); 4408 } 4409 if (IsMinMax) { 4410 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4411 if (!BT || (BT->getKind() != BuiltinType::Int && 4412 BT->getKind() != BuiltinType::UInt)) { 4413 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4414 return ExprError(); 4415 } 4416 } 4417 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4418 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4419 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4420 return ExprError(); 4421 } 4422 if (IsC11 && ValType->isPointerType() && 4423 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4424 diag::err_incomplete_type)) { 4425 return ExprError(); 4426 } 4427 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4428 // For __atomic_*_n operations, the value type must be a scalar integral or 4429 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4430 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4431 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4432 return ExprError(); 4433 } 4434 4435 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4436 !AtomTy->isScalarType()) { 4437 // For GNU atomics, require a trivially-copyable type. This is not part of 4438 // the GNU atomics specification, but we enforce it for sanity. 4439 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4440 << Ptr->getType() << Ptr->getSourceRange(); 4441 return ExprError(); 4442 } 4443 4444 switch (ValType.getObjCLifetime()) { 4445 case Qualifiers::OCL_None: 4446 case Qualifiers::OCL_ExplicitNone: 4447 // okay 4448 break; 4449 4450 case Qualifiers::OCL_Weak: 4451 case Qualifiers::OCL_Strong: 4452 case Qualifiers::OCL_Autoreleasing: 4453 // FIXME: Can this happen? By this point, ValType should be known 4454 // to be trivially copyable. 4455 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4456 << ValType << Ptr->getSourceRange(); 4457 return ExprError(); 4458 } 4459 4460 // All atomic operations have an overload which takes a pointer to a volatile 4461 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4462 // into the result or the other operands. Similarly atomic_load takes a 4463 // pointer to a const 'A'. 4464 ValType.removeLocalVolatile(); 4465 ValType.removeLocalConst(); 4466 QualType ResultType = ValType; 4467 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4468 Form == Init) 4469 ResultType = Context.VoidTy; 4470 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4471 ResultType = Context.BoolTy; 4472 4473 // The type of a parameter passed 'by value'. In the GNU atomics, such 4474 // arguments are actually passed as pointers. 4475 QualType ByValType = ValType; // 'CP' 4476 bool IsPassedByAddress = false; 4477 if (!IsC11 && !IsN) { 4478 ByValType = Ptr->getType(); 4479 IsPassedByAddress = true; 4480 } 4481 4482 // The first argument's non-CV pointer type is used to deduce the type of 4483 // subsequent arguments, except for: 4484 // - weak flag (always converted to bool) 4485 // - memory order (always converted to int) 4486 // - scope (always converted to int) 4487 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4488 QualType Ty; 4489 if (i < NumVals[Form] + 1) { 4490 switch (i) { 4491 case 0: 4492 // The first argument is always a pointer. It has a fixed type. 4493 // It is always dereferenced, a nullptr is undefined. 4494 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4495 // Nothing else to do: we already know all we want about this pointer. 4496 continue; 4497 case 1: 4498 // The second argument is the non-atomic operand. For arithmetic, this 4499 // is always passed by value, and for a compare_exchange it is always 4500 // passed by address. For the rest, GNU uses by-address and C11 uses 4501 // by-value. 4502 assert(Form != Load); 4503 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4504 Ty = ValType; 4505 else if (Form == Copy || Form == Xchg) { 4506 if (IsPassedByAddress) 4507 // The value pointer is always dereferenced, a nullptr is undefined. 4508 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4509 Ty = ByValType; 4510 } else if (Form == Arithmetic) 4511 Ty = Context.getPointerDiffType(); 4512 else { 4513 Expr *ValArg = TheCall->getArg(i); 4514 // The value pointer is always dereferenced, a nullptr is undefined. 4515 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4516 LangAS AS = LangAS::Default; 4517 // Keep address space of non-atomic pointer type. 4518 if (const PointerType *PtrTy = 4519 ValArg->getType()->getAs<PointerType>()) { 4520 AS = PtrTy->getPointeeType().getAddressSpace(); 4521 } 4522 Ty = Context.getPointerType( 4523 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4524 } 4525 break; 4526 case 2: 4527 // The third argument to compare_exchange / GNU exchange is the desired 4528 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4529 if (IsPassedByAddress) 4530 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4531 Ty = ByValType; 4532 break; 4533 case 3: 4534 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4535 Ty = Context.BoolTy; 4536 break; 4537 } 4538 } else { 4539 // The order(s) and scope are always converted to int. 4540 Ty = Context.IntTy; 4541 } 4542 4543 InitializedEntity Entity = 4544 InitializedEntity::InitializeParameter(Context, Ty, false); 4545 ExprResult Arg = TheCall->getArg(i); 4546 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4547 if (Arg.isInvalid()) 4548 return true; 4549 TheCall->setArg(i, Arg.get()); 4550 } 4551 4552 // Permute the arguments into a 'consistent' order. 4553 SmallVector<Expr*, 5> SubExprs; 4554 SubExprs.push_back(Ptr); 4555 switch (Form) { 4556 case Init: 4557 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4558 SubExprs.push_back(TheCall->getArg(1)); // Val1 4559 break; 4560 case Load: 4561 SubExprs.push_back(TheCall->getArg(1)); // Order 4562 break; 4563 case LoadCopy: 4564 case Copy: 4565 case Arithmetic: 4566 case Xchg: 4567 SubExprs.push_back(TheCall->getArg(2)); // Order 4568 SubExprs.push_back(TheCall->getArg(1)); // Val1 4569 break; 4570 case GNUXchg: 4571 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4572 SubExprs.push_back(TheCall->getArg(3)); // Order 4573 SubExprs.push_back(TheCall->getArg(1)); // Val1 4574 SubExprs.push_back(TheCall->getArg(2)); // Val2 4575 break; 4576 case C11CmpXchg: 4577 SubExprs.push_back(TheCall->getArg(3)); // Order 4578 SubExprs.push_back(TheCall->getArg(1)); // Val1 4579 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4580 SubExprs.push_back(TheCall->getArg(2)); // Val2 4581 break; 4582 case GNUCmpXchg: 4583 SubExprs.push_back(TheCall->getArg(4)); // Order 4584 SubExprs.push_back(TheCall->getArg(1)); // Val1 4585 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4586 SubExprs.push_back(TheCall->getArg(2)); // Val2 4587 SubExprs.push_back(TheCall->getArg(3)); // Weak 4588 break; 4589 } 4590 4591 if (SubExprs.size() >= 2 && Form != Init) { 4592 llvm::APSInt Result(32); 4593 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4594 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4595 Diag(SubExprs[1]->getBeginLoc(), 4596 diag::warn_atomic_op_has_invalid_memory_order) 4597 << SubExprs[1]->getSourceRange(); 4598 } 4599 4600 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4601 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4602 llvm::APSInt Result(32); 4603 if (Scope->isIntegerConstantExpr(Result, Context) && 4604 !ScopeModel->isValid(Result.getZExtValue())) { 4605 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4606 << Scope->getSourceRange(); 4607 } 4608 SubExprs.push_back(Scope); 4609 } 4610 4611 AtomicExpr *AE = 4612 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4613 ResultType, Op, TheCall->getRParenLoc()); 4614 4615 if ((Op == AtomicExpr::AO__c11_atomic_load || 4616 Op == AtomicExpr::AO__c11_atomic_store || 4617 Op == AtomicExpr::AO__opencl_atomic_load || 4618 Op == AtomicExpr::AO__opencl_atomic_store ) && 4619 Context.AtomicUsesUnsupportedLibcall(AE)) 4620 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4621 << ((Op == AtomicExpr::AO__c11_atomic_load || 4622 Op == AtomicExpr::AO__opencl_atomic_load) 4623 ? 0 4624 : 1); 4625 4626 return AE; 4627 } 4628 4629 /// checkBuiltinArgument - Given a call to a builtin function, perform 4630 /// normal type-checking on the given argument, updating the call in 4631 /// place. This is useful when a builtin function requires custom 4632 /// type-checking for some of its arguments but not necessarily all of 4633 /// them. 4634 /// 4635 /// Returns true on error. 4636 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4637 FunctionDecl *Fn = E->getDirectCallee(); 4638 assert(Fn && "builtin call without direct callee!"); 4639 4640 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4641 InitializedEntity Entity = 4642 InitializedEntity::InitializeParameter(S.Context, Param); 4643 4644 ExprResult Arg = E->getArg(0); 4645 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4646 if (Arg.isInvalid()) 4647 return true; 4648 4649 E->setArg(ArgIndex, Arg.get()); 4650 return false; 4651 } 4652 4653 /// We have a call to a function like __sync_fetch_and_add, which is an 4654 /// overloaded function based on the pointer type of its first argument. 4655 /// The main ActOnCallExpr routines have already promoted the types of 4656 /// arguments because all of these calls are prototyped as void(...). 4657 /// 4658 /// This function goes through and does final semantic checking for these 4659 /// builtins, as well as generating any warnings. 4660 ExprResult 4661 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4662 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4663 Expr *Callee = TheCall->getCallee(); 4664 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4665 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4666 4667 // Ensure that we have at least one argument to do type inference from. 4668 if (TheCall->getNumArgs() < 1) { 4669 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4670 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4671 return ExprError(); 4672 } 4673 4674 // Inspect the first argument of the atomic builtin. This should always be 4675 // a pointer type, whose element is an integral scalar or pointer type. 4676 // Because it is a pointer type, we don't have to worry about any implicit 4677 // casts here. 4678 // FIXME: We don't allow floating point scalars as input. 4679 Expr *FirstArg = TheCall->getArg(0); 4680 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4681 if (FirstArgResult.isInvalid()) 4682 return ExprError(); 4683 FirstArg = FirstArgResult.get(); 4684 TheCall->setArg(0, FirstArg); 4685 4686 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4687 if (!pointerType) { 4688 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4689 << FirstArg->getType() << FirstArg->getSourceRange(); 4690 return ExprError(); 4691 } 4692 4693 QualType ValType = pointerType->getPointeeType(); 4694 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4695 !ValType->isBlockPointerType()) { 4696 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4697 << FirstArg->getType() << FirstArg->getSourceRange(); 4698 return ExprError(); 4699 } 4700 4701 if (ValType.isConstQualified()) { 4702 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4703 << FirstArg->getType() << FirstArg->getSourceRange(); 4704 return ExprError(); 4705 } 4706 4707 switch (ValType.getObjCLifetime()) { 4708 case Qualifiers::OCL_None: 4709 case Qualifiers::OCL_ExplicitNone: 4710 // okay 4711 break; 4712 4713 case Qualifiers::OCL_Weak: 4714 case Qualifiers::OCL_Strong: 4715 case Qualifiers::OCL_Autoreleasing: 4716 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4717 << ValType << FirstArg->getSourceRange(); 4718 return ExprError(); 4719 } 4720 4721 // Strip any qualifiers off ValType. 4722 ValType = ValType.getUnqualifiedType(); 4723 4724 // The majority of builtins return a value, but a few have special return 4725 // types, so allow them to override appropriately below. 4726 QualType ResultType = ValType; 4727 4728 // We need to figure out which concrete builtin this maps onto. For example, 4729 // __sync_fetch_and_add with a 2 byte object turns into 4730 // __sync_fetch_and_add_2. 4731 #define BUILTIN_ROW(x) \ 4732 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4733 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4734 4735 static const unsigned BuiltinIndices[][5] = { 4736 BUILTIN_ROW(__sync_fetch_and_add), 4737 BUILTIN_ROW(__sync_fetch_and_sub), 4738 BUILTIN_ROW(__sync_fetch_and_or), 4739 BUILTIN_ROW(__sync_fetch_and_and), 4740 BUILTIN_ROW(__sync_fetch_and_xor), 4741 BUILTIN_ROW(__sync_fetch_and_nand), 4742 4743 BUILTIN_ROW(__sync_add_and_fetch), 4744 BUILTIN_ROW(__sync_sub_and_fetch), 4745 BUILTIN_ROW(__sync_and_and_fetch), 4746 BUILTIN_ROW(__sync_or_and_fetch), 4747 BUILTIN_ROW(__sync_xor_and_fetch), 4748 BUILTIN_ROW(__sync_nand_and_fetch), 4749 4750 BUILTIN_ROW(__sync_val_compare_and_swap), 4751 BUILTIN_ROW(__sync_bool_compare_and_swap), 4752 BUILTIN_ROW(__sync_lock_test_and_set), 4753 BUILTIN_ROW(__sync_lock_release), 4754 BUILTIN_ROW(__sync_swap) 4755 }; 4756 #undef BUILTIN_ROW 4757 4758 // Determine the index of the size. 4759 unsigned SizeIndex; 4760 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4761 case 1: SizeIndex = 0; break; 4762 case 2: SizeIndex = 1; break; 4763 case 4: SizeIndex = 2; break; 4764 case 8: SizeIndex = 3; break; 4765 case 16: SizeIndex = 4; break; 4766 default: 4767 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4768 << FirstArg->getType() << FirstArg->getSourceRange(); 4769 return ExprError(); 4770 } 4771 4772 // Each of these builtins has one pointer argument, followed by some number of 4773 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4774 // that we ignore. Find out which row of BuiltinIndices to read from as well 4775 // as the number of fixed args. 4776 unsigned BuiltinID = FDecl->getBuiltinID(); 4777 unsigned BuiltinIndex, NumFixed = 1; 4778 bool WarnAboutSemanticsChange = false; 4779 switch (BuiltinID) { 4780 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4781 case Builtin::BI__sync_fetch_and_add: 4782 case Builtin::BI__sync_fetch_and_add_1: 4783 case Builtin::BI__sync_fetch_and_add_2: 4784 case Builtin::BI__sync_fetch_and_add_4: 4785 case Builtin::BI__sync_fetch_and_add_8: 4786 case Builtin::BI__sync_fetch_and_add_16: 4787 BuiltinIndex = 0; 4788 break; 4789 4790 case Builtin::BI__sync_fetch_and_sub: 4791 case Builtin::BI__sync_fetch_and_sub_1: 4792 case Builtin::BI__sync_fetch_and_sub_2: 4793 case Builtin::BI__sync_fetch_and_sub_4: 4794 case Builtin::BI__sync_fetch_and_sub_8: 4795 case Builtin::BI__sync_fetch_and_sub_16: 4796 BuiltinIndex = 1; 4797 break; 4798 4799 case Builtin::BI__sync_fetch_and_or: 4800 case Builtin::BI__sync_fetch_and_or_1: 4801 case Builtin::BI__sync_fetch_and_or_2: 4802 case Builtin::BI__sync_fetch_and_or_4: 4803 case Builtin::BI__sync_fetch_and_or_8: 4804 case Builtin::BI__sync_fetch_and_or_16: 4805 BuiltinIndex = 2; 4806 break; 4807 4808 case Builtin::BI__sync_fetch_and_and: 4809 case Builtin::BI__sync_fetch_and_and_1: 4810 case Builtin::BI__sync_fetch_and_and_2: 4811 case Builtin::BI__sync_fetch_and_and_4: 4812 case Builtin::BI__sync_fetch_and_and_8: 4813 case Builtin::BI__sync_fetch_and_and_16: 4814 BuiltinIndex = 3; 4815 break; 4816 4817 case Builtin::BI__sync_fetch_and_xor: 4818 case Builtin::BI__sync_fetch_and_xor_1: 4819 case Builtin::BI__sync_fetch_and_xor_2: 4820 case Builtin::BI__sync_fetch_and_xor_4: 4821 case Builtin::BI__sync_fetch_and_xor_8: 4822 case Builtin::BI__sync_fetch_and_xor_16: 4823 BuiltinIndex = 4; 4824 break; 4825 4826 case Builtin::BI__sync_fetch_and_nand: 4827 case Builtin::BI__sync_fetch_and_nand_1: 4828 case Builtin::BI__sync_fetch_and_nand_2: 4829 case Builtin::BI__sync_fetch_and_nand_4: 4830 case Builtin::BI__sync_fetch_and_nand_8: 4831 case Builtin::BI__sync_fetch_and_nand_16: 4832 BuiltinIndex = 5; 4833 WarnAboutSemanticsChange = true; 4834 break; 4835 4836 case Builtin::BI__sync_add_and_fetch: 4837 case Builtin::BI__sync_add_and_fetch_1: 4838 case Builtin::BI__sync_add_and_fetch_2: 4839 case Builtin::BI__sync_add_and_fetch_4: 4840 case Builtin::BI__sync_add_and_fetch_8: 4841 case Builtin::BI__sync_add_and_fetch_16: 4842 BuiltinIndex = 6; 4843 break; 4844 4845 case Builtin::BI__sync_sub_and_fetch: 4846 case Builtin::BI__sync_sub_and_fetch_1: 4847 case Builtin::BI__sync_sub_and_fetch_2: 4848 case Builtin::BI__sync_sub_and_fetch_4: 4849 case Builtin::BI__sync_sub_and_fetch_8: 4850 case Builtin::BI__sync_sub_and_fetch_16: 4851 BuiltinIndex = 7; 4852 break; 4853 4854 case Builtin::BI__sync_and_and_fetch: 4855 case Builtin::BI__sync_and_and_fetch_1: 4856 case Builtin::BI__sync_and_and_fetch_2: 4857 case Builtin::BI__sync_and_and_fetch_4: 4858 case Builtin::BI__sync_and_and_fetch_8: 4859 case Builtin::BI__sync_and_and_fetch_16: 4860 BuiltinIndex = 8; 4861 break; 4862 4863 case Builtin::BI__sync_or_and_fetch: 4864 case Builtin::BI__sync_or_and_fetch_1: 4865 case Builtin::BI__sync_or_and_fetch_2: 4866 case Builtin::BI__sync_or_and_fetch_4: 4867 case Builtin::BI__sync_or_and_fetch_8: 4868 case Builtin::BI__sync_or_and_fetch_16: 4869 BuiltinIndex = 9; 4870 break; 4871 4872 case Builtin::BI__sync_xor_and_fetch: 4873 case Builtin::BI__sync_xor_and_fetch_1: 4874 case Builtin::BI__sync_xor_and_fetch_2: 4875 case Builtin::BI__sync_xor_and_fetch_4: 4876 case Builtin::BI__sync_xor_and_fetch_8: 4877 case Builtin::BI__sync_xor_and_fetch_16: 4878 BuiltinIndex = 10; 4879 break; 4880 4881 case Builtin::BI__sync_nand_and_fetch: 4882 case Builtin::BI__sync_nand_and_fetch_1: 4883 case Builtin::BI__sync_nand_and_fetch_2: 4884 case Builtin::BI__sync_nand_and_fetch_4: 4885 case Builtin::BI__sync_nand_and_fetch_8: 4886 case Builtin::BI__sync_nand_and_fetch_16: 4887 BuiltinIndex = 11; 4888 WarnAboutSemanticsChange = true; 4889 break; 4890 4891 case Builtin::BI__sync_val_compare_and_swap: 4892 case Builtin::BI__sync_val_compare_and_swap_1: 4893 case Builtin::BI__sync_val_compare_and_swap_2: 4894 case Builtin::BI__sync_val_compare_and_swap_4: 4895 case Builtin::BI__sync_val_compare_and_swap_8: 4896 case Builtin::BI__sync_val_compare_and_swap_16: 4897 BuiltinIndex = 12; 4898 NumFixed = 2; 4899 break; 4900 4901 case Builtin::BI__sync_bool_compare_and_swap: 4902 case Builtin::BI__sync_bool_compare_and_swap_1: 4903 case Builtin::BI__sync_bool_compare_and_swap_2: 4904 case Builtin::BI__sync_bool_compare_and_swap_4: 4905 case Builtin::BI__sync_bool_compare_and_swap_8: 4906 case Builtin::BI__sync_bool_compare_and_swap_16: 4907 BuiltinIndex = 13; 4908 NumFixed = 2; 4909 ResultType = Context.BoolTy; 4910 break; 4911 4912 case Builtin::BI__sync_lock_test_and_set: 4913 case Builtin::BI__sync_lock_test_and_set_1: 4914 case Builtin::BI__sync_lock_test_and_set_2: 4915 case Builtin::BI__sync_lock_test_and_set_4: 4916 case Builtin::BI__sync_lock_test_and_set_8: 4917 case Builtin::BI__sync_lock_test_and_set_16: 4918 BuiltinIndex = 14; 4919 break; 4920 4921 case Builtin::BI__sync_lock_release: 4922 case Builtin::BI__sync_lock_release_1: 4923 case Builtin::BI__sync_lock_release_2: 4924 case Builtin::BI__sync_lock_release_4: 4925 case Builtin::BI__sync_lock_release_8: 4926 case Builtin::BI__sync_lock_release_16: 4927 BuiltinIndex = 15; 4928 NumFixed = 0; 4929 ResultType = Context.VoidTy; 4930 break; 4931 4932 case Builtin::BI__sync_swap: 4933 case Builtin::BI__sync_swap_1: 4934 case Builtin::BI__sync_swap_2: 4935 case Builtin::BI__sync_swap_4: 4936 case Builtin::BI__sync_swap_8: 4937 case Builtin::BI__sync_swap_16: 4938 BuiltinIndex = 16; 4939 break; 4940 } 4941 4942 // Now that we know how many fixed arguments we expect, first check that we 4943 // have at least that many. 4944 if (TheCall->getNumArgs() < 1+NumFixed) { 4945 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4946 << 0 << 1 + NumFixed << TheCall->getNumArgs() 4947 << Callee->getSourceRange(); 4948 return ExprError(); 4949 } 4950 4951 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 4952 << Callee->getSourceRange(); 4953 4954 if (WarnAboutSemanticsChange) { 4955 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 4956 << Callee->getSourceRange(); 4957 } 4958 4959 // Get the decl for the concrete builtin from this, we can tell what the 4960 // concrete integer type we should convert to is. 4961 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4962 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4963 FunctionDecl *NewBuiltinDecl; 4964 if (NewBuiltinID == BuiltinID) 4965 NewBuiltinDecl = FDecl; 4966 else { 4967 // Perform builtin lookup to avoid redeclaring it. 4968 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4969 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 4970 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 4971 assert(Res.getFoundDecl()); 4972 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 4973 if (!NewBuiltinDecl) 4974 return ExprError(); 4975 } 4976 4977 // The first argument --- the pointer --- has a fixed type; we 4978 // deduce the types of the rest of the arguments accordingly. Walk 4979 // the remaining arguments, converting them to the deduced value type. 4980 for (unsigned i = 0; i != NumFixed; ++i) { 4981 ExprResult Arg = TheCall->getArg(i+1); 4982 4983 // GCC does an implicit conversion to the pointer or integer ValType. This 4984 // can fail in some cases (1i -> int**), check for this error case now. 4985 // Initialize the argument. 4986 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4987 ValType, /*consume*/ false); 4988 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4989 if (Arg.isInvalid()) 4990 return ExprError(); 4991 4992 // Okay, we have something that *can* be converted to the right type. Check 4993 // to see if there is a potentially weird extension going on here. This can 4994 // happen when you do an atomic operation on something like an char* and 4995 // pass in 42. The 42 gets converted to char. This is even more strange 4996 // for things like 45.123 -> char, etc. 4997 // FIXME: Do this check. 4998 TheCall->setArg(i+1, Arg.get()); 4999 } 5000 5001 ASTContext& Context = this->getASTContext(); 5002 5003 // Create a new DeclRefExpr to refer to the new decl. 5004 DeclRefExpr* NewDRE = DeclRefExpr::Create( 5005 Context, 5006 DRE->getQualifierLoc(), 5007 SourceLocation(), 5008 NewBuiltinDecl, 5009 /*enclosing*/ false, 5010 DRE->getLocation(), 5011 Context.BuiltinFnTy, 5012 DRE->getValueKind()); 5013 5014 // Set the callee in the CallExpr. 5015 // FIXME: This loses syntactic information. 5016 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5017 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5018 CK_BuiltinFnToFnPtr); 5019 TheCall->setCallee(PromotedCall.get()); 5020 5021 // Change the result type of the call to match the original value type. This 5022 // is arbitrary, but the codegen for these builtins ins design to handle it 5023 // gracefully. 5024 TheCall->setType(ResultType); 5025 5026 return TheCallResult; 5027 } 5028 5029 /// SemaBuiltinNontemporalOverloaded - We have a call to 5030 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5031 /// overloaded function based on the pointer type of its last argument. 5032 /// 5033 /// This function goes through and does final semantic checking for these 5034 /// builtins. 5035 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5036 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5037 DeclRefExpr *DRE = 5038 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5039 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5040 unsigned BuiltinID = FDecl->getBuiltinID(); 5041 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5042 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5043 "Unexpected nontemporal load/store builtin!"); 5044 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5045 unsigned numArgs = isStore ? 2 : 1; 5046 5047 // Ensure that we have the proper number of arguments. 5048 if (checkArgCount(*this, TheCall, numArgs)) 5049 return ExprError(); 5050 5051 // Inspect the last argument of the nontemporal builtin. This should always 5052 // be a pointer type, from which we imply the type of the memory access. 5053 // Because it is a pointer type, we don't have to worry about any implicit 5054 // casts here. 5055 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5056 ExprResult PointerArgResult = 5057 DefaultFunctionArrayLvalueConversion(PointerArg); 5058 5059 if (PointerArgResult.isInvalid()) 5060 return ExprError(); 5061 PointerArg = PointerArgResult.get(); 5062 TheCall->setArg(numArgs - 1, PointerArg); 5063 5064 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5065 if (!pointerType) { 5066 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5067 << PointerArg->getType() << PointerArg->getSourceRange(); 5068 return ExprError(); 5069 } 5070 5071 QualType ValType = pointerType->getPointeeType(); 5072 5073 // Strip any qualifiers off ValType. 5074 ValType = ValType.getUnqualifiedType(); 5075 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5076 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5077 !ValType->isVectorType()) { 5078 Diag(DRE->getBeginLoc(), 5079 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5080 << PointerArg->getType() << PointerArg->getSourceRange(); 5081 return ExprError(); 5082 } 5083 5084 if (!isStore) { 5085 TheCall->setType(ValType); 5086 return TheCallResult; 5087 } 5088 5089 ExprResult ValArg = TheCall->getArg(0); 5090 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5091 Context, ValType, /*consume*/ false); 5092 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5093 if (ValArg.isInvalid()) 5094 return ExprError(); 5095 5096 TheCall->setArg(0, ValArg.get()); 5097 TheCall->setType(Context.VoidTy); 5098 return TheCallResult; 5099 } 5100 5101 /// CheckObjCString - Checks that the argument to the builtin 5102 /// CFString constructor is correct 5103 /// Note: It might also make sense to do the UTF-16 conversion here (would 5104 /// simplify the backend). 5105 bool Sema::CheckObjCString(Expr *Arg) { 5106 Arg = Arg->IgnoreParenCasts(); 5107 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5108 5109 if (!Literal || !Literal->isAscii()) { 5110 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5111 << Arg->getSourceRange(); 5112 return true; 5113 } 5114 5115 if (Literal->containsNonAsciiOrNull()) { 5116 StringRef String = Literal->getString(); 5117 unsigned NumBytes = String.size(); 5118 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5119 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5120 llvm::UTF16 *ToPtr = &ToBuf[0]; 5121 5122 llvm::ConversionResult Result = 5123 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5124 ToPtr + NumBytes, llvm::strictConversion); 5125 // Check for conversion failure. 5126 if (Result != llvm::conversionOK) 5127 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5128 << Arg->getSourceRange(); 5129 } 5130 return false; 5131 } 5132 5133 /// CheckObjCString - Checks that the format string argument to the os_log() 5134 /// and os_trace() functions is correct, and converts it to const char *. 5135 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5136 Arg = Arg->IgnoreParenCasts(); 5137 auto *Literal = dyn_cast<StringLiteral>(Arg); 5138 if (!Literal) { 5139 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5140 Literal = ObjcLiteral->getString(); 5141 } 5142 } 5143 5144 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5145 return ExprError( 5146 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5147 << Arg->getSourceRange()); 5148 } 5149 5150 ExprResult Result(Literal); 5151 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5152 InitializedEntity Entity = 5153 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5154 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5155 return Result; 5156 } 5157 5158 /// Check that the user is calling the appropriate va_start builtin for the 5159 /// target and calling convention. 5160 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5161 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5162 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5163 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5164 bool IsWindows = TT.isOSWindows(); 5165 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5166 if (IsX64 || IsAArch64) { 5167 CallingConv CC = CC_C; 5168 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5169 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5170 if (IsMSVAStart) { 5171 // Don't allow this in System V ABI functions. 5172 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5173 return S.Diag(Fn->getBeginLoc(), 5174 diag::err_ms_va_start_used_in_sysv_function); 5175 } else { 5176 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5177 // On x64 Windows, don't allow this in System V ABI functions. 5178 // (Yes, that means there's no corresponding way to support variadic 5179 // System V ABI functions on Windows.) 5180 if ((IsWindows && CC == CC_X86_64SysV) || 5181 (!IsWindows && CC == CC_Win64)) 5182 return S.Diag(Fn->getBeginLoc(), 5183 diag::err_va_start_used_in_wrong_abi_function) 5184 << !IsWindows; 5185 } 5186 return false; 5187 } 5188 5189 if (IsMSVAStart) 5190 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5191 return false; 5192 } 5193 5194 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5195 ParmVarDecl **LastParam = nullptr) { 5196 // Determine whether the current function, block, or obj-c method is variadic 5197 // and get its parameter list. 5198 bool IsVariadic = false; 5199 ArrayRef<ParmVarDecl *> Params; 5200 DeclContext *Caller = S.CurContext; 5201 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5202 IsVariadic = Block->isVariadic(); 5203 Params = Block->parameters(); 5204 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5205 IsVariadic = FD->isVariadic(); 5206 Params = FD->parameters(); 5207 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5208 IsVariadic = MD->isVariadic(); 5209 // FIXME: This isn't correct for methods (results in bogus warning). 5210 Params = MD->parameters(); 5211 } else if (isa<CapturedDecl>(Caller)) { 5212 // We don't support va_start in a CapturedDecl. 5213 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5214 return true; 5215 } else { 5216 // This must be some other declcontext that parses exprs. 5217 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5218 return true; 5219 } 5220 5221 if (!IsVariadic) { 5222 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5223 return true; 5224 } 5225 5226 if (LastParam) 5227 *LastParam = Params.empty() ? nullptr : Params.back(); 5228 5229 return false; 5230 } 5231 5232 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5233 /// for validity. Emit an error and return true on failure; return false 5234 /// on success. 5235 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5236 Expr *Fn = TheCall->getCallee(); 5237 5238 if (checkVAStartABI(*this, BuiltinID, Fn)) 5239 return true; 5240 5241 if (TheCall->getNumArgs() > 2) { 5242 Diag(TheCall->getArg(2)->getBeginLoc(), 5243 diag::err_typecheck_call_too_many_args) 5244 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5245 << Fn->getSourceRange() 5246 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5247 (*(TheCall->arg_end() - 1))->getEndLoc()); 5248 return true; 5249 } 5250 5251 if (TheCall->getNumArgs() < 2) { 5252 return Diag(TheCall->getEndLoc(), 5253 diag::err_typecheck_call_too_few_args_at_least) 5254 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5255 } 5256 5257 // Type-check the first argument normally. 5258 if (checkBuiltinArgument(*this, TheCall, 0)) 5259 return true; 5260 5261 // Check that the current function is variadic, and get its last parameter. 5262 ParmVarDecl *LastParam; 5263 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5264 return true; 5265 5266 // Verify that the second argument to the builtin is the last argument of the 5267 // current function or method. 5268 bool SecondArgIsLastNamedArgument = false; 5269 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5270 5271 // These are valid if SecondArgIsLastNamedArgument is false after the next 5272 // block. 5273 QualType Type; 5274 SourceLocation ParamLoc; 5275 bool IsCRegister = false; 5276 5277 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5278 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5279 SecondArgIsLastNamedArgument = PV == LastParam; 5280 5281 Type = PV->getType(); 5282 ParamLoc = PV->getLocation(); 5283 IsCRegister = 5284 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5285 } 5286 } 5287 5288 if (!SecondArgIsLastNamedArgument) 5289 Diag(TheCall->getArg(1)->getBeginLoc(), 5290 diag::warn_second_arg_of_va_start_not_last_named_param); 5291 else if (IsCRegister || Type->isReferenceType() || 5292 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5293 // Promotable integers are UB, but enumerations need a bit of 5294 // extra checking to see what their promotable type actually is. 5295 if (!Type->isPromotableIntegerType()) 5296 return false; 5297 if (!Type->isEnumeralType()) 5298 return true; 5299 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5300 return !(ED && 5301 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5302 }()) { 5303 unsigned Reason = 0; 5304 if (Type->isReferenceType()) Reason = 1; 5305 else if (IsCRegister) Reason = 2; 5306 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5307 Diag(ParamLoc, diag::note_parameter_type) << Type; 5308 } 5309 5310 TheCall->setType(Context.VoidTy); 5311 return false; 5312 } 5313 5314 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5315 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5316 // const char *named_addr); 5317 5318 Expr *Func = Call->getCallee(); 5319 5320 if (Call->getNumArgs() < 3) 5321 return Diag(Call->getEndLoc(), 5322 diag::err_typecheck_call_too_few_args_at_least) 5323 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5324 5325 // Type-check the first argument normally. 5326 if (checkBuiltinArgument(*this, Call, 0)) 5327 return true; 5328 5329 // Check that the current function is variadic. 5330 if (checkVAStartIsInVariadicFunction(*this, Func)) 5331 return true; 5332 5333 // __va_start on Windows does not validate the parameter qualifiers 5334 5335 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5336 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5337 5338 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5339 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5340 5341 const QualType &ConstCharPtrTy = 5342 Context.getPointerType(Context.CharTy.withConst()); 5343 if (!Arg1Ty->isPointerType() || 5344 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5345 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5346 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5347 << 0 /* qualifier difference */ 5348 << 3 /* parameter mismatch */ 5349 << 2 << Arg1->getType() << ConstCharPtrTy; 5350 5351 const QualType SizeTy = Context.getSizeType(); 5352 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5353 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5354 << Arg2->getType() << SizeTy << 1 /* different class */ 5355 << 0 /* qualifier difference */ 5356 << 3 /* parameter mismatch */ 5357 << 3 << Arg2->getType() << SizeTy; 5358 5359 return false; 5360 } 5361 5362 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5363 /// friends. This is declared to take (...), so we have to check everything. 5364 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5365 if (TheCall->getNumArgs() < 2) 5366 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5367 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5368 if (TheCall->getNumArgs() > 2) 5369 return Diag(TheCall->getArg(2)->getBeginLoc(), 5370 diag::err_typecheck_call_too_many_args) 5371 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5372 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5373 (*(TheCall->arg_end() - 1))->getEndLoc()); 5374 5375 ExprResult OrigArg0 = TheCall->getArg(0); 5376 ExprResult OrigArg1 = TheCall->getArg(1); 5377 5378 // Do standard promotions between the two arguments, returning their common 5379 // type. 5380 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5381 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5382 return true; 5383 5384 // Make sure any conversions are pushed back into the call; this is 5385 // type safe since unordered compare builtins are declared as "_Bool 5386 // foo(...)". 5387 TheCall->setArg(0, OrigArg0.get()); 5388 TheCall->setArg(1, OrigArg1.get()); 5389 5390 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5391 return false; 5392 5393 // If the common type isn't a real floating type, then the arguments were 5394 // invalid for this operation. 5395 if (Res.isNull() || !Res->isRealFloatingType()) 5396 return Diag(OrigArg0.get()->getBeginLoc(), 5397 diag::err_typecheck_call_invalid_ordered_compare) 5398 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5399 << SourceRange(OrigArg0.get()->getBeginLoc(), 5400 OrigArg1.get()->getEndLoc()); 5401 5402 return false; 5403 } 5404 5405 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5406 /// __builtin_isnan and friends. This is declared to take (...), so we have 5407 /// to check everything. We expect the last argument to be a floating point 5408 /// value. 5409 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5410 if (TheCall->getNumArgs() < NumArgs) 5411 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5412 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5413 if (TheCall->getNumArgs() > NumArgs) 5414 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5415 diag::err_typecheck_call_too_many_args) 5416 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5417 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5418 (*(TheCall->arg_end() - 1))->getEndLoc()); 5419 5420 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5421 5422 if (OrigArg->isTypeDependent()) 5423 return false; 5424 5425 // This operation requires a non-_Complex floating-point number. 5426 if (!OrigArg->getType()->isRealFloatingType()) 5427 return Diag(OrigArg->getBeginLoc(), 5428 diag::err_typecheck_call_invalid_unary_fp) 5429 << OrigArg->getType() << OrigArg->getSourceRange(); 5430 5431 // If this is an implicit conversion from float -> float, double, or 5432 // long double, remove it. 5433 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5434 // Only remove standard FloatCasts, leaving other casts inplace 5435 if (Cast->getCastKind() == CK_FloatingCast) { 5436 Expr *CastArg = Cast->getSubExpr(); 5437 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5438 assert( 5439 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5440 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5441 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5442 "promotion from float to either float, double, or long double is " 5443 "the only expected cast here"); 5444 Cast->setSubExpr(nullptr); 5445 TheCall->setArg(NumArgs-1, CastArg); 5446 } 5447 } 5448 } 5449 5450 return false; 5451 } 5452 5453 // Customized Sema Checking for VSX builtins that have the following signature: 5454 // vector [...] builtinName(vector [...], vector [...], const int); 5455 // Which takes the same type of vectors (any legal vector type) for the first 5456 // two arguments and takes compile time constant for the third argument. 5457 // Example builtins are : 5458 // vector double vec_xxpermdi(vector double, vector double, int); 5459 // vector short vec_xxsldwi(vector short, vector short, int); 5460 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5461 unsigned ExpectedNumArgs = 3; 5462 if (TheCall->getNumArgs() < ExpectedNumArgs) 5463 return Diag(TheCall->getEndLoc(), 5464 diag::err_typecheck_call_too_few_args_at_least) 5465 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5466 << TheCall->getSourceRange(); 5467 5468 if (TheCall->getNumArgs() > ExpectedNumArgs) 5469 return Diag(TheCall->getEndLoc(), 5470 diag::err_typecheck_call_too_many_args_at_most) 5471 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5472 << TheCall->getSourceRange(); 5473 5474 // Check the third argument is a compile time constant 5475 llvm::APSInt Value; 5476 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5477 return Diag(TheCall->getBeginLoc(), 5478 diag::err_vsx_builtin_nonconstant_argument) 5479 << 3 /* argument index */ << TheCall->getDirectCallee() 5480 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5481 TheCall->getArg(2)->getEndLoc()); 5482 5483 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5484 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5485 5486 // Check the type of argument 1 and argument 2 are vectors. 5487 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5488 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5489 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5490 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5491 << TheCall->getDirectCallee() 5492 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5493 TheCall->getArg(1)->getEndLoc()); 5494 } 5495 5496 // Check the first two arguments are the same type. 5497 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5498 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5499 << TheCall->getDirectCallee() 5500 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5501 TheCall->getArg(1)->getEndLoc()); 5502 } 5503 5504 // When default clang type checking is turned off and the customized type 5505 // checking is used, the returning type of the function must be explicitly 5506 // set. Otherwise it is _Bool by default. 5507 TheCall->setType(Arg1Ty); 5508 5509 return false; 5510 } 5511 5512 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5513 // This is declared to take (...), so we have to check everything. 5514 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5515 if (TheCall->getNumArgs() < 2) 5516 return ExprError(Diag(TheCall->getEndLoc(), 5517 diag::err_typecheck_call_too_few_args_at_least) 5518 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5519 << TheCall->getSourceRange()); 5520 5521 // Determine which of the following types of shufflevector we're checking: 5522 // 1) unary, vector mask: (lhs, mask) 5523 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5524 QualType resType = TheCall->getArg(0)->getType(); 5525 unsigned numElements = 0; 5526 5527 if (!TheCall->getArg(0)->isTypeDependent() && 5528 !TheCall->getArg(1)->isTypeDependent()) { 5529 QualType LHSType = TheCall->getArg(0)->getType(); 5530 QualType RHSType = TheCall->getArg(1)->getType(); 5531 5532 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5533 return ExprError( 5534 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5535 << TheCall->getDirectCallee() 5536 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5537 TheCall->getArg(1)->getEndLoc())); 5538 5539 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5540 unsigned numResElements = TheCall->getNumArgs() - 2; 5541 5542 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5543 // with mask. If so, verify that RHS is an integer vector type with the 5544 // same number of elts as lhs. 5545 if (TheCall->getNumArgs() == 2) { 5546 if (!RHSType->hasIntegerRepresentation() || 5547 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5548 return ExprError(Diag(TheCall->getBeginLoc(), 5549 diag::err_vec_builtin_incompatible_vector) 5550 << TheCall->getDirectCallee() 5551 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5552 TheCall->getArg(1)->getEndLoc())); 5553 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5554 return ExprError(Diag(TheCall->getBeginLoc(), 5555 diag::err_vec_builtin_incompatible_vector) 5556 << TheCall->getDirectCallee() 5557 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5558 TheCall->getArg(1)->getEndLoc())); 5559 } else if (numElements != numResElements) { 5560 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5561 resType = Context.getVectorType(eltType, numResElements, 5562 VectorType::GenericVector); 5563 } 5564 } 5565 5566 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5567 if (TheCall->getArg(i)->isTypeDependent() || 5568 TheCall->getArg(i)->isValueDependent()) 5569 continue; 5570 5571 llvm::APSInt Result(32); 5572 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5573 return ExprError(Diag(TheCall->getBeginLoc(), 5574 diag::err_shufflevector_nonconstant_argument) 5575 << TheCall->getArg(i)->getSourceRange()); 5576 5577 // Allow -1 which will be translated to undef in the IR. 5578 if (Result.isSigned() && Result.isAllOnesValue()) 5579 continue; 5580 5581 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5582 return ExprError(Diag(TheCall->getBeginLoc(), 5583 diag::err_shufflevector_argument_too_large) 5584 << TheCall->getArg(i)->getSourceRange()); 5585 } 5586 5587 SmallVector<Expr*, 32> exprs; 5588 5589 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5590 exprs.push_back(TheCall->getArg(i)); 5591 TheCall->setArg(i, nullptr); 5592 } 5593 5594 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5595 TheCall->getCallee()->getBeginLoc(), 5596 TheCall->getRParenLoc()); 5597 } 5598 5599 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5600 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5601 SourceLocation BuiltinLoc, 5602 SourceLocation RParenLoc) { 5603 ExprValueKind VK = VK_RValue; 5604 ExprObjectKind OK = OK_Ordinary; 5605 QualType DstTy = TInfo->getType(); 5606 QualType SrcTy = E->getType(); 5607 5608 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5609 return ExprError(Diag(BuiltinLoc, 5610 diag::err_convertvector_non_vector) 5611 << E->getSourceRange()); 5612 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5613 return ExprError(Diag(BuiltinLoc, 5614 diag::err_convertvector_non_vector_type)); 5615 5616 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5617 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5618 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5619 if (SrcElts != DstElts) 5620 return ExprError(Diag(BuiltinLoc, 5621 diag::err_convertvector_incompatible_vector) 5622 << E->getSourceRange()); 5623 } 5624 5625 return new (Context) 5626 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5627 } 5628 5629 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5630 // This is declared to take (const void*, ...) and can take two 5631 // optional constant int args. 5632 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5633 unsigned NumArgs = TheCall->getNumArgs(); 5634 5635 if (NumArgs > 3) 5636 return Diag(TheCall->getEndLoc(), 5637 diag::err_typecheck_call_too_many_args_at_most) 5638 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5639 5640 // Argument 0 is checked for us and the remaining arguments must be 5641 // constant integers. 5642 for (unsigned i = 1; i != NumArgs; ++i) 5643 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5644 return true; 5645 5646 return false; 5647 } 5648 5649 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5650 // __assume does not evaluate its arguments, and should warn if its argument 5651 // has side effects. 5652 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5653 Expr *Arg = TheCall->getArg(0); 5654 if (Arg->isInstantiationDependent()) return false; 5655 5656 if (Arg->HasSideEffects(Context)) 5657 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5658 << Arg->getSourceRange() 5659 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5660 5661 return false; 5662 } 5663 5664 /// Handle __builtin_alloca_with_align. This is declared 5665 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5666 /// than 8. 5667 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5668 // The alignment must be a constant integer. 5669 Expr *Arg = TheCall->getArg(1); 5670 5671 // We can't check the value of a dependent argument. 5672 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5673 if (const auto *UE = 5674 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5675 if (UE->getKind() == UETT_AlignOf) 5676 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5677 << Arg->getSourceRange(); 5678 5679 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5680 5681 if (!Result.isPowerOf2()) 5682 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5683 << Arg->getSourceRange(); 5684 5685 if (Result < Context.getCharWidth()) 5686 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5687 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5688 5689 if (Result > std::numeric_limits<int32_t>::max()) 5690 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5691 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5692 } 5693 5694 return false; 5695 } 5696 5697 /// Handle __builtin_assume_aligned. This is declared 5698 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5699 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5700 unsigned NumArgs = TheCall->getNumArgs(); 5701 5702 if (NumArgs > 3) 5703 return Diag(TheCall->getEndLoc(), 5704 diag::err_typecheck_call_too_many_args_at_most) 5705 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5706 5707 // The alignment must be a constant integer. 5708 Expr *Arg = TheCall->getArg(1); 5709 5710 // We can't check the value of a dependent argument. 5711 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5712 llvm::APSInt Result; 5713 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5714 return true; 5715 5716 if (!Result.isPowerOf2()) 5717 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5718 << Arg->getSourceRange(); 5719 } 5720 5721 if (NumArgs > 2) { 5722 ExprResult Arg(TheCall->getArg(2)); 5723 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5724 Context.getSizeType(), false); 5725 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5726 if (Arg.isInvalid()) return true; 5727 TheCall->setArg(2, Arg.get()); 5728 } 5729 5730 return false; 5731 } 5732 5733 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5734 unsigned BuiltinID = 5735 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5736 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5737 5738 unsigned NumArgs = TheCall->getNumArgs(); 5739 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5740 if (NumArgs < NumRequiredArgs) { 5741 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5742 << 0 /* function call */ << NumRequiredArgs << NumArgs 5743 << TheCall->getSourceRange(); 5744 } 5745 if (NumArgs >= NumRequiredArgs + 0x100) { 5746 return Diag(TheCall->getEndLoc(), 5747 diag::err_typecheck_call_too_many_args_at_most) 5748 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5749 << TheCall->getSourceRange(); 5750 } 5751 unsigned i = 0; 5752 5753 // For formatting call, check buffer arg. 5754 if (!IsSizeCall) { 5755 ExprResult Arg(TheCall->getArg(i)); 5756 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5757 Context, Context.VoidPtrTy, false); 5758 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5759 if (Arg.isInvalid()) 5760 return true; 5761 TheCall->setArg(i, Arg.get()); 5762 i++; 5763 } 5764 5765 // Check string literal arg. 5766 unsigned FormatIdx = i; 5767 { 5768 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5769 if (Arg.isInvalid()) 5770 return true; 5771 TheCall->setArg(i, Arg.get()); 5772 i++; 5773 } 5774 5775 // Make sure variadic args are scalar. 5776 unsigned FirstDataArg = i; 5777 while (i < NumArgs) { 5778 ExprResult Arg = DefaultVariadicArgumentPromotion( 5779 TheCall->getArg(i), VariadicFunction, nullptr); 5780 if (Arg.isInvalid()) 5781 return true; 5782 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5783 if (ArgSize.getQuantity() >= 0x100) { 5784 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5785 << i << (int)ArgSize.getQuantity() << 0xff 5786 << TheCall->getSourceRange(); 5787 } 5788 TheCall->setArg(i, Arg.get()); 5789 i++; 5790 } 5791 5792 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5793 // call to avoid duplicate diagnostics. 5794 if (!IsSizeCall) { 5795 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5796 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5797 bool Success = CheckFormatArguments( 5798 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5799 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5800 CheckedVarArgs); 5801 if (!Success) 5802 return true; 5803 } 5804 5805 if (IsSizeCall) { 5806 TheCall->setType(Context.getSizeType()); 5807 } else { 5808 TheCall->setType(Context.VoidPtrTy); 5809 } 5810 return false; 5811 } 5812 5813 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5814 /// TheCall is a constant expression. 5815 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5816 llvm::APSInt &Result) { 5817 Expr *Arg = TheCall->getArg(ArgNum); 5818 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5819 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5820 5821 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5822 5823 if (!Arg->isIntegerConstantExpr(Result, Context)) 5824 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5825 << FDecl->getDeclName() << Arg->getSourceRange(); 5826 5827 return false; 5828 } 5829 5830 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5831 /// TheCall is a constant expression in the range [Low, High]. 5832 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5833 int Low, int High, bool RangeIsError) { 5834 llvm::APSInt Result; 5835 5836 // We can't check the value of a dependent argument. 5837 Expr *Arg = TheCall->getArg(ArgNum); 5838 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5839 return false; 5840 5841 // Check constant-ness first. 5842 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5843 return true; 5844 5845 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5846 if (RangeIsError) 5847 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5848 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5849 else 5850 // Defer the warning until we know if the code will be emitted so that 5851 // dead code can ignore this. 5852 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5853 PDiag(diag::warn_argument_invalid_range) 5854 << Result.toString(10) << Low << High 5855 << Arg->getSourceRange()); 5856 } 5857 5858 return false; 5859 } 5860 5861 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5862 /// TheCall is a constant expression is a multiple of Num.. 5863 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5864 unsigned Num) { 5865 llvm::APSInt Result; 5866 5867 // We can't check the value of a dependent argument. 5868 Expr *Arg = TheCall->getArg(ArgNum); 5869 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5870 return false; 5871 5872 // Check constant-ness first. 5873 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5874 return true; 5875 5876 if (Result.getSExtValue() % Num != 0) 5877 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5878 << Num << Arg->getSourceRange(); 5879 5880 return false; 5881 } 5882 5883 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 5884 /// TheCall is an ARM/AArch64 special register string literal. 5885 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 5886 int ArgNum, unsigned ExpectedFieldNum, 5887 bool AllowName) { 5888 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 5889 BuiltinID == ARM::BI__builtin_arm_wsr64 || 5890 BuiltinID == ARM::BI__builtin_arm_rsr || 5891 BuiltinID == ARM::BI__builtin_arm_rsrp || 5892 BuiltinID == ARM::BI__builtin_arm_wsr || 5893 BuiltinID == ARM::BI__builtin_arm_wsrp; 5894 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 5895 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 5896 BuiltinID == AArch64::BI__builtin_arm_rsr || 5897 BuiltinID == AArch64::BI__builtin_arm_rsrp || 5898 BuiltinID == AArch64::BI__builtin_arm_wsr || 5899 BuiltinID == AArch64::BI__builtin_arm_wsrp; 5900 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 5901 5902 // We can't check the value of a dependent argument. 5903 Expr *Arg = TheCall->getArg(ArgNum); 5904 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5905 return false; 5906 5907 // Check if the argument is a string literal. 5908 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 5909 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 5910 << Arg->getSourceRange(); 5911 5912 // Check the type of special register given. 5913 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 5914 SmallVector<StringRef, 6> Fields; 5915 Reg.split(Fields, ":"); 5916 5917 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 5918 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 5919 << Arg->getSourceRange(); 5920 5921 // If the string is the name of a register then we cannot check that it is 5922 // valid here but if the string is of one the forms described in ACLE then we 5923 // can check that the supplied fields are integers and within the valid 5924 // ranges. 5925 if (Fields.size() > 1) { 5926 bool FiveFields = Fields.size() == 5; 5927 5928 bool ValidString = true; 5929 if (IsARMBuiltin) { 5930 ValidString &= Fields[0].startswith_lower("cp") || 5931 Fields[0].startswith_lower("p"); 5932 if (ValidString) 5933 Fields[0] = 5934 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 5935 5936 ValidString &= Fields[2].startswith_lower("c"); 5937 if (ValidString) 5938 Fields[2] = Fields[2].drop_front(1); 5939 5940 if (FiveFields) { 5941 ValidString &= Fields[3].startswith_lower("c"); 5942 if (ValidString) 5943 Fields[3] = Fields[3].drop_front(1); 5944 } 5945 } 5946 5947 SmallVector<int, 5> Ranges; 5948 if (FiveFields) 5949 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 5950 else 5951 Ranges.append({15, 7, 15}); 5952 5953 for (unsigned i=0; i<Fields.size(); ++i) { 5954 int IntField; 5955 ValidString &= !Fields[i].getAsInteger(10, IntField); 5956 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 5957 } 5958 5959 if (!ValidString) 5960 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 5961 << Arg->getSourceRange(); 5962 } else if (IsAArch64Builtin && Fields.size() == 1) { 5963 // If the register name is one of those that appear in the condition below 5964 // and the special register builtin being used is one of the write builtins, 5965 // then we require that the argument provided for writing to the register 5966 // is an integer constant expression. This is because it will be lowered to 5967 // an MSR (immediate) instruction, so we need to know the immediate at 5968 // compile time. 5969 if (TheCall->getNumArgs() != 2) 5970 return false; 5971 5972 std::string RegLower = Reg.lower(); 5973 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 5974 RegLower != "pan" && RegLower != "uao") 5975 return false; 5976 5977 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 5978 } 5979 5980 return false; 5981 } 5982 5983 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 5984 /// This checks that the target supports __builtin_longjmp and 5985 /// that val is a constant 1. 5986 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 5987 if (!Context.getTargetInfo().hasSjLjLowering()) 5988 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 5989 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 5990 5991 Expr *Arg = TheCall->getArg(1); 5992 llvm::APSInt Result; 5993 5994 // TODO: This is less than ideal. Overload this to take a value. 5995 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5996 return true; 5997 5998 if (Result != 1) 5999 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6000 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6001 6002 return false; 6003 } 6004 6005 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6006 /// This checks that the target supports __builtin_setjmp. 6007 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6008 if (!Context.getTargetInfo().hasSjLjLowering()) 6009 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6010 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6011 return false; 6012 } 6013 6014 namespace { 6015 6016 class UncoveredArgHandler { 6017 enum { Unknown = -1, AllCovered = -2 }; 6018 6019 signed FirstUncoveredArg = Unknown; 6020 SmallVector<const Expr *, 4> DiagnosticExprs; 6021 6022 public: 6023 UncoveredArgHandler() = default; 6024 6025 bool hasUncoveredArg() const { 6026 return (FirstUncoveredArg >= 0); 6027 } 6028 6029 unsigned getUncoveredArg() const { 6030 assert(hasUncoveredArg() && "no uncovered argument"); 6031 return FirstUncoveredArg; 6032 } 6033 6034 void setAllCovered() { 6035 // A string has been found with all arguments covered, so clear out 6036 // the diagnostics. 6037 DiagnosticExprs.clear(); 6038 FirstUncoveredArg = AllCovered; 6039 } 6040 6041 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6042 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6043 6044 // Don't update if a previous string covers all arguments. 6045 if (FirstUncoveredArg == AllCovered) 6046 return; 6047 6048 // UncoveredArgHandler tracks the highest uncovered argument index 6049 // and with it all the strings that match this index. 6050 if (NewFirstUncoveredArg == FirstUncoveredArg) 6051 DiagnosticExprs.push_back(StrExpr); 6052 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6053 DiagnosticExprs.clear(); 6054 DiagnosticExprs.push_back(StrExpr); 6055 FirstUncoveredArg = NewFirstUncoveredArg; 6056 } 6057 } 6058 6059 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6060 }; 6061 6062 enum StringLiteralCheckType { 6063 SLCT_NotALiteral, 6064 SLCT_UncheckedLiteral, 6065 SLCT_CheckedLiteral 6066 }; 6067 6068 } // namespace 6069 6070 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6071 BinaryOperatorKind BinOpKind, 6072 bool AddendIsRight) { 6073 unsigned BitWidth = Offset.getBitWidth(); 6074 unsigned AddendBitWidth = Addend.getBitWidth(); 6075 // There might be negative interim results. 6076 if (Addend.isUnsigned()) { 6077 Addend = Addend.zext(++AddendBitWidth); 6078 Addend.setIsSigned(true); 6079 } 6080 // Adjust the bit width of the APSInts. 6081 if (AddendBitWidth > BitWidth) { 6082 Offset = Offset.sext(AddendBitWidth); 6083 BitWidth = AddendBitWidth; 6084 } else if (BitWidth > AddendBitWidth) { 6085 Addend = Addend.sext(BitWidth); 6086 } 6087 6088 bool Ov = false; 6089 llvm::APSInt ResOffset = Offset; 6090 if (BinOpKind == BO_Add) 6091 ResOffset = Offset.sadd_ov(Addend, Ov); 6092 else { 6093 assert(AddendIsRight && BinOpKind == BO_Sub && 6094 "operator must be add or sub with addend on the right"); 6095 ResOffset = Offset.ssub_ov(Addend, Ov); 6096 } 6097 6098 // We add an offset to a pointer here so we should support an offset as big as 6099 // possible. 6100 if (Ov) { 6101 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6102 "index (intermediate) result too big"); 6103 Offset = Offset.sext(2 * BitWidth); 6104 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6105 return; 6106 } 6107 6108 Offset = ResOffset; 6109 } 6110 6111 namespace { 6112 6113 // This is a wrapper class around StringLiteral to support offsetted string 6114 // literals as format strings. It takes the offset into account when returning 6115 // the string and its length or the source locations to display notes correctly. 6116 class FormatStringLiteral { 6117 const StringLiteral *FExpr; 6118 int64_t Offset; 6119 6120 public: 6121 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6122 : FExpr(fexpr), Offset(Offset) {} 6123 6124 StringRef getString() const { 6125 return FExpr->getString().drop_front(Offset); 6126 } 6127 6128 unsigned getByteLength() const { 6129 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6130 } 6131 6132 unsigned getLength() const { return FExpr->getLength() - Offset; } 6133 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6134 6135 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6136 6137 QualType getType() const { return FExpr->getType(); } 6138 6139 bool isAscii() const { return FExpr->isAscii(); } 6140 bool isWide() const { return FExpr->isWide(); } 6141 bool isUTF8() const { return FExpr->isUTF8(); } 6142 bool isUTF16() const { return FExpr->isUTF16(); } 6143 bool isUTF32() const { return FExpr->isUTF32(); } 6144 bool isPascal() const { return FExpr->isPascal(); } 6145 6146 SourceLocation getLocationOfByte( 6147 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6148 const TargetInfo &Target, unsigned *StartToken = nullptr, 6149 unsigned *StartTokenByteOffset = nullptr) const { 6150 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6151 StartToken, StartTokenByteOffset); 6152 } 6153 6154 SourceLocation getBeginLoc() const LLVM_READONLY { 6155 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6156 } 6157 6158 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6159 }; 6160 6161 } // namespace 6162 6163 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6164 const Expr *OrigFormatExpr, 6165 ArrayRef<const Expr *> Args, 6166 bool HasVAListArg, unsigned format_idx, 6167 unsigned firstDataArg, 6168 Sema::FormatStringType Type, 6169 bool inFunctionCall, 6170 Sema::VariadicCallType CallType, 6171 llvm::SmallBitVector &CheckedVarArgs, 6172 UncoveredArgHandler &UncoveredArg); 6173 6174 // Determine if an expression is a string literal or constant string. 6175 // If this function returns false on the arguments to a function expecting a 6176 // format string, we will usually need to emit a warning. 6177 // True string literals are then checked by CheckFormatString. 6178 static StringLiteralCheckType 6179 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6180 bool HasVAListArg, unsigned format_idx, 6181 unsigned firstDataArg, Sema::FormatStringType Type, 6182 Sema::VariadicCallType CallType, bool InFunctionCall, 6183 llvm::SmallBitVector &CheckedVarArgs, 6184 UncoveredArgHandler &UncoveredArg, 6185 llvm::APSInt Offset) { 6186 tryAgain: 6187 assert(Offset.isSigned() && "invalid offset"); 6188 6189 if (E->isTypeDependent() || E->isValueDependent()) 6190 return SLCT_NotALiteral; 6191 6192 E = E->IgnoreParenCasts(); 6193 6194 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6195 // Technically -Wformat-nonliteral does not warn about this case. 6196 // The behavior of printf and friends in this case is implementation 6197 // dependent. Ideally if the format string cannot be null then 6198 // it should have a 'nonnull' attribute in the function prototype. 6199 return SLCT_UncheckedLiteral; 6200 6201 switch (E->getStmtClass()) { 6202 case Stmt::BinaryConditionalOperatorClass: 6203 case Stmt::ConditionalOperatorClass: { 6204 // The expression is a literal if both sub-expressions were, and it was 6205 // completely checked only if both sub-expressions were checked. 6206 const AbstractConditionalOperator *C = 6207 cast<AbstractConditionalOperator>(E); 6208 6209 // Determine whether it is necessary to check both sub-expressions, for 6210 // example, because the condition expression is a constant that can be 6211 // evaluated at compile time. 6212 bool CheckLeft = true, CheckRight = true; 6213 6214 bool Cond; 6215 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 6216 if (Cond) 6217 CheckRight = false; 6218 else 6219 CheckLeft = false; 6220 } 6221 6222 // We need to maintain the offsets for the right and the left hand side 6223 // separately to check if every possible indexed expression is a valid 6224 // string literal. They might have different offsets for different string 6225 // literals in the end. 6226 StringLiteralCheckType Left; 6227 if (!CheckLeft) 6228 Left = SLCT_UncheckedLiteral; 6229 else { 6230 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6231 HasVAListArg, format_idx, firstDataArg, 6232 Type, CallType, InFunctionCall, 6233 CheckedVarArgs, UncoveredArg, Offset); 6234 if (Left == SLCT_NotALiteral || !CheckRight) { 6235 return Left; 6236 } 6237 } 6238 6239 StringLiteralCheckType Right = 6240 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6241 HasVAListArg, format_idx, firstDataArg, 6242 Type, CallType, InFunctionCall, CheckedVarArgs, 6243 UncoveredArg, Offset); 6244 6245 return (CheckLeft && Left < Right) ? Left : Right; 6246 } 6247 6248 case Stmt::ImplicitCastExprClass: 6249 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6250 goto tryAgain; 6251 6252 case Stmt::OpaqueValueExprClass: 6253 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6254 E = src; 6255 goto tryAgain; 6256 } 6257 return SLCT_NotALiteral; 6258 6259 case Stmt::PredefinedExprClass: 6260 // While __func__, etc., are technically not string literals, they 6261 // cannot contain format specifiers and thus are not a security 6262 // liability. 6263 return SLCT_UncheckedLiteral; 6264 6265 case Stmt::DeclRefExprClass: { 6266 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6267 6268 // As an exception, do not flag errors for variables binding to 6269 // const string literals. 6270 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6271 bool isConstant = false; 6272 QualType T = DR->getType(); 6273 6274 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6275 isConstant = AT->getElementType().isConstant(S.Context); 6276 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6277 isConstant = T.isConstant(S.Context) && 6278 PT->getPointeeType().isConstant(S.Context); 6279 } else if (T->isObjCObjectPointerType()) { 6280 // In ObjC, there is usually no "const ObjectPointer" type, 6281 // so don't check if the pointee type is constant. 6282 isConstant = T.isConstant(S.Context); 6283 } 6284 6285 if (isConstant) { 6286 if (const Expr *Init = VD->getAnyInitializer()) { 6287 // Look through initializers like const char c[] = { "foo" } 6288 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6289 if (InitList->isStringLiteralInit()) 6290 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6291 } 6292 return checkFormatStringExpr(S, Init, Args, 6293 HasVAListArg, format_idx, 6294 firstDataArg, Type, CallType, 6295 /*InFunctionCall*/ false, CheckedVarArgs, 6296 UncoveredArg, Offset); 6297 } 6298 } 6299 6300 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6301 // special check to see if the format string is a function parameter 6302 // of the function calling the printf function. If the function 6303 // has an attribute indicating it is a printf-like function, then we 6304 // should suppress warnings concerning non-literals being used in a call 6305 // to a vprintf function. For example: 6306 // 6307 // void 6308 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6309 // va_list ap; 6310 // va_start(ap, fmt); 6311 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6312 // ... 6313 // } 6314 if (HasVAListArg) { 6315 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6316 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6317 int PVIndex = PV->getFunctionScopeIndex() + 1; 6318 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6319 // adjust for implicit parameter 6320 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6321 if (MD->isInstance()) 6322 ++PVIndex; 6323 // We also check if the formats are compatible. 6324 // We can't pass a 'scanf' string to a 'printf' function. 6325 if (PVIndex == PVFormat->getFormatIdx() && 6326 Type == S.GetFormatStringType(PVFormat)) 6327 return SLCT_UncheckedLiteral; 6328 } 6329 } 6330 } 6331 } 6332 } 6333 6334 return SLCT_NotALiteral; 6335 } 6336 6337 case Stmt::CallExprClass: 6338 case Stmt::CXXMemberCallExprClass: { 6339 const CallExpr *CE = cast<CallExpr>(E); 6340 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6341 bool IsFirst = true; 6342 StringLiteralCheckType CommonResult; 6343 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6344 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6345 StringLiteralCheckType Result = checkFormatStringExpr( 6346 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6347 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6348 if (IsFirst) { 6349 CommonResult = Result; 6350 IsFirst = false; 6351 } 6352 } 6353 if (!IsFirst) 6354 return CommonResult; 6355 6356 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6357 unsigned BuiltinID = FD->getBuiltinID(); 6358 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6359 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6360 const Expr *Arg = CE->getArg(0); 6361 return checkFormatStringExpr(S, Arg, Args, 6362 HasVAListArg, format_idx, 6363 firstDataArg, Type, CallType, 6364 InFunctionCall, CheckedVarArgs, 6365 UncoveredArg, Offset); 6366 } 6367 } 6368 } 6369 6370 return SLCT_NotALiteral; 6371 } 6372 case Stmt::ObjCMessageExprClass: { 6373 const auto *ME = cast<ObjCMessageExpr>(E); 6374 if (const auto *ND = ME->getMethodDecl()) { 6375 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6376 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6377 return checkFormatStringExpr( 6378 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6379 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6380 } 6381 } 6382 6383 return SLCT_NotALiteral; 6384 } 6385 case Stmt::ObjCStringLiteralClass: 6386 case Stmt::StringLiteralClass: { 6387 const StringLiteral *StrE = nullptr; 6388 6389 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6390 StrE = ObjCFExpr->getString(); 6391 else 6392 StrE = cast<StringLiteral>(E); 6393 6394 if (StrE) { 6395 if (Offset.isNegative() || Offset > StrE->getLength()) { 6396 // TODO: It would be better to have an explicit warning for out of 6397 // bounds literals. 6398 return SLCT_NotALiteral; 6399 } 6400 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6401 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6402 firstDataArg, Type, InFunctionCall, CallType, 6403 CheckedVarArgs, UncoveredArg); 6404 return SLCT_CheckedLiteral; 6405 } 6406 6407 return SLCT_NotALiteral; 6408 } 6409 case Stmt::BinaryOperatorClass: { 6410 llvm::APSInt LResult; 6411 llvm::APSInt RResult; 6412 6413 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6414 6415 // A string literal + an int offset is still a string literal. 6416 if (BinOp->isAdditiveOp()) { 6417 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 6418 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 6419 6420 if (LIsInt != RIsInt) { 6421 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6422 6423 if (LIsInt) { 6424 if (BinOpKind == BO_Add) { 6425 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 6426 E = BinOp->getRHS(); 6427 goto tryAgain; 6428 } 6429 } else { 6430 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 6431 E = BinOp->getLHS(); 6432 goto tryAgain; 6433 } 6434 } 6435 } 6436 6437 return SLCT_NotALiteral; 6438 } 6439 case Stmt::UnaryOperatorClass: { 6440 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6441 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6442 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6443 llvm::APSInt IndexResult; 6444 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 6445 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 6446 E = ASE->getBase(); 6447 goto tryAgain; 6448 } 6449 } 6450 6451 return SLCT_NotALiteral; 6452 } 6453 6454 default: 6455 return SLCT_NotALiteral; 6456 } 6457 } 6458 6459 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6460 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6461 .Case("scanf", FST_Scanf) 6462 .Cases("printf", "printf0", FST_Printf) 6463 .Cases("NSString", "CFString", FST_NSString) 6464 .Case("strftime", FST_Strftime) 6465 .Case("strfmon", FST_Strfmon) 6466 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6467 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6468 .Case("os_trace", FST_OSLog) 6469 .Case("os_log", FST_OSLog) 6470 .Default(FST_Unknown); 6471 } 6472 6473 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6474 /// functions) for correct use of format strings. 6475 /// Returns true if a format string has been fully checked. 6476 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6477 ArrayRef<const Expr *> Args, 6478 bool IsCXXMember, 6479 VariadicCallType CallType, 6480 SourceLocation Loc, SourceRange Range, 6481 llvm::SmallBitVector &CheckedVarArgs) { 6482 FormatStringInfo FSI; 6483 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6484 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6485 FSI.FirstDataArg, GetFormatStringType(Format), 6486 CallType, Loc, Range, CheckedVarArgs); 6487 return false; 6488 } 6489 6490 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6491 bool HasVAListArg, unsigned format_idx, 6492 unsigned firstDataArg, FormatStringType Type, 6493 VariadicCallType CallType, 6494 SourceLocation Loc, SourceRange Range, 6495 llvm::SmallBitVector &CheckedVarArgs) { 6496 // CHECK: printf/scanf-like function is called with no format string. 6497 if (format_idx >= Args.size()) { 6498 Diag(Loc, diag::warn_missing_format_string) << Range; 6499 return false; 6500 } 6501 6502 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6503 6504 // CHECK: format string is not a string literal. 6505 // 6506 // Dynamically generated format strings are difficult to 6507 // automatically vet at compile time. Requiring that format strings 6508 // are string literals: (1) permits the checking of format strings by 6509 // the compiler and thereby (2) can practically remove the source of 6510 // many format string exploits. 6511 6512 // Format string can be either ObjC string (e.g. @"%d") or 6513 // C string (e.g. "%d") 6514 // ObjC string uses the same format specifiers as C string, so we can use 6515 // the same format string checking logic for both ObjC and C strings. 6516 UncoveredArgHandler UncoveredArg; 6517 StringLiteralCheckType CT = 6518 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6519 format_idx, firstDataArg, Type, CallType, 6520 /*IsFunctionCall*/ true, CheckedVarArgs, 6521 UncoveredArg, 6522 /*no string offset*/ llvm::APSInt(64, false) = 0); 6523 6524 // Generate a diagnostic where an uncovered argument is detected. 6525 if (UncoveredArg.hasUncoveredArg()) { 6526 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6527 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6528 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6529 } 6530 6531 if (CT != SLCT_NotALiteral) 6532 // Literal format string found, check done! 6533 return CT == SLCT_CheckedLiteral; 6534 6535 // Strftime is particular as it always uses a single 'time' argument, 6536 // so it is safe to pass a non-literal string. 6537 if (Type == FST_Strftime) 6538 return false; 6539 6540 // Do not emit diag when the string param is a macro expansion and the 6541 // format is either NSString or CFString. This is a hack to prevent 6542 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6543 // which are usually used in place of NS and CF string literals. 6544 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6545 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6546 return false; 6547 6548 // If there are no arguments specified, warn with -Wformat-security, otherwise 6549 // warn only with -Wformat-nonliteral. 6550 if (Args.size() == firstDataArg) { 6551 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6552 << OrigFormatExpr->getSourceRange(); 6553 switch (Type) { 6554 default: 6555 break; 6556 case FST_Kprintf: 6557 case FST_FreeBSDKPrintf: 6558 case FST_Printf: 6559 Diag(FormatLoc, diag::note_format_security_fixit) 6560 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6561 break; 6562 case FST_NSString: 6563 Diag(FormatLoc, diag::note_format_security_fixit) 6564 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6565 break; 6566 } 6567 } else { 6568 Diag(FormatLoc, diag::warn_format_nonliteral) 6569 << OrigFormatExpr->getSourceRange(); 6570 } 6571 return false; 6572 } 6573 6574 namespace { 6575 6576 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6577 protected: 6578 Sema &S; 6579 const FormatStringLiteral *FExpr; 6580 const Expr *OrigFormatExpr; 6581 const Sema::FormatStringType FSType; 6582 const unsigned FirstDataArg; 6583 const unsigned NumDataArgs; 6584 const char *Beg; // Start of format string. 6585 const bool HasVAListArg; 6586 ArrayRef<const Expr *> Args; 6587 unsigned FormatIdx; 6588 llvm::SmallBitVector CoveredArgs; 6589 bool usesPositionalArgs = false; 6590 bool atFirstArg = true; 6591 bool inFunctionCall; 6592 Sema::VariadicCallType CallType; 6593 llvm::SmallBitVector &CheckedVarArgs; 6594 UncoveredArgHandler &UncoveredArg; 6595 6596 public: 6597 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6598 const Expr *origFormatExpr, 6599 const Sema::FormatStringType type, unsigned firstDataArg, 6600 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6601 ArrayRef<const Expr *> Args, unsigned formatIdx, 6602 bool inFunctionCall, Sema::VariadicCallType callType, 6603 llvm::SmallBitVector &CheckedVarArgs, 6604 UncoveredArgHandler &UncoveredArg) 6605 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6606 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6607 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6608 inFunctionCall(inFunctionCall), CallType(callType), 6609 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6610 CoveredArgs.resize(numDataArgs); 6611 CoveredArgs.reset(); 6612 } 6613 6614 void DoneProcessing(); 6615 6616 void HandleIncompleteSpecifier(const char *startSpecifier, 6617 unsigned specifierLen) override; 6618 6619 void HandleInvalidLengthModifier( 6620 const analyze_format_string::FormatSpecifier &FS, 6621 const analyze_format_string::ConversionSpecifier &CS, 6622 const char *startSpecifier, unsigned specifierLen, 6623 unsigned DiagID); 6624 6625 void HandleNonStandardLengthModifier( 6626 const analyze_format_string::FormatSpecifier &FS, 6627 const char *startSpecifier, unsigned specifierLen); 6628 6629 void HandleNonStandardConversionSpecifier( 6630 const analyze_format_string::ConversionSpecifier &CS, 6631 const char *startSpecifier, unsigned specifierLen); 6632 6633 void HandlePosition(const char *startPos, unsigned posLen) override; 6634 6635 void HandleInvalidPosition(const char *startSpecifier, 6636 unsigned specifierLen, 6637 analyze_format_string::PositionContext p) override; 6638 6639 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6640 6641 void HandleNullChar(const char *nullCharacter) override; 6642 6643 template <typename Range> 6644 static void 6645 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6646 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6647 bool IsStringLocation, Range StringRange, 6648 ArrayRef<FixItHint> Fixit = None); 6649 6650 protected: 6651 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6652 const char *startSpec, 6653 unsigned specifierLen, 6654 const char *csStart, unsigned csLen); 6655 6656 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6657 const char *startSpec, 6658 unsigned specifierLen); 6659 6660 SourceRange getFormatStringRange(); 6661 CharSourceRange getSpecifierRange(const char *startSpecifier, 6662 unsigned specifierLen); 6663 SourceLocation getLocationOfByte(const char *x); 6664 6665 const Expr *getDataArg(unsigned i) const; 6666 6667 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6668 const analyze_format_string::ConversionSpecifier &CS, 6669 const char *startSpecifier, unsigned specifierLen, 6670 unsigned argIndex); 6671 6672 template <typename Range> 6673 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6674 bool IsStringLocation, Range StringRange, 6675 ArrayRef<FixItHint> Fixit = None); 6676 }; 6677 6678 } // namespace 6679 6680 SourceRange CheckFormatHandler::getFormatStringRange() { 6681 return OrigFormatExpr->getSourceRange(); 6682 } 6683 6684 CharSourceRange CheckFormatHandler:: 6685 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6686 SourceLocation Start = getLocationOfByte(startSpecifier); 6687 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6688 6689 // Advance the end SourceLocation by one due to half-open ranges. 6690 End = End.getLocWithOffset(1); 6691 6692 return CharSourceRange::getCharRange(Start, End); 6693 } 6694 6695 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6696 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6697 S.getLangOpts(), S.Context.getTargetInfo()); 6698 } 6699 6700 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6701 unsigned specifierLen){ 6702 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6703 getLocationOfByte(startSpecifier), 6704 /*IsStringLocation*/true, 6705 getSpecifierRange(startSpecifier, specifierLen)); 6706 } 6707 6708 void CheckFormatHandler::HandleInvalidLengthModifier( 6709 const analyze_format_string::FormatSpecifier &FS, 6710 const analyze_format_string::ConversionSpecifier &CS, 6711 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6712 using namespace analyze_format_string; 6713 6714 const LengthModifier &LM = FS.getLengthModifier(); 6715 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6716 6717 // See if we know how to fix this length modifier. 6718 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6719 if (FixedLM) { 6720 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6721 getLocationOfByte(LM.getStart()), 6722 /*IsStringLocation*/true, 6723 getSpecifierRange(startSpecifier, specifierLen)); 6724 6725 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6726 << FixedLM->toString() 6727 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6728 6729 } else { 6730 FixItHint Hint; 6731 if (DiagID == diag::warn_format_nonsensical_length) 6732 Hint = FixItHint::CreateRemoval(LMRange); 6733 6734 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6735 getLocationOfByte(LM.getStart()), 6736 /*IsStringLocation*/true, 6737 getSpecifierRange(startSpecifier, specifierLen), 6738 Hint); 6739 } 6740 } 6741 6742 void CheckFormatHandler::HandleNonStandardLengthModifier( 6743 const analyze_format_string::FormatSpecifier &FS, 6744 const char *startSpecifier, unsigned specifierLen) { 6745 using namespace analyze_format_string; 6746 6747 const LengthModifier &LM = FS.getLengthModifier(); 6748 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6749 6750 // See if we know how to fix this length modifier. 6751 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6752 if (FixedLM) { 6753 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6754 << LM.toString() << 0, 6755 getLocationOfByte(LM.getStart()), 6756 /*IsStringLocation*/true, 6757 getSpecifierRange(startSpecifier, specifierLen)); 6758 6759 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6760 << FixedLM->toString() 6761 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6762 6763 } else { 6764 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6765 << LM.toString() << 0, 6766 getLocationOfByte(LM.getStart()), 6767 /*IsStringLocation*/true, 6768 getSpecifierRange(startSpecifier, specifierLen)); 6769 } 6770 } 6771 6772 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6773 const analyze_format_string::ConversionSpecifier &CS, 6774 const char *startSpecifier, unsigned specifierLen) { 6775 using namespace analyze_format_string; 6776 6777 // See if we know how to fix this conversion specifier. 6778 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 6779 if (FixedCS) { 6780 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6781 << CS.toString() << /*conversion specifier*/1, 6782 getLocationOfByte(CS.getStart()), 6783 /*IsStringLocation*/true, 6784 getSpecifierRange(startSpecifier, specifierLen)); 6785 6786 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 6787 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 6788 << FixedCS->toString() 6789 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 6790 } else { 6791 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6792 << CS.toString() << /*conversion specifier*/1, 6793 getLocationOfByte(CS.getStart()), 6794 /*IsStringLocation*/true, 6795 getSpecifierRange(startSpecifier, specifierLen)); 6796 } 6797 } 6798 6799 void CheckFormatHandler::HandlePosition(const char *startPos, 6800 unsigned posLen) { 6801 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 6802 getLocationOfByte(startPos), 6803 /*IsStringLocation*/true, 6804 getSpecifierRange(startPos, posLen)); 6805 } 6806 6807 void 6808 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 6809 analyze_format_string::PositionContext p) { 6810 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 6811 << (unsigned) p, 6812 getLocationOfByte(startPos), /*IsStringLocation*/true, 6813 getSpecifierRange(startPos, posLen)); 6814 } 6815 6816 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 6817 unsigned posLen) { 6818 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 6819 getLocationOfByte(startPos), 6820 /*IsStringLocation*/true, 6821 getSpecifierRange(startPos, posLen)); 6822 } 6823 6824 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 6825 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 6826 // The presence of a null character is likely an error. 6827 EmitFormatDiagnostic( 6828 S.PDiag(diag::warn_printf_format_string_contains_null_char), 6829 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 6830 getFormatStringRange()); 6831 } 6832 } 6833 6834 // Note that this may return NULL if there was an error parsing or building 6835 // one of the argument expressions. 6836 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 6837 return Args[FirstDataArg + i]; 6838 } 6839 6840 void CheckFormatHandler::DoneProcessing() { 6841 // Does the number of data arguments exceed the number of 6842 // format conversions in the format string? 6843 if (!HasVAListArg) { 6844 // Find any arguments that weren't covered. 6845 CoveredArgs.flip(); 6846 signed notCoveredArg = CoveredArgs.find_first(); 6847 if (notCoveredArg >= 0) { 6848 assert((unsigned)notCoveredArg < NumDataArgs); 6849 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 6850 } else { 6851 UncoveredArg.setAllCovered(); 6852 } 6853 } 6854 } 6855 6856 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 6857 const Expr *ArgExpr) { 6858 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 6859 "Invalid state"); 6860 6861 if (!ArgExpr) 6862 return; 6863 6864 SourceLocation Loc = ArgExpr->getBeginLoc(); 6865 6866 if (S.getSourceManager().isInSystemMacro(Loc)) 6867 return; 6868 6869 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 6870 for (auto E : DiagnosticExprs) 6871 PDiag << E->getSourceRange(); 6872 6873 CheckFormatHandler::EmitFormatDiagnostic( 6874 S, IsFunctionCall, DiagnosticExprs[0], 6875 PDiag, Loc, /*IsStringLocation*/false, 6876 DiagnosticExprs[0]->getSourceRange()); 6877 } 6878 6879 bool 6880 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 6881 SourceLocation Loc, 6882 const char *startSpec, 6883 unsigned specifierLen, 6884 const char *csStart, 6885 unsigned csLen) { 6886 bool keepGoing = true; 6887 if (argIndex < NumDataArgs) { 6888 // Consider the argument coverered, even though the specifier doesn't 6889 // make sense. 6890 CoveredArgs.set(argIndex); 6891 } 6892 else { 6893 // If argIndex exceeds the number of data arguments we 6894 // don't issue a warning because that is just a cascade of warnings (and 6895 // they may have intended '%%' anyway). We don't want to continue processing 6896 // the format string after this point, however, as we will like just get 6897 // gibberish when trying to match arguments. 6898 keepGoing = false; 6899 } 6900 6901 StringRef Specifier(csStart, csLen); 6902 6903 // If the specifier in non-printable, it could be the first byte of a UTF-8 6904 // sequence. In that case, print the UTF-8 code point. If not, print the byte 6905 // hex value. 6906 std::string CodePointStr; 6907 if (!llvm::sys::locale::isPrint(*csStart)) { 6908 llvm::UTF32 CodePoint; 6909 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 6910 const llvm::UTF8 *E = 6911 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 6912 llvm::ConversionResult Result = 6913 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 6914 6915 if (Result != llvm::conversionOK) { 6916 unsigned char FirstChar = *csStart; 6917 CodePoint = (llvm::UTF32)FirstChar; 6918 } 6919 6920 llvm::raw_string_ostream OS(CodePointStr); 6921 if (CodePoint < 256) 6922 OS << "\\x" << llvm::format("%02x", CodePoint); 6923 else if (CodePoint <= 0xFFFF) 6924 OS << "\\u" << llvm::format("%04x", CodePoint); 6925 else 6926 OS << "\\U" << llvm::format("%08x", CodePoint); 6927 OS.flush(); 6928 Specifier = CodePointStr; 6929 } 6930 6931 EmitFormatDiagnostic( 6932 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 6933 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 6934 6935 return keepGoing; 6936 } 6937 6938 void 6939 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 6940 const char *startSpec, 6941 unsigned specifierLen) { 6942 EmitFormatDiagnostic( 6943 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 6944 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 6945 } 6946 6947 bool 6948 CheckFormatHandler::CheckNumArgs( 6949 const analyze_format_string::FormatSpecifier &FS, 6950 const analyze_format_string::ConversionSpecifier &CS, 6951 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 6952 6953 if (argIndex >= NumDataArgs) { 6954 PartialDiagnostic PDiag = FS.usesPositionalArg() 6955 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 6956 << (argIndex+1) << NumDataArgs) 6957 : S.PDiag(diag::warn_printf_insufficient_data_args); 6958 EmitFormatDiagnostic( 6959 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 6960 getSpecifierRange(startSpecifier, specifierLen)); 6961 6962 // Since more arguments than conversion tokens are given, by extension 6963 // all arguments are covered, so mark this as so. 6964 UncoveredArg.setAllCovered(); 6965 return false; 6966 } 6967 return true; 6968 } 6969 6970 template<typename Range> 6971 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 6972 SourceLocation Loc, 6973 bool IsStringLocation, 6974 Range StringRange, 6975 ArrayRef<FixItHint> FixIt) { 6976 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 6977 Loc, IsStringLocation, StringRange, FixIt); 6978 } 6979 6980 /// If the format string is not within the function call, emit a note 6981 /// so that the function call and string are in diagnostic messages. 6982 /// 6983 /// \param InFunctionCall if true, the format string is within the function 6984 /// call and only one diagnostic message will be produced. Otherwise, an 6985 /// extra note will be emitted pointing to location of the format string. 6986 /// 6987 /// \param ArgumentExpr the expression that is passed as the format string 6988 /// argument in the function call. Used for getting locations when two 6989 /// diagnostics are emitted. 6990 /// 6991 /// \param PDiag the callee should already have provided any strings for the 6992 /// diagnostic message. This function only adds locations and fixits 6993 /// to diagnostics. 6994 /// 6995 /// \param Loc primary location for diagnostic. If two diagnostics are 6996 /// required, one will be at Loc and a new SourceLocation will be created for 6997 /// the other one. 6998 /// 6999 /// \param IsStringLocation if true, Loc points to the format string should be 7000 /// used for the note. Otherwise, Loc points to the argument list and will 7001 /// be used with PDiag. 7002 /// 7003 /// \param StringRange some or all of the string to highlight. This is 7004 /// templated so it can accept either a CharSourceRange or a SourceRange. 7005 /// 7006 /// \param FixIt optional fix it hint for the format string. 7007 template <typename Range> 7008 void CheckFormatHandler::EmitFormatDiagnostic( 7009 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7010 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7011 Range StringRange, ArrayRef<FixItHint> FixIt) { 7012 if (InFunctionCall) { 7013 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7014 D << StringRange; 7015 D << FixIt; 7016 } else { 7017 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7018 << ArgumentExpr->getSourceRange(); 7019 7020 const Sema::SemaDiagnosticBuilder &Note = 7021 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7022 diag::note_format_string_defined); 7023 7024 Note << StringRange; 7025 Note << FixIt; 7026 } 7027 } 7028 7029 //===--- CHECK: Printf format string checking ------------------------------===// 7030 7031 namespace { 7032 7033 class CheckPrintfHandler : public CheckFormatHandler { 7034 public: 7035 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7036 const Expr *origFormatExpr, 7037 const Sema::FormatStringType type, unsigned firstDataArg, 7038 unsigned numDataArgs, bool isObjC, const char *beg, 7039 bool hasVAListArg, ArrayRef<const Expr *> Args, 7040 unsigned formatIdx, bool inFunctionCall, 7041 Sema::VariadicCallType CallType, 7042 llvm::SmallBitVector &CheckedVarArgs, 7043 UncoveredArgHandler &UncoveredArg) 7044 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7045 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7046 inFunctionCall, CallType, CheckedVarArgs, 7047 UncoveredArg) {} 7048 7049 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7050 7051 /// Returns true if '%@' specifiers are allowed in the format string. 7052 bool allowsObjCArg() const { 7053 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7054 FSType == Sema::FST_OSTrace; 7055 } 7056 7057 bool HandleInvalidPrintfConversionSpecifier( 7058 const analyze_printf::PrintfSpecifier &FS, 7059 const char *startSpecifier, 7060 unsigned specifierLen) override; 7061 7062 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7063 const char *startSpecifier, 7064 unsigned specifierLen) override; 7065 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7066 const char *StartSpecifier, 7067 unsigned SpecifierLen, 7068 const Expr *E); 7069 7070 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7071 const char *startSpecifier, unsigned specifierLen); 7072 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7073 const analyze_printf::OptionalAmount &Amt, 7074 unsigned type, 7075 const char *startSpecifier, unsigned specifierLen); 7076 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7077 const analyze_printf::OptionalFlag &flag, 7078 const char *startSpecifier, unsigned specifierLen); 7079 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7080 const analyze_printf::OptionalFlag &ignoredFlag, 7081 const analyze_printf::OptionalFlag &flag, 7082 const char *startSpecifier, unsigned specifierLen); 7083 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7084 const Expr *E); 7085 7086 void HandleEmptyObjCModifierFlag(const char *startFlag, 7087 unsigned flagLen) override; 7088 7089 void HandleInvalidObjCModifierFlag(const char *startFlag, 7090 unsigned flagLen) override; 7091 7092 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7093 const char *flagsEnd, 7094 const char *conversionPosition) 7095 override; 7096 }; 7097 7098 } // namespace 7099 7100 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7101 const analyze_printf::PrintfSpecifier &FS, 7102 const char *startSpecifier, 7103 unsigned specifierLen) { 7104 const analyze_printf::PrintfConversionSpecifier &CS = 7105 FS.getConversionSpecifier(); 7106 7107 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7108 getLocationOfByte(CS.getStart()), 7109 startSpecifier, specifierLen, 7110 CS.getStart(), CS.getLength()); 7111 } 7112 7113 bool CheckPrintfHandler::HandleAmount( 7114 const analyze_format_string::OptionalAmount &Amt, 7115 unsigned k, const char *startSpecifier, 7116 unsigned specifierLen) { 7117 if (Amt.hasDataArgument()) { 7118 if (!HasVAListArg) { 7119 unsigned argIndex = Amt.getArgIndex(); 7120 if (argIndex >= NumDataArgs) { 7121 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7122 << k, 7123 getLocationOfByte(Amt.getStart()), 7124 /*IsStringLocation*/true, 7125 getSpecifierRange(startSpecifier, specifierLen)); 7126 // Don't do any more checking. We will just emit 7127 // spurious errors. 7128 return false; 7129 } 7130 7131 // Type check the data argument. It should be an 'int'. 7132 // Although not in conformance with C99, we also allow the argument to be 7133 // an 'unsigned int' as that is a reasonably safe case. GCC also 7134 // doesn't emit a warning for that case. 7135 CoveredArgs.set(argIndex); 7136 const Expr *Arg = getDataArg(argIndex); 7137 if (!Arg) 7138 return false; 7139 7140 QualType T = Arg->getType(); 7141 7142 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7143 assert(AT.isValid()); 7144 7145 if (!AT.matchesType(S.Context, T)) { 7146 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7147 << k << AT.getRepresentativeTypeName(S.Context) 7148 << T << Arg->getSourceRange(), 7149 getLocationOfByte(Amt.getStart()), 7150 /*IsStringLocation*/true, 7151 getSpecifierRange(startSpecifier, specifierLen)); 7152 // Don't do any more checking. We will just emit 7153 // spurious errors. 7154 return false; 7155 } 7156 } 7157 } 7158 return true; 7159 } 7160 7161 void CheckPrintfHandler::HandleInvalidAmount( 7162 const analyze_printf::PrintfSpecifier &FS, 7163 const analyze_printf::OptionalAmount &Amt, 7164 unsigned type, 7165 const char *startSpecifier, 7166 unsigned specifierLen) { 7167 const analyze_printf::PrintfConversionSpecifier &CS = 7168 FS.getConversionSpecifier(); 7169 7170 FixItHint fixit = 7171 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7172 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7173 Amt.getConstantLength())) 7174 : FixItHint(); 7175 7176 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7177 << type << CS.toString(), 7178 getLocationOfByte(Amt.getStart()), 7179 /*IsStringLocation*/true, 7180 getSpecifierRange(startSpecifier, specifierLen), 7181 fixit); 7182 } 7183 7184 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7185 const analyze_printf::OptionalFlag &flag, 7186 const char *startSpecifier, 7187 unsigned specifierLen) { 7188 // Warn about pointless flag with a fixit removal. 7189 const analyze_printf::PrintfConversionSpecifier &CS = 7190 FS.getConversionSpecifier(); 7191 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7192 << flag.toString() << CS.toString(), 7193 getLocationOfByte(flag.getPosition()), 7194 /*IsStringLocation*/true, 7195 getSpecifierRange(startSpecifier, specifierLen), 7196 FixItHint::CreateRemoval( 7197 getSpecifierRange(flag.getPosition(), 1))); 7198 } 7199 7200 void CheckPrintfHandler::HandleIgnoredFlag( 7201 const analyze_printf::PrintfSpecifier &FS, 7202 const analyze_printf::OptionalFlag &ignoredFlag, 7203 const analyze_printf::OptionalFlag &flag, 7204 const char *startSpecifier, 7205 unsigned specifierLen) { 7206 // Warn about ignored flag with a fixit removal. 7207 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7208 << ignoredFlag.toString() << flag.toString(), 7209 getLocationOfByte(ignoredFlag.getPosition()), 7210 /*IsStringLocation*/true, 7211 getSpecifierRange(startSpecifier, specifierLen), 7212 FixItHint::CreateRemoval( 7213 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7214 } 7215 7216 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7217 unsigned flagLen) { 7218 // Warn about an empty flag. 7219 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7220 getLocationOfByte(startFlag), 7221 /*IsStringLocation*/true, 7222 getSpecifierRange(startFlag, flagLen)); 7223 } 7224 7225 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7226 unsigned flagLen) { 7227 // Warn about an invalid flag. 7228 auto Range = getSpecifierRange(startFlag, flagLen); 7229 StringRef flag(startFlag, flagLen); 7230 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7231 getLocationOfByte(startFlag), 7232 /*IsStringLocation*/true, 7233 Range, FixItHint::CreateRemoval(Range)); 7234 } 7235 7236 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7237 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7238 // Warn about using '[...]' without a '@' conversion. 7239 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7240 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7241 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7242 getLocationOfByte(conversionPosition), 7243 /*IsStringLocation*/true, 7244 Range, FixItHint::CreateRemoval(Range)); 7245 } 7246 7247 // Determines if the specified is a C++ class or struct containing 7248 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7249 // "c_str()"). 7250 template<typename MemberKind> 7251 static llvm::SmallPtrSet<MemberKind*, 1> 7252 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7253 const RecordType *RT = Ty->getAs<RecordType>(); 7254 llvm::SmallPtrSet<MemberKind*, 1> Results; 7255 7256 if (!RT) 7257 return Results; 7258 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7259 if (!RD || !RD->getDefinition()) 7260 return Results; 7261 7262 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7263 Sema::LookupMemberName); 7264 R.suppressDiagnostics(); 7265 7266 // We just need to include all members of the right kind turned up by the 7267 // filter, at this point. 7268 if (S.LookupQualifiedName(R, RT->getDecl())) 7269 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7270 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7271 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7272 Results.insert(FK); 7273 } 7274 return Results; 7275 } 7276 7277 /// Check if we could call '.c_str()' on an object. 7278 /// 7279 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7280 /// allow the call, or if it would be ambiguous). 7281 bool Sema::hasCStrMethod(const Expr *E) { 7282 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7283 7284 MethodSet Results = 7285 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7286 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7287 MI != ME; ++MI) 7288 if ((*MI)->getMinRequiredArguments() == 0) 7289 return true; 7290 return false; 7291 } 7292 7293 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7294 // better diagnostic if so. AT is assumed to be valid. 7295 // Returns true when a c_str() conversion method is found. 7296 bool CheckPrintfHandler::checkForCStrMembers( 7297 const analyze_printf::ArgType &AT, const Expr *E) { 7298 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7299 7300 MethodSet Results = 7301 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7302 7303 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7304 MI != ME; ++MI) { 7305 const CXXMethodDecl *Method = *MI; 7306 if (Method->getMinRequiredArguments() == 0 && 7307 AT.matchesType(S.Context, Method->getReturnType())) { 7308 // FIXME: Suggest parens if the expression needs them. 7309 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7310 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7311 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7312 return true; 7313 } 7314 } 7315 7316 return false; 7317 } 7318 7319 bool 7320 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7321 &FS, 7322 const char *startSpecifier, 7323 unsigned specifierLen) { 7324 using namespace analyze_format_string; 7325 using namespace analyze_printf; 7326 7327 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7328 7329 if (FS.consumesDataArgument()) { 7330 if (atFirstArg) { 7331 atFirstArg = false; 7332 usesPositionalArgs = FS.usesPositionalArg(); 7333 } 7334 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7335 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7336 startSpecifier, specifierLen); 7337 return false; 7338 } 7339 } 7340 7341 // First check if the field width, precision, and conversion specifier 7342 // have matching data arguments. 7343 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7344 startSpecifier, specifierLen)) { 7345 return false; 7346 } 7347 7348 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7349 startSpecifier, specifierLen)) { 7350 return false; 7351 } 7352 7353 if (!CS.consumesDataArgument()) { 7354 // FIXME: Technically specifying a precision or field width here 7355 // makes no sense. Worth issuing a warning at some point. 7356 return true; 7357 } 7358 7359 // Consume the argument. 7360 unsigned argIndex = FS.getArgIndex(); 7361 if (argIndex < NumDataArgs) { 7362 // The check to see if the argIndex is valid will come later. 7363 // We set the bit here because we may exit early from this 7364 // function if we encounter some other error. 7365 CoveredArgs.set(argIndex); 7366 } 7367 7368 // FreeBSD kernel extensions. 7369 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7370 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7371 // We need at least two arguments. 7372 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7373 return false; 7374 7375 // Claim the second argument. 7376 CoveredArgs.set(argIndex + 1); 7377 7378 // Type check the first argument (int for %b, pointer for %D) 7379 const Expr *Ex = getDataArg(argIndex); 7380 const analyze_printf::ArgType &AT = 7381 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7382 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7383 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7384 EmitFormatDiagnostic( 7385 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7386 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7387 << false << Ex->getSourceRange(), 7388 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7389 getSpecifierRange(startSpecifier, specifierLen)); 7390 7391 // Type check the second argument (char * for both %b and %D) 7392 Ex = getDataArg(argIndex + 1); 7393 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7394 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7395 EmitFormatDiagnostic( 7396 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7397 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7398 << false << Ex->getSourceRange(), 7399 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7400 getSpecifierRange(startSpecifier, specifierLen)); 7401 7402 return true; 7403 } 7404 7405 // Check for using an Objective-C specific conversion specifier 7406 // in a non-ObjC literal. 7407 if (!allowsObjCArg() && CS.isObjCArg()) { 7408 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7409 specifierLen); 7410 } 7411 7412 // %P can only be used with os_log. 7413 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7414 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7415 specifierLen); 7416 } 7417 7418 // %n is not allowed with os_log. 7419 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7420 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7421 getLocationOfByte(CS.getStart()), 7422 /*IsStringLocation*/ false, 7423 getSpecifierRange(startSpecifier, specifierLen)); 7424 7425 return true; 7426 } 7427 7428 // Only scalars are allowed for os_trace. 7429 if (FSType == Sema::FST_OSTrace && 7430 (CS.getKind() == ConversionSpecifier::PArg || 7431 CS.getKind() == ConversionSpecifier::sArg || 7432 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7433 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7434 specifierLen); 7435 } 7436 7437 // Check for use of public/private annotation outside of os_log(). 7438 if (FSType != Sema::FST_OSLog) { 7439 if (FS.isPublic().isSet()) { 7440 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7441 << "public", 7442 getLocationOfByte(FS.isPublic().getPosition()), 7443 /*IsStringLocation*/ false, 7444 getSpecifierRange(startSpecifier, specifierLen)); 7445 } 7446 if (FS.isPrivate().isSet()) { 7447 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7448 << "private", 7449 getLocationOfByte(FS.isPrivate().getPosition()), 7450 /*IsStringLocation*/ false, 7451 getSpecifierRange(startSpecifier, specifierLen)); 7452 } 7453 } 7454 7455 // Check for invalid use of field width 7456 if (!FS.hasValidFieldWidth()) { 7457 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7458 startSpecifier, specifierLen); 7459 } 7460 7461 // Check for invalid use of precision 7462 if (!FS.hasValidPrecision()) { 7463 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7464 startSpecifier, specifierLen); 7465 } 7466 7467 // Precision is mandatory for %P specifier. 7468 if (CS.getKind() == ConversionSpecifier::PArg && 7469 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7471 getLocationOfByte(startSpecifier), 7472 /*IsStringLocation*/ false, 7473 getSpecifierRange(startSpecifier, specifierLen)); 7474 } 7475 7476 // Check each flag does not conflict with any other component. 7477 if (!FS.hasValidThousandsGroupingPrefix()) 7478 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7479 if (!FS.hasValidLeadingZeros()) 7480 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7481 if (!FS.hasValidPlusPrefix()) 7482 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7483 if (!FS.hasValidSpacePrefix()) 7484 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7485 if (!FS.hasValidAlternativeForm()) 7486 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7487 if (!FS.hasValidLeftJustified()) 7488 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7489 7490 // Check that flags are not ignored by another flag 7491 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7492 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7493 startSpecifier, specifierLen); 7494 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7495 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7496 startSpecifier, specifierLen); 7497 7498 // Check the length modifier is valid with the given conversion specifier. 7499 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7500 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7501 diag::warn_format_nonsensical_length); 7502 else if (!FS.hasStandardLengthModifier()) 7503 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7504 else if (!FS.hasStandardLengthConversionCombination()) 7505 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7506 diag::warn_format_non_standard_conversion_spec); 7507 7508 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7509 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7510 7511 // The remaining checks depend on the data arguments. 7512 if (HasVAListArg) 7513 return true; 7514 7515 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7516 return false; 7517 7518 const Expr *Arg = getDataArg(argIndex); 7519 if (!Arg) 7520 return true; 7521 7522 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7523 } 7524 7525 static bool requiresParensToAddCast(const Expr *E) { 7526 // FIXME: We should have a general way to reason about operator 7527 // precedence and whether parens are actually needed here. 7528 // Take care of a few common cases where they aren't. 7529 const Expr *Inside = E->IgnoreImpCasts(); 7530 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7531 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7532 7533 switch (Inside->getStmtClass()) { 7534 case Stmt::ArraySubscriptExprClass: 7535 case Stmt::CallExprClass: 7536 case Stmt::CharacterLiteralClass: 7537 case Stmt::CXXBoolLiteralExprClass: 7538 case Stmt::DeclRefExprClass: 7539 case Stmt::FloatingLiteralClass: 7540 case Stmt::IntegerLiteralClass: 7541 case Stmt::MemberExprClass: 7542 case Stmt::ObjCArrayLiteralClass: 7543 case Stmt::ObjCBoolLiteralExprClass: 7544 case Stmt::ObjCBoxedExprClass: 7545 case Stmt::ObjCDictionaryLiteralClass: 7546 case Stmt::ObjCEncodeExprClass: 7547 case Stmt::ObjCIvarRefExprClass: 7548 case Stmt::ObjCMessageExprClass: 7549 case Stmt::ObjCPropertyRefExprClass: 7550 case Stmt::ObjCStringLiteralClass: 7551 case Stmt::ObjCSubscriptRefExprClass: 7552 case Stmt::ParenExprClass: 7553 case Stmt::StringLiteralClass: 7554 case Stmt::UnaryOperatorClass: 7555 return false; 7556 default: 7557 return true; 7558 } 7559 } 7560 7561 static std::pair<QualType, StringRef> 7562 shouldNotPrintDirectly(const ASTContext &Context, 7563 QualType IntendedTy, 7564 const Expr *E) { 7565 // Use a 'while' to peel off layers of typedefs. 7566 QualType TyTy = IntendedTy; 7567 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7568 StringRef Name = UserTy->getDecl()->getName(); 7569 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7570 .Case("CFIndex", Context.getNSIntegerType()) 7571 .Case("NSInteger", Context.getNSIntegerType()) 7572 .Case("NSUInteger", Context.getNSUIntegerType()) 7573 .Case("SInt32", Context.IntTy) 7574 .Case("UInt32", Context.UnsignedIntTy) 7575 .Default(QualType()); 7576 7577 if (!CastTy.isNull()) 7578 return std::make_pair(CastTy, Name); 7579 7580 TyTy = UserTy->desugar(); 7581 } 7582 7583 // Strip parens if necessary. 7584 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7585 return shouldNotPrintDirectly(Context, 7586 PE->getSubExpr()->getType(), 7587 PE->getSubExpr()); 7588 7589 // If this is a conditional expression, then its result type is constructed 7590 // via usual arithmetic conversions and thus there might be no necessary 7591 // typedef sugar there. Recurse to operands to check for NSInteger & 7592 // Co. usage condition. 7593 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7594 QualType TrueTy, FalseTy; 7595 StringRef TrueName, FalseName; 7596 7597 std::tie(TrueTy, TrueName) = 7598 shouldNotPrintDirectly(Context, 7599 CO->getTrueExpr()->getType(), 7600 CO->getTrueExpr()); 7601 std::tie(FalseTy, FalseName) = 7602 shouldNotPrintDirectly(Context, 7603 CO->getFalseExpr()->getType(), 7604 CO->getFalseExpr()); 7605 7606 if (TrueTy == FalseTy) 7607 return std::make_pair(TrueTy, TrueName); 7608 else if (TrueTy.isNull()) 7609 return std::make_pair(FalseTy, FalseName); 7610 else if (FalseTy.isNull()) 7611 return std::make_pair(TrueTy, TrueName); 7612 } 7613 7614 return std::make_pair(QualType(), StringRef()); 7615 } 7616 7617 bool 7618 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7619 const char *StartSpecifier, 7620 unsigned SpecifierLen, 7621 const Expr *E) { 7622 using namespace analyze_format_string; 7623 using namespace analyze_printf; 7624 7625 // Now type check the data expression that matches the 7626 // format specifier. 7627 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7628 if (!AT.isValid()) 7629 return true; 7630 7631 QualType ExprTy = E->getType(); 7632 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7633 ExprTy = TET->getUnderlyingExpr()->getType(); 7634 } 7635 7636 const analyze_printf::ArgType::MatchKind Match = 7637 AT.matchesType(S.Context, ExprTy); 7638 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 7639 if (Match == analyze_printf::ArgType::Match) 7640 return true; 7641 7642 // Look through argument promotions for our error message's reported type. 7643 // This includes the integral and floating promotions, but excludes array 7644 // and function pointer decay; seeing that an argument intended to be a 7645 // string has type 'char [6]' is probably more confusing than 'char *'. 7646 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7647 if (ICE->getCastKind() == CK_IntegralCast || 7648 ICE->getCastKind() == CK_FloatingCast) { 7649 E = ICE->getSubExpr(); 7650 ExprTy = E->getType(); 7651 7652 // Check if we didn't match because of an implicit cast from a 'char' 7653 // or 'short' to an 'int'. This is done because printf is a varargs 7654 // function. 7655 if (ICE->getType() == S.Context.IntTy || 7656 ICE->getType() == S.Context.UnsignedIntTy) { 7657 // All further checking is done on the subexpression. 7658 if (AT.matchesType(S.Context, ExprTy)) 7659 return true; 7660 } 7661 } 7662 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7663 // Special case for 'a', which has type 'int' in C. 7664 // Note, however, that we do /not/ want to treat multibyte constants like 7665 // 'MooV' as characters! This form is deprecated but still exists. 7666 if (ExprTy == S.Context.IntTy) 7667 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 7668 ExprTy = S.Context.CharTy; 7669 } 7670 7671 // Look through enums to their underlying type. 7672 bool IsEnum = false; 7673 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7674 ExprTy = EnumTy->getDecl()->getIntegerType(); 7675 IsEnum = true; 7676 } 7677 7678 // %C in an Objective-C context prints a unichar, not a wchar_t. 7679 // If the argument is an integer of some kind, believe the %C and suggest 7680 // a cast instead of changing the conversion specifier. 7681 QualType IntendedTy = ExprTy; 7682 if (isObjCContext() && 7683 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7684 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7685 !ExprTy->isCharType()) { 7686 // 'unichar' is defined as a typedef of unsigned short, but we should 7687 // prefer using the typedef if it is visible. 7688 IntendedTy = S.Context.UnsignedShortTy; 7689 7690 // While we are here, check if the value is an IntegerLiteral that happens 7691 // to be within the valid range. 7692 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7693 const llvm::APInt &V = IL->getValue(); 7694 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7695 return true; 7696 } 7697 7698 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7699 Sema::LookupOrdinaryName); 7700 if (S.LookupName(Result, S.getCurScope())) { 7701 NamedDecl *ND = Result.getFoundDecl(); 7702 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7703 if (TD->getUnderlyingType() == IntendedTy) 7704 IntendedTy = S.Context.getTypedefType(TD); 7705 } 7706 } 7707 } 7708 7709 // Special-case some of Darwin's platform-independence types by suggesting 7710 // casts to primitive types that are known to be large enough. 7711 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7712 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7713 QualType CastTy; 7714 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7715 if (!CastTy.isNull()) { 7716 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7717 // (long in ASTContext). Only complain to pedants. 7718 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7719 (AT.isSizeT() || AT.isPtrdiffT()) && 7720 AT.matchesType(S.Context, CastTy)) 7721 Pedantic = true; 7722 IntendedTy = CastTy; 7723 ShouldNotPrintDirectly = true; 7724 } 7725 } 7726 7727 // We may be able to offer a FixItHint if it is a supported type. 7728 PrintfSpecifier fixedFS = FS; 7729 bool Success = 7730 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7731 7732 if (Success) { 7733 // Get the fix string from the fixed format specifier 7734 SmallString<16> buf; 7735 llvm::raw_svector_ostream os(buf); 7736 fixedFS.toString(os); 7737 7738 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 7739 7740 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 7741 unsigned Diag = 7742 Pedantic 7743 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7744 : diag::warn_format_conversion_argument_type_mismatch; 7745 // In this case, the specifier is wrong and should be changed to match 7746 // the argument. 7747 EmitFormatDiagnostic(S.PDiag(Diag) 7748 << AT.getRepresentativeTypeName(S.Context) 7749 << IntendedTy << IsEnum << E->getSourceRange(), 7750 E->getBeginLoc(), 7751 /*IsStringLocation*/ false, SpecRange, 7752 FixItHint::CreateReplacement(SpecRange, os.str())); 7753 } else { 7754 // The canonical type for formatting this value is different from the 7755 // actual type of the expression. (This occurs, for example, with Darwin's 7756 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 7757 // should be printed as 'long' for 64-bit compatibility.) 7758 // Rather than emitting a normal format/argument mismatch, we want to 7759 // add a cast to the recommended type (and correct the format string 7760 // if necessary). 7761 SmallString<16> CastBuf; 7762 llvm::raw_svector_ostream CastFix(CastBuf); 7763 CastFix << "("; 7764 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 7765 CastFix << ")"; 7766 7767 SmallVector<FixItHint,4> Hints; 7768 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 7769 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 7770 7771 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 7772 // If there's already a cast present, just replace it. 7773 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 7774 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 7775 7776 } else if (!requiresParensToAddCast(E)) { 7777 // If the expression has high enough precedence, 7778 // just write the C-style cast. 7779 Hints.push_back( 7780 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7781 } else { 7782 // Otherwise, add parens around the expression as well as the cast. 7783 CastFix << "("; 7784 Hints.push_back( 7785 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7786 7787 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 7788 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 7789 } 7790 7791 if (ShouldNotPrintDirectly) { 7792 // The expression has a type that should not be printed directly. 7793 // We extract the name from the typedef because we don't want to show 7794 // the underlying type in the diagnostic. 7795 StringRef Name; 7796 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 7797 Name = TypedefTy->getDecl()->getName(); 7798 else 7799 Name = CastTyName; 7800 unsigned Diag = Pedantic 7801 ? diag::warn_format_argument_needs_cast_pedantic 7802 : diag::warn_format_argument_needs_cast; 7803 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 7804 << E->getSourceRange(), 7805 E->getBeginLoc(), /*IsStringLocation=*/false, 7806 SpecRange, Hints); 7807 } else { 7808 // In this case, the expression could be printed using a different 7809 // specifier, but we've decided that the specifier is probably correct 7810 // and we should cast instead. Just use the normal warning message. 7811 EmitFormatDiagnostic( 7812 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7813 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 7814 << E->getSourceRange(), 7815 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 7816 } 7817 } 7818 } else { 7819 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 7820 SpecifierLen); 7821 // Since the warning for passing non-POD types to variadic functions 7822 // was deferred until now, we emit a warning for non-POD 7823 // arguments here. 7824 switch (S.isValidVarArgType(ExprTy)) { 7825 case Sema::VAK_Valid: 7826 case Sema::VAK_ValidInCXX11: { 7827 unsigned Diag = 7828 Pedantic 7829 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7830 : diag::warn_format_conversion_argument_type_mismatch; 7831 7832 EmitFormatDiagnostic( 7833 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 7834 << IsEnum << CSR << E->getSourceRange(), 7835 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7836 break; 7837 } 7838 case Sema::VAK_Undefined: 7839 case Sema::VAK_MSVCUndefined: 7840 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 7841 << S.getLangOpts().CPlusPlus11 << ExprTy 7842 << CallType 7843 << AT.getRepresentativeTypeName(S.Context) << CSR 7844 << E->getSourceRange(), 7845 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7846 checkForCStrMembers(AT, E); 7847 break; 7848 7849 case Sema::VAK_Invalid: 7850 if (ExprTy->isObjCObjectType()) 7851 EmitFormatDiagnostic( 7852 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 7853 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 7854 << AT.getRepresentativeTypeName(S.Context) << CSR 7855 << E->getSourceRange(), 7856 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7857 else 7858 // FIXME: If this is an initializer list, suggest removing the braces 7859 // or inserting a cast to the target type. 7860 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 7861 << isa<InitListExpr>(E) << ExprTy << CallType 7862 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 7863 break; 7864 } 7865 7866 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 7867 "format string specifier index out of range"); 7868 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 7869 } 7870 7871 return true; 7872 } 7873 7874 //===--- CHECK: Scanf format string checking ------------------------------===// 7875 7876 namespace { 7877 7878 class CheckScanfHandler : public CheckFormatHandler { 7879 public: 7880 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 7881 const Expr *origFormatExpr, Sema::FormatStringType type, 7882 unsigned firstDataArg, unsigned numDataArgs, 7883 const char *beg, bool hasVAListArg, 7884 ArrayRef<const Expr *> Args, unsigned formatIdx, 7885 bool inFunctionCall, Sema::VariadicCallType CallType, 7886 llvm::SmallBitVector &CheckedVarArgs, 7887 UncoveredArgHandler &UncoveredArg) 7888 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7889 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7890 inFunctionCall, CallType, CheckedVarArgs, 7891 UncoveredArg) {} 7892 7893 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 7894 const char *startSpecifier, 7895 unsigned specifierLen) override; 7896 7897 bool HandleInvalidScanfConversionSpecifier( 7898 const analyze_scanf::ScanfSpecifier &FS, 7899 const char *startSpecifier, 7900 unsigned specifierLen) override; 7901 7902 void HandleIncompleteScanList(const char *start, const char *end) override; 7903 }; 7904 7905 } // namespace 7906 7907 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 7908 const char *end) { 7909 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 7910 getLocationOfByte(end), /*IsStringLocation*/true, 7911 getSpecifierRange(start, end - start)); 7912 } 7913 7914 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 7915 const analyze_scanf::ScanfSpecifier &FS, 7916 const char *startSpecifier, 7917 unsigned specifierLen) { 7918 const analyze_scanf::ScanfConversionSpecifier &CS = 7919 FS.getConversionSpecifier(); 7920 7921 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7922 getLocationOfByte(CS.getStart()), 7923 startSpecifier, specifierLen, 7924 CS.getStart(), CS.getLength()); 7925 } 7926 7927 bool CheckScanfHandler::HandleScanfSpecifier( 7928 const analyze_scanf::ScanfSpecifier &FS, 7929 const char *startSpecifier, 7930 unsigned specifierLen) { 7931 using namespace analyze_scanf; 7932 using namespace analyze_format_string; 7933 7934 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 7935 7936 // Handle case where '%' and '*' don't consume an argument. These shouldn't 7937 // be used to decide if we are using positional arguments consistently. 7938 if (FS.consumesDataArgument()) { 7939 if (atFirstArg) { 7940 atFirstArg = false; 7941 usesPositionalArgs = FS.usesPositionalArg(); 7942 } 7943 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7944 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7945 startSpecifier, specifierLen); 7946 return false; 7947 } 7948 } 7949 7950 // Check if the field with is non-zero. 7951 const OptionalAmount &Amt = FS.getFieldWidth(); 7952 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 7953 if (Amt.getConstantAmount() == 0) { 7954 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 7955 Amt.getConstantLength()); 7956 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 7957 getLocationOfByte(Amt.getStart()), 7958 /*IsStringLocation*/true, R, 7959 FixItHint::CreateRemoval(R)); 7960 } 7961 } 7962 7963 if (!FS.consumesDataArgument()) { 7964 // FIXME: Technically specifying a precision or field width here 7965 // makes no sense. Worth issuing a warning at some point. 7966 return true; 7967 } 7968 7969 // Consume the argument. 7970 unsigned argIndex = FS.getArgIndex(); 7971 if (argIndex < NumDataArgs) { 7972 // The check to see if the argIndex is valid will come later. 7973 // We set the bit here because we may exit early from this 7974 // function if we encounter some other error. 7975 CoveredArgs.set(argIndex); 7976 } 7977 7978 // Check the length modifier is valid with the given conversion specifier. 7979 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7980 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7981 diag::warn_format_nonsensical_length); 7982 else if (!FS.hasStandardLengthModifier()) 7983 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7984 else if (!FS.hasStandardLengthConversionCombination()) 7985 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7986 diag::warn_format_non_standard_conversion_spec); 7987 7988 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7989 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7990 7991 // The remaining checks depend on the data arguments. 7992 if (HasVAListArg) 7993 return true; 7994 7995 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7996 return false; 7997 7998 // Check that the argument type matches the format specifier. 7999 const Expr *Ex = getDataArg(argIndex); 8000 if (!Ex) 8001 return true; 8002 8003 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8004 8005 if (!AT.isValid()) { 8006 return true; 8007 } 8008 8009 analyze_format_string::ArgType::MatchKind Match = 8010 AT.matchesType(S.Context, Ex->getType()); 8011 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8012 if (Match == analyze_format_string::ArgType::Match) 8013 return true; 8014 8015 ScanfSpecifier fixedFS = FS; 8016 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8017 S.getLangOpts(), S.Context); 8018 8019 unsigned Diag = 8020 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8021 : diag::warn_format_conversion_argument_type_mismatch; 8022 8023 if (Success) { 8024 // Get the fix string from the fixed format specifier. 8025 SmallString<128> buf; 8026 llvm::raw_svector_ostream os(buf); 8027 fixedFS.toString(os); 8028 8029 EmitFormatDiagnostic( 8030 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8031 << Ex->getType() << false << Ex->getSourceRange(), 8032 Ex->getBeginLoc(), 8033 /*IsStringLocation*/ false, 8034 getSpecifierRange(startSpecifier, specifierLen), 8035 FixItHint::CreateReplacement( 8036 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8037 } else { 8038 EmitFormatDiagnostic(S.PDiag(Diag) 8039 << AT.getRepresentativeTypeName(S.Context) 8040 << Ex->getType() << false << Ex->getSourceRange(), 8041 Ex->getBeginLoc(), 8042 /*IsStringLocation*/ false, 8043 getSpecifierRange(startSpecifier, specifierLen)); 8044 } 8045 8046 return true; 8047 } 8048 8049 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8050 const Expr *OrigFormatExpr, 8051 ArrayRef<const Expr *> Args, 8052 bool HasVAListArg, unsigned format_idx, 8053 unsigned firstDataArg, 8054 Sema::FormatStringType Type, 8055 bool inFunctionCall, 8056 Sema::VariadicCallType CallType, 8057 llvm::SmallBitVector &CheckedVarArgs, 8058 UncoveredArgHandler &UncoveredArg) { 8059 // CHECK: is the format string a wide literal? 8060 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8061 CheckFormatHandler::EmitFormatDiagnostic( 8062 S, inFunctionCall, Args[format_idx], 8063 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8064 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8065 return; 8066 } 8067 8068 // Str - The format string. NOTE: this is NOT null-terminated! 8069 StringRef StrRef = FExpr->getString(); 8070 const char *Str = StrRef.data(); 8071 // Account for cases where the string literal is truncated in a declaration. 8072 const ConstantArrayType *T = 8073 S.Context.getAsConstantArrayType(FExpr->getType()); 8074 assert(T && "String literal not of constant array type!"); 8075 size_t TypeSize = T->getSize().getZExtValue(); 8076 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8077 const unsigned numDataArgs = Args.size() - firstDataArg; 8078 8079 // Emit a warning if the string literal is truncated and does not contain an 8080 // embedded null character. 8081 if (TypeSize <= StrRef.size() && 8082 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8083 CheckFormatHandler::EmitFormatDiagnostic( 8084 S, inFunctionCall, Args[format_idx], 8085 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8086 FExpr->getBeginLoc(), 8087 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8088 return; 8089 } 8090 8091 // CHECK: empty format string? 8092 if (StrLen == 0 && numDataArgs > 0) { 8093 CheckFormatHandler::EmitFormatDiagnostic( 8094 S, inFunctionCall, Args[format_idx], 8095 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8096 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8097 return; 8098 } 8099 8100 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8101 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8102 Type == Sema::FST_OSTrace) { 8103 CheckPrintfHandler H( 8104 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8105 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8106 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8107 CheckedVarArgs, UncoveredArg); 8108 8109 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8110 S.getLangOpts(), 8111 S.Context.getTargetInfo(), 8112 Type == Sema::FST_FreeBSDKPrintf)) 8113 H.DoneProcessing(); 8114 } else if (Type == Sema::FST_Scanf) { 8115 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8116 numDataArgs, Str, HasVAListArg, Args, format_idx, 8117 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8118 8119 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8120 S.getLangOpts(), 8121 S.Context.getTargetInfo())) 8122 H.DoneProcessing(); 8123 } // TODO: handle other formats 8124 } 8125 8126 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8127 // Str - The format string. NOTE: this is NOT null-terminated! 8128 StringRef StrRef = FExpr->getString(); 8129 const char *Str = StrRef.data(); 8130 // Account for cases where the string literal is truncated in a declaration. 8131 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8132 assert(T && "String literal not of constant array type!"); 8133 size_t TypeSize = T->getSize().getZExtValue(); 8134 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8135 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8136 getLangOpts(), 8137 Context.getTargetInfo()); 8138 } 8139 8140 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8141 8142 // Returns the related absolute value function that is larger, of 0 if one 8143 // does not exist. 8144 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8145 switch (AbsFunction) { 8146 default: 8147 return 0; 8148 8149 case Builtin::BI__builtin_abs: 8150 return Builtin::BI__builtin_labs; 8151 case Builtin::BI__builtin_labs: 8152 return Builtin::BI__builtin_llabs; 8153 case Builtin::BI__builtin_llabs: 8154 return 0; 8155 8156 case Builtin::BI__builtin_fabsf: 8157 return Builtin::BI__builtin_fabs; 8158 case Builtin::BI__builtin_fabs: 8159 return Builtin::BI__builtin_fabsl; 8160 case Builtin::BI__builtin_fabsl: 8161 return 0; 8162 8163 case Builtin::BI__builtin_cabsf: 8164 return Builtin::BI__builtin_cabs; 8165 case Builtin::BI__builtin_cabs: 8166 return Builtin::BI__builtin_cabsl; 8167 case Builtin::BI__builtin_cabsl: 8168 return 0; 8169 8170 case Builtin::BIabs: 8171 return Builtin::BIlabs; 8172 case Builtin::BIlabs: 8173 return Builtin::BIllabs; 8174 case Builtin::BIllabs: 8175 return 0; 8176 8177 case Builtin::BIfabsf: 8178 return Builtin::BIfabs; 8179 case Builtin::BIfabs: 8180 return Builtin::BIfabsl; 8181 case Builtin::BIfabsl: 8182 return 0; 8183 8184 case Builtin::BIcabsf: 8185 return Builtin::BIcabs; 8186 case Builtin::BIcabs: 8187 return Builtin::BIcabsl; 8188 case Builtin::BIcabsl: 8189 return 0; 8190 } 8191 } 8192 8193 // Returns the argument type of the absolute value function. 8194 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8195 unsigned AbsType) { 8196 if (AbsType == 0) 8197 return QualType(); 8198 8199 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8200 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8201 if (Error != ASTContext::GE_None) 8202 return QualType(); 8203 8204 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8205 if (!FT) 8206 return QualType(); 8207 8208 if (FT->getNumParams() != 1) 8209 return QualType(); 8210 8211 return FT->getParamType(0); 8212 } 8213 8214 // Returns the best absolute value function, or zero, based on type and 8215 // current absolute value function. 8216 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8217 unsigned AbsFunctionKind) { 8218 unsigned BestKind = 0; 8219 uint64_t ArgSize = Context.getTypeSize(ArgType); 8220 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8221 Kind = getLargerAbsoluteValueFunction(Kind)) { 8222 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8223 if (Context.getTypeSize(ParamType) >= ArgSize) { 8224 if (BestKind == 0) 8225 BestKind = Kind; 8226 else if (Context.hasSameType(ParamType, ArgType)) { 8227 BestKind = Kind; 8228 break; 8229 } 8230 } 8231 } 8232 return BestKind; 8233 } 8234 8235 enum AbsoluteValueKind { 8236 AVK_Integer, 8237 AVK_Floating, 8238 AVK_Complex 8239 }; 8240 8241 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8242 if (T->isIntegralOrEnumerationType()) 8243 return AVK_Integer; 8244 if (T->isRealFloatingType()) 8245 return AVK_Floating; 8246 if (T->isAnyComplexType()) 8247 return AVK_Complex; 8248 8249 llvm_unreachable("Type not integer, floating, or complex"); 8250 } 8251 8252 // Changes the absolute value function to a different type. Preserves whether 8253 // the function is a builtin. 8254 static unsigned changeAbsFunction(unsigned AbsKind, 8255 AbsoluteValueKind ValueKind) { 8256 switch (ValueKind) { 8257 case AVK_Integer: 8258 switch (AbsKind) { 8259 default: 8260 return 0; 8261 case Builtin::BI__builtin_fabsf: 8262 case Builtin::BI__builtin_fabs: 8263 case Builtin::BI__builtin_fabsl: 8264 case Builtin::BI__builtin_cabsf: 8265 case Builtin::BI__builtin_cabs: 8266 case Builtin::BI__builtin_cabsl: 8267 return Builtin::BI__builtin_abs; 8268 case Builtin::BIfabsf: 8269 case Builtin::BIfabs: 8270 case Builtin::BIfabsl: 8271 case Builtin::BIcabsf: 8272 case Builtin::BIcabs: 8273 case Builtin::BIcabsl: 8274 return Builtin::BIabs; 8275 } 8276 case AVK_Floating: 8277 switch (AbsKind) { 8278 default: 8279 return 0; 8280 case Builtin::BI__builtin_abs: 8281 case Builtin::BI__builtin_labs: 8282 case Builtin::BI__builtin_llabs: 8283 case Builtin::BI__builtin_cabsf: 8284 case Builtin::BI__builtin_cabs: 8285 case Builtin::BI__builtin_cabsl: 8286 return Builtin::BI__builtin_fabsf; 8287 case Builtin::BIabs: 8288 case Builtin::BIlabs: 8289 case Builtin::BIllabs: 8290 case Builtin::BIcabsf: 8291 case Builtin::BIcabs: 8292 case Builtin::BIcabsl: 8293 return Builtin::BIfabsf; 8294 } 8295 case AVK_Complex: 8296 switch (AbsKind) { 8297 default: 8298 return 0; 8299 case Builtin::BI__builtin_abs: 8300 case Builtin::BI__builtin_labs: 8301 case Builtin::BI__builtin_llabs: 8302 case Builtin::BI__builtin_fabsf: 8303 case Builtin::BI__builtin_fabs: 8304 case Builtin::BI__builtin_fabsl: 8305 return Builtin::BI__builtin_cabsf; 8306 case Builtin::BIabs: 8307 case Builtin::BIlabs: 8308 case Builtin::BIllabs: 8309 case Builtin::BIfabsf: 8310 case Builtin::BIfabs: 8311 case Builtin::BIfabsl: 8312 return Builtin::BIcabsf; 8313 } 8314 } 8315 llvm_unreachable("Unable to convert function"); 8316 } 8317 8318 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8319 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8320 if (!FnInfo) 8321 return 0; 8322 8323 switch (FDecl->getBuiltinID()) { 8324 default: 8325 return 0; 8326 case Builtin::BI__builtin_abs: 8327 case Builtin::BI__builtin_fabs: 8328 case Builtin::BI__builtin_fabsf: 8329 case Builtin::BI__builtin_fabsl: 8330 case Builtin::BI__builtin_labs: 8331 case Builtin::BI__builtin_llabs: 8332 case Builtin::BI__builtin_cabs: 8333 case Builtin::BI__builtin_cabsf: 8334 case Builtin::BI__builtin_cabsl: 8335 case Builtin::BIabs: 8336 case Builtin::BIlabs: 8337 case Builtin::BIllabs: 8338 case Builtin::BIfabs: 8339 case Builtin::BIfabsf: 8340 case Builtin::BIfabsl: 8341 case Builtin::BIcabs: 8342 case Builtin::BIcabsf: 8343 case Builtin::BIcabsl: 8344 return FDecl->getBuiltinID(); 8345 } 8346 llvm_unreachable("Unknown Builtin type"); 8347 } 8348 8349 // If the replacement is valid, emit a note with replacement function. 8350 // Additionally, suggest including the proper header if not already included. 8351 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8352 unsigned AbsKind, QualType ArgType) { 8353 bool EmitHeaderHint = true; 8354 const char *HeaderName = nullptr; 8355 const char *FunctionName = nullptr; 8356 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8357 FunctionName = "std::abs"; 8358 if (ArgType->isIntegralOrEnumerationType()) { 8359 HeaderName = "cstdlib"; 8360 } else if (ArgType->isRealFloatingType()) { 8361 HeaderName = "cmath"; 8362 } else { 8363 llvm_unreachable("Invalid Type"); 8364 } 8365 8366 // Lookup all std::abs 8367 if (NamespaceDecl *Std = S.getStdNamespace()) { 8368 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8369 R.suppressDiagnostics(); 8370 S.LookupQualifiedName(R, Std); 8371 8372 for (const auto *I : R) { 8373 const FunctionDecl *FDecl = nullptr; 8374 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8375 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8376 } else { 8377 FDecl = dyn_cast<FunctionDecl>(I); 8378 } 8379 if (!FDecl) 8380 continue; 8381 8382 // Found std::abs(), check that they are the right ones. 8383 if (FDecl->getNumParams() != 1) 8384 continue; 8385 8386 // Check that the parameter type can handle the argument. 8387 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8388 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8389 S.Context.getTypeSize(ArgType) <= 8390 S.Context.getTypeSize(ParamType)) { 8391 // Found a function, don't need the header hint. 8392 EmitHeaderHint = false; 8393 break; 8394 } 8395 } 8396 } 8397 } else { 8398 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8399 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8400 8401 if (HeaderName) { 8402 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8403 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8404 R.suppressDiagnostics(); 8405 S.LookupName(R, S.getCurScope()); 8406 8407 if (R.isSingleResult()) { 8408 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8409 if (FD && FD->getBuiltinID() == AbsKind) { 8410 EmitHeaderHint = false; 8411 } else { 8412 return; 8413 } 8414 } else if (!R.empty()) { 8415 return; 8416 } 8417 } 8418 } 8419 8420 S.Diag(Loc, diag::note_replace_abs_function) 8421 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8422 8423 if (!HeaderName) 8424 return; 8425 8426 if (!EmitHeaderHint) 8427 return; 8428 8429 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8430 << FunctionName; 8431 } 8432 8433 template <std::size_t StrLen> 8434 static bool IsStdFunction(const FunctionDecl *FDecl, 8435 const char (&Str)[StrLen]) { 8436 if (!FDecl) 8437 return false; 8438 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8439 return false; 8440 if (!FDecl->isInStdNamespace()) 8441 return false; 8442 8443 return true; 8444 } 8445 8446 // Warn when using the wrong abs() function. 8447 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8448 const FunctionDecl *FDecl) { 8449 if (Call->getNumArgs() != 1) 8450 return; 8451 8452 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8453 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8454 if (AbsKind == 0 && !IsStdAbs) 8455 return; 8456 8457 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8458 QualType ParamType = Call->getArg(0)->getType(); 8459 8460 // Unsigned types cannot be negative. Suggest removing the absolute value 8461 // function call. 8462 if (ArgType->isUnsignedIntegerType()) { 8463 const char *FunctionName = 8464 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8465 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8466 Diag(Call->getExprLoc(), diag::note_remove_abs) 8467 << FunctionName 8468 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8469 return; 8470 } 8471 8472 // Taking the absolute value of a pointer is very suspicious, they probably 8473 // wanted to index into an array, dereference a pointer, call a function, etc. 8474 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8475 unsigned DiagType = 0; 8476 if (ArgType->isFunctionType()) 8477 DiagType = 1; 8478 else if (ArgType->isArrayType()) 8479 DiagType = 2; 8480 8481 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8482 return; 8483 } 8484 8485 // std::abs has overloads which prevent most of the absolute value problems 8486 // from occurring. 8487 if (IsStdAbs) 8488 return; 8489 8490 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8491 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8492 8493 // The argument and parameter are the same kind. Check if they are the right 8494 // size. 8495 if (ArgValueKind == ParamValueKind) { 8496 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8497 return; 8498 8499 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8500 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8501 << FDecl << ArgType << ParamType; 8502 8503 if (NewAbsKind == 0) 8504 return; 8505 8506 emitReplacement(*this, Call->getExprLoc(), 8507 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8508 return; 8509 } 8510 8511 // ArgValueKind != ParamValueKind 8512 // The wrong type of absolute value function was used. Attempt to find the 8513 // proper one. 8514 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8515 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8516 if (NewAbsKind == 0) 8517 return; 8518 8519 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8520 << FDecl << ParamValueKind << ArgValueKind; 8521 8522 emitReplacement(*this, Call->getExprLoc(), 8523 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8524 } 8525 8526 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8527 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8528 const FunctionDecl *FDecl) { 8529 if (!Call || !FDecl) return; 8530 8531 // Ignore template specializations and macros. 8532 if (inTemplateInstantiation()) return; 8533 if (Call->getExprLoc().isMacroID()) return; 8534 8535 // Only care about the one template argument, two function parameter std::max 8536 if (Call->getNumArgs() != 2) return; 8537 if (!IsStdFunction(FDecl, "max")) return; 8538 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8539 if (!ArgList) return; 8540 if (ArgList->size() != 1) return; 8541 8542 // Check that template type argument is unsigned integer. 8543 const auto& TA = ArgList->get(0); 8544 if (TA.getKind() != TemplateArgument::Type) return; 8545 QualType ArgType = TA.getAsType(); 8546 if (!ArgType->isUnsignedIntegerType()) return; 8547 8548 // See if either argument is a literal zero. 8549 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8550 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8551 if (!MTE) return false; 8552 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8553 if (!Num) return false; 8554 if (Num->getValue() != 0) return false; 8555 return true; 8556 }; 8557 8558 const Expr *FirstArg = Call->getArg(0); 8559 const Expr *SecondArg = Call->getArg(1); 8560 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8561 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8562 8563 // Only warn when exactly one argument is zero. 8564 if (IsFirstArgZero == IsSecondArgZero) return; 8565 8566 SourceRange FirstRange = FirstArg->getSourceRange(); 8567 SourceRange SecondRange = SecondArg->getSourceRange(); 8568 8569 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8570 8571 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8572 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8573 8574 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8575 SourceRange RemovalRange; 8576 if (IsFirstArgZero) { 8577 RemovalRange = SourceRange(FirstRange.getBegin(), 8578 SecondRange.getBegin().getLocWithOffset(-1)); 8579 } else { 8580 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8581 SecondRange.getEnd()); 8582 } 8583 8584 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8585 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8586 << FixItHint::CreateRemoval(RemovalRange); 8587 } 8588 8589 //===--- CHECK: Standard memory functions ---------------------------------===// 8590 8591 /// Takes the expression passed to the size_t parameter of functions 8592 /// such as memcmp, strncat, etc and warns if it's a comparison. 8593 /// 8594 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8595 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8596 IdentifierInfo *FnName, 8597 SourceLocation FnLoc, 8598 SourceLocation RParenLoc) { 8599 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8600 if (!Size) 8601 return false; 8602 8603 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8604 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8605 return false; 8606 8607 SourceRange SizeRange = Size->getSourceRange(); 8608 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8609 << SizeRange << FnName; 8610 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8611 << FnName 8612 << FixItHint::CreateInsertion( 8613 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8614 << FixItHint::CreateRemoval(RParenLoc); 8615 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8616 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8617 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8618 ")"); 8619 8620 return true; 8621 } 8622 8623 /// Determine whether the given type is or contains a dynamic class type 8624 /// (e.g., whether it has a vtable). 8625 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8626 bool &IsContained) { 8627 // Look through array types while ignoring qualifiers. 8628 const Type *Ty = T->getBaseElementTypeUnsafe(); 8629 IsContained = false; 8630 8631 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8632 RD = RD ? RD->getDefinition() : nullptr; 8633 if (!RD || RD->isInvalidDecl()) 8634 return nullptr; 8635 8636 if (RD->isDynamicClass()) 8637 return RD; 8638 8639 // Check all the fields. If any bases were dynamic, the class is dynamic. 8640 // It's impossible for a class to transitively contain itself by value, so 8641 // infinite recursion is impossible. 8642 for (auto *FD : RD->fields()) { 8643 bool SubContained; 8644 if (const CXXRecordDecl *ContainedRD = 8645 getContainedDynamicClass(FD->getType(), SubContained)) { 8646 IsContained = true; 8647 return ContainedRD; 8648 } 8649 } 8650 8651 return nullptr; 8652 } 8653 8654 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8655 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8656 if (Unary->getKind() == UETT_SizeOf) 8657 return Unary; 8658 return nullptr; 8659 } 8660 8661 /// If E is a sizeof expression, returns its argument expression, 8662 /// otherwise returns NULL. 8663 static const Expr *getSizeOfExprArg(const Expr *E) { 8664 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8665 if (!SizeOf->isArgumentType()) 8666 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8667 return nullptr; 8668 } 8669 8670 /// If E is a sizeof expression, returns its argument type. 8671 static QualType getSizeOfArgType(const Expr *E) { 8672 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8673 return SizeOf->getTypeOfArgument(); 8674 return QualType(); 8675 } 8676 8677 namespace { 8678 8679 struct SearchNonTrivialToInitializeField 8680 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8681 using Super = 8682 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8683 8684 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8685 8686 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8687 SourceLocation SL) { 8688 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8689 asDerived().visitArray(PDIK, AT, SL); 8690 return; 8691 } 8692 8693 Super::visitWithKind(PDIK, FT, SL); 8694 } 8695 8696 void visitARCStrong(QualType FT, SourceLocation SL) { 8697 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8698 } 8699 void visitARCWeak(QualType FT, SourceLocation SL) { 8700 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8701 } 8702 void visitStruct(QualType FT, SourceLocation SL) { 8703 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8704 visit(FD->getType(), FD->getLocation()); 8705 } 8706 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8707 const ArrayType *AT, SourceLocation SL) { 8708 visit(getContext().getBaseElementType(AT), SL); 8709 } 8710 void visitTrivial(QualType FT, SourceLocation SL) {} 8711 8712 static void diag(QualType RT, const Expr *E, Sema &S) { 8713 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 8714 } 8715 8716 ASTContext &getContext() { return S.getASTContext(); } 8717 8718 const Expr *E; 8719 Sema &S; 8720 }; 8721 8722 struct SearchNonTrivialToCopyField 8723 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 8724 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 8725 8726 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 8727 8728 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 8729 SourceLocation SL) { 8730 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8731 asDerived().visitArray(PCK, AT, SL); 8732 return; 8733 } 8734 8735 Super::visitWithKind(PCK, FT, SL); 8736 } 8737 8738 void visitARCStrong(QualType FT, SourceLocation SL) { 8739 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8740 } 8741 void visitARCWeak(QualType FT, SourceLocation SL) { 8742 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8743 } 8744 void visitStruct(QualType FT, SourceLocation SL) { 8745 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8746 visit(FD->getType(), FD->getLocation()); 8747 } 8748 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 8749 SourceLocation SL) { 8750 visit(getContext().getBaseElementType(AT), SL); 8751 } 8752 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 8753 SourceLocation SL) {} 8754 void visitTrivial(QualType FT, SourceLocation SL) {} 8755 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 8756 8757 static void diag(QualType RT, const Expr *E, Sema &S) { 8758 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 8759 } 8760 8761 ASTContext &getContext() { return S.getASTContext(); } 8762 8763 const Expr *E; 8764 Sema &S; 8765 }; 8766 8767 } 8768 8769 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 8770 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 8771 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 8772 8773 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 8774 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 8775 return false; 8776 8777 return doesExprLikelyComputeSize(BO->getLHS()) || 8778 doesExprLikelyComputeSize(BO->getRHS()); 8779 } 8780 8781 return getAsSizeOfExpr(SizeofExpr) != nullptr; 8782 } 8783 8784 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 8785 /// 8786 /// \code 8787 /// #define MACRO 0 8788 /// foo(MACRO); 8789 /// foo(0); 8790 /// \endcode 8791 /// 8792 /// This should return true for the first call to foo, but not for the second 8793 /// (regardless of whether foo is a macro or function). 8794 static bool isArgumentExpandedFromMacro(SourceManager &SM, 8795 SourceLocation CallLoc, 8796 SourceLocation ArgLoc) { 8797 if (!CallLoc.isMacroID()) 8798 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 8799 8800 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 8801 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 8802 } 8803 8804 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 8805 /// last two arguments transposed. 8806 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 8807 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 8808 return; 8809 8810 const Expr *SizeArg = 8811 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 8812 8813 auto isLiteralZero = [](const Expr *E) { 8814 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 8815 }; 8816 8817 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 8818 SourceLocation CallLoc = Call->getRParenLoc(); 8819 SourceManager &SM = S.getSourceManager(); 8820 if (isLiteralZero(SizeArg) && 8821 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 8822 8823 SourceLocation DiagLoc = SizeArg->getExprLoc(); 8824 8825 // Some platforms #define bzero to __builtin_memset. See if this is the 8826 // case, and if so, emit a better diagnostic. 8827 if (BId == Builtin::BIbzero || 8828 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 8829 CallLoc, SM, S.getLangOpts()) == "bzero")) { 8830 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 8831 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 8832 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 8833 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 8834 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 8835 } 8836 return; 8837 } 8838 8839 // If the second argument to a memset is a sizeof expression and the third 8840 // isn't, this is also likely an error. This should catch 8841 // 'memset(buf, sizeof(buf), 0xff)'. 8842 if (BId == Builtin::BImemset && 8843 doesExprLikelyComputeSize(Call->getArg(1)) && 8844 !doesExprLikelyComputeSize(Call->getArg(2))) { 8845 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 8846 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 8847 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 8848 return; 8849 } 8850 } 8851 8852 /// Check for dangerous or invalid arguments to memset(). 8853 /// 8854 /// This issues warnings on known problematic, dangerous or unspecified 8855 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 8856 /// function calls. 8857 /// 8858 /// \param Call The call expression to diagnose. 8859 void Sema::CheckMemaccessArguments(const CallExpr *Call, 8860 unsigned BId, 8861 IdentifierInfo *FnName) { 8862 assert(BId != 0); 8863 8864 // It is possible to have a non-standard definition of memset. Validate 8865 // we have enough arguments, and if not, abort further checking. 8866 unsigned ExpectedNumArgs = 8867 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 8868 if (Call->getNumArgs() < ExpectedNumArgs) 8869 return; 8870 8871 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 8872 BId == Builtin::BIstrndup ? 1 : 2); 8873 unsigned LenArg = 8874 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 8875 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 8876 8877 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 8878 Call->getBeginLoc(), Call->getRParenLoc())) 8879 return; 8880 8881 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 8882 CheckMemaccessSize(*this, BId, Call); 8883 8884 // We have special checking when the length is a sizeof expression. 8885 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 8886 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 8887 llvm::FoldingSetNodeID SizeOfArgID; 8888 8889 // Although widely used, 'bzero' is not a standard function. Be more strict 8890 // with the argument types before allowing diagnostics and only allow the 8891 // form bzero(ptr, sizeof(...)). 8892 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8893 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 8894 return; 8895 8896 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 8897 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 8898 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 8899 8900 QualType DestTy = Dest->getType(); 8901 QualType PointeeTy; 8902 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 8903 PointeeTy = DestPtrTy->getPointeeType(); 8904 8905 // Never warn about void type pointers. This can be used to suppress 8906 // false positives. 8907 if (PointeeTy->isVoidType()) 8908 continue; 8909 8910 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 8911 // actually comparing the expressions for equality. Because computing the 8912 // expression IDs can be expensive, we only do this if the diagnostic is 8913 // enabled. 8914 if (SizeOfArg && 8915 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 8916 SizeOfArg->getExprLoc())) { 8917 // We only compute IDs for expressions if the warning is enabled, and 8918 // cache the sizeof arg's ID. 8919 if (SizeOfArgID == llvm::FoldingSetNodeID()) 8920 SizeOfArg->Profile(SizeOfArgID, Context, true); 8921 llvm::FoldingSetNodeID DestID; 8922 Dest->Profile(DestID, Context, true); 8923 if (DestID == SizeOfArgID) { 8924 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 8925 // over sizeof(src) as well. 8926 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 8927 StringRef ReadableName = FnName->getName(); 8928 8929 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 8930 if (UnaryOp->getOpcode() == UO_AddrOf) 8931 ActionIdx = 1; // If its an address-of operator, just remove it. 8932 if (!PointeeTy->isIncompleteType() && 8933 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 8934 ActionIdx = 2; // If the pointee's size is sizeof(char), 8935 // suggest an explicit length. 8936 8937 // If the function is defined as a builtin macro, do not show macro 8938 // expansion. 8939 SourceLocation SL = SizeOfArg->getExprLoc(); 8940 SourceRange DSR = Dest->getSourceRange(); 8941 SourceRange SSR = SizeOfArg->getSourceRange(); 8942 SourceManager &SM = getSourceManager(); 8943 8944 if (SM.isMacroArgExpansion(SL)) { 8945 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 8946 SL = SM.getSpellingLoc(SL); 8947 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 8948 SM.getSpellingLoc(DSR.getEnd())); 8949 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 8950 SM.getSpellingLoc(SSR.getEnd())); 8951 } 8952 8953 DiagRuntimeBehavior(SL, SizeOfArg, 8954 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 8955 << ReadableName 8956 << PointeeTy 8957 << DestTy 8958 << DSR 8959 << SSR); 8960 DiagRuntimeBehavior(SL, SizeOfArg, 8961 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 8962 << ActionIdx 8963 << SSR); 8964 8965 break; 8966 } 8967 } 8968 8969 // Also check for cases where the sizeof argument is the exact same 8970 // type as the memory argument, and where it points to a user-defined 8971 // record type. 8972 if (SizeOfArgTy != QualType()) { 8973 if (PointeeTy->isRecordType() && 8974 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 8975 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 8976 PDiag(diag::warn_sizeof_pointer_type_memaccess) 8977 << FnName << SizeOfArgTy << ArgIdx 8978 << PointeeTy << Dest->getSourceRange() 8979 << LenExpr->getSourceRange()); 8980 break; 8981 } 8982 } 8983 } else if (DestTy->isArrayType()) { 8984 PointeeTy = DestTy; 8985 } 8986 8987 if (PointeeTy == QualType()) 8988 continue; 8989 8990 // Always complain about dynamic classes. 8991 bool IsContained; 8992 if (const CXXRecordDecl *ContainedRD = 8993 getContainedDynamicClass(PointeeTy, IsContained)) { 8994 8995 unsigned OperationType = 0; 8996 // "overwritten" if we're warning about the destination for any call 8997 // but memcmp; otherwise a verb appropriate to the call. 8998 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 8999 if (BId == Builtin::BImemcpy) 9000 OperationType = 1; 9001 else if(BId == Builtin::BImemmove) 9002 OperationType = 2; 9003 else if (BId == Builtin::BImemcmp) 9004 OperationType = 3; 9005 } 9006 9007 DiagRuntimeBehavior( 9008 Dest->getExprLoc(), Dest, 9009 PDiag(diag::warn_dyn_class_memaccess) 9010 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 9011 << FnName << IsContained << ContainedRD << OperationType 9012 << Call->getCallee()->getSourceRange()); 9013 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9014 BId != Builtin::BImemset) 9015 DiagRuntimeBehavior( 9016 Dest->getExprLoc(), Dest, 9017 PDiag(diag::warn_arc_object_memaccess) 9018 << ArgIdx << FnName << PointeeTy 9019 << Call->getCallee()->getSourceRange()); 9020 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9021 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9022 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9023 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9024 PDiag(diag::warn_cstruct_memaccess) 9025 << ArgIdx << FnName << PointeeTy << 0); 9026 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9027 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9028 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9029 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9030 PDiag(diag::warn_cstruct_memaccess) 9031 << ArgIdx << FnName << PointeeTy << 1); 9032 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9033 } else { 9034 continue; 9035 } 9036 } else 9037 continue; 9038 9039 DiagRuntimeBehavior( 9040 Dest->getExprLoc(), Dest, 9041 PDiag(diag::note_bad_memaccess_silence) 9042 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9043 break; 9044 } 9045 } 9046 9047 // A little helper routine: ignore addition and subtraction of integer literals. 9048 // This intentionally does not ignore all integer constant expressions because 9049 // we don't want to remove sizeof(). 9050 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9051 Ex = Ex->IgnoreParenCasts(); 9052 9053 while (true) { 9054 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9055 if (!BO || !BO->isAdditiveOp()) 9056 break; 9057 9058 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9059 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9060 9061 if (isa<IntegerLiteral>(RHS)) 9062 Ex = LHS; 9063 else if (isa<IntegerLiteral>(LHS)) 9064 Ex = RHS; 9065 else 9066 break; 9067 } 9068 9069 return Ex; 9070 } 9071 9072 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9073 ASTContext &Context) { 9074 // Only handle constant-sized or VLAs, but not flexible members. 9075 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9076 // Only issue the FIXIT for arrays of size > 1. 9077 if (CAT->getSize().getSExtValue() <= 1) 9078 return false; 9079 } else if (!Ty->isVariableArrayType()) { 9080 return false; 9081 } 9082 return true; 9083 } 9084 9085 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9086 // be the size of the source, instead of the destination. 9087 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9088 IdentifierInfo *FnName) { 9089 9090 // Don't crash if the user has the wrong number of arguments 9091 unsigned NumArgs = Call->getNumArgs(); 9092 if ((NumArgs != 3) && (NumArgs != 4)) 9093 return; 9094 9095 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9096 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9097 const Expr *CompareWithSrc = nullptr; 9098 9099 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9100 Call->getBeginLoc(), Call->getRParenLoc())) 9101 return; 9102 9103 // Look for 'strlcpy(dst, x, sizeof(x))' 9104 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9105 CompareWithSrc = Ex; 9106 else { 9107 // Look for 'strlcpy(dst, x, strlen(x))' 9108 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9109 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9110 SizeCall->getNumArgs() == 1) 9111 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9112 } 9113 } 9114 9115 if (!CompareWithSrc) 9116 return; 9117 9118 // Determine if the argument to sizeof/strlen is equal to the source 9119 // argument. In principle there's all kinds of things you could do 9120 // here, for instance creating an == expression and evaluating it with 9121 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9122 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9123 if (!SrcArgDRE) 9124 return; 9125 9126 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9127 if (!CompareWithSrcDRE || 9128 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9129 return; 9130 9131 const Expr *OriginalSizeArg = Call->getArg(2); 9132 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9133 << OriginalSizeArg->getSourceRange() << FnName; 9134 9135 // Output a FIXIT hint if the destination is an array (rather than a 9136 // pointer to an array). This could be enhanced to handle some 9137 // pointers if we know the actual size, like if DstArg is 'array+2' 9138 // we could say 'sizeof(array)-2'. 9139 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9140 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9141 return; 9142 9143 SmallString<128> sizeString; 9144 llvm::raw_svector_ostream OS(sizeString); 9145 OS << "sizeof("; 9146 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9147 OS << ")"; 9148 9149 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9150 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9151 OS.str()); 9152 } 9153 9154 /// Check if two expressions refer to the same declaration. 9155 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9156 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9157 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9158 return D1->getDecl() == D2->getDecl(); 9159 return false; 9160 } 9161 9162 static const Expr *getStrlenExprArg(const Expr *E) { 9163 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9164 const FunctionDecl *FD = CE->getDirectCallee(); 9165 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9166 return nullptr; 9167 return CE->getArg(0)->IgnoreParenCasts(); 9168 } 9169 return nullptr; 9170 } 9171 9172 // Warn on anti-patterns as the 'size' argument to strncat. 9173 // The correct size argument should look like following: 9174 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9175 void Sema::CheckStrncatArguments(const CallExpr *CE, 9176 IdentifierInfo *FnName) { 9177 // Don't crash if the user has the wrong number of arguments. 9178 if (CE->getNumArgs() < 3) 9179 return; 9180 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9181 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9182 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9183 9184 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9185 CE->getRParenLoc())) 9186 return; 9187 9188 // Identify common expressions, which are wrongly used as the size argument 9189 // to strncat and may lead to buffer overflows. 9190 unsigned PatternType = 0; 9191 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9192 // - sizeof(dst) 9193 if (referToTheSameDecl(SizeOfArg, DstArg)) 9194 PatternType = 1; 9195 // - sizeof(src) 9196 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9197 PatternType = 2; 9198 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9199 if (BE->getOpcode() == BO_Sub) { 9200 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9201 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9202 // - sizeof(dst) - strlen(dst) 9203 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9204 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9205 PatternType = 1; 9206 // - sizeof(src) - (anything) 9207 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9208 PatternType = 2; 9209 } 9210 } 9211 9212 if (PatternType == 0) 9213 return; 9214 9215 // Generate the diagnostic. 9216 SourceLocation SL = LenArg->getBeginLoc(); 9217 SourceRange SR = LenArg->getSourceRange(); 9218 SourceManager &SM = getSourceManager(); 9219 9220 // If the function is defined as a builtin macro, do not show macro expansion. 9221 if (SM.isMacroArgExpansion(SL)) { 9222 SL = SM.getSpellingLoc(SL); 9223 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9224 SM.getSpellingLoc(SR.getEnd())); 9225 } 9226 9227 // Check if the destination is an array (rather than a pointer to an array). 9228 QualType DstTy = DstArg->getType(); 9229 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9230 Context); 9231 if (!isKnownSizeArray) { 9232 if (PatternType == 1) 9233 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9234 else 9235 Diag(SL, diag::warn_strncat_src_size) << SR; 9236 return; 9237 } 9238 9239 if (PatternType == 1) 9240 Diag(SL, diag::warn_strncat_large_size) << SR; 9241 else 9242 Diag(SL, diag::warn_strncat_src_size) << SR; 9243 9244 SmallString<128> sizeString; 9245 llvm::raw_svector_ostream OS(sizeString); 9246 OS << "sizeof("; 9247 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9248 OS << ") - "; 9249 OS << "strlen("; 9250 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9251 OS << ") - 1"; 9252 9253 Diag(SL, diag::note_strncat_wrong_size) 9254 << FixItHint::CreateReplacement(SR, OS.str()); 9255 } 9256 9257 void 9258 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9259 SourceLocation ReturnLoc, 9260 bool isObjCMethod, 9261 const AttrVec *Attrs, 9262 const FunctionDecl *FD) { 9263 // Check if the return value is null but should not be. 9264 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9265 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9266 CheckNonNullExpr(*this, RetValExp)) 9267 Diag(ReturnLoc, diag::warn_null_ret) 9268 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9269 9270 // C++11 [basic.stc.dynamic.allocation]p4: 9271 // If an allocation function declared with a non-throwing 9272 // exception-specification fails to allocate storage, it shall return 9273 // a null pointer. Any other allocation function that fails to allocate 9274 // storage shall indicate failure only by throwing an exception [...] 9275 if (FD) { 9276 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9277 if (Op == OO_New || Op == OO_Array_New) { 9278 const FunctionProtoType *Proto 9279 = FD->getType()->castAs<FunctionProtoType>(); 9280 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9281 CheckNonNullExpr(*this, RetValExp)) 9282 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9283 << FD << getLangOpts().CPlusPlus11; 9284 } 9285 } 9286 } 9287 9288 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9289 9290 /// Check for comparisons of floating point operands using != and ==. 9291 /// Issue a warning if these are no self-comparisons, as they are not likely 9292 /// to do what the programmer intended. 9293 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9294 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9295 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9296 9297 // Special case: check for x == x (which is OK). 9298 // Do not emit warnings for such cases. 9299 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9300 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9301 if (DRL->getDecl() == DRR->getDecl()) 9302 return; 9303 9304 // Special case: check for comparisons against literals that can be exactly 9305 // represented by APFloat. In such cases, do not emit a warning. This 9306 // is a heuristic: often comparison against such literals are used to 9307 // detect if a value in a variable has not changed. This clearly can 9308 // lead to false negatives. 9309 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9310 if (FLL->isExact()) 9311 return; 9312 } else 9313 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9314 if (FLR->isExact()) 9315 return; 9316 9317 // Check for comparisons with builtin types. 9318 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9319 if (CL->getBuiltinCallee()) 9320 return; 9321 9322 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9323 if (CR->getBuiltinCallee()) 9324 return; 9325 9326 // Emit the diagnostic. 9327 Diag(Loc, diag::warn_floatingpoint_eq) 9328 << LHS->getSourceRange() << RHS->getSourceRange(); 9329 } 9330 9331 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9332 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9333 9334 namespace { 9335 9336 /// Structure recording the 'active' range of an integer-valued 9337 /// expression. 9338 struct IntRange { 9339 /// The number of bits active in the int. 9340 unsigned Width; 9341 9342 /// True if the int is known not to have negative values. 9343 bool NonNegative; 9344 9345 IntRange(unsigned Width, bool NonNegative) 9346 : Width(Width), NonNegative(NonNegative) {} 9347 9348 /// Returns the range of the bool type. 9349 static IntRange forBoolType() { 9350 return IntRange(1, true); 9351 } 9352 9353 /// Returns the range of an opaque value of the given integral type. 9354 static IntRange forValueOfType(ASTContext &C, QualType T) { 9355 return forValueOfCanonicalType(C, 9356 T->getCanonicalTypeInternal().getTypePtr()); 9357 } 9358 9359 /// Returns the range of an opaque value of a canonical integral type. 9360 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9361 assert(T->isCanonicalUnqualified()); 9362 9363 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9364 T = VT->getElementType().getTypePtr(); 9365 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9366 T = CT->getElementType().getTypePtr(); 9367 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9368 T = AT->getValueType().getTypePtr(); 9369 9370 if (!C.getLangOpts().CPlusPlus) { 9371 // For enum types in C code, use the underlying datatype. 9372 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9373 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9374 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9375 // For enum types in C++, use the known bit width of the enumerators. 9376 EnumDecl *Enum = ET->getDecl(); 9377 // In C++11, enums can have a fixed underlying type. Use this type to 9378 // compute the range. 9379 if (Enum->isFixed()) { 9380 return IntRange(C.getIntWidth(QualType(T, 0)), 9381 !ET->isSignedIntegerOrEnumerationType()); 9382 } 9383 9384 unsigned NumPositive = Enum->getNumPositiveBits(); 9385 unsigned NumNegative = Enum->getNumNegativeBits(); 9386 9387 if (NumNegative == 0) 9388 return IntRange(NumPositive, true/*NonNegative*/); 9389 else 9390 return IntRange(std::max(NumPositive + 1, NumNegative), 9391 false/*NonNegative*/); 9392 } 9393 9394 const BuiltinType *BT = cast<BuiltinType>(T); 9395 assert(BT->isInteger()); 9396 9397 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9398 } 9399 9400 /// Returns the "target" range of a canonical integral type, i.e. 9401 /// the range of values expressible in the type. 9402 /// 9403 /// This matches forValueOfCanonicalType except that enums have the 9404 /// full range of their type, not the range of their enumerators. 9405 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9406 assert(T->isCanonicalUnqualified()); 9407 9408 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9409 T = VT->getElementType().getTypePtr(); 9410 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9411 T = CT->getElementType().getTypePtr(); 9412 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9413 T = AT->getValueType().getTypePtr(); 9414 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9415 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9416 9417 const BuiltinType *BT = cast<BuiltinType>(T); 9418 assert(BT->isInteger()); 9419 9420 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9421 } 9422 9423 /// Returns the supremum of two ranges: i.e. their conservative merge. 9424 static IntRange join(IntRange L, IntRange R) { 9425 return IntRange(std::max(L.Width, R.Width), 9426 L.NonNegative && R.NonNegative); 9427 } 9428 9429 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9430 static IntRange meet(IntRange L, IntRange R) { 9431 return IntRange(std::min(L.Width, R.Width), 9432 L.NonNegative || R.NonNegative); 9433 } 9434 }; 9435 9436 } // namespace 9437 9438 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9439 unsigned MaxWidth) { 9440 if (value.isSigned() && value.isNegative()) 9441 return IntRange(value.getMinSignedBits(), false); 9442 9443 if (value.getBitWidth() > MaxWidth) 9444 value = value.trunc(MaxWidth); 9445 9446 // isNonNegative() just checks the sign bit without considering 9447 // signedness. 9448 return IntRange(value.getActiveBits(), true); 9449 } 9450 9451 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9452 unsigned MaxWidth) { 9453 if (result.isInt()) 9454 return GetValueRange(C, result.getInt(), MaxWidth); 9455 9456 if (result.isVector()) { 9457 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9458 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9459 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9460 R = IntRange::join(R, El); 9461 } 9462 return R; 9463 } 9464 9465 if (result.isComplexInt()) { 9466 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9467 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9468 return IntRange::join(R, I); 9469 } 9470 9471 // This can happen with lossless casts to intptr_t of "based" lvalues. 9472 // Assume it might use arbitrary bits. 9473 // FIXME: The only reason we need to pass the type in here is to get 9474 // the sign right on this one case. It would be nice if APValue 9475 // preserved this. 9476 assert(result.isLValue() || result.isAddrLabelDiff()); 9477 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9478 } 9479 9480 static QualType GetExprType(const Expr *E) { 9481 QualType Ty = E->getType(); 9482 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9483 Ty = AtomicRHS->getValueType(); 9484 return Ty; 9485 } 9486 9487 /// Pseudo-evaluate the given integer expression, estimating the 9488 /// range of values it might take. 9489 /// 9490 /// \param MaxWidth - the width to which the value will be truncated 9491 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 9492 E = E->IgnoreParens(); 9493 9494 // Try a full evaluation first. 9495 Expr::EvalResult result; 9496 if (E->EvaluateAsRValue(result, C)) 9497 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9498 9499 // I think we only want to look through implicit casts here; if the 9500 // user has an explicit widening cast, we should treat the value as 9501 // being of the new, wider type. 9502 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9503 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9504 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 9505 9506 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9507 9508 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9509 CE->getCastKind() == CK_BooleanToSignedIntegral; 9510 9511 // Assume that non-integer casts can span the full range of the type. 9512 if (!isIntegerCast) 9513 return OutputTypeRange; 9514 9515 IntRange SubRange 9516 = GetExprRange(C, CE->getSubExpr(), 9517 std::min(MaxWidth, OutputTypeRange.Width)); 9518 9519 // Bail out if the subexpr's range is as wide as the cast type. 9520 if (SubRange.Width >= OutputTypeRange.Width) 9521 return OutputTypeRange; 9522 9523 // Otherwise, we take the smaller width, and we're non-negative if 9524 // either the output type or the subexpr is. 9525 return IntRange(SubRange.Width, 9526 SubRange.NonNegative || OutputTypeRange.NonNegative); 9527 } 9528 9529 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9530 // If we can fold the condition, just take that operand. 9531 bool CondResult; 9532 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9533 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9534 : CO->getFalseExpr(), 9535 MaxWidth); 9536 9537 // Otherwise, conservatively merge. 9538 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9539 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9540 return IntRange::join(L, R); 9541 } 9542 9543 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9544 switch (BO->getOpcode()) { 9545 case BO_Cmp: 9546 llvm_unreachable("builtin <=> should have class type"); 9547 9548 // Boolean-valued operations are single-bit and positive. 9549 case BO_LAnd: 9550 case BO_LOr: 9551 case BO_LT: 9552 case BO_GT: 9553 case BO_LE: 9554 case BO_GE: 9555 case BO_EQ: 9556 case BO_NE: 9557 return IntRange::forBoolType(); 9558 9559 // The type of the assignments is the type of the LHS, so the RHS 9560 // is not necessarily the same type. 9561 case BO_MulAssign: 9562 case BO_DivAssign: 9563 case BO_RemAssign: 9564 case BO_AddAssign: 9565 case BO_SubAssign: 9566 case BO_XorAssign: 9567 case BO_OrAssign: 9568 // TODO: bitfields? 9569 return IntRange::forValueOfType(C, GetExprType(E)); 9570 9571 // Simple assignments just pass through the RHS, which will have 9572 // been coerced to the LHS type. 9573 case BO_Assign: 9574 // TODO: bitfields? 9575 return GetExprRange(C, BO->getRHS(), MaxWidth); 9576 9577 // Operations with opaque sources are black-listed. 9578 case BO_PtrMemD: 9579 case BO_PtrMemI: 9580 return IntRange::forValueOfType(C, GetExprType(E)); 9581 9582 // Bitwise-and uses the *infinum* of the two source ranges. 9583 case BO_And: 9584 case BO_AndAssign: 9585 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9586 GetExprRange(C, BO->getRHS(), MaxWidth)); 9587 9588 // Left shift gets black-listed based on a judgement call. 9589 case BO_Shl: 9590 // ...except that we want to treat '1 << (blah)' as logically 9591 // positive. It's an important idiom. 9592 if (IntegerLiteral *I 9593 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9594 if (I->getValue() == 1) { 9595 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9596 return IntRange(R.Width, /*NonNegative*/ true); 9597 } 9598 } 9599 LLVM_FALLTHROUGH; 9600 9601 case BO_ShlAssign: 9602 return IntRange::forValueOfType(C, GetExprType(E)); 9603 9604 // Right shift by a constant can narrow its left argument. 9605 case BO_Shr: 9606 case BO_ShrAssign: { 9607 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9608 9609 // If the shift amount is a positive constant, drop the width by 9610 // that much. 9611 llvm::APSInt shift; 9612 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9613 shift.isNonNegative()) { 9614 unsigned zext = shift.getZExtValue(); 9615 if (zext >= L.Width) 9616 L.Width = (L.NonNegative ? 0 : 1); 9617 else 9618 L.Width -= zext; 9619 } 9620 9621 return L; 9622 } 9623 9624 // Comma acts as its right operand. 9625 case BO_Comma: 9626 return GetExprRange(C, BO->getRHS(), MaxWidth); 9627 9628 // Black-list pointer subtractions. 9629 case BO_Sub: 9630 if (BO->getLHS()->getType()->isPointerType()) 9631 return IntRange::forValueOfType(C, GetExprType(E)); 9632 break; 9633 9634 // The width of a division result is mostly determined by the size 9635 // of the LHS. 9636 case BO_Div: { 9637 // Don't 'pre-truncate' the operands. 9638 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9639 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9640 9641 // If the divisor is constant, use that. 9642 llvm::APSInt divisor; 9643 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9644 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9645 if (log2 >= L.Width) 9646 L.Width = (L.NonNegative ? 0 : 1); 9647 else 9648 L.Width = std::min(L.Width - log2, MaxWidth); 9649 return L; 9650 } 9651 9652 // Otherwise, just use the LHS's width. 9653 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9654 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9655 } 9656 9657 // The result of a remainder can't be larger than the result of 9658 // either side. 9659 case BO_Rem: { 9660 // Don't 'pre-truncate' the operands. 9661 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9662 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9663 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9664 9665 IntRange meet = IntRange::meet(L, R); 9666 meet.Width = std::min(meet.Width, MaxWidth); 9667 return meet; 9668 } 9669 9670 // The default behavior is okay for these. 9671 case BO_Mul: 9672 case BO_Add: 9673 case BO_Xor: 9674 case BO_Or: 9675 break; 9676 } 9677 9678 // The default case is to treat the operation as if it were closed 9679 // on the narrowest type that encompasses both operands. 9680 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9681 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9682 return IntRange::join(L, R); 9683 } 9684 9685 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9686 switch (UO->getOpcode()) { 9687 // Boolean-valued operations are white-listed. 9688 case UO_LNot: 9689 return IntRange::forBoolType(); 9690 9691 // Operations with opaque sources are black-listed. 9692 case UO_Deref: 9693 case UO_AddrOf: // should be impossible 9694 return IntRange::forValueOfType(C, GetExprType(E)); 9695 9696 default: 9697 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9698 } 9699 } 9700 9701 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9702 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9703 9704 if (const auto *BitField = E->getSourceBitField()) 9705 return IntRange(BitField->getBitWidthValue(C), 9706 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9707 9708 return IntRange::forValueOfType(C, GetExprType(E)); 9709 } 9710 9711 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9712 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9713 } 9714 9715 /// Checks whether the given value, which currently has the given 9716 /// source semantics, has the same value when coerced through the 9717 /// target semantics. 9718 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9719 const llvm::fltSemantics &Src, 9720 const llvm::fltSemantics &Tgt) { 9721 llvm::APFloat truncated = value; 9722 9723 bool ignored; 9724 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9725 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9726 9727 return truncated.bitwiseIsEqual(value); 9728 } 9729 9730 /// Checks whether the given value, which currently has the given 9731 /// source semantics, has the same value when coerced through the 9732 /// target semantics. 9733 /// 9734 /// The value might be a vector of floats (or a complex number). 9735 static bool IsSameFloatAfterCast(const APValue &value, 9736 const llvm::fltSemantics &Src, 9737 const llvm::fltSemantics &Tgt) { 9738 if (value.isFloat()) 9739 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9740 9741 if (value.isVector()) { 9742 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9743 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9744 return false; 9745 return true; 9746 } 9747 9748 assert(value.isComplexFloat()); 9749 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9750 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9751 } 9752 9753 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9754 9755 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9756 // Suppress cases where we are comparing against an enum constant. 9757 if (const DeclRefExpr *DR = 9758 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9759 if (isa<EnumConstantDecl>(DR->getDecl())) 9760 return true; 9761 9762 // Suppress cases where the '0' value is expanded from a macro. 9763 if (E->getBeginLoc().isMacroID()) 9764 return true; 9765 9766 return false; 9767 } 9768 9769 static bool isKnownToHaveUnsignedValue(Expr *E) { 9770 return E->getType()->isIntegerType() && 9771 (!E->getType()->isSignedIntegerType() || 9772 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9773 } 9774 9775 namespace { 9776 /// The promoted range of values of a type. In general this has the 9777 /// following structure: 9778 /// 9779 /// |-----------| . . . |-----------| 9780 /// ^ ^ ^ ^ 9781 /// Min HoleMin HoleMax Max 9782 /// 9783 /// ... where there is only a hole if a signed type is promoted to unsigned 9784 /// (in which case Min and Max are the smallest and largest representable 9785 /// values). 9786 struct PromotedRange { 9787 // Min, or HoleMax if there is a hole. 9788 llvm::APSInt PromotedMin; 9789 // Max, or HoleMin if there is a hole. 9790 llvm::APSInt PromotedMax; 9791 9792 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9793 if (R.Width == 0) 9794 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9795 else if (R.Width >= BitWidth && !Unsigned) { 9796 // Promotion made the type *narrower*. This happens when promoting 9797 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9798 // Treat all values of 'signed int' as being in range for now. 9799 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9800 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9801 } else { 9802 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9803 .extOrTrunc(BitWidth); 9804 PromotedMin.setIsUnsigned(Unsigned); 9805 9806 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9807 .extOrTrunc(BitWidth); 9808 PromotedMax.setIsUnsigned(Unsigned); 9809 } 9810 } 9811 9812 // Determine whether this range is contiguous (has no hole). 9813 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9814 9815 // Where a constant value is within the range. 9816 enum ComparisonResult { 9817 LT = 0x1, 9818 LE = 0x2, 9819 GT = 0x4, 9820 GE = 0x8, 9821 EQ = 0x10, 9822 NE = 0x20, 9823 InRangeFlag = 0x40, 9824 9825 Less = LE | LT | NE, 9826 Min = LE | InRangeFlag, 9827 InRange = InRangeFlag, 9828 Max = GE | InRangeFlag, 9829 Greater = GE | GT | NE, 9830 9831 OnlyValue = LE | GE | EQ | InRangeFlag, 9832 InHole = NE 9833 }; 9834 9835 ComparisonResult compare(const llvm::APSInt &Value) const { 9836 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 9837 Value.isUnsigned() == PromotedMin.isUnsigned()); 9838 if (!isContiguous()) { 9839 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 9840 if (Value.isMinValue()) return Min; 9841 if (Value.isMaxValue()) return Max; 9842 if (Value >= PromotedMin) return InRange; 9843 if (Value <= PromotedMax) return InRange; 9844 return InHole; 9845 } 9846 9847 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 9848 case -1: return Less; 9849 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 9850 case 1: 9851 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 9852 case -1: return InRange; 9853 case 0: return Max; 9854 case 1: return Greater; 9855 } 9856 } 9857 9858 llvm_unreachable("impossible compare result"); 9859 } 9860 9861 static llvm::Optional<StringRef> 9862 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 9863 if (Op == BO_Cmp) { 9864 ComparisonResult LTFlag = LT, GTFlag = GT; 9865 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 9866 9867 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 9868 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 9869 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 9870 return llvm::None; 9871 } 9872 9873 ComparisonResult TrueFlag, FalseFlag; 9874 if (Op == BO_EQ) { 9875 TrueFlag = EQ; 9876 FalseFlag = NE; 9877 } else if (Op == BO_NE) { 9878 TrueFlag = NE; 9879 FalseFlag = EQ; 9880 } else { 9881 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 9882 TrueFlag = LT; 9883 FalseFlag = GE; 9884 } else { 9885 TrueFlag = GT; 9886 FalseFlag = LE; 9887 } 9888 if (Op == BO_GE || Op == BO_LE) 9889 std::swap(TrueFlag, FalseFlag); 9890 } 9891 if (R & TrueFlag) 9892 return StringRef("true"); 9893 if (R & FalseFlag) 9894 return StringRef("false"); 9895 return llvm::None; 9896 } 9897 }; 9898 } 9899 9900 static bool HasEnumType(Expr *E) { 9901 // Strip off implicit integral promotions. 9902 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9903 if (ICE->getCastKind() != CK_IntegralCast && 9904 ICE->getCastKind() != CK_NoOp) 9905 break; 9906 E = ICE->getSubExpr(); 9907 } 9908 9909 return E->getType()->isEnumeralType(); 9910 } 9911 9912 static int classifyConstantValue(Expr *Constant) { 9913 // The values of this enumeration are used in the diagnostics 9914 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 9915 enum ConstantValueKind { 9916 Miscellaneous = 0, 9917 LiteralTrue, 9918 LiteralFalse 9919 }; 9920 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 9921 return BL->getValue() ? ConstantValueKind::LiteralTrue 9922 : ConstantValueKind::LiteralFalse; 9923 return ConstantValueKind::Miscellaneous; 9924 } 9925 9926 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 9927 Expr *Constant, Expr *Other, 9928 const llvm::APSInt &Value, 9929 bool RhsConstant) { 9930 if (S.inTemplateInstantiation()) 9931 return false; 9932 9933 Expr *OriginalOther = Other; 9934 9935 Constant = Constant->IgnoreParenImpCasts(); 9936 Other = Other->IgnoreParenImpCasts(); 9937 9938 // Suppress warnings on tautological comparisons between values of the same 9939 // enumeration type. There are only two ways we could warn on this: 9940 // - If the constant is outside the range of representable values of 9941 // the enumeration. In such a case, we should warn about the cast 9942 // to enumeration type, not about the comparison. 9943 // - If the constant is the maximum / minimum in-range value. For an 9944 // enumeratin type, such comparisons can be meaningful and useful. 9945 if (Constant->getType()->isEnumeralType() && 9946 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 9947 return false; 9948 9949 // TODO: Investigate using GetExprRange() to get tighter bounds 9950 // on the bit ranges. 9951 QualType OtherT = Other->getType(); 9952 if (const auto *AT = OtherT->getAs<AtomicType>()) 9953 OtherT = AT->getValueType(); 9954 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 9955 9956 // Whether we're treating Other as being a bool because of the form of 9957 // expression despite it having another type (typically 'int' in C). 9958 bool OtherIsBooleanDespiteType = 9959 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 9960 if (OtherIsBooleanDespiteType) 9961 OtherRange = IntRange::forBoolType(); 9962 9963 // Determine the promoted range of the other type and see if a comparison of 9964 // the constant against that range is tautological. 9965 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 9966 Value.isUnsigned()); 9967 auto Cmp = OtherPromotedRange.compare(Value); 9968 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 9969 if (!Result) 9970 return false; 9971 9972 // Suppress the diagnostic for an in-range comparison if the constant comes 9973 // from a macro or enumerator. We don't want to diagnose 9974 // 9975 // some_long_value <= INT_MAX 9976 // 9977 // when sizeof(int) == sizeof(long). 9978 bool InRange = Cmp & PromotedRange::InRangeFlag; 9979 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 9980 return false; 9981 9982 // If this is a comparison to an enum constant, include that 9983 // constant in the diagnostic. 9984 const EnumConstantDecl *ED = nullptr; 9985 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 9986 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 9987 9988 // Should be enough for uint128 (39 decimal digits) 9989 SmallString<64> PrettySourceValue; 9990 llvm::raw_svector_ostream OS(PrettySourceValue); 9991 if (ED) 9992 OS << '\'' << *ED << "' (" << Value << ")"; 9993 else 9994 OS << Value; 9995 9996 // FIXME: We use a somewhat different formatting for the in-range cases and 9997 // cases involving boolean values for historical reasons. We should pick a 9998 // consistent way of presenting these diagnostics. 9999 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10000 S.DiagRuntimeBehavior( 10001 E->getOperatorLoc(), E, 10002 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10003 : diag::warn_tautological_bool_compare) 10004 << OS.str() << classifyConstantValue(Constant) 10005 << OtherT << OtherIsBooleanDespiteType << *Result 10006 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10007 } else { 10008 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10009 ? (HasEnumType(OriginalOther) 10010 ? diag::warn_unsigned_enum_always_true_comparison 10011 : diag::warn_unsigned_always_true_comparison) 10012 : diag::warn_tautological_constant_compare; 10013 10014 S.Diag(E->getOperatorLoc(), Diag) 10015 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10016 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10017 } 10018 10019 return true; 10020 } 10021 10022 /// Analyze the operands of the given comparison. Implements the 10023 /// fallback case from AnalyzeComparison. 10024 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10025 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10026 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10027 } 10028 10029 /// Implements -Wsign-compare. 10030 /// 10031 /// \param E the binary operator to check for warnings 10032 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10033 // The type the comparison is being performed in. 10034 QualType T = E->getLHS()->getType(); 10035 10036 // Only analyze comparison operators where both sides have been converted to 10037 // the same type. 10038 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10039 return AnalyzeImpConvsInComparison(S, E); 10040 10041 // Don't analyze value-dependent comparisons directly. 10042 if (E->isValueDependent()) 10043 return AnalyzeImpConvsInComparison(S, E); 10044 10045 Expr *LHS = E->getLHS(); 10046 Expr *RHS = E->getRHS(); 10047 10048 if (T->isIntegralType(S.Context)) { 10049 llvm::APSInt RHSValue; 10050 llvm::APSInt LHSValue; 10051 10052 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10053 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10054 10055 // We don't care about expressions whose result is a constant. 10056 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10057 return AnalyzeImpConvsInComparison(S, E); 10058 10059 // We only care about expressions where just one side is literal 10060 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10061 // Is the constant on the RHS or LHS? 10062 const bool RhsConstant = IsRHSIntegralLiteral; 10063 Expr *Const = RhsConstant ? RHS : LHS; 10064 Expr *Other = RhsConstant ? LHS : RHS; 10065 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10066 10067 // Check whether an integer constant comparison results in a value 10068 // of 'true' or 'false'. 10069 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10070 return AnalyzeImpConvsInComparison(S, E); 10071 } 10072 } 10073 10074 if (!T->hasUnsignedIntegerRepresentation()) { 10075 // We don't do anything special if this isn't an unsigned integral 10076 // comparison: we're only interested in integral comparisons, and 10077 // signed comparisons only happen in cases we don't care to warn about. 10078 return AnalyzeImpConvsInComparison(S, E); 10079 } 10080 10081 LHS = LHS->IgnoreParenImpCasts(); 10082 RHS = RHS->IgnoreParenImpCasts(); 10083 10084 if (!S.getLangOpts().CPlusPlus) { 10085 // Avoid warning about comparison of integers with different signs when 10086 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10087 // the type of `E`. 10088 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10089 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10090 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10091 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10092 } 10093 10094 // Check to see if one of the (unmodified) operands is of different 10095 // signedness. 10096 Expr *signedOperand, *unsignedOperand; 10097 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10098 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10099 "unsigned comparison between two signed integer expressions?"); 10100 signedOperand = LHS; 10101 unsignedOperand = RHS; 10102 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10103 signedOperand = RHS; 10104 unsignedOperand = LHS; 10105 } else { 10106 return AnalyzeImpConvsInComparison(S, E); 10107 } 10108 10109 // Otherwise, calculate the effective range of the signed operand. 10110 IntRange signedRange = GetExprRange(S.Context, signedOperand); 10111 10112 // Go ahead and analyze implicit conversions in the operands. Note 10113 // that we skip the implicit conversions on both sides. 10114 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10115 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10116 10117 // If the signed range is non-negative, -Wsign-compare won't fire. 10118 if (signedRange.NonNegative) 10119 return; 10120 10121 // For (in)equality comparisons, if the unsigned operand is a 10122 // constant which cannot collide with a overflowed signed operand, 10123 // then reinterpreting the signed operand as unsigned will not 10124 // change the result of the comparison. 10125 if (E->isEqualityOp()) { 10126 unsigned comparisonWidth = S.Context.getIntWidth(T); 10127 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 10128 10129 // We should never be unable to prove that the unsigned operand is 10130 // non-negative. 10131 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10132 10133 if (unsignedRange.Width < comparisonWidth) 10134 return; 10135 } 10136 10137 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10138 S.PDiag(diag::warn_mixed_sign_comparison) 10139 << LHS->getType() << RHS->getType() 10140 << LHS->getSourceRange() << RHS->getSourceRange()); 10141 } 10142 10143 /// Analyzes an attempt to assign the given value to a bitfield. 10144 /// 10145 /// Returns true if there was something fishy about the attempt. 10146 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10147 SourceLocation InitLoc) { 10148 assert(Bitfield->isBitField()); 10149 if (Bitfield->isInvalidDecl()) 10150 return false; 10151 10152 // White-list bool bitfields. 10153 QualType BitfieldType = Bitfield->getType(); 10154 if (BitfieldType->isBooleanType()) 10155 return false; 10156 10157 if (BitfieldType->isEnumeralType()) { 10158 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10159 // If the underlying enum type was not explicitly specified as an unsigned 10160 // type and the enum contain only positive values, MSVC++ will cause an 10161 // inconsistency by storing this as a signed type. 10162 if (S.getLangOpts().CPlusPlus11 && 10163 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10164 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10165 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10166 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10167 << BitfieldEnumDecl->getNameAsString(); 10168 } 10169 } 10170 10171 if (Bitfield->getType()->isBooleanType()) 10172 return false; 10173 10174 // Ignore value- or type-dependent expressions. 10175 if (Bitfield->getBitWidth()->isValueDependent() || 10176 Bitfield->getBitWidth()->isTypeDependent() || 10177 Init->isValueDependent() || 10178 Init->isTypeDependent()) 10179 return false; 10180 10181 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10182 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10183 10184 llvm::APSInt Value; 10185 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 10186 Expr::SE_AllowSideEffects)) { 10187 // The RHS is not constant. If the RHS has an enum type, make sure the 10188 // bitfield is wide enough to hold all the values of the enum without 10189 // truncation. 10190 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10191 EnumDecl *ED = EnumTy->getDecl(); 10192 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10193 10194 // Enum types are implicitly signed on Windows, so check if there are any 10195 // negative enumerators to see if the enum was intended to be signed or 10196 // not. 10197 bool SignedEnum = ED->getNumNegativeBits() > 0; 10198 10199 // Check for surprising sign changes when assigning enum values to a 10200 // bitfield of different signedness. If the bitfield is signed and we 10201 // have exactly the right number of bits to store this unsigned enum, 10202 // suggest changing the enum to an unsigned type. This typically happens 10203 // on Windows where unfixed enums always use an underlying type of 'int'. 10204 unsigned DiagID = 0; 10205 if (SignedEnum && !SignedBitfield) { 10206 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10207 } else if (SignedBitfield && !SignedEnum && 10208 ED->getNumPositiveBits() == FieldWidth) { 10209 DiagID = diag::warn_signed_bitfield_enum_conversion; 10210 } 10211 10212 if (DiagID) { 10213 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10214 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10215 SourceRange TypeRange = 10216 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10217 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10218 << SignedEnum << TypeRange; 10219 } 10220 10221 // Compute the required bitwidth. If the enum has negative values, we need 10222 // one more bit than the normal number of positive bits to represent the 10223 // sign bit. 10224 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10225 ED->getNumNegativeBits()) 10226 : ED->getNumPositiveBits(); 10227 10228 // Check the bitwidth. 10229 if (BitsNeeded > FieldWidth) { 10230 Expr *WidthExpr = Bitfield->getBitWidth(); 10231 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10232 << Bitfield << ED; 10233 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10234 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10235 } 10236 } 10237 10238 return false; 10239 } 10240 10241 unsigned OriginalWidth = Value.getBitWidth(); 10242 10243 if (!Value.isSigned() || Value.isNegative()) 10244 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10245 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10246 OriginalWidth = Value.getMinSignedBits(); 10247 10248 if (OriginalWidth <= FieldWidth) 10249 return false; 10250 10251 // Compute the value which the bitfield will contain. 10252 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10253 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10254 10255 // Check whether the stored value is equal to the original value. 10256 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10257 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10258 return false; 10259 10260 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10261 // therefore don't strictly fit into a signed bitfield of width 1. 10262 if (FieldWidth == 1 && Value == 1) 10263 return false; 10264 10265 std::string PrettyValue = Value.toString(10); 10266 std::string PrettyTrunc = TruncatedValue.toString(10); 10267 10268 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10269 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10270 << Init->getSourceRange(); 10271 10272 return true; 10273 } 10274 10275 /// Analyze the given simple or compound assignment for warning-worthy 10276 /// operations. 10277 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10278 // Just recurse on the LHS. 10279 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10280 10281 // We want to recurse on the RHS as normal unless we're assigning to 10282 // a bitfield. 10283 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10284 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10285 E->getOperatorLoc())) { 10286 // Recurse, ignoring any implicit conversions on the RHS. 10287 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10288 E->getOperatorLoc()); 10289 } 10290 } 10291 10292 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10293 10294 // Diagnose implicitly sequentially-consistent atomic assignment. 10295 if (E->getLHS()->getType()->isAtomicType()) 10296 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10297 } 10298 10299 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10300 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10301 SourceLocation CContext, unsigned diag, 10302 bool pruneControlFlow = false) { 10303 if (pruneControlFlow) { 10304 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10305 S.PDiag(diag) 10306 << SourceType << T << E->getSourceRange() 10307 << SourceRange(CContext)); 10308 return; 10309 } 10310 S.Diag(E->getExprLoc(), diag) 10311 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10312 } 10313 10314 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10315 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10316 SourceLocation CContext, 10317 unsigned diag, bool pruneControlFlow = false) { 10318 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10319 } 10320 10321 /// Diagnose an implicit cast from a floating point value to an integer value. 10322 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10323 SourceLocation CContext) { 10324 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10325 const bool PruneWarnings = S.inTemplateInstantiation(); 10326 10327 Expr *InnerE = E->IgnoreParenImpCasts(); 10328 // We also want to warn on, e.g., "int i = -1.234" 10329 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10330 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10331 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10332 10333 const bool IsLiteral = 10334 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10335 10336 llvm::APFloat Value(0.0); 10337 bool IsConstant = 10338 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10339 if (!IsConstant) { 10340 return DiagnoseImpCast(S, E, T, CContext, 10341 diag::warn_impcast_float_integer, PruneWarnings); 10342 } 10343 10344 bool isExact = false; 10345 10346 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10347 T->hasUnsignedIntegerRepresentation()); 10348 llvm::APFloat::opStatus Result = Value.convertToInteger( 10349 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10350 10351 if (Result == llvm::APFloat::opOK && isExact) { 10352 if (IsLiteral) return; 10353 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10354 PruneWarnings); 10355 } 10356 10357 // Conversion of a floating-point value to a non-bool integer where the 10358 // integral part cannot be represented by the integer type is undefined. 10359 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10360 return DiagnoseImpCast( 10361 S, E, T, CContext, 10362 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10363 : diag::warn_impcast_float_to_integer_out_of_range, 10364 PruneWarnings); 10365 10366 unsigned DiagID = 0; 10367 if (IsLiteral) { 10368 // Warn on floating point literal to integer. 10369 DiagID = diag::warn_impcast_literal_float_to_integer; 10370 } else if (IntegerValue == 0) { 10371 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10372 return DiagnoseImpCast(S, E, T, CContext, 10373 diag::warn_impcast_float_integer, PruneWarnings); 10374 } 10375 // Warn on non-zero to zero conversion. 10376 DiagID = diag::warn_impcast_float_to_integer_zero; 10377 } else { 10378 if (IntegerValue.isUnsigned()) { 10379 if (!IntegerValue.isMaxValue()) { 10380 return DiagnoseImpCast(S, E, T, CContext, 10381 diag::warn_impcast_float_integer, PruneWarnings); 10382 } 10383 } else { // IntegerValue.isSigned() 10384 if (!IntegerValue.isMaxSignedValue() && 10385 !IntegerValue.isMinSignedValue()) { 10386 return DiagnoseImpCast(S, E, T, CContext, 10387 diag::warn_impcast_float_integer, PruneWarnings); 10388 } 10389 } 10390 // Warn on evaluatable floating point expression to integer conversion. 10391 DiagID = diag::warn_impcast_float_to_integer; 10392 } 10393 10394 // FIXME: Force the precision of the source value down so we don't print 10395 // digits which are usually useless (we don't really care here if we 10396 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10397 // would automatically print the shortest representation, but it's a bit 10398 // tricky to implement. 10399 SmallString<16> PrettySourceValue; 10400 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10401 precision = (precision * 59 + 195) / 196; 10402 Value.toString(PrettySourceValue, precision); 10403 10404 SmallString<16> PrettyTargetValue; 10405 if (IsBool) 10406 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10407 else 10408 IntegerValue.toString(PrettyTargetValue); 10409 10410 if (PruneWarnings) { 10411 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10412 S.PDiag(DiagID) 10413 << E->getType() << T.getUnqualifiedType() 10414 << PrettySourceValue << PrettyTargetValue 10415 << E->getSourceRange() << SourceRange(CContext)); 10416 } else { 10417 S.Diag(E->getExprLoc(), DiagID) 10418 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10419 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10420 } 10421 } 10422 10423 /// Analyze the given compound assignment for the possible losing of 10424 /// floating-point precision. 10425 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10426 assert(isa<CompoundAssignOperator>(E) && 10427 "Must be compound assignment operation"); 10428 // Recurse on the LHS and RHS in here 10429 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10430 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10431 10432 if (E->getLHS()->getType()->isAtomicType()) 10433 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10434 10435 // Now check the outermost expression 10436 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10437 const auto *RBT = cast<CompoundAssignOperator>(E) 10438 ->getComputationResultType() 10439 ->getAs<BuiltinType>(); 10440 10441 // The below checks assume source is floating point. 10442 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10443 10444 // If source is floating point but target is not. 10445 if (!ResultBT->isFloatingPoint()) 10446 return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(), 10447 E->getExprLoc()); 10448 10449 // If both source and target are floating points. 10450 // Builtin FP kinds are ordered by increasing FP rank. 10451 if (ResultBT->getKind() < RBT->getKind() && 10452 // We don't want to warn for system macro. 10453 !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10454 // warn about dropping FP rank. 10455 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10456 diag::warn_impcast_float_result_precision); 10457 } 10458 10459 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10460 IntRange Range) { 10461 if (!Range.Width) return "0"; 10462 10463 llvm::APSInt ValueInRange = Value; 10464 ValueInRange.setIsSigned(!Range.NonNegative); 10465 ValueInRange = ValueInRange.trunc(Range.Width); 10466 return ValueInRange.toString(10); 10467 } 10468 10469 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10470 if (!isa<ImplicitCastExpr>(Ex)) 10471 return false; 10472 10473 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10474 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10475 const Type *Source = 10476 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10477 if (Target->isDependentType()) 10478 return false; 10479 10480 const BuiltinType *FloatCandidateBT = 10481 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10482 const Type *BoolCandidateType = ToBool ? Target : Source; 10483 10484 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10485 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10486 } 10487 10488 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10489 SourceLocation CC) { 10490 unsigned NumArgs = TheCall->getNumArgs(); 10491 for (unsigned i = 0; i < NumArgs; ++i) { 10492 Expr *CurrA = TheCall->getArg(i); 10493 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10494 continue; 10495 10496 bool IsSwapped = ((i > 0) && 10497 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10498 IsSwapped |= ((i < (NumArgs - 1)) && 10499 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10500 if (IsSwapped) { 10501 // Warn on this floating-point to bool conversion. 10502 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10503 CurrA->getType(), CC, 10504 diag::warn_impcast_floating_point_to_bool); 10505 } 10506 } 10507 } 10508 10509 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10510 SourceLocation CC) { 10511 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10512 E->getExprLoc())) 10513 return; 10514 10515 // Don't warn on functions which have return type nullptr_t. 10516 if (isa<CallExpr>(E)) 10517 return; 10518 10519 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10520 const Expr::NullPointerConstantKind NullKind = 10521 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10522 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10523 return; 10524 10525 // Return if target type is a safe conversion. 10526 if (T->isAnyPointerType() || T->isBlockPointerType() || 10527 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10528 return; 10529 10530 SourceLocation Loc = E->getSourceRange().getBegin(); 10531 10532 // Venture through the macro stacks to get to the source of macro arguments. 10533 // The new location is a better location than the complete location that was 10534 // passed in. 10535 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10536 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10537 10538 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10539 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10540 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10541 Loc, S.SourceMgr, S.getLangOpts()); 10542 if (MacroName == "NULL") 10543 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10544 } 10545 10546 // Only warn if the null and context location are in the same macro expansion. 10547 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10548 return; 10549 10550 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10551 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10552 << FixItHint::CreateReplacement(Loc, 10553 S.getFixItZeroLiteralForType(T, Loc)); 10554 } 10555 10556 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10557 ObjCArrayLiteral *ArrayLiteral); 10558 10559 static void 10560 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10561 ObjCDictionaryLiteral *DictionaryLiteral); 10562 10563 /// Check a single element within a collection literal against the 10564 /// target element type. 10565 static void checkObjCCollectionLiteralElement(Sema &S, 10566 QualType TargetElementType, 10567 Expr *Element, 10568 unsigned ElementKind) { 10569 // Skip a bitcast to 'id' or qualified 'id'. 10570 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10571 if (ICE->getCastKind() == CK_BitCast && 10572 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10573 Element = ICE->getSubExpr(); 10574 } 10575 10576 QualType ElementType = Element->getType(); 10577 ExprResult ElementResult(Element); 10578 if (ElementType->getAs<ObjCObjectPointerType>() && 10579 S.CheckSingleAssignmentConstraints(TargetElementType, 10580 ElementResult, 10581 false, false) 10582 != Sema::Compatible) { 10583 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 10584 << ElementType << ElementKind << TargetElementType 10585 << Element->getSourceRange(); 10586 } 10587 10588 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10589 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10590 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10591 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10592 } 10593 10594 /// Check an Objective-C array literal being converted to the given 10595 /// target type. 10596 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10597 ObjCArrayLiteral *ArrayLiteral) { 10598 if (!S.NSArrayDecl) 10599 return; 10600 10601 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10602 if (!TargetObjCPtr) 10603 return; 10604 10605 if (TargetObjCPtr->isUnspecialized() || 10606 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10607 != S.NSArrayDecl->getCanonicalDecl()) 10608 return; 10609 10610 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10611 if (TypeArgs.size() != 1) 10612 return; 10613 10614 QualType TargetElementType = TypeArgs[0]; 10615 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10616 checkObjCCollectionLiteralElement(S, TargetElementType, 10617 ArrayLiteral->getElement(I), 10618 0); 10619 } 10620 } 10621 10622 /// Check an Objective-C dictionary literal being converted to the given 10623 /// target type. 10624 static void 10625 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10626 ObjCDictionaryLiteral *DictionaryLiteral) { 10627 if (!S.NSDictionaryDecl) 10628 return; 10629 10630 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10631 if (!TargetObjCPtr) 10632 return; 10633 10634 if (TargetObjCPtr->isUnspecialized() || 10635 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10636 != S.NSDictionaryDecl->getCanonicalDecl()) 10637 return; 10638 10639 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10640 if (TypeArgs.size() != 2) 10641 return; 10642 10643 QualType TargetKeyType = TypeArgs[0]; 10644 QualType TargetObjectType = TypeArgs[1]; 10645 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10646 auto Element = DictionaryLiteral->getKeyValueElement(I); 10647 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10648 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10649 } 10650 } 10651 10652 // Helper function to filter out cases for constant width constant conversion. 10653 // Don't warn on char array initialization or for non-decimal values. 10654 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10655 SourceLocation CC) { 10656 // If initializing from a constant, and the constant starts with '0', 10657 // then it is a binary, octal, or hexadecimal. Allow these constants 10658 // to fill all the bits, even if there is a sign change. 10659 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10660 const char FirstLiteralCharacter = 10661 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 10662 if (FirstLiteralCharacter == '0') 10663 return false; 10664 } 10665 10666 // If the CC location points to a '{', and the type is char, then assume 10667 // assume it is an array initialization. 10668 if (CC.isValid() && T->isCharType()) { 10669 const char FirstContextCharacter = 10670 S.getSourceManager().getCharacterData(CC)[0]; 10671 if (FirstContextCharacter == '{') 10672 return false; 10673 } 10674 10675 return true; 10676 } 10677 10678 static void 10679 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10680 bool *ICContext = nullptr) { 10681 if (E->isTypeDependent() || E->isValueDependent()) return; 10682 10683 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10684 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10685 if (Source == Target) return; 10686 if (Target->isDependentType()) return; 10687 10688 // If the conversion context location is invalid don't complain. We also 10689 // don't want to emit a warning if the issue occurs from the expansion of 10690 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10691 // delay this check as long as possible. Once we detect we are in that 10692 // scenario, we just return. 10693 if (CC.isInvalid()) 10694 return; 10695 10696 if (Source->isAtomicType()) 10697 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 10698 10699 // Diagnose implicit casts to bool. 10700 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10701 if (isa<StringLiteral>(E)) 10702 // Warn on string literal to bool. Checks for string literals in logical 10703 // and expressions, for instance, assert(0 && "error here"), are 10704 // prevented by a check in AnalyzeImplicitConversions(). 10705 return DiagnoseImpCast(S, E, T, CC, 10706 diag::warn_impcast_string_literal_to_bool); 10707 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10708 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10709 // This covers the literal expressions that evaluate to Objective-C 10710 // objects. 10711 return DiagnoseImpCast(S, E, T, CC, 10712 diag::warn_impcast_objective_c_literal_to_bool); 10713 } 10714 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10715 // Warn on pointer to bool conversion that is always true. 10716 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10717 SourceRange(CC)); 10718 } 10719 } 10720 10721 // Check implicit casts from Objective-C collection literals to specialized 10722 // collection types, e.g., NSArray<NSString *> *. 10723 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10724 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10725 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10726 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10727 10728 // Strip vector types. 10729 if (isa<VectorType>(Source)) { 10730 if (!isa<VectorType>(Target)) { 10731 if (S.SourceMgr.isInSystemMacro(CC)) 10732 return; 10733 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10734 } 10735 10736 // If the vector cast is cast between two vectors of the same size, it is 10737 // a bitcast, not a conversion. 10738 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10739 return; 10740 10741 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10742 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10743 } 10744 if (auto VecTy = dyn_cast<VectorType>(Target)) 10745 Target = VecTy->getElementType().getTypePtr(); 10746 10747 // Strip complex types. 10748 if (isa<ComplexType>(Source)) { 10749 if (!isa<ComplexType>(Target)) { 10750 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10751 return; 10752 10753 return DiagnoseImpCast(S, E, T, CC, 10754 S.getLangOpts().CPlusPlus 10755 ? diag::err_impcast_complex_scalar 10756 : diag::warn_impcast_complex_scalar); 10757 } 10758 10759 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10760 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10761 } 10762 10763 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10764 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10765 10766 // If the source is floating point... 10767 if (SourceBT && SourceBT->isFloatingPoint()) { 10768 // ...and the target is floating point... 10769 if (TargetBT && TargetBT->isFloatingPoint()) { 10770 // ...then warn if we're dropping FP rank. 10771 10772 // Builtin FP kinds are ordered by increasing FP rank. 10773 if (SourceBT->getKind() > TargetBT->getKind()) { 10774 // Don't warn about float constants that are precisely 10775 // representable in the target type. 10776 Expr::EvalResult result; 10777 if (E->EvaluateAsRValue(result, S.Context)) { 10778 // Value might be a float, a float vector, or a float complex. 10779 if (IsSameFloatAfterCast(result.Val, 10780 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10781 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10782 return; 10783 } 10784 10785 if (S.SourceMgr.isInSystemMacro(CC)) 10786 return; 10787 10788 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10789 } 10790 // ... or possibly if we're increasing rank, too 10791 else if (TargetBT->getKind() > SourceBT->getKind()) { 10792 if (S.SourceMgr.isInSystemMacro(CC)) 10793 return; 10794 10795 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10796 } 10797 return; 10798 } 10799 10800 // If the target is integral, always warn. 10801 if (TargetBT && TargetBT->isInteger()) { 10802 if (S.SourceMgr.isInSystemMacro(CC)) 10803 return; 10804 10805 DiagnoseFloatingImpCast(S, E, T, CC); 10806 } 10807 10808 // Detect the case where a call result is converted from floating-point to 10809 // to bool, and the final argument to the call is converted from bool, to 10810 // discover this typo: 10811 // 10812 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10813 // 10814 // FIXME: This is an incredibly special case; is there some more general 10815 // way to detect this class of misplaced-parentheses bug? 10816 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10817 // Check last argument of function call to see if it is an 10818 // implicit cast from a type matching the type the result 10819 // is being cast to. 10820 CallExpr *CEx = cast<CallExpr>(E); 10821 if (unsigned NumArgs = CEx->getNumArgs()) { 10822 Expr *LastA = CEx->getArg(NumArgs - 1); 10823 Expr *InnerE = LastA->IgnoreParenImpCasts(); 10824 if (isa<ImplicitCastExpr>(LastA) && 10825 InnerE->getType()->isBooleanType()) { 10826 // Warn on this floating-point to bool conversion 10827 DiagnoseImpCast(S, E, T, CC, 10828 diag::warn_impcast_floating_point_to_bool); 10829 } 10830 } 10831 } 10832 return; 10833 } 10834 10835 DiagnoseNullConversion(S, E, T, CC); 10836 10837 S.DiscardMisalignedMemberAddress(Target, E); 10838 10839 if (!Source->isIntegerType() || !Target->isIntegerType()) 10840 return; 10841 10842 // TODO: remove this early return once the false positives for constant->bool 10843 // in templates, macros, etc, are reduced or removed. 10844 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 10845 return; 10846 10847 IntRange SourceRange = GetExprRange(S.Context, E); 10848 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 10849 10850 if (SourceRange.Width > TargetRange.Width) { 10851 // If the source is a constant, use a default-on diagnostic. 10852 // TODO: this should happen for bitfield stores, too. 10853 llvm::APSInt Value(32); 10854 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 10855 if (S.SourceMgr.isInSystemMacro(CC)) 10856 return; 10857 10858 std::string PrettySourceValue = Value.toString(10); 10859 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10860 10861 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10862 S.PDiag(diag::warn_impcast_integer_precision_constant) 10863 << PrettySourceValue << PrettyTargetValue 10864 << E->getType() << T << E->getSourceRange() 10865 << clang::SourceRange(CC)); 10866 return; 10867 } 10868 10869 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 10870 if (S.SourceMgr.isInSystemMacro(CC)) 10871 return; 10872 10873 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 10874 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 10875 /* pruneControlFlow */ true); 10876 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 10877 } 10878 10879 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 10880 SourceRange.NonNegative && Source->isSignedIntegerType()) { 10881 // Warn when doing a signed to signed conversion, warn if the positive 10882 // source value is exactly the width of the target type, which will 10883 // cause a negative value to be stored. 10884 10885 llvm::APSInt Value; 10886 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 10887 !S.SourceMgr.isInSystemMacro(CC)) { 10888 if (isSameWidthConstantConversion(S, E, T, CC)) { 10889 std::string PrettySourceValue = Value.toString(10); 10890 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10891 10892 S.DiagRuntimeBehavior( 10893 E->getExprLoc(), E, 10894 S.PDiag(diag::warn_impcast_integer_precision_constant) 10895 << PrettySourceValue << PrettyTargetValue << E->getType() << T 10896 << E->getSourceRange() << clang::SourceRange(CC)); 10897 return; 10898 } 10899 } 10900 10901 // Fall through for non-constants to give a sign conversion warning. 10902 } 10903 10904 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 10905 (!TargetRange.NonNegative && SourceRange.NonNegative && 10906 SourceRange.Width == TargetRange.Width)) { 10907 if (S.SourceMgr.isInSystemMacro(CC)) 10908 return; 10909 10910 unsigned DiagID = diag::warn_impcast_integer_sign; 10911 10912 // Traditionally, gcc has warned about this under -Wsign-compare. 10913 // We also want to warn about it in -Wconversion. 10914 // So if -Wconversion is off, use a completely identical diagnostic 10915 // in the sign-compare group. 10916 // The conditional-checking code will 10917 if (ICContext) { 10918 DiagID = diag::warn_impcast_integer_sign_conditional; 10919 *ICContext = true; 10920 } 10921 10922 return DiagnoseImpCast(S, E, T, CC, DiagID); 10923 } 10924 10925 // Diagnose conversions between different enumeration types. 10926 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 10927 // type, to give us better diagnostics. 10928 QualType SourceType = E->getType(); 10929 if (!S.getLangOpts().CPlusPlus) { 10930 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10931 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 10932 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 10933 SourceType = S.Context.getTypeDeclType(Enum); 10934 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 10935 } 10936 } 10937 10938 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 10939 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 10940 if (SourceEnum->getDecl()->hasNameForLinkage() && 10941 TargetEnum->getDecl()->hasNameForLinkage() && 10942 SourceEnum != TargetEnum) { 10943 if (S.SourceMgr.isInSystemMacro(CC)) 10944 return; 10945 10946 return DiagnoseImpCast(S, E, SourceType, T, CC, 10947 diag::warn_impcast_different_enum_types); 10948 } 10949 } 10950 10951 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10952 SourceLocation CC, QualType T); 10953 10954 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 10955 SourceLocation CC, bool &ICContext) { 10956 E = E->IgnoreParenImpCasts(); 10957 10958 if (isa<ConditionalOperator>(E)) 10959 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 10960 10961 AnalyzeImplicitConversions(S, E, CC); 10962 if (E->getType() != T) 10963 return CheckImplicitConversion(S, E, T, CC, &ICContext); 10964 } 10965 10966 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10967 SourceLocation CC, QualType T) { 10968 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 10969 10970 bool Suspicious = false; 10971 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 10972 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 10973 10974 // If -Wconversion would have warned about either of the candidates 10975 // for a signedness conversion to the context type... 10976 if (!Suspicious) return; 10977 10978 // ...but it's currently ignored... 10979 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 10980 return; 10981 10982 // ...then check whether it would have warned about either of the 10983 // candidates for a signedness conversion to the condition type. 10984 if (E->getType() == T) return; 10985 10986 Suspicious = false; 10987 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 10988 E->getType(), CC, &Suspicious); 10989 if (!Suspicious) 10990 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 10991 E->getType(), CC, &Suspicious); 10992 } 10993 10994 /// Check conversion of given expression to boolean. 10995 /// Input argument E is a logical expression. 10996 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 10997 if (S.getLangOpts().Bool) 10998 return; 10999 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11000 return; 11001 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11002 } 11003 11004 /// AnalyzeImplicitConversions - Find and report any interesting 11005 /// implicit conversions in the given expression. There are a couple 11006 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11007 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 11008 SourceLocation CC) { 11009 QualType T = OrigE->getType(); 11010 Expr *E = OrigE->IgnoreParenImpCasts(); 11011 11012 if (E->isTypeDependent() || E->isValueDependent()) 11013 return; 11014 11015 // For conditional operators, we analyze the arguments as if they 11016 // were being fed directly into the output. 11017 if (isa<ConditionalOperator>(E)) { 11018 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11019 CheckConditionalOperator(S, CO, CC, T); 11020 return; 11021 } 11022 11023 // Check implicit argument conversions for function calls. 11024 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11025 CheckImplicitArgumentConversions(S, Call, CC); 11026 11027 // Go ahead and check any implicit conversions we might have skipped. 11028 // The non-canonical typecheck is just an optimization; 11029 // CheckImplicitConversion will filter out dead implicit conversions. 11030 if (E->getType() != T) 11031 CheckImplicitConversion(S, E, T, CC); 11032 11033 // Now continue drilling into this expression. 11034 11035 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11036 // The bound subexpressions in a PseudoObjectExpr are not reachable 11037 // as transitive children. 11038 // FIXME: Use a more uniform representation for this. 11039 for (auto *SE : POE->semantics()) 11040 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11041 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 11042 } 11043 11044 // Skip past explicit casts. 11045 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11046 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11047 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11048 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11049 return AnalyzeImplicitConversions(S, E, CC); 11050 } 11051 11052 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11053 // Do a somewhat different check with comparison operators. 11054 if (BO->isComparisonOp()) 11055 return AnalyzeComparison(S, BO); 11056 11057 // And with simple assignments. 11058 if (BO->getOpcode() == BO_Assign) 11059 return AnalyzeAssignment(S, BO); 11060 // And with compound assignments. 11061 if (BO->isAssignmentOp()) 11062 return AnalyzeCompoundAssignment(S, BO); 11063 } 11064 11065 // These break the otherwise-useful invariant below. Fortunately, 11066 // we don't really need to recurse into them, because any internal 11067 // expressions should have been analyzed already when they were 11068 // built into statements. 11069 if (isa<StmtExpr>(E)) return; 11070 11071 // Don't descend into unevaluated contexts. 11072 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11073 11074 // Now just recurse over the expression's children. 11075 CC = E->getExprLoc(); 11076 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11077 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11078 for (Stmt *SubStmt : E->children()) { 11079 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11080 if (!ChildExpr) 11081 continue; 11082 11083 if (IsLogicalAndOperator && 11084 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11085 // Ignore checking string literals that are in logical and operators. 11086 // This is a common pattern for asserts. 11087 continue; 11088 AnalyzeImplicitConversions(S, ChildExpr, CC); 11089 } 11090 11091 if (BO && BO->isLogicalOp()) { 11092 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11093 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11094 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11095 11096 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11097 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11098 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11099 } 11100 11101 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11102 if (U->getOpcode() == UO_LNot) { 11103 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11104 } else if (U->getOpcode() != UO_AddrOf) { 11105 if (U->getSubExpr()->getType()->isAtomicType()) 11106 S.Diag(U->getSubExpr()->getBeginLoc(), 11107 diag::warn_atomic_implicit_seq_cst); 11108 } 11109 } 11110 } 11111 11112 /// Diagnose integer type and any valid implicit conversion to it. 11113 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11114 // Taking into account implicit conversions, 11115 // allow any integer. 11116 if (!E->getType()->isIntegerType()) { 11117 S.Diag(E->getBeginLoc(), 11118 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11119 return true; 11120 } 11121 // Potentially emit standard warnings for implicit conversions if enabled 11122 // using -Wconversion. 11123 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11124 return false; 11125 } 11126 11127 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11128 // Returns true when emitting a warning about taking the address of a reference. 11129 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11130 const PartialDiagnostic &PD) { 11131 E = E->IgnoreParenImpCasts(); 11132 11133 const FunctionDecl *FD = nullptr; 11134 11135 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11136 if (!DRE->getDecl()->getType()->isReferenceType()) 11137 return false; 11138 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11139 if (!M->getMemberDecl()->getType()->isReferenceType()) 11140 return false; 11141 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11142 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11143 return false; 11144 FD = Call->getDirectCallee(); 11145 } else { 11146 return false; 11147 } 11148 11149 SemaRef.Diag(E->getExprLoc(), PD); 11150 11151 // If possible, point to location of function. 11152 if (FD) { 11153 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11154 } 11155 11156 return true; 11157 } 11158 11159 // Returns true if the SourceLocation is expanded from any macro body. 11160 // Returns false if the SourceLocation is invalid, is from not in a macro 11161 // expansion, or is from expanded from a top-level macro argument. 11162 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11163 if (Loc.isInvalid()) 11164 return false; 11165 11166 while (Loc.isMacroID()) { 11167 if (SM.isMacroBodyExpansion(Loc)) 11168 return true; 11169 Loc = SM.getImmediateMacroCallerLoc(Loc); 11170 } 11171 11172 return false; 11173 } 11174 11175 /// Diagnose pointers that are always non-null. 11176 /// \param E the expression containing the pointer 11177 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11178 /// compared to a null pointer 11179 /// \param IsEqual True when the comparison is equal to a null pointer 11180 /// \param Range Extra SourceRange to highlight in the diagnostic 11181 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11182 Expr::NullPointerConstantKind NullKind, 11183 bool IsEqual, SourceRange Range) { 11184 if (!E) 11185 return; 11186 11187 // Don't warn inside macros. 11188 if (E->getExprLoc().isMacroID()) { 11189 const SourceManager &SM = getSourceManager(); 11190 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11191 IsInAnyMacroBody(SM, Range.getBegin())) 11192 return; 11193 } 11194 E = E->IgnoreImpCasts(); 11195 11196 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11197 11198 if (isa<CXXThisExpr>(E)) { 11199 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11200 : diag::warn_this_bool_conversion; 11201 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11202 return; 11203 } 11204 11205 bool IsAddressOf = false; 11206 11207 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11208 if (UO->getOpcode() != UO_AddrOf) 11209 return; 11210 IsAddressOf = true; 11211 E = UO->getSubExpr(); 11212 } 11213 11214 if (IsAddressOf) { 11215 unsigned DiagID = IsCompare 11216 ? diag::warn_address_of_reference_null_compare 11217 : diag::warn_address_of_reference_bool_conversion; 11218 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11219 << IsEqual; 11220 if (CheckForReference(*this, E, PD)) { 11221 return; 11222 } 11223 } 11224 11225 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11226 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11227 std::string Str; 11228 llvm::raw_string_ostream S(Str); 11229 E->printPretty(S, nullptr, getPrintingPolicy()); 11230 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11231 : diag::warn_cast_nonnull_to_bool; 11232 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11233 << E->getSourceRange() << Range << IsEqual; 11234 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11235 }; 11236 11237 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11238 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11239 if (auto *Callee = Call->getDirectCallee()) { 11240 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11241 ComplainAboutNonnullParamOrCall(A); 11242 return; 11243 } 11244 } 11245 } 11246 11247 // Expect to find a single Decl. Skip anything more complicated. 11248 ValueDecl *D = nullptr; 11249 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11250 D = R->getDecl(); 11251 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11252 D = M->getMemberDecl(); 11253 } 11254 11255 // Weak Decls can be null. 11256 if (!D || D->isWeak()) 11257 return; 11258 11259 // Check for parameter decl with nonnull attribute 11260 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11261 if (getCurFunction() && 11262 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11263 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11264 ComplainAboutNonnullParamOrCall(A); 11265 return; 11266 } 11267 11268 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11269 auto ParamIter = llvm::find(FD->parameters(), PV); 11270 assert(ParamIter != FD->param_end()); 11271 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11272 11273 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11274 if (!NonNull->args_size()) { 11275 ComplainAboutNonnullParamOrCall(NonNull); 11276 return; 11277 } 11278 11279 for (const ParamIdx &ArgNo : NonNull->args()) { 11280 if (ArgNo.getASTIndex() == ParamNo) { 11281 ComplainAboutNonnullParamOrCall(NonNull); 11282 return; 11283 } 11284 } 11285 } 11286 } 11287 } 11288 } 11289 11290 QualType T = D->getType(); 11291 const bool IsArray = T->isArrayType(); 11292 const bool IsFunction = T->isFunctionType(); 11293 11294 // Address of function is used to silence the function warning. 11295 if (IsAddressOf && IsFunction) { 11296 return; 11297 } 11298 11299 // Found nothing. 11300 if (!IsAddressOf && !IsFunction && !IsArray) 11301 return; 11302 11303 // Pretty print the expression for the diagnostic. 11304 std::string Str; 11305 llvm::raw_string_ostream S(Str); 11306 E->printPretty(S, nullptr, getPrintingPolicy()); 11307 11308 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11309 : diag::warn_impcast_pointer_to_bool; 11310 enum { 11311 AddressOf, 11312 FunctionPointer, 11313 ArrayPointer 11314 } DiagType; 11315 if (IsAddressOf) 11316 DiagType = AddressOf; 11317 else if (IsFunction) 11318 DiagType = FunctionPointer; 11319 else if (IsArray) 11320 DiagType = ArrayPointer; 11321 else 11322 llvm_unreachable("Could not determine diagnostic."); 11323 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11324 << Range << IsEqual; 11325 11326 if (!IsFunction) 11327 return; 11328 11329 // Suggest '&' to silence the function warning. 11330 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11331 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11332 11333 // Check to see if '()' fixit should be emitted. 11334 QualType ReturnType; 11335 UnresolvedSet<4> NonTemplateOverloads; 11336 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11337 if (ReturnType.isNull()) 11338 return; 11339 11340 if (IsCompare) { 11341 // There are two cases here. If there is null constant, the only suggest 11342 // for a pointer return type. If the null is 0, then suggest if the return 11343 // type is a pointer or an integer type. 11344 if (!ReturnType->isPointerType()) { 11345 if (NullKind == Expr::NPCK_ZeroExpression || 11346 NullKind == Expr::NPCK_ZeroLiteral) { 11347 if (!ReturnType->isIntegerType()) 11348 return; 11349 } else { 11350 return; 11351 } 11352 } 11353 } else { // !IsCompare 11354 // For function to bool, only suggest if the function pointer has bool 11355 // return type. 11356 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11357 return; 11358 } 11359 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11360 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11361 } 11362 11363 /// Diagnoses "dangerous" implicit conversions within the given 11364 /// expression (which is a full expression). Implements -Wconversion 11365 /// and -Wsign-compare. 11366 /// 11367 /// \param CC the "context" location of the implicit conversion, i.e. 11368 /// the most location of the syntactic entity requiring the implicit 11369 /// conversion 11370 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11371 // Don't diagnose in unevaluated contexts. 11372 if (isUnevaluatedContext()) 11373 return; 11374 11375 // Don't diagnose for value- or type-dependent expressions. 11376 if (E->isTypeDependent() || E->isValueDependent()) 11377 return; 11378 11379 // Check for array bounds violations in cases where the check isn't triggered 11380 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11381 // ArraySubscriptExpr is on the RHS of a variable initialization. 11382 CheckArrayAccess(E); 11383 11384 // This is not the right CC for (e.g.) a variable initialization. 11385 AnalyzeImplicitConversions(*this, E, CC); 11386 } 11387 11388 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11389 /// Input argument E is a logical expression. 11390 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11391 ::CheckBoolLikeConversion(*this, E, CC); 11392 } 11393 11394 /// Diagnose when expression is an integer constant expression and its evaluation 11395 /// results in integer overflow 11396 void Sema::CheckForIntOverflow (Expr *E) { 11397 // Use a work list to deal with nested struct initializers. 11398 SmallVector<Expr *, 2> Exprs(1, E); 11399 11400 do { 11401 Expr *OriginalE = Exprs.pop_back_val(); 11402 Expr *E = OriginalE->IgnoreParenCasts(); 11403 11404 if (isa<BinaryOperator>(E)) { 11405 E->EvaluateForOverflow(Context); 11406 continue; 11407 } 11408 11409 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11410 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11411 else if (isa<ObjCBoxedExpr>(OriginalE)) 11412 E->EvaluateForOverflow(Context); 11413 else if (auto Call = dyn_cast<CallExpr>(E)) 11414 Exprs.append(Call->arg_begin(), Call->arg_end()); 11415 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 11416 Exprs.append(Message->arg_begin(), Message->arg_end()); 11417 } while (!Exprs.empty()); 11418 } 11419 11420 namespace { 11421 11422 /// Visitor for expressions which looks for unsequenced operations on the 11423 /// same object. 11424 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 11425 using Base = EvaluatedExprVisitor<SequenceChecker>; 11426 11427 /// A tree of sequenced regions within an expression. Two regions are 11428 /// unsequenced if one is an ancestor or a descendent of the other. When we 11429 /// finish processing an expression with sequencing, such as a comma 11430 /// expression, we fold its tree nodes into its parent, since they are 11431 /// unsequenced with respect to nodes we will visit later. 11432 class SequenceTree { 11433 struct Value { 11434 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 11435 unsigned Parent : 31; 11436 unsigned Merged : 1; 11437 }; 11438 SmallVector<Value, 8> Values; 11439 11440 public: 11441 /// A region within an expression which may be sequenced with respect 11442 /// to some other region. 11443 class Seq { 11444 friend class SequenceTree; 11445 11446 unsigned Index = 0; 11447 11448 explicit Seq(unsigned N) : Index(N) {} 11449 11450 public: 11451 Seq() = default; 11452 }; 11453 11454 SequenceTree() { Values.push_back(Value(0)); } 11455 Seq root() const { return Seq(0); } 11456 11457 /// Create a new sequence of operations, which is an unsequenced 11458 /// subset of \p Parent. This sequence of operations is sequenced with 11459 /// respect to other children of \p Parent. 11460 Seq allocate(Seq Parent) { 11461 Values.push_back(Value(Parent.Index)); 11462 return Seq(Values.size() - 1); 11463 } 11464 11465 /// Merge a sequence of operations into its parent. 11466 void merge(Seq S) { 11467 Values[S.Index].Merged = true; 11468 } 11469 11470 /// Determine whether two operations are unsequenced. This operation 11471 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 11472 /// should have been merged into its parent as appropriate. 11473 bool isUnsequenced(Seq Cur, Seq Old) { 11474 unsigned C = representative(Cur.Index); 11475 unsigned Target = representative(Old.Index); 11476 while (C >= Target) { 11477 if (C == Target) 11478 return true; 11479 C = Values[C].Parent; 11480 } 11481 return false; 11482 } 11483 11484 private: 11485 /// Pick a representative for a sequence. 11486 unsigned representative(unsigned K) { 11487 if (Values[K].Merged) 11488 // Perform path compression as we go. 11489 return Values[K].Parent = representative(Values[K].Parent); 11490 return K; 11491 } 11492 }; 11493 11494 /// An object for which we can track unsequenced uses. 11495 using Object = NamedDecl *; 11496 11497 /// Different flavors of object usage which we track. We only track the 11498 /// least-sequenced usage of each kind. 11499 enum UsageKind { 11500 /// A read of an object. Multiple unsequenced reads are OK. 11501 UK_Use, 11502 11503 /// A modification of an object which is sequenced before the value 11504 /// computation of the expression, such as ++n in C++. 11505 UK_ModAsValue, 11506 11507 /// A modification of an object which is not sequenced before the value 11508 /// computation of the expression, such as n++. 11509 UK_ModAsSideEffect, 11510 11511 UK_Count = UK_ModAsSideEffect + 1 11512 }; 11513 11514 struct Usage { 11515 Expr *Use = nullptr; 11516 SequenceTree::Seq Seq; 11517 11518 Usage() = default; 11519 }; 11520 11521 struct UsageInfo { 11522 Usage Uses[UK_Count]; 11523 11524 /// Have we issued a diagnostic for this variable already? 11525 bool Diagnosed = false; 11526 11527 UsageInfo() = default; 11528 }; 11529 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 11530 11531 Sema &SemaRef; 11532 11533 /// Sequenced regions within the expression. 11534 SequenceTree Tree; 11535 11536 /// Declaration modifications and references which we have seen. 11537 UsageInfoMap UsageMap; 11538 11539 /// The region we are currently within. 11540 SequenceTree::Seq Region; 11541 11542 /// Filled in with declarations which were modified as a side-effect 11543 /// (that is, post-increment operations). 11544 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 11545 11546 /// Expressions to check later. We defer checking these to reduce 11547 /// stack usage. 11548 SmallVectorImpl<Expr *> &WorkList; 11549 11550 /// RAII object wrapping the visitation of a sequenced subexpression of an 11551 /// expression. At the end of this process, the side-effects of the evaluation 11552 /// become sequenced with respect to the value computation of the result, so 11553 /// we downgrade any UK_ModAsSideEffect within the evaluation to 11554 /// UK_ModAsValue. 11555 struct SequencedSubexpression { 11556 SequencedSubexpression(SequenceChecker &Self) 11557 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11558 Self.ModAsSideEffect = &ModAsSideEffect; 11559 } 11560 11561 ~SequencedSubexpression() { 11562 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11563 UsageInfo &U = Self.UsageMap[M.first]; 11564 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11565 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11566 SideEffectUsage = M.second; 11567 } 11568 Self.ModAsSideEffect = OldModAsSideEffect; 11569 } 11570 11571 SequenceChecker &Self; 11572 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11573 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11574 }; 11575 11576 /// RAII object wrapping the visitation of a subexpression which we might 11577 /// choose to evaluate as a constant. If any subexpression is evaluated and 11578 /// found to be non-constant, this allows us to suppress the evaluation of 11579 /// the outer expression. 11580 class EvaluationTracker { 11581 public: 11582 EvaluationTracker(SequenceChecker &Self) 11583 : Self(Self), Prev(Self.EvalTracker) { 11584 Self.EvalTracker = this; 11585 } 11586 11587 ~EvaluationTracker() { 11588 Self.EvalTracker = Prev; 11589 if (Prev) 11590 Prev->EvalOK &= EvalOK; 11591 } 11592 11593 bool evaluate(const Expr *E, bool &Result) { 11594 if (!EvalOK || E->isValueDependent()) 11595 return false; 11596 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11597 return EvalOK; 11598 } 11599 11600 private: 11601 SequenceChecker &Self; 11602 EvaluationTracker *Prev; 11603 bool EvalOK = true; 11604 } *EvalTracker = nullptr; 11605 11606 /// Find the object which is produced by the specified expression, 11607 /// if any. 11608 Object getObject(Expr *E, bool Mod) const { 11609 E = E->IgnoreParenCasts(); 11610 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11611 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11612 return getObject(UO->getSubExpr(), Mod); 11613 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11614 if (BO->getOpcode() == BO_Comma) 11615 return getObject(BO->getRHS(), Mod); 11616 if (Mod && BO->isAssignmentOp()) 11617 return getObject(BO->getLHS(), Mod); 11618 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11619 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11620 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11621 return ME->getMemberDecl(); 11622 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11623 // FIXME: If this is a reference, map through to its value. 11624 return DRE->getDecl(); 11625 return nullptr; 11626 } 11627 11628 /// Note that an object was modified or used by an expression. 11629 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11630 Usage &U = UI.Uses[UK]; 11631 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11632 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11633 ModAsSideEffect->push_back(std::make_pair(O, U)); 11634 U.Use = Ref; 11635 U.Seq = Region; 11636 } 11637 } 11638 11639 /// Check whether a modification or use conflicts with a prior usage. 11640 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11641 bool IsModMod) { 11642 if (UI.Diagnosed) 11643 return; 11644 11645 const Usage &U = UI.Uses[OtherKind]; 11646 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11647 return; 11648 11649 Expr *Mod = U.Use; 11650 Expr *ModOrUse = Ref; 11651 if (OtherKind == UK_Use) 11652 std::swap(Mod, ModOrUse); 11653 11654 SemaRef.Diag(Mod->getExprLoc(), 11655 IsModMod ? diag::warn_unsequenced_mod_mod 11656 : diag::warn_unsequenced_mod_use) 11657 << O << SourceRange(ModOrUse->getExprLoc()); 11658 UI.Diagnosed = true; 11659 } 11660 11661 void notePreUse(Object O, Expr *Use) { 11662 UsageInfo &U = UsageMap[O]; 11663 // Uses conflict with other modifications. 11664 checkUsage(O, U, Use, UK_ModAsValue, false); 11665 } 11666 11667 void notePostUse(Object O, Expr *Use) { 11668 UsageInfo &U = UsageMap[O]; 11669 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 11670 addUsage(U, O, Use, UK_Use); 11671 } 11672 11673 void notePreMod(Object O, Expr *Mod) { 11674 UsageInfo &U = UsageMap[O]; 11675 // Modifications conflict with other modifications and with uses. 11676 checkUsage(O, U, Mod, UK_ModAsValue, true); 11677 checkUsage(O, U, Mod, UK_Use, false); 11678 } 11679 11680 void notePostMod(Object O, Expr *Use, UsageKind UK) { 11681 UsageInfo &U = UsageMap[O]; 11682 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 11683 addUsage(U, O, Use, UK); 11684 } 11685 11686 public: 11687 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 11688 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 11689 Visit(E); 11690 } 11691 11692 void VisitStmt(Stmt *S) { 11693 // Skip all statements which aren't expressions for now. 11694 } 11695 11696 void VisitExpr(Expr *E) { 11697 // By default, just recurse to evaluated subexpressions. 11698 Base::VisitStmt(E); 11699 } 11700 11701 void VisitCastExpr(CastExpr *E) { 11702 Object O = Object(); 11703 if (E->getCastKind() == CK_LValueToRValue) 11704 O = getObject(E->getSubExpr(), false); 11705 11706 if (O) 11707 notePreUse(O, E); 11708 VisitExpr(E); 11709 if (O) 11710 notePostUse(O, E); 11711 } 11712 11713 void VisitBinComma(BinaryOperator *BO) { 11714 // C++11 [expr.comma]p1: 11715 // Every value computation and side effect associated with the left 11716 // expression is sequenced before every value computation and side 11717 // effect associated with the right expression. 11718 SequenceTree::Seq LHS = Tree.allocate(Region); 11719 SequenceTree::Seq RHS = Tree.allocate(Region); 11720 SequenceTree::Seq OldRegion = Region; 11721 11722 { 11723 SequencedSubexpression SeqLHS(*this); 11724 Region = LHS; 11725 Visit(BO->getLHS()); 11726 } 11727 11728 Region = RHS; 11729 Visit(BO->getRHS()); 11730 11731 Region = OldRegion; 11732 11733 // Forget that LHS and RHS are sequenced. They are both unsequenced 11734 // with respect to other stuff. 11735 Tree.merge(LHS); 11736 Tree.merge(RHS); 11737 } 11738 11739 void VisitBinAssign(BinaryOperator *BO) { 11740 // The modification is sequenced after the value computation of the LHS 11741 // and RHS, so check it before inspecting the operands and update the 11742 // map afterwards. 11743 Object O = getObject(BO->getLHS(), true); 11744 if (!O) 11745 return VisitExpr(BO); 11746 11747 notePreMod(O, BO); 11748 11749 // C++11 [expr.ass]p7: 11750 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11751 // only once. 11752 // 11753 // Therefore, for a compound assignment operator, O is considered used 11754 // everywhere except within the evaluation of E1 itself. 11755 if (isa<CompoundAssignOperator>(BO)) 11756 notePreUse(O, BO); 11757 11758 Visit(BO->getLHS()); 11759 11760 if (isa<CompoundAssignOperator>(BO)) 11761 notePostUse(O, BO); 11762 11763 Visit(BO->getRHS()); 11764 11765 // C++11 [expr.ass]p1: 11766 // the assignment is sequenced [...] before the value computation of the 11767 // assignment expression. 11768 // C11 6.5.16/3 has no such rule. 11769 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11770 : UK_ModAsSideEffect); 11771 } 11772 11773 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11774 VisitBinAssign(CAO); 11775 } 11776 11777 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11778 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11779 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11780 Object O = getObject(UO->getSubExpr(), true); 11781 if (!O) 11782 return VisitExpr(UO); 11783 11784 notePreMod(O, UO); 11785 Visit(UO->getSubExpr()); 11786 // C++11 [expr.pre.incr]p1: 11787 // the expression ++x is equivalent to x+=1 11788 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11789 : UK_ModAsSideEffect); 11790 } 11791 11792 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11793 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11794 void VisitUnaryPostIncDec(UnaryOperator *UO) { 11795 Object O = getObject(UO->getSubExpr(), true); 11796 if (!O) 11797 return VisitExpr(UO); 11798 11799 notePreMod(O, UO); 11800 Visit(UO->getSubExpr()); 11801 notePostMod(O, UO, UK_ModAsSideEffect); 11802 } 11803 11804 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 11805 void VisitBinLOr(BinaryOperator *BO) { 11806 // The side-effects of the LHS of an '&&' are sequenced before the 11807 // value computation of the RHS, and hence before the value computation 11808 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 11809 // as if they were unconditionally sequenced. 11810 EvaluationTracker Eval(*this); 11811 { 11812 SequencedSubexpression Sequenced(*this); 11813 Visit(BO->getLHS()); 11814 } 11815 11816 bool Result; 11817 if (Eval.evaluate(BO->getLHS(), Result)) { 11818 if (!Result) 11819 Visit(BO->getRHS()); 11820 } else { 11821 // Check for unsequenced operations in the RHS, treating it as an 11822 // entirely separate evaluation. 11823 // 11824 // FIXME: If there are operations in the RHS which are unsequenced 11825 // with respect to operations outside the RHS, and those operations 11826 // are unconditionally evaluated, diagnose them. 11827 WorkList.push_back(BO->getRHS()); 11828 } 11829 } 11830 void VisitBinLAnd(BinaryOperator *BO) { 11831 EvaluationTracker Eval(*this); 11832 { 11833 SequencedSubexpression Sequenced(*this); 11834 Visit(BO->getLHS()); 11835 } 11836 11837 bool Result; 11838 if (Eval.evaluate(BO->getLHS(), Result)) { 11839 if (Result) 11840 Visit(BO->getRHS()); 11841 } else { 11842 WorkList.push_back(BO->getRHS()); 11843 } 11844 } 11845 11846 // Only visit the condition, unless we can be sure which subexpression will 11847 // be chosen. 11848 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 11849 EvaluationTracker Eval(*this); 11850 { 11851 SequencedSubexpression Sequenced(*this); 11852 Visit(CO->getCond()); 11853 } 11854 11855 bool Result; 11856 if (Eval.evaluate(CO->getCond(), Result)) 11857 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 11858 else { 11859 WorkList.push_back(CO->getTrueExpr()); 11860 WorkList.push_back(CO->getFalseExpr()); 11861 } 11862 } 11863 11864 void VisitCallExpr(CallExpr *CE) { 11865 // C++11 [intro.execution]p15: 11866 // When calling a function [...], every value computation and side effect 11867 // associated with any argument expression, or with the postfix expression 11868 // designating the called function, is sequenced before execution of every 11869 // expression or statement in the body of the function [and thus before 11870 // the value computation of its result]. 11871 SequencedSubexpression Sequenced(*this); 11872 Base::VisitCallExpr(CE); 11873 11874 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 11875 } 11876 11877 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 11878 // This is a call, so all subexpressions are sequenced before the result. 11879 SequencedSubexpression Sequenced(*this); 11880 11881 if (!CCE->isListInitialization()) 11882 return VisitExpr(CCE); 11883 11884 // In C++11, list initializations are sequenced. 11885 SmallVector<SequenceTree::Seq, 32> Elts; 11886 SequenceTree::Seq Parent = Region; 11887 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 11888 E = CCE->arg_end(); 11889 I != E; ++I) { 11890 Region = Tree.allocate(Parent); 11891 Elts.push_back(Region); 11892 Visit(*I); 11893 } 11894 11895 // Forget that the initializers are sequenced. 11896 Region = Parent; 11897 for (unsigned I = 0; I < Elts.size(); ++I) 11898 Tree.merge(Elts[I]); 11899 } 11900 11901 void VisitInitListExpr(InitListExpr *ILE) { 11902 if (!SemaRef.getLangOpts().CPlusPlus11) 11903 return VisitExpr(ILE); 11904 11905 // In C++11, list initializations are sequenced. 11906 SmallVector<SequenceTree::Seq, 32> Elts; 11907 SequenceTree::Seq Parent = Region; 11908 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 11909 Expr *E = ILE->getInit(I); 11910 if (!E) continue; 11911 Region = Tree.allocate(Parent); 11912 Elts.push_back(Region); 11913 Visit(E); 11914 } 11915 11916 // Forget that the initializers are sequenced. 11917 Region = Parent; 11918 for (unsigned I = 0; I < Elts.size(); ++I) 11919 Tree.merge(Elts[I]); 11920 } 11921 }; 11922 11923 } // namespace 11924 11925 void Sema::CheckUnsequencedOperations(Expr *E) { 11926 SmallVector<Expr *, 8> WorkList; 11927 WorkList.push_back(E); 11928 while (!WorkList.empty()) { 11929 Expr *Item = WorkList.pop_back_val(); 11930 SequenceChecker(*this, Item, WorkList); 11931 } 11932 } 11933 11934 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 11935 bool IsConstexpr) { 11936 CheckImplicitConversions(E, CheckLoc); 11937 if (!E->isInstantiationDependent()) 11938 CheckUnsequencedOperations(E); 11939 if (!IsConstexpr && !E->isValueDependent()) 11940 CheckForIntOverflow(E); 11941 DiagnoseMisalignedMembers(); 11942 } 11943 11944 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 11945 FieldDecl *BitField, 11946 Expr *Init) { 11947 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 11948 } 11949 11950 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 11951 SourceLocation Loc) { 11952 if (!PType->isVariablyModifiedType()) 11953 return; 11954 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 11955 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 11956 return; 11957 } 11958 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 11959 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 11960 return; 11961 } 11962 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 11963 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 11964 return; 11965 } 11966 11967 const ArrayType *AT = S.Context.getAsArrayType(PType); 11968 if (!AT) 11969 return; 11970 11971 if (AT->getSizeModifier() != ArrayType::Star) { 11972 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 11973 return; 11974 } 11975 11976 S.Diag(Loc, diag::err_array_star_in_function_definition); 11977 } 11978 11979 /// CheckParmsForFunctionDef - Check that the parameters of the given 11980 /// function are appropriate for the definition of a function. This 11981 /// takes care of any checks that cannot be performed on the 11982 /// declaration itself, e.g., that the types of each of the function 11983 /// parameters are complete. 11984 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 11985 bool CheckParameterNames) { 11986 bool HasInvalidParm = false; 11987 for (ParmVarDecl *Param : Parameters) { 11988 // C99 6.7.5.3p4: the parameters in a parameter type list in a 11989 // function declarator that is part of a function definition of 11990 // that function shall not have incomplete type. 11991 // 11992 // This is also C++ [dcl.fct]p6. 11993 if (!Param->isInvalidDecl() && 11994 RequireCompleteType(Param->getLocation(), Param->getType(), 11995 diag::err_typecheck_decl_incomplete_type)) { 11996 Param->setInvalidDecl(); 11997 HasInvalidParm = true; 11998 } 11999 12000 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12001 // declaration of each parameter shall include an identifier. 12002 if (CheckParameterNames && 12003 Param->getIdentifier() == nullptr && 12004 !Param->isImplicit() && 12005 !getLangOpts().CPlusPlus) 12006 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12007 12008 // C99 6.7.5.3p12: 12009 // If the function declarator is not part of a definition of that 12010 // function, parameters may have incomplete type and may use the [*] 12011 // notation in their sequences of declarator specifiers to specify 12012 // variable length array types. 12013 QualType PType = Param->getOriginalType(); 12014 // FIXME: This diagnostic should point the '[*]' if source-location 12015 // information is added for it. 12016 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12017 12018 // If the parameter is a c++ class type and it has to be destructed in the 12019 // callee function, declare the destructor so that it can be called by the 12020 // callee function. Do not perform any direct access check on the dtor here. 12021 if (!Param->isInvalidDecl()) { 12022 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12023 if (!ClassDecl->isInvalidDecl() && 12024 !ClassDecl->hasIrrelevantDestructor() && 12025 !ClassDecl->isDependentContext() && 12026 ClassDecl->isParamDestroyedInCallee()) { 12027 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12028 MarkFunctionReferenced(Param->getLocation(), Destructor); 12029 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12030 } 12031 } 12032 } 12033 12034 // Parameters with the pass_object_size attribute only need to be marked 12035 // constant at function definitions. Because we lack information about 12036 // whether we're on a declaration or definition when we're instantiating the 12037 // attribute, we need to check for constness here. 12038 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12039 if (!Param->getType().isConstQualified()) 12040 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12041 << Attr->getSpelling() << 1; 12042 } 12043 12044 return HasInvalidParm; 12045 } 12046 12047 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12048 /// or MemberExpr. 12049 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12050 ASTContext &Context) { 12051 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12052 return Context.getDeclAlign(DRE->getDecl()); 12053 12054 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12055 return Context.getDeclAlign(ME->getMemberDecl()); 12056 12057 return TypeAlign; 12058 } 12059 12060 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12061 /// pointer cast increases the alignment requirements. 12062 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12063 // This is actually a lot of work to potentially be doing on every 12064 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12065 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12066 return; 12067 12068 // Ignore dependent types. 12069 if (T->isDependentType() || Op->getType()->isDependentType()) 12070 return; 12071 12072 // Require that the destination be a pointer type. 12073 const PointerType *DestPtr = T->getAs<PointerType>(); 12074 if (!DestPtr) return; 12075 12076 // If the destination has alignment 1, we're done. 12077 QualType DestPointee = DestPtr->getPointeeType(); 12078 if (DestPointee->isIncompleteType()) return; 12079 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12080 if (DestAlign.isOne()) return; 12081 12082 // Require that the source be a pointer type. 12083 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12084 if (!SrcPtr) return; 12085 QualType SrcPointee = SrcPtr->getPointeeType(); 12086 12087 // Whitelist casts from cv void*. We already implicitly 12088 // whitelisted casts to cv void*, since they have alignment 1. 12089 // Also whitelist casts involving incomplete types, which implicitly 12090 // includes 'void'. 12091 if (SrcPointee->isIncompleteType()) return; 12092 12093 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12094 12095 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12096 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12097 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12098 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12099 if (UO->getOpcode() == UO_AddrOf) 12100 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12101 } 12102 12103 if (SrcAlign >= DestAlign) return; 12104 12105 Diag(TRange.getBegin(), diag::warn_cast_align) 12106 << Op->getType() << T 12107 << static_cast<unsigned>(SrcAlign.getQuantity()) 12108 << static_cast<unsigned>(DestAlign.getQuantity()) 12109 << TRange << Op->getSourceRange(); 12110 } 12111 12112 /// Check whether this array fits the idiom of a size-one tail padded 12113 /// array member of a struct. 12114 /// 12115 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12116 /// commonly used to emulate flexible arrays in C89 code. 12117 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12118 const NamedDecl *ND) { 12119 if (Size != 1 || !ND) return false; 12120 12121 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12122 if (!FD) return false; 12123 12124 // Don't consider sizes resulting from macro expansions or template argument 12125 // substitution to form C89 tail-padded arrays. 12126 12127 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12128 while (TInfo) { 12129 TypeLoc TL = TInfo->getTypeLoc(); 12130 // Look through typedefs. 12131 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12132 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12133 TInfo = TDL->getTypeSourceInfo(); 12134 continue; 12135 } 12136 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12137 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12138 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12139 return false; 12140 } 12141 break; 12142 } 12143 12144 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12145 if (!RD) return false; 12146 if (RD->isUnion()) return false; 12147 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12148 if (!CRD->isStandardLayout()) return false; 12149 } 12150 12151 // See if this is the last field decl in the record. 12152 const Decl *D = FD; 12153 while ((D = D->getNextDeclInContext())) 12154 if (isa<FieldDecl>(D)) 12155 return false; 12156 return true; 12157 } 12158 12159 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12160 const ArraySubscriptExpr *ASE, 12161 bool AllowOnePastEnd, bool IndexNegated) { 12162 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12163 if (IndexExpr->isValueDependent()) 12164 return; 12165 12166 const Type *EffectiveType = 12167 BaseExpr->getType()->getPointeeOrArrayElementType(); 12168 BaseExpr = BaseExpr->IgnoreParenCasts(); 12169 const ConstantArrayType *ArrayTy = 12170 Context.getAsConstantArrayType(BaseExpr->getType()); 12171 if (!ArrayTy) 12172 return; 12173 12174 llvm::APSInt index; 12175 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 12176 return; 12177 if (IndexNegated) 12178 index = -index; 12179 12180 const NamedDecl *ND = nullptr; 12181 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12182 ND = DRE->getDecl(); 12183 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12184 ND = ME->getMemberDecl(); 12185 12186 if (index.isUnsigned() || !index.isNegative()) { 12187 llvm::APInt size = ArrayTy->getSize(); 12188 if (!size.isStrictlyPositive()) 12189 return; 12190 12191 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 12192 if (BaseType != EffectiveType) { 12193 // Make sure we're comparing apples to apples when comparing index to size 12194 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12195 uint64_t array_typesize = Context.getTypeSize(BaseType); 12196 // Handle ptrarith_typesize being zero, such as when casting to void* 12197 if (!ptrarith_typesize) ptrarith_typesize = 1; 12198 if (ptrarith_typesize != array_typesize) { 12199 // There's a cast to a different size type involved 12200 uint64_t ratio = array_typesize / ptrarith_typesize; 12201 // TODO: Be smarter about handling cases where array_typesize is not a 12202 // multiple of ptrarith_typesize 12203 if (ptrarith_typesize * ratio == array_typesize) 12204 size *= llvm::APInt(size.getBitWidth(), ratio); 12205 } 12206 } 12207 12208 if (size.getBitWidth() > index.getBitWidth()) 12209 index = index.zext(size.getBitWidth()); 12210 else if (size.getBitWidth() < index.getBitWidth()) 12211 size = size.zext(index.getBitWidth()); 12212 12213 // For array subscripting the index must be less than size, but for pointer 12214 // arithmetic also allow the index (offset) to be equal to size since 12215 // computing the next address after the end of the array is legal and 12216 // commonly done e.g. in C++ iterators and range-based for loops. 12217 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12218 return; 12219 12220 // Also don't warn for arrays of size 1 which are members of some 12221 // structure. These are often used to approximate flexible arrays in C89 12222 // code. 12223 if (IsTailPaddedMemberArray(*this, size, ND)) 12224 return; 12225 12226 // Suppress the warning if the subscript expression (as identified by the 12227 // ']' location) and the index expression are both from macro expansions 12228 // within a system header. 12229 if (ASE) { 12230 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12231 ASE->getRBracketLoc()); 12232 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12233 SourceLocation IndexLoc = 12234 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12235 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12236 return; 12237 } 12238 } 12239 12240 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12241 if (ASE) 12242 DiagID = diag::warn_array_index_exceeds_bounds; 12243 12244 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12245 PDiag(DiagID) << index.toString(10, true) 12246 << size.toString(10, true) 12247 << (unsigned)size.getLimitedValue(~0U) 12248 << IndexExpr->getSourceRange()); 12249 } else { 12250 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12251 if (!ASE) { 12252 DiagID = diag::warn_ptr_arith_precedes_bounds; 12253 if (index.isNegative()) index = -index; 12254 } 12255 12256 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12257 PDiag(DiagID) << index.toString(10, true) 12258 << IndexExpr->getSourceRange()); 12259 } 12260 12261 if (!ND) { 12262 // Try harder to find a NamedDecl to point at in the note. 12263 while (const ArraySubscriptExpr *ASE = 12264 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12265 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12266 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12267 ND = DRE->getDecl(); 12268 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12269 ND = ME->getMemberDecl(); 12270 } 12271 12272 if (ND) 12273 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12274 PDiag(diag::note_array_index_out_of_bounds) 12275 << ND->getDeclName()); 12276 } 12277 12278 void Sema::CheckArrayAccess(const Expr *expr) { 12279 int AllowOnePastEnd = 0; 12280 while (expr) { 12281 expr = expr->IgnoreParenImpCasts(); 12282 switch (expr->getStmtClass()) { 12283 case Stmt::ArraySubscriptExprClass: { 12284 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12285 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12286 AllowOnePastEnd > 0); 12287 expr = ASE->getBase(); 12288 break; 12289 } 12290 case Stmt::MemberExprClass: { 12291 expr = cast<MemberExpr>(expr)->getBase(); 12292 break; 12293 } 12294 case Stmt::OMPArraySectionExprClass: { 12295 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12296 if (ASE->getLowerBound()) 12297 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12298 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12299 return; 12300 } 12301 case Stmt::UnaryOperatorClass: { 12302 // Only unwrap the * and & unary operators 12303 const UnaryOperator *UO = cast<UnaryOperator>(expr); 12304 expr = UO->getSubExpr(); 12305 switch (UO->getOpcode()) { 12306 case UO_AddrOf: 12307 AllowOnePastEnd++; 12308 break; 12309 case UO_Deref: 12310 AllowOnePastEnd--; 12311 break; 12312 default: 12313 return; 12314 } 12315 break; 12316 } 12317 case Stmt::ConditionalOperatorClass: { 12318 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 12319 if (const Expr *lhs = cond->getLHS()) 12320 CheckArrayAccess(lhs); 12321 if (const Expr *rhs = cond->getRHS()) 12322 CheckArrayAccess(rhs); 12323 return; 12324 } 12325 case Stmt::CXXOperatorCallExprClass: { 12326 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 12327 for (const auto *Arg : OCE->arguments()) 12328 CheckArrayAccess(Arg); 12329 return; 12330 } 12331 default: 12332 return; 12333 } 12334 } 12335 } 12336 12337 //===--- CHECK: Objective-C retain cycles ----------------------------------// 12338 12339 namespace { 12340 12341 struct RetainCycleOwner { 12342 VarDecl *Variable = nullptr; 12343 SourceRange Range; 12344 SourceLocation Loc; 12345 bool Indirect = false; 12346 12347 RetainCycleOwner() = default; 12348 12349 void setLocsFrom(Expr *e) { 12350 Loc = e->getExprLoc(); 12351 Range = e->getSourceRange(); 12352 } 12353 }; 12354 12355 } // namespace 12356 12357 /// Consider whether capturing the given variable can possibly lead to 12358 /// a retain cycle. 12359 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 12360 // In ARC, it's captured strongly iff the variable has __strong 12361 // lifetime. In MRR, it's captured strongly if the variable is 12362 // __block and has an appropriate type. 12363 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12364 return false; 12365 12366 owner.Variable = var; 12367 if (ref) 12368 owner.setLocsFrom(ref); 12369 return true; 12370 } 12371 12372 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 12373 while (true) { 12374 e = e->IgnoreParens(); 12375 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 12376 switch (cast->getCastKind()) { 12377 case CK_BitCast: 12378 case CK_LValueBitCast: 12379 case CK_LValueToRValue: 12380 case CK_ARCReclaimReturnedObject: 12381 e = cast->getSubExpr(); 12382 continue; 12383 12384 default: 12385 return false; 12386 } 12387 } 12388 12389 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 12390 ObjCIvarDecl *ivar = ref->getDecl(); 12391 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12392 return false; 12393 12394 // Try to find a retain cycle in the base. 12395 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 12396 return false; 12397 12398 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 12399 owner.Indirect = true; 12400 return true; 12401 } 12402 12403 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 12404 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 12405 if (!var) return false; 12406 return considerVariable(var, ref, owner); 12407 } 12408 12409 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 12410 if (member->isArrow()) return false; 12411 12412 // Don't count this as an indirect ownership. 12413 e = member->getBase(); 12414 continue; 12415 } 12416 12417 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 12418 // Only pay attention to pseudo-objects on property references. 12419 ObjCPropertyRefExpr *pre 12420 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 12421 ->IgnoreParens()); 12422 if (!pre) return false; 12423 if (pre->isImplicitProperty()) return false; 12424 ObjCPropertyDecl *property = pre->getExplicitProperty(); 12425 if (!property->isRetaining() && 12426 !(property->getPropertyIvarDecl() && 12427 property->getPropertyIvarDecl()->getType() 12428 .getObjCLifetime() == Qualifiers::OCL_Strong)) 12429 return false; 12430 12431 owner.Indirect = true; 12432 if (pre->isSuperReceiver()) { 12433 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 12434 if (!owner.Variable) 12435 return false; 12436 owner.Loc = pre->getLocation(); 12437 owner.Range = pre->getSourceRange(); 12438 return true; 12439 } 12440 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 12441 ->getSourceExpr()); 12442 continue; 12443 } 12444 12445 // Array ivars? 12446 12447 return false; 12448 } 12449 } 12450 12451 namespace { 12452 12453 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 12454 ASTContext &Context; 12455 VarDecl *Variable; 12456 Expr *Capturer = nullptr; 12457 bool VarWillBeReased = false; 12458 12459 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 12460 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 12461 Context(Context), Variable(variable) {} 12462 12463 void VisitDeclRefExpr(DeclRefExpr *ref) { 12464 if (ref->getDecl() == Variable && !Capturer) 12465 Capturer = ref; 12466 } 12467 12468 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 12469 if (Capturer) return; 12470 Visit(ref->getBase()); 12471 if (Capturer && ref->isFreeIvar()) 12472 Capturer = ref; 12473 } 12474 12475 void VisitBlockExpr(BlockExpr *block) { 12476 // Look inside nested blocks 12477 if (block->getBlockDecl()->capturesVariable(Variable)) 12478 Visit(block->getBlockDecl()->getBody()); 12479 } 12480 12481 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 12482 if (Capturer) return; 12483 if (OVE->getSourceExpr()) 12484 Visit(OVE->getSourceExpr()); 12485 } 12486 12487 void VisitBinaryOperator(BinaryOperator *BinOp) { 12488 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 12489 return; 12490 Expr *LHS = BinOp->getLHS(); 12491 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 12492 if (DRE->getDecl() != Variable) 12493 return; 12494 if (Expr *RHS = BinOp->getRHS()) { 12495 RHS = RHS->IgnoreParenCasts(); 12496 llvm::APSInt Value; 12497 VarWillBeReased = 12498 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 12499 } 12500 } 12501 } 12502 }; 12503 12504 } // namespace 12505 12506 /// Check whether the given argument is a block which captures a 12507 /// variable. 12508 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 12509 assert(owner.Variable && owner.Loc.isValid()); 12510 12511 e = e->IgnoreParenCasts(); 12512 12513 // Look through [^{...} copy] and Block_copy(^{...}). 12514 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 12515 Selector Cmd = ME->getSelector(); 12516 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 12517 e = ME->getInstanceReceiver(); 12518 if (!e) 12519 return nullptr; 12520 e = e->IgnoreParenCasts(); 12521 } 12522 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 12523 if (CE->getNumArgs() == 1) { 12524 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 12525 if (Fn) { 12526 const IdentifierInfo *FnI = Fn->getIdentifier(); 12527 if (FnI && FnI->isStr("_Block_copy")) { 12528 e = CE->getArg(0)->IgnoreParenCasts(); 12529 } 12530 } 12531 } 12532 } 12533 12534 BlockExpr *block = dyn_cast<BlockExpr>(e); 12535 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 12536 return nullptr; 12537 12538 FindCaptureVisitor visitor(S.Context, owner.Variable); 12539 visitor.Visit(block->getBlockDecl()->getBody()); 12540 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 12541 } 12542 12543 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 12544 RetainCycleOwner &owner) { 12545 assert(capturer); 12546 assert(owner.Variable && owner.Loc.isValid()); 12547 12548 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 12549 << owner.Variable << capturer->getSourceRange(); 12550 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 12551 << owner.Indirect << owner.Range; 12552 } 12553 12554 /// Check for a keyword selector that starts with the word 'add' or 12555 /// 'set'. 12556 static bool isSetterLikeSelector(Selector sel) { 12557 if (sel.isUnarySelector()) return false; 12558 12559 StringRef str = sel.getNameForSlot(0); 12560 while (!str.empty() && str.front() == '_') str = str.substr(1); 12561 if (str.startswith("set")) 12562 str = str.substr(3); 12563 else if (str.startswith("add")) { 12564 // Specially whitelist 'addOperationWithBlock:'. 12565 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12566 return false; 12567 str = str.substr(3); 12568 } 12569 else 12570 return false; 12571 12572 if (str.empty()) return true; 12573 return !isLowercase(str.front()); 12574 } 12575 12576 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12577 ObjCMessageExpr *Message) { 12578 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12579 Message->getReceiverInterface(), 12580 NSAPI::ClassId_NSMutableArray); 12581 if (!IsMutableArray) { 12582 return None; 12583 } 12584 12585 Selector Sel = Message->getSelector(); 12586 12587 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12588 S.NSAPIObj->getNSArrayMethodKind(Sel); 12589 if (!MKOpt) { 12590 return None; 12591 } 12592 12593 NSAPI::NSArrayMethodKind MK = *MKOpt; 12594 12595 switch (MK) { 12596 case NSAPI::NSMutableArr_addObject: 12597 case NSAPI::NSMutableArr_insertObjectAtIndex: 12598 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12599 return 0; 12600 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12601 return 1; 12602 12603 default: 12604 return None; 12605 } 12606 12607 return None; 12608 } 12609 12610 static 12611 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12612 ObjCMessageExpr *Message) { 12613 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12614 Message->getReceiverInterface(), 12615 NSAPI::ClassId_NSMutableDictionary); 12616 if (!IsMutableDictionary) { 12617 return None; 12618 } 12619 12620 Selector Sel = Message->getSelector(); 12621 12622 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 12623 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 12624 if (!MKOpt) { 12625 return None; 12626 } 12627 12628 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 12629 12630 switch (MK) { 12631 case NSAPI::NSMutableDict_setObjectForKey: 12632 case NSAPI::NSMutableDict_setValueForKey: 12633 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 12634 return 0; 12635 12636 default: 12637 return None; 12638 } 12639 12640 return None; 12641 } 12642 12643 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 12644 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 12645 Message->getReceiverInterface(), 12646 NSAPI::ClassId_NSMutableSet); 12647 12648 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 12649 Message->getReceiverInterface(), 12650 NSAPI::ClassId_NSMutableOrderedSet); 12651 if (!IsMutableSet && !IsMutableOrderedSet) { 12652 return None; 12653 } 12654 12655 Selector Sel = Message->getSelector(); 12656 12657 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 12658 if (!MKOpt) { 12659 return None; 12660 } 12661 12662 NSAPI::NSSetMethodKind MK = *MKOpt; 12663 12664 switch (MK) { 12665 case NSAPI::NSMutableSet_addObject: 12666 case NSAPI::NSOrderedSet_setObjectAtIndex: 12667 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 12668 case NSAPI::NSOrderedSet_insertObjectAtIndex: 12669 return 0; 12670 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 12671 return 1; 12672 } 12673 12674 return None; 12675 } 12676 12677 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 12678 if (!Message->isInstanceMessage()) { 12679 return; 12680 } 12681 12682 Optional<int> ArgOpt; 12683 12684 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 12685 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 12686 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 12687 return; 12688 } 12689 12690 int ArgIndex = *ArgOpt; 12691 12692 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 12693 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 12694 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 12695 } 12696 12697 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 12698 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12699 if (ArgRE->isObjCSelfExpr()) { 12700 Diag(Message->getSourceRange().getBegin(), 12701 diag::warn_objc_circular_container) 12702 << ArgRE->getDecl() << StringRef("'super'"); 12703 } 12704 } 12705 } else { 12706 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 12707 12708 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 12709 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 12710 } 12711 12712 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 12713 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12714 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 12715 ValueDecl *Decl = ReceiverRE->getDecl(); 12716 Diag(Message->getSourceRange().getBegin(), 12717 diag::warn_objc_circular_container) 12718 << Decl << Decl; 12719 if (!ArgRE->isObjCSelfExpr()) { 12720 Diag(Decl->getLocation(), 12721 diag::note_objc_circular_container_declared_here) 12722 << Decl; 12723 } 12724 } 12725 } 12726 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12727 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12728 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12729 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12730 Diag(Message->getSourceRange().getBegin(), 12731 diag::warn_objc_circular_container) 12732 << Decl << Decl; 12733 Diag(Decl->getLocation(), 12734 diag::note_objc_circular_container_declared_here) 12735 << Decl; 12736 } 12737 } 12738 } 12739 } 12740 } 12741 12742 /// Check a message send to see if it's likely to cause a retain cycle. 12743 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 12744 // Only check instance methods whose selector looks like a setter. 12745 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12746 return; 12747 12748 // Try to find a variable that the receiver is strongly owned by. 12749 RetainCycleOwner owner; 12750 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12751 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12752 return; 12753 } else { 12754 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12755 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12756 owner.Loc = msg->getSuperLoc(); 12757 owner.Range = msg->getSuperLoc(); 12758 } 12759 12760 // Check whether the receiver is captured by any of the arguments. 12761 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12762 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12763 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12764 // noescape blocks should not be retained by the method. 12765 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 12766 continue; 12767 return diagnoseRetainCycle(*this, capturer, owner); 12768 } 12769 } 12770 } 12771 12772 /// Check a property assign to see if it's likely to cause a retain cycle. 12773 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 12774 RetainCycleOwner owner; 12775 if (!findRetainCycleOwner(*this, receiver, owner)) 12776 return; 12777 12778 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 12779 diagnoseRetainCycle(*this, capturer, owner); 12780 } 12781 12782 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 12783 RetainCycleOwner Owner; 12784 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 12785 return; 12786 12787 // Because we don't have an expression for the variable, we have to set the 12788 // location explicitly here. 12789 Owner.Loc = Var->getLocation(); 12790 Owner.Range = Var->getSourceRange(); 12791 12792 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 12793 diagnoseRetainCycle(*this, Capturer, Owner); 12794 } 12795 12796 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 12797 Expr *RHS, bool isProperty) { 12798 // Check if RHS is an Objective-C object literal, which also can get 12799 // immediately zapped in a weak reference. Note that we explicitly 12800 // allow ObjCStringLiterals, since those are designed to never really die. 12801 RHS = RHS->IgnoreParenImpCasts(); 12802 12803 // This enum needs to match with the 'select' in 12804 // warn_objc_arc_literal_assign (off-by-1). 12805 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 12806 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 12807 return false; 12808 12809 S.Diag(Loc, diag::warn_arc_literal_assign) 12810 << (unsigned) Kind 12811 << (isProperty ? 0 : 1) 12812 << RHS->getSourceRange(); 12813 12814 return true; 12815 } 12816 12817 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 12818 Qualifiers::ObjCLifetime LT, 12819 Expr *RHS, bool isProperty) { 12820 // Strip off any implicit cast added to get to the one ARC-specific. 12821 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12822 if (cast->getCastKind() == CK_ARCConsumeObject) { 12823 S.Diag(Loc, diag::warn_arc_retained_assign) 12824 << (LT == Qualifiers::OCL_ExplicitNone) 12825 << (isProperty ? 0 : 1) 12826 << RHS->getSourceRange(); 12827 return true; 12828 } 12829 RHS = cast->getSubExpr(); 12830 } 12831 12832 if (LT == Qualifiers::OCL_Weak && 12833 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 12834 return true; 12835 12836 return false; 12837 } 12838 12839 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 12840 QualType LHS, Expr *RHS) { 12841 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 12842 12843 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 12844 return false; 12845 12846 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 12847 return true; 12848 12849 return false; 12850 } 12851 12852 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 12853 Expr *LHS, Expr *RHS) { 12854 QualType LHSType; 12855 // PropertyRef on LHS type need be directly obtained from 12856 // its declaration as it has a PseudoType. 12857 ObjCPropertyRefExpr *PRE 12858 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 12859 if (PRE && !PRE->isImplicitProperty()) { 12860 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12861 if (PD) 12862 LHSType = PD->getType(); 12863 } 12864 12865 if (LHSType.isNull()) 12866 LHSType = LHS->getType(); 12867 12868 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 12869 12870 if (LT == Qualifiers::OCL_Weak) { 12871 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 12872 getCurFunction()->markSafeWeakUse(LHS); 12873 } 12874 12875 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 12876 return; 12877 12878 // FIXME. Check for other life times. 12879 if (LT != Qualifiers::OCL_None) 12880 return; 12881 12882 if (PRE) { 12883 if (PRE->isImplicitProperty()) 12884 return; 12885 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12886 if (!PD) 12887 return; 12888 12889 unsigned Attributes = PD->getPropertyAttributes(); 12890 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 12891 // when 'assign' attribute was not explicitly specified 12892 // by user, ignore it and rely on property type itself 12893 // for lifetime info. 12894 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 12895 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 12896 LHSType->isObjCRetainableType()) 12897 return; 12898 12899 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12900 if (cast->getCastKind() == CK_ARCConsumeObject) { 12901 Diag(Loc, diag::warn_arc_retained_property_assign) 12902 << RHS->getSourceRange(); 12903 return; 12904 } 12905 RHS = cast->getSubExpr(); 12906 } 12907 } 12908 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 12909 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 12910 return; 12911 } 12912 } 12913 } 12914 12915 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 12916 12917 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 12918 SourceLocation StmtLoc, 12919 const NullStmt *Body) { 12920 // Do not warn if the body is a macro that expands to nothing, e.g: 12921 // 12922 // #define CALL(x) 12923 // if (condition) 12924 // CALL(0); 12925 if (Body->hasLeadingEmptyMacro()) 12926 return false; 12927 12928 // Get line numbers of statement and body. 12929 bool StmtLineInvalid; 12930 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 12931 &StmtLineInvalid); 12932 if (StmtLineInvalid) 12933 return false; 12934 12935 bool BodyLineInvalid; 12936 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 12937 &BodyLineInvalid); 12938 if (BodyLineInvalid) 12939 return false; 12940 12941 // Warn if null statement and body are on the same line. 12942 if (StmtLine != BodyLine) 12943 return false; 12944 12945 return true; 12946 } 12947 12948 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 12949 const Stmt *Body, 12950 unsigned DiagID) { 12951 // Since this is a syntactic check, don't emit diagnostic for template 12952 // instantiations, this just adds noise. 12953 if (CurrentInstantiationScope) 12954 return; 12955 12956 // The body should be a null statement. 12957 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12958 if (!NBody) 12959 return; 12960 12961 // Do the usual checks. 12962 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12963 return; 12964 12965 Diag(NBody->getSemiLoc(), DiagID); 12966 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12967 } 12968 12969 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 12970 const Stmt *PossibleBody) { 12971 assert(!CurrentInstantiationScope); // Ensured by caller 12972 12973 SourceLocation StmtLoc; 12974 const Stmt *Body; 12975 unsigned DiagID; 12976 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 12977 StmtLoc = FS->getRParenLoc(); 12978 Body = FS->getBody(); 12979 DiagID = diag::warn_empty_for_body; 12980 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 12981 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 12982 Body = WS->getBody(); 12983 DiagID = diag::warn_empty_while_body; 12984 } else 12985 return; // Neither `for' nor `while'. 12986 12987 // The body should be a null statement. 12988 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12989 if (!NBody) 12990 return; 12991 12992 // Skip expensive checks if diagnostic is disabled. 12993 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 12994 return; 12995 12996 // Do the usual checks. 12997 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12998 return; 12999 13000 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13001 // noise level low, emit diagnostics only if for/while is followed by a 13002 // CompoundStmt, e.g.: 13003 // for (int i = 0; i < n; i++); 13004 // { 13005 // a(i); 13006 // } 13007 // or if for/while is followed by a statement with more indentation 13008 // than for/while itself: 13009 // for (int i = 0; i < n; i++); 13010 // a(i); 13011 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13012 if (!ProbableTypo) { 13013 bool BodyColInvalid; 13014 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13015 PossibleBody->getBeginLoc(), &BodyColInvalid); 13016 if (BodyColInvalid) 13017 return; 13018 13019 bool StmtColInvalid; 13020 unsigned StmtCol = 13021 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13022 if (StmtColInvalid) 13023 return; 13024 13025 if (BodyCol > StmtCol) 13026 ProbableTypo = true; 13027 } 13028 13029 if (ProbableTypo) { 13030 Diag(NBody->getSemiLoc(), DiagID); 13031 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13032 } 13033 } 13034 13035 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13036 13037 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13038 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13039 SourceLocation OpLoc) { 13040 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13041 return; 13042 13043 if (inTemplateInstantiation()) 13044 return; 13045 13046 // Strip parens and casts away. 13047 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13048 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13049 13050 // Check for a call expression 13051 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13052 if (!CE || CE->getNumArgs() != 1) 13053 return; 13054 13055 // Check for a call to std::move 13056 if (!CE->isCallToStdMove()) 13057 return; 13058 13059 // Get argument from std::move 13060 RHSExpr = CE->getArg(0); 13061 13062 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13063 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13064 13065 // Two DeclRefExpr's, check that the decls are the same. 13066 if (LHSDeclRef && RHSDeclRef) { 13067 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13068 return; 13069 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13070 RHSDeclRef->getDecl()->getCanonicalDecl()) 13071 return; 13072 13073 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13074 << LHSExpr->getSourceRange() 13075 << RHSExpr->getSourceRange(); 13076 return; 13077 } 13078 13079 // Member variables require a different approach to check for self moves. 13080 // MemberExpr's are the same if every nested MemberExpr refers to the same 13081 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13082 // the base Expr's are CXXThisExpr's. 13083 const Expr *LHSBase = LHSExpr; 13084 const Expr *RHSBase = RHSExpr; 13085 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13086 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13087 if (!LHSME || !RHSME) 13088 return; 13089 13090 while (LHSME && RHSME) { 13091 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13092 RHSME->getMemberDecl()->getCanonicalDecl()) 13093 return; 13094 13095 LHSBase = LHSME->getBase(); 13096 RHSBase = RHSME->getBase(); 13097 LHSME = dyn_cast<MemberExpr>(LHSBase); 13098 RHSME = dyn_cast<MemberExpr>(RHSBase); 13099 } 13100 13101 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13102 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13103 if (LHSDeclRef && RHSDeclRef) { 13104 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13105 return; 13106 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13107 RHSDeclRef->getDecl()->getCanonicalDecl()) 13108 return; 13109 13110 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13111 << LHSExpr->getSourceRange() 13112 << RHSExpr->getSourceRange(); 13113 return; 13114 } 13115 13116 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13117 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13118 << LHSExpr->getSourceRange() 13119 << RHSExpr->getSourceRange(); 13120 } 13121 13122 //===--- Layout compatibility ----------------------------------------------// 13123 13124 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13125 13126 /// Check if two enumeration types are layout-compatible. 13127 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13128 // C++11 [dcl.enum] p8: 13129 // Two enumeration types are layout-compatible if they have the same 13130 // underlying type. 13131 return ED1->isComplete() && ED2->isComplete() && 13132 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13133 } 13134 13135 /// Check if two fields are layout-compatible. 13136 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13137 FieldDecl *Field2) { 13138 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13139 return false; 13140 13141 if (Field1->isBitField() != Field2->isBitField()) 13142 return false; 13143 13144 if (Field1->isBitField()) { 13145 // Make sure that the bit-fields are the same length. 13146 unsigned Bits1 = Field1->getBitWidthValue(C); 13147 unsigned Bits2 = Field2->getBitWidthValue(C); 13148 13149 if (Bits1 != Bits2) 13150 return false; 13151 } 13152 13153 return true; 13154 } 13155 13156 /// Check if two standard-layout structs are layout-compatible. 13157 /// (C++11 [class.mem] p17) 13158 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13159 RecordDecl *RD2) { 13160 // If both records are C++ classes, check that base classes match. 13161 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13162 // If one of records is a CXXRecordDecl we are in C++ mode, 13163 // thus the other one is a CXXRecordDecl, too. 13164 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13165 // Check number of base classes. 13166 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13167 return false; 13168 13169 // Check the base classes. 13170 for (CXXRecordDecl::base_class_const_iterator 13171 Base1 = D1CXX->bases_begin(), 13172 BaseEnd1 = D1CXX->bases_end(), 13173 Base2 = D2CXX->bases_begin(); 13174 Base1 != BaseEnd1; 13175 ++Base1, ++Base2) { 13176 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13177 return false; 13178 } 13179 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13180 // If only RD2 is a C++ class, it should have zero base classes. 13181 if (D2CXX->getNumBases() > 0) 13182 return false; 13183 } 13184 13185 // Check the fields. 13186 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13187 Field2End = RD2->field_end(), 13188 Field1 = RD1->field_begin(), 13189 Field1End = RD1->field_end(); 13190 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13191 if (!isLayoutCompatible(C, *Field1, *Field2)) 13192 return false; 13193 } 13194 if (Field1 != Field1End || Field2 != Field2End) 13195 return false; 13196 13197 return true; 13198 } 13199 13200 /// Check if two standard-layout unions are layout-compatible. 13201 /// (C++11 [class.mem] p18) 13202 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13203 RecordDecl *RD2) { 13204 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13205 for (auto *Field2 : RD2->fields()) 13206 UnmatchedFields.insert(Field2); 13207 13208 for (auto *Field1 : RD1->fields()) { 13209 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13210 I = UnmatchedFields.begin(), 13211 E = UnmatchedFields.end(); 13212 13213 for ( ; I != E; ++I) { 13214 if (isLayoutCompatible(C, Field1, *I)) { 13215 bool Result = UnmatchedFields.erase(*I); 13216 (void) Result; 13217 assert(Result); 13218 break; 13219 } 13220 } 13221 if (I == E) 13222 return false; 13223 } 13224 13225 return UnmatchedFields.empty(); 13226 } 13227 13228 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13229 RecordDecl *RD2) { 13230 if (RD1->isUnion() != RD2->isUnion()) 13231 return false; 13232 13233 if (RD1->isUnion()) 13234 return isLayoutCompatibleUnion(C, RD1, RD2); 13235 else 13236 return isLayoutCompatibleStruct(C, RD1, RD2); 13237 } 13238 13239 /// Check if two types are layout-compatible in C++11 sense. 13240 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13241 if (T1.isNull() || T2.isNull()) 13242 return false; 13243 13244 // C++11 [basic.types] p11: 13245 // If two types T1 and T2 are the same type, then T1 and T2 are 13246 // layout-compatible types. 13247 if (C.hasSameType(T1, T2)) 13248 return true; 13249 13250 T1 = T1.getCanonicalType().getUnqualifiedType(); 13251 T2 = T2.getCanonicalType().getUnqualifiedType(); 13252 13253 const Type::TypeClass TC1 = T1->getTypeClass(); 13254 const Type::TypeClass TC2 = T2->getTypeClass(); 13255 13256 if (TC1 != TC2) 13257 return false; 13258 13259 if (TC1 == Type::Enum) { 13260 return isLayoutCompatible(C, 13261 cast<EnumType>(T1)->getDecl(), 13262 cast<EnumType>(T2)->getDecl()); 13263 } else if (TC1 == Type::Record) { 13264 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13265 return false; 13266 13267 return isLayoutCompatible(C, 13268 cast<RecordType>(T1)->getDecl(), 13269 cast<RecordType>(T2)->getDecl()); 13270 } 13271 13272 return false; 13273 } 13274 13275 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13276 13277 /// Given a type tag expression find the type tag itself. 13278 /// 13279 /// \param TypeExpr Type tag expression, as it appears in user's code. 13280 /// 13281 /// \param VD Declaration of an identifier that appears in a type tag. 13282 /// 13283 /// \param MagicValue Type tag magic value. 13284 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13285 const ValueDecl **VD, uint64_t *MagicValue) { 13286 while(true) { 13287 if (!TypeExpr) 13288 return false; 13289 13290 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13291 13292 switch (TypeExpr->getStmtClass()) { 13293 case Stmt::UnaryOperatorClass: { 13294 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13295 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13296 TypeExpr = UO->getSubExpr(); 13297 continue; 13298 } 13299 return false; 13300 } 13301 13302 case Stmt::DeclRefExprClass: { 13303 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 13304 *VD = DRE->getDecl(); 13305 return true; 13306 } 13307 13308 case Stmt::IntegerLiteralClass: { 13309 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 13310 llvm::APInt MagicValueAPInt = IL->getValue(); 13311 if (MagicValueAPInt.getActiveBits() <= 64) { 13312 *MagicValue = MagicValueAPInt.getZExtValue(); 13313 return true; 13314 } else 13315 return false; 13316 } 13317 13318 case Stmt::BinaryConditionalOperatorClass: 13319 case Stmt::ConditionalOperatorClass: { 13320 const AbstractConditionalOperator *ACO = 13321 cast<AbstractConditionalOperator>(TypeExpr); 13322 bool Result; 13323 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 13324 if (Result) 13325 TypeExpr = ACO->getTrueExpr(); 13326 else 13327 TypeExpr = ACO->getFalseExpr(); 13328 continue; 13329 } 13330 return false; 13331 } 13332 13333 case Stmt::BinaryOperatorClass: { 13334 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 13335 if (BO->getOpcode() == BO_Comma) { 13336 TypeExpr = BO->getRHS(); 13337 continue; 13338 } 13339 return false; 13340 } 13341 13342 default: 13343 return false; 13344 } 13345 } 13346 } 13347 13348 /// Retrieve the C type corresponding to type tag TypeExpr. 13349 /// 13350 /// \param TypeExpr Expression that specifies a type tag. 13351 /// 13352 /// \param MagicValues Registered magic values. 13353 /// 13354 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 13355 /// kind. 13356 /// 13357 /// \param TypeInfo Information about the corresponding C type. 13358 /// 13359 /// \returns true if the corresponding C type was found. 13360 static bool GetMatchingCType( 13361 const IdentifierInfo *ArgumentKind, 13362 const Expr *TypeExpr, const ASTContext &Ctx, 13363 const llvm::DenseMap<Sema::TypeTagMagicValue, 13364 Sema::TypeTagData> *MagicValues, 13365 bool &FoundWrongKind, 13366 Sema::TypeTagData &TypeInfo) { 13367 FoundWrongKind = false; 13368 13369 // Variable declaration that has type_tag_for_datatype attribute. 13370 const ValueDecl *VD = nullptr; 13371 13372 uint64_t MagicValue; 13373 13374 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 13375 return false; 13376 13377 if (VD) { 13378 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 13379 if (I->getArgumentKind() != ArgumentKind) { 13380 FoundWrongKind = true; 13381 return false; 13382 } 13383 TypeInfo.Type = I->getMatchingCType(); 13384 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 13385 TypeInfo.MustBeNull = I->getMustBeNull(); 13386 return true; 13387 } 13388 return false; 13389 } 13390 13391 if (!MagicValues) 13392 return false; 13393 13394 llvm::DenseMap<Sema::TypeTagMagicValue, 13395 Sema::TypeTagData>::const_iterator I = 13396 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 13397 if (I == MagicValues->end()) 13398 return false; 13399 13400 TypeInfo = I->second; 13401 return true; 13402 } 13403 13404 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 13405 uint64_t MagicValue, QualType Type, 13406 bool LayoutCompatible, 13407 bool MustBeNull) { 13408 if (!TypeTagForDatatypeMagicValues) 13409 TypeTagForDatatypeMagicValues.reset( 13410 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 13411 13412 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 13413 (*TypeTagForDatatypeMagicValues)[Magic] = 13414 TypeTagData(Type, LayoutCompatible, MustBeNull); 13415 } 13416 13417 static bool IsSameCharType(QualType T1, QualType T2) { 13418 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 13419 if (!BT1) 13420 return false; 13421 13422 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 13423 if (!BT2) 13424 return false; 13425 13426 BuiltinType::Kind T1Kind = BT1->getKind(); 13427 BuiltinType::Kind T2Kind = BT2->getKind(); 13428 13429 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 13430 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 13431 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 13432 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 13433 } 13434 13435 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 13436 const ArrayRef<const Expr *> ExprArgs, 13437 SourceLocation CallSiteLoc) { 13438 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 13439 bool IsPointerAttr = Attr->getIsPointer(); 13440 13441 // Retrieve the argument representing the 'type_tag'. 13442 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 13443 if (TypeTagIdxAST >= ExprArgs.size()) { 13444 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13445 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 13446 return; 13447 } 13448 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 13449 bool FoundWrongKind; 13450 TypeTagData TypeInfo; 13451 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 13452 TypeTagForDatatypeMagicValues.get(), 13453 FoundWrongKind, TypeInfo)) { 13454 if (FoundWrongKind) 13455 Diag(TypeTagExpr->getExprLoc(), 13456 diag::warn_type_tag_for_datatype_wrong_kind) 13457 << TypeTagExpr->getSourceRange(); 13458 return; 13459 } 13460 13461 // Retrieve the argument representing the 'arg_idx'. 13462 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 13463 if (ArgumentIdxAST >= ExprArgs.size()) { 13464 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13465 << 1 << Attr->getArgumentIdx().getSourceIndex(); 13466 return; 13467 } 13468 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 13469 if (IsPointerAttr) { 13470 // Skip implicit cast of pointer to `void *' (as a function argument). 13471 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 13472 if (ICE->getType()->isVoidPointerType() && 13473 ICE->getCastKind() == CK_BitCast) 13474 ArgumentExpr = ICE->getSubExpr(); 13475 } 13476 QualType ArgumentType = ArgumentExpr->getType(); 13477 13478 // Passing a `void*' pointer shouldn't trigger a warning. 13479 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 13480 return; 13481 13482 if (TypeInfo.MustBeNull) { 13483 // Type tag with matching void type requires a null pointer. 13484 if (!ArgumentExpr->isNullPointerConstant(Context, 13485 Expr::NPC_ValueDependentIsNotNull)) { 13486 Diag(ArgumentExpr->getExprLoc(), 13487 diag::warn_type_safety_null_pointer_required) 13488 << ArgumentKind->getName() 13489 << ArgumentExpr->getSourceRange() 13490 << TypeTagExpr->getSourceRange(); 13491 } 13492 return; 13493 } 13494 13495 QualType RequiredType = TypeInfo.Type; 13496 if (IsPointerAttr) 13497 RequiredType = Context.getPointerType(RequiredType); 13498 13499 bool mismatch = false; 13500 if (!TypeInfo.LayoutCompatible) { 13501 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 13502 13503 // C++11 [basic.fundamental] p1: 13504 // Plain char, signed char, and unsigned char are three distinct types. 13505 // 13506 // But we treat plain `char' as equivalent to `signed char' or `unsigned 13507 // char' depending on the current char signedness mode. 13508 if (mismatch) 13509 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 13510 RequiredType->getPointeeType())) || 13511 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 13512 mismatch = false; 13513 } else 13514 if (IsPointerAttr) 13515 mismatch = !isLayoutCompatible(Context, 13516 ArgumentType->getPointeeType(), 13517 RequiredType->getPointeeType()); 13518 else 13519 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 13520 13521 if (mismatch) 13522 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 13523 << ArgumentType << ArgumentKind 13524 << TypeInfo.LayoutCompatible << RequiredType 13525 << ArgumentExpr->getSourceRange() 13526 << TypeTagExpr->getSourceRange(); 13527 } 13528 13529 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 13530 CharUnits Alignment) { 13531 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 13532 } 13533 13534 void Sema::DiagnoseMisalignedMembers() { 13535 for (MisalignedMember &m : MisalignedMembers) { 13536 const NamedDecl *ND = m.RD; 13537 if (ND->getName().empty()) { 13538 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 13539 ND = TD; 13540 } 13541 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 13542 << m.MD << ND << m.E->getSourceRange(); 13543 } 13544 MisalignedMembers.clear(); 13545 } 13546 13547 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 13548 E = E->IgnoreParens(); 13549 if (!T->isPointerType() && !T->isIntegerType()) 13550 return; 13551 if (isa<UnaryOperator>(E) && 13552 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13553 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13554 if (isa<MemberExpr>(Op)) { 13555 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 13556 MisalignedMember(Op)); 13557 if (MA != MisalignedMembers.end() && 13558 (T->isIntegerType() || 13559 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13560 Context.getTypeAlignInChars( 13561 T->getPointeeType()) <= MA->Alignment)))) 13562 MisalignedMembers.erase(MA); 13563 } 13564 } 13565 } 13566 13567 void Sema::RefersToMemberWithReducedAlignment( 13568 Expr *E, 13569 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13570 Action) { 13571 const auto *ME = dyn_cast<MemberExpr>(E); 13572 if (!ME) 13573 return; 13574 13575 // No need to check expressions with an __unaligned-qualified type. 13576 if (E->getType().getQualifiers().hasUnaligned()) 13577 return; 13578 13579 // For a chain of MemberExpr like "a.b.c.d" this list 13580 // will keep FieldDecl's like [d, c, b]. 13581 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13582 const MemberExpr *TopME = nullptr; 13583 bool AnyIsPacked = false; 13584 do { 13585 QualType BaseType = ME->getBase()->getType(); 13586 if (ME->isArrow()) 13587 BaseType = BaseType->getPointeeType(); 13588 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13589 if (RD->isInvalidDecl()) 13590 return; 13591 13592 ValueDecl *MD = ME->getMemberDecl(); 13593 auto *FD = dyn_cast<FieldDecl>(MD); 13594 // We do not care about non-data members. 13595 if (!FD || FD->isInvalidDecl()) 13596 return; 13597 13598 AnyIsPacked = 13599 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13600 ReverseMemberChain.push_back(FD); 13601 13602 TopME = ME; 13603 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13604 } while (ME); 13605 assert(TopME && "We did not compute a topmost MemberExpr!"); 13606 13607 // Not the scope of this diagnostic. 13608 if (!AnyIsPacked) 13609 return; 13610 13611 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13612 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13613 // TODO: The innermost base of the member expression may be too complicated. 13614 // For now, just disregard these cases. This is left for future 13615 // improvement. 13616 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13617 return; 13618 13619 // Alignment expected by the whole expression. 13620 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13621 13622 // No need to do anything else with this case. 13623 if (ExpectedAlignment.isOne()) 13624 return; 13625 13626 // Synthesize offset of the whole access. 13627 CharUnits Offset; 13628 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 13629 I++) { 13630 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 13631 } 13632 13633 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 13634 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 13635 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 13636 13637 // The base expression of the innermost MemberExpr may give 13638 // stronger guarantees than the class containing the member. 13639 if (DRE && !TopME->isArrow()) { 13640 const ValueDecl *VD = DRE->getDecl(); 13641 if (!VD->getType()->isReferenceType()) 13642 CompleteObjectAlignment = 13643 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 13644 } 13645 13646 // Check if the synthesized offset fulfills the alignment. 13647 if (Offset % ExpectedAlignment != 0 || 13648 // It may fulfill the offset it but the effective alignment may still be 13649 // lower than the expected expression alignment. 13650 CompleteObjectAlignment < ExpectedAlignment) { 13651 // If this happens, we want to determine a sensible culprit of this. 13652 // Intuitively, watching the chain of member expressions from right to 13653 // left, we start with the required alignment (as required by the field 13654 // type) but some packed attribute in that chain has reduced the alignment. 13655 // It may happen that another packed structure increases it again. But if 13656 // we are here such increase has not been enough. So pointing the first 13657 // FieldDecl that either is packed or else its RecordDecl is, 13658 // seems reasonable. 13659 FieldDecl *FD = nullptr; 13660 CharUnits Alignment; 13661 for (FieldDecl *FDI : ReverseMemberChain) { 13662 if (FDI->hasAttr<PackedAttr>() || 13663 FDI->getParent()->hasAttr<PackedAttr>()) { 13664 FD = FDI; 13665 Alignment = std::min( 13666 Context.getTypeAlignInChars(FD->getType()), 13667 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 13668 break; 13669 } 13670 } 13671 assert(FD && "We did not find a packed FieldDecl!"); 13672 Action(E, FD->getParent(), FD, Alignment); 13673 } 13674 } 13675 13676 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 13677 using namespace std::placeholders; 13678 13679 RefersToMemberWithReducedAlignment( 13680 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 13681 _2, _3, _4)); 13682 } 13683