1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/Stmt.h" 34 #include "clang/AST/TemplateBase.h" 35 #include "clang/AST/Type.h" 36 #include "clang/AST/TypeLoc.h" 37 #include "clang/AST/UnresolvedSet.h" 38 #include "clang/Basic/AddressSpaces.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/Diagnostic.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/OpenCLOptions.h" 45 #include "clang/Basic/OperatorKinds.h" 46 #include "clang/Basic/PartialDiagnostic.h" 47 #include "clang/Basic/SourceLocation.h" 48 #include "clang/Basic/SourceManager.h" 49 #include "clang/Basic/Specifiers.h" 50 #include "clang/Basic/SyncScope.h" 51 #include "clang/Basic/TargetBuiltins.h" 52 #include "clang/Basic/TargetCXXABI.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "clang/Basic/TypeTraits.h" 55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 56 #include "clang/Sema/Initialization.h" 57 #include "clang/Sema/Lookup.h" 58 #include "clang/Sema/Ownership.h" 59 #include "clang/Sema/Scope.h" 60 #include "clang/Sema/ScopeInfo.h" 61 #include "clang/Sema/Sema.h" 62 #include "clang/Sema/SemaInternal.h" 63 #include "llvm/ADT/APFloat.h" 64 #include "llvm/ADT/APInt.h" 65 #include "llvm/ADT/APSInt.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/FoldingSet.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/SmallBitVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallString.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSwitch.h" 78 #include "llvm/ADT/Triple.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/ConvertUTF.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/Locale.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include <algorithm> 89 #include <cassert> 90 #include <cstddef> 91 #include <cstdint> 92 #include <functional> 93 #include <limits> 94 #include <string> 95 #include <tuple> 96 #include <utility> 97 98 using namespace clang; 99 using namespace sema; 100 101 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 102 unsigned ByteNo) const { 103 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 104 Context.getTargetInfo()); 105 } 106 107 /// Checks that a call expression's argument count is the desired number. 108 /// This is useful when doing custom type-checking. Returns true on error. 109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 110 unsigned argCount = call->getNumArgs(); 111 if (argCount == desiredArgCount) return false; 112 113 if (argCount < desiredArgCount) 114 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 115 << 0 /*function call*/ << desiredArgCount << argCount 116 << call->getSourceRange(); 117 118 // Highlight all the excess arguments. 119 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 120 call->getArg(argCount - 1)->getEndLoc()); 121 122 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 123 << 0 /*function call*/ << desiredArgCount << argCount 124 << call->getArg(1)->getSourceRange(); 125 } 126 127 /// Check that the first argument to __builtin_annotation is an integer 128 /// and the second argument is a non-wide string literal. 129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 130 if (checkArgCount(S, TheCall, 2)) 131 return true; 132 133 // First argument should be an integer. 134 Expr *ValArg = TheCall->getArg(0); 135 QualType Ty = ValArg->getType(); 136 if (!Ty->isIntegerType()) { 137 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 138 << ValArg->getSourceRange(); 139 return true; 140 } 141 142 // Second argument should be a constant string. 143 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 144 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 145 if (!Literal || !Literal->isAscii()) { 146 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 147 << StrArg->getSourceRange(); 148 return true; 149 } 150 151 TheCall->setType(Ty); 152 return false; 153 } 154 155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 156 // We need at least one argument. 157 if (TheCall->getNumArgs() < 1) { 158 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 159 << 0 << 1 << TheCall->getNumArgs() 160 << TheCall->getCallee()->getSourceRange(); 161 return true; 162 } 163 164 // All arguments should be wide string literals. 165 for (Expr *Arg : TheCall->arguments()) { 166 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 167 if (!Literal || !Literal->isWide()) { 168 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 169 << Arg->getSourceRange(); 170 return true; 171 } 172 } 173 174 return false; 175 } 176 177 /// Check that the argument to __builtin_addressof is a glvalue, and set the 178 /// result type to the corresponding pointer type. 179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 180 if (checkArgCount(S, TheCall, 1)) 181 return true; 182 183 ExprResult Arg(TheCall->getArg(0)); 184 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 185 if (ResultType.isNull()) 186 return true; 187 188 TheCall->setArg(0, Arg.get()); 189 TheCall->setType(ResultType); 190 return false; 191 } 192 193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 194 if (checkArgCount(S, TheCall, 3)) 195 return true; 196 197 // First two arguments should be integers. 198 for (unsigned I = 0; I < 2; ++I) { 199 ExprResult Arg = TheCall->getArg(I); 200 QualType Ty = Arg.get()->getType(); 201 if (!Ty->isIntegerType()) { 202 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 203 << Ty << Arg.get()->getSourceRange(); 204 return true; 205 } 206 InitializedEntity Entity = InitializedEntity::InitializeParameter( 207 S.getASTContext(), Ty, /*consume*/ false); 208 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 209 if (Arg.isInvalid()) 210 return true; 211 TheCall->setArg(I, Arg.get()); 212 } 213 214 // Third argument should be a pointer to a non-const integer. 215 // IRGen correctly handles volatile, restrict, and address spaces, and 216 // the other qualifiers aren't possible. 217 { 218 ExprResult Arg = TheCall->getArg(2); 219 QualType Ty = Arg.get()->getType(); 220 const auto *PtrTy = Ty->getAs<PointerType>(); 221 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 222 !PtrTy->getPointeeType().isConstQualified())) { 223 S.Diag(Arg.get()->getBeginLoc(), 224 diag::err_overflow_builtin_must_be_ptr_int) 225 << Ty << Arg.get()->getSourceRange(); 226 return true; 227 } 228 InitializedEntity Entity = InitializedEntity::InitializeParameter( 229 S.getASTContext(), Ty, /*consume*/ false); 230 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 231 if (Arg.isInvalid()) 232 return true; 233 TheCall->setArg(2, Arg.get()); 234 } 235 return false; 236 } 237 238 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 239 CallExpr *TheCall, unsigned SizeIdx, 240 unsigned DstSizeIdx, 241 StringRef LikelyMacroName) { 242 if (TheCall->getNumArgs() <= SizeIdx || 243 TheCall->getNumArgs() <= DstSizeIdx) 244 return; 245 246 const Expr *SizeArg = TheCall->getArg(SizeIdx); 247 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 248 249 Expr::EvalResult SizeResult, DstSizeResult; 250 251 // find out if both sizes are known at compile time 252 if (!SizeArg->EvaluateAsInt(SizeResult, S.Context) || 253 !DstSizeArg->EvaluateAsInt(DstSizeResult, S.Context)) 254 return; 255 256 llvm::APSInt Size = SizeResult.Val.getInt(); 257 llvm::APSInt DstSize = DstSizeResult.Val.getInt(); 258 259 if (Size.ule(DstSize)) 260 return; 261 262 // Confirmed overflow, so generate the diagnostic. 263 StringRef FunctionName = FDecl->getName(); 264 SourceLocation SL = TheCall->getBeginLoc(); 265 SourceManager &SM = S.getSourceManager(); 266 // If we're in an expansion of a macro whose name corresponds to this builtin, 267 // use the simple macro name and location. 268 if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) == 269 LikelyMacroName) { 270 FunctionName = LikelyMacroName; 271 SL = SM.getImmediateMacroCallerLoc(SL); 272 } 273 274 S.Diag(SL, diag::warn_memcpy_chk_overflow) 275 << FunctionName << DstSize.toString(/*Radix=*/10) 276 << Size.toString(/*Radix=*/10); 277 } 278 279 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 280 if (checkArgCount(S, BuiltinCall, 2)) 281 return true; 282 283 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 284 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 285 Expr *Call = BuiltinCall->getArg(0); 286 Expr *Chain = BuiltinCall->getArg(1); 287 288 if (Call->getStmtClass() != Stmt::CallExprClass) { 289 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 290 << Call->getSourceRange(); 291 return true; 292 } 293 294 auto CE = cast<CallExpr>(Call); 295 if (CE->getCallee()->getType()->isBlockPointerType()) { 296 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 297 << Call->getSourceRange(); 298 return true; 299 } 300 301 const Decl *TargetDecl = CE->getCalleeDecl(); 302 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 303 if (FD->getBuiltinID()) { 304 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 305 << Call->getSourceRange(); 306 return true; 307 } 308 309 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 310 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 311 << Call->getSourceRange(); 312 return true; 313 } 314 315 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 316 if (ChainResult.isInvalid()) 317 return true; 318 if (!ChainResult.get()->getType()->isPointerType()) { 319 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 320 << Chain->getSourceRange(); 321 return true; 322 } 323 324 QualType ReturnTy = CE->getCallReturnType(S.Context); 325 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 326 QualType BuiltinTy = S.Context.getFunctionType( 327 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 328 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 329 330 Builtin = 331 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 332 333 BuiltinCall->setType(CE->getType()); 334 BuiltinCall->setValueKind(CE->getValueKind()); 335 BuiltinCall->setObjectKind(CE->getObjectKind()); 336 BuiltinCall->setCallee(Builtin); 337 BuiltinCall->setArg(1, ChainResult.get()); 338 339 return false; 340 } 341 342 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 343 Scope::ScopeFlags NeededScopeFlags, 344 unsigned DiagID) { 345 // Scopes aren't available during instantiation. Fortunately, builtin 346 // functions cannot be template args so they cannot be formed through template 347 // instantiation. Therefore checking once during the parse is sufficient. 348 if (SemaRef.inTemplateInstantiation()) 349 return false; 350 351 Scope *S = SemaRef.getCurScope(); 352 while (S && !S->isSEHExceptScope()) 353 S = S->getParent(); 354 if (!S || !(S->getFlags() & NeededScopeFlags)) { 355 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 356 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 357 << DRE->getDecl()->getIdentifier(); 358 return true; 359 } 360 361 return false; 362 } 363 364 static inline bool isBlockPointer(Expr *Arg) { 365 return Arg->getType()->isBlockPointerType(); 366 } 367 368 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 369 /// void*, which is a requirement of device side enqueue. 370 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 371 const BlockPointerType *BPT = 372 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 373 ArrayRef<QualType> Params = 374 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 375 unsigned ArgCounter = 0; 376 bool IllegalParams = false; 377 // Iterate through the block parameters until either one is found that is not 378 // a local void*, or the block is valid. 379 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 380 I != E; ++I, ++ArgCounter) { 381 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 382 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 383 LangAS::opencl_local) { 384 // Get the location of the error. If a block literal has been passed 385 // (BlockExpr) then we can point straight to the offending argument, 386 // else we just point to the variable reference. 387 SourceLocation ErrorLoc; 388 if (isa<BlockExpr>(BlockArg)) { 389 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 390 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 391 } else if (isa<DeclRefExpr>(BlockArg)) { 392 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 393 } 394 S.Diag(ErrorLoc, 395 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 396 IllegalParams = true; 397 } 398 } 399 400 return IllegalParams; 401 } 402 403 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 404 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 405 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 406 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 407 return true; 408 } 409 return false; 410 } 411 412 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 413 if (checkArgCount(S, TheCall, 2)) 414 return true; 415 416 if (checkOpenCLSubgroupExt(S, TheCall)) 417 return true; 418 419 // First argument is an ndrange_t type. 420 Expr *NDRangeArg = TheCall->getArg(0); 421 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 422 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 423 << TheCall->getDirectCallee() << "'ndrange_t'"; 424 return true; 425 } 426 427 Expr *BlockArg = TheCall->getArg(1); 428 if (!isBlockPointer(BlockArg)) { 429 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 430 << TheCall->getDirectCallee() << "block"; 431 return true; 432 } 433 return checkOpenCLBlockArgs(S, BlockArg); 434 } 435 436 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 437 /// get_kernel_work_group_size 438 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 439 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 440 if (checkArgCount(S, TheCall, 1)) 441 return true; 442 443 Expr *BlockArg = TheCall->getArg(0); 444 if (!isBlockPointer(BlockArg)) { 445 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 446 << TheCall->getDirectCallee() << "block"; 447 return true; 448 } 449 return checkOpenCLBlockArgs(S, BlockArg); 450 } 451 452 /// Diagnose integer type and any valid implicit conversion to it. 453 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 454 const QualType &IntType); 455 456 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 457 unsigned Start, unsigned End) { 458 bool IllegalParams = false; 459 for (unsigned I = Start; I <= End; ++I) 460 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 461 S.Context.getSizeType()); 462 return IllegalParams; 463 } 464 465 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 466 /// 'local void*' parameter of passed block. 467 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 468 Expr *BlockArg, 469 unsigned NumNonVarArgs) { 470 const BlockPointerType *BPT = 471 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 472 unsigned NumBlockParams = 473 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 474 unsigned TotalNumArgs = TheCall->getNumArgs(); 475 476 // For each argument passed to the block, a corresponding uint needs to 477 // be passed to describe the size of the local memory. 478 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 479 S.Diag(TheCall->getBeginLoc(), 480 diag::err_opencl_enqueue_kernel_local_size_args); 481 return true; 482 } 483 484 // Check that the sizes of the local memory are specified by integers. 485 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 486 TotalNumArgs - 1); 487 } 488 489 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 490 /// overload formats specified in Table 6.13.17.1. 491 /// int enqueue_kernel(queue_t queue, 492 /// kernel_enqueue_flags_t flags, 493 /// const ndrange_t ndrange, 494 /// void (^block)(void)) 495 /// int enqueue_kernel(queue_t queue, 496 /// kernel_enqueue_flags_t flags, 497 /// const ndrange_t ndrange, 498 /// uint num_events_in_wait_list, 499 /// clk_event_t *event_wait_list, 500 /// clk_event_t *event_ret, 501 /// void (^block)(void)) 502 /// int enqueue_kernel(queue_t queue, 503 /// kernel_enqueue_flags_t flags, 504 /// const ndrange_t ndrange, 505 /// void (^block)(local void*, ...), 506 /// uint size0, ...) 507 /// int enqueue_kernel(queue_t queue, 508 /// kernel_enqueue_flags_t flags, 509 /// const ndrange_t ndrange, 510 /// uint num_events_in_wait_list, 511 /// clk_event_t *event_wait_list, 512 /// clk_event_t *event_ret, 513 /// void (^block)(local void*, ...), 514 /// uint size0, ...) 515 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 516 unsigned NumArgs = TheCall->getNumArgs(); 517 518 if (NumArgs < 4) { 519 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args); 520 return true; 521 } 522 523 Expr *Arg0 = TheCall->getArg(0); 524 Expr *Arg1 = TheCall->getArg(1); 525 Expr *Arg2 = TheCall->getArg(2); 526 Expr *Arg3 = TheCall->getArg(3); 527 528 // First argument always needs to be a queue_t type. 529 if (!Arg0->getType()->isQueueT()) { 530 S.Diag(TheCall->getArg(0)->getBeginLoc(), 531 diag::err_opencl_builtin_expected_type) 532 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 533 return true; 534 } 535 536 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 537 if (!Arg1->getType()->isIntegerType()) { 538 S.Diag(TheCall->getArg(1)->getBeginLoc(), 539 diag::err_opencl_builtin_expected_type) 540 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 541 return true; 542 } 543 544 // Third argument is always an ndrange_t type. 545 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 546 S.Diag(TheCall->getArg(2)->getBeginLoc(), 547 diag::err_opencl_builtin_expected_type) 548 << TheCall->getDirectCallee() << "'ndrange_t'"; 549 return true; 550 } 551 552 // With four arguments, there is only one form that the function could be 553 // called in: no events and no variable arguments. 554 if (NumArgs == 4) { 555 // check that the last argument is the right block type. 556 if (!isBlockPointer(Arg3)) { 557 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 558 << TheCall->getDirectCallee() << "block"; 559 return true; 560 } 561 // we have a block type, check the prototype 562 const BlockPointerType *BPT = 563 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 564 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 565 S.Diag(Arg3->getBeginLoc(), 566 diag::err_opencl_enqueue_kernel_blocks_no_args); 567 return true; 568 } 569 return false; 570 } 571 // we can have block + varargs. 572 if (isBlockPointer(Arg3)) 573 return (checkOpenCLBlockArgs(S, Arg3) || 574 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 575 // last two cases with either exactly 7 args or 7 args and varargs. 576 if (NumArgs >= 7) { 577 // check common block argument. 578 Expr *Arg6 = TheCall->getArg(6); 579 if (!isBlockPointer(Arg6)) { 580 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 581 << TheCall->getDirectCallee() << "block"; 582 return true; 583 } 584 if (checkOpenCLBlockArgs(S, Arg6)) 585 return true; 586 587 // Forth argument has to be any integer type. 588 if (!Arg3->getType()->isIntegerType()) { 589 S.Diag(TheCall->getArg(3)->getBeginLoc(), 590 diag::err_opencl_builtin_expected_type) 591 << TheCall->getDirectCallee() << "integer"; 592 return true; 593 } 594 // check remaining common arguments. 595 Expr *Arg4 = TheCall->getArg(4); 596 Expr *Arg5 = TheCall->getArg(5); 597 598 // Fifth argument is always passed as a pointer to clk_event_t. 599 if (!Arg4->isNullPointerConstant(S.Context, 600 Expr::NPC_ValueDependentIsNotNull) && 601 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 602 S.Diag(TheCall->getArg(4)->getBeginLoc(), 603 diag::err_opencl_builtin_expected_type) 604 << TheCall->getDirectCallee() 605 << S.Context.getPointerType(S.Context.OCLClkEventTy); 606 return true; 607 } 608 609 // Sixth argument is always passed as a pointer to clk_event_t. 610 if (!Arg5->isNullPointerConstant(S.Context, 611 Expr::NPC_ValueDependentIsNotNull) && 612 !(Arg5->getType()->isPointerType() && 613 Arg5->getType()->getPointeeType()->isClkEventT())) { 614 S.Diag(TheCall->getArg(5)->getBeginLoc(), 615 diag::err_opencl_builtin_expected_type) 616 << TheCall->getDirectCallee() 617 << S.Context.getPointerType(S.Context.OCLClkEventTy); 618 return true; 619 } 620 621 if (NumArgs == 7) 622 return false; 623 624 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 625 } 626 627 // None of the specific case has been detected, give generic error 628 S.Diag(TheCall->getBeginLoc(), 629 diag::err_opencl_enqueue_kernel_incorrect_args); 630 return true; 631 } 632 633 /// Returns OpenCL access qual. 634 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 635 return D->getAttr<OpenCLAccessAttr>(); 636 } 637 638 /// Returns true if pipe element type is different from the pointer. 639 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 640 const Expr *Arg0 = Call->getArg(0); 641 // First argument type should always be pipe. 642 if (!Arg0->getType()->isPipeType()) { 643 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 644 << Call->getDirectCallee() << Arg0->getSourceRange(); 645 return true; 646 } 647 OpenCLAccessAttr *AccessQual = 648 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 649 // Validates the access qualifier is compatible with the call. 650 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 651 // read_only and write_only, and assumed to be read_only if no qualifier is 652 // specified. 653 switch (Call->getDirectCallee()->getBuiltinID()) { 654 case Builtin::BIread_pipe: 655 case Builtin::BIreserve_read_pipe: 656 case Builtin::BIcommit_read_pipe: 657 case Builtin::BIwork_group_reserve_read_pipe: 658 case Builtin::BIsub_group_reserve_read_pipe: 659 case Builtin::BIwork_group_commit_read_pipe: 660 case Builtin::BIsub_group_commit_read_pipe: 661 if (!(!AccessQual || AccessQual->isReadOnly())) { 662 S.Diag(Arg0->getBeginLoc(), 663 diag::err_opencl_builtin_pipe_invalid_access_modifier) 664 << "read_only" << Arg0->getSourceRange(); 665 return true; 666 } 667 break; 668 case Builtin::BIwrite_pipe: 669 case Builtin::BIreserve_write_pipe: 670 case Builtin::BIcommit_write_pipe: 671 case Builtin::BIwork_group_reserve_write_pipe: 672 case Builtin::BIsub_group_reserve_write_pipe: 673 case Builtin::BIwork_group_commit_write_pipe: 674 case Builtin::BIsub_group_commit_write_pipe: 675 if (!(AccessQual && AccessQual->isWriteOnly())) { 676 S.Diag(Arg0->getBeginLoc(), 677 diag::err_opencl_builtin_pipe_invalid_access_modifier) 678 << "write_only" << Arg0->getSourceRange(); 679 return true; 680 } 681 break; 682 default: 683 break; 684 } 685 return false; 686 } 687 688 /// Returns true if pipe element type is different from the pointer. 689 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 690 const Expr *Arg0 = Call->getArg(0); 691 const Expr *ArgIdx = Call->getArg(Idx); 692 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 693 const QualType EltTy = PipeTy->getElementType(); 694 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 695 // The Idx argument should be a pointer and the type of the pointer and 696 // the type of pipe element should also be the same. 697 if (!ArgTy || 698 !S.Context.hasSameType( 699 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 700 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 701 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 702 << ArgIdx->getType() << ArgIdx->getSourceRange(); 703 return true; 704 } 705 return false; 706 } 707 708 // Performs semantic analysis for the read/write_pipe call. 709 // \param S Reference to the semantic analyzer. 710 // \param Call A pointer to the builtin call. 711 // \return True if a semantic error has been found, false otherwise. 712 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 713 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 714 // functions have two forms. 715 switch (Call->getNumArgs()) { 716 case 2: 717 if (checkOpenCLPipeArg(S, Call)) 718 return true; 719 // The call with 2 arguments should be 720 // read/write_pipe(pipe T, T*). 721 // Check packet type T. 722 if (checkOpenCLPipePacketType(S, Call, 1)) 723 return true; 724 break; 725 726 case 4: { 727 if (checkOpenCLPipeArg(S, Call)) 728 return true; 729 // The call with 4 arguments should be 730 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 731 // Check reserve_id_t. 732 if (!Call->getArg(1)->getType()->isReserveIDT()) { 733 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 734 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 735 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 736 return true; 737 } 738 739 // Check the index. 740 const Expr *Arg2 = Call->getArg(2); 741 if (!Arg2->getType()->isIntegerType() && 742 !Arg2->getType()->isUnsignedIntegerType()) { 743 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 744 << Call->getDirectCallee() << S.Context.UnsignedIntTy 745 << Arg2->getType() << Arg2->getSourceRange(); 746 return true; 747 } 748 749 // Check packet type T. 750 if (checkOpenCLPipePacketType(S, Call, 3)) 751 return true; 752 } break; 753 default: 754 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 755 << Call->getDirectCallee() << Call->getSourceRange(); 756 return true; 757 } 758 759 return false; 760 } 761 762 // Performs a semantic analysis on the {work_group_/sub_group_ 763 // /_}reserve_{read/write}_pipe 764 // \param S Reference to the semantic analyzer. 765 // \param Call The call to the builtin function to be analyzed. 766 // \return True if a semantic error was found, false otherwise. 767 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 768 if (checkArgCount(S, Call, 2)) 769 return true; 770 771 if (checkOpenCLPipeArg(S, Call)) 772 return true; 773 774 // Check the reserve size. 775 if (!Call->getArg(1)->getType()->isIntegerType() && 776 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 777 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 778 << Call->getDirectCallee() << S.Context.UnsignedIntTy 779 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 780 return true; 781 } 782 783 // Since return type of reserve_read/write_pipe built-in function is 784 // reserve_id_t, which is not defined in the builtin def file , we used int 785 // as return type and need to override the return type of these functions. 786 Call->setType(S.Context.OCLReserveIDTy); 787 788 return false; 789 } 790 791 // Performs a semantic analysis on {work_group_/sub_group_ 792 // /_}commit_{read/write}_pipe 793 // \param S Reference to the semantic analyzer. 794 // \param Call The call to the builtin function to be analyzed. 795 // \return True if a semantic error was found, false otherwise. 796 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 797 if (checkArgCount(S, Call, 2)) 798 return true; 799 800 if (checkOpenCLPipeArg(S, Call)) 801 return true; 802 803 // Check reserve_id_t. 804 if (!Call->getArg(1)->getType()->isReserveIDT()) { 805 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 806 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 807 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 808 return true; 809 } 810 811 return false; 812 } 813 814 // Performs a semantic analysis on the call to built-in Pipe 815 // Query Functions. 816 // \param S Reference to the semantic analyzer. 817 // \param Call The call to the builtin function to be analyzed. 818 // \return True if a semantic error was found, false otherwise. 819 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 820 if (checkArgCount(S, Call, 1)) 821 return true; 822 823 if (!Call->getArg(0)->getType()->isPipeType()) { 824 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 825 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 826 return true; 827 } 828 829 return false; 830 } 831 832 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 833 // Performs semantic analysis for the to_global/local/private call. 834 // \param S Reference to the semantic analyzer. 835 // \param BuiltinID ID of the builtin function. 836 // \param Call A pointer to the builtin call. 837 // \return True if a semantic error has been found, false otherwise. 838 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 839 CallExpr *Call) { 840 if (Call->getNumArgs() != 1) { 841 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 842 << Call->getDirectCallee() << Call->getSourceRange(); 843 return true; 844 } 845 846 auto RT = Call->getArg(0)->getType(); 847 if (!RT->isPointerType() || RT->getPointeeType() 848 .getAddressSpace() == LangAS::opencl_constant) { 849 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 850 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 851 return true; 852 } 853 854 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 855 S.Diag(Call->getArg(0)->getBeginLoc(), 856 diag::warn_opencl_generic_address_space_arg) 857 << Call->getDirectCallee()->getNameInfo().getAsString() 858 << Call->getArg(0)->getSourceRange(); 859 } 860 861 RT = RT->getPointeeType(); 862 auto Qual = RT.getQualifiers(); 863 switch (BuiltinID) { 864 case Builtin::BIto_global: 865 Qual.setAddressSpace(LangAS::opencl_global); 866 break; 867 case Builtin::BIto_local: 868 Qual.setAddressSpace(LangAS::opencl_local); 869 break; 870 case Builtin::BIto_private: 871 Qual.setAddressSpace(LangAS::opencl_private); 872 break; 873 default: 874 llvm_unreachable("Invalid builtin function"); 875 } 876 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 877 RT.getUnqualifiedType(), Qual))); 878 879 return false; 880 } 881 882 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 883 if (checkArgCount(S, TheCall, 1)) 884 return ExprError(); 885 886 // Compute __builtin_launder's parameter type from the argument. 887 // The parameter type is: 888 // * The type of the argument if it's not an array or function type, 889 // Otherwise, 890 // * The decayed argument type. 891 QualType ParamTy = [&]() { 892 QualType ArgTy = TheCall->getArg(0)->getType(); 893 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 894 return S.Context.getPointerType(Ty->getElementType()); 895 if (ArgTy->isFunctionType()) { 896 return S.Context.getPointerType(ArgTy); 897 } 898 return ArgTy; 899 }(); 900 901 TheCall->setType(ParamTy); 902 903 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 904 if (!ParamTy->isPointerType()) 905 return 0; 906 if (ParamTy->isFunctionPointerType()) 907 return 1; 908 if (ParamTy->isVoidPointerType()) 909 return 2; 910 return llvm::Optional<unsigned>{}; 911 }(); 912 if (DiagSelect.hasValue()) { 913 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 914 << DiagSelect.getValue() << TheCall->getSourceRange(); 915 return ExprError(); 916 } 917 918 // We either have an incomplete class type, or we have a class template 919 // whose instantiation has not been forced. Example: 920 // 921 // template <class T> struct Foo { T value; }; 922 // Foo<int> *p = nullptr; 923 // auto *d = __builtin_launder(p); 924 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 925 diag::err_incomplete_type)) 926 return ExprError(); 927 928 assert(ParamTy->getPointeeType()->isObjectType() && 929 "Unhandled non-object pointer case"); 930 931 InitializedEntity Entity = 932 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 933 ExprResult Arg = 934 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 935 if (Arg.isInvalid()) 936 return ExprError(); 937 TheCall->setArg(0, Arg.get()); 938 939 return TheCall; 940 } 941 942 // Emit an error and return true if the current architecture is not in the list 943 // of supported architectures. 944 static bool 945 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 946 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 947 llvm::Triple::ArchType CurArch = 948 S.getASTContext().getTargetInfo().getTriple().getArch(); 949 if (llvm::is_contained(SupportedArchs, CurArch)) 950 return false; 951 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 952 << TheCall->getSourceRange(); 953 return true; 954 } 955 956 ExprResult 957 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 958 CallExpr *TheCall) { 959 ExprResult TheCallResult(TheCall); 960 961 // Find out if any arguments are required to be integer constant expressions. 962 unsigned ICEArguments = 0; 963 ASTContext::GetBuiltinTypeError Error; 964 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 965 if (Error != ASTContext::GE_None) 966 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 967 968 // If any arguments are required to be ICE's, check and diagnose. 969 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 970 // Skip arguments not required to be ICE's. 971 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 972 973 llvm::APSInt Result; 974 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 975 return true; 976 ICEArguments &= ~(1 << ArgNo); 977 } 978 979 switch (BuiltinID) { 980 case Builtin::BI__builtin___CFStringMakeConstantString: 981 assert(TheCall->getNumArgs() == 1 && 982 "Wrong # arguments to builtin CFStringMakeConstantString"); 983 if (CheckObjCString(TheCall->getArg(0))) 984 return ExprError(); 985 break; 986 case Builtin::BI__builtin_ms_va_start: 987 case Builtin::BI__builtin_stdarg_start: 988 case Builtin::BI__builtin_va_start: 989 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 990 return ExprError(); 991 break; 992 case Builtin::BI__va_start: { 993 switch (Context.getTargetInfo().getTriple().getArch()) { 994 case llvm::Triple::aarch64: 995 case llvm::Triple::arm: 996 case llvm::Triple::thumb: 997 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 998 return ExprError(); 999 break; 1000 default: 1001 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1002 return ExprError(); 1003 break; 1004 } 1005 break; 1006 } 1007 1008 // The acquire, release, and no fence variants are ARM and AArch64 only. 1009 case Builtin::BI_interlockedbittestandset_acq: 1010 case Builtin::BI_interlockedbittestandset_rel: 1011 case Builtin::BI_interlockedbittestandset_nf: 1012 case Builtin::BI_interlockedbittestandreset_acq: 1013 case Builtin::BI_interlockedbittestandreset_rel: 1014 case Builtin::BI_interlockedbittestandreset_nf: 1015 if (CheckBuiltinTargetSupport( 1016 *this, BuiltinID, TheCall, 1017 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1018 return ExprError(); 1019 break; 1020 1021 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1022 case Builtin::BI_bittest64: 1023 case Builtin::BI_bittestandcomplement64: 1024 case Builtin::BI_bittestandreset64: 1025 case Builtin::BI_bittestandset64: 1026 case Builtin::BI_interlockedbittestandreset64: 1027 case Builtin::BI_interlockedbittestandset64: 1028 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1029 {llvm::Triple::x86_64, llvm::Triple::arm, 1030 llvm::Triple::thumb, llvm::Triple::aarch64})) 1031 return ExprError(); 1032 break; 1033 1034 case Builtin::BI__builtin_isgreater: 1035 case Builtin::BI__builtin_isgreaterequal: 1036 case Builtin::BI__builtin_isless: 1037 case Builtin::BI__builtin_islessequal: 1038 case Builtin::BI__builtin_islessgreater: 1039 case Builtin::BI__builtin_isunordered: 1040 if (SemaBuiltinUnorderedCompare(TheCall)) 1041 return ExprError(); 1042 break; 1043 case Builtin::BI__builtin_fpclassify: 1044 if (SemaBuiltinFPClassification(TheCall, 6)) 1045 return ExprError(); 1046 break; 1047 case Builtin::BI__builtin_isfinite: 1048 case Builtin::BI__builtin_isinf: 1049 case Builtin::BI__builtin_isinf_sign: 1050 case Builtin::BI__builtin_isnan: 1051 case Builtin::BI__builtin_isnormal: 1052 case Builtin::BI__builtin_signbit: 1053 case Builtin::BI__builtin_signbitf: 1054 case Builtin::BI__builtin_signbitl: 1055 if (SemaBuiltinFPClassification(TheCall, 1)) 1056 return ExprError(); 1057 break; 1058 case Builtin::BI__builtin_shufflevector: 1059 return SemaBuiltinShuffleVector(TheCall); 1060 // TheCall will be freed by the smart pointer here, but that's fine, since 1061 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1062 case Builtin::BI__builtin_prefetch: 1063 if (SemaBuiltinPrefetch(TheCall)) 1064 return ExprError(); 1065 break; 1066 case Builtin::BI__builtin_alloca_with_align: 1067 if (SemaBuiltinAllocaWithAlign(TheCall)) 1068 return ExprError(); 1069 break; 1070 case Builtin::BI__assume: 1071 case Builtin::BI__builtin_assume: 1072 if (SemaBuiltinAssume(TheCall)) 1073 return ExprError(); 1074 break; 1075 case Builtin::BI__builtin_assume_aligned: 1076 if (SemaBuiltinAssumeAligned(TheCall)) 1077 return ExprError(); 1078 break; 1079 case Builtin::BI__builtin_object_size: 1080 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1081 return ExprError(); 1082 break; 1083 case Builtin::BI__builtin_longjmp: 1084 if (SemaBuiltinLongjmp(TheCall)) 1085 return ExprError(); 1086 break; 1087 case Builtin::BI__builtin_setjmp: 1088 if (SemaBuiltinSetjmp(TheCall)) 1089 return ExprError(); 1090 break; 1091 case Builtin::BI_setjmp: 1092 case Builtin::BI_setjmpex: 1093 if (checkArgCount(*this, TheCall, 1)) 1094 return true; 1095 break; 1096 case Builtin::BI__builtin_classify_type: 1097 if (checkArgCount(*this, TheCall, 1)) return true; 1098 TheCall->setType(Context.IntTy); 1099 break; 1100 case Builtin::BI__builtin_constant_p: 1101 if (checkArgCount(*this, TheCall, 1)) return true; 1102 TheCall->setType(Context.IntTy); 1103 break; 1104 case Builtin::BI__builtin_launder: 1105 return SemaBuiltinLaunder(*this, TheCall); 1106 case Builtin::BI__sync_fetch_and_add: 1107 case Builtin::BI__sync_fetch_and_add_1: 1108 case Builtin::BI__sync_fetch_and_add_2: 1109 case Builtin::BI__sync_fetch_and_add_4: 1110 case Builtin::BI__sync_fetch_and_add_8: 1111 case Builtin::BI__sync_fetch_and_add_16: 1112 case Builtin::BI__sync_fetch_and_sub: 1113 case Builtin::BI__sync_fetch_and_sub_1: 1114 case Builtin::BI__sync_fetch_and_sub_2: 1115 case Builtin::BI__sync_fetch_and_sub_4: 1116 case Builtin::BI__sync_fetch_and_sub_8: 1117 case Builtin::BI__sync_fetch_and_sub_16: 1118 case Builtin::BI__sync_fetch_and_or: 1119 case Builtin::BI__sync_fetch_and_or_1: 1120 case Builtin::BI__sync_fetch_and_or_2: 1121 case Builtin::BI__sync_fetch_and_or_4: 1122 case Builtin::BI__sync_fetch_and_or_8: 1123 case Builtin::BI__sync_fetch_and_or_16: 1124 case Builtin::BI__sync_fetch_and_and: 1125 case Builtin::BI__sync_fetch_and_and_1: 1126 case Builtin::BI__sync_fetch_and_and_2: 1127 case Builtin::BI__sync_fetch_and_and_4: 1128 case Builtin::BI__sync_fetch_and_and_8: 1129 case Builtin::BI__sync_fetch_and_and_16: 1130 case Builtin::BI__sync_fetch_and_xor: 1131 case Builtin::BI__sync_fetch_and_xor_1: 1132 case Builtin::BI__sync_fetch_and_xor_2: 1133 case Builtin::BI__sync_fetch_and_xor_4: 1134 case Builtin::BI__sync_fetch_and_xor_8: 1135 case Builtin::BI__sync_fetch_and_xor_16: 1136 case Builtin::BI__sync_fetch_and_nand: 1137 case Builtin::BI__sync_fetch_and_nand_1: 1138 case Builtin::BI__sync_fetch_and_nand_2: 1139 case Builtin::BI__sync_fetch_and_nand_4: 1140 case Builtin::BI__sync_fetch_and_nand_8: 1141 case Builtin::BI__sync_fetch_and_nand_16: 1142 case Builtin::BI__sync_add_and_fetch: 1143 case Builtin::BI__sync_add_and_fetch_1: 1144 case Builtin::BI__sync_add_and_fetch_2: 1145 case Builtin::BI__sync_add_and_fetch_4: 1146 case Builtin::BI__sync_add_and_fetch_8: 1147 case Builtin::BI__sync_add_and_fetch_16: 1148 case Builtin::BI__sync_sub_and_fetch: 1149 case Builtin::BI__sync_sub_and_fetch_1: 1150 case Builtin::BI__sync_sub_and_fetch_2: 1151 case Builtin::BI__sync_sub_and_fetch_4: 1152 case Builtin::BI__sync_sub_and_fetch_8: 1153 case Builtin::BI__sync_sub_and_fetch_16: 1154 case Builtin::BI__sync_and_and_fetch: 1155 case Builtin::BI__sync_and_and_fetch_1: 1156 case Builtin::BI__sync_and_and_fetch_2: 1157 case Builtin::BI__sync_and_and_fetch_4: 1158 case Builtin::BI__sync_and_and_fetch_8: 1159 case Builtin::BI__sync_and_and_fetch_16: 1160 case Builtin::BI__sync_or_and_fetch: 1161 case Builtin::BI__sync_or_and_fetch_1: 1162 case Builtin::BI__sync_or_and_fetch_2: 1163 case Builtin::BI__sync_or_and_fetch_4: 1164 case Builtin::BI__sync_or_and_fetch_8: 1165 case Builtin::BI__sync_or_and_fetch_16: 1166 case Builtin::BI__sync_xor_and_fetch: 1167 case Builtin::BI__sync_xor_and_fetch_1: 1168 case Builtin::BI__sync_xor_and_fetch_2: 1169 case Builtin::BI__sync_xor_and_fetch_4: 1170 case Builtin::BI__sync_xor_and_fetch_8: 1171 case Builtin::BI__sync_xor_and_fetch_16: 1172 case Builtin::BI__sync_nand_and_fetch: 1173 case Builtin::BI__sync_nand_and_fetch_1: 1174 case Builtin::BI__sync_nand_and_fetch_2: 1175 case Builtin::BI__sync_nand_and_fetch_4: 1176 case Builtin::BI__sync_nand_and_fetch_8: 1177 case Builtin::BI__sync_nand_and_fetch_16: 1178 case Builtin::BI__sync_val_compare_and_swap: 1179 case Builtin::BI__sync_val_compare_and_swap_1: 1180 case Builtin::BI__sync_val_compare_and_swap_2: 1181 case Builtin::BI__sync_val_compare_and_swap_4: 1182 case Builtin::BI__sync_val_compare_and_swap_8: 1183 case Builtin::BI__sync_val_compare_and_swap_16: 1184 case Builtin::BI__sync_bool_compare_and_swap: 1185 case Builtin::BI__sync_bool_compare_and_swap_1: 1186 case Builtin::BI__sync_bool_compare_and_swap_2: 1187 case Builtin::BI__sync_bool_compare_and_swap_4: 1188 case Builtin::BI__sync_bool_compare_and_swap_8: 1189 case Builtin::BI__sync_bool_compare_and_swap_16: 1190 case Builtin::BI__sync_lock_test_and_set: 1191 case Builtin::BI__sync_lock_test_and_set_1: 1192 case Builtin::BI__sync_lock_test_and_set_2: 1193 case Builtin::BI__sync_lock_test_and_set_4: 1194 case Builtin::BI__sync_lock_test_and_set_8: 1195 case Builtin::BI__sync_lock_test_and_set_16: 1196 case Builtin::BI__sync_lock_release: 1197 case Builtin::BI__sync_lock_release_1: 1198 case Builtin::BI__sync_lock_release_2: 1199 case Builtin::BI__sync_lock_release_4: 1200 case Builtin::BI__sync_lock_release_8: 1201 case Builtin::BI__sync_lock_release_16: 1202 case Builtin::BI__sync_swap: 1203 case Builtin::BI__sync_swap_1: 1204 case Builtin::BI__sync_swap_2: 1205 case Builtin::BI__sync_swap_4: 1206 case Builtin::BI__sync_swap_8: 1207 case Builtin::BI__sync_swap_16: 1208 return SemaBuiltinAtomicOverloaded(TheCallResult); 1209 case Builtin::BI__sync_synchronize: 1210 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1211 << TheCall->getCallee()->getSourceRange(); 1212 break; 1213 case Builtin::BI__builtin_nontemporal_load: 1214 case Builtin::BI__builtin_nontemporal_store: 1215 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1216 #define BUILTIN(ID, TYPE, ATTRS) 1217 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1218 case Builtin::BI##ID: \ 1219 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1220 #include "clang/Basic/Builtins.def" 1221 case Builtin::BI__annotation: 1222 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1223 return ExprError(); 1224 break; 1225 case Builtin::BI__builtin_annotation: 1226 if (SemaBuiltinAnnotation(*this, TheCall)) 1227 return ExprError(); 1228 break; 1229 case Builtin::BI__builtin_addressof: 1230 if (SemaBuiltinAddressof(*this, TheCall)) 1231 return ExprError(); 1232 break; 1233 case Builtin::BI__builtin_add_overflow: 1234 case Builtin::BI__builtin_sub_overflow: 1235 case Builtin::BI__builtin_mul_overflow: 1236 if (SemaBuiltinOverflow(*this, TheCall)) 1237 return ExprError(); 1238 break; 1239 case Builtin::BI__builtin_operator_new: 1240 case Builtin::BI__builtin_operator_delete: { 1241 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1242 ExprResult Res = 1243 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1244 if (Res.isInvalid()) 1245 CorrectDelayedTyposInExpr(TheCallResult.get()); 1246 return Res; 1247 } 1248 case Builtin::BI__builtin_dump_struct: { 1249 // We first want to ensure we are called with 2 arguments 1250 if (checkArgCount(*this, TheCall, 2)) 1251 return ExprError(); 1252 // Ensure that the first argument is of type 'struct XX *' 1253 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1254 const QualType PtrArgType = PtrArg->getType(); 1255 if (!PtrArgType->isPointerType() || 1256 !PtrArgType->getPointeeType()->isRecordType()) { 1257 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1258 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1259 << "structure pointer"; 1260 return ExprError(); 1261 } 1262 1263 // Ensure that the second argument is of type 'FunctionType' 1264 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1265 const QualType FnPtrArgType = FnPtrArg->getType(); 1266 if (!FnPtrArgType->isPointerType()) { 1267 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1268 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1269 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1270 return ExprError(); 1271 } 1272 1273 const auto *FuncType = 1274 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1275 1276 if (!FuncType) { 1277 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1278 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1279 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1280 return ExprError(); 1281 } 1282 1283 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1284 if (!FT->getNumParams()) { 1285 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1286 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1287 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1288 return ExprError(); 1289 } 1290 QualType PT = FT->getParamType(0); 1291 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1292 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1293 !PT->getPointeeType().isConstQualified()) { 1294 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1295 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1296 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1297 return ExprError(); 1298 } 1299 } 1300 1301 TheCall->setType(Context.IntTy); 1302 break; 1303 } 1304 1305 // check secure string manipulation functions where overflows 1306 // are detectable at compile time 1307 case Builtin::BI__builtin___memcpy_chk: 1308 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy"); 1309 break; 1310 case Builtin::BI__builtin___memmove_chk: 1311 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove"); 1312 break; 1313 case Builtin::BI__builtin___memset_chk: 1314 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset"); 1315 break; 1316 case Builtin::BI__builtin___strlcat_chk: 1317 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat"); 1318 break; 1319 case Builtin::BI__builtin___strlcpy_chk: 1320 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy"); 1321 break; 1322 case Builtin::BI__builtin___strncat_chk: 1323 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat"); 1324 break; 1325 case Builtin::BI__builtin___strncpy_chk: 1326 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy"); 1327 break; 1328 case Builtin::BI__builtin___stpncpy_chk: 1329 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy"); 1330 break; 1331 case Builtin::BI__builtin___memccpy_chk: 1332 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy"); 1333 break; 1334 case Builtin::BI__builtin___snprintf_chk: 1335 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf"); 1336 break; 1337 case Builtin::BI__builtin___vsnprintf_chk: 1338 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf"); 1339 break; 1340 case Builtin::BI__builtin_call_with_static_chain: 1341 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1342 return ExprError(); 1343 break; 1344 case Builtin::BI__exception_code: 1345 case Builtin::BI_exception_code: 1346 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1347 diag::err_seh___except_block)) 1348 return ExprError(); 1349 break; 1350 case Builtin::BI__exception_info: 1351 case Builtin::BI_exception_info: 1352 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1353 diag::err_seh___except_filter)) 1354 return ExprError(); 1355 break; 1356 case Builtin::BI__GetExceptionInfo: 1357 if (checkArgCount(*this, TheCall, 1)) 1358 return ExprError(); 1359 1360 if (CheckCXXThrowOperand( 1361 TheCall->getBeginLoc(), 1362 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1363 TheCall)) 1364 return ExprError(); 1365 1366 TheCall->setType(Context.VoidPtrTy); 1367 break; 1368 // OpenCL v2.0, s6.13.16 - Pipe functions 1369 case Builtin::BIread_pipe: 1370 case Builtin::BIwrite_pipe: 1371 // Since those two functions are declared with var args, we need a semantic 1372 // check for the argument. 1373 if (SemaBuiltinRWPipe(*this, TheCall)) 1374 return ExprError(); 1375 break; 1376 case Builtin::BIreserve_read_pipe: 1377 case Builtin::BIreserve_write_pipe: 1378 case Builtin::BIwork_group_reserve_read_pipe: 1379 case Builtin::BIwork_group_reserve_write_pipe: 1380 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1381 return ExprError(); 1382 break; 1383 case Builtin::BIsub_group_reserve_read_pipe: 1384 case Builtin::BIsub_group_reserve_write_pipe: 1385 if (checkOpenCLSubgroupExt(*this, TheCall) || 1386 SemaBuiltinReserveRWPipe(*this, TheCall)) 1387 return ExprError(); 1388 break; 1389 case Builtin::BIcommit_read_pipe: 1390 case Builtin::BIcommit_write_pipe: 1391 case Builtin::BIwork_group_commit_read_pipe: 1392 case Builtin::BIwork_group_commit_write_pipe: 1393 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1394 return ExprError(); 1395 break; 1396 case Builtin::BIsub_group_commit_read_pipe: 1397 case Builtin::BIsub_group_commit_write_pipe: 1398 if (checkOpenCLSubgroupExt(*this, TheCall) || 1399 SemaBuiltinCommitRWPipe(*this, TheCall)) 1400 return ExprError(); 1401 break; 1402 case Builtin::BIget_pipe_num_packets: 1403 case Builtin::BIget_pipe_max_packets: 1404 if (SemaBuiltinPipePackets(*this, TheCall)) 1405 return ExprError(); 1406 break; 1407 case Builtin::BIto_global: 1408 case Builtin::BIto_local: 1409 case Builtin::BIto_private: 1410 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1411 return ExprError(); 1412 break; 1413 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1414 case Builtin::BIenqueue_kernel: 1415 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1416 return ExprError(); 1417 break; 1418 case Builtin::BIget_kernel_work_group_size: 1419 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1420 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1421 return ExprError(); 1422 break; 1423 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1424 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1425 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1426 return ExprError(); 1427 break; 1428 case Builtin::BI__builtin_os_log_format: 1429 case Builtin::BI__builtin_os_log_format_buffer_size: 1430 if (SemaBuiltinOSLogFormat(TheCall)) 1431 return ExprError(); 1432 break; 1433 } 1434 1435 // Since the target specific builtins for each arch overlap, only check those 1436 // of the arch we are compiling for. 1437 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1438 switch (Context.getTargetInfo().getTriple().getArch()) { 1439 case llvm::Triple::arm: 1440 case llvm::Triple::armeb: 1441 case llvm::Triple::thumb: 1442 case llvm::Triple::thumbeb: 1443 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1444 return ExprError(); 1445 break; 1446 case llvm::Triple::aarch64: 1447 case llvm::Triple::aarch64_be: 1448 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1449 return ExprError(); 1450 break; 1451 case llvm::Triple::hexagon: 1452 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1453 return ExprError(); 1454 break; 1455 case llvm::Triple::mips: 1456 case llvm::Triple::mipsel: 1457 case llvm::Triple::mips64: 1458 case llvm::Triple::mips64el: 1459 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1460 return ExprError(); 1461 break; 1462 case llvm::Triple::systemz: 1463 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1464 return ExprError(); 1465 break; 1466 case llvm::Triple::x86: 1467 case llvm::Triple::x86_64: 1468 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1469 return ExprError(); 1470 break; 1471 case llvm::Triple::ppc: 1472 case llvm::Triple::ppc64: 1473 case llvm::Triple::ppc64le: 1474 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1475 return ExprError(); 1476 break; 1477 default: 1478 break; 1479 } 1480 } 1481 1482 return TheCallResult; 1483 } 1484 1485 // Get the valid immediate range for the specified NEON type code. 1486 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1487 NeonTypeFlags Type(t); 1488 int IsQuad = ForceQuad ? true : Type.isQuad(); 1489 switch (Type.getEltType()) { 1490 case NeonTypeFlags::Int8: 1491 case NeonTypeFlags::Poly8: 1492 return shift ? 7 : (8 << IsQuad) - 1; 1493 case NeonTypeFlags::Int16: 1494 case NeonTypeFlags::Poly16: 1495 return shift ? 15 : (4 << IsQuad) - 1; 1496 case NeonTypeFlags::Int32: 1497 return shift ? 31 : (2 << IsQuad) - 1; 1498 case NeonTypeFlags::Int64: 1499 case NeonTypeFlags::Poly64: 1500 return shift ? 63 : (1 << IsQuad) - 1; 1501 case NeonTypeFlags::Poly128: 1502 return shift ? 127 : (1 << IsQuad) - 1; 1503 case NeonTypeFlags::Float16: 1504 assert(!shift && "cannot shift float types!"); 1505 return (4 << IsQuad) - 1; 1506 case NeonTypeFlags::Float32: 1507 assert(!shift && "cannot shift float types!"); 1508 return (2 << IsQuad) - 1; 1509 case NeonTypeFlags::Float64: 1510 assert(!shift && "cannot shift float types!"); 1511 return (1 << IsQuad) - 1; 1512 } 1513 llvm_unreachable("Invalid NeonTypeFlag!"); 1514 } 1515 1516 /// getNeonEltType - Return the QualType corresponding to the elements of 1517 /// the vector type specified by the NeonTypeFlags. This is used to check 1518 /// the pointer arguments for Neon load/store intrinsics. 1519 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1520 bool IsPolyUnsigned, bool IsInt64Long) { 1521 switch (Flags.getEltType()) { 1522 case NeonTypeFlags::Int8: 1523 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1524 case NeonTypeFlags::Int16: 1525 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1526 case NeonTypeFlags::Int32: 1527 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1528 case NeonTypeFlags::Int64: 1529 if (IsInt64Long) 1530 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1531 else 1532 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1533 : Context.LongLongTy; 1534 case NeonTypeFlags::Poly8: 1535 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1536 case NeonTypeFlags::Poly16: 1537 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1538 case NeonTypeFlags::Poly64: 1539 if (IsInt64Long) 1540 return Context.UnsignedLongTy; 1541 else 1542 return Context.UnsignedLongLongTy; 1543 case NeonTypeFlags::Poly128: 1544 break; 1545 case NeonTypeFlags::Float16: 1546 return Context.HalfTy; 1547 case NeonTypeFlags::Float32: 1548 return Context.FloatTy; 1549 case NeonTypeFlags::Float64: 1550 return Context.DoubleTy; 1551 } 1552 llvm_unreachable("Invalid NeonTypeFlag!"); 1553 } 1554 1555 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1556 llvm::APSInt Result; 1557 uint64_t mask = 0; 1558 unsigned TV = 0; 1559 int PtrArgNum = -1; 1560 bool HasConstPtr = false; 1561 switch (BuiltinID) { 1562 #define GET_NEON_OVERLOAD_CHECK 1563 #include "clang/Basic/arm_neon.inc" 1564 #include "clang/Basic/arm_fp16.inc" 1565 #undef GET_NEON_OVERLOAD_CHECK 1566 } 1567 1568 // For NEON intrinsics which are overloaded on vector element type, validate 1569 // the immediate which specifies which variant to emit. 1570 unsigned ImmArg = TheCall->getNumArgs()-1; 1571 if (mask) { 1572 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1573 return true; 1574 1575 TV = Result.getLimitedValue(64); 1576 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1577 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1578 << TheCall->getArg(ImmArg)->getSourceRange(); 1579 } 1580 1581 if (PtrArgNum >= 0) { 1582 // Check that pointer arguments have the specified type. 1583 Expr *Arg = TheCall->getArg(PtrArgNum); 1584 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1585 Arg = ICE->getSubExpr(); 1586 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1587 QualType RHSTy = RHS.get()->getType(); 1588 1589 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1590 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1591 Arch == llvm::Triple::aarch64_be; 1592 bool IsInt64Long = 1593 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1594 QualType EltTy = 1595 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1596 if (HasConstPtr) 1597 EltTy = EltTy.withConst(); 1598 QualType LHSTy = Context.getPointerType(EltTy); 1599 AssignConvertType ConvTy; 1600 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1601 if (RHS.isInvalid()) 1602 return true; 1603 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1604 RHS.get(), AA_Assigning)) 1605 return true; 1606 } 1607 1608 // For NEON intrinsics which take an immediate value as part of the 1609 // instruction, range check them here. 1610 unsigned i = 0, l = 0, u = 0; 1611 switch (BuiltinID) { 1612 default: 1613 return false; 1614 #define GET_NEON_IMMEDIATE_CHECK 1615 #include "clang/Basic/arm_neon.inc" 1616 #include "clang/Basic/arm_fp16.inc" 1617 #undef GET_NEON_IMMEDIATE_CHECK 1618 } 1619 1620 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1621 } 1622 1623 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1624 unsigned MaxWidth) { 1625 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1626 BuiltinID == ARM::BI__builtin_arm_ldaex || 1627 BuiltinID == ARM::BI__builtin_arm_strex || 1628 BuiltinID == ARM::BI__builtin_arm_stlex || 1629 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1630 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1631 BuiltinID == AArch64::BI__builtin_arm_strex || 1632 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1633 "unexpected ARM builtin"); 1634 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1635 BuiltinID == ARM::BI__builtin_arm_ldaex || 1636 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1637 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1638 1639 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1640 1641 // Ensure that we have the proper number of arguments. 1642 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1643 return true; 1644 1645 // Inspect the pointer argument of the atomic builtin. This should always be 1646 // a pointer type, whose element is an integral scalar or pointer type. 1647 // Because it is a pointer type, we don't have to worry about any implicit 1648 // casts here. 1649 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1650 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1651 if (PointerArgRes.isInvalid()) 1652 return true; 1653 PointerArg = PointerArgRes.get(); 1654 1655 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1656 if (!pointerType) { 1657 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1658 << PointerArg->getType() << PointerArg->getSourceRange(); 1659 return true; 1660 } 1661 1662 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1663 // task is to insert the appropriate casts into the AST. First work out just 1664 // what the appropriate type is. 1665 QualType ValType = pointerType->getPointeeType(); 1666 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1667 if (IsLdrex) 1668 AddrType.addConst(); 1669 1670 // Issue a warning if the cast is dodgy. 1671 CastKind CastNeeded = CK_NoOp; 1672 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1673 CastNeeded = CK_BitCast; 1674 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1675 << PointerArg->getType() << Context.getPointerType(AddrType) 1676 << AA_Passing << PointerArg->getSourceRange(); 1677 } 1678 1679 // Finally, do the cast and replace the argument with the corrected version. 1680 AddrType = Context.getPointerType(AddrType); 1681 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1682 if (PointerArgRes.isInvalid()) 1683 return true; 1684 PointerArg = PointerArgRes.get(); 1685 1686 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1687 1688 // In general, we allow ints, floats and pointers to be loaded and stored. 1689 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1690 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1691 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1692 << PointerArg->getType() << PointerArg->getSourceRange(); 1693 return true; 1694 } 1695 1696 // But ARM doesn't have instructions to deal with 128-bit versions. 1697 if (Context.getTypeSize(ValType) > MaxWidth) { 1698 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1699 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1700 << PointerArg->getType() << PointerArg->getSourceRange(); 1701 return true; 1702 } 1703 1704 switch (ValType.getObjCLifetime()) { 1705 case Qualifiers::OCL_None: 1706 case Qualifiers::OCL_ExplicitNone: 1707 // okay 1708 break; 1709 1710 case Qualifiers::OCL_Weak: 1711 case Qualifiers::OCL_Strong: 1712 case Qualifiers::OCL_Autoreleasing: 1713 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1714 << ValType << PointerArg->getSourceRange(); 1715 return true; 1716 } 1717 1718 if (IsLdrex) { 1719 TheCall->setType(ValType); 1720 return false; 1721 } 1722 1723 // Initialize the argument to be stored. 1724 ExprResult ValArg = TheCall->getArg(0); 1725 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1726 Context, ValType, /*consume*/ false); 1727 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1728 if (ValArg.isInvalid()) 1729 return true; 1730 TheCall->setArg(0, ValArg.get()); 1731 1732 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1733 // but the custom checker bypasses all default analysis. 1734 TheCall->setType(Context.IntTy); 1735 return false; 1736 } 1737 1738 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1739 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1740 BuiltinID == ARM::BI__builtin_arm_ldaex || 1741 BuiltinID == ARM::BI__builtin_arm_strex || 1742 BuiltinID == ARM::BI__builtin_arm_stlex) { 1743 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1744 } 1745 1746 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1747 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1748 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1749 } 1750 1751 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1752 BuiltinID == ARM::BI__builtin_arm_wsr64) 1753 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1754 1755 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1756 BuiltinID == ARM::BI__builtin_arm_rsrp || 1757 BuiltinID == ARM::BI__builtin_arm_wsr || 1758 BuiltinID == ARM::BI__builtin_arm_wsrp) 1759 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1760 1761 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1762 return true; 1763 1764 // For intrinsics which take an immediate value as part of the instruction, 1765 // range check them here. 1766 // FIXME: VFP Intrinsics should error if VFP not present. 1767 switch (BuiltinID) { 1768 default: return false; 1769 case ARM::BI__builtin_arm_ssat: 1770 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1771 case ARM::BI__builtin_arm_usat: 1772 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1773 case ARM::BI__builtin_arm_ssat16: 1774 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1775 case ARM::BI__builtin_arm_usat16: 1776 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1777 case ARM::BI__builtin_arm_vcvtr_f: 1778 case ARM::BI__builtin_arm_vcvtr_d: 1779 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1780 case ARM::BI__builtin_arm_dmb: 1781 case ARM::BI__builtin_arm_dsb: 1782 case ARM::BI__builtin_arm_isb: 1783 case ARM::BI__builtin_arm_dbg: 1784 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1785 } 1786 } 1787 1788 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1789 CallExpr *TheCall) { 1790 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1791 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1792 BuiltinID == AArch64::BI__builtin_arm_strex || 1793 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1794 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1795 } 1796 1797 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1798 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1799 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1800 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1801 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1802 } 1803 1804 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1805 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1806 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1807 1808 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1809 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1810 BuiltinID == AArch64::BI__builtin_arm_wsr || 1811 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1812 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1813 1814 // Only check the valid encoding range. Any constant in this range would be 1815 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 1816 // an exception for incorrect registers. This matches MSVC behavior. 1817 if (BuiltinID == AArch64::BI_ReadStatusReg || 1818 BuiltinID == AArch64::BI_WriteStatusReg) 1819 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 1820 1821 if (BuiltinID == AArch64::BI__getReg) 1822 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1823 1824 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1825 return true; 1826 1827 // For intrinsics which take an immediate value as part of the instruction, 1828 // range check them here. 1829 unsigned i = 0, l = 0, u = 0; 1830 switch (BuiltinID) { 1831 default: return false; 1832 case AArch64::BI__builtin_arm_dmb: 1833 case AArch64::BI__builtin_arm_dsb: 1834 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1835 } 1836 1837 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1838 } 1839 1840 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1841 struct BuiltinAndString { 1842 unsigned BuiltinID; 1843 const char *Str; 1844 }; 1845 1846 static BuiltinAndString ValidCPU[] = { 1847 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" }, 1848 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" }, 1849 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" }, 1850 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" }, 1851 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" }, 1852 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" }, 1853 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" }, 1854 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" }, 1855 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" }, 1856 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" }, 1857 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" }, 1858 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" }, 1859 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" }, 1860 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" }, 1861 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" }, 1862 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" }, 1863 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" }, 1864 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" }, 1865 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" }, 1866 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" }, 1867 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" }, 1868 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" }, 1869 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" }, 1870 }; 1871 1872 static BuiltinAndString ValidHVX[] = { 1873 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" }, 1874 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" }, 1875 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" }, 1876 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" }, 1877 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" }, 1878 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" }, 1879 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" }, 1880 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" }, 1881 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" }, 1882 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" }, 1883 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" }, 1884 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" }, 1885 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" }, 1886 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" }, 1887 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" }, 1888 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" }, 1889 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" }, 1890 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" }, 1891 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" }, 1892 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" }, 1893 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" }, 1894 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" }, 1895 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" }, 1896 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" }, 1897 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" }, 1898 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" }, 1899 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" }, 1900 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" }, 1901 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" }, 1902 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" }, 1903 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" }, 1904 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" }, 1905 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" }, 1906 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" }, 1907 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" }, 1908 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" }, 1909 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" }, 1910 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" }, 1911 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" }, 1912 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" }, 1913 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" }, 1914 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" }, 1915 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" }, 1916 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" }, 1917 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" }, 1918 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" }, 1919 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" }, 1920 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" }, 1921 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" }, 1922 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" }, 1923 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" }, 1924 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" }, 1925 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" }, 1926 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" }, 1927 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" }, 1928 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" }, 1929 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" }, 1930 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" }, 1931 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" }, 1932 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" }, 1933 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" }, 1934 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" }, 1935 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" }, 1936 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" }, 1937 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" }, 1938 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" }, 1939 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" }, 1940 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" }, 1941 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" }, 1942 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" }, 1943 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" }, 1944 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" }, 1945 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" }, 1946 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" }, 1947 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" }, 1948 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" }, 1949 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" }, 1950 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" }, 1951 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" }, 1952 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" }, 1953 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" }, 1954 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" }, 1955 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" }, 1956 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" }, 1957 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" }, 1958 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" }, 1959 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" }, 1960 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" }, 1961 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" }, 1962 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" }, 1963 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" }, 1964 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" }, 1965 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" }, 1966 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" }, 1967 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" }, 1968 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" }, 1969 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" }, 1970 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" }, 1971 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" }, 1972 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" }, 1973 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" }, 1974 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" }, 2526 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" }, 2527 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" }, 2528 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" }, 2529 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" }, 2530 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" }, 2531 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" }, 2532 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" }, 2533 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" }, 2534 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" }, 2535 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" }, 2536 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" }, 2537 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" }, 2538 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" }, 2539 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" }, 2540 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" }, 2541 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" }, 2542 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" }, 2543 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" }, 2544 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" }, 2545 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" }, 2546 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" }, 2547 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" }, 2548 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" }, 2549 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" }, 2550 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" }, 2551 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" }, 2552 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" }, 2553 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" }, 2554 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" }, 2555 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" }, 2556 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" }, 2557 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" }, 2558 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" }, 2559 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" }, 2560 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" }, 2561 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" }, 2562 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" }, 2563 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" }, 2564 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" }, 2565 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" }, 2566 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" }, 2567 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" }, 2568 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" }, 2569 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" }, 2570 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" }, 2571 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" }, 2572 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" }, 2573 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" }, 2574 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" }, 2575 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" }, 2576 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" }, 2577 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" }, 2578 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" }, 2579 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" }, 2580 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" }, 2581 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" }, 2582 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" }, 2583 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" }, 2584 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" }, 2585 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" }, 2586 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" }, 2587 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" }, 2588 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" }, 2589 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" }, 2590 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" }, 2591 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" }, 2592 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" }, 2593 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" }, 2594 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" }, 2595 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" }, 2596 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" }, 2597 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" }, 2598 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" }, 2599 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" }, 2600 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" }, 2601 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" }, 2602 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" }, 2603 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" }, 2604 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" }, 2605 }; 2606 2607 // Sort the tables on first execution so we can binary search them. 2608 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { 2609 return LHS.BuiltinID < RHS.BuiltinID; 2610 }; 2611 static const bool SortOnce = 2612 (llvm::sort(ValidCPU, SortCmp), 2613 llvm::sort(ValidHVX, SortCmp), true); 2614 (void)SortOnce; 2615 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { 2616 return BI.BuiltinID < BuiltinID; 2617 }; 2618 2619 const TargetInfo &TI = Context.getTargetInfo(); 2620 2621 const BuiltinAndString *FC = 2622 std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID, 2623 LowerBoundCmp); 2624 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { 2625 const TargetOptions &Opts = TI.getTargetOpts(); 2626 StringRef CPU = Opts.CPU; 2627 if (!CPU.empty()) { 2628 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2629 CPU.consume_front("hexagon"); 2630 SmallVector<StringRef, 3> CPUs; 2631 StringRef(FC->Str).split(CPUs, ','); 2632 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) 2633 return Diag(TheCall->getBeginLoc(), 2634 diag::err_hexagon_builtin_unsupported_cpu); 2635 } 2636 } 2637 2638 const BuiltinAndString *FH = 2639 std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID, 2640 LowerBoundCmp); 2641 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { 2642 if (!TI.hasFeature("hvx")) 2643 return Diag(TheCall->getBeginLoc(), 2644 diag::err_hexagon_builtin_requires_hvx); 2645 2646 SmallVector<StringRef, 3> HVXs; 2647 StringRef(FH->Str).split(HVXs, ','); 2648 bool IsValid = llvm::any_of(HVXs, 2649 [&TI] (StringRef V) { 2650 std::string F = "hvx" + V.str(); 2651 return TI.hasFeature(F); 2652 }); 2653 if (!IsValid) 2654 return Diag(TheCall->getBeginLoc(), 2655 diag::err_hexagon_builtin_unsupported_hvx); 2656 } 2657 2658 return false; 2659 } 2660 2661 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2662 struct ArgInfo { 2663 uint8_t OpNum; 2664 bool IsSigned; 2665 uint8_t BitWidth; 2666 uint8_t Align; 2667 }; 2668 struct BuiltinInfo { 2669 unsigned BuiltinID; 2670 ArgInfo Infos[2]; 2671 }; 2672 2673 static BuiltinInfo Infos[] = { 2674 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2675 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2676 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2677 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2678 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2679 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2680 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2681 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2682 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2683 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2684 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2685 2686 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2697 2698 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2701 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2706 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2709 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2713 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2715 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2716 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2717 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2718 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2719 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2720 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2721 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2722 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2724 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2725 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2727 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2728 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2730 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2731 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2732 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2733 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2737 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2739 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2745 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2749 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2750 {{ 1, false, 6, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2758 {{ 1, false, 5, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2765 { 2, false, 5, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2767 { 2, false, 6, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2769 { 3, false, 5, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2771 { 3, false, 6, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2788 {{ 2, false, 4, 0 }, 2789 { 3, false, 5, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2791 {{ 2, false, 4, 0 }, 2792 { 3, false, 5, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2794 {{ 2, false, 4, 0 }, 2795 { 3, false, 5, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2797 {{ 2, false, 4, 0 }, 2798 { 3, false, 5, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2810 { 2, false, 5, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2812 { 2, false, 6, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2822 {{ 1, false, 4, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2825 {{ 1, false, 4, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2846 {{ 3, false, 1, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2851 {{ 3, false, 1, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2856 {{ 3, false, 1, 0 }} }, 2857 }; 2858 2859 // Use a dynamically initialized static to sort the table exactly once on 2860 // first run. 2861 static const bool SortOnce = 2862 (llvm::sort(Infos, 2863 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2864 return LHS.BuiltinID < RHS.BuiltinID; 2865 }), 2866 true); 2867 (void)SortOnce; 2868 2869 const BuiltinInfo *F = 2870 std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID, 2871 [](const BuiltinInfo &BI, unsigned BuiltinID) { 2872 return BI.BuiltinID < BuiltinID; 2873 }); 2874 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2875 return false; 2876 2877 bool Error = false; 2878 2879 for (const ArgInfo &A : F->Infos) { 2880 // Ignore empty ArgInfo elements. 2881 if (A.BitWidth == 0) 2882 continue; 2883 2884 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2885 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2886 if (!A.Align) { 2887 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2888 } else { 2889 unsigned M = 1 << A.Align; 2890 Min *= M; 2891 Max *= M; 2892 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2893 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2894 } 2895 } 2896 return Error; 2897 } 2898 2899 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2900 CallExpr *TheCall) { 2901 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2902 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2903 } 2904 2905 2906 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 2907 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2908 // ordering for DSP is unspecified. MSA is ordered by the data format used 2909 // by the underlying instruction i.e., df/m, df/n and then by size. 2910 // 2911 // FIXME: The size tests here should instead be tablegen'd along with the 2912 // definitions from include/clang/Basic/BuiltinsMips.def. 2913 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2914 // be too. 2915 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2916 unsigned i = 0, l = 0, u = 0, m = 0; 2917 switch (BuiltinID) { 2918 default: return false; 2919 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2920 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2921 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2922 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2923 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2924 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2925 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2926 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2927 // df/m field. 2928 // These intrinsics take an unsigned 3 bit immediate. 2929 case Mips::BI__builtin_msa_bclri_b: 2930 case Mips::BI__builtin_msa_bnegi_b: 2931 case Mips::BI__builtin_msa_bseti_b: 2932 case Mips::BI__builtin_msa_sat_s_b: 2933 case Mips::BI__builtin_msa_sat_u_b: 2934 case Mips::BI__builtin_msa_slli_b: 2935 case Mips::BI__builtin_msa_srai_b: 2936 case Mips::BI__builtin_msa_srari_b: 2937 case Mips::BI__builtin_msa_srli_b: 2938 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2939 case Mips::BI__builtin_msa_binsli_b: 2940 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2941 // These intrinsics take an unsigned 4 bit immediate. 2942 case Mips::BI__builtin_msa_bclri_h: 2943 case Mips::BI__builtin_msa_bnegi_h: 2944 case Mips::BI__builtin_msa_bseti_h: 2945 case Mips::BI__builtin_msa_sat_s_h: 2946 case Mips::BI__builtin_msa_sat_u_h: 2947 case Mips::BI__builtin_msa_slli_h: 2948 case Mips::BI__builtin_msa_srai_h: 2949 case Mips::BI__builtin_msa_srari_h: 2950 case Mips::BI__builtin_msa_srli_h: 2951 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2952 case Mips::BI__builtin_msa_binsli_h: 2953 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2954 // These intrinsics take an unsigned 5 bit immediate. 2955 // The first block of intrinsics actually have an unsigned 5 bit field, 2956 // not a df/n field. 2957 case Mips::BI__builtin_msa_clei_u_b: 2958 case Mips::BI__builtin_msa_clei_u_h: 2959 case Mips::BI__builtin_msa_clei_u_w: 2960 case Mips::BI__builtin_msa_clei_u_d: 2961 case Mips::BI__builtin_msa_clti_u_b: 2962 case Mips::BI__builtin_msa_clti_u_h: 2963 case Mips::BI__builtin_msa_clti_u_w: 2964 case Mips::BI__builtin_msa_clti_u_d: 2965 case Mips::BI__builtin_msa_maxi_u_b: 2966 case Mips::BI__builtin_msa_maxi_u_h: 2967 case Mips::BI__builtin_msa_maxi_u_w: 2968 case Mips::BI__builtin_msa_maxi_u_d: 2969 case Mips::BI__builtin_msa_mini_u_b: 2970 case Mips::BI__builtin_msa_mini_u_h: 2971 case Mips::BI__builtin_msa_mini_u_w: 2972 case Mips::BI__builtin_msa_mini_u_d: 2973 case Mips::BI__builtin_msa_addvi_b: 2974 case Mips::BI__builtin_msa_addvi_h: 2975 case Mips::BI__builtin_msa_addvi_w: 2976 case Mips::BI__builtin_msa_addvi_d: 2977 case Mips::BI__builtin_msa_bclri_w: 2978 case Mips::BI__builtin_msa_bnegi_w: 2979 case Mips::BI__builtin_msa_bseti_w: 2980 case Mips::BI__builtin_msa_sat_s_w: 2981 case Mips::BI__builtin_msa_sat_u_w: 2982 case Mips::BI__builtin_msa_slli_w: 2983 case Mips::BI__builtin_msa_srai_w: 2984 case Mips::BI__builtin_msa_srari_w: 2985 case Mips::BI__builtin_msa_srli_w: 2986 case Mips::BI__builtin_msa_srlri_w: 2987 case Mips::BI__builtin_msa_subvi_b: 2988 case Mips::BI__builtin_msa_subvi_h: 2989 case Mips::BI__builtin_msa_subvi_w: 2990 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2991 case Mips::BI__builtin_msa_binsli_w: 2992 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2993 // These intrinsics take an unsigned 6 bit immediate. 2994 case Mips::BI__builtin_msa_bclri_d: 2995 case Mips::BI__builtin_msa_bnegi_d: 2996 case Mips::BI__builtin_msa_bseti_d: 2997 case Mips::BI__builtin_msa_sat_s_d: 2998 case Mips::BI__builtin_msa_sat_u_d: 2999 case Mips::BI__builtin_msa_slli_d: 3000 case Mips::BI__builtin_msa_srai_d: 3001 case Mips::BI__builtin_msa_srari_d: 3002 case Mips::BI__builtin_msa_srli_d: 3003 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3004 case Mips::BI__builtin_msa_binsli_d: 3005 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3006 // These intrinsics take a signed 5 bit immediate. 3007 case Mips::BI__builtin_msa_ceqi_b: 3008 case Mips::BI__builtin_msa_ceqi_h: 3009 case Mips::BI__builtin_msa_ceqi_w: 3010 case Mips::BI__builtin_msa_ceqi_d: 3011 case Mips::BI__builtin_msa_clti_s_b: 3012 case Mips::BI__builtin_msa_clti_s_h: 3013 case Mips::BI__builtin_msa_clti_s_w: 3014 case Mips::BI__builtin_msa_clti_s_d: 3015 case Mips::BI__builtin_msa_clei_s_b: 3016 case Mips::BI__builtin_msa_clei_s_h: 3017 case Mips::BI__builtin_msa_clei_s_w: 3018 case Mips::BI__builtin_msa_clei_s_d: 3019 case Mips::BI__builtin_msa_maxi_s_b: 3020 case Mips::BI__builtin_msa_maxi_s_h: 3021 case Mips::BI__builtin_msa_maxi_s_w: 3022 case Mips::BI__builtin_msa_maxi_s_d: 3023 case Mips::BI__builtin_msa_mini_s_b: 3024 case Mips::BI__builtin_msa_mini_s_h: 3025 case Mips::BI__builtin_msa_mini_s_w: 3026 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3027 // These intrinsics take an unsigned 8 bit immediate. 3028 case Mips::BI__builtin_msa_andi_b: 3029 case Mips::BI__builtin_msa_nori_b: 3030 case Mips::BI__builtin_msa_ori_b: 3031 case Mips::BI__builtin_msa_shf_b: 3032 case Mips::BI__builtin_msa_shf_h: 3033 case Mips::BI__builtin_msa_shf_w: 3034 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3035 case Mips::BI__builtin_msa_bseli_b: 3036 case Mips::BI__builtin_msa_bmnzi_b: 3037 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3038 // df/n format 3039 // These intrinsics take an unsigned 4 bit immediate. 3040 case Mips::BI__builtin_msa_copy_s_b: 3041 case Mips::BI__builtin_msa_copy_u_b: 3042 case Mips::BI__builtin_msa_insve_b: 3043 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3044 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3045 // These intrinsics take an unsigned 3 bit immediate. 3046 case Mips::BI__builtin_msa_copy_s_h: 3047 case Mips::BI__builtin_msa_copy_u_h: 3048 case Mips::BI__builtin_msa_insve_h: 3049 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3050 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3051 // These intrinsics take an unsigned 2 bit immediate. 3052 case Mips::BI__builtin_msa_copy_s_w: 3053 case Mips::BI__builtin_msa_copy_u_w: 3054 case Mips::BI__builtin_msa_insve_w: 3055 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3056 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3057 // These intrinsics take an unsigned 1 bit immediate. 3058 case Mips::BI__builtin_msa_copy_s_d: 3059 case Mips::BI__builtin_msa_copy_u_d: 3060 case Mips::BI__builtin_msa_insve_d: 3061 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3062 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3063 // Memory offsets and immediate loads. 3064 // These intrinsics take a signed 10 bit immediate. 3065 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3066 case Mips::BI__builtin_msa_ldi_h: 3067 case Mips::BI__builtin_msa_ldi_w: 3068 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3069 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3070 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3071 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3072 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3073 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3074 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3075 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3076 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3077 } 3078 3079 if (!m) 3080 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3081 3082 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3083 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3084 } 3085 3086 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3087 unsigned i = 0, l = 0, u = 0; 3088 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3089 BuiltinID == PPC::BI__builtin_divdeu || 3090 BuiltinID == PPC::BI__builtin_bpermd; 3091 bool IsTarget64Bit = Context.getTargetInfo() 3092 .getTypeWidth(Context 3093 .getTargetInfo() 3094 .getIntPtrType()) == 64; 3095 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3096 BuiltinID == PPC::BI__builtin_divweu || 3097 BuiltinID == PPC::BI__builtin_divde || 3098 BuiltinID == PPC::BI__builtin_divdeu; 3099 3100 if (Is64BitBltin && !IsTarget64Bit) 3101 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3102 << TheCall->getSourceRange(); 3103 3104 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 3105 (BuiltinID == PPC::BI__builtin_bpermd && 3106 !Context.getTargetInfo().hasFeature("bpermd"))) 3107 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3108 << TheCall->getSourceRange(); 3109 3110 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3111 if (!Context.getTargetInfo().hasFeature("vsx")) 3112 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3113 << TheCall->getSourceRange(); 3114 return false; 3115 }; 3116 3117 switch (BuiltinID) { 3118 default: return false; 3119 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3120 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3121 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3122 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3123 case PPC::BI__builtin_tbegin: 3124 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3125 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3126 case PPC::BI__builtin_tabortwc: 3127 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3128 case PPC::BI__builtin_tabortwci: 3129 case PPC::BI__builtin_tabortdci: 3130 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3131 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3132 case PPC::BI__builtin_vsx_xxpermdi: 3133 case PPC::BI__builtin_vsx_xxsldwi: 3134 return SemaBuiltinVSX(TheCall); 3135 case PPC::BI__builtin_unpack_vector_int128: 3136 return SemaVSXCheck(TheCall) || 3137 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3138 case PPC::BI__builtin_pack_vector_int128: 3139 return SemaVSXCheck(TheCall); 3140 } 3141 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3142 } 3143 3144 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3145 CallExpr *TheCall) { 3146 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3147 Expr *Arg = TheCall->getArg(0); 3148 llvm::APSInt AbortCode(32); 3149 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3150 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3151 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3152 << Arg->getSourceRange(); 3153 } 3154 3155 // For intrinsics which take an immediate value as part of the instruction, 3156 // range check them here. 3157 unsigned i = 0, l = 0, u = 0; 3158 switch (BuiltinID) { 3159 default: return false; 3160 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3161 case SystemZ::BI__builtin_s390_verimb: 3162 case SystemZ::BI__builtin_s390_verimh: 3163 case SystemZ::BI__builtin_s390_verimf: 3164 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3165 case SystemZ::BI__builtin_s390_vfaeb: 3166 case SystemZ::BI__builtin_s390_vfaeh: 3167 case SystemZ::BI__builtin_s390_vfaef: 3168 case SystemZ::BI__builtin_s390_vfaebs: 3169 case SystemZ::BI__builtin_s390_vfaehs: 3170 case SystemZ::BI__builtin_s390_vfaefs: 3171 case SystemZ::BI__builtin_s390_vfaezb: 3172 case SystemZ::BI__builtin_s390_vfaezh: 3173 case SystemZ::BI__builtin_s390_vfaezf: 3174 case SystemZ::BI__builtin_s390_vfaezbs: 3175 case SystemZ::BI__builtin_s390_vfaezhs: 3176 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3177 case SystemZ::BI__builtin_s390_vfisb: 3178 case SystemZ::BI__builtin_s390_vfidb: 3179 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3180 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3181 case SystemZ::BI__builtin_s390_vftcisb: 3182 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3183 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3184 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3185 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3186 case SystemZ::BI__builtin_s390_vstrcb: 3187 case SystemZ::BI__builtin_s390_vstrch: 3188 case SystemZ::BI__builtin_s390_vstrcf: 3189 case SystemZ::BI__builtin_s390_vstrczb: 3190 case SystemZ::BI__builtin_s390_vstrczh: 3191 case SystemZ::BI__builtin_s390_vstrczf: 3192 case SystemZ::BI__builtin_s390_vstrcbs: 3193 case SystemZ::BI__builtin_s390_vstrchs: 3194 case SystemZ::BI__builtin_s390_vstrcfs: 3195 case SystemZ::BI__builtin_s390_vstrczbs: 3196 case SystemZ::BI__builtin_s390_vstrczhs: 3197 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3198 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3199 case SystemZ::BI__builtin_s390_vfminsb: 3200 case SystemZ::BI__builtin_s390_vfmaxsb: 3201 case SystemZ::BI__builtin_s390_vfmindb: 3202 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3203 } 3204 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3205 } 3206 3207 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3208 /// This checks that the target supports __builtin_cpu_supports and 3209 /// that the string argument is constant and valid. 3210 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3211 Expr *Arg = TheCall->getArg(0); 3212 3213 // Check if the argument is a string literal. 3214 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3215 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3216 << Arg->getSourceRange(); 3217 3218 // Check the contents of the string. 3219 StringRef Feature = 3220 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3221 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3222 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3223 << Arg->getSourceRange(); 3224 return false; 3225 } 3226 3227 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3228 /// This checks that the target supports __builtin_cpu_is and 3229 /// that the string argument is constant and valid. 3230 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3231 Expr *Arg = TheCall->getArg(0); 3232 3233 // Check if the argument is a string literal. 3234 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3235 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3236 << Arg->getSourceRange(); 3237 3238 // Check the contents of the string. 3239 StringRef Feature = 3240 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3241 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3242 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3243 << Arg->getSourceRange(); 3244 return false; 3245 } 3246 3247 // Check if the rounding mode is legal. 3248 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3249 // Indicates if this instruction has rounding control or just SAE. 3250 bool HasRC = false; 3251 3252 unsigned ArgNum = 0; 3253 switch (BuiltinID) { 3254 default: 3255 return false; 3256 case X86::BI__builtin_ia32_vcvttsd2si32: 3257 case X86::BI__builtin_ia32_vcvttsd2si64: 3258 case X86::BI__builtin_ia32_vcvttsd2usi32: 3259 case X86::BI__builtin_ia32_vcvttsd2usi64: 3260 case X86::BI__builtin_ia32_vcvttss2si32: 3261 case X86::BI__builtin_ia32_vcvttss2si64: 3262 case X86::BI__builtin_ia32_vcvttss2usi32: 3263 case X86::BI__builtin_ia32_vcvttss2usi64: 3264 ArgNum = 1; 3265 break; 3266 case X86::BI__builtin_ia32_maxpd512: 3267 case X86::BI__builtin_ia32_maxps512: 3268 case X86::BI__builtin_ia32_minpd512: 3269 case X86::BI__builtin_ia32_minps512: 3270 ArgNum = 2; 3271 break; 3272 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3273 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3274 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3275 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3276 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3277 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3278 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3279 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3280 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3281 case X86::BI__builtin_ia32_exp2pd_mask: 3282 case X86::BI__builtin_ia32_exp2ps_mask: 3283 case X86::BI__builtin_ia32_getexppd512_mask: 3284 case X86::BI__builtin_ia32_getexpps512_mask: 3285 case X86::BI__builtin_ia32_rcp28pd_mask: 3286 case X86::BI__builtin_ia32_rcp28ps_mask: 3287 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3288 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3289 case X86::BI__builtin_ia32_vcomisd: 3290 case X86::BI__builtin_ia32_vcomiss: 3291 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3292 ArgNum = 3; 3293 break; 3294 case X86::BI__builtin_ia32_cmppd512_mask: 3295 case X86::BI__builtin_ia32_cmpps512_mask: 3296 case X86::BI__builtin_ia32_cmpsd_mask: 3297 case X86::BI__builtin_ia32_cmpss_mask: 3298 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3299 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3300 case X86::BI__builtin_ia32_getexpss128_round_mask: 3301 case X86::BI__builtin_ia32_maxsd_round_mask: 3302 case X86::BI__builtin_ia32_maxss_round_mask: 3303 case X86::BI__builtin_ia32_minsd_round_mask: 3304 case X86::BI__builtin_ia32_minss_round_mask: 3305 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3306 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3307 case X86::BI__builtin_ia32_reducepd512_mask: 3308 case X86::BI__builtin_ia32_reduceps512_mask: 3309 case X86::BI__builtin_ia32_rndscalepd_mask: 3310 case X86::BI__builtin_ia32_rndscaleps_mask: 3311 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3312 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3313 ArgNum = 4; 3314 break; 3315 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3316 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3317 case X86::BI__builtin_ia32_fixupimmps512_mask: 3318 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3319 case X86::BI__builtin_ia32_fixupimmsd_mask: 3320 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3321 case X86::BI__builtin_ia32_fixupimmss_mask: 3322 case X86::BI__builtin_ia32_fixupimmss_maskz: 3323 case X86::BI__builtin_ia32_rangepd512_mask: 3324 case X86::BI__builtin_ia32_rangeps512_mask: 3325 case X86::BI__builtin_ia32_rangesd128_round_mask: 3326 case X86::BI__builtin_ia32_rangess128_round_mask: 3327 case X86::BI__builtin_ia32_reducesd_mask: 3328 case X86::BI__builtin_ia32_reducess_mask: 3329 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3330 case X86::BI__builtin_ia32_rndscaless_round_mask: 3331 ArgNum = 5; 3332 break; 3333 case X86::BI__builtin_ia32_vcvtsd2si64: 3334 case X86::BI__builtin_ia32_vcvtsd2si32: 3335 case X86::BI__builtin_ia32_vcvtsd2usi32: 3336 case X86::BI__builtin_ia32_vcvtsd2usi64: 3337 case X86::BI__builtin_ia32_vcvtss2si32: 3338 case X86::BI__builtin_ia32_vcvtss2si64: 3339 case X86::BI__builtin_ia32_vcvtss2usi32: 3340 case X86::BI__builtin_ia32_vcvtss2usi64: 3341 case X86::BI__builtin_ia32_sqrtpd512: 3342 case X86::BI__builtin_ia32_sqrtps512: 3343 ArgNum = 1; 3344 HasRC = true; 3345 break; 3346 case X86::BI__builtin_ia32_addpd512: 3347 case X86::BI__builtin_ia32_addps512: 3348 case X86::BI__builtin_ia32_divpd512: 3349 case X86::BI__builtin_ia32_divps512: 3350 case X86::BI__builtin_ia32_mulpd512: 3351 case X86::BI__builtin_ia32_mulps512: 3352 case X86::BI__builtin_ia32_subpd512: 3353 case X86::BI__builtin_ia32_subps512: 3354 case X86::BI__builtin_ia32_cvtsi2sd64: 3355 case X86::BI__builtin_ia32_cvtsi2ss32: 3356 case X86::BI__builtin_ia32_cvtsi2ss64: 3357 case X86::BI__builtin_ia32_cvtusi2sd64: 3358 case X86::BI__builtin_ia32_cvtusi2ss32: 3359 case X86::BI__builtin_ia32_cvtusi2ss64: 3360 ArgNum = 2; 3361 HasRC = true; 3362 break; 3363 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3364 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3365 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3366 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3367 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3368 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3369 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3370 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3371 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3372 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3373 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3374 ArgNum = 3; 3375 HasRC = true; 3376 break; 3377 case X86::BI__builtin_ia32_addss_round_mask: 3378 case X86::BI__builtin_ia32_addsd_round_mask: 3379 case X86::BI__builtin_ia32_divss_round_mask: 3380 case X86::BI__builtin_ia32_divsd_round_mask: 3381 case X86::BI__builtin_ia32_mulss_round_mask: 3382 case X86::BI__builtin_ia32_mulsd_round_mask: 3383 case X86::BI__builtin_ia32_subss_round_mask: 3384 case X86::BI__builtin_ia32_subsd_round_mask: 3385 case X86::BI__builtin_ia32_scalefpd512_mask: 3386 case X86::BI__builtin_ia32_scalefps512_mask: 3387 case X86::BI__builtin_ia32_scalefsd_round_mask: 3388 case X86::BI__builtin_ia32_scalefss_round_mask: 3389 case X86::BI__builtin_ia32_getmantpd512_mask: 3390 case X86::BI__builtin_ia32_getmantps512_mask: 3391 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3392 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3393 case X86::BI__builtin_ia32_sqrtss_round_mask: 3394 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3395 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3396 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3397 case X86::BI__builtin_ia32_vfmaddss3_mask: 3398 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3399 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3400 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3401 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3402 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3403 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3404 case X86::BI__builtin_ia32_vfmaddps512_mask: 3405 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3406 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3407 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3408 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3409 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3410 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3411 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3412 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3413 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3414 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3415 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3416 ArgNum = 4; 3417 HasRC = true; 3418 break; 3419 case X86::BI__builtin_ia32_getmantsd_round_mask: 3420 case X86::BI__builtin_ia32_getmantss_round_mask: 3421 ArgNum = 5; 3422 HasRC = true; 3423 break; 3424 } 3425 3426 llvm::APSInt Result; 3427 3428 // We can't check the value of a dependent argument. 3429 Expr *Arg = TheCall->getArg(ArgNum); 3430 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3431 return false; 3432 3433 // Check constant-ness first. 3434 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3435 return true; 3436 3437 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3438 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3439 // combined with ROUND_NO_EXC. 3440 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3441 Result == 8/*ROUND_NO_EXC*/ || 3442 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3443 return false; 3444 3445 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3446 << Arg->getSourceRange(); 3447 } 3448 3449 // Check if the gather/scatter scale is legal. 3450 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3451 CallExpr *TheCall) { 3452 unsigned ArgNum = 0; 3453 switch (BuiltinID) { 3454 default: 3455 return false; 3456 case X86::BI__builtin_ia32_gatherpfdpd: 3457 case X86::BI__builtin_ia32_gatherpfdps: 3458 case X86::BI__builtin_ia32_gatherpfqpd: 3459 case X86::BI__builtin_ia32_gatherpfqps: 3460 case X86::BI__builtin_ia32_scatterpfdpd: 3461 case X86::BI__builtin_ia32_scatterpfdps: 3462 case X86::BI__builtin_ia32_scatterpfqpd: 3463 case X86::BI__builtin_ia32_scatterpfqps: 3464 ArgNum = 3; 3465 break; 3466 case X86::BI__builtin_ia32_gatherd_pd: 3467 case X86::BI__builtin_ia32_gatherd_pd256: 3468 case X86::BI__builtin_ia32_gatherq_pd: 3469 case X86::BI__builtin_ia32_gatherq_pd256: 3470 case X86::BI__builtin_ia32_gatherd_ps: 3471 case X86::BI__builtin_ia32_gatherd_ps256: 3472 case X86::BI__builtin_ia32_gatherq_ps: 3473 case X86::BI__builtin_ia32_gatherq_ps256: 3474 case X86::BI__builtin_ia32_gatherd_q: 3475 case X86::BI__builtin_ia32_gatherd_q256: 3476 case X86::BI__builtin_ia32_gatherq_q: 3477 case X86::BI__builtin_ia32_gatherq_q256: 3478 case X86::BI__builtin_ia32_gatherd_d: 3479 case X86::BI__builtin_ia32_gatherd_d256: 3480 case X86::BI__builtin_ia32_gatherq_d: 3481 case X86::BI__builtin_ia32_gatherq_d256: 3482 case X86::BI__builtin_ia32_gather3div2df: 3483 case X86::BI__builtin_ia32_gather3div2di: 3484 case X86::BI__builtin_ia32_gather3div4df: 3485 case X86::BI__builtin_ia32_gather3div4di: 3486 case X86::BI__builtin_ia32_gather3div4sf: 3487 case X86::BI__builtin_ia32_gather3div4si: 3488 case X86::BI__builtin_ia32_gather3div8sf: 3489 case X86::BI__builtin_ia32_gather3div8si: 3490 case X86::BI__builtin_ia32_gather3siv2df: 3491 case X86::BI__builtin_ia32_gather3siv2di: 3492 case X86::BI__builtin_ia32_gather3siv4df: 3493 case X86::BI__builtin_ia32_gather3siv4di: 3494 case X86::BI__builtin_ia32_gather3siv4sf: 3495 case X86::BI__builtin_ia32_gather3siv4si: 3496 case X86::BI__builtin_ia32_gather3siv8sf: 3497 case X86::BI__builtin_ia32_gather3siv8si: 3498 case X86::BI__builtin_ia32_gathersiv8df: 3499 case X86::BI__builtin_ia32_gathersiv16sf: 3500 case X86::BI__builtin_ia32_gatherdiv8df: 3501 case X86::BI__builtin_ia32_gatherdiv16sf: 3502 case X86::BI__builtin_ia32_gathersiv8di: 3503 case X86::BI__builtin_ia32_gathersiv16si: 3504 case X86::BI__builtin_ia32_gatherdiv8di: 3505 case X86::BI__builtin_ia32_gatherdiv16si: 3506 case X86::BI__builtin_ia32_scatterdiv2df: 3507 case X86::BI__builtin_ia32_scatterdiv2di: 3508 case X86::BI__builtin_ia32_scatterdiv4df: 3509 case X86::BI__builtin_ia32_scatterdiv4di: 3510 case X86::BI__builtin_ia32_scatterdiv4sf: 3511 case X86::BI__builtin_ia32_scatterdiv4si: 3512 case X86::BI__builtin_ia32_scatterdiv8sf: 3513 case X86::BI__builtin_ia32_scatterdiv8si: 3514 case X86::BI__builtin_ia32_scattersiv2df: 3515 case X86::BI__builtin_ia32_scattersiv2di: 3516 case X86::BI__builtin_ia32_scattersiv4df: 3517 case X86::BI__builtin_ia32_scattersiv4di: 3518 case X86::BI__builtin_ia32_scattersiv4sf: 3519 case X86::BI__builtin_ia32_scattersiv4si: 3520 case X86::BI__builtin_ia32_scattersiv8sf: 3521 case X86::BI__builtin_ia32_scattersiv8si: 3522 case X86::BI__builtin_ia32_scattersiv8df: 3523 case X86::BI__builtin_ia32_scattersiv16sf: 3524 case X86::BI__builtin_ia32_scatterdiv8df: 3525 case X86::BI__builtin_ia32_scatterdiv16sf: 3526 case X86::BI__builtin_ia32_scattersiv8di: 3527 case X86::BI__builtin_ia32_scattersiv16si: 3528 case X86::BI__builtin_ia32_scatterdiv8di: 3529 case X86::BI__builtin_ia32_scatterdiv16si: 3530 ArgNum = 4; 3531 break; 3532 } 3533 3534 llvm::APSInt Result; 3535 3536 // We can't check the value of a dependent argument. 3537 Expr *Arg = TheCall->getArg(ArgNum); 3538 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3539 return false; 3540 3541 // Check constant-ness first. 3542 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3543 return true; 3544 3545 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3546 return false; 3547 3548 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3549 << Arg->getSourceRange(); 3550 } 3551 3552 static bool isX86_32Builtin(unsigned BuiltinID) { 3553 // These builtins only work on x86-32 targets. 3554 switch (BuiltinID) { 3555 case X86::BI__builtin_ia32_readeflags_u32: 3556 case X86::BI__builtin_ia32_writeeflags_u32: 3557 return true; 3558 } 3559 3560 return false; 3561 } 3562 3563 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3564 if (BuiltinID == X86::BI__builtin_cpu_supports) 3565 return SemaBuiltinCpuSupports(*this, TheCall); 3566 3567 if (BuiltinID == X86::BI__builtin_cpu_is) 3568 return SemaBuiltinCpuIs(*this, TheCall); 3569 3570 // Check for 32-bit only builtins on a 64-bit target. 3571 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3572 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3573 return Diag(TheCall->getCallee()->getBeginLoc(), 3574 diag::err_32_bit_builtin_64_bit_tgt); 3575 3576 // If the intrinsic has rounding or SAE make sure its valid. 3577 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3578 return true; 3579 3580 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3581 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3582 return true; 3583 3584 // For intrinsics which take an immediate value as part of the instruction, 3585 // range check them here. 3586 int i = 0, l = 0, u = 0; 3587 switch (BuiltinID) { 3588 default: 3589 return false; 3590 case X86::BI__builtin_ia32_vec_ext_v2si: 3591 case X86::BI__builtin_ia32_vec_ext_v2di: 3592 case X86::BI__builtin_ia32_vextractf128_pd256: 3593 case X86::BI__builtin_ia32_vextractf128_ps256: 3594 case X86::BI__builtin_ia32_vextractf128_si256: 3595 case X86::BI__builtin_ia32_extract128i256: 3596 case X86::BI__builtin_ia32_extractf64x4_mask: 3597 case X86::BI__builtin_ia32_extracti64x4_mask: 3598 case X86::BI__builtin_ia32_extractf32x8_mask: 3599 case X86::BI__builtin_ia32_extracti32x8_mask: 3600 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3601 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3602 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3603 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3604 i = 1; l = 0; u = 1; 3605 break; 3606 case X86::BI__builtin_ia32_vec_set_v2di: 3607 case X86::BI__builtin_ia32_vinsertf128_pd256: 3608 case X86::BI__builtin_ia32_vinsertf128_ps256: 3609 case X86::BI__builtin_ia32_vinsertf128_si256: 3610 case X86::BI__builtin_ia32_insert128i256: 3611 case X86::BI__builtin_ia32_insertf32x8: 3612 case X86::BI__builtin_ia32_inserti32x8: 3613 case X86::BI__builtin_ia32_insertf64x4: 3614 case X86::BI__builtin_ia32_inserti64x4: 3615 case X86::BI__builtin_ia32_insertf64x2_256: 3616 case X86::BI__builtin_ia32_inserti64x2_256: 3617 case X86::BI__builtin_ia32_insertf32x4_256: 3618 case X86::BI__builtin_ia32_inserti32x4_256: 3619 i = 2; l = 0; u = 1; 3620 break; 3621 case X86::BI__builtin_ia32_vpermilpd: 3622 case X86::BI__builtin_ia32_vec_ext_v4hi: 3623 case X86::BI__builtin_ia32_vec_ext_v4si: 3624 case X86::BI__builtin_ia32_vec_ext_v4sf: 3625 case X86::BI__builtin_ia32_vec_ext_v4di: 3626 case X86::BI__builtin_ia32_extractf32x4_mask: 3627 case X86::BI__builtin_ia32_extracti32x4_mask: 3628 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3629 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3630 i = 1; l = 0; u = 3; 3631 break; 3632 case X86::BI_mm_prefetch: 3633 case X86::BI__builtin_ia32_vec_ext_v8hi: 3634 case X86::BI__builtin_ia32_vec_ext_v8si: 3635 i = 1; l = 0; u = 7; 3636 break; 3637 case X86::BI__builtin_ia32_sha1rnds4: 3638 case X86::BI__builtin_ia32_blendpd: 3639 case X86::BI__builtin_ia32_shufpd: 3640 case X86::BI__builtin_ia32_vec_set_v4hi: 3641 case X86::BI__builtin_ia32_vec_set_v4si: 3642 case X86::BI__builtin_ia32_vec_set_v4di: 3643 case X86::BI__builtin_ia32_shuf_f32x4_256: 3644 case X86::BI__builtin_ia32_shuf_f64x2_256: 3645 case X86::BI__builtin_ia32_shuf_i32x4_256: 3646 case X86::BI__builtin_ia32_shuf_i64x2_256: 3647 case X86::BI__builtin_ia32_insertf64x2_512: 3648 case X86::BI__builtin_ia32_inserti64x2_512: 3649 case X86::BI__builtin_ia32_insertf32x4: 3650 case X86::BI__builtin_ia32_inserti32x4: 3651 i = 2; l = 0; u = 3; 3652 break; 3653 case X86::BI__builtin_ia32_vpermil2pd: 3654 case X86::BI__builtin_ia32_vpermil2pd256: 3655 case X86::BI__builtin_ia32_vpermil2ps: 3656 case X86::BI__builtin_ia32_vpermil2ps256: 3657 i = 3; l = 0; u = 3; 3658 break; 3659 case X86::BI__builtin_ia32_cmpb128_mask: 3660 case X86::BI__builtin_ia32_cmpw128_mask: 3661 case X86::BI__builtin_ia32_cmpd128_mask: 3662 case X86::BI__builtin_ia32_cmpq128_mask: 3663 case X86::BI__builtin_ia32_cmpb256_mask: 3664 case X86::BI__builtin_ia32_cmpw256_mask: 3665 case X86::BI__builtin_ia32_cmpd256_mask: 3666 case X86::BI__builtin_ia32_cmpq256_mask: 3667 case X86::BI__builtin_ia32_cmpb512_mask: 3668 case X86::BI__builtin_ia32_cmpw512_mask: 3669 case X86::BI__builtin_ia32_cmpd512_mask: 3670 case X86::BI__builtin_ia32_cmpq512_mask: 3671 case X86::BI__builtin_ia32_ucmpb128_mask: 3672 case X86::BI__builtin_ia32_ucmpw128_mask: 3673 case X86::BI__builtin_ia32_ucmpd128_mask: 3674 case X86::BI__builtin_ia32_ucmpq128_mask: 3675 case X86::BI__builtin_ia32_ucmpb256_mask: 3676 case X86::BI__builtin_ia32_ucmpw256_mask: 3677 case X86::BI__builtin_ia32_ucmpd256_mask: 3678 case X86::BI__builtin_ia32_ucmpq256_mask: 3679 case X86::BI__builtin_ia32_ucmpb512_mask: 3680 case X86::BI__builtin_ia32_ucmpw512_mask: 3681 case X86::BI__builtin_ia32_ucmpd512_mask: 3682 case X86::BI__builtin_ia32_ucmpq512_mask: 3683 case X86::BI__builtin_ia32_vpcomub: 3684 case X86::BI__builtin_ia32_vpcomuw: 3685 case X86::BI__builtin_ia32_vpcomud: 3686 case X86::BI__builtin_ia32_vpcomuq: 3687 case X86::BI__builtin_ia32_vpcomb: 3688 case X86::BI__builtin_ia32_vpcomw: 3689 case X86::BI__builtin_ia32_vpcomd: 3690 case X86::BI__builtin_ia32_vpcomq: 3691 case X86::BI__builtin_ia32_vec_set_v8hi: 3692 case X86::BI__builtin_ia32_vec_set_v8si: 3693 i = 2; l = 0; u = 7; 3694 break; 3695 case X86::BI__builtin_ia32_vpermilpd256: 3696 case X86::BI__builtin_ia32_roundps: 3697 case X86::BI__builtin_ia32_roundpd: 3698 case X86::BI__builtin_ia32_roundps256: 3699 case X86::BI__builtin_ia32_roundpd256: 3700 case X86::BI__builtin_ia32_getmantpd128_mask: 3701 case X86::BI__builtin_ia32_getmantpd256_mask: 3702 case X86::BI__builtin_ia32_getmantps128_mask: 3703 case X86::BI__builtin_ia32_getmantps256_mask: 3704 case X86::BI__builtin_ia32_getmantpd512_mask: 3705 case X86::BI__builtin_ia32_getmantps512_mask: 3706 case X86::BI__builtin_ia32_vec_ext_v16qi: 3707 case X86::BI__builtin_ia32_vec_ext_v16hi: 3708 i = 1; l = 0; u = 15; 3709 break; 3710 case X86::BI__builtin_ia32_pblendd128: 3711 case X86::BI__builtin_ia32_blendps: 3712 case X86::BI__builtin_ia32_blendpd256: 3713 case X86::BI__builtin_ia32_shufpd256: 3714 case X86::BI__builtin_ia32_roundss: 3715 case X86::BI__builtin_ia32_roundsd: 3716 case X86::BI__builtin_ia32_rangepd128_mask: 3717 case X86::BI__builtin_ia32_rangepd256_mask: 3718 case X86::BI__builtin_ia32_rangepd512_mask: 3719 case X86::BI__builtin_ia32_rangeps128_mask: 3720 case X86::BI__builtin_ia32_rangeps256_mask: 3721 case X86::BI__builtin_ia32_rangeps512_mask: 3722 case X86::BI__builtin_ia32_getmantsd_round_mask: 3723 case X86::BI__builtin_ia32_getmantss_round_mask: 3724 case X86::BI__builtin_ia32_vec_set_v16qi: 3725 case X86::BI__builtin_ia32_vec_set_v16hi: 3726 i = 2; l = 0; u = 15; 3727 break; 3728 case X86::BI__builtin_ia32_vec_ext_v32qi: 3729 i = 1; l = 0; u = 31; 3730 break; 3731 case X86::BI__builtin_ia32_cmpps: 3732 case X86::BI__builtin_ia32_cmpss: 3733 case X86::BI__builtin_ia32_cmppd: 3734 case X86::BI__builtin_ia32_cmpsd: 3735 case X86::BI__builtin_ia32_cmpps256: 3736 case X86::BI__builtin_ia32_cmppd256: 3737 case X86::BI__builtin_ia32_cmpps128_mask: 3738 case X86::BI__builtin_ia32_cmppd128_mask: 3739 case X86::BI__builtin_ia32_cmpps256_mask: 3740 case X86::BI__builtin_ia32_cmppd256_mask: 3741 case X86::BI__builtin_ia32_cmpps512_mask: 3742 case X86::BI__builtin_ia32_cmppd512_mask: 3743 case X86::BI__builtin_ia32_cmpsd_mask: 3744 case X86::BI__builtin_ia32_cmpss_mask: 3745 case X86::BI__builtin_ia32_vec_set_v32qi: 3746 i = 2; l = 0; u = 31; 3747 break; 3748 case X86::BI__builtin_ia32_permdf256: 3749 case X86::BI__builtin_ia32_permdi256: 3750 case X86::BI__builtin_ia32_permdf512: 3751 case X86::BI__builtin_ia32_permdi512: 3752 case X86::BI__builtin_ia32_vpermilps: 3753 case X86::BI__builtin_ia32_vpermilps256: 3754 case X86::BI__builtin_ia32_vpermilpd512: 3755 case X86::BI__builtin_ia32_vpermilps512: 3756 case X86::BI__builtin_ia32_pshufd: 3757 case X86::BI__builtin_ia32_pshufd256: 3758 case X86::BI__builtin_ia32_pshufd512: 3759 case X86::BI__builtin_ia32_pshufhw: 3760 case X86::BI__builtin_ia32_pshufhw256: 3761 case X86::BI__builtin_ia32_pshufhw512: 3762 case X86::BI__builtin_ia32_pshuflw: 3763 case X86::BI__builtin_ia32_pshuflw256: 3764 case X86::BI__builtin_ia32_pshuflw512: 3765 case X86::BI__builtin_ia32_vcvtps2ph: 3766 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3767 case X86::BI__builtin_ia32_vcvtps2ph256: 3768 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3769 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3770 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3771 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3772 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3773 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3774 case X86::BI__builtin_ia32_rndscaleps_mask: 3775 case X86::BI__builtin_ia32_rndscalepd_mask: 3776 case X86::BI__builtin_ia32_reducepd128_mask: 3777 case X86::BI__builtin_ia32_reducepd256_mask: 3778 case X86::BI__builtin_ia32_reducepd512_mask: 3779 case X86::BI__builtin_ia32_reduceps128_mask: 3780 case X86::BI__builtin_ia32_reduceps256_mask: 3781 case X86::BI__builtin_ia32_reduceps512_mask: 3782 case X86::BI__builtin_ia32_prold512: 3783 case X86::BI__builtin_ia32_prolq512: 3784 case X86::BI__builtin_ia32_prold128: 3785 case X86::BI__builtin_ia32_prold256: 3786 case X86::BI__builtin_ia32_prolq128: 3787 case X86::BI__builtin_ia32_prolq256: 3788 case X86::BI__builtin_ia32_prord512: 3789 case X86::BI__builtin_ia32_prorq512: 3790 case X86::BI__builtin_ia32_prord128: 3791 case X86::BI__builtin_ia32_prord256: 3792 case X86::BI__builtin_ia32_prorq128: 3793 case X86::BI__builtin_ia32_prorq256: 3794 case X86::BI__builtin_ia32_fpclasspd128_mask: 3795 case X86::BI__builtin_ia32_fpclasspd256_mask: 3796 case X86::BI__builtin_ia32_fpclassps128_mask: 3797 case X86::BI__builtin_ia32_fpclassps256_mask: 3798 case X86::BI__builtin_ia32_fpclassps512_mask: 3799 case X86::BI__builtin_ia32_fpclasspd512_mask: 3800 case X86::BI__builtin_ia32_fpclasssd_mask: 3801 case X86::BI__builtin_ia32_fpclassss_mask: 3802 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3803 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3804 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3805 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3806 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3807 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3808 case X86::BI__builtin_ia32_kshiftliqi: 3809 case X86::BI__builtin_ia32_kshiftlihi: 3810 case X86::BI__builtin_ia32_kshiftlisi: 3811 case X86::BI__builtin_ia32_kshiftlidi: 3812 case X86::BI__builtin_ia32_kshiftriqi: 3813 case X86::BI__builtin_ia32_kshiftrihi: 3814 case X86::BI__builtin_ia32_kshiftrisi: 3815 case X86::BI__builtin_ia32_kshiftridi: 3816 i = 1; l = 0; u = 255; 3817 break; 3818 case X86::BI__builtin_ia32_vperm2f128_pd256: 3819 case X86::BI__builtin_ia32_vperm2f128_ps256: 3820 case X86::BI__builtin_ia32_vperm2f128_si256: 3821 case X86::BI__builtin_ia32_permti256: 3822 case X86::BI__builtin_ia32_pblendw128: 3823 case X86::BI__builtin_ia32_pblendw256: 3824 case X86::BI__builtin_ia32_blendps256: 3825 case X86::BI__builtin_ia32_pblendd256: 3826 case X86::BI__builtin_ia32_palignr128: 3827 case X86::BI__builtin_ia32_palignr256: 3828 case X86::BI__builtin_ia32_palignr512: 3829 case X86::BI__builtin_ia32_alignq512: 3830 case X86::BI__builtin_ia32_alignd512: 3831 case X86::BI__builtin_ia32_alignd128: 3832 case X86::BI__builtin_ia32_alignd256: 3833 case X86::BI__builtin_ia32_alignq128: 3834 case X86::BI__builtin_ia32_alignq256: 3835 case X86::BI__builtin_ia32_vcomisd: 3836 case X86::BI__builtin_ia32_vcomiss: 3837 case X86::BI__builtin_ia32_shuf_f32x4: 3838 case X86::BI__builtin_ia32_shuf_f64x2: 3839 case X86::BI__builtin_ia32_shuf_i32x4: 3840 case X86::BI__builtin_ia32_shuf_i64x2: 3841 case X86::BI__builtin_ia32_shufpd512: 3842 case X86::BI__builtin_ia32_shufps: 3843 case X86::BI__builtin_ia32_shufps256: 3844 case X86::BI__builtin_ia32_shufps512: 3845 case X86::BI__builtin_ia32_dbpsadbw128: 3846 case X86::BI__builtin_ia32_dbpsadbw256: 3847 case X86::BI__builtin_ia32_dbpsadbw512: 3848 case X86::BI__builtin_ia32_vpshldd128: 3849 case X86::BI__builtin_ia32_vpshldd256: 3850 case X86::BI__builtin_ia32_vpshldd512: 3851 case X86::BI__builtin_ia32_vpshldq128: 3852 case X86::BI__builtin_ia32_vpshldq256: 3853 case X86::BI__builtin_ia32_vpshldq512: 3854 case X86::BI__builtin_ia32_vpshldw128: 3855 case X86::BI__builtin_ia32_vpshldw256: 3856 case X86::BI__builtin_ia32_vpshldw512: 3857 case X86::BI__builtin_ia32_vpshrdd128: 3858 case X86::BI__builtin_ia32_vpshrdd256: 3859 case X86::BI__builtin_ia32_vpshrdd512: 3860 case X86::BI__builtin_ia32_vpshrdq128: 3861 case X86::BI__builtin_ia32_vpshrdq256: 3862 case X86::BI__builtin_ia32_vpshrdq512: 3863 case X86::BI__builtin_ia32_vpshrdw128: 3864 case X86::BI__builtin_ia32_vpshrdw256: 3865 case X86::BI__builtin_ia32_vpshrdw512: 3866 i = 2; l = 0; u = 255; 3867 break; 3868 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3869 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3870 case X86::BI__builtin_ia32_fixupimmps512_mask: 3871 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3872 case X86::BI__builtin_ia32_fixupimmsd_mask: 3873 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3874 case X86::BI__builtin_ia32_fixupimmss_mask: 3875 case X86::BI__builtin_ia32_fixupimmss_maskz: 3876 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3877 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3878 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3879 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3880 case X86::BI__builtin_ia32_fixupimmps128_mask: 3881 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3882 case X86::BI__builtin_ia32_fixupimmps256_mask: 3883 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3884 case X86::BI__builtin_ia32_pternlogd512_mask: 3885 case X86::BI__builtin_ia32_pternlogd512_maskz: 3886 case X86::BI__builtin_ia32_pternlogq512_mask: 3887 case X86::BI__builtin_ia32_pternlogq512_maskz: 3888 case X86::BI__builtin_ia32_pternlogd128_mask: 3889 case X86::BI__builtin_ia32_pternlogd128_maskz: 3890 case X86::BI__builtin_ia32_pternlogd256_mask: 3891 case X86::BI__builtin_ia32_pternlogd256_maskz: 3892 case X86::BI__builtin_ia32_pternlogq128_mask: 3893 case X86::BI__builtin_ia32_pternlogq128_maskz: 3894 case X86::BI__builtin_ia32_pternlogq256_mask: 3895 case X86::BI__builtin_ia32_pternlogq256_maskz: 3896 i = 3; l = 0; u = 255; 3897 break; 3898 case X86::BI__builtin_ia32_gatherpfdpd: 3899 case X86::BI__builtin_ia32_gatherpfdps: 3900 case X86::BI__builtin_ia32_gatherpfqpd: 3901 case X86::BI__builtin_ia32_gatherpfqps: 3902 case X86::BI__builtin_ia32_scatterpfdpd: 3903 case X86::BI__builtin_ia32_scatterpfdps: 3904 case X86::BI__builtin_ia32_scatterpfqpd: 3905 case X86::BI__builtin_ia32_scatterpfqps: 3906 i = 4; l = 2; u = 3; 3907 break; 3908 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3909 case X86::BI__builtin_ia32_rndscaless_round_mask: 3910 i = 4; l = 0; u = 255; 3911 break; 3912 } 3913 3914 // Note that we don't force a hard error on the range check here, allowing 3915 // template-generated or macro-generated dead code to potentially have out-of- 3916 // range values. These need to code generate, but don't need to necessarily 3917 // make any sense. We use a warning that defaults to an error. 3918 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3919 } 3920 3921 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3922 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3923 /// Returns true when the format fits the function and the FormatStringInfo has 3924 /// been populated. 3925 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3926 FormatStringInfo *FSI) { 3927 FSI->HasVAListArg = Format->getFirstArg() == 0; 3928 FSI->FormatIdx = Format->getFormatIdx() - 1; 3929 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3930 3931 // The way the format attribute works in GCC, the implicit this argument 3932 // of member functions is counted. However, it doesn't appear in our own 3933 // lists, so decrement format_idx in that case. 3934 if (IsCXXMember) { 3935 if(FSI->FormatIdx == 0) 3936 return false; 3937 --FSI->FormatIdx; 3938 if (FSI->FirstDataArg != 0) 3939 --FSI->FirstDataArg; 3940 } 3941 return true; 3942 } 3943 3944 /// Checks if a the given expression evaluates to null. 3945 /// 3946 /// Returns true if the value evaluates to null. 3947 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3948 // If the expression has non-null type, it doesn't evaluate to null. 3949 if (auto nullability 3950 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3951 if (*nullability == NullabilityKind::NonNull) 3952 return false; 3953 } 3954 3955 // As a special case, transparent unions initialized with zero are 3956 // considered null for the purposes of the nonnull attribute. 3957 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3958 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3959 if (const CompoundLiteralExpr *CLE = 3960 dyn_cast<CompoundLiteralExpr>(Expr)) 3961 if (const InitListExpr *ILE = 3962 dyn_cast<InitListExpr>(CLE->getInitializer())) 3963 Expr = ILE->getInit(0); 3964 } 3965 3966 bool Result; 3967 return (!Expr->isValueDependent() && 3968 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3969 !Result); 3970 } 3971 3972 static void CheckNonNullArgument(Sema &S, 3973 const Expr *ArgExpr, 3974 SourceLocation CallSiteLoc) { 3975 if (CheckNonNullExpr(S, ArgExpr)) 3976 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3977 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 3978 } 3979 3980 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3981 FormatStringInfo FSI; 3982 if ((GetFormatStringType(Format) == FST_NSString) && 3983 getFormatStringInfo(Format, false, &FSI)) { 3984 Idx = FSI.FormatIdx; 3985 return true; 3986 } 3987 return false; 3988 } 3989 3990 /// Diagnose use of %s directive in an NSString which is being passed 3991 /// as formatting string to formatting method. 3992 static void 3993 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3994 const NamedDecl *FDecl, 3995 Expr **Args, 3996 unsigned NumArgs) { 3997 unsigned Idx = 0; 3998 bool Format = false; 3999 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4000 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4001 Idx = 2; 4002 Format = true; 4003 } 4004 else 4005 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4006 if (S.GetFormatNSStringIdx(I, Idx)) { 4007 Format = true; 4008 break; 4009 } 4010 } 4011 if (!Format || NumArgs <= Idx) 4012 return; 4013 const Expr *FormatExpr = Args[Idx]; 4014 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4015 FormatExpr = CSCE->getSubExpr(); 4016 const StringLiteral *FormatString; 4017 if (const ObjCStringLiteral *OSL = 4018 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4019 FormatString = OSL->getString(); 4020 else 4021 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4022 if (!FormatString) 4023 return; 4024 if (S.FormatStringHasSArg(FormatString)) { 4025 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4026 << "%s" << 1 << 1; 4027 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4028 << FDecl->getDeclName(); 4029 } 4030 } 4031 4032 /// Determine whether the given type has a non-null nullability annotation. 4033 static bool isNonNullType(ASTContext &ctx, QualType type) { 4034 if (auto nullability = type->getNullability(ctx)) 4035 return *nullability == NullabilityKind::NonNull; 4036 4037 return false; 4038 } 4039 4040 static void CheckNonNullArguments(Sema &S, 4041 const NamedDecl *FDecl, 4042 const FunctionProtoType *Proto, 4043 ArrayRef<const Expr *> Args, 4044 SourceLocation CallSiteLoc) { 4045 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4046 4047 // Check the attributes attached to the method/function itself. 4048 llvm::SmallBitVector NonNullArgs; 4049 if (FDecl) { 4050 // Handle the nonnull attribute on the function/method declaration itself. 4051 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4052 if (!NonNull->args_size()) { 4053 // Easy case: all pointer arguments are nonnull. 4054 for (const auto *Arg : Args) 4055 if (S.isValidPointerAttrType(Arg->getType())) 4056 CheckNonNullArgument(S, Arg, CallSiteLoc); 4057 return; 4058 } 4059 4060 for (const ParamIdx &Idx : NonNull->args()) { 4061 unsigned IdxAST = Idx.getASTIndex(); 4062 if (IdxAST >= Args.size()) 4063 continue; 4064 if (NonNullArgs.empty()) 4065 NonNullArgs.resize(Args.size()); 4066 NonNullArgs.set(IdxAST); 4067 } 4068 } 4069 } 4070 4071 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4072 // Handle the nonnull attribute on the parameters of the 4073 // function/method. 4074 ArrayRef<ParmVarDecl*> parms; 4075 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4076 parms = FD->parameters(); 4077 else 4078 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4079 4080 unsigned ParamIndex = 0; 4081 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4082 I != E; ++I, ++ParamIndex) { 4083 const ParmVarDecl *PVD = *I; 4084 if (PVD->hasAttr<NonNullAttr>() || 4085 isNonNullType(S.Context, PVD->getType())) { 4086 if (NonNullArgs.empty()) 4087 NonNullArgs.resize(Args.size()); 4088 4089 NonNullArgs.set(ParamIndex); 4090 } 4091 } 4092 } else { 4093 // If we have a non-function, non-method declaration but no 4094 // function prototype, try to dig out the function prototype. 4095 if (!Proto) { 4096 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4097 QualType type = VD->getType().getNonReferenceType(); 4098 if (auto pointerType = type->getAs<PointerType>()) 4099 type = pointerType->getPointeeType(); 4100 else if (auto blockType = type->getAs<BlockPointerType>()) 4101 type = blockType->getPointeeType(); 4102 // FIXME: data member pointers? 4103 4104 // Dig out the function prototype, if there is one. 4105 Proto = type->getAs<FunctionProtoType>(); 4106 } 4107 } 4108 4109 // Fill in non-null argument information from the nullability 4110 // information on the parameter types (if we have them). 4111 if (Proto) { 4112 unsigned Index = 0; 4113 for (auto paramType : Proto->getParamTypes()) { 4114 if (isNonNullType(S.Context, paramType)) { 4115 if (NonNullArgs.empty()) 4116 NonNullArgs.resize(Args.size()); 4117 4118 NonNullArgs.set(Index); 4119 } 4120 4121 ++Index; 4122 } 4123 } 4124 } 4125 4126 // Check for non-null arguments. 4127 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4128 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4129 if (NonNullArgs[ArgIndex]) 4130 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4131 } 4132 } 4133 4134 /// Handles the checks for format strings, non-POD arguments to vararg 4135 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4136 /// attributes. 4137 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4138 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4139 bool IsMemberFunction, SourceLocation Loc, 4140 SourceRange Range, VariadicCallType CallType) { 4141 // FIXME: We should check as much as we can in the template definition. 4142 if (CurContext->isDependentContext()) 4143 return; 4144 4145 // Printf and scanf checking. 4146 llvm::SmallBitVector CheckedVarArgs; 4147 if (FDecl) { 4148 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4149 // Only create vector if there are format attributes. 4150 CheckedVarArgs.resize(Args.size()); 4151 4152 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4153 CheckedVarArgs); 4154 } 4155 } 4156 4157 // Refuse POD arguments that weren't caught by the format string 4158 // checks above. 4159 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4160 if (CallType != VariadicDoesNotApply && 4161 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4162 unsigned NumParams = Proto ? Proto->getNumParams() 4163 : FDecl && isa<FunctionDecl>(FDecl) 4164 ? cast<FunctionDecl>(FDecl)->getNumParams() 4165 : FDecl && isa<ObjCMethodDecl>(FDecl) 4166 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4167 : 0; 4168 4169 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4170 // Args[ArgIdx] can be null in malformed code. 4171 if (const Expr *Arg = Args[ArgIdx]) { 4172 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4173 checkVariadicArgument(Arg, CallType); 4174 } 4175 } 4176 } 4177 4178 if (FDecl || Proto) { 4179 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4180 4181 // Type safety checking. 4182 if (FDecl) { 4183 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4184 CheckArgumentWithTypeTag(I, Args, Loc); 4185 } 4186 } 4187 4188 if (FD) 4189 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4190 } 4191 4192 /// CheckConstructorCall - Check a constructor call for correctness and safety 4193 /// properties not enforced by the C type system. 4194 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4195 ArrayRef<const Expr *> Args, 4196 const FunctionProtoType *Proto, 4197 SourceLocation Loc) { 4198 VariadicCallType CallType = 4199 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4200 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4201 Loc, SourceRange(), CallType); 4202 } 4203 4204 /// CheckFunctionCall - Check a direct function call for various correctness 4205 /// and safety properties not strictly enforced by the C type system. 4206 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4207 const FunctionProtoType *Proto) { 4208 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4209 isa<CXXMethodDecl>(FDecl); 4210 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4211 IsMemberOperatorCall; 4212 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4213 TheCall->getCallee()); 4214 Expr** Args = TheCall->getArgs(); 4215 unsigned NumArgs = TheCall->getNumArgs(); 4216 4217 Expr *ImplicitThis = nullptr; 4218 if (IsMemberOperatorCall) { 4219 // If this is a call to a member operator, hide the first argument 4220 // from checkCall. 4221 // FIXME: Our choice of AST representation here is less than ideal. 4222 ImplicitThis = Args[0]; 4223 ++Args; 4224 --NumArgs; 4225 } else if (IsMemberFunction) 4226 ImplicitThis = 4227 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4228 4229 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4230 IsMemberFunction, TheCall->getRParenLoc(), 4231 TheCall->getCallee()->getSourceRange(), CallType); 4232 4233 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4234 // None of the checks below are needed for functions that don't have 4235 // simple names (e.g., C++ conversion functions). 4236 if (!FnInfo) 4237 return false; 4238 4239 CheckAbsoluteValueFunction(TheCall, FDecl); 4240 CheckMaxUnsignedZero(TheCall, FDecl); 4241 4242 if (getLangOpts().ObjC) 4243 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4244 4245 unsigned CMId = FDecl->getMemoryFunctionKind(); 4246 if (CMId == 0) 4247 return false; 4248 4249 // Handle memory setting and copying functions. 4250 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4251 CheckStrlcpycatArguments(TheCall, FnInfo); 4252 else if (CMId == Builtin::BIstrncat) 4253 CheckStrncatArguments(TheCall, FnInfo); 4254 else 4255 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4256 4257 return false; 4258 } 4259 4260 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4261 ArrayRef<const Expr *> Args) { 4262 VariadicCallType CallType = 4263 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4264 4265 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4266 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4267 CallType); 4268 4269 return false; 4270 } 4271 4272 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4273 const FunctionProtoType *Proto) { 4274 QualType Ty; 4275 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4276 Ty = V->getType().getNonReferenceType(); 4277 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4278 Ty = F->getType().getNonReferenceType(); 4279 else 4280 return false; 4281 4282 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4283 !Ty->isFunctionProtoType()) 4284 return false; 4285 4286 VariadicCallType CallType; 4287 if (!Proto || !Proto->isVariadic()) { 4288 CallType = VariadicDoesNotApply; 4289 } else if (Ty->isBlockPointerType()) { 4290 CallType = VariadicBlock; 4291 } else { // Ty->isFunctionPointerType() 4292 CallType = VariadicFunction; 4293 } 4294 4295 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4296 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4297 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4298 TheCall->getCallee()->getSourceRange(), CallType); 4299 4300 return false; 4301 } 4302 4303 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4304 /// such as function pointers returned from functions. 4305 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4306 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4307 TheCall->getCallee()); 4308 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4309 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4310 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4311 TheCall->getCallee()->getSourceRange(), CallType); 4312 4313 return false; 4314 } 4315 4316 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4317 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4318 return false; 4319 4320 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4321 switch (Op) { 4322 case AtomicExpr::AO__c11_atomic_init: 4323 case AtomicExpr::AO__opencl_atomic_init: 4324 llvm_unreachable("There is no ordering argument for an init"); 4325 4326 case AtomicExpr::AO__c11_atomic_load: 4327 case AtomicExpr::AO__opencl_atomic_load: 4328 case AtomicExpr::AO__atomic_load_n: 4329 case AtomicExpr::AO__atomic_load: 4330 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4331 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4332 4333 case AtomicExpr::AO__c11_atomic_store: 4334 case AtomicExpr::AO__opencl_atomic_store: 4335 case AtomicExpr::AO__atomic_store: 4336 case AtomicExpr::AO__atomic_store_n: 4337 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4338 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4339 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4340 4341 default: 4342 return true; 4343 } 4344 } 4345 4346 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4347 AtomicExpr::AtomicOp Op) { 4348 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4349 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4350 4351 // All the non-OpenCL operations take one of the following forms. 4352 // The OpenCL operations take the __c11 forms with one extra argument for 4353 // synchronization scope. 4354 enum { 4355 // C __c11_atomic_init(A *, C) 4356 Init, 4357 4358 // C __c11_atomic_load(A *, int) 4359 Load, 4360 4361 // void __atomic_load(A *, CP, int) 4362 LoadCopy, 4363 4364 // void __atomic_store(A *, CP, int) 4365 Copy, 4366 4367 // C __c11_atomic_add(A *, M, int) 4368 Arithmetic, 4369 4370 // C __atomic_exchange_n(A *, CP, int) 4371 Xchg, 4372 4373 // void __atomic_exchange(A *, C *, CP, int) 4374 GNUXchg, 4375 4376 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4377 C11CmpXchg, 4378 4379 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4380 GNUCmpXchg 4381 } Form = Init; 4382 4383 const unsigned NumForm = GNUCmpXchg + 1; 4384 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4385 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4386 // where: 4387 // C is an appropriate type, 4388 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4389 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4390 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4391 // the int parameters are for orderings. 4392 4393 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4394 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4395 "need to update code for modified forms"); 4396 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4397 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4398 AtomicExpr::AO__atomic_load, 4399 "need to update code for modified C11 atomics"); 4400 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4401 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4402 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4403 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4404 IsOpenCL; 4405 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4406 Op == AtomicExpr::AO__atomic_store_n || 4407 Op == AtomicExpr::AO__atomic_exchange_n || 4408 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4409 bool IsAddSub = false; 4410 bool IsMinMax = false; 4411 4412 switch (Op) { 4413 case AtomicExpr::AO__c11_atomic_init: 4414 case AtomicExpr::AO__opencl_atomic_init: 4415 Form = Init; 4416 break; 4417 4418 case AtomicExpr::AO__c11_atomic_load: 4419 case AtomicExpr::AO__opencl_atomic_load: 4420 case AtomicExpr::AO__atomic_load_n: 4421 Form = Load; 4422 break; 4423 4424 case AtomicExpr::AO__atomic_load: 4425 Form = LoadCopy; 4426 break; 4427 4428 case AtomicExpr::AO__c11_atomic_store: 4429 case AtomicExpr::AO__opencl_atomic_store: 4430 case AtomicExpr::AO__atomic_store: 4431 case AtomicExpr::AO__atomic_store_n: 4432 Form = Copy; 4433 break; 4434 4435 case AtomicExpr::AO__c11_atomic_fetch_add: 4436 case AtomicExpr::AO__c11_atomic_fetch_sub: 4437 case AtomicExpr::AO__opencl_atomic_fetch_add: 4438 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4439 case AtomicExpr::AO__opencl_atomic_fetch_min: 4440 case AtomicExpr::AO__opencl_atomic_fetch_max: 4441 case AtomicExpr::AO__atomic_fetch_add: 4442 case AtomicExpr::AO__atomic_fetch_sub: 4443 case AtomicExpr::AO__atomic_add_fetch: 4444 case AtomicExpr::AO__atomic_sub_fetch: 4445 IsAddSub = true; 4446 LLVM_FALLTHROUGH; 4447 case AtomicExpr::AO__c11_atomic_fetch_and: 4448 case AtomicExpr::AO__c11_atomic_fetch_or: 4449 case AtomicExpr::AO__c11_atomic_fetch_xor: 4450 case AtomicExpr::AO__opencl_atomic_fetch_and: 4451 case AtomicExpr::AO__opencl_atomic_fetch_or: 4452 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4453 case AtomicExpr::AO__atomic_fetch_and: 4454 case AtomicExpr::AO__atomic_fetch_or: 4455 case AtomicExpr::AO__atomic_fetch_xor: 4456 case AtomicExpr::AO__atomic_fetch_nand: 4457 case AtomicExpr::AO__atomic_and_fetch: 4458 case AtomicExpr::AO__atomic_or_fetch: 4459 case AtomicExpr::AO__atomic_xor_fetch: 4460 case AtomicExpr::AO__atomic_nand_fetch: 4461 Form = Arithmetic; 4462 break; 4463 4464 case AtomicExpr::AO__atomic_fetch_min: 4465 case AtomicExpr::AO__atomic_fetch_max: 4466 IsMinMax = true; 4467 Form = Arithmetic; 4468 break; 4469 4470 case AtomicExpr::AO__c11_atomic_exchange: 4471 case AtomicExpr::AO__opencl_atomic_exchange: 4472 case AtomicExpr::AO__atomic_exchange_n: 4473 Form = Xchg; 4474 break; 4475 4476 case AtomicExpr::AO__atomic_exchange: 4477 Form = GNUXchg; 4478 break; 4479 4480 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4481 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4482 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4483 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4484 Form = C11CmpXchg; 4485 break; 4486 4487 case AtomicExpr::AO__atomic_compare_exchange: 4488 case AtomicExpr::AO__atomic_compare_exchange_n: 4489 Form = GNUCmpXchg; 4490 break; 4491 } 4492 4493 unsigned AdjustedNumArgs = NumArgs[Form]; 4494 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4495 ++AdjustedNumArgs; 4496 // Check we have the right number of arguments. 4497 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4498 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4499 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4500 << TheCall->getCallee()->getSourceRange(); 4501 return ExprError(); 4502 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4503 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4504 diag::err_typecheck_call_too_many_args) 4505 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4506 << TheCall->getCallee()->getSourceRange(); 4507 return ExprError(); 4508 } 4509 4510 // Inspect the first argument of the atomic operation. 4511 Expr *Ptr = TheCall->getArg(0); 4512 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4513 if (ConvertedPtr.isInvalid()) 4514 return ExprError(); 4515 4516 Ptr = ConvertedPtr.get(); 4517 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4518 if (!pointerType) { 4519 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4520 << Ptr->getType() << Ptr->getSourceRange(); 4521 return ExprError(); 4522 } 4523 4524 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4525 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4526 QualType ValType = AtomTy; // 'C' 4527 if (IsC11) { 4528 if (!AtomTy->isAtomicType()) { 4529 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4530 << Ptr->getType() << Ptr->getSourceRange(); 4531 return ExprError(); 4532 } 4533 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4534 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4535 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4536 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4537 << Ptr->getSourceRange(); 4538 return ExprError(); 4539 } 4540 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4541 } else if (Form != Load && Form != LoadCopy) { 4542 if (ValType.isConstQualified()) { 4543 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4544 << Ptr->getType() << Ptr->getSourceRange(); 4545 return ExprError(); 4546 } 4547 } 4548 4549 // For an arithmetic operation, the implied arithmetic must be well-formed. 4550 if (Form == Arithmetic) { 4551 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4552 if (IsAddSub && !ValType->isIntegerType() 4553 && !ValType->isPointerType()) { 4554 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4555 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4556 return ExprError(); 4557 } 4558 if (IsMinMax) { 4559 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4560 if (!BT || (BT->getKind() != BuiltinType::Int && 4561 BT->getKind() != BuiltinType::UInt)) { 4562 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4563 return ExprError(); 4564 } 4565 } 4566 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4567 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4568 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4569 return ExprError(); 4570 } 4571 if (IsC11 && ValType->isPointerType() && 4572 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4573 diag::err_incomplete_type)) { 4574 return ExprError(); 4575 } 4576 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4577 // For __atomic_*_n operations, the value type must be a scalar integral or 4578 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4579 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4580 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4581 return ExprError(); 4582 } 4583 4584 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4585 !AtomTy->isScalarType()) { 4586 // For GNU atomics, require a trivially-copyable type. This is not part of 4587 // the GNU atomics specification, but we enforce it for sanity. 4588 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4589 << Ptr->getType() << Ptr->getSourceRange(); 4590 return ExprError(); 4591 } 4592 4593 switch (ValType.getObjCLifetime()) { 4594 case Qualifiers::OCL_None: 4595 case Qualifiers::OCL_ExplicitNone: 4596 // okay 4597 break; 4598 4599 case Qualifiers::OCL_Weak: 4600 case Qualifiers::OCL_Strong: 4601 case Qualifiers::OCL_Autoreleasing: 4602 // FIXME: Can this happen? By this point, ValType should be known 4603 // to be trivially copyable. 4604 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4605 << ValType << Ptr->getSourceRange(); 4606 return ExprError(); 4607 } 4608 4609 // All atomic operations have an overload which takes a pointer to a volatile 4610 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4611 // into the result or the other operands. Similarly atomic_load takes a 4612 // pointer to a const 'A'. 4613 ValType.removeLocalVolatile(); 4614 ValType.removeLocalConst(); 4615 QualType ResultType = ValType; 4616 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4617 Form == Init) 4618 ResultType = Context.VoidTy; 4619 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4620 ResultType = Context.BoolTy; 4621 4622 // The type of a parameter passed 'by value'. In the GNU atomics, such 4623 // arguments are actually passed as pointers. 4624 QualType ByValType = ValType; // 'CP' 4625 bool IsPassedByAddress = false; 4626 if (!IsC11 && !IsN) { 4627 ByValType = Ptr->getType(); 4628 IsPassedByAddress = true; 4629 } 4630 4631 // The first argument's non-CV pointer type is used to deduce the type of 4632 // subsequent arguments, except for: 4633 // - weak flag (always converted to bool) 4634 // - memory order (always converted to int) 4635 // - scope (always converted to int) 4636 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4637 QualType Ty; 4638 if (i < NumVals[Form] + 1) { 4639 switch (i) { 4640 case 0: 4641 // The first argument is always a pointer. It has a fixed type. 4642 // It is always dereferenced, a nullptr is undefined. 4643 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4644 // Nothing else to do: we already know all we want about this pointer. 4645 continue; 4646 case 1: 4647 // The second argument is the non-atomic operand. For arithmetic, this 4648 // is always passed by value, and for a compare_exchange it is always 4649 // passed by address. For the rest, GNU uses by-address and C11 uses 4650 // by-value. 4651 assert(Form != Load); 4652 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4653 Ty = ValType; 4654 else if (Form == Copy || Form == Xchg) { 4655 if (IsPassedByAddress) 4656 // The value pointer is always dereferenced, a nullptr is undefined. 4657 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4658 Ty = ByValType; 4659 } else if (Form == Arithmetic) 4660 Ty = Context.getPointerDiffType(); 4661 else { 4662 Expr *ValArg = TheCall->getArg(i); 4663 // The value pointer is always dereferenced, a nullptr is undefined. 4664 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4665 LangAS AS = LangAS::Default; 4666 // Keep address space of non-atomic pointer type. 4667 if (const PointerType *PtrTy = 4668 ValArg->getType()->getAs<PointerType>()) { 4669 AS = PtrTy->getPointeeType().getAddressSpace(); 4670 } 4671 Ty = Context.getPointerType( 4672 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4673 } 4674 break; 4675 case 2: 4676 // The third argument to compare_exchange / GNU exchange is the desired 4677 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4678 if (IsPassedByAddress) 4679 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4680 Ty = ByValType; 4681 break; 4682 case 3: 4683 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4684 Ty = Context.BoolTy; 4685 break; 4686 } 4687 } else { 4688 // The order(s) and scope are always converted to int. 4689 Ty = Context.IntTy; 4690 } 4691 4692 InitializedEntity Entity = 4693 InitializedEntity::InitializeParameter(Context, Ty, false); 4694 ExprResult Arg = TheCall->getArg(i); 4695 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4696 if (Arg.isInvalid()) 4697 return true; 4698 TheCall->setArg(i, Arg.get()); 4699 } 4700 4701 // Permute the arguments into a 'consistent' order. 4702 SmallVector<Expr*, 5> SubExprs; 4703 SubExprs.push_back(Ptr); 4704 switch (Form) { 4705 case Init: 4706 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4707 SubExprs.push_back(TheCall->getArg(1)); // Val1 4708 break; 4709 case Load: 4710 SubExprs.push_back(TheCall->getArg(1)); // Order 4711 break; 4712 case LoadCopy: 4713 case Copy: 4714 case Arithmetic: 4715 case Xchg: 4716 SubExprs.push_back(TheCall->getArg(2)); // Order 4717 SubExprs.push_back(TheCall->getArg(1)); // Val1 4718 break; 4719 case GNUXchg: 4720 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4721 SubExprs.push_back(TheCall->getArg(3)); // Order 4722 SubExprs.push_back(TheCall->getArg(1)); // Val1 4723 SubExprs.push_back(TheCall->getArg(2)); // Val2 4724 break; 4725 case C11CmpXchg: 4726 SubExprs.push_back(TheCall->getArg(3)); // Order 4727 SubExprs.push_back(TheCall->getArg(1)); // Val1 4728 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4729 SubExprs.push_back(TheCall->getArg(2)); // Val2 4730 break; 4731 case GNUCmpXchg: 4732 SubExprs.push_back(TheCall->getArg(4)); // Order 4733 SubExprs.push_back(TheCall->getArg(1)); // Val1 4734 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4735 SubExprs.push_back(TheCall->getArg(2)); // Val2 4736 SubExprs.push_back(TheCall->getArg(3)); // Weak 4737 break; 4738 } 4739 4740 if (SubExprs.size() >= 2 && Form != Init) { 4741 llvm::APSInt Result(32); 4742 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4743 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4744 Diag(SubExprs[1]->getBeginLoc(), 4745 diag::warn_atomic_op_has_invalid_memory_order) 4746 << SubExprs[1]->getSourceRange(); 4747 } 4748 4749 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4750 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4751 llvm::APSInt Result(32); 4752 if (Scope->isIntegerConstantExpr(Result, Context) && 4753 !ScopeModel->isValid(Result.getZExtValue())) { 4754 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4755 << Scope->getSourceRange(); 4756 } 4757 SubExprs.push_back(Scope); 4758 } 4759 4760 AtomicExpr *AE = 4761 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4762 ResultType, Op, TheCall->getRParenLoc()); 4763 4764 if ((Op == AtomicExpr::AO__c11_atomic_load || 4765 Op == AtomicExpr::AO__c11_atomic_store || 4766 Op == AtomicExpr::AO__opencl_atomic_load || 4767 Op == AtomicExpr::AO__opencl_atomic_store ) && 4768 Context.AtomicUsesUnsupportedLibcall(AE)) 4769 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4770 << ((Op == AtomicExpr::AO__c11_atomic_load || 4771 Op == AtomicExpr::AO__opencl_atomic_load) 4772 ? 0 4773 : 1); 4774 4775 return AE; 4776 } 4777 4778 /// checkBuiltinArgument - Given a call to a builtin function, perform 4779 /// normal type-checking on the given argument, updating the call in 4780 /// place. This is useful when a builtin function requires custom 4781 /// type-checking for some of its arguments but not necessarily all of 4782 /// them. 4783 /// 4784 /// Returns true on error. 4785 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4786 FunctionDecl *Fn = E->getDirectCallee(); 4787 assert(Fn && "builtin call without direct callee!"); 4788 4789 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4790 InitializedEntity Entity = 4791 InitializedEntity::InitializeParameter(S.Context, Param); 4792 4793 ExprResult Arg = E->getArg(0); 4794 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4795 if (Arg.isInvalid()) 4796 return true; 4797 4798 E->setArg(ArgIndex, Arg.get()); 4799 return false; 4800 } 4801 4802 /// We have a call to a function like __sync_fetch_and_add, which is an 4803 /// overloaded function based on the pointer type of its first argument. 4804 /// The main ActOnCallExpr routines have already promoted the types of 4805 /// arguments because all of these calls are prototyped as void(...). 4806 /// 4807 /// This function goes through and does final semantic checking for these 4808 /// builtins, as well as generating any warnings. 4809 ExprResult 4810 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4811 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4812 Expr *Callee = TheCall->getCallee(); 4813 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4814 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4815 4816 // Ensure that we have at least one argument to do type inference from. 4817 if (TheCall->getNumArgs() < 1) { 4818 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4819 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4820 return ExprError(); 4821 } 4822 4823 // Inspect the first argument of the atomic builtin. This should always be 4824 // a pointer type, whose element is an integral scalar or pointer type. 4825 // Because it is a pointer type, we don't have to worry about any implicit 4826 // casts here. 4827 // FIXME: We don't allow floating point scalars as input. 4828 Expr *FirstArg = TheCall->getArg(0); 4829 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4830 if (FirstArgResult.isInvalid()) 4831 return ExprError(); 4832 FirstArg = FirstArgResult.get(); 4833 TheCall->setArg(0, FirstArg); 4834 4835 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4836 if (!pointerType) { 4837 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4838 << FirstArg->getType() << FirstArg->getSourceRange(); 4839 return ExprError(); 4840 } 4841 4842 QualType ValType = pointerType->getPointeeType(); 4843 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4844 !ValType->isBlockPointerType()) { 4845 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4846 << FirstArg->getType() << FirstArg->getSourceRange(); 4847 return ExprError(); 4848 } 4849 4850 if (ValType.isConstQualified()) { 4851 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4852 << FirstArg->getType() << FirstArg->getSourceRange(); 4853 return ExprError(); 4854 } 4855 4856 switch (ValType.getObjCLifetime()) { 4857 case Qualifiers::OCL_None: 4858 case Qualifiers::OCL_ExplicitNone: 4859 // okay 4860 break; 4861 4862 case Qualifiers::OCL_Weak: 4863 case Qualifiers::OCL_Strong: 4864 case Qualifiers::OCL_Autoreleasing: 4865 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4866 << ValType << FirstArg->getSourceRange(); 4867 return ExprError(); 4868 } 4869 4870 // Strip any qualifiers off ValType. 4871 ValType = ValType.getUnqualifiedType(); 4872 4873 // The majority of builtins return a value, but a few have special return 4874 // types, so allow them to override appropriately below. 4875 QualType ResultType = ValType; 4876 4877 // We need to figure out which concrete builtin this maps onto. For example, 4878 // __sync_fetch_and_add with a 2 byte object turns into 4879 // __sync_fetch_and_add_2. 4880 #define BUILTIN_ROW(x) \ 4881 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4882 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4883 4884 static const unsigned BuiltinIndices[][5] = { 4885 BUILTIN_ROW(__sync_fetch_and_add), 4886 BUILTIN_ROW(__sync_fetch_and_sub), 4887 BUILTIN_ROW(__sync_fetch_and_or), 4888 BUILTIN_ROW(__sync_fetch_and_and), 4889 BUILTIN_ROW(__sync_fetch_and_xor), 4890 BUILTIN_ROW(__sync_fetch_and_nand), 4891 4892 BUILTIN_ROW(__sync_add_and_fetch), 4893 BUILTIN_ROW(__sync_sub_and_fetch), 4894 BUILTIN_ROW(__sync_and_and_fetch), 4895 BUILTIN_ROW(__sync_or_and_fetch), 4896 BUILTIN_ROW(__sync_xor_and_fetch), 4897 BUILTIN_ROW(__sync_nand_and_fetch), 4898 4899 BUILTIN_ROW(__sync_val_compare_and_swap), 4900 BUILTIN_ROW(__sync_bool_compare_and_swap), 4901 BUILTIN_ROW(__sync_lock_test_and_set), 4902 BUILTIN_ROW(__sync_lock_release), 4903 BUILTIN_ROW(__sync_swap) 4904 }; 4905 #undef BUILTIN_ROW 4906 4907 // Determine the index of the size. 4908 unsigned SizeIndex; 4909 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4910 case 1: SizeIndex = 0; break; 4911 case 2: SizeIndex = 1; break; 4912 case 4: SizeIndex = 2; break; 4913 case 8: SizeIndex = 3; break; 4914 case 16: SizeIndex = 4; break; 4915 default: 4916 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4917 << FirstArg->getType() << FirstArg->getSourceRange(); 4918 return ExprError(); 4919 } 4920 4921 // Each of these builtins has one pointer argument, followed by some number of 4922 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4923 // that we ignore. Find out which row of BuiltinIndices to read from as well 4924 // as the number of fixed args. 4925 unsigned BuiltinID = FDecl->getBuiltinID(); 4926 unsigned BuiltinIndex, NumFixed = 1; 4927 bool WarnAboutSemanticsChange = false; 4928 switch (BuiltinID) { 4929 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4930 case Builtin::BI__sync_fetch_and_add: 4931 case Builtin::BI__sync_fetch_and_add_1: 4932 case Builtin::BI__sync_fetch_and_add_2: 4933 case Builtin::BI__sync_fetch_and_add_4: 4934 case Builtin::BI__sync_fetch_and_add_8: 4935 case Builtin::BI__sync_fetch_and_add_16: 4936 BuiltinIndex = 0; 4937 break; 4938 4939 case Builtin::BI__sync_fetch_and_sub: 4940 case Builtin::BI__sync_fetch_and_sub_1: 4941 case Builtin::BI__sync_fetch_and_sub_2: 4942 case Builtin::BI__sync_fetch_and_sub_4: 4943 case Builtin::BI__sync_fetch_and_sub_8: 4944 case Builtin::BI__sync_fetch_and_sub_16: 4945 BuiltinIndex = 1; 4946 break; 4947 4948 case Builtin::BI__sync_fetch_and_or: 4949 case Builtin::BI__sync_fetch_and_or_1: 4950 case Builtin::BI__sync_fetch_and_or_2: 4951 case Builtin::BI__sync_fetch_and_or_4: 4952 case Builtin::BI__sync_fetch_and_or_8: 4953 case Builtin::BI__sync_fetch_and_or_16: 4954 BuiltinIndex = 2; 4955 break; 4956 4957 case Builtin::BI__sync_fetch_and_and: 4958 case Builtin::BI__sync_fetch_and_and_1: 4959 case Builtin::BI__sync_fetch_and_and_2: 4960 case Builtin::BI__sync_fetch_and_and_4: 4961 case Builtin::BI__sync_fetch_and_and_8: 4962 case Builtin::BI__sync_fetch_and_and_16: 4963 BuiltinIndex = 3; 4964 break; 4965 4966 case Builtin::BI__sync_fetch_and_xor: 4967 case Builtin::BI__sync_fetch_and_xor_1: 4968 case Builtin::BI__sync_fetch_and_xor_2: 4969 case Builtin::BI__sync_fetch_and_xor_4: 4970 case Builtin::BI__sync_fetch_and_xor_8: 4971 case Builtin::BI__sync_fetch_and_xor_16: 4972 BuiltinIndex = 4; 4973 break; 4974 4975 case Builtin::BI__sync_fetch_and_nand: 4976 case Builtin::BI__sync_fetch_and_nand_1: 4977 case Builtin::BI__sync_fetch_and_nand_2: 4978 case Builtin::BI__sync_fetch_and_nand_4: 4979 case Builtin::BI__sync_fetch_and_nand_8: 4980 case Builtin::BI__sync_fetch_and_nand_16: 4981 BuiltinIndex = 5; 4982 WarnAboutSemanticsChange = true; 4983 break; 4984 4985 case Builtin::BI__sync_add_and_fetch: 4986 case Builtin::BI__sync_add_and_fetch_1: 4987 case Builtin::BI__sync_add_and_fetch_2: 4988 case Builtin::BI__sync_add_and_fetch_4: 4989 case Builtin::BI__sync_add_and_fetch_8: 4990 case Builtin::BI__sync_add_and_fetch_16: 4991 BuiltinIndex = 6; 4992 break; 4993 4994 case Builtin::BI__sync_sub_and_fetch: 4995 case Builtin::BI__sync_sub_and_fetch_1: 4996 case Builtin::BI__sync_sub_and_fetch_2: 4997 case Builtin::BI__sync_sub_and_fetch_4: 4998 case Builtin::BI__sync_sub_and_fetch_8: 4999 case Builtin::BI__sync_sub_and_fetch_16: 5000 BuiltinIndex = 7; 5001 break; 5002 5003 case Builtin::BI__sync_and_and_fetch: 5004 case Builtin::BI__sync_and_and_fetch_1: 5005 case Builtin::BI__sync_and_and_fetch_2: 5006 case Builtin::BI__sync_and_and_fetch_4: 5007 case Builtin::BI__sync_and_and_fetch_8: 5008 case Builtin::BI__sync_and_and_fetch_16: 5009 BuiltinIndex = 8; 5010 break; 5011 5012 case Builtin::BI__sync_or_and_fetch: 5013 case Builtin::BI__sync_or_and_fetch_1: 5014 case Builtin::BI__sync_or_and_fetch_2: 5015 case Builtin::BI__sync_or_and_fetch_4: 5016 case Builtin::BI__sync_or_and_fetch_8: 5017 case Builtin::BI__sync_or_and_fetch_16: 5018 BuiltinIndex = 9; 5019 break; 5020 5021 case Builtin::BI__sync_xor_and_fetch: 5022 case Builtin::BI__sync_xor_and_fetch_1: 5023 case Builtin::BI__sync_xor_and_fetch_2: 5024 case Builtin::BI__sync_xor_and_fetch_4: 5025 case Builtin::BI__sync_xor_and_fetch_8: 5026 case Builtin::BI__sync_xor_and_fetch_16: 5027 BuiltinIndex = 10; 5028 break; 5029 5030 case Builtin::BI__sync_nand_and_fetch: 5031 case Builtin::BI__sync_nand_and_fetch_1: 5032 case Builtin::BI__sync_nand_and_fetch_2: 5033 case Builtin::BI__sync_nand_and_fetch_4: 5034 case Builtin::BI__sync_nand_and_fetch_8: 5035 case Builtin::BI__sync_nand_and_fetch_16: 5036 BuiltinIndex = 11; 5037 WarnAboutSemanticsChange = true; 5038 break; 5039 5040 case Builtin::BI__sync_val_compare_and_swap: 5041 case Builtin::BI__sync_val_compare_and_swap_1: 5042 case Builtin::BI__sync_val_compare_and_swap_2: 5043 case Builtin::BI__sync_val_compare_and_swap_4: 5044 case Builtin::BI__sync_val_compare_and_swap_8: 5045 case Builtin::BI__sync_val_compare_and_swap_16: 5046 BuiltinIndex = 12; 5047 NumFixed = 2; 5048 break; 5049 5050 case Builtin::BI__sync_bool_compare_and_swap: 5051 case Builtin::BI__sync_bool_compare_and_swap_1: 5052 case Builtin::BI__sync_bool_compare_and_swap_2: 5053 case Builtin::BI__sync_bool_compare_and_swap_4: 5054 case Builtin::BI__sync_bool_compare_and_swap_8: 5055 case Builtin::BI__sync_bool_compare_and_swap_16: 5056 BuiltinIndex = 13; 5057 NumFixed = 2; 5058 ResultType = Context.BoolTy; 5059 break; 5060 5061 case Builtin::BI__sync_lock_test_and_set: 5062 case Builtin::BI__sync_lock_test_and_set_1: 5063 case Builtin::BI__sync_lock_test_and_set_2: 5064 case Builtin::BI__sync_lock_test_and_set_4: 5065 case Builtin::BI__sync_lock_test_and_set_8: 5066 case Builtin::BI__sync_lock_test_and_set_16: 5067 BuiltinIndex = 14; 5068 break; 5069 5070 case Builtin::BI__sync_lock_release: 5071 case Builtin::BI__sync_lock_release_1: 5072 case Builtin::BI__sync_lock_release_2: 5073 case Builtin::BI__sync_lock_release_4: 5074 case Builtin::BI__sync_lock_release_8: 5075 case Builtin::BI__sync_lock_release_16: 5076 BuiltinIndex = 15; 5077 NumFixed = 0; 5078 ResultType = Context.VoidTy; 5079 break; 5080 5081 case Builtin::BI__sync_swap: 5082 case Builtin::BI__sync_swap_1: 5083 case Builtin::BI__sync_swap_2: 5084 case Builtin::BI__sync_swap_4: 5085 case Builtin::BI__sync_swap_8: 5086 case Builtin::BI__sync_swap_16: 5087 BuiltinIndex = 16; 5088 break; 5089 } 5090 5091 // Now that we know how many fixed arguments we expect, first check that we 5092 // have at least that many. 5093 if (TheCall->getNumArgs() < 1+NumFixed) { 5094 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5095 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5096 << Callee->getSourceRange(); 5097 return ExprError(); 5098 } 5099 5100 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5101 << Callee->getSourceRange(); 5102 5103 if (WarnAboutSemanticsChange) { 5104 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5105 << Callee->getSourceRange(); 5106 } 5107 5108 // Get the decl for the concrete builtin from this, we can tell what the 5109 // concrete integer type we should convert to is. 5110 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5111 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5112 FunctionDecl *NewBuiltinDecl; 5113 if (NewBuiltinID == BuiltinID) 5114 NewBuiltinDecl = FDecl; 5115 else { 5116 // Perform builtin lookup to avoid redeclaring it. 5117 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5118 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5119 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5120 assert(Res.getFoundDecl()); 5121 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5122 if (!NewBuiltinDecl) 5123 return ExprError(); 5124 } 5125 5126 // The first argument --- the pointer --- has a fixed type; we 5127 // deduce the types of the rest of the arguments accordingly. Walk 5128 // the remaining arguments, converting them to the deduced value type. 5129 for (unsigned i = 0; i != NumFixed; ++i) { 5130 ExprResult Arg = TheCall->getArg(i+1); 5131 5132 // GCC does an implicit conversion to the pointer or integer ValType. This 5133 // can fail in some cases (1i -> int**), check for this error case now. 5134 // Initialize the argument. 5135 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5136 ValType, /*consume*/ false); 5137 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5138 if (Arg.isInvalid()) 5139 return ExprError(); 5140 5141 // Okay, we have something that *can* be converted to the right type. Check 5142 // to see if there is a potentially weird extension going on here. This can 5143 // happen when you do an atomic operation on something like an char* and 5144 // pass in 42. The 42 gets converted to char. This is even more strange 5145 // for things like 45.123 -> char, etc. 5146 // FIXME: Do this check. 5147 TheCall->setArg(i+1, Arg.get()); 5148 } 5149 5150 // Create a new DeclRefExpr to refer to the new decl. 5151 DeclRefExpr* NewDRE = DeclRefExpr::Create( 5152 Context, 5153 DRE->getQualifierLoc(), 5154 SourceLocation(), 5155 NewBuiltinDecl, 5156 /*enclosing*/ false, 5157 DRE->getLocation(), 5158 Context.BuiltinFnTy, 5159 DRE->getValueKind()); 5160 5161 // Set the callee in the CallExpr. 5162 // FIXME: This loses syntactic information. 5163 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5164 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5165 CK_BuiltinFnToFnPtr); 5166 TheCall->setCallee(PromotedCall.get()); 5167 5168 // Change the result type of the call to match the original value type. This 5169 // is arbitrary, but the codegen for these builtins ins design to handle it 5170 // gracefully. 5171 TheCall->setType(ResultType); 5172 5173 return TheCallResult; 5174 } 5175 5176 /// SemaBuiltinNontemporalOverloaded - We have a call to 5177 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5178 /// overloaded function based on the pointer type of its last argument. 5179 /// 5180 /// This function goes through and does final semantic checking for these 5181 /// builtins. 5182 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5183 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5184 DeclRefExpr *DRE = 5185 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5186 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5187 unsigned BuiltinID = FDecl->getBuiltinID(); 5188 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5189 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5190 "Unexpected nontemporal load/store builtin!"); 5191 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5192 unsigned numArgs = isStore ? 2 : 1; 5193 5194 // Ensure that we have the proper number of arguments. 5195 if (checkArgCount(*this, TheCall, numArgs)) 5196 return ExprError(); 5197 5198 // Inspect the last argument of the nontemporal builtin. This should always 5199 // be a pointer type, from which we imply the type of the memory access. 5200 // Because it is a pointer type, we don't have to worry about any implicit 5201 // casts here. 5202 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5203 ExprResult PointerArgResult = 5204 DefaultFunctionArrayLvalueConversion(PointerArg); 5205 5206 if (PointerArgResult.isInvalid()) 5207 return ExprError(); 5208 PointerArg = PointerArgResult.get(); 5209 TheCall->setArg(numArgs - 1, PointerArg); 5210 5211 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5212 if (!pointerType) { 5213 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5214 << PointerArg->getType() << PointerArg->getSourceRange(); 5215 return ExprError(); 5216 } 5217 5218 QualType ValType = pointerType->getPointeeType(); 5219 5220 // Strip any qualifiers off ValType. 5221 ValType = ValType.getUnqualifiedType(); 5222 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5223 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5224 !ValType->isVectorType()) { 5225 Diag(DRE->getBeginLoc(), 5226 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5227 << PointerArg->getType() << PointerArg->getSourceRange(); 5228 return ExprError(); 5229 } 5230 5231 if (!isStore) { 5232 TheCall->setType(ValType); 5233 return TheCallResult; 5234 } 5235 5236 ExprResult ValArg = TheCall->getArg(0); 5237 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5238 Context, ValType, /*consume*/ false); 5239 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5240 if (ValArg.isInvalid()) 5241 return ExprError(); 5242 5243 TheCall->setArg(0, ValArg.get()); 5244 TheCall->setType(Context.VoidTy); 5245 return TheCallResult; 5246 } 5247 5248 /// CheckObjCString - Checks that the argument to the builtin 5249 /// CFString constructor is correct 5250 /// Note: It might also make sense to do the UTF-16 conversion here (would 5251 /// simplify the backend). 5252 bool Sema::CheckObjCString(Expr *Arg) { 5253 Arg = Arg->IgnoreParenCasts(); 5254 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5255 5256 if (!Literal || !Literal->isAscii()) { 5257 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5258 << Arg->getSourceRange(); 5259 return true; 5260 } 5261 5262 if (Literal->containsNonAsciiOrNull()) { 5263 StringRef String = Literal->getString(); 5264 unsigned NumBytes = String.size(); 5265 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5266 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5267 llvm::UTF16 *ToPtr = &ToBuf[0]; 5268 5269 llvm::ConversionResult Result = 5270 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5271 ToPtr + NumBytes, llvm::strictConversion); 5272 // Check for conversion failure. 5273 if (Result != llvm::conversionOK) 5274 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5275 << Arg->getSourceRange(); 5276 } 5277 return false; 5278 } 5279 5280 /// CheckObjCString - Checks that the format string argument to the os_log() 5281 /// and os_trace() functions is correct, and converts it to const char *. 5282 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5283 Arg = Arg->IgnoreParenCasts(); 5284 auto *Literal = dyn_cast<StringLiteral>(Arg); 5285 if (!Literal) { 5286 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5287 Literal = ObjcLiteral->getString(); 5288 } 5289 } 5290 5291 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5292 return ExprError( 5293 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5294 << Arg->getSourceRange()); 5295 } 5296 5297 ExprResult Result(Literal); 5298 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5299 InitializedEntity Entity = 5300 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5301 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5302 return Result; 5303 } 5304 5305 /// Check that the user is calling the appropriate va_start builtin for the 5306 /// target and calling convention. 5307 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5308 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5309 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5310 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5311 bool IsWindows = TT.isOSWindows(); 5312 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5313 if (IsX64 || IsAArch64) { 5314 CallingConv CC = CC_C; 5315 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5316 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5317 if (IsMSVAStart) { 5318 // Don't allow this in System V ABI functions. 5319 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5320 return S.Diag(Fn->getBeginLoc(), 5321 diag::err_ms_va_start_used_in_sysv_function); 5322 } else { 5323 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5324 // On x64 Windows, don't allow this in System V ABI functions. 5325 // (Yes, that means there's no corresponding way to support variadic 5326 // System V ABI functions on Windows.) 5327 if ((IsWindows && CC == CC_X86_64SysV) || 5328 (!IsWindows && CC == CC_Win64)) 5329 return S.Diag(Fn->getBeginLoc(), 5330 diag::err_va_start_used_in_wrong_abi_function) 5331 << !IsWindows; 5332 } 5333 return false; 5334 } 5335 5336 if (IsMSVAStart) 5337 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5338 return false; 5339 } 5340 5341 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5342 ParmVarDecl **LastParam = nullptr) { 5343 // Determine whether the current function, block, or obj-c method is variadic 5344 // and get its parameter list. 5345 bool IsVariadic = false; 5346 ArrayRef<ParmVarDecl *> Params; 5347 DeclContext *Caller = S.CurContext; 5348 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5349 IsVariadic = Block->isVariadic(); 5350 Params = Block->parameters(); 5351 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5352 IsVariadic = FD->isVariadic(); 5353 Params = FD->parameters(); 5354 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5355 IsVariadic = MD->isVariadic(); 5356 // FIXME: This isn't correct for methods (results in bogus warning). 5357 Params = MD->parameters(); 5358 } else if (isa<CapturedDecl>(Caller)) { 5359 // We don't support va_start in a CapturedDecl. 5360 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5361 return true; 5362 } else { 5363 // This must be some other declcontext that parses exprs. 5364 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5365 return true; 5366 } 5367 5368 if (!IsVariadic) { 5369 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5370 return true; 5371 } 5372 5373 if (LastParam) 5374 *LastParam = Params.empty() ? nullptr : Params.back(); 5375 5376 return false; 5377 } 5378 5379 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5380 /// for validity. Emit an error and return true on failure; return false 5381 /// on success. 5382 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5383 Expr *Fn = TheCall->getCallee(); 5384 5385 if (checkVAStartABI(*this, BuiltinID, Fn)) 5386 return true; 5387 5388 if (TheCall->getNumArgs() > 2) { 5389 Diag(TheCall->getArg(2)->getBeginLoc(), 5390 diag::err_typecheck_call_too_many_args) 5391 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5392 << Fn->getSourceRange() 5393 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5394 (*(TheCall->arg_end() - 1))->getEndLoc()); 5395 return true; 5396 } 5397 5398 if (TheCall->getNumArgs() < 2) { 5399 return Diag(TheCall->getEndLoc(), 5400 diag::err_typecheck_call_too_few_args_at_least) 5401 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5402 } 5403 5404 // Type-check the first argument normally. 5405 if (checkBuiltinArgument(*this, TheCall, 0)) 5406 return true; 5407 5408 // Check that the current function is variadic, and get its last parameter. 5409 ParmVarDecl *LastParam; 5410 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5411 return true; 5412 5413 // Verify that the second argument to the builtin is the last argument of the 5414 // current function or method. 5415 bool SecondArgIsLastNamedArgument = false; 5416 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5417 5418 // These are valid if SecondArgIsLastNamedArgument is false after the next 5419 // block. 5420 QualType Type; 5421 SourceLocation ParamLoc; 5422 bool IsCRegister = false; 5423 5424 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5425 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5426 SecondArgIsLastNamedArgument = PV == LastParam; 5427 5428 Type = PV->getType(); 5429 ParamLoc = PV->getLocation(); 5430 IsCRegister = 5431 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5432 } 5433 } 5434 5435 if (!SecondArgIsLastNamedArgument) 5436 Diag(TheCall->getArg(1)->getBeginLoc(), 5437 diag::warn_second_arg_of_va_start_not_last_named_param); 5438 else if (IsCRegister || Type->isReferenceType() || 5439 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5440 // Promotable integers are UB, but enumerations need a bit of 5441 // extra checking to see what their promotable type actually is. 5442 if (!Type->isPromotableIntegerType()) 5443 return false; 5444 if (!Type->isEnumeralType()) 5445 return true; 5446 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5447 return !(ED && 5448 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5449 }()) { 5450 unsigned Reason = 0; 5451 if (Type->isReferenceType()) Reason = 1; 5452 else if (IsCRegister) Reason = 2; 5453 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5454 Diag(ParamLoc, diag::note_parameter_type) << Type; 5455 } 5456 5457 TheCall->setType(Context.VoidTy); 5458 return false; 5459 } 5460 5461 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5462 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5463 // const char *named_addr); 5464 5465 Expr *Func = Call->getCallee(); 5466 5467 if (Call->getNumArgs() < 3) 5468 return Diag(Call->getEndLoc(), 5469 diag::err_typecheck_call_too_few_args_at_least) 5470 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5471 5472 // Type-check the first argument normally. 5473 if (checkBuiltinArgument(*this, Call, 0)) 5474 return true; 5475 5476 // Check that the current function is variadic. 5477 if (checkVAStartIsInVariadicFunction(*this, Func)) 5478 return true; 5479 5480 // __va_start on Windows does not validate the parameter qualifiers 5481 5482 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5483 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5484 5485 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5486 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5487 5488 const QualType &ConstCharPtrTy = 5489 Context.getPointerType(Context.CharTy.withConst()); 5490 if (!Arg1Ty->isPointerType() || 5491 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5492 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5493 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5494 << 0 /* qualifier difference */ 5495 << 3 /* parameter mismatch */ 5496 << 2 << Arg1->getType() << ConstCharPtrTy; 5497 5498 const QualType SizeTy = Context.getSizeType(); 5499 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5500 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5501 << Arg2->getType() << SizeTy << 1 /* different class */ 5502 << 0 /* qualifier difference */ 5503 << 3 /* parameter mismatch */ 5504 << 3 << Arg2->getType() << SizeTy; 5505 5506 return false; 5507 } 5508 5509 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5510 /// friends. This is declared to take (...), so we have to check everything. 5511 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5512 if (TheCall->getNumArgs() < 2) 5513 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5514 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5515 if (TheCall->getNumArgs() > 2) 5516 return Diag(TheCall->getArg(2)->getBeginLoc(), 5517 diag::err_typecheck_call_too_many_args) 5518 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5519 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5520 (*(TheCall->arg_end() - 1))->getEndLoc()); 5521 5522 ExprResult OrigArg0 = TheCall->getArg(0); 5523 ExprResult OrigArg1 = TheCall->getArg(1); 5524 5525 // Do standard promotions between the two arguments, returning their common 5526 // type. 5527 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5528 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5529 return true; 5530 5531 // Make sure any conversions are pushed back into the call; this is 5532 // type safe since unordered compare builtins are declared as "_Bool 5533 // foo(...)". 5534 TheCall->setArg(0, OrigArg0.get()); 5535 TheCall->setArg(1, OrigArg1.get()); 5536 5537 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5538 return false; 5539 5540 // If the common type isn't a real floating type, then the arguments were 5541 // invalid for this operation. 5542 if (Res.isNull() || !Res->isRealFloatingType()) 5543 return Diag(OrigArg0.get()->getBeginLoc(), 5544 diag::err_typecheck_call_invalid_ordered_compare) 5545 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5546 << SourceRange(OrigArg0.get()->getBeginLoc(), 5547 OrigArg1.get()->getEndLoc()); 5548 5549 return false; 5550 } 5551 5552 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5553 /// __builtin_isnan and friends. This is declared to take (...), so we have 5554 /// to check everything. We expect the last argument to be a floating point 5555 /// value. 5556 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5557 if (TheCall->getNumArgs() < NumArgs) 5558 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5559 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5560 if (TheCall->getNumArgs() > NumArgs) 5561 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5562 diag::err_typecheck_call_too_many_args) 5563 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5564 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5565 (*(TheCall->arg_end() - 1))->getEndLoc()); 5566 5567 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5568 5569 if (OrigArg->isTypeDependent()) 5570 return false; 5571 5572 // This operation requires a non-_Complex floating-point number. 5573 if (!OrigArg->getType()->isRealFloatingType()) 5574 return Diag(OrigArg->getBeginLoc(), 5575 diag::err_typecheck_call_invalid_unary_fp) 5576 << OrigArg->getType() << OrigArg->getSourceRange(); 5577 5578 // If this is an implicit conversion from float -> float, double, or 5579 // long double, remove it. 5580 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5581 // Only remove standard FloatCasts, leaving other casts inplace 5582 if (Cast->getCastKind() == CK_FloatingCast) { 5583 Expr *CastArg = Cast->getSubExpr(); 5584 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5585 assert( 5586 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5587 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5588 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5589 "promotion from float to either float, double, or long double is " 5590 "the only expected cast here"); 5591 Cast->setSubExpr(nullptr); 5592 TheCall->setArg(NumArgs-1, CastArg); 5593 } 5594 } 5595 } 5596 5597 return false; 5598 } 5599 5600 // Customized Sema Checking for VSX builtins that have the following signature: 5601 // vector [...] builtinName(vector [...], vector [...], const int); 5602 // Which takes the same type of vectors (any legal vector type) for the first 5603 // two arguments and takes compile time constant for the third argument. 5604 // Example builtins are : 5605 // vector double vec_xxpermdi(vector double, vector double, int); 5606 // vector short vec_xxsldwi(vector short, vector short, int); 5607 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5608 unsigned ExpectedNumArgs = 3; 5609 if (TheCall->getNumArgs() < ExpectedNumArgs) 5610 return Diag(TheCall->getEndLoc(), 5611 diag::err_typecheck_call_too_few_args_at_least) 5612 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5613 << TheCall->getSourceRange(); 5614 5615 if (TheCall->getNumArgs() > ExpectedNumArgs) 5616 return Diag(TheCall->getEndLoc(), 5617 diag::err_typecheck_call_too_many_args_at_most) 5618 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5619 << TheCall->getSourceRange(); 5620 5621 // Check the third argument is a compile time constant 5622 llvm::APSInt Value; 5623 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5624 return Diag(TheCall->getBeginLoc(), 5625 diag::err_vsx_builtin_nonconstant_argument) 5626 << 3 /* argument index */ << TheCall->getDirectCallee() 5627 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5628 TheCall->getArg(2)->getEndLoc()); 5629 5630 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5631 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5632 5633 // Check the type of argument 1 and argument 2 are vectors. 5634 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5635 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5636 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5637 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5638 << TheCall->getDirectCallee() 5639 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5640 TheCall->getArg(1)->getEndLoc()); 5641 } 5642 5643 // Check the first two arguments are the same type. 5644 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5645 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5646 << TheCall->getDirectCallee() 5647 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5648 TheCall->getArg(1)->getEndLoc()); 5649 } 5650 5651 // When default clang type checking is turned off and the customized type 5652 // checking is used, the returning type of the function must be explicitly 5653 // set. Otherwise it is _Bool by default. 5654 TheCall->setType(Arg1Ty); 5655 5656 return false; 5657 } 5658 5659 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5660 // This is declared to take (...), so we have to check everything. 5661 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5662 if (TheCall->getNumArgs() < 2) 5663 return ExprError(Diag(TheCall->getEndLoc(), 5664 diag::err_typecheck_call_too_few_args_at_least) 5665 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5666 << TheCall->getSourceRange()); 5667 5668 // Determine which of the following types of shufflevector we're checking: 5669 // 1) unary, vector mask: (lhs, mask) 5670 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5671 QualType resType = TheCall->getArg(0)->getType(); 5672 unsigned numElements = 0; 5673 5674 if (!TheCall->getArg(0)->isTypeDependent() && 5675 !TheCall->getArg(1)->isTypeDependent()) { 5676 QualType LHSType = TheCall->getArg(0)->getType(); 5677 QualType RHSType = TheCall->getArg(1)->getType(); 5678 5679 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5680 return ExprError( 5681 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5682 << TheCall->getDirectCallee() 5683 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5684 TheCall->getArg(1)->getEndLoc())); 5685 5686 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5687 unsigned numResElements = TheCall->getNumArgs() - 2; 5688 5689 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5690 // with mask. If so, verify that RHS is an integer vector type with the 5691 // same number of elts as lhs. 5692 if (TheCall->getNumArgs() == 2) { 5693 if (!RHSType->hasIntegerRepresentation() || 5694 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5695 return ExprError(Diag(TheCall->getBeginLoc(), 5696 diag::err_vec_builtin_incompatible_vector) 5697 << TheCall->getDirectCallee() 5698 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5699 TheCall->getArg(1)->getEndLoc())); 5700 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5701 return ExprError(Diag(TheCall->getBeginLoc(), 5702 diag::err_vec_builtin_incompatible_vector) 5703 << TheCall->getDirectCallee() 5704 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5705 TheCall->getArg(1)->getEndLoc())); 5706 } else if (numElements != numResElements) { 5707 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5708 resType = Context.getVectorType(eltType, numResElements, 5709 VectorType::GenericVector); 5710 } 5711 } 5712 5713 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5714 if (TheCall->getArg(i)->isTypeDependent() || 5715 TheCall->getArg(i)->isValueDependent()) 5716 continue; 5717 5718 llvm::APSInt Result(32); 5719 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5720 return ExprError(Diag(TheCall->getBeginLoc(), 5721 diag::err_shufflevector_nonconstant_argument) 5722 << TheCall->getArg(i)->getSourceRange()); 5723 5724 // Allow -1 which will be translated to undef in the IR. 5725 if (Result.isSigned() && Result.isAllOnesValue()) 5726 continue; 5727 5728 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5729 return ExprError(Diag(TheCall->getBeginLoc(), 5730 diag::err_shufflevector_argument_too_large) 5731 << TheCall->getArg(i)->getSourceRange()); 5732 } 5733 5734 SmallVector<Expr*, 32> exprs; 5735 5736 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5737 exprs.push_back(TheCall->getArg(i)); 5738 TheCall->setArg(i, nullptr); 5739 } 5740 5741 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5742 TheCall->getCallee()->getBeginLoc(), 5743 TheCall->getRParenLoc()); 5744 } 5745 5746 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5747 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5748 SourceLocation BuiltinLoc, 5749 SourceLocation RParenLoc) { 5750 ExprValueKind VK = VK_RValue; 5751 ExprObjectKind OK = OK_Ordinary; 5752 QualType DstTy = TInfo->getType(); 5753 QualType SrcTy = E->getType(); 5754 5755 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5756 return ExprError(Diag(BuiltinLoc, 5757 diag::err_convertvector_non_vector) 5758 << E->getSourceRange()); 5759 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5760 return ExprError(Diag(BuiltinLoc, 5761 diag::err_convertvector_non_vector_type)); 5762 5763 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5764 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5765 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5766 if (SrcElts != DstElts) 5767 return ExprError(Diag(BuiltinLoc, 5768 diag::err_convertvector_incompatible_vector) 5769 << E->getSourceRange()); 5770 } 5771 5772 return new (Context) 5773 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5774 } 5775 5776 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5777 // This is declared to take (const void*, ...) and can take two 5778 // optional constant int args. 5779 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5780 unsigned NumArgs = TheCall->getNumArgs(); 5781 5782 if (NumArgs > 3) 5783 return Diag(TheCall->getEndLoc(), 5784 diag::err_typecheck_call_too_many_args_at_most) 5785 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5786 5787 // Argument 0 is checked for us and the remaining arguments must be 5788 // constant integers. 5789 for (unsigned i = 1; i != NumArgs; ++i) 5790 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5791 return true; 5792 5793 return false; 5794 } 5795 5796 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5797 // __assume does not evaluate its arguments, and should warn if its argument 5798 // has side effects. 5799 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5800 Expr *Arg = TheCall->getArg(0); 5801 if (Arg->isInstantiationDependent()) return false; 5802 5803 if (Arg->HasSideEffects(Context)) 5804 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5805 << Arg->getSourceRange() 5806 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5807 5808 return false; 5809 } 5810 5811 /// Handle __builtin_alloca_with_align. This is declared 5812 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5813 /// than 8. 5814 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5815 // The alignment must be a constant integer. 5816 Expr *Arg = TheCall->getArg(1); 5817 5818 // We can't check the value of a dependent argument. 5819 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5820 if (const auto *UE = 5821 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5822 if (UE->getKind() == UETT_AlignOf || 5823 UE->getKind() == UETT_PreferredAlignOf) 5824 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5825 << Arg->getSourceRange(); 5826 5827 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5828 5829 if (!Result.isPowerOf2()) 5830 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5831 << Arg->getSourceRange(); 5832 5833 if (Result < Context.getCharWidth()) 5834 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5835 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5836 5837 if (Result > std::numeric_limits<int32_t>::max()) 5838 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5839 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5840 } 5841 5842 return false; 5843 } 5844 5845 /// Handle __builtin_assume_aligned. This is declared 5846 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5847 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5848 unsigned NumArgs = TheCall->getNumArgs(); 5849 5850 if (NumArgs > 3) 5851 return Diag(TheCall->getEndLoc(), 5852 diag::err_typecheck_call_too_many_args_at_most) 5853 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5854 5855 // The alignment must be a constant integer. 5856 Expr *Arg = TheCall->getArg(1); 5857 5858 // We can't check the value of a dependent argument. 5859 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5860 llvm::APSInt Result; 5861 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5862 return true; 5863 5864 if (!Result.isPowerOf2()) 5865 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5866 << Arg->getSourceRange(); 5867 } 5868 5869 if (NumArgs > 2) { 5870 ExprResult Arg(TheCall->getArg(2)); 5871 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5872 Context.getSizeType(), false); 5873 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5874 if (Arg.isInvalid()) return true; 5875 TheCall->setArg(2, Arg.get()); 5876 } 5877 5878 return false; 5879 } 5880 5881 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5882 unsigned BuiltinID = 5883 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5884 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5885 5886 unsigned NumArgs = TheCall->getNumArgs(); 5887 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5888 if (NumArgs < NumRequiredArgs) { 5889 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5890 << 0 /* function call */ << NumRequiredArgs << NumArgs 5891 << TheCall->getSourceRange(); 5892 } 5893 if (NumArgs >= NumRequiredArgs + 0x100) { 5894 return Diag(TheCall->getEndLoc(), 5895 diag::err_typecheck_call_too_many_args_at_most) 5896 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5897 << TheCall->getSourceRange(); 5898 } 5899 unsigned i = 0; 5900 5901 // For formatting call, check buffer arg. 5902 if (!IsSizeCall) { 5903 ExprResult Arg(TheCall->getArg(i)); 5904 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5905 Context, Context.VoidPtrTy, false); 5906 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5907 if (Arg.isInvalid()) 5908 return true; 5909 TheCall->setArg(i, Arg.get()); 5910 i++; 5911 } 5912 5913 // Check string literal arg. 5914 unsigned FormatIdx = i; 5915 { 5916 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5917 if (Arg.isInvalid()) 5918 return true; 5919 TheCall->setArg(i, Arg.get()); 5920 i++; 5921 } 5922 5923 // Make sure variadic args are scalar. 5924 unsigned FirstDataArg = i; 5925 while (i < NumArgs) { 5926 ExprResult Arg = DefaultVariadicArgumentPromotion( 5927 TheCall->getArg(i), VariadicFunction, nullptr); 5928 if (Arg.isInvalid()) 5929 return true; 5930 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5931 if (ArgSize.getQuantity() >= 0x100) { 5932 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5933 << i << (int)ArgSize.getQuantity() << 0xff 5934 << TheCall->getSourceRange(); 5935 } 5936 TheCall->setArg(i, Arg.get()); 5937 i++; 5938 } 5939 5940 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5941 // call to avoid duplicate diagnostics. 5942 if (!IsSizeCall) { 5943 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5944 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5945 bool Success = CheckFormatArguments( 5946 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5947 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5948 CheckedVarArgs); 5949 if (!Success) 5950 return true; 5951 } 5952 5953 if (IsSizeCall) { 5954 TheCall->setType(Context.getSizeType()); 5955 } else { 5956 TheCall->setType(Context.VoidPtrTy); 5957 } 5958 return false; 5959 } 5960 5961 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5962 /// TheCall is a constant expression. 5963 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5964 llvm::APSInt &Result) { 5965 Expr *Arg = TheCall->getArg(ArgNum); 5966 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5967 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5968 5969 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5970 5971 if (!Arg->isIntegerConstantExpr(Result, Context)) 5972 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5973 << FDecl->getDeclName() << Arg->getSourceRange(); 5974 5975 return false; 5976 } 5977 5978 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5979 /// TheCall is a constant expression in the range [Low, High]. 5980 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5981 int Low, int High, bool RangeIsError) { 5982 llvm::APSInt Result; 5983 5984 // We can't check the value of a dependent argument. 5985 Expr *Arg = TheCall->getArg(ArgNum); 5986 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5987 return false; 5988 5989 // Check constant-ness first. 5990 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5991 return true; 5992 5993 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5994 if (RangeIsError) 5995 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5996 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5997 else 5998 // Defer the warning until we know if the code will be emitted so that 5999 // dead code can ignore this. 6000 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6001 PDiag(diag::warn_argument_invalid_range) 6002 << Result.toString(10) << Low << High 6003 << Arg->getSourceRange()); 6004 } 6005 6006 return false; 6007 } 6008 6009 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6010 /// TheCall is a constant expression is a multiple of Num.. 6011 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6012 unsigned Num) { 6013 llvm::APSInt Result; 6014 6015 // We can't check the value of a dependent argument. 6016 Expr *Arg = TheCall->getArg(ArgNum); 6017 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6018 return false; 6019 6020 // Check constant-ness first. 6021 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6022 return true; 6023 6024 if (Result.getSExtValue() % Num != 0) 6025 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6026 << Num << Arg->getSourceRange(); 6027 6028 return false; 6029 } 6030 6031 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6032 /// TheCall is an ARM/AArch64 special register string literal. 6033 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6034 int ArgNum, unsigned ExpectedFieldNum, 6035 bool AllowName) { 6036 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6037 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6038 BuiltinID == ARM::BI__builtin_arm_rsr || 6039 BuiltinID == ARM::BI__builtin_arm_rsrp || 6040 BuiltinID == ARM::BI__builtin_arm_wsr || 6041 BuiltinID == ARM::BI__builtin_arm_wsrp; 6042 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6043 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6044 BuiltinID == AArch64::BI__builtin_arm_rsr || 6045 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6046 BuiltinID == AArch64::BI__builtin_arm_wsr || 6047 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6048 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6049 6050 // We can't check the value of a dependent argument. 6051 Expr *Arg = TheCall->getArg(ArgNum); 6052 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6053 return false; 6054 6055 // Check if the argument is a string literal. 6056 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6057 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6058 << Arg->getSourceRange(); 6059 6060 // Check the type of special register given. 6061 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6062 SmallVector<StringRef, 6> Fields; 6063 Reg.split(Fields, ":"); 6064 6065 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6066 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6067 << Arg->getSourceRange(); 6068 6069 // If the string is the name of a register then we cannot check that it is 6070 // valid here but if the string is of one the forms described in ACLE then we 6071 // can check that the supplied fields are integers and within the valid 6072 // ranges. 6073 if (Fields.size() > 1) { 6074 bool FiveFields = Fields.size() == 5; 6075 6076 bool ValidString = true; 6077 if (IsARMBuiltin) { 6078 ValidString &= Fields[0].startswith_lower("cp") || 6079 Fields[0].startswith_lower("p"); 6080 if (ValidString) 6081 Fields[0] = 6082 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6083 6084 ValidString &= Fields[2].startswith_lower("c"); 6085 if (ValidString) 6086 Fields[2] = Fields[2].drop_front(1); 6087 6088 if (FiveFields) { 6089 ValidString &= Fields[3].startswith_lower("c"); 6090 if (ValidString) 6091 Fields[3] = Fields[3].drop_front(1); 6092 } 6093 } 6094 6095 SmallVector<int, 5> Ranges; 6096 if (FiveFields) 6097 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6098 else 6099 Ranges.append({15, 7, 15}); 6100 6101 for (unsigned i=0; i<Fields.size(); ++i) { 6102 int IntField; 6103 ValidString &= !Fields[i].getAsInteger(10, IntField); 6104 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6105 } 6106 6107 if (!ValidString) 6108 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6109 << Arg->getSourceRange(); 6110 } else if (IsAArch64Builtin && Fields.size() == 1) { 6111 // If the register name is one of those that appear in the condition below 6112 // and the special register builtin being used is one of the write builtins, 6113 // then we require that the argument provided for writing to the register 6114 // is an integer constant expression. This is because it will be lowered to 6115 // an MSR (immediate) instruction, so we need to know the immediate at 6116 // compile time. 6117 if (TheCall->getNumArgs() != 2) 6118 return false; 6119 6120 std::string RegLower = Reg.lower(); 6121 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6122 RegLower != "pan" && RegLower != "uao") 6123 return false; 6124 6125 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6126 } 6127 6128 return false; 6129 } 6130 6131 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6132 /// This checks that the target supports __builtin_longjmp and 6133 /// that val is a constant 1. 6134 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6135 if (!Context.getTargetInfo().hasSjLjLowering()) 6136 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6137 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6138 6139 Expr *Arg = TheCall->getArg(1); 6140 llvm::APSInt Result; 6141 6142 // TODO: This is less than ideal. Overload this to take a value. 6143 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6144 return true; 6145 6146 if (Result != 1) 6147 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6148 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6149 6150 return false; 6151 } 6152 6153 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6154 /// This checks that the target supports __builtin_setjmp. 6155 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6156 if (!Context.getTargetInfo().hasSjLjLowering()) 6157 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6158 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6159 return false; 6160 } 6161 6162 namespace { 6163 6164 class UncoveredArgHandler { 6165 enum { Unknown = -1, AllCovered = -2 }; 6166 6167 signed FirstUncoveredArg = Unknown; 6168 SmallVector<const Expr *, 4> DiagnosticExprs; 6169 6170 public: 6171 UncoveredArgHandler() = default; 6172 6173 bool hasUncoveredArg() const { 6174 return (FirstUncoveredArg >= 0); 6175 } 6176 6177 unsigned getUncoveredArg() const { 6178 assert(hasUncoveredArg() && "no uncovered argument"); 6179 return FirstUncoveredArg; 6180 } 6181 6182 void setAllCovered() { 6183 // A string has been found with all arguments covered, so clear out 6184 // the diagnostics. 6185 DiagnosticExprs.clear(); 6186 FirstUncoveredArg = AllCovered; 6187 } 6188 6189 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6190 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6191 6192 // Don't update if a previous string covers all arguments. 6193 if (FirstUncoveredArg == AllCovered) 6194 return; 6195 6196 // UncoveredArgHandler tracks the highest uncovered argument index 6197 // and with it all the strings that match this index. 6198 if (NewFirstUncoveredArg == FirstUncoveredArg) 6199 DiagnosticExprs.push_back(StrExpr); 6200 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6201 DiagnosticExprs.clear(); 6202 DiagnosticExprs.push_back(StrExpr); 6203 FirstUncoveredArg = NewFirstUncoveredArg; 6204 } 6205 } 6206 6207 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6208 }; 6209 6210 enum StringLiteralCheckType { 6211 SLCT_NotALiteral, 6212 SLCT_UncheckedLiteral, 6213 SLCT_CheckedLiteral 6214 }; 6215 6216 } // namespace 6217 6218 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6219 BinaryOperatorKind BinOpKind, 6220 bool AddendIsRight) { 6221 unsigned BitWidth = Offset.getBitWidth(); 6222 unsigned AddendBitWidth = Addend.getBitWidth(); 6223 // There might be negative interim results. 6224 if (Addend.isUnsigned()) { 6225 Addend = Addend.zext(++AddendBitWidth); 6226 Addend.setIsSigned(true); 6227 } 6228 // Adjust the bit width of the APSInts. 6229 if (AddendBitWidth > BitWidth) { 6230 Offset = Offset.sext(AddendBitWidth); 6231 BitWidth = AddendBitWidth; 6232 } else if (BitWidth > AddendBitWidth) { 6233 Addend = Addend.sext(BitWidth); 6234 } 6235 6236 bool Ov = false; 6237 llvm::APSInt ResOffset = Offset; 6238 if (BinOpKind == BO_Add) 6239 ResOffset = Offset.sadd_ov(Addend, Ov); 6240 else { 6241 assert(AddendIsRight && BinOpKind == BO_Sub && 6242 "operator must be add or sub with addend on the right"); 6243 ResOffset = Offset.ssub_ov(Addend, Ov); 6244 } 6245 6246 // We add an offset to a pointer here so we should support an offset as big as 6247 // possible. 6248 if (Ov) { 6249 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6250 "index (intermediate) result too big"); 6251 Offset = Offset.sext(2 * BitWidth); 6252 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6253 return; 6254 } 6255 6256 Offset = ResOffset; 6257 } 6258 6259 namespace { 6260 6261 // This is a wrapper class around StringLiteral to support offsetted string 6262 // literals as format strings. It takes the offset into account when returning 6263 // the string and its length or the source locations to display notes correctly. 6264 class FormatStringLiteral { 6265 const StringLiteral *FExpr; 6266 int64_t Offset; 6267 6268 public: 6269 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6270 : FExpr(fexpr), Offset(Offset) {} 6271 6272 StringRef getString() const { 6273 return FExpr->getString().drop_front(Offset); 6274 } 6275 6276 unsigned getByteLength() const { 6277 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6278 } 6279 6280 unsigned getLength() const { return FExpr->getLength() - Offset; } 6281 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6282 6283 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6284 6285 QualType getType() const { return FExpr->getType(); } 6286 6287 bool isAscii() const { return FExpr->isAscii(); } 6288 bool isWide() const { return FExpr->isWide(); } 6289 bool isUTF8() const { return FExpr->isUTF8(); } 6290 bool isUTF16() const { return FExpr->isUTF16(); } 6291 bool isUTF32() const { return FExpr->isUTF32(); } 6292 bool isPascal() const { return FExpr->isPascal(); } 6293 6294 SourceLocation getLocationOfByte( 6295 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6296 const TargetInfo &Target, unsigned *StartToken = nullptr, 6297 unsigned *StartTokenByteOffset = nullptr) const { 6298 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6299 StartToken, StartTokenByteOffset); 6300 } 6301 6302 SourceLocation getBeginLoc() const LLVM_READONLY { 6303 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6304 } 6305 6306 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6307 }; 6308 6309 } // namespace 6310 6311 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6312 const Expr *OrigFormatExpr, 6313 ArrayRef<const Expr *> Args, 6314 bool HasVAListArg, unsigned format_idx, 6315 unsigned firstDataArg, 6316 Sema::FormatStringType Type, 6317 bool inFunctionCall, 6318 Sema::VariadicCallType CallType, 6319 llvm::SmallBitVector &CheckedVarArgs, 6320 UncoveredArgHandler &UncoveredArg); 6321 6322 // Determine if an expression is a string literal or constant string. 6323 // If this function returns false on the arguments to a function expecting a 6324 // format string, we will usually need to emit a warning. 6325 // True string literals are then checked by CheckFormatString. 6326 static StringLiteralCheckType 6327 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6328 bool HasVAListArg, unsigned format_idx, 6329 unsigned firstDataArg, Sema::FormatStringType Type, 6330 Sema::VariadicCallType CallType, bool InFunctionCall, 6331 llvm::SmallBitVector &CheckedVarArgs, 6332 UncoveredArgHandler &UncoveredArg, 6333 llvm::APSInt Offset) { 6334 tryAgain: 6335 assert(Offset.isSigned() && "invalid offset"); 6336 6337 if (E->isTypeDependent() || E->isValueDependent()) 6338 return SLCT_NotALiteral; 6339 6340 E = E->IgnoreParenCasts(); 6341 6342 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6343 // Technically -Wformat-nonliteral does not warn about this case. 6344 // The behavior of printf and friends in this case is implementation 6345 // dependent. Ideally if the format string cannot be null then 6346 // it should have a 'nonnull' attribute in the function prototype. 6347 return SLCT_UncheckedLiteral; 6348 6349 switch (E->getStmtClass()) { 6350 case Stmt::BinaryConditionalOperatorClass: 6351 case Stmt::ConditionalOperatorClass: { 6352 // The expression is a literal if both sub-expressions were, and it was 6353 // completely checked only if both sub-expressions were checked. 6354 const AbstractConditionalOperator *C = 6355 cast<AbstractConditionalOperator>(E); 6356 6357 // Determine whether it is necessary to check both sub-expressions, for 6358 // example, because the condition expression is a constant that can be 6359 // evaluated at compile time. 6360 bool CheckLeft = true, CheckRight = true; 6361 6362 bool Cond; 6363 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 6364 if (Cond) 6365 CheckRight = false; 6366 else 6367 CheckLeft = false; 6368 } 6369 6370 // We need to maintain the offsets for the right and the left hand side 6371 // separately to check if every possible indexed expression is a valid 6372 // string literal. They might have different offsets for different string 6373 // literals in the end. 6374 StringLiteralCheckType Left; 6375 if (!CheckLeft) 6376 Left = SLCT_UncheckedLiteral; 6377 else { 6378 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6379 HasVAListArg, format_idx, firstDataArg, 6380 Type, CallType, InFunctionCall, 6381 CheckedVarArgs, UncoveredArg, Offset); 6382 if (Left == SLCT_NotALiteral || !CheckRight) { 6383 return Left; 6384 } 6385 } 6386 6387 StringLiteralCheckType Right = 6388 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6389 HasVAListArg, format_idx, firstDataArg, 6390 Type, CallType, InFunctionCall, CheckedVarArgs, 6391 UncoveredArg, Offset); 6392 6393 return (CheckLeft && Left < Right) ? Left : Right; 6394 } 6395 6396 case Stmt::ImplicitCastExprClass: 6397 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6398 goto tryAgain; 6399 6400 case Stmt::OpaqueValueExprClass: 6401 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6402 E = src; 6403 goto tryAgain; 6404 } 6405 return SLCT_NotALiteral; 6406 6407 case Stmt::PredefinedExprClass: 6408 // While __func__, etc., are technically not string literals, they 6409 // cannot contain format specifiers and thus are not a security 6410 // liability. 6411 return SLCT_UncheckedLiteral; 6412 6413 case Stmt::DeclRefExprClass: { 6414 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6415 6416 // As an exception, do not flag errors for variables binding to 6417 // const string literals. 6418 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6419 bool isConstant = false; 6420 QualType T = DR->getType(); 6421 6422 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6423 isConstant = AT->getElementType().isConstant(S.Context); 6424 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6425 isConstant = T.isConstant(S.Context) && 6426 PT->getPointeeType().isConstant(S.Context); 6427 } else if (T->isObjCObjectPointerType()) { 6428 // In ObjC, there is usually no "const ObjectPointer" type, 6429 // so don't check if the pointee type is constant. 6430 isConstant = T.isConstant(S.Context); 6431 } 6432 6433 if (isConstant) { 6434 if (const Expr *Init = VD->getAnyInitializer()) { 6435 // Look through initializers like const char c[] = { "foo" } 6436 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6437 if (InitList->isStringLiteralInit()) 6438 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6439 } 6440 return checkFormatStringExpr(S, Init, Args, 6441 HasVAListArg, format_idx, 6442 firstDataArg, Type, CallType, 6443 /*InFunctionCall*/ false, CheckedVarArgs, 6444 UncoveredArg, Offset); 6445 } 6446 } 6447 6448 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6449 // special check to see if the format string is a function parameter 6450 // of the function calling the printf function. If the function 6451 // has an attribute indicating it is a printf-like function, then we 6452 // should suppress warnings concerning non-literals being used in a call 6453 // to a vprintf function. For example: 6454 // 6455 // void 6456 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6457 // va_list ap; 6458 // va_start(ap, fmt); 6459 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6460 // ... 6461 // } 6462 if (HasVAListArg) { 6463 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6464 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6465 int PVIndex = PV->getFunctionScopeIndex() + 1; 6466 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6467 // adjust for implicit parameter 6468 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6469 if (MD->isInstance()) 6470 ++PVIndex; 6471 // We also check if the formats are compatible. 6472 // We can't pass a 'scanf' string to a 'printf' function. 6473 if (PVIndex == PVFormat->getFormatIdx() && 6474 Type == S.GetFormatStringType(PVFormat)) 6475 return SLCT_UncheckedLiteral; 6476 } 6477 } 6478 } 6479 } 6480 } 6481 6482 return SLCT_NotALiteral; 6483 } 6484 6485 case Stmt::CallExprClass: 6486 case Stmt::CXXMemberCallExprClass: { 6487 const CallExpr *CE = cast<CallExpr>(E); 6488 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6489 bool IsFirst = true; 6490 StringLiteralCheckType CommonResult; 6491 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6492 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6493 StringLiteralCheckType Result = checkFormatStringExpr( 6494 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6495 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6496 if (IsFirst) { 6497 CommonResult = Result; 6498 IsFirst = false; 6499 } 6500 } 6501 if (!IsFirst) 6502 return CommonResult; 6503 6504 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6505 unsigned BuiltinID = FD->getBuiltinID(); 6506 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6507 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6508 const Expr *Arg = CE->getArg(0); 6509 return checkFormatStringExpr(S, Arg, Args, 6510 HasVAListArg, format_idx, 6511 firstDataArg, Type, CallType, 6512 InFunctionCall, CheckedVarArgs, 6513 UncoveredArg, Offset); 6514 } 6515 } 6516 } 6517 6518 return SLCT_NotALiteral; 6519 } 6520 case Stmt::ObjCMessageExprClass: { 6521 const auto *ME = cast<ObjCMessageExpr>(E); 6522 if (const auto *ND = ME->getMethodDecl()) { 6523 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6524 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6525 return checkFormatStringExpr( 6526 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6527 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6528 } 6529 } 6530 6531 return SLCT_NotALiteral; 6532 } 6533 case Stmt::ObjCStringLiteralClass: 6534 case Stmt::StringLiteralClass: { 6535 const StringLiteral *StrE = nullptr; 6536 6537 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6538 StrE = ObjCFExpr->getString(); 6539 else 6540 StrE = cast<StringLiteral>(E); 6541 6542 if (StrE) { 6543 if (Offset.isNegative() || Offset > StrE->getLength()) { 6544 // TODO: It would be better to have an explicit warning for out of 6545 // bounds literals. 6546 return SLCT_NotALiteral; 6547 } 6548 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6549 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6550 firstDataArg, Type, InFunctionCall, CallType, 6551 CheckedVarArgs, UncoveredArg); 6552 return SLCT_CheckedLiteral; 6553 } 6554 6555 return SLCT_NotALiteral; 6556 } 6557 case Stmt::BinaryOperatorClass: { 6558 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6559 6560 // A string literal + an int offset is still a string literal. 6561 if (BinOp->isAdditiveOp()) { 6562 Expr::EvalResult LResult, RResult; 6563 6564 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 6565 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 6566 6567 if (LIsInt != RIsInt) { 6568 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6569 6570 if (LIsInt) { 6571 if (BinOpKind == BO_Add) { 6572 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6573 E = BinOp->getRHS(); 6574 goto tryAgain; 6575 } 6576 } else { 6577 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6578 E = BinOp->getLHS(); 6579 goto tryAgain; 6580 } 6581 } 6582 } 6583 6584 return SLCT_NotALiteral; 6585 } 6586 case Stmt::UnaryOperatorClass: { 6587 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6588 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6589 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6590 Expr::EvalResult IndexResult; 6591 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 6592 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6593 /*RHS is int*/ true); 6594 E = ASE->getBase(); 6595 goto tryAgain; 6596 } 6597 } 6598 6599 return SLCT_NotALiteral; 6600 } 6601 6602 default: 6603 return SLCT_NotALiteral; 6604 } 6605 } 6606 6607 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6608 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6609 .Case("scanf", FST_Scanf) 6610 .Cases("printf", "printf0", FST_Printf) 6611 .Cases("NSString", "CFString", FST_NSString) 6612 .Case("strftime", FST_Strftime) 6613 .Case("strfmon", FST_Strfmon) 6614 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6615 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6616 .Case("os_trace", FST_OSLog) 6617 .Case("os_log", FST_OSLog) 6618 .Default(FST_Unknown); 6619 } 6620 6621 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6622 /// functions) for correct use of format strings. 6623 /// Returns true if a format string has been fully checked. 6624 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6625 ArrayRef<const Expr *> Args, 6626 bool IsCXXMember, 6627 VariadicCallType CallType, 6628 SourceLocation Loc, SourceRange Range, 6629 llvm::SmallBitVector &CheckedVarArgs) { 6630 FormatStringInfo FSI; 6631 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6632 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6633 FSI.FirstDataArg, GetFormatStringType(Format), 6634 CallType, Loc, Range, CheckedVarArgs); 6635 return false; 6636 } 6637 6638 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6639 bool HasVAListArg, unsigned format_idx, 6640 unsigned firstDataArg, FormatStringType Type, 6641 VariadicCallType CallType, 6642 SourceLocation Loc, SourceRange Range, 6643 llvm::SmallBitVector &CheckedVarArgs) { 6644 // CHECK: printf/scanf-like function is called with no format string. 6645 if (format_idx >= Args.size()) { 6646 Diag(Loc, diag::warn_missing_format_string) << Range; 6647 return false; 6648 } 6649 6650 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6651 6652 // CHECK: format string is not a string literal. 6653 // 6654 // Dynamically generated format strings are difficult to 6655 // automatically vet at compile time. Requiring that format strings 6656 // are string literals: (1) permits the checking of format strings by 6657 // the compiler and thereby (2) can practically remove the source of 6658 // many format string exploits. 6659 6660 // Format string can be either ObjC string (e.g. @"%d") or 6661 // C string (e.g. "%d") 6662 // ObjC string uses the same format specifiers as C string, so we can use 6663 // the same format string checking logic for both ObjC and C strings. 6664 UncoveredArgHandler UncoveredArg; 6665 StringLiteralCheckType CT = 6666 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6667 format_idx, firstDataArg, Type, CallType, 6668 /*IsFunctionCall*/ true, CheckedVarArgs, 6669 UncoveredArg, 6670 /*no string offset*/ llvm::APSInt(64, false) = 0); 6671 6672 // Generate a diagnostic where an uncovered argument is detected. 6673 if (UncoveredArg.hasUncoveredArg()) { 6674 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6675 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6676 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6677 } 6678 6679 if (CT != SLCT_NotALiteral) 6680 // Literal format string found, check done! 6681 return CT == SLCT_CheckedLiteral; 6682 6683 // Strftime is particular as it always uses a single 'time' argument, 6684 // so it is safe to pass a non-literal string. 6685 if (Type == FST_Strftime) 6686 return false; 6687 6688 // Do not emit diag when the string param is a macro expansion and the 6689 // format is either NSString or CFString. This is a hack to prevent 6690 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6691 // which are usually used in place of NS and CF string literals. 6692 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6693 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6694 return false; 6695 6696 // If there are no arguments specified, warn with -Wformat-security, otherwise 6697 // warn only with -Wformat-nonliteral. 6698 if (Args.size() == firstDataArg) { 6699 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6700 << OrigFormatExpr->getSourceRange(); 6701 switch (Type) { 6702 default: 6703 break; 6704 case FST_Kprintf: 6705 case FST_FreeBSDKPrintf: 6706 case FST_Printf: 6707 Diag(FormatLoc, diag::note_format_security_fixit) 6708 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6709 break; 6710 case FST_NSString: 6711 Diag(FormatLoc, diag::note_format_security_fixit) 6712 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6713 break; 6714 } 6715 } else { 6716 Diag(FormatLoc, diag::warn_format_nonliteral) 6717 << OrigFormatExpr->getSourceRange(); 6718 } 6719 return false; 6720 } 6721 6722 namespace { 6723 6724 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6725 protected: 6726 Sema &S; 6727 const FormatStringLiteral *FExpr; 6728 const Expr *OrigFormatExpr; 6729 const Sema::FormatStringType FSType; 6730 const unsigned FirstDataArg; 6731 const unsigned NumDataArgs; 6732 const char *Beg; // Start of format string. 6733 const bool HasVAListArg; 6734 ArrayRef<const Expr *> Args; 6735 unsigned FormatIdx; 6736 llvm::SmallBitVector CoveredArgs; 6737 bool usesPositionalArgs = false; 6738 bool atFirstArg = true; 6739 bool inFunctionCall; 6740 Sema::VariadicCallType CallType; 6741 llvm::SmallBitVector &CheckedVarArgs; 6742 UncoveredArgHandler &UncoveredArg; 6743 6744 public: 6745 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6746 const Expr *origFormatExpr, 6747 const Sema::FormatStringType type, unsigned firstDataArg, 6748 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6749 ArrayRef<const Expr *> Args, unsigned formatIdx, 6750 bool inFunctionCall, Sema::VariadicCallType callType, 6751 llvm::SmallBitVector &CheckedVarArgs, 6752 UncoveredArgHandler &UncoveredArg) 6753 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6754 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6755 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6756 inFunctionCall(inFunctionCall), CallType(callType), 6757 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6758 CoveredArgs.resize(numDataArgs); 6759 CoveredArgs.reset(); 6760 } 6761 6762 void DoneProcessing(); 6763 6764 void HandleIncompleteSpecifier(const char *startSpecifier, 6765 unsigned specifierLen) override; 6766 6767 void HandleInvalidLengthModifier( 6768 const analyze_format_string::FormatSpecifier &FS, 6769 const analyze_format_string::ConversionSpecifier &CS, 6770 const char *startSpecifier, unsigned specifierLen, 6771 unsigned DiagID); 6772 6773 void HandleNonStandardLengthModifier( 6774 const analyze_format_string::FormatSpecifier &FS, 6775 const char *startSpecifier, unsigned specifierLen); 6776 6777 void HandleNonStandardConversionSpecifier( 6778 const analyze_format_string::ConversionSpecifier &CS, 6779 const char *startSpecifier, unsigned specifierLen); 6780 6781 void HandlePosition(const char *startPos, unsigned posLen) override; 6782 6783 void HandleInvalidPosition(const char *startSpecifier, 6784 unsigned specifierLen, 6785 analyze_format_string::PositionContext p) override; 6786 6787 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6788 6789 void HandleNullChar(const char *nullCharacter) override; 6790 6791 template <typename Range> 6792 static void 6793 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6794 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6795 bool IsStringLocation, Range StringRange, 6796 ArrayRef<FixItHint> Fixit = None); 6797 6798 protected: 6799 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6800 const char *startSpec, 6801 unsigned specifierLen, 6802 const char *csStart, unsigned csLen); 6803 6804 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6805 const char *startSpec, 6806 unsigned specifierLen); 6807 6808 SourceRange getFormatStringRange(); 6809 CharSourceRange getSpecifierRange(const char *startSpecifier, 6810 unsigned specifierLen); 6811 SourceLocation getLocationOfByte(const char *x); 6812 6813 const Expr *getDataArg(unsigned i) const; 6814 6815 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6816 const analyze_format_string::ConversionSpecifier &CS, 6817 const char *startSpecifier, unsigned specifierLen, 6818 unsigned argIndex); 6819 6820 template <typename Range> 6821 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6822 bool IsStringLocation, Range StringRange, 6823 ArrayRef<FixItHint> Fixit = None); 6824 }; 6825 6826 } // namespace 6827 6828 SourceRange CheckFormatHandler::getFormatStringRange() { 6829 return OrigFormatExpr->getSourceRange(); 6830 } 6831 6832 CharSourceRange CheckFormatHandler:: 6833 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6834 SourceLocation Start = getLocationOfByte(startSpecifier); 6835 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6836 6837 // Advance the end SourceLocation by one due to half-open ranges. 6838 End = End.getLocWithOffset(1); 6839 6840 return CharSourceRange::getCharRange(Start, End); 6841 } 6842 6843 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6844 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6845 S.getLangOpts(), S.Context.getTargetInfo()); 6846 } 6847 6848 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6849 unsigned specifierLen){ 6850 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6851 getLocationOfByte(startSpecifier), 6852 /*IsStringLocation*/true, 6853 getSpecifierRange(startSpecifier, specifierLen)); 6854 } 6855 6856 void CheckFormatHandler::HandleInvalidLengthModifier( 6857 const analyze_format_string::FormatSpecifier &FS, 6858 const analyze_format_string::ConversionSpecifier &CS, 6859 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6860 using namespace analyze_format_string; 6861 6862 const LengthModifier &LM = FS.getLengthModifier(); 6863 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6864 6865 // See if we know how to fix this length modifier. 6866 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6867 if (FixedLM) { 6868 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6869 getLocationOfByte(LM.getStart()), 6870 /*IsStringLocation*/true, 6871 getSpecifierRange(startSpecifier, specifierLen)); 6872 6873 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6874 << FixedLM->toString() 6875 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6876 6877 } else { 6878 FixItHint Hint; 6879 if (DiagID == diag::warn_format_nonsensical_length) 6880 Hint = FixItHint::CreateRemoval(LMRange); 6881 6882 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6883 getLocationOfByte(LM.getStart()), 6884 /*IsStringLocation*/true, 6885 getSpecifierRange(startSpecifier, specifierLen), 6886 Hint); 6887 } 6888 } 6889 6890 void CheckFormatHandler::HandleNonStandardLengthModifier( 6891 const analyze_format_string::FormatSpecifier &FS, 6892 const char *startSpecifier, unsigned specifierLen) { 6893 using namespace analyze_format_string; 6894 6895 const LengthModifier &LM = FS.getLengthModifier(); 6896 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6897 6898 // See if we know how to fix this length modifier. 6899 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6900 if (FixedLM) { 6901 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6902 << LM.toString() << 0, 6903 getLocationOfByte(LM.getStart()), 6904 /*IsStringLocation*/true, 6905 getSpecifierRange(startSpecifier, specifierLen)); 6906 6907 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6908 << FixedLM->toString() 6909 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6910 6911 } else { 6912 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6913 << LM.toString() << 0, 6914 getLocationOfByte(LM.getStart()), 6915 /*IsStringLocation*/true, 6916 getSpecifierRange(startSpecifier, specifierLen)); 6917 } 6918 } 6919 6920 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6921 const analyze_format_string::ConversionSpecifier &CS, 6922 const char *startSpecifier, unsigned specifierLen) { 6923 using namespace analyze_format_string; 6924 6925 // See if we know how to fix this conversion specifier. 6926 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 6927 if (FixedCS) { 6928 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6929 << CS.toString() << /*conversion specifier*/1, 6930 getLocationOfByte(CS.getStart()), 6931 /*IsStringLocation*/true, 6932 getSpecifierRange(startSpecifier, specifierLen)); 6933 6934 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 6935 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 6936 << FixedCS->toString() 6937 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 6938 } else { 6939 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6940 << CS.toString() << /*conversion specifier*/1, 6941 getLocationOfByte(CS.getStart()), 6942 /*IsStringLocation*/true, 6943 getSpecifierRange(startSpecifier, specifierLen)); 6944 } 6945 } 6946 6947 void CheckFormatHandler::HandlePosition(const char *startPos, 6948 unsigned posLen) { 6949 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 6950 getLocationOfByte(startPos), 6951 /*IsStringLocation*/true, 6952 getSpecifierRange(startPos, posLen)); 6953 } 6954 6955 void 6956 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 6957 analyze_format_string::PositionContext p) { 6958 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 6959 << (unsigned) p, 6960 getLocationOfByte(startPos), /*IsStringLocation*/true, 6961 getSpecifierRange(startPos, posLen)); 6962 } 6963 6964 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 6965 unsigned posLen) { 6966 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 6967 getLocationOfByte(startPos), 6968 /*IsStringLocation*/true, 6969 getSpecifierRange(startPos, posLen)); 6970 } 6971 6972 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 6973 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 6974 // The presence of a null character is likely an error. 6975 EmitFormatDiagnostic( 6976 S.PDiag(diag::warn_printf_format_string_contains_null_char), 6977 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 6978 getFormatStringRange()); 6979 } 6980 } 6981 6982 // Note that this may return NULL if there was an error parsing or building 6983 // one of the argument expressions. 6984 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 6985 return Args[FirstDataArg + i]; 6986 } 6987 6988 void CheckFormatHandler::DoneProcessing() { 6989 // Does the number of data arguments exceed the number of 6990 // format conversions in the format string? 6991 if (!HasVAListArg) { 6992 // Find any arguments that weren't covered. 6993 CoveredArgs.flip(); 6994 signed notCoveredArg = CoveredArgs.find_first(); 6995 if (notCoveredArg >= 0) { 6996 assert((unsigned)notCoveredArg < NumDataArgs); 6997 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 6998 } else { 6999 UncoveredArg.setAllCovered(); 7000 } 7001 } 7002 } 7003 7004 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7005 const Expr *ArgExpr) { 7006 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7007 "Invalid state"); 7008 7009 if (!ArgExpr) 7010 return; 7011 7012 SourceLocation Loc = ArgExpr->getBeginLoc(); 7013 7014 if (S.getSourceManager().isInSystemMacro(Loc)) 7015 return; 7016 7017 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7018 for (auto E : DiagnosticExprs) 7019 PDiag << E->getSourceRange(); 7020 7021 CheckFormatHandler::EmitFormatDiagnostic( 7022 S, IsFunctionCall, DiagnosticExprs[0], 7023 PDiag, Loc, /*IsStringLocation*/false, 7024 DiagnosticExprs[0]->getSourceRange()); 7025 } 7026 7027 bool 7028 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7029 SourceLocation Loc, 7030 const char *startSpec, 7031 unsigned specifierLen, 7032 const char *csStart, 7033 unsigned csLen) { 7034 bool keepGoing = true; 7035 if (argIndex < NumDataArgs) { 7036 // Consider the argument coverered, even though the specifier doesn't 7037 // make sense. 7038 CoveredArgs.set(argIndex); 7039 } 7040 else { 7041 // If argIndex exceeds the number of data arguments we 7042 // don't issue a warning because that is just a cascade of warnings (and 7043 // they may have intended '%%' anyway). We don't want to continue processing 7044 // the format string after this point, however, as we will like just get 7045 // gibberish when trying to match arguments. 7046 keepGoing = false; 7047 } 7048 7049 StringRef Specifier(csStart, csLen); 7050 7051 // If the specifier in non-printable, it could be the first byte of a UTF-8 7052 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7053 // hex value. 7054 std::string CodePointStr; 7055 if (!llvm::sys::locale::isPrint(*csStart)) { 7056 llvm::UTF32 CodePoint; 7057 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7058 const llvm::UTF8 *E = 7059 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7060 llvm::ConversionResult Result = 7061 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7062 7063 if (Result != llvm::conversionOK) { 7064 unsigned char FirstChar = *csStart; 7065 CodePoint = (llvm::UTF32)FirstChar; 7066 } 7067 7068 llvm::raw_string_ostream OS(CodePointStr); 7069 if (CodePoint < 256) 7070 OS << "\\x" << llvm::format("%02x", CodePoint); 7071 else if (CodePoint <= 0xFFFF) 7072 OS << "\\u" << llvm::format("%04x", CodePoint); 7073 else 7074 OS << "\\U" << llvm::format("%08x", CodePoint); 7075 OS.flush(); 7076 Specifier = CodePointStr; 7077 } 7078 7079 EmitFormatDiagnostic( 7080 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7081 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7082 7083 return keepGoing; 7084 } 7085 7086 void 7087 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7088 const char *startSpec, 7089 unsigned specifierLen) { 7090 EmitFormatDiagnostic( 7091 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7092 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7093 } 7094 7095 bool 7096 CheckFormatHandler::CheckNumArgs( 7097 const analyze_format_string::FormatSpecifier &FS, 7098 const analyze_format_string::ConversionSpecifier &CS, 7099 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7100 7101 if (argIndex >= NumDataArgs) { 7102 PartialDiagnostic PDiag = FS.usesPositionalArg() 7103 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7104 << (argIndex+1) << NumDataArgs) 7105 : S.PDiag(diag::warn_printf_insufficient_data_args); 7106 EmitFormatDiagnostic( 7107 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7108 getSpecifierRange(startSpecifier, specifierLen)); 7109 7110 // Since more arguments than conversion tokens are given, by extension 7111 // all arguments are covered, so mark this as so. 7112 UncoveredArg.setAllCovered(); 7113 return false; 7114 } 7115 return true; 7116 } 7117 7118 template<typename Range> 7119 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7120 SourceLocation Loc, 7121 bool IsStringLocation, 7122 Range StringRange, 7123 ArrayRef<FixItHint> FixIt) { 7124 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7125 Loc, IsStringLocation, StringRange, FixIt); 7126 } 7127 7128 /// If the format string is not within the function call, emit a note 7129 /// so that the function call and string are in diagnostic messages. 7130 /// 7131 /// \param InFunctionCall if true, the format string is within the function 7132 /// call and only one diagnostic message will be produced. Otherwise, an 7133 /// extra note will be emitted pointing to location of the format string. 7134 /// 7135 /// \param ArgumentExpr the expression that is passed as the format string 7136 /// argument in the function call. Used for getting locations when two 7137 /// diagnostics are emitted. 7138 /// 7139 /// \param PDiag the callee should already have provided any strings for the 7140 /// diagnostic message. This function only adds locations and fixits 7141 /// to diagnostics. 7142 /// 7143 /// \param Loc primary location for diagnostic. If two diagnostics are 7144 /// required, one will be at Loc and a new SourceLocation will be created for 7145 /// the other one. 7146 /// 7147 /// \param IsStringLocation if true, Loc points to the format string should be 7148 /// used for the note. Otherwise, Loc points to the argument list and will 7149 /// be used with PDiag. 7150 /// 7151 /// \param StringRange some or all of the string to highlight. This is 7152 /// templated so it can accept either a CharSourceRange or a SourceRange. 7153 /// 7154 /// \param FixIt optional fix it hint for the format string. 7155 template <typename Range> 7156 void CheckFormatHandler::EmitFormatDiagnostic( 7157 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7158 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7159 Range StringRange, ArrayRef<FixItHint> FixIt) { 7160 if (InFunctionCall) { 7161 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7162 D << StringRange; 7163 D << FixIt; 7164 } else { 7165 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7166 << ArgumentExpr->getSourceRange(); 7167 7168 const Sema::SemaDiagnosticBuilder &Note = 7169 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7170 diag::note_format_string_defined); 7171 7172 Note << StringRange; 7173 Note << FixIt; 7174 } 7175 } 7176 7177 //===--- CHECK: Printf format string checking ------------------------------===// 7178 7179 namespace { 7180 7181 class CheckPrintfHandler : public CheckFormatHandler { 7182 public: 7183 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7184 const Expr *origFormatExpr, 7185 const Sema::FormatStringType type, unsigned firstDataArg, 7186 unsigned numDataArgs, bool isObjC, const char *beg, 7187 bool hasVAListArg, ArrayRef<const Expr *> Args, 7188 unsigned formatIdx, bool inFunctionCall, 7189 Sema::VariadicCallType CallType, 7190 llvm::SmallBitVector &CheckedVarArgs, 7191 UncoveredArgHandler &UncoveredArg) 7192 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7193 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7194 inFunctionCall, CallType, CheckedVarArgs, 7195 UncoveredArg) {} 7196 7197 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7198 7199 /// Returns true if '%@' specifiers are allowed in the format string. 7200 bool allowsObjCArg() const { 7201 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7202 FSType == Sema::FST_OSTrace; 7203 } 7204 7205 bool HandleInvalidPrintfConversionSpecifier( 7206 const analyze_printf::PrintfSpecifier &FS, 7207 const char *startSpecifier, 7208 unsigned specifierLen) override; 7209 7210 void handleInvalidMaskType(StringRef MaskType) override; 7211 7212 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7213 const char *startSpecifier, 7214 unsigned specifierLen) override; 7215 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7216 const char *StartSpecifier, 7217 unsigned SpecifierLen, 7218 const Expr *E); 7219 7220 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7221 const char *startSpecifier, unsigned specifierLen); 7222 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7223 const analyze_printf::OptionalAmount &Amt, 7224 unsigned type, 7225 const char *startSpecifier, unsigned specifierLen); 7226 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7227 const analyze_printf::OptionalFlag &flag, 7228 const char *startSpecifier, unsigned specifierLen); 7229 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7230 const analyze_printf::OptionalFlag &ignoredFlag, 7231 const analyze_printf::OptionalFlag &flag, 7232 const char *startSpecifier, unsigned specifierLen); 7233 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7234 const Expr *E); 7235 7236 void HandleEmptyObjCModifierFlag(const char *startFlag, 7237 unsigned flagLen) override; 7238 7239 void HandleInvalidObjCModifierFlag(const char *startFlag, 7240 unsigned flagLen) override; 7241 7242 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7243 const char *flagsEnd, 7244 const char *conversionPosition) 7245 override; 7246 }; 7247 7248 } // namespace 7249 7250 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7251 const analyze_printf::PrintfSpecifier &FS, 7252 const char *startSpecifier, 7253 unsigned specifierLen) { 7254 const analyze_printf::PrintfConversionSpecifier &CS = 7255 FS.getConversionSpecifier(); 7256 7257 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7258 getLocationOfByte(CS.getStart()), 7259 startSpecifier, specifierLen, 7260 CS.getStart(), CS.getLength()); 7261 } 7262 7263 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7264 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7265 } 7266 7267 bool CheckPrintfHandler::HandleAmount( 7268 const analyze_format_string::OptionalAmount &Amt, 7269 unsigned k, const char *startSpecifier, 7270 unsigned specifierLen) { 7271 if (Amt.hasDataArgument()) { 7272 if (!HasVAListArg) { 7273 unsigned argIndex = Amt.getArgIndex(); 7274 if (argIndex >= NumDataArgs) { 7275 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7276 << k, 7277 getLocationOfByte(Amt.getStart()), 7278 /*IsStringLocation*/true, 7279 getSpecifierRange(startSpecifier, specifierLen)); 7280 // Don't do any more checking. We will just emit 7281 // spurious errors. 7282 return false; 7283 } 7284 7285 // Type check the data argument. It should be an 'int'. 7286 // Although not in conformance with C99, we also allow the argument to be 7287 // an 'unsigned int' as that is a reasonably safe case. GCC also 7288 // doesn't emit a warning for that case. 7289 CoveredArgs.set(argIndex); 7290 const Expr *Arg = getDataArg(argIndex); 7291 if (!Arg) 7292 return false; 7293 7294 QualType T = Arg->getType(); 7295 7296 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7297 assert(AT.isValid()); 7298 7299 if (!AT.matchesType(S.Context, T)) { 7300 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7301 << k << AT.getRepresentativeTypeName(S.Context) 7302 << T << Arg->getSourceRange(), 7303 getLocationOfByte(Amt.getStart()), 7304 /*IsStringLocation*/true, 7305 getSpecifierRange(startSpecifier, specifierLen)); 7306 // Don't do any more checking. We will just emit 7307 // spurious errors. 7308 return false; 7309 } 7310 } 7311 } 7312 return true; 7313 } 7314 7315 void CheckPrintfHandler::HandleInvalidAmount( 7316 const analyze_printf::PrintfSpecifier &FS, 7317 const analyze_printf::OptionalAmount &Amt, 7318 unsigned type, 7319 const char *startSpecifier, 7320 unsigned specifierLen) { 7321 const analyze_printf::PrintfConversionSpecifier &CS = 7322 FS.getConversionSpecifier(); 7323 7324 FixItHint fixit = 7325 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7326 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7327 Amt.getConstantLength())) 7328 : FixItHint(); 7329 7330 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7331 << type << CS.toString(), 7332 getLocationOfByte(Amt.getStart()), 7333 /*IsStringLocation*/true, 7334 getSpecifierRange(startSpecifier, specifierLen), 7335 fixit); 7336 } 7337 7338 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7339 const analyze_printf::OptionalFlag &flag, 7340 const char *startSpecifier, 7341 unsigned specifierLen) { 7342 // Warn about pointless flag with a fixit removal. 7343 const analyze_printf::PrintfConversionSpecifier &CS = 7344 FS.getConversionSpecifier(); 7345 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7346 << flag.toString() << CS.toString(), 7347 getLocationOfByte(flag.getPosition()), 7348 /*IsStringLocation*/true, 7349 getSpecifierRange(startSpecifier, specifierLen), 7350 FixItHint::CreateRemoval( 7351 getSpecifierRange(flag.getPosition(), 1))); 7352 } 7353 7354 void CheckPrintfHandler::HandleIgnoredFlag( 7355 const analyze_printf::PrintfSpecifier &FS, 7356 const analyze_printf::OptionalFlag &ignoredFlag, 7357 const analyze_printf::OptionalFlag &flag, 7358 const char *startSpecifier, 7359 unsigned specifierLen) { 7360 // Warn about ignored flag with a fixit removal. 7361 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7362 << ignoredFlag.toString() << flag.toString(), 7363 getLocationOfByte(ignoredFlag.getPosition()), 7364 /*IsStringLocation*/true, 7365 getSpecifierRange(startSpecifier, specifierLen), 7366 FixItHint::CreateRemoval( 7367 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7368 } 7369 7370 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7371 unsigned flagLen) { 7372 // Warn about an empty flag. 7373 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7374 getLocationOfByte(startFlag), 7375 /*IsStringLocation*/true, 7376 getSpecifierRange(startFlag, flagLen)); 7377 } 7378 7379 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7380 unsigned flagLen) { 7381 // Warn about an invalid flag. 7382 auto Range = getSpecifierRange(startFlag, flagLen); 7383 StringRef flag(startFlag, flagLen); 7384 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7385 getLocationOfByte(startFlag), 7386 /*IsStringLocation*/true, 7387 Range, FixItHint::CreateRemoval(Range)); 7388 } 7389 7390 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7391 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7392 // Warn about using '[...]' without a '@' conversion. 7393 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7394 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7395 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7396 getLocationOfByte(conversionPosition), 7397 /*IsStringLocation*/true, 7398 Range, FixItHint::CreateRemoval(Range)); 7399 } 7400 7401 // Determines if the specified is a C++ class or struct containing 7402 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7403 // "c_str()"). 7404 template<typename MemberKind> 7405 static llvm::SmallPtrSet<MemberKind*, 1> 7406 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7407 const RecordType *RT = Ty->getAs<RecordType>(); 7408 llvm::SmallPtrSet<MemberKind*, 1> Results; 7409 7410 if (!RT) 7411 return Results; 7412 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7413 if (!RD || !RD->getDefinition()) 7414 return Results; 7415 7416 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7417 Sema::LookupMemberName); 7418 R.suppressDiagnostics(); 7419 7420 // We just need to include all members of the right kind turned up by the 7421 // filter, at this point. 7422 if (S.LookupQualifiedName(R, RT->getDecl())) 7423 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7424 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7425 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7426 Results.insert(FK); 7427 } 7428 return Results; 7429 } 7430 7431 /// Check if we could call '.c_str()' on an object. 7432 /// 7433 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7434 /// allow the call, or if it would be ambiguous). 7435 bool Sema::hasCStrMethod(const Expr *E) { 7436 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7437 7438 MethodSet Results = 7439 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7440 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7441 MI != ME; ++MI) 7442 if ((*MI)->getMinRequiredArguments() == 0) 7443 return true; 7444 return false; 7445 } 7446 7447 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7448 // better diagnostic if so. AT is assumed to be valid. 7449 // Returns true when a c_str() conversion method is found. 7450 bool CheckPrintfHandler::checkForCStrMembers( 7451 const analyze_printf::ArgType &AT, const Expr *E) { 7452 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7453 7454 MethodSet Results = 7455 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7456 7457 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7458 MI != ME; ++MI) { 7459 const CXXMethodDecl *Method = *MI; 7460 if (Method->getMinRequiredArguments() == 0 && 7461 AT.matchesType(S.Context, Method->getReturnType())) { 7462 // FIXME: Suggest parens if the expression needs them. 7463 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7464 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7465 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7466 return true; 7467 } 7468 } 7469 7470 return false; 7471 } 7472 7473 bool 7474 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7475 &FS, 7476 const char *startSpecifier, 7477 unsigned specifierLen) { 7478 using namespace analyze_format_string; 7479 using namespace analyze_printf; 7480 7481 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7482 7483 if (FS.consumesDataArgument()) { 7484 if (atFirstArg) { 7485 atFirstArg = false; 7486 usesPositionalArgs = FS.usesPositionalArg(); 7487 } 7488 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7489 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7490 startSpecifier, specifierLen); 7491 return false; 7492 } 7493 } 7494 7495 // First check if the field width, precision, and conversion specifier 7496 // have matching data arguments. 7497 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7498 startSpecifier, specifierLen)) { 7499 return false; 7500 } 7501 7502 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7503 startSpecifier, specifierLen)) { 7504 return false; 7505 } 7506 7507 if (!CS.consumesDataArgument()) { 7508 // FIXME: Technically specifying a precision or field width here 7509 // makes no sense. Worth issuing a warning at some point. 7510 return true; 7511 } 7512 7513 // Consume the argument. 7514 unsigned argIndex = FS.getArgIndex(); 7515 if (argIndex < NumDataArgs) { 7516 // The check to see if the argIndex is valid will come later. 7517 // We set the bit here because we may exit early from this 7518 // function if we encounter some other error. 7519 CoveredArgs.set(argIndex); 7520 } 7521 7522 // FreeBSD kernel extensions. 7523 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7524 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7525 // We need at least two arguments. 7526 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7527 return false; 7528 7529 // Claim the second argument. 7530 CoveredArgs.set(argIndex + 1); 7531 7532 // Type check the first argument (int for %b, pointer for %D) 7533 const Expr *Ex = getDataArg(argIndex); 7534 const analyze_printf::ArgType &AT = 7535 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7536 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7537 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7538 EmitFormatDiagnostic( 7539 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7540 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7541 << false << Ex->getSourceRange(), 7542 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7543 getSpecifierRange(startSpecifier, specifierLen)); 7544 7545 // Type check the second argument (char * for both %b and %D) 7546 Ex = getDataArg(argIndex + 1); 7547 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7548 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7549 EmitFormatDiagnostic( 7550 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7551 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7552 << false << Ex->getSourceRange(), 7553 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7554 getSpecifierRange(startSpecifier, specifierLen)); 7555 7556 return true; 7557 } 7558 7559 // Check for using an Objective-C specific conversion specifier 7560 // in a non-ObjC literal. 7561 if (!allowsObjCArg() && CS.isObjCArg()) { 7562 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7563 specifierLen); 7564 } 7565 7566 // %P can only be used with os_log. 7567 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7568 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7569 specifierLen); 7570 } 7571 7572 // %n is not allowed with os_log. 7573 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7574 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7575 getLocationOfByte(CS.getStart()), 7576 /*IsStringLocation*/ false, 7577 getSpecifierRange(startSpecifier, specifierLen)); 7578 7579 return true; 7580 } 7581 7582 // Only scalars are allowed for os_trace. 7583 if (FSType == Sema::FST_OSTrace && 7584 (CS.getKind() == ConversionSpecifier::PArg || 7585 CS.getKind() == ConversionSpecifier::sArg || 7586 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7587 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7588 specifierLen); 7589 } 7590 7591 // Check for use of public/private annotation outside of os_log(). 7592 if (FSType != Sema::FST_OSLog) { 7593 if (FS.isPublic().isSet()) { 7594 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7595 << "public", 7596 getLocationOfByte(FS.isPublic().getPosition()), 7597 /*IsStringLocation*/ false, 7598 getSpecifierRange(startSpecifier, specifierLen)); 7599 } 7600 if (FS.isPrivate().isSet()) { 7601 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7602 << "private", 7603 getLocationOfByte(FS.isPrivate().getPosition()), 7604 /*IsStringLocation*/ false, 7605 getSpecifierRange(startSpecifier, specifierLen)); 7606 } 7607 } 7608 7609 // Check for invalid use of field width 7610 if (!FS.hasValidFieldWidth()) { 7611 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7612 startSpecifier, specifierLen); 7613 } 7614 7615 // Check for invalid use of precision 7616 if (!FS.hasValidPrecision()) { 7617 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7618 startSpecifier, specifierLen); 7619 } 7620 7621 // Precision is mandatory for %P specifier. 7622 if (CS.getKind() == ConversionSpecifier::PArg && 7623 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7624 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7625 getLocationOfByte(startSpecifier), 7626 /*IsStringLocation*/ false, 7627 getSpecifierRange(startSpecifier, specifierLen)); 7628 } 7629 7630 // Check each flag does not conflict with any other component. 7631 if (!FS.hasValidThousandsGroupingPrefix()) 7632 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7633 if (!FS.hasValidLeadingZeros()) 7634 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7635 if (!FS.hasValidPlusPrefix()) 7636 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7637 if (!FS.hasValidSpacePrefix()) 7638 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7639 if (!FS.hasValidAlternativeForm()) 7640 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7641 if (!FS.hasValidLeftJustified()) 7642 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7643 7644 // Check that flags are not ignored by another flag 7645 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7646 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7647 startSpecifier, specifierLen); 7648 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7649 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7650 startSpecifier, specifierLen); 7651 7652 // Check the length modifier is valid with the given conversion specifier. 7653 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7654 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7655 diag::warn_format_nonsensical_length); 7656 else if (!FS.hasStandardLengthModifier()) 7657 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7658 else if (!FS.hasStandardLengthConversionCombination()) 7659 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7660 diag::warn_format_non_standard_conversion_spec); 7661 7662 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7663 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7664 7665 // The remaining checks depend on the data arguments. 7666 if (HasVAListArg) 7667 return true; 7668 7669 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7670 return false; 7671 7672 const Expr *Arg = getDataArg(argIndex); 7673 if (!Arg) 7674 return true; 7675 7676 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7677 } 7678 7679 static bool requiresParensToAddCast(const Expr *E) { 7680 // FIXME: We should have a general way to reason about operator 7681 // precedence and whether parens are actually needed here. 7682 // Take care of a few common cases where they aren't. 7683 const Expr *Inside = E->IgnoreImpCasts(); 7684 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7685 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7686 7687 switch (Inside->getStmtClass()) { 7688 case Stmt::ArraySubscriptExprClass: 7689 case Stmt::CallExprClass: 7690 case Stmt::CharacterLiteralClass: 7691 case Stmt::CXXBoolLiteralExprClass: 7692 case Stmt::DeclRefExprClass: 7693 case Stmt::FloatingLiteralClass: 7694 case Stmt::IntegerLiteralClass: 7695 case Stmt::MemberExprClass: 7696 case Stmt::ObjCArrayLiteralClass: 7697 case Stmt::ObjCBoolLiteralExprClass: 7698 case Stmt::ObjCBoxedExprClass: 7699 case Stmt::ObjCDictionaryLiteralClass: 7700 case Stmt::ObjCEncodeExprClass: 7701 case Stmt::ObjCIvarRefExprClass: 7702 case Stmt::ObjCMessageExprClass: 7703 case Stmt::ObjCPropertyRefExprClass: 7704 case Stmt::ObjCStringLiteralClass: 7705 case Stmt::ObjCSubscriptRefExprClass: 7706 case Stmt::ParenExprClass: 7707 case Stmt::StringLiteralClass: 7708 case Stmt::UnaryOperatorClass: 7709 return false; 7710 default: 7711 return true; 7712 } 7713 } 7714 7715 static std::pair<QualType, StringRef> 7716 shouldNotPrintDirectly(const ASTContext &Context, 7717 QualType IntendedTy, 7718 const Expr *E) { 7719 // Use a 'while' to peel off layers of typedefs. 7720 QualType TyTy = IntendedTy; 7721 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7722 StringRef Name = UserTy->getDecl()->getName(); 7723 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7724 .Case("CFIndex", Context.getNSIntegerType()) 7725 .Case("NSInteger", Context.getNSIntegerType()) 7726 .Case("NSUInteger", Context.getNSUIntegerType()) 7727 .Case("SInt32", Context.IntTy) 7728 .Case("UInt32", Context.UnsignedIntTy) 7729 .Default(QualType()); 7730 7731 if (!CastTy.isNull()) 7732 return std::make_pair(CastTy, Name); 7733 7734 TyTy = UserTy->desugar(); 7735 } 7736 7737 // Strip parens if necessary. 7738 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7739 return shouldNotPrintDirectly(Context, 7740 PE->getSubExpr()->getType(), 7741 PE->getSubExpr()); 7742 7743 // If this is a conditional expression, then its result type is constructed 7744 // via usual arithmetic conversions and thus there might be no necessary 7745 // typedef sugar there. Recurse to operands to check for NSInteger & 7746 // Co. usage condition. 7747 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7748 QualType TrueTy, FalseTy; 7749 StringRef TrueName, FalseName; 7750 7751 std::tie(TrueTy, TrueName) = 7752 shouldNotPrintDirectly(Context, 7753 CO->getTrueExpr()->getType(), 7754 CO->getTrueExpr()); 7755 std::tie(FalseTy, FalseName) = 7756 shouldNotPrintDirectly(Context, 7757 CO->getFalseExpr()->getType(), 7758 CO->getFalseExpr()); 7759 7760 if (TrueTy == FalseTy) 7761 return std::make_pair(TrueTy, TrueName); 7762 else if (TrueTy.isNull()) 7763 return std::make_pair(FalseTy, FalseName); 7764 else if (FalseTy.isNull()) 7765 return std::make_pair(TrueTy, TrueName); 7766 } 7767 7768 return std::make_pair(QualType(), StringRef()); 7769 } 7770 7771 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 7772 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 7773 /// type do not count. 7774 static bool 7775 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 7776 QualType From = ICE->getSubExpr()->getType(); 7777 QualType To = ICE->getType(); 7778 // It's an integer promotion if the destination type is the promoted 7779 // source type. 7780 if (ICE->getCastKind() == CK_IntegralCast && 7781 From->isPromotableIntegerType() && 7782 S.Context.getPromotedIntegerType(From) == To) 7783 return true; 7784 // Look through vector types, since we do default argument promotion for 7785 // those in OpenCL. 7786 if (const auto *VecTy = From->getAs<ExtVectorType>()) 7787 From = VecTy->getElementType(); 7788 if (const auto *VecTy = To->getAs<ExtVectorType>()) 7789 To = VecTy->getElementType(); 7790 // It's a floating promotion if the source type is a lower rank. 7791 return ICE->getCastKind() == CK_FloatingCast && 7792 S.Context.getFloatingTypeOrder(From, To) < 0; 7793 } 7794 7795 bool 7796 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7797 const char *StartSpecifier, 7798 unsigned SpecifierLen, 7799 const Expr *E) { 7800 using namespace analyze_format_string; 7801 using namespace analyze_printf; 7802 7803 // Now type check the data expression that matches the 7804 // format specifier. 7805 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7806 if (!AT.isValid()) 7807 return true; 7808 7809 QualType ExprTy = E->getType(); 7810 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7811 ExprTy = TET->getUnderlyingExpr()->getType(); 7812 } 7813 7814 const analyze_printf::ArgType::MatchKind Match = 7815 AT.matchesType(S.Context, ExprTy); 7816 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 7817 if (Match == analyze_printf::ArgType::Match) 7818 return true; 7819 7820 // Look through argument promotions for our error message's reported type. 7821 // This includes the integral and floating promotions, but excludes array 7822 // and function pointer decay (seeing that an argument intended to be a 7823 // string has type 'char [6]' is probably more confusing than 'char *') and 7824 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 7825 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7826 if (isArithmeticArgumentPromotion(S, ICE)) { 7827 E = ICE->getSubExpr(); 7828 ExprTy = E->getType(); 7829 7830 // Check if we didn't match because of an implicit cast from a 'char' 7831 // or 'short' to an 'int'. This is done because printf is a varargs 7832 // function. 7833 if (ICE->getType() == S.Context.IntTy || 7834 ICE->getType() == S.Context.UnsignedIntTy) { 7835 // All further checking is done on the subexpression. 7836 if (AT.matchesType(S.Context, ExprTy)) 7837 return true; 7838 } 7839 } 7840 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7841 // Special case for 'a', which has type 'int' in C. 7842 // Note, however, that we do /not/ want to treat multibyte constants like 7843 // 'MooV' as characters! This form is deprecated but still exists. 7844 if (ExprTy == S.Context.IntTy) 7845 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 7846 ExprTy = S.Context.CharTy; 7847 } 7848 7849 // Look through enums to their underlying type. 7850 bool IsEnum = false; 7851 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7852 ExprTy = EnumTy->getDecl()->getIntegerType(); 7853 IsEnum = true; 7854 } 7855 7856 // %C in an Objective-C context prints a unichar, not a wchar_t. 7857 // If the argument is an integer of some kind, believe the %C and suggest 7858 // a cast instead of changing the conversion specifier. 7859 QualType IntendedTy = ExprTy; 7860 if (isObjCContext() && 7861 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7862 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7863 !ExprTy->isCharType()) { 7864 // 'unichar' is defined as a typedef of unsigned short, but we should 7865 // prefer using the typedef if it is visible. 7866 IntendedTy = S.Context.UnsignedShortTy; 7867 7868 // While we are here, check if the value is an IntegerLiteral that happens 7869 // to be within the valid range. 7870 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7871 const llvm::APInt &V = IL->getValue(); 7872 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7873 return true; 7874 } 7875 7876 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7877 Sema::LookupOrdinaryName); 7878 if (S.LookupName(Result, S.getCurScope())) { 7879 NamedDecl *ND = Result.getFoundDecl(); 7880 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7881 if (TD->getUnderlyingType() == IntendedTy) 7882 IntendedTy = S.Context.getTypedefType(TD); 7883 } 7884 } 7885 } 7886 7887 // Special-case some of Darwin's platform-independence types by suggesting 7888 // casts to primitive types that are known to be large enough. 7889 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7890 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7891 QualType CastTy; 7892 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7893 if (!CastTy.isNull()) { 7894 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7895 // (long in ASTContext). Only complain to pedants. 7896 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7897 (AT.isSizeT() || AT.isPtrdiffT()) && 7898 AT.matchesType(S.Context, CastTy)) 7899 Pedantic = true; 7900 IntendedTy = CastTy; 7901 ShouldNotPrintDirectly = true; 7902 } 7903 } 7904 7905 // We may be able to offer a FixItHint if it is a supported type. 7906 PrintfSpecifier fixedFS = FS; 7907 bool Success = 7908 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7909 7910 if (Success) { 7911 // Get the fix string from the fixed format specifier 7912 SmallString<16> buf; 7913 llvm::raw_svector_ostream os(buf); 7914 fixedFS.toString(os); 7915 7916 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 7917 7918 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 7919 unsigned Diag = 7920 Pedantic 7921 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7922 : diag::warn_format_conversion_argument_type_mismatch; 7923 // In this case, the specifier is wrong and should be changed to match 7924 // the argument. 7925 EmitFormatDiagnostic(S.PDiag(Diag) 7926 << AT.getRepresentativeTypeName(S.Context) 7927 << IntendedTy << IsEnum << E->getSourceRange(), 7928 E->getBeginLoc(), 7929 /*IsStringLocation*/ false, SpecRange, 7930 FixItHint::CreateReplacement(SpecRange, os.str())); 7931 } else { 7932 // The canonical type for formatting this value is different from the 7933 // actual type of the expression. (This occurs, for example, with Darwin's 7934 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 7935 // should be printed as 'long' for 64-bit compatibility.) 7936 // Rather than emitting a normal format/argument mismatch, we want to 7937 // add a cast to the recommended type (and correct the format string 7938 // if necessary). 7939 SmallString<16> CastBuf; 7940 llvm::raw_svector_ostream CastFix(CastBuf); 7941 CastFix << "("; 7942 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 7943 CastFix << ")"; 7944 7945 SmallVector<FixItHint,4> Hints; 7946 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 7947 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 7948 7949 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 7950 // If there's already a cast present, just replace it. 7951 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 7952 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 7953 7954 } else if (!requiresParensToAddCast(E)) { 7955 // If the expression has high enough precedence, 7956 // just write the C-style cast. 7957 Hints.push_back( 7958 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7959 } else { 7960 // Otherwise, add parens around the expression as well as the cast. 7961 CastFix << "("; 7962 Hints.push_back( 7963 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7964 7965 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 7966 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 7967 } 7968 7969 if (ShouldNotPrintDirectly) { 7970 // The expression has a type that should not be printed directly. 7971 // We extract the name from the typedef because we don't want to show 7972 // the underlying type in the diagnostic. 7973 StringRef Name; 7974 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 7975 Name = TypedefTy->getDecl()->getName(); 7976 else 7977 Name = CastTyName; 7978 unsigned Diag = Pedantic 7979 ? diag::warn_format_argument_needs_cast_pedantic 7980 : diag::warn_format_argument_needs_cast; 7981 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 7982 << E->getSourceRange(), 7983 E->getBeginLoc(), /*IsStringLocation=*/false, 7984 SpecRange, Hints); 7985 } else { 7986 // In this case, the expression could be printed using a different 7987 // specifier, but we've decided that the specifier is probably correct 7988 // and we should cast instead. Just use the normal warning message. 7989 EmitFormatDiagnostic( 7990 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7991 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 7992 << E->getSourceRange(), 7993 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 7994 } 7995 } 7996 } else { 7997 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 7998 SpecifierLen); 7999 // Since the warning for passing non-POD types to variadic functions 8000 // was deferred until now, we emit a warning for non-POD 8001 // arguments here. 8002 switch (S.isValidVarArgType(ExprTy)) { 8003 case Sema::VAK_Valid: 8004 case Sema::VAK_ValidInCXX11: { 8005 unsigned Diag = 8006 Pedantic 8007 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8008 : diag::warn_format_conversion_argument_type_mismatch; 8009 8010 EmitFormatDiagnostic( 8011 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8012 << IsEnum << CSR << E->getSourceRange(), 8013 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8014 break; 8015 } 8016 case Sema::VAK_Undefined: 8017 case Sema::VAK_MSVCUndefined: 8018 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8019 << S.getLangOpts().CPlusPlus11 << ExprTy 8020 << CallType 8021 << AT.getRepresentativeTypeName(S.Context) << CSR 8022 << E->getSourceRange(), 8023 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8024 checkForCStrMembers(AT, E); 8025 break; 8026 8027 case Sema::VAK_Invalid: 8028 if (ExprTy->isObjCObjectType()) 8029 EmitFormatDiagnostic( 8030 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8031 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8032 << AT.getRepresentativeTypeName(S.Context) << CSR 8033 << E->getSourceRange(), 8034 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8035 else 8036 // FIXME: If this is an initializer list, suggest removing the braces 8037 // or inserting a cast to the target type. 8038 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8039 << isa<InitListExpr>(E) << ExprTy << CallType 8040 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8041 break; 8042 } 8043 8044 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8045 "format string specifier index out of range"); 8046 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8047 } 8048 8049 return true; 8050 } 8051 8052 //===--- CHECK: Scanf format string checking ------------------------------===// 8053 8054 namespace { 8055 8056 class CheckScanfHandler : public CheckFormatHandler { 8057 public: 8058 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8059 const Expr *origFormatExpr, Sema::FormatStringType type, 8060 unsigned firstDataArg, unsigned numDataArgs, 8061 const char *beg, bool hasVAListArg, 8062 ArrayRef<const Expr *> Args, unsigned formatIdx, 8063 bool inFunctionCall, Sema::VariadicCallType CallType, 8064 llvm::SmallBitVector &CheckedVarArgs, 8065 UncoveredArgHandler &UncoveredArg) 8066 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8067 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8068 inFunctionCall, CallType, CheckedVarArgs, 8069 UncoveredArg) {} 8070 8071 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8072 const char *startSpecifier, 8073 unsigned specifierLen) override; 8074 8075 bool HandleInvalidScanfConversionSpecifier( 8076 const analyze_scanf::ScanfSpecifier &FS, 8077 const char *startSpecifier, 8078 unsigned specifierLen) override; 8079 8080 void HandleIncompleteScanList(const char *start, const char *end) override; 8081 }; 8082 8083 } // namespace 8084 8085 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8086 const char *end) { 8087 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8088 getLocationOfByte(end), /*IsStringLocation*/true, 8089 getSpecifierRange(start, end - start)); 8090 } 8091 8092 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8093 const analyze_scanf::ScanfSpecifier &FS, 8094 const char *startSpecifier, 8095 unsigned specifierLen) { 8096 const analyze_scanf::ScanfConversionSpecifier &CS = 8097 FS.getConversionSpecifier(); 8098 8099 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8100 getLocationOfByte(CS.getStart()), 8101 startSpecifier, specifierLen, 8102 CS.getStart(), CS.getLength()); 8103 } 8104 8105 bool CheckScanfHandler::HandleScanfSpecifier( 8106 const analyze_scanf::ScanfSpecifier &FS, 8107 const char *startSpecifier, 8108 unsigned specifierLen) { 8109 using namespace analyze_scanf; 8110 using namespace analyze_format_string; 8111 8112 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8113 8114 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8115 // be used to decide if we are using positional arguments consistently. 8116 if (FS.consumesDataArgument()) { 8117 if (atFirstArg) { 8118 atFirstArg = false; 8119 usesPositionalArgs = FS.usesPositionalArg(); 8120 } 8121 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8122 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8123 startSpecifier, specifierLen); 8124 return false; 8125 } 8126 } 8127 8128 // Check if the field with is non-zero. 8129 const OptionalAmount &Amt = FS.getFieldWidth(); 8130 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8131 if (Amt.getConstantAmount() == 0) { 8132 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8133 Amt.getConstantLength()); 8134 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8135 getLocationOfByte(Amt.getStart()), 8136 /*IsStringLocation*/true, R, 8137 FixItHint::CreateRemoval(R)); 8138 } 8139 } 8140 8141 if (!FS.consumesDataArgument()) { 8142 // FIXME: Technically specifying a precision or field width here 8143 // makes no sense. Worth issuing a warning at some point. 8144 return true; 8145 } 8146 8147 // Consume the argument. 8148 unsigned argIndex = FS.getArgIndex(); 8149 if (argIndex < NumDataArgs) { 8150 // The check to see if the argIndex is valid will come later. 8151 // We set the bit here because we may exit early from this 8152 // function if we encounter some other error. 8153 CoveredArgs.set(argIndex); 8154 } 8155 8156 // Check the length modifier is valid with the given conversion specifier. 8157 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 8158 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8159 diag::warn_format_nonsensical_length); 8160 else if (!FS.hasStandardLengthModifier()) 8161 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8162 else if (!FS.hasStandardLengthConversionCombination()) 8163 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8164 diag::warn_format_non_standard_conversion_spec); 8165 8166 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8167 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8168 8169 // The remaining checks depend on the data arguments. 8170 if (HasVAListArg) 8171 return true; 8172 8173 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8174 return false; 8175 8176 // Check that the argument type matches the format specifier. 8177 const Expr *Ex = getDataArg(argIndex); 8178 if (!Ex) 8179 return true; 8180 8181 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8182 8183 if (!AT.isValid()) { 8184 return true; 8185 } 8186 8187 analyze_format_string::ArgType::MatchKind Match = 8188 AT.matchesType(S.Context, Ex->getType()); 8189 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8190 if (Match == analyze_format_string::ArgType::Match) 8191 return true; 8192 8193 ScanfSpecifier fixedFS = FS; 8194 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8195 S.getLangOpts(), S.Context); 8196 8197 unsigned Diag = 8198 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8199 : diag::warn_format_conversion_argument_type_mismatch; 8200 8201 if (Success) { 8202 // Get the fix string from the fixed format specifier. 8203 SmallString<128> buf; 8204 llvm::raw_svector_ostream os(buf); 8205 fixedFS.toString(os); 8206 8207 EmitFormatDiagnostic( 8208 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8209 << Ex->getType() << false << Ex->getSourceRange(), 8210 Ex->getBeginLoc(), 8211 /*IsStringLocation*/ false, 8212 getSpecifierRange(startSpecifier, specifierLen), 8213 FixItHint::CreateReplacement( 8214 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8215 } else { 8216 EmitFormatDiagnostic(S.PDiag(Diag) 8217 << AT.getRepresentativeTypeName(S.Context) 8218 << Ex->getType() << false << Ex->getSourceRange(), 8219 Ex->getBeginLoc(), 8220 /*IsStringLocation*/ false, 8221 getSpecifierRange(startSpecifier, specifierLen)); 8222 } 8223 8224 return true; 8225 } 8226 8227 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8228 const Expr *OrigFormatExpr, 8229 ArrayRef<const Expr *> Args, 8230 bool HasVAListArg, unsigned format_idx, 8231 unsigned firstDataArg, 8232 Sema::FormatStringType Type, 8233 bool inFunctionCall, 8234 Sema::VariadicCallType CallType, 8235 llvm::SmallBitVector &CheckedVarArgs, 8236 UncoveredArgHandler &UncoveredArg) { 8237 // CHECK: is the format string a wide literal? 8238 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8239 CheckFormatHandler::EmitFormatDiagnostic( 8240 S, inFunctionCall, Args[format_idx], 8241 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8242 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8243 return; 8244 } 8245 8246 // Str - The format string. NOTE: this is NOT null-terminated! 8247 StringRef StrRef = FExpr->getString(); 8248 const char *Str = StrRef.data(); 8249 // Account for cases where the string literal is truncated in a declaration. 8250 const ConstantArrayType *T = 8251 S.Context.getAsConstantArrayType(FExpr->getType()); 8252 assert(T && "String literal not of constant array type!"); 8253 size_t TypeSize = T->getSize().getZExtValue(); 8254 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8255 const unsigned numDataArgs = Args.size() - firstDataArg; 8256 8257 // Emit a warning if the string literal is truncated and does not contain an 8258 // embedded null character. 8259 if (TypeSize <= StrRef.size() && 8260 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8261 CheckFormatHandler::EmitFormatDiagnostic( 8262 S, inFunctionCall, Args[format_idx], 8263 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8264 FExpr->getBeginLoc(), 8265 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8266 return; 8267 } 8268 8269 // CHECK: empty format string? 8270 if (StrLen == 0 && numDataArgs > 0) { 8271 CheckFormatHandler::EmitFormatDiagnostic( 8272 S, inFunctionCall, Args[format_idx], 8273 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8274 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8275 return; 8276 } 8277 8278 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8279 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8280 Type == Sema::FST_OSTrace) { 8281 CheckPrintfHandler H( 8282 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8283 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8284 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8285 CheckedVarArgs, UncoveredArg); 8286 8287 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8288 S.getLangOpts(), 8289 S.Context.getTargetInfo(), 8290 Type == Sema::FST_FreeBSDKPrintf)) 8291 H.DoneProcessing(); 8292 } else if (Type == Sema::FST_Scanf) { 8293 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8294 numDataArgs, Str, HasVAListArg, Args, format_idx, 8295 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8296 8297 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8298 S.getLangOpts(), 8299 S.Context.getTargetInfo())) 8300 H.DoneProcessing(); 8301 } // TODO: handle other formats 8302 } 8303 8304 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8305 // Str - The format string. NOTE: this is NOT null-terminated! 8306 StringRef StrRef = FExpr->getString(); 8307 const char *Str = StrRef.data(); 8308 // Account for cases where the string literal is truncated in a declaration. 8309 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8310 assert(T && "String literal not of constant array type!"); 8311 size_t TypeSize = T->getSize().getZExtValue(); 8312 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8313 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8314 getLangOpts(), 8315 Context.getTargetInfo()); 8316 } 8317 8318 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8319 8320 // Returns the related absolute value function that is larger, of 0 if one 8321 // does not exist. 8322 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8323 switch (AbsFunction) { 8324 default: 8325 return 0; 8326 8327 case Builtin::BI__builtin_abs: 8328 return Builtin::BI__builtin_labs; 8329 case Builtin::BI__builtin_labs: 8330 return Builtin::BI__builtin_llabs; 8331 case Builtin::BI__builtin_llabs: 8332 return 0; 8333 8334 case Builtin::BI__builtin_fabsf: 8335 return Builtin::BI__builtin_fabs; 8336 case Builtin::BI__builtin_fabs: 8337 return Builtin::BI__builtin_fabsl; 8338 case Builtin::BI__builtin_fabsl: 8339 return 0; 8340 8341 case Builtin::BI__builtin_cabsf: 8342 return Builtin::BI__builtin_cabs; 8343 case Builtin::BI__builtin_cabs: 8344 return Builtin::BI__builtin_cabsl; 8345 case Builtin::BI__builtin_cabsl: 8346 return 0; 8347 8348 case Builtin::BIabs: 8349 return Builtin::BIlabs; 8350 case Builtin::BIlabs: 8351 return Builtin::BIllabs; 8352 case Builtin::BIllabs: 8353 return 0; 8354 8355 case Builtin::BIfabsf: 8356 return Builtin::BIfabs; 8357 case Builtin::BIfabs: 8358 return Builtin::BIfabsl; 8359 case Builtin::BIfabsl: 8360 return 0; 8361 8362 case Builtin::BIcabsf: 8363 return Builtin::BIcabs; 8364 case Builtin::BIcabs: 8365 return Builtin::BIcabsl; 8366 case Builtin::BIcabsl: 8367 return 0; 8368 } 8369 } 8370 8371 // Returns the argument type of the absolute value function. 8372 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8373 unsigned AbsType) { 8374 if (AbsType == 0) 8375 return QualType(); 8376 8377 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8378 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8379 if (Error != ASTContext::GE_None) 8380 return QualType(); 8381 8382 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8383 if (!FT) 8384 return QualType(); 8385 8386 if (FT->getNumParams() != 1) 8387 return QualType(); 8388 8389 return FT->getParamType(0); 8390 } 8391 8392 // Returns the best absolute value function, or zero, based on type and 8393 // current absolute value function. 8394 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8395 unsigned AbsFunctionKind) { 8396 unsigned BestKind = 0; 8397 uint64_t ArgSize = Context.getTypeSize(ArgType); 8398 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8399 Kind = getLargerAbsoluteValueFunction(Kind)) { 8400 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8401 if (Context.getTypeSize(ParamType) >= ArgSize) { 8402 if (BestKind == 0) 8403 BestKind = Kind; 8404 else if (Context.hasSameType(ParamType, ArgType)) { 8405 BestKind = Kind; 8406 break; 8407 } 8408 } 8409 } 8410 return BestKind; 8411 } 8412 8413 enum AbsoluteValueKind { 8414 AVK_Integer, 8415 AVK_Floating, 8416 AVK_Complex 8417 }; 8418 8419 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8420 if (T->isIntegralOrEnumerationType()) 8421 return AVK_Integer; 8422 if (T->isRealFloatingType()) 8423 return AVK_Floating; 8424 if (T->isAnyComplexType()) 8425 return AVK_Complex; 8426 8427 llvm_unreachable("Type not integer, floating, or complex"); 8428 } 8429 8430 // Changes the absolute value function to a different type. Preserves whether 8431 // the function is a builtin. 8432 static unsigned changeAbsFunction(unsigned AbsKind, 8433 AbsoluteValueKind ValueKind) { 8434 switch (ValueKind) { 8435 case AVK_Integer: 8436 switch (AbsKind) { 8437 default: 8438 return 0; 8439 case Builtin::BI__builtin_fabsf: 8440 case Builtin::BI__builtin_fabs: 8441 case Builtin::BI__builtin_fabsl: 8442 case Builtin::BI__builtin_cabsf: 8443 case Builtin::BI__builtin_cabs: 8444 case Builtin::BI__builtin_cabsl: 8445 return Builtin::BI__builtin_abs; 8446 case Builtin::BIfabsf: 8447 case Builtin::BIfabs: 8448 case Builtin::BIfabsl: 8449 case Builtin::BIcabsf: 8450 case Builtin::BIcabs: 8451 case Builtin::BIcabsl: 8452 return Builtin::BIabs; 8453 } 8454 case AVK_Floating: 8455 switch (AbsKind) { 8456 default: 8457 return 0; 8458 case Builtin::BI__builtin_abs: 8459 case Builtin::BI__builtin_labs: 8460 case Builtin::BI__builtin_llabs: 8461 case Builtin::BI__builtin_cabsf: 8462 case Builtin::BI__builtin_cabs: 8463 case Builtin::BI__builtin_cabsl: 8464 return Builtin::BI__builtin_fabsf; 8465 case Builtin::BIabs: 8466 case Builtin::BIlabs: 8467 case Builtin::BIllabs: 8468 case Builtin::BIcabsf: 8469 case Builtin::BIcabs: 8470 case Builtin::BIcabsl: 8471 return Builtin::BIfabsf; 8472 } 8473 case AVK_Complex: 8474 switch (AbsKind) { 8475 default: 8476 return 0; 8477 case Builtin::BI__builtin_abs: 8478 case Builtin::BI__builtin_labs: 8479 case Builtin::BI__builtin_llabs: 8480 case Builtin::BI__builtin_fabsf: 8481 case Builtin::BI__builtin_fabs: 8482 case Builtin::BI__builtin_fabsl: 8483 return Builtin::BI__builtin_cabsf; 8484 case Builtin::BIabs: 8485 case Builtin::BIlabs: 8486 case Builtin::BIllabs: 8487 case Builtin::BIfabsf: 8488 case Builtin::BIfabs: 8489 case Builtin::BIfabsl: 8490 return Builtin::BIcabsf; 8491 } 8492 } 8493 llvm_unreachable("Unable to convert function"); 8494 } 8495 8496 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8497 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8498 if (!FnInfo) 8499 return 0; 8500 8501 switch (FDecl->getBuiltinID()) { 8502 default: 8503 return 0; 8504 case Builtin::BI__builtin_abs: 8505 case Builtin::BI__builtin_fabs: 8506 case Builtin::BI__builtin_fabsf: 8507 case Builtin::BI__builtin_fabsl: 8508 case Builtin::BI__builtin_labs: 8509 case Builtin::BI__builtin_llabs: 8510 case Builtin::BI__builtin_cabs: 8511 case Builtin::BI__builtin_cabsf: 8512 case Builtin::BI__builtin_cabsl: 8513 case Builtin::BIabs: 8514 case Builtin::BIlabs: 8515 case Builtin::BIllabs: 8516 case Builtin::BIfabs: 8517 case Builtin::BIfabsf: 8518 case Builtin::BIfabsl: 8519 case Builtin::BIcabs: 8520 case Builtin::BIcabsf: 8521 case Builtin::BIcabsl: 8522 return FDecl->getBuiltinID(); 8523 } 8524 llvm_unreachable("Unknown Builtin type"); 8525 } 8526 8527 // If the replacement is valid, emit a note with replacement function. 8528 // Additionally, suggest including the proper header if not already included. 8529 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8530 unsigned AbsKind, QualType ArgType) { 8531 bool EmitHeaderHint = true; 8532 const char *HeaderName = nullptr; 8533 const char *FunctionName = nullptr; 8534 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8535 FunctionName = "std::abs"; 8536 if (ArgType->isIntegralOrEnumerationType()) { 8537 HeaderName = "cstdlib"; 8538 } else if (ArgType->isRealFloatingType()) { 8539 HeaderName = "cmath"; 8540 } else { 8541 llvm_unreachable("Invalid Type"); 8542 } 8543 8544 // Lookup all std::abs 8545 if (NamespaceDecl *Std = S.getStdNamespace()) { 8546 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8547 R.suppressDiagnostics(); 8548 S.LookupQualifiedName(R, Std); 8549 8550 for (const auto *I : R) { 8551 const FunctionDecl *FDecl = nullptr; 8552 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8553 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8554 } else { 8555 FDecl = dyn_cast<FunctionDecl>(I); 8556 } 8557 if (!FDecl) 8558 continue; 8559 8560 // Found std::abs(), check that they are the right ones. 8561 if (FDecl->getNumParams() != 1) 8562 continue; 8563 8564 // Check that the parameter type can handle the argument. 8565 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8566 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8567 S.Context.getTypeSize(ArgType) <= 8568 S.Context.getTypeSize(ParamType)) { 8569 // Found a function, don't need the header hint. 8570 EmitHeaderHint = false; 8571 break; 8572 } 8573 } 8574 } 8575 } else { 8576 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8577 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8578 8579 if (HeaderName) { 8580 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8581 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8582 R.suppressDiagnostics(); 8583 S.LookupName(R, S.getCurScope()); 8584 8585 if (R.isSingleResult()) { 8586 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8587 if (FD && FD->getBuiltinID() == AbsKind) { 8588 EmitHeaderHint = false; 8589 } else { 8590 return; 8591 } 8592 } else if (!R.empty()) { 8593 return; 8594 } 8595 } 8596 } 8597 8598 S.Diag(Loc, diag::note_replace_abs_function) 8599 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8600 8601 if (!HeaderName) 8602 return; 8603 8604 if (!EmitHeaderHint) 8605 return; 8606 8607 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8608 << FunctionName; 8609 } 8610 8611 template <std::size_t StrLen> 8612 static bool IsStdFunction(const FunctionDecl *FDecl, 8613 const char (&Str)[StrLen]) { 8614 if (!FDecl) 8615 return false; 8616 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8617 return false; 8618 if (!FDecl->isInStdNamespace()) 8619 return false; 8620 8621 return true; 8622 } 8623 8624 // Warn when using the wrong abs() function. 8625 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8626 const FunctionDecl *FDecl) { 8627 if (Call->getNumArgs() != 1) 8628 return; 8629 8630 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8631 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8632 if (AbsKind == 0 && !IsStdAbs) 8633 return; 8634 8635 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8636 QualType ParamType = Call->getArg(0)->getType(); 8637 8638 // Unsigned types cannot be negative. Suggest removing the absolute value 8639 // function call. 8640 if (ArgType->isUnsignedIntegerType()) { 8641 const char *FunctionName = 8642 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8643 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8644 Diag(Call->getExprLoc(), diag::note_remove_abs) 8645 << FunctionName 8646 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8647 return; 8648 } 8649 8650 // Taking the absolute value of a pointer is very suspicious, they probably 8651 // wanted to index into an array, dereference a pointer, call a function, etc. 8652 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8653 unsigned DiagType = 0; 8654 if (ArgType->isFunctionType()) 8655 DiagType = 1; 8656 else if (ArgType->isArrayType()) 8657 DiagType = 2; 8658 8659 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8660 return; 8661 } 8662 8663 // std::abs has overloads which prevent most of the absolute value problems 8664 // from occurring. 8665 if (IsStdAbs) 8666 return; 8667 8668 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8669 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8670 8671 // The argument and parameter are the same kind. Check if they are the right 8672 // size. 8673 if (ArgValueKind == ParamValueKind) { 8674 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8675 return; 8676 8677 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8678 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8679 << FDecl << ArgType << ParamType; 8680 8681 if (NewAbsKind == 0) 8682 return; 8683 8684 emitReplacement(*this, Call->getExprLoc(), 8685 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8686 return; 8687 } 8688 8689 // ArgValueKind != ParamValueKind 8690 // The wrong type of absolute value function was used. Attempt to find the 8691 // proper one. 8692 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8693 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8694 if (NewAbsKind == 0) 8695 return; 8696 8697 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8698 << FDecl << ParamValueKind << ArgValueKind; 8699 8700 emitReplacement(*this, Call->getExprLoc(), 8701 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8702 } 8703 8704 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8705 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8706 const FunctionDecl *FDecl) { 8707 if (!Call || !FDecl) return; 8708 8709 // Ignore template specializations and macros. 8710 if (inTemplateInstantiation()) return; 8711 if (Call->getExprLoc().isMacroID()) return; 8712 8713 // Only care about the one template argument, two function parameter std::max 8714 if (Call->getNumArgs() != 2) return; 8715 if (!IsStdFunction(FDecl, "max")) return; 8716 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8717 if (!ArgList) return; 8718 if (ArgList->size() != 1) return; 8719 8720 // Check that template type argument is unsigned integer. 8721 const auto& TA = ArgList->get(0); 8722 if (TA.getKind() != TemplateArgument::Type) return; 8723 QualType ArgType = TA.getAsType(); 8724 if (!ArgType->isUnsignedIntegerType()) return; 8725 8726 // See if either argument is a literal zero. 8727 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8728 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8729 if (!MTE) return false; 8730 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8731 if (!Num) return false; 8732 if (Num->getValue() != 0) return false; 8733 return true; 8734 }; 8735 8736 const Expr *FirstArg = Call->getArg(0); 8737 const Expr *SecondArg = Call->getArg(1); 8738 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8739 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8740 8741 // Only warn when exactly one argument is zero. 8742 if (IsFirstArgZero == IsSecondArgZero) return; 8743 8744 SourceRange FirstRange = FirstArg->getSourceRange(); 8745 SourceRange SecondRange = SecondArg->getSourceRange(); 8746 8747 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8748 8749 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8750 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8751 8752 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8753 SourceRange RemovalRange; 8754 if (IsFirstArgZero) { 8755 RemovalRange = SourceRange(FirstRange.getBegin(), 8756 SecondRange.getBegin().getLocWithOffset(-1)); 8757 } else { 8758 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8759 SecondRange.getEnd()); 8760 } 8761 8762 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8763 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8764 << FixItHint::CreateRemoval(RemovalRange); 8765 } 8766 8767 //===--- CHECK: Standard memory functions ---------------------------------===// 8768 8769 /// Takes the expression passed to the size_t parameter of functions 8770 /// such as memcmp, strncat, etc and warns if it's a comparison. 8771 /// 8772 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8773 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8774 IdentifierInfo *FnName, 8775 SourceLocation FnLoc, 8776 SourceLocation RParenLoc) { 8777 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8778 if (!Size) 8779 return false; 8780 8781 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8782 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8783 return false; 8784 8785 SourceRange SizeRange = Size->getSourceRange(); 8786 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8787 << SizeRange << FnName; 8788 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8789 << FnName 8790 << FixItHint::CreateInsertion( 8791 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8792 << FixItHint::CreateRemoval(RParenLoc); 8793 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8794 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8795 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8796 ")"); 8797 8798 return true; 8799 } 8800 8801 /// Determine whether the given type is or contains a dynamic class type 8802 /// (e.g., whether it has a vtable). 8803 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8804 bool &IsContained) { 8805 // Look through array types while ignoring qualifiers. 8806 const Type *Ty = T->getBaseElementTypeUnsafe(); 8807 IsContained = false; 8808 8809 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8810 RD = RD ? RD->getDefinition() : nullptr; 8811 if (!RD || RD->isInvalidDecl()) 8812 return nullptr; 8813 8814 if (RD->isDynamicClass()) 8815 return RD; 8816 8817 // Check all the fields. If any bases were dynamic, the class is dynamic. 8818 // It's impossible for a class to transitively contain itself by value, so 8819 // infinite recursion is impossible. 8820 for (auto *FD : RD->fields()) { 8821 bool SubContained; 8822 if (const CXXRecordDecl *ContainedRD = 8823 getContainedDynamicClass(FD->getType(), SubContained)) { 8824 IsContained = true; 8825 return ContainedRD; 8826 } 8827 } 8828 8829 return nullptr; 8830 } 8831 8832 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8833 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8834 if (Unary->getKind() == UETT_SizeOf) 8835 return Unary; 8836 return nullptr; 8837 } 8838 8839 /// If E is a sizeof expression, returns its argument expression, 8840 /// otherwise returns NULL. 8841 static const Expr *getSizeOfExprArg(const Expr *E) { 8842 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8843 if (!SizeOf->isArgumentType()) 8844 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8845 return nullptr; 8846 } 8847 8848 /// If E is a sizeof expression, returns its argument type. 8849 static QualType getSizeOfArgType(const Expr *E) { 8850 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8851 return SizeOf->getTypeOfArgument(); 8852 return QualType(); 8853 } 8854 8855 namespace { 8856 8857 struct SearchNonTrivialToInitializeField 8858 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8859 using Super = 8860 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8861 8862 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8863 8864 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8865 SourceLocation SL) { 8866 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8867 asDerived().visitArray(PDIK, AT, SL); 8868 return; 8869 } 8870 8871 Super::visitWithKind(PDIK, FT, SL); 8872 } 8873 8874 void visitARCStrong(QualType FT, SourceLocation SL) { 8875 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8876 } 8877 void visitARCWeak(QualType FT, SourceLocation SL) { 8878 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8879 } 8880 void visitStruct(QualType FT, SourceLocation SL) { 8881 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8882 visit(FD->getType(), FD->getLocation()); 8883 } 8884 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8885 const ArrayType *AT, SourceLocation SL) { 8886 visit(getContext().getBaseElementType(AT), SL); 8887 } 8888 void visitTrivial(QualType FT, SourceLocation SL) {} 8889 8890 static void diag(QualType RT, const Expr *E, Sema &S) { 8891 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 8892 } 8893 8894 ASTContext &getContext() { return S.getASTContext(); } 8895 8896 const Expr *E; 8897 Sema &S; 8898 }; 8899 8900 struct SearchNonTrivialToCopyField 8901 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 8902 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 8903 8904 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 8905 8906 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 8907 SourceLocation SL) { 8908 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8909 asDerived().visitArray(PCK, AT, SL); 8910 return; 8911 } 8912 8913 Super::visitWithKind(PCK, FT, SL); 8914 } 8915 8916 void visitARCStrong(QualType FT, SourceLocation SL) { 8917 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8918 } 8919 void visitARCWeak(QualType FT, SourceLocation SL) { 8920 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8921 } 8922 void visitStruct(QualType FT, SourceLocation SL) { 8923 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8924 visit(FD->getType(), FD->getLocation()); 8925 } 8926 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 8927 SourceLocation SL) { 8928 visit(getContext().getBaseElementType(AT), SL); 8929 } 8930 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 8931 SourceLocation SL) {} 8932 void visitTrivial(QualType FT, SourceLocation SL) {} 8933 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 8934 8935 static void diag(QualType RT, const Expr *E, Sema &S) { 8936 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 8937 } 8938 8939 ASTContext &getContext() { return S.getASTContext(); } 8940 8941 const Expr *E; 8942 Sema &S; 8943 }; 8944 8945 } 8946 8947 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 8948 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 8949 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 8950 8951 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 8952 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 8953 return false; 8954 8955 return doesExprLikelyComputeSize(BO->getLHS()) || 8956 doesExprLikelyComputeSize(BO->getRHS()); 8957 } 8958 8959 return getAsSizeOfExpr(SizeofExpr) != nullptr; 8960 } 8961 8962 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 8963 /// 8964 /// \code 8965 /// #define MACRO 0 8966 /// foo(MACRO); 8967 /// foo(0); 8968 /// \endcode 8969 /// 8970 /// This should return true for the first call to foo, but not for the second 8971 /// (regardless of whether foo is a macro or function). 8972 static bool isArgumentExpandedFromMacro(SourceManager &SM, 8973 SourceLocation CallLoc, 8974 SourceLocation ArgLoc) { 8975 if (!CallLoc.isMacroID()) 8976 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 8977 8978 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 8979 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 8980 } 8981 8982 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 8983 /// last two arguments transposed. 8984 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 8985 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 8986 return; 8987 8988 const Expr *SizeArg = 8989 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 8990 8991 auto isLiteralZero = [](const Expr *E) { 8992 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 8993 }; 8994 8995 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 8996 SourceLocation CallLoc = Call->getRParenLoc(); 8997 SourceManager &SM = S.getSourceManager(); 8998 if (isLiteralZero(SizeArg) && 8999 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9000 9001 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9002 9003 // Some platforms #define bzero to __builtin_memset. See if this is the 9004 // case, and if so, emit a better diagnostic. 9005 if (BId == Builtin::BIbzero || 9006 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9007 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9008 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9009 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9010 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9011 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9012 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9013 } 9014 return; 9015 } 9016 9017 // If the second argument to a memset is a sizeof expression and the third 9018 // isn't, this is also likely an error. This should catch 9019 // 'memset(buf, sizeof(buf), 0xff)'. 9020 if (BId == Builtin::BImemset && 9021 doesExprLikelyComputeSize(Call->getArg(1)) && 9022 !doesExprLikelyComputeSize(Call->getArg(2))) { 9023 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9024 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9025 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9026 return; 9027 } 9028 } 9029 9030 /// Check for dangerous or invalid arguments to memset(). 9031 /// 9032 /// This issues warnings on known problematic, dangerous or unspecified 9033 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9034 /// function calls. 9035 /// 9036 /// \param Call The call expression to diagnose. 9037 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9038 unsigned BId, 9039 IdentifierInfo *FnName) { 9040 assert(BId != 0); 9041 9042 // It is possible to have a non-standard definition of memset. Validate 9043 // we have enough arguments, and if not, abort further checking. 9044 unsigned ExpectedNumArgs = 9045 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9046 if (Call->getNumArgs() < ExpectedNumArgs) 9047 return; 9048 9049 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9050 BId == Builtin::BIstrndup ? 1 : 2); 9051 unsigned LenArg = 9052 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9053 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9054 9055 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9056 Call->getBeginLoc(), Call->getRParenLoc())) 9057 return; 9058 9059 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9060 CheckMemaccessSize(*this, BId, Call); 9061 9062 // We have special checking when the length is a sizeof expression. 9063 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9064 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9065 llvm::FoldingSetNodeID SizeOfArgID; 9066 9067 // Although widely used, 'bzero' is not a standard function. Be more strict 9068 // with the argument types before allowing diagnostics and only allow the 9069 // form bzero(ptr, sizeof(...)). 9070 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9071 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9072 return; 9073 9074 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9075 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9076 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9077 9078 QualType DestTy = Dest->getType(); 9079 QualType PointeeTy; 9080 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9081 PointeeTy = DestPtrTy->getPointeeType(); 9082 9083 // Never warn about void type pointers. This can be used to suppress 9084 // false positives. 9085 if (PointeeTy->isVoidType()) 9086 continue; 9087 9088 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9089 // actually comparing the expressions for equality. Because computing the 9090 // expression IDs can be expensive, we only do this if the diagnostic is 9091 // enabled. 9092 if (SizeOfArg && 9093 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9094 SizeOfArg->getExprLoc())) { 9095 // We only compute IDs for expressions if the warning is enabled, and 9096 // cache the sizeof arg's ID. 9097 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9098 SizeOfArg->Profile(SizeOfArgID, Context, true); 9099 llvm::FoldingSetNodeID DestID; 9100 Dest->Profile(DestID, Context, true); 9101 if (DestID == SizeOfArgID) { 9102 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9103 // over sizeof(src) as well. 9104 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9105 StringRef ReadableName = FnName->getName(); 9106 9107 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9108 if (UnaryOp->getOpcode() == UO_AddrOf) 9109 ActionIdx = 1; // If its an address-of operator, just remove it. 9110 if (!PointeeTy->isIncompleteType() && 9111 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9112 ActionIdx = 2; // If the pointee's size is sizeof(char), 9113 // suggest an explicit length. 9114 9115 // If the function is defined as a builtin macro, do not show macro 9116 // expansion. 9117 SourceLocation SL = SizeOfArg->getExprLoc(); 9118 SourceRange DSR = Dest->getSourceRange(); 9119 SourceRange SSR = SizeOfArg->getSourceRange(); 9120 SourceManager &SM = getSourceManager(); 9121 9122 if (SM.isMacroArgExpansion(SL)) { 9123 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9124 SL = SM.getSpellingLoc(SL); 9125 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9126 SM.getSpellingLoc(DSR.getEnd())); 9127 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9128 SM.getSpellingLoc(SSR.getEnd())); 9129 } 9130 9131 DiagRuntimeBehavior(SL, SizeOfArg, 9132 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9133 << ReadableName 9134 << PointeeTy 9135 << DestTy 9136 << DSR 9137 << SSR); 9138 DiagRuntimeBehavior(SL, SizeOfArg, 9139 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9140 << ActionIdx 9141 << SSR); 9142 9143 break; 9144 } 9145 } 9146 9147 // Also check for cases where the sizeof argument is the exact same 9148 // type as the memory argument, and where it points to a user-defined 9149 // record type. 9150 if (SizeOfArgTy != QualType()) { 9151 if (PointeeTy->isRecordType() && 9152 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9153 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9154 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9155 << FnName << SizeOfArgTy << ArgIdx 9156 << PointeeTy << Dest->getSourceRange() 9157 << LenExpr->getSourceRange()); 9158 break; 9159 } 9160 } 9161 } else if (DestTy->isArrayType()) { 9162 PointeeTy = DestTy; 9163 } 9164 9165 if (PointeeTy == QualType()) 9166 continue; 9167 9168 // Always complain about dynamic classes. 9169 bool IsContained; 9170 if (const CXXRecordDecl *ContainedRD = 9171 getContainedDynamicClass(PointeeTy, IsContained)) { 9172 9173 unsigned OperationType = 0; 9174 // "overwritten" if we're warning about the destination for any call 9175 // but memcmp; otherwise a verb appropriate to the call. 9176 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 9177 if (BId == Builtin::BImemcpy) 9178 OperationType = 1; 9179 else if(BId == Builtin::BImemmove) 9180 OperationType = 2; 9181 else if (BId == Builtin::BImemcmp) 9182 OperationType = 3; 9183 } 9184 9185 DiagRuntimeBehavior( 9186 Dest->getExprLoc(), Dest, 9187 PDiag(diag::warn_dyn_class_memaccess) 9188 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 9189 << FnName << IsContained << ContainedRD << OperationType 9190 << Call->getCallee()->getSourceRange()); 9191 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9192 BId != Builtin::BImemset) 9193 DiagRuntimeBehavior( 9194 Dest->getExprLoc(), Dest, 9195 PDiag(diag::warn_arc_object_memaccess) 9196 << ArgIdx << FnName << PointeeTy 9197 << Call->getCallee()->getSourceRange()); 9198 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9199 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9200 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9201 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9202 PDiag(diag::warn_cstruct_memaccess) 9203 << ArgIdx << FnName << PointeeTy << 0); 9204 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9205 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9206 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9207 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9208 PDiag(diag::warn_cstruct_memaccess) 9209 << ArgIdx << FnName << PointeeTy << 1); 9210 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9211 } else { 9212 continue; 9213 } 9214 } else 9215 continue; 9216 9217 DiagRuntimeBehavior( 9218 Dest->getExprLoc(), Dest, 9219 PDiag(diag::note_bad_memaccess_silence) 9220 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9221 break; 9222 } 9223 } 9224 9225 // A little helper routine: ignore addition and subtraction of integer literals. 9226 // This intentionally does not ignore all integer constant expressions because 9227 // we don't want to remove sizeof(). 9228 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9229 Ex = Ex->IgnoreParenCasts(); 9230 9231 while (true) { 9232 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9233 if (!BO || !BO->isAdditiveOp()) 9234 break; 9235 9236 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9237 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9238 9239 if (isa<IntegerLiteral>(RHS)) 9240 Ex = LHS; 9241 else if (isa<IntegerLiteral>(LHS)) 9242 Ex = RHS; 9243 else 9244 break; 9245 } 9246 9247 return Ex; 9248 } 9249 9250 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9251 ASTContext &Context) { 9252 // Only handle constant-sized or VLAs, but not flexible members. 9253 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9254 // Only issue the FIXIT for arrays of size > 1. 9255 if (CAT->getSize().getSExtValue() <= 1) 9256 return false; 9257 } else if (!Ty->isVariableArrayType()) { 9258 return false; 9259 } 9260 return true; 9261 } 9262 9263 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9264 // be the size of the source, instead of the destination. 9265 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9266 IdentifierInfo *FnName) { 9267 9268 // Don't crash if the user has the wrong number of arguments 9269 unsigned NumArgs = Call->getNumArgs(); 9270 if ((NumArgs != 3) && (NumArgs != 4)) 9271 return; 9272 9273 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9274 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9275 const Expr *CompareWithSrc = nullptr; 9276 9277 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9278 Call->getBeginLoc(), Call->getRParenLoc())) 9279 return; 9280 9281 // Look for 'strlcpy(dst, x, sizeof(x))' 9282 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9283 CompareWithSrc = Ex; 9284 else { 9285 // Look for 'strlcpy(dst, x, strlen(x))' 9286 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9287 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9288 SizeCall->getNumArgs() == 1) 9289 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9290 } 9291 } 9292 9293 if (!CompareWithSrc) 9294 return; 9295 9296 // Determine if the argument to sizeof/strlen is equal to the source 9297 // argument. In principle there's all kinds of things you could do 9298 // here, for instance creating an == expression and evaluating it with 9299 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9300 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9301 if (!SrcArgDRE) 9302 return; 9303 9304 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9305 if (!CompareWithSrcDRE || 9306 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9307 return; 9308 9309 const Expr *OriginalSizeArg = Call->getArg(2); 9310 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9311 << OriginalSizeArg->getSourceRange() << FnName; 9312 9313 // Output a FIXIT hint if the destination is an array (rather than a 9314 // pointer to an array). This could be enhanced to handle some 9315 // pointers if we know the actual size, like if DstArg is 'array+2' 9316 // we could say 'sizeof(array)-2'. 9317 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9318 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9319 return; 9320 9321 SmallString<128> sizeString; 9322 llvm::raw_svector_ostream OS(sizeString); 9323 OS << "sizeof("; 9324 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9325 OS << ")"; 9326 9327 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9328 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9329 OS.str()); 9330 } 9331 9332 /// Check if two expressions refer to the same declaration. 9333 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9334 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9335 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9336 return D1->getDecl() == D2->getDecl(); 9337 return false; 9338 } 9339 9340 static const Expr *getStrlenExprArg(const Expr *E) { 9341 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9342 const FunctionDecl *FD = CE->getDirectCallee(); 9343 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9344 return nullptr; 9345 return CE->getArg(0)->IgnoreParenCasts(); 9346 } 9347 return nullptr; 9348 } 9349 9350 // Warn on anti-patterns as the 'size' argument to strncat. 9351 // The correct size argument should look like following: 9352 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9353 void Sema::CheckStrncatArguments(const CallExpr *CE, 9354 IdentifierInfo *FnName) { 9355 // Don't crash if the user has the wrong number of arguments. 9356 if (CE->getNumArgs() < 3) 9357 return; 9358 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9359 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9360 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9361 9362 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9363 CE->getRParenLoc())) 9364 return; 9365 9366 // Identify common expressions, which are wrongly used as the size argument 9367 // to strncat and may lead to buffer overflows. 9368 unsigned PatternType = 0; 9369 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9370 // - sizeof(dst) 9371 if (referToTheSameDecl(SizeOfArg, DstArg)) 9372 PatternType = 1; 9373 // - sizeof(src) 9374 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9375 PatternType = 2; 9376 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9377 if (BE->getOpcode() == BO_Sub) { 9378 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9379 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9380 // - sizeof(dst) - strlen(dst) 9381 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9382 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9383 PatternType = 1; 9384 // - sizeof(src) - (anything) 9385 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9386 PatternType = 2; 9387 } 9388 } 9389 9390 if (PatternType == 0) 9391 return; 9392 9393 // Generate the diagnostic. 9394 SourceLocation SL = LenArg->getBeginLoc(); 9395 SourceRange SR = LenArg->getSourceRange(); 9396 SourceManager &SM = getSourceManager(); 9397 9398 // If the function is defined as a builtin macro, do not show macro expansion. 9399 if (SM.isMacroArgExpansion(SL)) { 9400 SL = SM.getSpellingLoc(SL); 9401 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9402 SM.getSpellingLoc(SR.getEnd())); 9403 } 9404 9405 // Check if the destination is an array (rather than a pointer to an array). 9406 QualType DstTy = DstArg->getType(); 9407 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9408 Context); 9409 if (!isKnownSizeArray) { 9410 if (PatternType == 1) 9411 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9412 else 9413 Diag(SL, diag::warn_strncat_src_size) << SR; 9414 return; 9415 } 9416 9417 if (PatternType == 1) 9418 Diag(SL, diag::warn_strncat_large_size) << SR; 9419 else 9420 Diag(SL, diag::warn_strncat_src_size) << SR; 9421 9422 SmallString<128> sizeString; 9423 llvm::raw_svector_ostream OS(sizeString); 9424 OS << "sizeof("; 9425 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9426 OS << ") - "; 9427 OS << "strlen("; 9428 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9429 OS << ") - 1"; 9430 9431 Diag(SL, diag::note_strncat_wrong_size) 9432 << FixItHint::CreateReplacement(SR, OS.str()); 9433 } 9434 9435 void 9436 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9437 SourceLocation ReturnLoc, 9438 bool isObjCMethod, 9439 const AttrVec *Attrs, 9440 const FunctionDecl *FD) { 9441 // Check if the return value is null but should not be. 9442 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9443 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9444 CheckNonNullExpr(*this, RetValExp)) 9445 Diag(ReturnLoc, diag::warn_null_ret) 9446 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9447 9448 // C++11 [basic.stc.dynamic.allocation]p4: 9449 // If an allocation function declared with a non-throwing 9450 // exception-specification fails to allocate storage, it shall return 9451 // a null pointer. Any other allocation function that fails to allocate 9452 // storage shall indicate failure only by throwing an exception [...] 9453 if (FD) { 9454 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9455 if (Op == OO_New || Op == OO_Array_New) { 9456 const FunctionProtoType *Proto 9457 = FD->getType()->castAs<FunctionProtoType>(); 9458 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9459 CheckNonNullExpr(*this, RetValExp)) 9460 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9461 << FD << getLangOpts().CPlusPlus11; 9462 } 9463 } 9464 } 9465 9466 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9467 9468 /// Check for comparisons of floating point operands using != and ==. 9469 /// Issue a warning if these are no self-comparisons, as they are not likely 9470 /// to do what the programmer intended. 9471 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9472 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9473 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9474 9475 // Special case: check for x == x (which is OK). 9476 // Do not emit warnings for such cases. 9477 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9478 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9479 if (DRL->getDecl() == DRR->getDecl()) 9480 return; 9481 9482 // Special case: check for comparisons against literals that can be exactly 9483 // represented by APFloat. In such cases, do not emit a warning. This 9484 // is a heuristic: often comparison against such literals are used to 9485 // detect if a value in a variable has not changed. This clearly can 9486 // lead to false negatives. 9487 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9488 if (FLL->isExact()) 9489 return; 9490 } else 9491 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9492 if (FLR->isExact()) 9493 return; 9494 9495 // Check for comparisons with builtin types. 9496 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9497 if (CL->getBuiltinCallee()) 9498 return; 9499 9500 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9501 if (CR->getBuiltinCallee()) 9502 return; 9503 9504 // Emit the diagnostic. 9505 Diag(Loc, diag::warn_floatingpoint_eq) 9506 << LHS->getSourceRange() << RHS->getSourceRange(); 9507 } 9508 9509 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9510 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9511 9512 namespace { 9513 9514 /// Structure recording the 'active' range of an integer-valued 9515 /// expression. 9516 struct IntRange { 9517 /// The number of bits active in the int. 9518 unsigned Width; 9519 9520 /// True if the int is known not to have negative values. 9521 bool NonNegative; 9522 9523 IntRange(unsigned Width, bool NonNegative) 9524 : Width(Width), NonNegative(NonNegative) {} 9525 9526 /// Returns the range of the bool type. 9527 static IntRange forBoolType() { 9528 return IntRange(1, true); 9529 } 9530 9531 /// Returns the range of an opaque value of the given integral type. 9532 static IntRange forValueOfType(ASTContext &C, QualType T) { 9533 return forValueOfCanonicalType(C, 9534 T->getCanonicalTypeInternal().getTypePtr()); 9535 } 9536 9537 /// Returns the range of an opaque value of a canonical integral type. 9538 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9539 assert(T->isCanonicalUnqualified()); 9540 9541 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9542 T = VT->getElementType().getTypePtr(); 9543 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9544 T = CT->getElementType().getTypePtr(); 9545 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9546 T = AT->getValueType().getTypePtr(); 9547 9548 if (!C.getLangOpts().CPlusPlus) { 9549 // For enum types in C code, use the underlying datatype. 9550 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9551 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9552 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9553 // For enum types in C++, use the known bit width of the enumerators. 9554 EnumDecl *Enum = ET->getDecl(); 9555 // In C++11, enums can have a fixed underlying type. Use this type to 9556 // compute the range. 9557 if (Enum->isFixed()) { 9558 return IntRange(C.getIntWidth(QualType(T, 0)), 9559 !ET->isSignedIntegerOrEnumerationType()); 9560 } 9561 9562 unsigned NumPositive = Enum->getNumPositiveBits(); 9563 unsigned NumNegative = Enum->getNumNegativeBits(); 9564 9565 if (NumNegative == 0) 9566 return IntRange(NumPositive, true/*NonNegative*/); 9567 else 9568 return IntRange(std::max(NumPositive + 1, NumNegative), 9569 false/*NonNegative*/); 9570 } 9571 9572 const BuiltinType *BT = cast<BuiltinType>(T); 9573 assert(BT->isInteger()); 9574 9575 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9576 } 9577 9578 /// Returns the "target" range of a canonical integral type, i.e. 9579 /// the range of values expressible in the type. 9580 /// 9581 /// This matches forValueOfCanonicalType except that enums have the 9582 /// full range of their type, not the range of their enumerators. 9583 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9584 assert(T->isCanonicalUnqualified()); 9585 9586 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9587 T = VT->getElementType().getTypePtr(); 9588 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9589 T = CT->getElementType().getTypePtr(); 9590 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9591 T = AT->getValueType().getTypePtr(); 9592 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9593 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9594 9595 const BuiltinType *BT = cast<BuiltinType>(T); 9596 assert(BT->isInteger()); 9597 9598 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9599 } 9600 9601 /// Returns the supremum of two ranges: i.e. their conservative merge. 9602 static IntRange join(IntRange L, IntRange R) { 9603 return IntRange(std::max(L.Width, R.Width), 9604 L.NonNegative && R.NonNegative); 9605 } 9606 9607 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9608 static IntRange meet(IntRange L, IntRange R) { 9609 return IntRange(std::min(L.Width, R.Width), 9610 L.NonNegative || R.NonNegative); 9611 } 9612 }; 9613 9614 } // namespace 9615 9616 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9617 unsigned MaxWidth) { 9618 if (value.isSigned() && value.isNegative()) 9619 return IntRange(value.getMinSignedBits(), false); 9620 9621 if (value.getBitWidth() > MaxWidth) 9622 value = value.trunc(MaxWidth); 9623 9624 // isNonNegative() just checks the sign bit without considering 9625 // signedness. 9626 return IntRange(value.getActiveBits(), true); 9627 } 9628 9629 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9630 unsigned MaxWidth) { 9631 if (result.isInt()) 9632 return GetValueRange(C, result.getInt(), MaxWidth); 9633 9634 if (result.isVector()) { 9635 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9636 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9637 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9638 R = IntRange::join(R, El); 9639 } 9640 return R; 9641 } 9642 9643 if (result.isComplexInt()) { 9644 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9645 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9646 return IntRange::join(R, I); 9647 } 9648 9649 // This can happen with lossless casts to intptr_t of "based" lvalues. 9650 // Assume it might use arbitrary bits. 9651 // FIXME: The only reason we need to pass the type in here is to get 9652 // the sign right on this one case. It would be nice if APValue 9653 // preserved this. 9654 assert(result.isLValue() || result.isAddrLabelDiff()); 9655 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9656 } 9657 9658 static QualType GetExprType(const Expr *E) { 9659 QualType Ty = E->getType(); 9660 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9661 Ty = AtomicRHS->getValueType(); 9662 return Ty; 9663 } 9664 9665 /// Pseudo-evaluate the given integer expression, estimating the 9666 /// range of values it might take. 9667 /// 9668 /// \param MaxWidth - the width to which the value will be truncated 9669 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 9670 E = E->IgnoreParens(); 9671 9672 // Try a full evaluation first. 9673 Expr::EvalResult result; 9674 if (E->EvaluateAsRValue(result, C)) 9675 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9676 9677 // I think we only want to look through implicit casts here; if the 9678 // user has an explicit widening cast, we should treat the value as 9679 // being of the new, wider type. 9680 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9681 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9682 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 9683 9684 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9685 9686 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9687 CE->getCastKind() == CK_BooleanToSignedIntegral; 9688 9689 // Assume that non-integer casts can span the full range of the type. 9690 if (!isIntegerCast) 9691 return OutputTypeRange; 9692 9693 IntRange SubRange 9694 = GetExprRange(C, CE->getSubExpr(), 9695 std::min(MaxWidth, OutputTypeRange.Width)); 9696 9697 // Bail out if the subexpr's range is as wide as the cast type. 9698 if (SubRange.Width >= OutputTypeRange.Width) 9699 return OutputTypeRange; 9700 9701 // Otherwise, we take the smaller width, and we're non-negative if 9702 // either the output type or the subexpr is. 9703 return IntRange(SubRange.Width, 9704 SubRange.NonNegative || OutputTypeRange.NonNegative); 9705 } 9706 9707 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9708 // If we can fold the condition, just take that operand. 9709 bool CondResult; 9710 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9711 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9712 : CO->getFalseExpr(), 9713 MaxWidth); 9714 9715 // Otherwise, conservatively merge. 9716 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9717 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9718 return IntRange::join(L, R); 9719 } 9720 9721 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9722 switch (BO->getOpcode()) { 9723 case BO_Cmp: 9724 llvm_unreachable("builtin <=> should have class type"); 9725 9726 // Boolean-valued operations are single-bit and positive. 9727 case BO_LAnd: 9728 case BO_LOr: 9729 case BO_LT: 9730 case BO_GT: 9731 case BO_LE: 9732 case BO_GE: 9733 case BO_EQ: 9734 case BO_NE: 9735 return IntRange::forBoolType(); 9736 9737 // The type of the assignments is the type of the LHS, so the RHS 9738 // is not necessarily the same type. 9739 case BO_MulAssign: 9740 case BO_DivAssign: 9741 case BO_RemAssign: 9742 case BO_AddAssign: 9743 case BO_SubAssign: 9744 case BO_XorAssign: 9745 case BO_OrAssign: 9746 // TODO: bitfields? 9747 return IntRange::forValueOfType(C, GetExprType(E)); 9748 9749 // Simple assignments just pass through the RHS, which will have 9750 // been coerced to the LHS type. 9751 case BO_Assign: 9752 // TODO: bitfields? 9753 return GetExprRange(C, BO->getRHS(), MaxWidth); 9754 9755 // Operations with opaque sources are black-listed. 9756 case BO_PtrMemD: 9757 case BO_PtrMemI: 9758 return IntRange::forValueOfType(C, GetExprType(E)); 9759 9760 // Bitwise-and uses the *infinum* of the two source ranges. 9761 case BO_And: 9762 case BO_AndAssign: 9763 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9764 GetExprRange(C, BO->getRHS(), MaxWidth)); 9765 9766 // Left shift gets black-listed based on a judgement call. 9767 case BO_Shl: 9768 // ...except that we want to treat '1 << (blah)' as logically 9769 // positive. It's an important idiom. 9770 if (IntegerLiteral *I 9771 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9772 if (I->getValue() == 1) { 9773 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9774 return IntRange(R.Width, /*NonNegative*/ true); 9775 } 9776 } 9777 LLVM_FALLTHROUGH; 9778 9779 case BO_ShlAssign: 9780 return IntRange::forValueOfType(C, GetExprType(E)); 9781 9782 // Right shift by a constant can narrow its left argument. 9783 case BO_Shr: 9784 case BO_ShrAssign: { 9785 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9786 9787 // If the shift amount is a positive constant, drop the width by 9788 // that much. 9789 llvm::APSInt shift; 9790 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9791 shift.isNonNegative()) { 9792 unsigned zext = shift.getZExtValue(); 9793 if (zext >= L.Width) 9794 L.Width = (L.NonNegative ? 0 : 1); 9795 else 9796 L.Width -= zext; 9797 } 9798 9799 return L; 9800 } 9801 9802 // Comma acts as its right operand. 9803 case BO_Comma: 9804 return GetExprRange(C, BO->getRHS(), MaxWidth); 9805 9806 // Black-list pointer subtractions. 9807 case BO_Sub: 9808 if (BO->getLHS()->getType()->isPointerType()) 9809 return IntRange::forValueOfType(C, GetExprType(E)); 9810 break; 9811 9812 // The width of a division result is mostly determined by the size 9813 // of the LHS. 9814 case BO_Div: { 9815 // Don't 'pre-truncate' the operands. 9816 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9817 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9818 9819 // If the divisor is constant, use that. 9820 llvm::APSInt divisor; 9821 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9822 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9823 if (log2 >= L.Width) 9824 L.Width = (L.NonNegative ? 0 : 1); 9825 else 9826 L.Width = std::min(L.Width - log2, MaxWidth); 9827 return L; 9828 } 9829 9830 // Otherwise, just use the LHS's width. 9831 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9832 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9833 } 9834 9835 // The result of a remainder can't be larger than the result of 9836 // either side. 9837 case BO_Rem: { 9838 // Don't 'pre-truncate' the operands. 9839 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9840 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9841 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9842 9843 IntRange meet = IntRange::meet(L, R); 9844 meet.Width = std::min(meet.Width, MaxWidth); 9845 return meet; 9846 } 9847 9848 // The default behavior is okay for these. 9849 case BO_Mul: 9850 case BO_Add: 9851 case BO_Xor: 9852 case BO_Or: 9853 break; 9854 } 9855 9856 // The default case is to treat the operation as if it were closed 9857 // on the narrowest type that encompasses both operands. 9858 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9859 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9860 return IntRange::join(L, R); 9861 } 9862 9863 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9864 switch (UO->getOpcode()) { 9865 // Boolean-valued operations are white-listed. 9866 case UO_LNot: 9867 return IntRange::forBoolType(); 9868 9869 // Operations with opaque sources are black-listed. 9870 case UO_Deref: 9871 case UO_AddrOf: // should be impossible 9872 return IntRange::forValueOfType(C, GetExprType(E)); 9873 9874 default: 9875 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9876 } 9877 } 9878 9879 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9880 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9881 9882 if (const auto *BitField = E->getSourceBitField()) 9883 return IntRange(BitField->getBitWidthValue(C), 9884 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9885 9886 return IntRange::forValueOfType(C, GetExprType(E)); 9887 } 9888 9889 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9890 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9891 } 9892 9893 /// Checks whether the given value, which currently has the given 9894 /// source semantics, has the same value when coerced through the 9895 /// target semantics. 9896 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9897 const llvm::fltSemantics &Src, 9898 const llvm::fltSemantics &Tgt) { 9899 llvm::APFloat truncated = value; 9900 9901 bool ignored; 9902 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9903 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9904 9905 return truncated.bitwiseIsEqual(value); 9906 } 9907 9908 /// Checks whether the given value, which currently has the given 9909 /// source semantics, has the same value when coerced through the 9910 /// target semantics. 9911 /// 9912 /// The value might be a vector of floats (or a complex number). 9913 static bool IsSameFloatAfterCast(const APValue &value, 9914 const llvm::fltSemantics &Src, 9915 const llvm::fltSemantics &Tgt) { 9916 if (value.isFloat()) 9917 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9918 9919 if (value.isVector()) { 9920 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9921 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9922 return false; 9923 return true; 9924 } 9925 9926 assert(value.isComplexFloat()); 9927 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9928 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9929 } 9930 9931 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9932 9933 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9934 // Suppress cases where we are comparing against an enum constant. 9935 if (const DeclRefExpr *DR = 9936 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9937 if (isa<EnumConstantDecl>(DR->getDecl())) 9938 return true; 9939 9940 // Suppress cases where the '0' value is expanded from a macro. 9941 if (E->getBeginLoc().isMacroID()) 9942 return true; 9943 9944 return false; 9945 } 9946 9947 static bool isKnownToHaveUnsignedValue(Expr *E) { 9948 return E->getType()->isIntegerType() && 9949 (!E->getType()->isSignedIntegerType() || 9950 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9951 } 9952 9953 namespace { 9954 /// The promoted range of values of a type. In general this has the 9955 /// following structure: 9956 /// 9957 /// |-----------| . . . |-----------| 9958 /// ^ ^ ^ ^ 9959 /// Min HoleMin HoleMax Max 9960 /// 9961 /// ... where there is only a hole if a signed type is promoted to unsigned 9962 /// (in which case Min and Max are the smallest and largest representable 9963 /// values). 9964 struct PromotedRange { 9965 // Min, or HoleMax if there is a hole. 9966 llvm::APSInt PromotedMin; 9967 // Max, or HoleMin if there is a hole. 9968 llvm::APSInt PromotedMax; 9969 9970 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9971 if (R.Width == 0) 9972 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9973 else if (R.Width >= BitWidth && !Unsigned) { 9974 // Promotion made the type *narrower*. This happens when promoting 9975 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9976 // Treat all values of 'signed int' as being in range for now. 9977 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9978 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9979 } else { 9980 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9981 .extOrTrunc(BitWidth); 9982 PromotedMin.setIsUnsigned(Unsigned); 9983 9984 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9985 .extOrTrunc(BitWidth); 9986 PromotedMax.setIsUnsigned(Unsigned); 9987 } 9988 } 9989 9990 // Determine whether this range is contiguous (has no hole). 9991 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9992 9993 // Where a constant value is within the range. 9994 enum ComparisonResult { 9995 LT = 0x1, 9996 LE = 0x2, 9997 GT = 0x4, 9998 GE = 0x8, 9999 EQ = 0x10, 10000 NE = 0x20, 10001 InRangeFlag = 0x40, 10002 10003 Less = LE | LT | NE, 10004 Min = LE | InRangeFlag, 10005 InRange = InRangeFlag, 10006 Max = GE | InRangeFlag, 10007 Greater = GE | GT | NE, 10008 10009 OnlyValue = LE | GE | EQ | InRangeFlag, 10010 InHole = NE 10011 }; 10012 10013 ComparisonResult compare(const llvm::APSInt &Value) const { 10014 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10015 Value.isUnsigned() == PromotedMin.isUnsigned()); 10016 if (!isContiguous()) { 10017 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10018 if (Value.isMinValue()) return Min; 10019 if (Value.isMaxValue()) return Max; 10020 if (Value >= PromotedMin) return InRange; 10021 if (Value <= PromotedMax) return InRange; 10022 return InHole; 10023 } 10024 10025 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10026 case -1: return Less; 10027 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10028 case 1: 10029 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10030 case -1: return InRange; 10031 case 0: return Max; 10032 case 1: return Greater; 10033 } 10034 } 10035 10036 llvm_unreachable("impossible compare result"); 10037 } 10038 10039 static llvm::Optional<StringRef> 10040 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10041 if (Op == BO_Cmp) { 10042 ComparisonResult LTFlag = LT, GTFlag = GT; 10043 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10044 10045 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10046 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10047 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10048 return llvm::None; 10049 } 10050 10051 ComparisonResult TrueFlag, FalseFlag; 10052 if (Op == BO_EQ) { 10053 TrueFlag = EQ; 10054 FalseFlag = NE; 10055 } else if (Op == BO_NE) { 10056 TrueFlag = NE; 10057 FalseFlag = EQ; 10058 } else { 10059 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10060 TrueFlag = LT; 10061 FalseFlag = GE; 10062 } else { 10063 TrueFlag = GT; 10064 FalseFlag = LE; 10065 } 10066 if (Op == BO_GE || Op == BO_LE) 10067 std::swap(TrueFlag, FalseFlag); 10068 } 10069 if (R & TrueFlag) 10070 return StringRef("true"); 10071 if (R & FalseFlag) 10072 return StringRef("false"); 10073 return llvm::None; 10074 } 10075 }; 10076 } 10077 10078 static bool HasEnumType(Expr *E) { 10079 // Strip off implicit integral promotions. 10080 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10081 if (ICE->getCastKind() != CK_IntegralCast && 10082 ICE->getCastKind() != CK_NoOp) 10083 break; 10084 E = ICE->getSubExpr(); 10085 } 10086 10087 return E->getType()->isEnumeralType(); 10088 } 10089 10090 static int classifyConstantValue(Expr *Constant) { 10091 // The values of this enumeration are used in the diagnostics 10092 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10093 enum ConstantValueKind { 10094 Miscellaneous = 0, 10095 LiteralTrue, 10096 LiteralFalse 10097 }; 10098 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10099 return BL->getValue() ? ConstantValueKind::LiteralTrue 10100 : ConstantValueKind::LiteralFalse; 10101 return ConstantValueKind::Miscellaneous; 10102 } 10103 10104 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10105 Expr *Constant, Expr *Other, 10106 const llvm::APSInt &Value, 10107 bool RhsConstant) { 10108 if (S.inTemplateInstantiation()) 10109 return false; 10110 10111 Expr *OriginalOther = Other; 10112 10113 Constant = Constant->IgnoreParenImpCasts(); 10114 Other = Other->IgnoreParenImpCasts(); 10115 10116 // Suppress warnings on tautological comparisons between values of the same 10117 // enumeration type. There are only two ways we could warn on this: 10118 // - If the constant is outside the range of representable values of 10119 // the enumeration. In such a case, we should warn about the cast 10120 // to enumeration type, not about the comparison. 10121 // - If the constant is the maximum / minimum in-range value. For an 10122 // enumeratin type, such comparisons can be meaningful and useful. 10123 if (Constant->getType()->isEnumeralType() && 10124 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10125 return false; 10126 10127 // TODO: Investigate using GetExprRange() to get tighter bounds 10128 // on the bit ranges. 10129 QualType OtherT = Other->getType(); 10130 if (const auto *AT = OtherT->getAs<AtomicType>()) 10131 OtherT = AT->getValueType(); 10132 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10133 10134 // Whether we're treating Other as being a bool because of the form of 10135 // expression despite it having another type (typically 'int' in C). 10136 bool OtherIsBooleanDespiteType = 10137 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10138 if (OtherIsBooleanDespiteType) 10139 OtherRange = IntRange::forBoolType(); 10140 10141 // Determine the promoted range of the other type and see if a comparison of 10142 // the constant against that range is tautological. 10143 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10144 Value.isUnsigned()); 10145 auto Cmp = OtherPromotedRange.compare(Value); 10146 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10147 if (!Result) 10148 return false; 10149 10150 // Suppress the diagnostic for an in-range comparison if the constant comes 10151 // from a macro or enumerator. We don't want to diagnose 10152 // 10153 // some_long_value <= INT_MAX 10154 // 10155 // when sizeof(int) == sizeof(long). 10156 bool InRange = Cmp & PromotedRange::InRangeFlag; 10157 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10158 return false; 10159 10160 // If this is a comparison to an enum constant, include that 10161 // constant in the diagnostic. 10162 const EnumConstantDecl *ED = nullptr; 10163 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10164 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10165 10166 // Should be enough for uint128 (39 decimal digits) 10167 SmallString<64> PrettySourceValue; 10168 llvm::raw_svector_ostream OS(PrettySourceValue); 10169 if (ED) 10170 OS << '\'' << *ED << "' (" << Value << ")"; 10171 else 10172 OS << Value; 10173 10174 // FIXME: We use a somewhat different formatting for the in-range cases and 10175 // cases involving boolean values for historical reasons. We should pick a 10176 // consistent way of presenting these diagnostics. 10177 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10178 S.DiagRuntimeBehavior( 10179 E->getOperatorLoc(), E, 10180 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10181 : diag::warn_tautological_bool_compare) 10182 << OS.str() << classifyConstantValue(Constant) 10183 << OtherT << OtherIsBooleanDespiteType << *Result 10184 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10185 } else { 10186 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10187 ? (HasEnumType(OriginalOther) 10188 ? diag::warn_unsigned_enum_always_true_comparison 10189 : diag::warn_unsigned_always_true_comparison) 10190 : diag::warn_tautological_constant_compare; 10191 10192 S.Diag(E->getOperatorLoc(), Diag) 10193 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10194 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10195 } 10196 10197 return true; 10198 } 10199 10200 /// Analyze the operands of the given comparison. Implements the 10201 /// fallback case from AnalyzeComparison. 10202 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10203 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10204 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10205 } 10206 10207 /// Implements -Wsign-compare. 10208 /// 10209 /// \param E the binary operator to check for warnings 10210 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10211 // The type the comparison is being performed in. 10212 QualType T = E->getLHS()->getType(); 10213 10214 // Only analyze comparison operators where both sides have been converted to 10215 // the same type. 10216 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10217 return AnalyzeImpConvsInComparison(S, E); 10218 10219 // Don't analyze value-dependent comparisons directly. 10220 if (E->isValueDependent()) 10221 return AnalyzeImpConvsInComparison(S, E); 10222 10223 Expr *LHS = E->getLHS(); 10224 Expr *RHS = E->getRHS(); 10225 10226 if (T->isIntegralType(S.Context)) { 10227 llvm::APSInt RHSValue; 10228 llvm::APSInt LHSValue; 10229 10230 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10231 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10232 10233 // We don't care about expressions whose result is a constant. 10234 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10235 return AnalyzeImpConvsInComparison(S, E); 10236 10237 // We only care about expressions where just one side is literal 10238 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10239 // Is the constant on the RHS or LHS? 10240 const bool RhsConstant = IsRHSIntegralLiteral; 10241 Expr *Const = RhsConstant ? RHS : LHS; 10242 Expr *Other = RhsConstant ? LHS : RHS; 10243 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10244 10245 // Check whether an integer constant comparison results in a value 10246 // of 'true' or 'false'. 10247 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10248 return AnalyzeImpConvsInComparison(S, E); 10249 } 10250 } 10251 10252 if (!T->hasUnsignedIntegerRepresentation()) { 10253 // We don't do anything special if this isn't an unsigned integral 10254 // comparison: we're only interested in integral comparisons, and 10255 // signed comparisons only happen in cases we don't care to warn about. 10256 return AnalyzeImpConvsInComparison(S, E); 10257 } 10258 10259 LHS = LHS->IgnoreParenImpCasts(); 10260 RHS = RHS->IgnoreParenImpCasts(); 10261 10262 if (!S.getLangOpts().CPlusPlus) { 10263 // Avoid warning about comparison of integers with different signs when 10264 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10265 // the type of `E`. 10266 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10267 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10268 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10269 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10270 } 10271 10272 // Check to see if one of the (unmodified) operands is of different 10273 // signedness. 10274 Expr *signedOperand, *unsignedOperand; 10275 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10276 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10277 "unsigned comparison between two signed integer expressions?"); 10278 signedOperand = LHS; 10279 unsignedOperand = RHS; 10280 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10281 signedOperand = RHS; 10282 unsignedOperand = LHS; 10283 } else { 10284 return AnalyzeImpConvsInComparison(S, E); 10285 } 10286 10287 // Otherwise, calculate the effective range of the signed operand. 10288 IntRange signedRange = GetExprRange(S.Context, signedOperand); 10289 10290 // Go ahead and analyze implicit conversions in the operands. Note 10291 // that we skip the implicit conversions on both sides. 10292 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10293 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10294 10295 // If the signed range is non-negative, -Wsign-compare won't fire. 10296 if (signedRange.NonNegative) 10297 return; 10298 10299 // For (in)equality comparisons, if the unsigned operand is a 10300 // constant which cannot collide with a overflowed signed operand, 10301 // then reinterpreting the signed operand as unsigned will not 10302 // change the result of the comparison. 10303 if (E->isEqualityOp()) { 10304 unsigned comparisonWidth = S.Context.getIntWidth(T); 10305 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 10306 10307 // We should never be unable to prove that the unsigned operand is 10308 // non-negative. 10309 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10310 10311 if (unsignedRange.Width < comparisonWidth) 10312 return; 10313 } 10314 10315 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10316 S.PDiag(diag::warn_mixed_sign_comparison) 10317 << LHS->getType() << RHS->getType() 10318 << LHS->getSourceRange() << RHS->getSourceRange()); 10319 } 10320 10321 /// Analyzes an attempt to assign the given value to a bitfield. 10322 /// 10323 /// Returns true if there was something fishy about the attempt. 10324 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10325 SourceLocation InitLoc) { 10326 assert(Bitfield->isBitField()); 10327 if (Bitfield->isInvalidDecl()) 10328 return false; 10329 10330 // White-list bool bitfields. 10331 QualType BitfieldType = Bitfield->getType(); 10332 if (BitfieldType->isBooleanType()) 10333 return false; 10334 10335 if (BitfieldType->isEnumeralType()) { 10336 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10337 // If the underlying enum type was not explicitly specified as an unsigned 10338 // type and the enum contain only positive values, MSVC++ will cause an 10339 // inconsistency by storing this as a signed type. 10340 if (S.getLangOpts().CPlusPlus11 && 10341 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10342 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10343 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10344 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10345 << BitfieldEnumDecl->getNameAsString(); 10346 } 10347 } 10348 10349 if (Bitfield->getType()->isBooleanType()) 10350 return false; 10351 10352 // Ignore value- or type-dependent expressions. 10353 if (Bitfield->getBitWidth()->isValueDependent() || 10354 Bitfield->getBitWidth()->isTypeDependent() || 10355 Init->isValueDependent() || 10356 Init->isTypeDependent()) 10357 return false; 10358 10359 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10360 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10361 10362 Expr::EvalResult Result; 10363 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10364 Expr::SE_AllowSideEffects)) { 10365 // The RHS is not constant. If the RHS has an enum type, make sure the 10366 // bitfield is wide enough to hold all the values of the enum without 10367 // truncation. 10368 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10369 EnumDecl *ED = EnumTy->getDecl(); 10370 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10371 10372 // Enum types are implicitly signed on Windows, so check if there are any 10373 // negative enumerators to see if the enum was intended to be signed or 10374 // not. 10375 bool SignedEnum = ED->getNumNegativeBits() > 0; 10376 10377 // Check for surprising sign changes when assigning enum values to a 10378 // bitfield of different signedness. If the bitfield is signed and we 10379 // have exactly the right number of bits to store this unsigned enum, 10380 // suggest changing the enum to an unsigned type. This typically happens 10381 // on Windows where unfixed enums always use an underlying type of 'int'. 10382 unsigned DiagID = 0; 10383 if (SignedEnum && !SignedBitfield) { 10384 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10385 } else if (SignedBitfield && !SignedEnum && 10386 ED->getNumPositiveBits() == FieldWidth) { 10387 DiagID = diag::warn_signed_bitfield_enum_conversion; 10388 } 10389 10390 if (DiagID) { 10391 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10392 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10393 SourceRange TypeRange = 10394 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10395 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10396 << SignedEnum << TypeRange; 10397 } 10398 10399 // Compute the required bitwidth. If the enum has negative values, we need 10400 // one more bit than the normal number of positive bits to represent the 10401 // sign bit. 10402 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10403 ED->getNumNegativeBits()) 10404 : ED->getNumPositiveBits(); 10405 10406 // Check the bitwidth. 10407 if (BitsNeeded > FieldWidth) { 10408 Expr *WidthExpr = Bitfield->getBitWidth(); 10409 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10410 << Bitfield << ED; 10411 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10412 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10413 } 10414 } 10415 10416 return false; 10417 } 10418 10419 llvm::APSInt Value = Result.Val.getInt(); 10420 10421 unsigned OriginalWidth = Value.getBitWidth(); 10422 10423 if (!Value.isSigned() || Value.isNegative()) 10424 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10425 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10426 OriginalWidth = Value.getMinSignedBits(); 10427 10428 if (OriginalWidth <= FieldWidth) 10429 return false; 10430 10431 // Compute the value which the bitfield will contain. 10432 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10433 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10434 10435 // Check whether the stored value is equal to the original value. 10436 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10437 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10438 return false; 10439 10440 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10441 // therefore don't strictly fit into a signed bitfield of width 1. 10442 if (FieldWidth == 1 && Value == 1) 10443 return false; 10444 10445 std::string PrettyValue = Value.toString(10); 10446 std::string PrettyTrunc = TruncatedValue.toString(10); 10447 10448 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10449 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10450 << Init->getSourceRange(); 10451 10452 return true; 10453 } 10454 10455 /// Analyze the given simple or compound assignment for warning-worthy 10456 /// operations. 10457 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10458 // Just recurse on the LHS. 10459 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10460 10461 // We want to recurse on the RHS as normal unless we're assigning to 10462 // a bitfield. 10463 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10464 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10465 E->getOperatorLoc())) { 10466 // Recurse, ignoring any implicit conversions on the RHS. 10467 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10468 E->getOperatorLoc()); 10469 } 10470 } 10471 10472 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10473 10474 // Diagnose implicitly sequentially-consistent atomic assignment. 10475 if (E->getLHS()->getType()->isAtomicType()) 10476 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10477 } 10478 10479 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10480 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10481 SourceLocation CContext, unsigned diag, 10482 bool pruneControlFlow = false) { 10483 if (pruneControlFlow) { 10484 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10485 S.PDiag(diag) 10486 << SourceType << T << E->getSourceRange() 10487 << SourceRange(CContext)); 10488 return; 10489 } 10490 S.Diag(E->getExprLoc(), diag) 10491 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10492 } 10493 10494 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10495 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10496 SourceLocation CContext, 10497 unsigned diag, bool pruneControlFlow = false) { 10498 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10499 } 10500 10501 /// Diagnose an implicit cast from a floating point value to an integer value. 10502 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10503 SourceLocation CContext) { 10504 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10505 const bool PruneWarnings = S.inTemplateInstantiation(); 10506 10507 Expr *InnerE = E->IgnoreParenImpCasts(); 10508 // We also want to warn on, e.g., "int i = -1.234" 10509 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10510 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10511 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10512 10513 const bool IsLiteral = 10514 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10515 10516 llvm::APFloat Value(0.0); 10517 bool IsConstant = 10518 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10519 if (!IsConstant) { 10520 return DiagnoseImpCast(S, E, T, CContext, 10521 diag::warn_impcast_float_integer, PruneWarnings); 10522 } 10523 10524 bool isExact = false; 10525 10526 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10527 T->hasUnsignedIntegerRepresentation()); 10528 llvm::APFloat::opStatus Result = Value.convertToInteger( 10529 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10530 10531 if (Result == llvm::APFloat::opOK && isExact) { 10532 if (IsLiteral) return; 10533 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10534 PruneWarnings); 10535 } 10536 10537 // Conversion of a floating-point value to a non-bool integer where the 10538 // integral part cannot be represented by the integer type is undefined. 10539 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10540 return DiagnoseImpCast( 10541 S, E, T, CContext, 10542 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10543 : diag::warn_impcast_float_to_integer_out_of_range, 10544 PruneWarnings); 10545 10546 unsigned DiagID = 0; 10547 if (IsLiteral) { 10548 // Warn on floating point literal to integer. 10549 DiagID = diag::warn_impcast_literal_float_to_integer; 10550 } else if (IntegerValue == 0) { 10551 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10552 return DiagnoseImpCast(S, E, T, CContext, 10553 diag::warn_impcast_float_integer, PruneWarnings); 10554 } 10555 // Warn on non-zero to zero conversion. 10556 DiagID = diag::warn_impcast_float_to_integer_zero; 10557 } else { 10558 if (IntegerValue.isUnsigned()) { 10559 if (!IntegerValue.isMaxValue()) { 10560 return DiagnoseImpCast(S, E, T, CContext, 10561 diag::warn_impcast_float_integer, PruneWarnings); 10562 } 10563 } else { // IntegerValue.isSigned() 10564 if (!IntegerValue.isMaxSignedValue() && 10565 !IntegerValue.isMinSignedValue()) { 10566 return DiagnoseImpCast(S, E, T, CContext, 10567 diag::warn_impcast_float_integer, PruneWarnings); 10568 } 10569 } 10570 // Warn on evaluatable floating point expression to integer conversion. 10571 DiagID = diag::warn_impcast_float_to_integer; 10572 } 10573 10574 // FIXME: Force the precision of the source value down so we don't print 10575 // digits which are usually useless (we don't really care here if we 10576 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10577 // would automatically print the shortest representation, but it's a bit 10578 // tricky to implement. 10579 SmallString<16> PrettySourceValue; 10580 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10581 precision = (precision * 59 + 195) / 196; 10582 Value.toString(PrettySourceValue, precision); 10583 10584 SmallString<16> PrettyTargetValue; 10585 if (IsBool) 10586 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10587 else 10588 IntegerValue.toString(PrettyTargetValue); 10589 10590 if (PruneWarnings) { 10591 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10592 S.PDiag(DiagID) 10593 << E->getType() << T.getUnqualifiedType() 10594 << PrettySourceValue << PrettyTargetValue 10595 << E->getSourceRange() << SourceRange(CContext)); 10596 } else { 10597 S.Diag(E->getExprLoc(), DiagID) 10598 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10599 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10600 } 10601 } 10602 10603 /// Analyze the given compound assignment for the possible losing of 10604 /// floating-point precision. 10605 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10606 assert(isa<CompoundAssignOperator>(E) && 10607 "Must be compound assignment operation"); 10608 // Recurse on the LHS and RHS in here 10609 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10610 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10611 10612 if (E->getLHS()->getType()->isAtomicType()) 10613 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10614 10615 // Now check the outermost expression 10616 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10617 const auto *RBT = cast<CompoundAssignOperator>(E) 10618 ->getComputationResultType() 10619 ->getAs<BuiltinType>(); 10620 10621 // The below checks assume source is floating point. 10622 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10623 10624 // If source is floating point but target is not. 10625 if (!ResultBT->isFloatingPoint()) 10626 return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(), 10627 E->getExprLoc()); 10628 10629 // If both source and target are floating points. 10630 // Builtin FP kinds are ordered by increasing FP rank. 10631 if (ResultBT->getKind() < RBT->getKind() && 10632 // We don't want to warn for system macro. 10633 !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10634 // warn about dropping FP rank. 10635 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10636 diag::warn_impcast_float_result_precision); 10637 } 10638 10639 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10640 IntRange Range) { 10641 if (!Range.Width) return "0"; 10642 10643 llvm::APSInt ValueInRange = Value; 10644 ValueInRange.setIsSigned(!Range.NonNegative); 10645 ValueInRange = ValueInRange.trunc(Range.Width); 10646 return ValueInRange.toString(10); 10647 } 10648 10649 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10650 if (!isa<ImplicitCastExpr>(Ex)) 10651 return false; 10652 10653 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10654 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10655 const Type *Source = 10656 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10657 if (Target->isDependentType()) 10658 return false; 10659 10660 const BuiltinType *FloatCandidateBT = 10661 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10662 const Type *BoolCandidateType = ToBool ? Target : Source; 10663 10664 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10665 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10666 } 10667 10668 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10669 SourceLocation CC) { 10670 unsigned NumArgs = TheCall->getNumArgs(); 10671 for (unsigned i = 0; i < NumArgs; ++i) { 10672 Expr *CurrA = TheCall->getArg(i); 10673 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10674 continue; 10675 10676 bool IsSwapped = ((i > 0) && 10677 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10678 IsSwapped |= ((i < (NumArgs - 1)) && 10679 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10680 if (IsSwapped) { 10681 // Warn on this floating-point to bool conversion. 10682 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10683 CurrA->getType(), CC, 10684 diag::warn_impcast_floating_point_to_bool); 10685 } 10686 } 10687 } 10688 10689 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10690 SourceLocation CC) { 10691 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10692 E->getExprLoc())) 10693 return; 10694 10695 // Don't warn on functions which have return type nullptr_t. 10696 if (isa<CallExpr>(E)) 10697 return; 10698 10699 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10700 const Expr::NullPointerConstantKind NullKind = 10701 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10702 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10703 return; 10704 10705 // Return if target type is a safe conversion. 10706 if (T->isAnyPointerType() || T->isBlockPointerType() || 10707 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10708 return; 10709 10710 SourceLocation Loc = E->getSourceRange().getBegin(); 10711 10712 // Venture through the macro stacks to get to the source of macro arguments. 10713 // The new location is a better location than the complete location that was 10714 // passed in. 10715 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10716 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10717 10718 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10719 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10720 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10721 Loc, S.SourceMgr, S.getLangOpts()); 10722 if (MacroName == "NULL") 10723 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10724 } 10725 10726 // Only warn if the null and context location are in the same macro expansion. 10727 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10728 return; 10729 10730 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10731 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10732 << FixItHint::CreateReplacement(Loc, 10733 S.getFixItZeroLiteralForType(T, Loc)); 10734 } 10735 10736 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10737 ObjCArrayLiteral *ArrayLiteral); 10738 10739 static void 10740 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10741 ObjCDictionaryLiteral *DictionaryLiteral); 10742 10743 /// Check a single element within a collection literal against the 10744 /// target element type. 10745 static void checkObjCCollectionLiteralElement(Sema &S, 10746 QualType TargetElementType, 10747 Expr *Element, 10748 unsigned ElementKind) { 10749 // Skip a bitcast to 'id' or qualified 'id'. 10750 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10751 if (ICE->getCastKind() == CK_BitCast && 10752 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10753 Element = ICE->getSubExpr(); 10754 } 10755 10756 QualType ElementType = Element->getType(); 10757 ExprResult ElementResult(Element); 10758 if (ElementType->getAs<ObjCObjectPointerType>() && 10759 S.CheckSingleAssignmentConstraints(TargetElementType, 10760 ElementResult, 10761 false, false) 10762 != Sema::Compatible) { 10763 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 10764 << ElementType << ElementKind << TargetElementType 10765 << Element->getSourceRange(); 10766 } 10767 10768 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10769 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10770 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10771 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10772 } 10773 10774 /// Check an Objective-C array literal being converted to the given 10775 /// target type. 10776 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10777 ObjCArrayLiteral *ArrayLiteral) { 10778 if (!S.NSArrayDecl) 10779 return; 10780 10781 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10782 if (!TargetObjCPtr) 10783 return; 10784 10785 if (TargetObjCPtr->isUnspecialized() || 10786 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10787 != S.NSArrayDecl->getCanonicalDecl()) 10788 return; 10789 10790 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10791 if (TypeArgs.size() != 1) 10792 return; 10793 10794 QualType TargetElementType = TypeArgs[0]; 10795 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10796 checkObjCCollectionLiteralElement(S, TargetElementType, 10797 ArrayLiteral->getElement(I), 10798 0); 10799 } 10800 } 10801 10802 /// Check an Objective-C dictionary literal being converted to the given 10803 /// target type. 10804 static void 10805 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10806 ObjCDictionaryLiteral *DictionaryLiteral) { 10807 if (!S.NSDictionaryDecl) 10808 return; 10809 10810 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10811 if (!TargetObjCPtr) 10812 return; 10813 10814 if (TargetObjCPtr->isUnspecialized() || 10815 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10816 != S.NSDictionaryDecl->getCanonicalDecl()) 10817 return; 10818 10819 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10820 if (TypeArgs.size() != 2) 10821 return; 10822 10823 QualType TargetKeyType = TypeArgs[0]; 10824 QualType TargetObjectType = TypeArgs[1]; 10825 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10826 auto Element = DictionaryLiteral->getKeyValueElement(I); 10827 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10828 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10829 } 10830 } 10831 10832 // Helper function to filter out cases for constant width constant conversion. 10833 // Don't warn on char array initialization or for non-decimal values. 10834 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10835 SourceLocation CC) { 10836 // If initializing from a constant, and the constant starts with '0', 10837 // then it is a binary, octal, or hexadecimal. Allow these constants 10838 // to fill all the bits, even if there is a sign change. 10839 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10840 const char FirstLiteralCharacter = 10841 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 10842 if (FirstLiteralCharacter == '0') 10843 return false; 10844 } 10845 10846 // If the CC location points to a '{', and the type is char, then assume 10847 // assume it is an array initialization. 10848 if (CC.isValid() && T->isCharType()) { 10849 const char FirstContextCharacter = 10850 S.getSourceManager().getCharacterData(CC)[0]; 10851 if (FirstContextCharacter == '{') 10852 return false; 10853 } 10854 10855 return true; 10856 } 10857 10858 static void 10859 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10860 bool *ICContext = nullptr) { 10861 if (E->isTypeDependent() || E->isValueDependent()) return; 10862 10863 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10864 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10865 if (Source == Target) return; 10866 if (Target->isDependentType()) return; 10867 10868 // If the conversion context location is invalid don't complain. We also 10869 // don't want to emit a warning if the issue occurs from the expansion of 10870 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10871 // delay this check as long as possible. Once we detect we are in that 10872 // scenario, we just return. 10873 if (CC.isInvalid()) 10874 return; 10875 10876 if (Source->isAtomicType()) 10877 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 10878 10879 // Diagnose implicit casts to bool. 10880 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10881 if (isa<StringLiteral>(E)) 10882 // Warn on string literal to bool. Checks for string literals in logical 10883 // and expressions, for instance, assert(0 && "error here"), are 10884 // prevented by a check in AnalyzeImplicitConversions(). 10885 return DiagnoseImpCast(S, E, T, CC, 10886 diag::warn_impcast_string_literal_to_bool); 10887 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10888 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10889 // This covers the literal expressions that evaluate to Objective-C 10890 // objects. 10891 return DiagnoseImpCast(S, E, T, CC, 10892 diag::warn_impcast_objective_c_literal_to_bool); 10893 } 10894 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10895 // Warn on pointer to bool conversion that is always true. 10896 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10897 SourceRange(CC)); 10898 } 10899 } 10900 10901 // Check implicit casts from Objective-C collection literals to specialized 10902 // collection types, e.g., NSArray<NSString *> *. 10903 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10904 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10905 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10906 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10907 10908 // Strip vector types. 10909 if (isa<VectorType>(Source)) { 10910 if (!isa<VectorType>(Target)) { 10911 if (S.SourceMgr.isInSystemMacro(CC)) 10912 return; 10913 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10914 } 10915 10916 // If the vector cast is cast between two vectors of the same size, it is 10917 // a bitcast, not a conversion. 10918 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10919 return; 10920 10921 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10922 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10923 } 10924 if (auto VecTy = dyn_cast<VectorType>(Target)) 10925 Target = VecTy->getElementType().getTypePtr(); 10926 10927 // Strip complex types. 10928 if (isa<ComplexType>(Source)) { 10929 if (!isa<ComplexType>(Target)) { 10930 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10931 return; 10932 10933 return DiagnoseImpCast(S, E, T, CC, 10934 S.getLangOpts().CPlusPlus 10935 ? diag::err_impcast_complex_scalar 10936 : diag::warn_impcast_complex_scalar); 10937 } 10938 10939 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10940 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10941 } 10942 10943 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10944 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10945 10946 // If the source is floating point... 10947 if (SourceBT && SourceBT->isFloatingPoint()) { 10948 // ...and the target is floating point... 10949 if (TargetBT && TargetBT->isFloatingPoint()) { 10950 // ...then warn if we're dropping FP rank. 10951 10952 // Builtin FP kinds are ordered by increasing FP rank. 10953 if (SourceBT->getKind() > TargetBT->getKind()) { 10954 // Don't warn about float constants that are precisely 10955 // representable in the target type. 10956 Expr::EvalResult result; 10957 if (E->EvaluateAsRValue(result, S.Context)) { 10958 // Value might be a float, a float vector, or a float complex. 10959 if (IsSameFloatAfterCast(result.Val, 10960 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10961 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10962 return; 10963 } 10964 10965 if (S.SourceMgr.isInSystemMacro(CC)) 10966 return; 10967 10968 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10969 } 10970 // ... or possibly if we're increasing rank, too 10971 else if (TargetBT->getKind() > SourceBT->getKind()) { 10972 if (S.SourceMgr.isInSystemMacro(CC)) 10973 return; 10974 10975 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10976 } 10977 return; 10978 } 10979 10980 // If the target is integral, always warn. 10981 if (TargetBT && TargetBT->isInteger()) { 10982 if (S.SourceMgr.isInSystemMacro(CC)) 10983 return; 10984 10985 DiagnoseFloatingImpCast(S, E, T, CC); 10986 } 10987 10988 // Detect the case where a call result is converted from floating-point to 10989 // to bool, and the final argument to the call is converted from bool, to 10990 // discover this typo: 10991 // 10992 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10993 // 10994 // FIXME: This is an incredibly special case; is there some more general 10995 // way to detect this class of misplaced-parentheses bug? 10996 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10997 // Check last argument of function call to see if it is an 10998 // implicit cast from a type matching the type the result 10999 // is being cast to. 11000 CallExpr *CEx = cast<CallExpr>(E); 11001 if (unsigned NumArgs = CEx->getNumArgs()) { 11002 Expr *LastA = CEx->getArg(NumArgs - 1); 11003 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11004 if (isa<ImplicitCastExpr>(LastA) && 11005 InnerE->getType()->isBooleanType()) { 11006 // Warn on this floating-point to bool conversion 11007 DiagnoseImpCast(S, E, T, CC, 11008 diag::warn_impcast_floating_point_to_bool); 11009 } 11010 } 11011 } 11012 return; 11013 } 11014 11015 if (Source->isFixedPointType()) { 11016 // TODO: Only CK_FixedPointCast is supported now. The other valid casts 11017 // should be accounted for here. 11018 if (Target->isFixedPointType()) { 11019 Expr::EvalResult Result; 11020 if (E->EvaluateAsFixedPoint(Result, S.Context, 11021 Expr::SE_AllowSideEffects)) { 11022 APFixedPoint Value = Result.Val.getFixedPoint(); 11023 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11024 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11025 if (Value > MaxVal || Value < MinVal) { 11026 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11027 S.PDiag(diag::warn_impcast_fixed_point_range) 11028 << Value.toString() << T 11029 << E->getSourceRange() 11030 << clang::SourceRange(CC)); 11031 return; 11032 } 11033 } 11034 } 11035 } 11036 11037 DiagnoseNullConversion(S, E, T, CC); 11038 11039 S.DiscardMisalignedMemberAddress(Target, E); 11040 11041 if (!Source->isIntegerType() || !Target->isIntegerType()) 11042 return; 11043 11044 // TODO: remove this early return once the false positives for constant->bool 11045 // in templates, macros, etc, are reduced or removed. 11046 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11047 return; 11048 11049 IntRange SourceRange = GetExprRange(S.Context, E); 11050 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11051 11052 if (SourceRange.Width > TargetRange.Width) { 11053 // If the source is a constant, use a default-on diagnostic. 11054 // TODO: this should happen for bitfield stores, too. 11055 Expr::EvalResult Result; 11056 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11057 llvm::APSInt Value(32); 11058 Value = Result.Val.getInt(); 11059 11060 if (S.SourceMgr.isInSystemMacro(CC)) 11061 return; 11062 11063 std::string PrettySourceValue = Value.toString(10); 11064 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11065 11066 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11067 S.PDiag(diag::warn_impcast_integer_precision_constant) 11068 << PrettySourceValue << PrettyTargetValue 11069 << E->getType() << T << E->getSourceRange() 11070 << clang::SourceRange(CC)); 11071 return; 11072 } 11073 11074 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11075 if (S.SourceMgr.isInSystemMacro(CC)) 11076 return; 11077 11078 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11079 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11080 /* pruneControlFlow */ true); 11081 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11082 } 11083 11084 if (TargetRange.Width > SourceRange.Width) { 11085 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11086 if (UO->getOpcode() == UO_Minus) 11087 if (Source->isUnsignedIntegerType()) { 11088 if (Target->isUnsignedIntegerType()) 11089 return DiagnoseImpCast(S, E, T, CC, 11090 diag::warn_impcast_high_order_zero_bits); 11091 if (Target->isSignedIntegerType()) 11092 return DiagnoseImpCast(S, E, T, CC, 11093 diag::warn_impcast_nonnegative_result); 11094 } 11095 } 11096 11097 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11098 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11099 // Warn when doing a signed to signed conversion, warn if the positive 11100 // source value is exactly the width of the target type, which will 11101 // cause a negative value to be stored. 11102 11103 Expr::EvalResult Result; 11104 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11105 !S.SourceMgr.isInSystemMacro(CC)) { 11106 llvm::APSInt Value = Result.Val.getInt(); 11107 if (isSameWidthConstantConversion(S, E, T, CC)) { 11108 std::string PrettySourceValue = Value.toString(10); 11109 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11110 11111 S.DiagRuntimeBehavior( 11112 E->getExprLoc(), E, 11113 S.PDiag(diag::warn_impcast_integer_precision_constant) 11114 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11115 << E->getSourceRange() << clang::SourceRange(CC)); 11116 return; 11117 } 11118 } 11119 11120 // Fall through for non-constants to give a sign conversion warning. 11121 } 11122 11123 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11124 (!TargetRange.NonNegative && SourceRange.NonNegative && 11125 SourceRange.Width == TargetRange.Width)) { 11126 if (S.SourceMgr.isInSystemMacro(CC)) 11127 return; 11128 11129 unsigned DiagID = diag::warn_impcast_integer_sign; 11130 11131 // Traditionally, gcc has warned about this under -Wsign-compare. 11132 // We also want to warn about it in -Wconversion. 11133 // So if -Wconversion is off, use a completely identical diagnostic 11134 // in the sign-compare group. 11135 // The conditional-checking code will 11136 if (ICContext) { 11137 DiagID = diag::warn_impcast_integer_sign_conditional; 11138 *ICContext = true; 11139 } 11140 11141 return DiagnoseImpCast(S, E, T, CC, DiagID); 11142 } 11143 11144 // Diagnose conversions between different enumeration types. 11145 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11146 // type, to give us better diagnostics. 11147 QualType SourceType = E->getType(); 11148 if (!S.getLangOpts().CPlusPlus) { 11149 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11150 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11151 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11152 SourceType = S.Context.getTypeDeclType(Enum); 11153 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11154 } 11155 } 11156 11157 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11158 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11159 if (SourceEnum->getDecl()->hasNameForLinkage() && 11160 TargetEnum->getDecl()->hasNameForLinkage() && 11161 SourceEnum != TargetEnum) { 11162 if (S.SourceMgr.isInSystemMacro(CC)) 11163 return; 11164 11165 return DiagnoseImpCast(S, E, SourceType, T, CC, 11166 diag::warn_impcast_different_enum_types); 11167 } 11168 } 11169 11170 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11171 SourceLocation CC, QualType T); 11172 11173 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11174 SourceLocation CC, bool &ICContext) { 11175 E = E->IgnoreParenImpCasts(); 11176 11177 if (isa<ConditionalOperator>(E)) 11178 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11179 11180 AnalyzeImplicitConversions(S, E, CC); 11181 if (E->getType() != T) 11182 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11183 } 11184 11185 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11186 SourceLocation CC, QualType T) { 11187 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11188 11189 bool Suspicious = false; 11190 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11191 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11192 11193 // If -Wconversion would have warned about either of the candidates 11194 // for a signedness conversion to the context type... 11195 if (!Suspicious) return; 11196 11197 // ...but it's currently ignored... 11198 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11199 return; 11200 11201 // ...then check whether it would have warned about either of the 11202 // candidates for a signedness conversion to the condition type. 11203 if (E->getType() == T) return; 11204 11205 Suspicious = false; 11206 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11207 E->getType(), CC, &Suspicious); 11208 if (!Suspicious) 11209 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11210 E->getType(), CC, &Suspicious); 11211 } 11212 11213 /// Check conversion of given expression to boolean. 11214 /// Input argument E is a logical expression. 11215 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11216 if (S.getLangOpts().Bool) 11217 return; 11218 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11219 return; 11220 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11221 } 11222 11223 /// AnalyzeImplicitConversions - Find and report any interesting 11224 /// implicit conversions in the given expression. There are a couple 11225 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11226 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 11227 SourceLocation CC) { 11228 QualType T = OrigE->getType(); 11229 Expr *E = OrigE->IgnoreParenImpCasts(); 11230 11231 if (E->isTypeDependent() || E->isValueDependent()) 11232 return; 11233 11234 // For conditional operators, we analyze the arguments as if they 11235 // were being fed directly into the output. 11236 if (isa<ConditionalOperator>(E)) { 11237 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11238 CheckConditionalOperator(S, CO, CC, T); 11239 return; 11240 } 11241 11242 // Check implicit argument conversions for function calls. 11243 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11244 CheckImplicitArgumentConversions(S, Call, CC); 11245 11246 // Go ahead and check any implicit conversions we might have skipped. 11247 // The non-canonical typecheck is just an optimization; 11248 // CheckImplicitConversion will filter out dead implicit conversions. 11249 if (E->getType() != T) 11250 CheckImplicitConversion(S, E, T, CC); 11251 11252 // Now continue drilling into this expression. 11253 11254 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11255 // The bound subexpressions in a PseudoObjectExpr are not reachable 11256 // as transitive children. 11257 // FIXME: Use a more uniform representation for this. 11258 for (auto *SE : POE->semantics()) 11259 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11260 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 11261 } 11262 11263 // Skip past explicit casts. 11264 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11265 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11266 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11267 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11268 return AnalyzeImplicitConversions(S, E, CC); 11269 } 11270 11271 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11272 // Do a somewhat different check with comparison operators. 11273 if (BO->isComparisonOp()) 11274 return AnalyzeComparison(S, BO); 11275 11276 // And with simple assignments. 11277 if (BO->getOpcode() == BO_Assign) 11278 return AnalyzeAssignment(S, BO); 11279 // And with compound assignments. 11280 if (BO->isAssignmentOp()) 11281 return AnalyzeCompoundAssignment(S, BO); 11282 } 11283 11284 // These break the otherwise-useful invariant below. Fortunately, 11285 // we don't really need to recurse into them, because any internal 11286 // expressions should have been analyzed already when they were 11287 // built into statements. 11288 if (isa<StmtExpr>(E)) return; 11289 11290 // Don't descend into unevaluated contexts. 11291 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11292 11293 // Now just recurse over the expression's children. 11294 CC = E->getExprLoc(); 11295 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11296 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11297 for (Stmt *SubStmt : E->children()) { 11298 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11299 if (!ChildExpr) 11300 continue; 11301 11302 if (IsLogicalAndOperator && 11303 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11304 // Ignore checking string literals that are in logical and operators. 11305 // This is a common pattern for asserts. 11306 continue; 11307 AnalyzeImplicitConversions(S, ChildExpr, CC); 11308 } 11309 11310 if (BO && BO->isLogicalOp()) { 11311 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11312 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11313 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11314 11315 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11316 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11317 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11318 } 11319 11320 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11321 if (U->getOpcode() == UO_LNot) { 11322 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11323 } else if (U->getOpcode() != UO_AddrOf) { 11324 if (U->getSubExpr()->getType()->isAtomicType()) 11325 S.Diag(U->getSubExpr()->getBeginLoc(), 11326 diag::warn_atomic_implicit_seq_cst); 11327 } 11328 } 11329 } 11330 11331 /// Diagnose integer type and any valid implicit conversion to it. 11332 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11333 // Taking into account implicit conversions, 11334 // allow any integer. 11335 if (!E->getType()->isIntegerType()) { 11336 S.Diag(E->getBeginLoc(), 11337 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11338 return true; 11339 } 11340 // Potentially emit standard warnings for implicit conversions if enabled 11341 // using -Wconversion. 11342 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11343 return false; 11344 } 11345 11346 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11347 // Returns true when emitting a warning about taking the address of a reference. 11348 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11349 const PartialDiagnostic &PD) { 11350 E = E->IgnoreParenImpCasts(); 11351 11352 const FunctionDecl *FD = nullptr; 11353 11354 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11355 if (!DRE->getDecl()->getType()->isReferenceType()) 11356 return false; 11357 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11358 if (!M->getMemberDecl()->getType()->isReferenceType()) 11359 return false; 11360 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11361 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11362 return false; 11363 FD = Call->getDirectCallee(); 11364 } else { 11365 return false; 11366 } 11367 11368 SemaRef.Diag(E->getExprLoc(), PD); 11369 11370 // If possible, point to location of function. 11371 if (FD) { 11372 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11373 } 11374 11375 return true; 11376 } 11377 11378 // Returns true if the SourceLocation is expanded from any macro body. 11379 // Returns false if the SourceLocation is invalid, is from not in a macro 11380 // expansion, or is from expanded from a top-level macro argument. 11381 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11382 if (Loc.isInvalid()) 11383 return false; 11384 11385 while (Loc.isMacroID()) { 11386 if (SM.isMacroBodyExpansion(Loc)) 11387 return true; 11388 Loc = SM.getImmediateMacroCallerLoc(Loc); 11389 } 11390 11391 return false; 11392 } 11393 11394 /// Diagnose pointers that are always non-null. 11395 /// \param E the expression containing the pointer 11396 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11397 /// compared to a null pointer 11398 /// \param IsEqual True when the comparison is equal to a null pointer 11399 /// \param Range Extra SourceRange to highlight in the diagnostic 11400 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11401 Expr::NullPointerConstantKind NullKind, 11402 bool IsEqual, SourceRange Range) { 11403 if (!E) 11404 return; 11405 11406 // Don't warn inside macros. 11407 if (E->getExprLoc().isMacroID()) { 11408 const SourceManager &SM = getSourceManager(); 11409 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11410 IsInAnyMacroBody(SM, Range.getBegin())) 11411 return; 11412 } 11413 E = E->IgnoreImpCasts(); 11414 11415 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11416 11417 if (isa<CXXThisExpr>(E)) { 11418 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11419 : diag::warn_this_bool_conversion; 11420 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11421 return; 11422 } 11423 11424 bool IsAddressOf = false; 11425 11426 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11427 if (UO->getOpcode() != UO_AddrOf) 11428 return; 11429 IsAddressOf = true; 11430 E = UO->getSubExpr(); 11431 } 11432 11433 if (IsAddressOf) { 11434 unsigned DiagID = IsCompare 11435 ? diag::warn_address_of_reference_null_compare 11436 : diag::warn_address_of_reference_bool_conversion; 11437 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11438 << IsEqual; 11439 if (CheckForReference(*this, E, PD)) { 11440 return; 11441 } 11442 } 11443 11444 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11445 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11446 std::string Str; 11447 llvm::raw_string_ostream S(Str); 11448 E->printPretty(S, nullptr, getPrintingPolicy()); 11449 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11450 : diag::warn_cast_nonnull_to_bool; 11451 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11452 << E->getSourceRange() << Range << IsEqual; 11453 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11454 }; 11455 11456 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11457 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11458 if (auto *Callee = Call->getDirectCallee()) { 11459 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11460 ComplainAboutNonnullParamOrCall(A); 11461 return; 11462 } 11463 } 11464 } 11465 11466 // Expect to find a single Decl. Skip anything more complicated. 11467 ValueDecl *D = nullptr; 11468 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11469 D = R->getDecl(); 11470 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11471 D = M->getMemberDecl(); 11472 } 11473 11474 // Weak Decls can be null. 11475 if (!D || D->isWeak()) 11476 return; 11477 11478 // Check for parameter decl with nonnull attribute 11479 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11480 if (getCurFunction() && 11481 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11482 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11483 ComplainAboutNonnullParamOrCall(A); 11484 return; 11485 } 11486 11487 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11488 auto ParamIter = llvm::find(FD->parameters(), PV); 11489 assert(ParamIter != FD->param_end()); 11490 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11491 11492 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11493 if (!NonNull->args_size()) { 11494 ComplainAboutNonnullParamOrCall(NonNull); 11495 return; 11496 } 11497 11498 for (const ParamIdx &ArgNo : NonNull->args()) { 11499 if (ArgNo.getASTIndex() == ParamNo) { 11500 ComplainAboutNonnullParamOrCall(NonNull); 11501 return; 11502 } 11503 } 11504 } 11505 } 11506 } 11507 } 11508 11509 QualType T = D->getType(); 11510 const bool IsArray = T->isArrayType(); 11511 const bool IsFunction = T->isFunctionType(); 11512 11513 // Address of function is used to silence the function warning. 11514 if (IsAddressOf && IsFunction) { 11515 return; 11516 } 11517 11518 // Found nothing. 11519 if (!IsAddressOf && !IsFunction && !IsArray) 11520 return; 11521 11522 // Pretty print the expression for the diagnostic. 11523 std::string Str; 11524 llvm::raw_string_ostream S(Str); 11525 E->printPretty(S, nullptr, getPrintingPolicy()); 11526 11527 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11528 : diag::warn_impcast_pointer_to_bool; 11529 enum { 11530 AddressOf, 11531 FunctionPointer, 11532 ArrayPointer 11533 } DiagType; 11534 if (IsAddressOf) 11535 DiagType = AddressOf; 11536 else if (IsFunction) 11537 DiagType = FunctionPointer; 11538 else if (IsArray) 11539 DiagType = ArrayPointer; 11540 else 11541 llvm_unreachable("Could not determine diagnostic."); 11542 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11543 << Range << IsEqual; 11544 11545 if (!IsFunction) 11546 return; 11547 11548 // Suggest '&' to silence the function warning. 11549 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11550 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11551 11552 // Check to see if '()' fixit should be emitted. 11553 QualType ReturnType; 11554 UnresolvedSet<4> NonTemplateOverloads; 11555 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11556 if (ReturnType.isNull()) 11557 return; 11558 11559 if (IsCompare) { 11560 // There are two cases here. If there is null constant, the only suggest 11561 // for a pointer return type. If the null is 0, then suggest if the return 11562 // type is a pointer or an integer type. 11563 if (!ReturnType->isPointerType()) { 11564 if (NullKind == Expr::NPCK_ZeroExpression || 11565 NullKind == Expr::NPCK_ZeroLiteral) { 11566 if (!ReturnType->isIntegerType()) 11567 return; 11568 } else { 11569 return; 11570 } 11571 } 11572 } else { // !IsCompare 11573 // For function to bool, only suggest if the function pointer has bool 11574 // return type. 11575 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11576 return; 11577 } 11578 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11579 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11580 } 11581 11582 /// Diagnoses "dangerous" implicit conversions within the given 11583 /// expression (which is a full expression). Implements -Wconversion 11584 /// and -Wsign-compare. 11585 /// 11586 /// \param CC the "context" location of the implicit conversion, i.e. 11587 /// the most location of the syntactic entity requiring the implicit 11588 /// conversion 11589 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11590 // Don't diagnose in unevaluated contexts. 11591 if (isUnevaluatedContext()) 11592 return; 11593 11594 // Don't diagnose for value- or type-dependent expressions. 11595 if (E->isTypeDependent() || E->isValueDependent()) 11596 return; 11597 11598 // Check for array bounds violations in cases where the check isn't triggered 11599 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11600 // ArraySubscriptExpr is on the RHS of a variable initialization. 11601 CheckArrayAccess(E); 11602 11603 // This is not the right CC for (e.g.) a variable initialization. 11604 AnalyzeImplicitConversions(*this, E, CC); 11605 } 11606 11607 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11608 /// Input argument E is a logical expression. 11609 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11610 ::CheckBoolLikeConversion(*this, E, CC); 11611 } 11612 11613 /// Diagnose when expression is an integer constant expression and its evaluation 11614 /// results in integer overflow 11615 void Sema::CheckForIntOverflow (Expr *E) { 11616 // Use a work list to deal with nested struct initializers. 11617 SmallVector<Expr *, 2> Exprs(1, E); 11618 11619 do { 11620 Expr *OriginalE = Exprs.pop_back_val(); 11621 Expr *E = OriginalE->IgnoreParenCasts(); 11622 11623 if (isa<BinaryOperator>(E)) { 11624 E->EvaluateForOverflow(Context); 11625 continue; 11626 } 11627 11628 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11629 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11630 else if (isa<ObjCBoxedExpr>(OriginalE)) 11631 E->EvaluateForOverflow(Context); 11632 else if (auto Call = dyn_cast<CallExpr>(E)) 11633 Exprs.append(Call->arg_begin(), Call->arg_end()); 11634 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 11635 Exprs.append(Message->arg_begin(), Message->arg_end()); 11636 } while (!Exprs.empty()); 11637 } 11638 11639 namespace { 11640 11641 /// Visitor for expressions which looks for unsequenced operations on the 11642 /// same object. 11643 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 11644 using Base = EvaluatedExprVisitor<SequenceChecker>; 11645 11646 /// A tree of sequenced regions within an expression. Two regions are 11647 /// unsequenced if one is an ancestor or a descendent of the other. When we 11648 /// finish processing an expression with sequencing, such as a comma 11649 /// expression, we fold its tree nodes into its parent, since they are 11650 /// unsequenced with respect to nodes we will visit later. 11651 class SequenceTree { 11652 struct Value { 11653 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 11654 unsigned Parent : 31; 11655 unsigned Merged : 1; 11656 }; 11657 SmallVector<Value, 8> Values; 11658 11659 public: 11660 /// A region within an expression which may be sequenced with respect 11661 /// to some other region. 11662 class Seq { 11663 friend class SequenceTree; 11664 11665 unsigned Index; 11666 11667 explicit Seq(unsigned N) : Index(N) {} 11668 11669 public: 11670 Seq() : Index(0) {} 11671 }; 11672 11673 SequenceTree() { Values.push_back(Value(0)); } 11674 Seq root() const { return Seq(0); } 11675 11676 /// Create a new sequence of operations, which is an unsequenced 11677 /// subset of \p Parent. This sequence of operations is sequenced with 11678 /// respect to other children of \p Parent. 11679 Seq allocate(Seq Parent) { 11680 Values.push_back(Value(Parent.Index)); 11681 return Seq(Values.size() - 1); 11682 } 11683 11684 /// Merge a sequence of operations into its parent. 11685 void merge(Seq S) { 11686 Values[S.Index].Merged = true; 11687 } 11688 11689 /// Determine whether two operations are unsequenced. This operation 11690 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 11691 /// should have been merged into its parent as appropriate. 11692 bool isUnsequenced(Seq Cur, Seq Old) { 11693 unsigned C = representative(Cur.Index); 11694 unsigned Target = representative(Old.Index); 11695 while (C >= Target) { 11696 if (C == Target) 11697 return true; 11698 C = Values[C].Parent; 11699 } 11700 return false; 11701 } 11702 11703 private: 11704 /// Pick a representative for a sequence. 11705 unsigned representative(unsigned K) { 11706 if (Values[K].Merged) 11707 // Perform path compression as we go. 11708 return Values[K].Parent = representative(Values[K].Parent); 11709 return K; 11710 } 11711 }; 11712 11713 /// An object for which we can track unsequenced uses. 11714 using Object = NamedDecl *; 11715 11716 /// Different flavors of object usage which we track. We only track the 11717 /// least-sequenced usage of each kind. 11718 enum UsageKind { 11719 /// A read of an object. Multiple unsequenced reads are OK. 11720 UK_Use, 11721 11722 /// A modification of an object which is sequenced before the value 11723 /// computation of the expression, such as ++n in C++. 11724 UK_ModAsValue, 11725 11726 /// A modification of an object which is not sequenced before the value 11727 /// computation of the expression, such as n++. 11728 UK_ModAsSideEffect, 11729 11730 UK_Count = UK_ModAsSideEffect + 1 11731 }; 11732 11733 struct Usage { 11734 Expr *Use; 11735 SequenceTree::Seq Seq; 11736 11737 Usage() : Use(nullptr), Seq() {} 11738 }; 11739 11740 struct UsageInfo { 11741 Usage Uses[UK_Count]; 11742 11743 /// Have we issued a diagnostic for this variable already? 11744 bool Diagnosed; 11745 11746 UsageInfo() : Uses(), Diagnosed(false) {} 11747 }; 11748 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 11749 11750 Sema &SemaRef; 11751 11752 /// Sequenced regions within the expression. 11753 SequenceTree Tree; 11754 11755 /// Declaration modifications and references which we have seen. 11756 UsageInfoMap UsageMap; 11757 11758 /// The region we are currently within. 11759 SequenceTree::Seq Region; 11760 11761 /// Filled in with declarations which were modified as a side-effect 11762 /// (that is, post-increment operations). 11763 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 11764 11765 /// Expressions to check later. We defer checking these to reduce 11766 /// stack usage. 11767 SmallVectorImpl<Expr *> &WorkList; 11768 11769 /// RAII object wrapping the visitation of a sequenced subexpression of an 11770 /// expression. At the end of this process, the side-effects of the evaluation 11771 /// become sequenced with respect to the value computation of the result, so 11772 /// we downgrade any UK_ModAsSideEffect within the evaluation to 11773 /// UK_ModAsValue. 11774 struct SequencedSubexpression { 11775 SequencedSubexpression(SequenceChecker &Self) 11776 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11777 Self.ModAsSideEffect = &ModAsSideEffect; 11778 } 11779 11780 ~SequencedSubexpression() { 11781 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11782 UsageInfo &U = Self.UsageMap[M.first]; 11783 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11784 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11785 SideEffectUsage = M.second; 11786 } 11787 Self.ModAsSideEffect = OldModAsSideEffect; 11788 } 11789 11790 SequenceChecker &Self; 11791 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11792 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11793 }; 11794 11795 /// RAII object wrapping the visitation of a subexpression which we might 11796 /// choose to evaluate as a constant. If any subexpression is evaluated and 11797 /// found to be non-constant, this allows us to suppress the evaluation of 11798 /// the outer expression. 11799 class EvaluationTracker { 11800 public: 11801 EvaluationTracker(SequenceChecker &Self) 11802 : Self(Self), Prev(Self.EvalTracker) { 11803 Self.EvalTracker = this; 11804 } 11805 11806 ~EvaluationTracker() { 11807 Self.EvalTracker = Prev; 11808 if (Prev) 11809 Prev->EvalOK &= EvalOK; 11810 } 11811 11812 bool evaluate(const Expr *E, bool &Result) { 11813 if (!EvalOK || E->isValueDependent()) 11814 return false; 11815 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11816 return EvalOK; 11817 } 11818 11819 private: 11820 SequenceChecker &Self; 11821 EvaluationTracker *Prev; 11822 bool EvalOK = true; 11823 } *EvalTracker = nullptr; 11824 11825 /// Find the object which is produced by the specified expression, 11826 /// if any. 11827 Object getObject(Expr *E, bool Mod) const { 11828 E = E->IgnoreParenCasts(); 11829 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11830 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11831 return getObject(UO->getSubExpr(), Mod); 11832 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11833 if (BO->getOpcode() == BO_Comma) 11834 return getObject(BO->getRHS(), Mod); 11835 if (Mod && BO->isAssignmentOp()) 11836 return getObject(BO->getLHS(), Mod); 11837 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11838 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11839 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11840 return ME->getMemberDecl(); 11841 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11842 // FIXME: If this is a reference, map through to its value. 11843 return DRE->getDecl(); 11844 return nullptr; 11845 } 11846 11847 /// Note that an object was modified or used by an expression. 11848 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11849 Usage &U = UI.Uses[UK]; 11850 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11851 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11852 ModAsSideEffect->push_back(std::make_pair(O, U)); 11853 U.Use = Ref; 11854 U.Seq = Region; 11855 } 11856 } 11857 11858 /// Check whether a modification or use conflicts with a prior usage. 11859 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11860 bool IsModMod) { 11861 if (UI.Diagnosed) 11862 return; 11863 11864 const Usage &U = UI.Uses[OtherKind]; 11865 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11866 return; 11867 11868 Expr *Mod = U.Use; 11869 Expr *ModOrUse = Ref; 11870 if (OtherKind == UK_Use) 11871 std::swap(Mod, ModOrUse); 11872 11873 SemaRef.Diag(Mod->getExprLoc(), 11874 IsModMod ? diag::warn_unsequenced_mod_mod 11875 : diag::warn_unsequenced_mod_use) 11876 << O << SourceRange(ModOrUse->getExprLoc()); 11877 UI.Diagnosed = true; 11878 } 11879 11880 void notePreUse(Object O, Expr *Use) { 11881 UsageInfo &U = UsageMap[O]; 11882 // Uses conflict with other modifications. 11883 checkUsage(O, U, Use, UK_ModAsValue, false); 11884 } 11885 11886 void notePostUse(Object O, Expr *Use) { 11887 UsageInfo &U = UsageMap[O]; 11888 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 11889 addUsage(U, O, Use, UK_Use); 11890 } 11891 11892 void notePreMod(Object O, Expr *Mod) { 11893 UsageInfo &U = UsageMap[O]; 11894 // Modifications conflict with other modifications and with uses. 11895 checkUsage(O, U, Mod, UK_ModAsValue, true); 11896 checkUsage(O, U, Mod, UK_Use, false); 11897 } 11898 11899 void notePostMod(Object O, Expr *Use, UsageKind UK) { 11900 UsageInfo &U = UsageMap[O]; 11901 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 11902 addUsage(U, O, Use, UK); 11903 } 11904 11905 public: 11906 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 11907 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 11908 Visit(E); 11909 } 11910 11911 void VisitStmt(Stmt *S) { 11912 // Skip all statements which aren't expressions for now. 11913 } 11914 11915 void VisitExpr(Expr *E) { 11916 // By default, just recurse to evaluated subexpressions. 11917 Base::VisitStmt(E); 11918 } 11919 11920 void VisitCastExpr(CastExpr *E) { 11921 Object O = Object(); 11922 if (E->getCastKind() == CK_LValueToRValue) 11923 O = getObject(E->getSubExpr(), false); 11924 11925 if (O) 11926 notePreUse(O, E); 11927 VisitExpr(E); 11928 if (O) 11929 notePostUse(O, E); 11930 } 11931 11932 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) { 11933 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 11934 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 11935 SequenceTree::Seq OldRegion = Region; 11936 11937 { 11938 SequencedSubexpression SeqBefore(*this); 11939 Region = BeforeRegion; 11940 Visit(SequencedBefore); 11941 } 11942 11943 Region = AfterRegion; 11944 Visit(SequencedAfter); 11945 11946 Region = OldRegion; 11947 11948 Tree.merge(BeforeRegion); 11949 Tree.merge(AfterRegion); 11950 } 11951 11952 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) { 11953 // C++17 [expr.sub]p1: 11954 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 11955 // expression E1 is sequenced before the expression E2. 11956 if (SemaRef.getLangOpts().CPlusPlus17) 11957 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 11958 else 11959 Base::VisitStmt(ASE); 11960 } 11961 11962 void VisitBinComma(BinaryOperator *BO) { 11963 // C++11 [expr.comma]p1: 11964 // Every value computation and side effect associated with the left 11965 // expression is sequenced before every value computation and side 11966 // effect associated with the right expression. 11967 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 11968 } 11969 11970 void VisitBinAssign(BinaryOperator *BO) { 11971 // The modification is sequenced after the value computation of the LHS 11972 // and RHS, so check it before inspecting the operands and update the 11973 // map afterwards. 11974 Object O = getObject(BO->getLHS(), true); 11975 if (!O) 11976 return VisitExpr(BO); 11977 11978 notePreMod(O, BO); 11979 11980 // C++11 [expr.ass]p7: 11981 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11982 // only once. 11983 // 11984 // Therefore, for a compound assignment operator, O is considered used 11985 // everywhere except within the evaluation of E1 itself. 11986 if (isa<CompoundAssignOperator>(BO)) 11987 notePreUse(O, BO); 11988 11989 Visit(BO->getLHS()); 11990 11991 if (isa<CompoundAssignOperator>(BO)) 11992 notePostUse(O, BO); 11993 11994 Visit(BO->getRHS()); 11995 11996 // C++11 [expr.ass]p1: 11997 // the assignment is sequenced [...] before the value computation of the 11998 // assignment expression. 11999 // C11 6.5.16/3 has no such rule. 12000 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12001 : UK_ModAsSideEffect); 12002 } 12003 12004 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 12005 VisitBinAssign(CAO); 12006 } 12007 12008 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12009 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12010 void VisitUnaryPreIncDec(UnaryOperator *UO) { 12011 Object O = getObject(UO->getSubExpr(), true); 12012 if (!O) 12013 return VisitExpr(UO); 12014 12015 notePreMod(O, UO); 12016 Visit(UO->getSubExpr()); 12017 // C++11 [expr.pre.incr]p1: 12018 // the expression ++x is equivalent to x+=1 12019 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12020 : UK_ModAsSideEffect); 12021 } 12022 12023 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12024 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12025 void VisitUnaryPostIncDec(UnaryOperator *UO) { 12026 Object O = getObject(UO->getSubExpr(), true); 12027 if (!O) 12028 return VisitExpr(UO); 12029 12030 notePreMod(O, UO); 12031 Visit(UO->getSubExpr()); 12032 notePostMod(O, UO, UK_ModAsSideEffect); 12033 } 12034 12035 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 12036 void VisitBinLOr(BinaryOperator *BO) { 12037 // The side-effects of the LHS of an '&&' are sequenced before the 12038 // value computation of the RHS, and hence before the value computation 12039 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 12040 // as if they were unconditionally sequenced. 12041 EvaluationTracker Eval(*this); 12042 { 12043 SequencedSubexpression Sequenced(*this); 12044 Visit(BO->getLHS()); 12045 } 12046 12047 bool Result; 12048 if (Eval.evaluate(BO->getLHS(), Result)) { 12049 if (!Result) 12050 Visit(BO->getRHS()); 12051 } else { 12052 // Check for unsequenced operations in the RHS, treating it as an 12053 // entirely separate evaluation. 12054 // 12055 // FIXME: If there are operations in the RHS which are unsequenced 12056 // with respect to operations outside the RHS, and those operations 12057 // are unconditionally evaluated, diagnose them. 12058 WorkList.push_back(BO->getRHS()); 12059 } 12060 } 12061 void VisitBinLAnd(BinaryOperator *BO) { 12062 EvaluationTracker Eval(*this); 12063 { 12064 SequencedSubexpression Sequenced(*this); 12065 Visit(BO->getLHS()); 12066 } 12067 12068 bool Result; 12069 if (Eval.evaluate(BO->getLHS(), Result)) { 12070 if (Result) 12071 Visit(BO->getRHS()); 12072 } else { 12073 WorkList.push_back(BO->getRHS()); 12074 } 12075 } 12076 12077 // Only visit the condition, unless we can be sure which subexpression will 12078 // be chosen. 12079 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 12080 EvaluationTracker Eval(*this); 12081 { 12082 SequencedSubexpression Sequenced(*this); 12083 Visit(CO->getCond()); 12084 } 12085 12086 bool Result; 12087 if (Eval.evaluate(CO->getCond(), Result)) 12088 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 12089 else { 12090 WorkList.push_back(CO->getTrueExpr()); 12091 WorkList.push_back(CO->getFalseExpr()); 12092 } 12093 } 12094 12095 void VisitCallExpr(CallExpr *CE) { 12096 // C++11 [intro.execution]p15: 12097 // When calling a function [...], every value computation and side effect 12098 // associated with any argument expression, or with the postfix expression 12099 // designating the called function, is sequenced before execution of every 12100 // expression or statement in the body of the function [and thus before 12101 // the value computation of its result]. 12102 SequencedSubexpression Sequenced(*this); 12103 Base::VisitCallExpr(CE); 12104 12105 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12106 } 12107 12108 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 12109 // This is a call, so all subexpressions are sequenced before the result. 12110 SequencedSubexpression Sequenced(*this); 12111 12112 if (!CCE->isListInitialization()) 12113 return VisitExpr(CCE); 12114 12115 // In C++11, list initializations are sequenced. 12116 SmallVector<SequenceTree::Seq, 32> Elts; 12117 SequenceTree::Seq Parent = Region; 12118 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 12119 E = CCE->arg_end(); 12120 I != E; ++I) { 12121 Region = Tree.allocate(Parent); 12122 Elts.push_back(Region); 12123 Visit(*I); 12124 } 12125 12126 // Forget that the initializers are sequenced. 12127 Region = Parent; 12128 for (unsigned I = 0; I < Elts.size(); ++I) 12129 Tree.merge(Elts[I]); 12130 } 12131 12132 void VisitInitListExpr(InitListExpr *ILE) { 12133 if (!SemaRef.getLangOpts().CPlusPlus11) 12134 return VisitExpr(ILE); 12135 12136 // In C++11, list initializations are sequenced. 12137 SmallVector<SequenceTree::Seq, 32> Elts; 12138 SequenceTree::Seq Parent = Region; 12139 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12140 Expr *E = ILE->getInit(I); 12141 if (!E) continue; 12142 Region = Tree.allocate(Parent); 12143 Elts.push_back(Region); 12144 Visit(E); 12145 } 12146 12147 // Forget that the initializers are sequenced. 12148 Region = Parent; 12149 for (unsigned I = 0; I < Elts.size(); ++I) 12150 Tree.merge(Elts[I]); 12151 } 12152 }; 12153 12154 } // namespace 12155 12156 void Sema::CheckUnsequencedOperations(Expr *E) { 12157 SmallVector<Expr *, 8> WorkList; 12158 WorkList.push_back(E); 12159 while (!WorkList.empty()) { 12160 Expr *Item = WorkList.pop_back_val(); 12161 SequenceChecker(*this, Item, WorkList); 12162 } 12163 } 12164 12165 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12166 bool IsConstexpr) { 12167 CheckImplicitConversions(E, CheckLoc); 12168 if (!E->isInstantiationDependent()) 12169 CheckUnsequencedOperations(E); 12170 if (!IsConstexpr && !E->isValueDependent()) 12171 CheckForIntOverflow(E); 12172 DiagnoseMisalignedMembers(); 12173 } 12174 12175 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12176 FieldDecl *BitField, 12177 Expr *Init) { 12178 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12179 } 12180 12181 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12182 SourceLocation Loc) { 12183 if (!PType->isVariablyModifiedType()) 12184 return; 12185 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12186 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12187 return; 12188 } 12189 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12190 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12191 return; 12192 } 12193 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12194 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12195 return; 12196 } 12197 12198 const ArrayType *AT = S.Context.getAsArrayType(PType); 12199 if (!AT) 12200 return; 12201 12202 if (AT->getSizeModifier() != ArrayType::Star) { 12203 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12204 return; 12205 } 12206 12207 S.Diag(Loc, diag::err_array_star_in_function_definition); 12208 } 12209 12210 /// CheckParmsForFunctionDef - Check that the parameters of the given 12211 /// function are appropriate for the definition of a function. This 12212 /// takes care of any checks that cannot be performed on the 12213 /// declaration itself, e.g., that the types of each of the function 12214 /// parameters are complete. 12215 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12216 bool CheckParameterNames) { 12217 bool HasInvalidParm = false; 12218 for (ParmVarDecl *Param : Parameters) { 12219 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12220 // function declarator that is part of a function definition of 12221 // that function shall not have incomplete type. 12222 // 12223 // This is also C++ [dcl.fct]p6. 12224 if (!Param->isInvalidDecl() && 12225 RequireCompleteType(Param->getLocation(), Param->getType(), 12226 diag::err_typecheck_decl_incomplete_type)) { 12227 Param->setInvalidDecl(); 12228 HasInvalidParm = true; 12229 } 12230 12231 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12232 // declaration of each parameter shall include an identifier. 12233 if (CheckParameterNames && 12234 Param->getIdentifier() == nullptr && 12235 !Param->isImplicit() && 12236 !getLangOpts().CPlusPlus) 12237 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12238 12239 // C99 6.7.5.3p12: 12240 // If the function declarator is not part of a definition of that 12241 // function, parameters may have incomplete type and may use the [*] 12242 // notation in their sequences of declarator specifiers to specify 12243 // variable length array types. 12244 QualType PType = Param->getOriginalType(); 12245 // FIXME: This diagnostic should point the '[*]' if source-location 12246 // information is added for it. 12247 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12248 12249 // If the parameter is a c++ class type and it has to be destructed in the 12250 // callee function, declare the destructor so that it can be called by the 12251 // callee function. Do not perform any direct access check on the dtor here. 12252 if (!Param->isInvalidDecl()) { 12253 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12254 if (!ClassDecl->isInvalidDecl() && 12255 !ClassDecl->hasIrrelevantDestructor() && 12256 !ClassDecl->isDependentContext() && 12257 ClassDecl->isParamDestroyedInCallee()) { 12258 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12259 MarkFunctionReferenced(Param->getLocation(), Destructor); 12260 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12261 } 12262 } 12263 } 12264 12265 // Parameters with the pass_object_size attribute only need to be marked 12266 // constant at function definitions. Because we lack information about 12267 // whether we're on a declaration or definition when we're instantiating the 12268 // attribute, we need to check for constness here. 12269 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12270 if (!Param->getType().isConstQualified()) 12271 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12272 << Attr->getSpelling() << 1; 12273 12274 // Check for parameter names shadowing fields from the class. 12275 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 12276 // The owning context for the parameter should be the function, but we 12277 // want to see if this function's declaration context is a record. 12278 DeclContext *DC = Param->getDeclContext(); 12279 if (DC && DC->isFunctionOrMethod()) { 12280 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 12281 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 12282 RD, /*DeclIsField*/ false); 12283 } 12284 } 12285 } 12286 12287 return HasInvalidParm; 12288 } 12289 12290 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12291 /// or MemberExpr. 12292 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12293 ASTContext &Context) { 12294 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12295 return Context.getDeclAlign(DRE->getDecl()); 12296 12297 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12298 return Context.getDeclAlign(ME->getMemberDecl()); 12299 12300 return TypeAlign; 12301 } 12302 12303 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12304 /// pointer cast increases the alignment requirements. 12305 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12306 // This is actually a lot of work to potentially be doing on every 12307 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12308 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12309 return; 12310 12311 // Ignore dependent types. 12312 if (T->isDependentType() || Op->getType()->isDependentType()) 12313 return; 12314 12315 // Require that the destination be a pointer type. 12316 const PointerType *DestPtr = T->getAs<PointerType>(); 12317 if (!DestPtr) return; 12318 12319 // If the destination has alignment 1, we're done. 12320 QualType DestPointee = DestPtr->getPointeeType(); 12321 if (DestPointee->isIncompleteType()) return; 12322 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12323 if (DestAlign.isOne()) return; 12324 12325 // Require that the source be a pointer type. 12326 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12327 if (!SrcPtr) return; 12328 QualType SrcPointee = SrcPtr->getPointeeType(); 12329 12330 // Whitelist casts from cv void*. We already implicitly 12331 // whitelisted casts to cv void*, since they have alignment 1. 12332 // Also whitelist casts involving incomplete types, which implicitly 12333 // includes 'void'. 12334 if (SrcPointee->isIncompleteType()) return; 12335 12336 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12337 12338 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12339 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12340 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12341 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12342 if (UO->getOpcode() == UO_AddrOf) 12343 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12344 } 12345 12346 if (SrcAlign >= DestAlign) return; 12347 12348 Diag(TRange.getBegin(), diag::warn_cast_align) 12349 << Op->getType() << T 12350 << static_cast<unsigned>(SrcAlign.getQuantity()) 12351 << static_cast<unsigned>(DestAlign.getQuantity()) 12352 << TRange << Op->getSourceRange(); 12353 } 12354 12355 /// Check whether this array fits the idiom of a size-one tail padded 12356 /// array member of a struct. 12357 /// 12358 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12359 /// commonly used to emulate flexible arrays in C89 code. 12360 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12361 const NamedDecl *ND) { 12362 if (Size != 1 || !ND) return false; 12363 12364 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12365 if (!FD) return false; 12366 12367 // Don't consider sizes resulting from macro expansions or template argument 12368 // substitution to form C89 tail-padded arrays. 12369 12370 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12371 while (TInfo) { 12372 TypeLoc TL = TInfo->getTypeLoc(); 12373 // Look through typedefs. 12374 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12375 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12376 TInfo = TDL->getTypeSourceInfo(); 12377 continue; 12378 } 12379 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12380 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12381 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12382 return false; 12383 } 12384 break; 12385 } 12386 12387 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12388 if (!RD) return false; 12389 if (RD->isUnion()) return false; 12390 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12391 if (!CRD->isStandardLayout()) return false; 12392 } 12393 12394 // See if this is the last field decl in the record. 12395 const Decl *D = FD; 12396 while ((D = D->getNextDeclInContext())) 12397 if (isa<FieldDecl>(D)) 12398 return false; 12399 return true; 12400 } 12401 12402 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12403 const ArraySubscriptExpr *ASE, 12404 bool AllowOnePastEnd, bool IndexNegated) { 12405 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12406 if (IndexExpr->isValueDependent()) 12407 return; 12408 12409 const Type *EffectiveType = 12410 BaseExpr->getType()->getPointeeOrArrayElementType(); 12411 BaseExpr = BaseExpr->IgnoreParenCasts(); 12412 const ConstantArrayType *ArrayTy = 12413 Context.getAsConstantArrayType(BaseExpr->getType()); 12414 12415 if (!ArrayTy) 12416 return; 12417 12418 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 12419 12420 Expr::EvalResult Result; 12421 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 12422 return; 12423 12424 llvm::APSInt index = Result.Val.getInt(); 12425 if (IndexNegated) 12426 index = -index; 12427 12428 const NamedDecl *ND = nullptr; 12429 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12430 ND = DRE->getDecl(); 12431 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12432 ND = ME->getMemberDecl(); 12433 12434 if (index.isUnsigned() || !index.isNegative()) { 12435 // It is possible that the type of the base expression after 12436 // IgnoreParenCasts is incomplete, even though the type of the base 12437 // expression before IgnoreParenCasts is complete (see PR39746 for an 12438 // example). In this case we have no information about whether the array 12439 // access exceeds the array bounds. However we can still diagnose an array 12440 // access which precedes the array bounds. 12441 if (BaseType->isIncompleteType()) 12442 return; 12443 12444 llvm::APInt size = ArrayTy->getSize(); 12445 if (!size.isStrictlyPositive()) 12446 return; 12447 12448 if (BaseType != EffectiveType) { 12449 // Make sure we're comparing apples to apples when comparing index to size 12450 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12451 uint64_t array_typesize = Context.getTypeSize(BaseType); 12452 // Handle ptrarith_typesize being zero, such as when casting to void* 12453 if (!ptrarith_typesize) ptrarith_typesize = 1; 12454 if (ptrarith_typesize != array_typesize) { 12455 // There's a cast to a different size type involved 12456 uint64_t ratio = array_typesize / ptrarith_typesize; 12457 // TODO: Be smarter about handling cases where array_typesize is not a 12458 // multiple of ptrarith_typesize 12459 if (ptrarith_typesize * ratio == array_typesize) 12460 size *= llvm::APInt(size.getBitWidth(), ratio); 12461 } 12462 } 12463 12464 if (size.getBitWidth() > index.getBitWidth()) 12465 index = index.zext(size.getBitWidth()); 12466 else if (size.getBitWidth() < index.getBitWidth()) 12467 size = size.zext(index.getBitWidth()); 12468 12469 // For array subscripting the index must be less than size, but for pointer 12470 // arithmetic also allow the index (offset) to be equal to size since 12471 // computing the next address after the end of the array is legal and 12472 // commonly done e.g. in C++ iterators and range-based for loops. 12473 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12474 return; 12475 12476 // Also don't warn for arrays of size 1 which are members of some 12477 // structure. These are often used to approximate flexible arrays in C89 12478 // code. 12479 if (IsTailPaddedMemberArray(*this, size, ND)) 12480 return; 12481 12482 // Suppress the warning if the subscript expression (as identified by the 12483 // ']' location) and the index expression are both from macro expansions 12484 // within a system header. 12485 if (ASE) { 12486 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12487 ASE->getRBracketLoc()); 12488 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12489 SourceLocation IndexLoc = 12490 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12491 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12492 return; 12493 } 12494 } 12495 12496 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12497 if (ASE) 12498 DiagID = diag::warn_array_index_exceeds_bounds; 12499 12500 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12501 PDiag(DiagID) << index.toString(10, true) 12502 << size.toString(10, true) 12503 << (unsigned)size.getLimitedValue(~0U) 12504 << IndexExpr->getSourceRange()); 12505 } else { 12506 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12507 if (!ASE) { 12508 DiagID = diag::warn_ptr_arith_precedes_bounds; 12509 if (index.isNegative()) index = -index; 12510 } 12511 12512 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12513 PDiag(DiagID) << index.toString(10, true) 12514 << IndexExpr->getSourceRange()); 12515 } 12516 12517 if (!ND) { 12518 // Try harder to find a NamedDecl to point at in the note. 12519 while (const ArraySubscriptExpr *ASE = 12520 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12521 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12522 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12523 ND = DRE->getDecl(); 12524 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12525 ND = ME->getMemberDecl(); 12526 } 12527 12528 if (ND) 12529 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12530 PDiag(diag::note_array_index_out_of_bounds) 12531 << ND->getDeclName()); 12532 } 12533 12534 void Sema::CheckArrayAccess(const Expr *expr) { 12535 int AllowOnePastEnd = 0; 12536 while (expr) { 12537 expr = expr->IgnoreParenImpCasts(); 12538 switch (expr->getStmtClass()) { 12539 case Stmt::ArraySubscriptExprClass: { 12540 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12541 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12542 AllowOnePastEnd > 0); 12543 expr = ASE->getBase(); 12544 break; 12545 } 12546 case Stmt::MemberExprClass: { 12547 expr = cast<MemberExpr>(expr)->getBase(); 12548 break; 12549 } 12550 case Stmt::OMPArraySectionExprClass: { 12551 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12552 if (ASE->getLowerBound()) 12553 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12554 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12555 return; 12556 } 12557 case Stmt::UnaryOperatorClass: { 12558 // Only unwrap the * and & unary operators 12559 const UnaryOperator *UO = cast<UnaryOperator>(expr); 12560 expr = UO->getSubExpr(); 12561 switch (UO->getOpcode()) { 12562 case UO_AddrOf: 12563 AllowOnePastEnd++; 12564 break; 12565 case UO_Deref: 12566 AllowOnePastEnd--; 12567 break; 12568 default: 12569 return; 12570 } 12571 break; 12572 } 12573 case Stmt::ConditionalOperatorClass: { 12574 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 12575 if (const Expr *lhs = cond->getLHS()) 12576 CheckArrayAccess(lhs); 12577 if (const Expr *rhs = cond->getRHS()) 12578 CheckArrayAccess(rhs); 12579 return; 12580 } 12581 case Stmt::CXXOperatorCallExprClass: { 12582 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 12583 for (const auto *Arg : OCE->arguments()) 12584 CheckArrayAccess(Arg); 12585 return; 12586 } 12587 default: 12588 return; 12589 } 12590 } 12591 } 12592 12593 //===--- CHECK: Objective-C retain cycles ----------------------------------// 12594 12595 namespace { 12596 12597 struct RetainCycleOwner { 12598 VarDecl *Variable = nullptr; 12599 SourceRange Range; 12600 SourceLocation Loc; 12601 bool Indirect = false; 12602 12603 RetainCycleOwner() = default; 12604 12605 void setLocsFrom(Expr *e) { 12606 Loc = e->getExprLoc(); 12607 Range = e->getSourceRange(); 12608 } 12609 }; 12610 12611 } // namespace 12612 12613 /// Consider whether capturing the given variable can possibly lead to 12614 /// a retain cycle. 12615 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 12616 // In ARC, it's captured strongly iff the variable has __strong 12617 // lifetime. In MRR, it's captured strongly if the variable is 12618 // __block and has an appropriate type. 12619 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12620 return false; 12621 12622 owner.Variable = var; 12623 if (ref) 12624 owner.setLocsFrom(ref); 12625 return true; 12626 } 12627 12628 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 12629 while (true) { 12630 e = e->IgnoreParens(); 12631 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 12632 switch (cast->getCastKind()) { 12633 case CK_BitCast: 12634 case CK_LValueBitCast: 12635 case CK_LValueToRValue: 12636 case CK_ARCReclaimReturnedObject: 12637 e = cast->getSubExpr(); 12638 continue; 12639 12640 default: 12641 return false; 12642 } 12643 } 12644 12645 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 12646 ObjCIvarDecl *ivar = ref->getDecl(); 12647 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12648 return false; 12649 12650 // Try to find a retain cycle in the base. 12651 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 12652 return false; 12653 12654 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 12655 owner.Indirect = true; 12656 return true; 12657 } 12658 12659 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 12660 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 12661 if (!var) return false; 12662 return considerVariable(var, ref, owner); 12663 } 12664 12665 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 12666 if (member->isArrow()) return false; 12667 12668 // Don't count this as an indirect ownership. 12669 e = member->getBase(); 12670 continue; 12671 } 12672 12673 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 12674 // Only pay attention to pseudo-objects on property references. 12675 ObjCPropertyRefExpr *pre 12676 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 12677 ->IgnoreParens()); 12678 if (!pre) return false; 12679 if (pre->isImplicitProperty()) return false; 12680 ObjCPropertyDecl *property = pre->getExplicitProperty(); 12681 if (!property->isRetaining() && 12682 !(property->getPropertyIvarDecl() && 12683 property->getPropertyIvarDecl()->getType() 12684 .getObjCLifetime() == Qualifiers::OCL_Strong)) 12685 return false; 12686 12687 owner.Indirect = true; 12688 if (pre->isSuperReceiver()) { 12689 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 12690 if (!owner.Variable) 12691 return false; 12692 owner.Loc = pre->getLocation(); 12693 owner.Range = pre->getSourceRange(); 12694 return true; 12695 } 12696 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 12697 ->getSourceExpr()); 12698 continue; 12699 } 12700 12701 // Array ivars? 12702 12703 return false; 12704 } 12705 } 12706 12707 namespace { 12708 12709 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 12710 ASTContext &Context; 12711 VarDecl *Variable; 12712 Expr *Capturer = nullptr; 12713 bool VarWillBeReased = false; 12714 12715 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 12716 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 12717 Context(Context), Variable(variable) {} 12718 12719 void VisitDeclRefExpr(DeclRefExpr *ref) { 12720 if (ref->getDecl() == Variable && !Capturer) 12721 Capturer = ref; 12722 } 12723 12724 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 12725 if (Capturer) return; 12726 Visit(ref->getBase()); 12727 if (Capturer && ref->isFreeIvar()) 12728 Capturer = ref; 12729 } 12730 12731 void VisitBlockExpr(BlockExpr *block) { 12732 // Look inside nested blocks 12733 if (block->getBlockDecl()->capturesVariable(Variable)) 12734 Visit(block->getBlockDecl()->getBody()); 12735 } 12736 12737 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 12738 if (Capturer) return; 12739 if (OVE->getSourceExpr()) 12740 Visit(OVE->getSourceExpr()); 12741 } 12742 12743 void VisitBinaryOperator(BinaryOperator *BinOp) { 12744 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 12745 return; 12746 Expr *LHS = BinOp->getLHS(); 12747 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 12748 if (DRE->getDecl() != Variable) 12749 return; 12750 if (Expr *RHS = BinOp->getRHS()) { 12751 RHS = RHS->IgnoreParenCasts(); 12752 llvm::APSInt Value; 12753 VarWillBeReased = 12754 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 12755 } 12756 } 12757 } 12758 }; 12759 12760 } // namespace 12761 12762 /// Check whether the given argument is a block which captures a 12763 /// variable. 12764 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 12765 assert(owner.Variable && owner.Loc.isValid()); 12766 12767 e = e->IgnoreParenCasts(); 12768 12769 // Look through [^{...} copy] and Block_copy(^{...}). 12770 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 12771 Selector Cmd = ME->getSelector(); 12772 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 12773 e = ME->getInstanceReceiver(); 12774 if (!e) 12775 return nullptr; 12776 e = e->IgnoreParenCasts(); 12777 } 12778 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 12779 if (CE->getNumArgs() == 1) { 12780 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 12781 if (Fn) { 12782 const IdentifierInfo *FnI = Fn->getIdentifier(); 12783 if (FnI && FnI->isStr("_Block_copy")) { 12784 e = CE->getArg(0)->IgnoreParenCasts(); 12785 } 12786 } 12787 } 12788 } 12789 12790 BlockExpr *block = dyn_cast<BlockExpr>(e); 12791 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 12792 return nullptr; 12793 12794 FindCaptureVisitor visitor(S.Context, owner.Variable); 12795 visitor.Visit(block->getBlockDecl()->getBody()); 12796 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 12797 } 12798 12799 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 12800 RetainCycleOwner &owner) { 12801 assert(capturer); 12802 assert(owner.Variable && owner.Loc.isValid()); 12803 12804 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 12805 << owner.Variable << capturer->getSourceRange(); 12806 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 12807 << owner.Indirect << owner.Range; 12808 } 12809 12810 /// Check for a keyword selector that starts with the word 'add' or 12811 /// 'set'. 12812 static bool isSetterLikeSelector(Selector sel) { 12813 if (sel.isUnarySelector()) return false; 12814 12815 StringRef str = sel.getNameForSlot(0); 12816 while (!str.empty() && str.front() == '_') str = str.substr(1); 12817 if (str.startswith("set")) 12818 str = str.substr(3); 12819 else if (str.startswith("add")) { 12820 // Specially whitelist 'addOperationWithBlock:'. 12821 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12822 return false; 12823 str = str.substr(3); 12824 } 12825 else 12826 return false; 12827 12828 if (str.empty()) return true; 12829 return !isLowercase(str.front()); 12830 } 12831 12832 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12833 ObjCMessageExpr *Message) { 12834 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12835 Message->getReceiverInterface(), 12836 NSAPI::ClassId_NSMutableArray); 12837 if (!IsMutableArray) { 12838 return None; 12839 } 12840 12841 Selector Sel = Message->getSelector(); 12842 12843 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12844 S.NSAPIObj->getNSArrayMethodKind(Sel); 12845 if (!MKOpt) { 12846 return None; 12847 } 12848 12849 NSAPI::NSArrayMethodKind MK = *MKOpt; 12850 12851 switch (MK) { 12852 case NSAPI::NSMutableArr_addObject: 12853 case NSAPI::NSMutableArr_insertObjectAtIndex: 12854 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12855 return 0; 12856 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12857 return 1; 12858 12859 default: 12860 return None; 12861 } 12862 12863 return None; 12864 } 12865 12866 static 12867 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12868 ObjCMessageExpr *Message) { 12869 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12870 Message->getReceiverInterface(), 12871 NSAPI::ClassId_NSMutableDictionary); 12872 if (!IsMutableDictionary) { 12873 return None; 12874 } 12875 12876 Selector Sel = Message->getSelector(); 12877 12878 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 12879 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 12880 if (!MKOpt) { 12881 return None; 12882 } 12883 12884 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 12885 12886 switch (MK) { 12887 case NSAPI::NSMutableDict_setObjectForKey: 12888 case NSAPI::NSMutableDict_setValueForKey: 12889 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 12890 return 0; 12891 12892 default: 12893 return None; 12894 } 12895 12896 return None; 12897 } 12898 12899 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 12900 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 12901 Message->getReceiverInterface(), 12902 NSAPI::ClassId_NSMutableSet); 12903 12904 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 12905 Message->getReceiverInterface(), 12906 NSAPI::ClassId_NSMutableOrderedSet); 12907 if (!IsMutableSet && !IsMutableOrderedSet) { 12908 return None; 12909 } 12910 12911 Selector Sel = Message->getSelector(); 12912 12913 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 12914 if (!MKOpt) { 12915 return None; 12916 } 12917 12918 NSAPI::NSSetMethodKind MK = *MKOpt; 12919 12920 switch (MK) { 12921 case NSAPI::NSMutableSet_addObject: 12922 case NSAPI::NSOrderedSet_setObjectAtIndex: 12923 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 12924 case NSAPI::NSOrderedSet_insertObjectAtIndex: 12925 return 0; 12926 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 12927 return 1; 12928 } 12929 12930 return None; 12931 } 12932 12933 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 12934 if (!Message->isInstanceMessage()) { 12935 return; 12936 } 12937 12938 Optional<int> ArgOpt; 12939 12940 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 12941 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 12942 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 12943 return; 12944 } 12945 12946 int ArgIndex = *ArgOpt; 12947 12948 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 12949 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 12950 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 12951 } 12952 12953 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 12954 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12955 if (ArgRE->isObjCSelfExpr()) { 12956 Diag(Message->getSourceRange().getBegin(), 12957 diag::warn_objc_circular_container) 12958 << ArgRE->getDecl() << StringRef("'super'"); 12959 } 12960 } 12961 } else { 12962 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 12963 12964 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 12965 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 12966 } 12967 12968 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 12969 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12970 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 12971 ValueDecl *Decl = ReceiverRE->getDecl(); 12972 Diag(Message->getSourceRange().getBegin(), 12973 diag::warn_objc_circular_container) 12974 << Decl << Decl; 12975 if (!ArgRE->isObjCSelfExpr()) { 12976 Diag(Decl->getLocation(), 12977 diag::note_objc_circular_container_declared_here) 12978 << Decl; 12979 } 12980 } 12981 } 12982 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12983 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12984 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12985 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12986 Diag(Message->getSourceRange().getBegin(), 12987 diag::warn_objc_circular_container) 12988 << Decl << Decl; 12989 Diag(Decl->getLocation(), 12990 diag::note_objc_circular_container_declared_here) 12991 << Decl; 12992 } 12993 } 12994 } 12995 } 12996 } 12997 12998 /// Check a message send to see if it's likely to cause a retain cycle. 12999 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13000 // Only check instance methods whose selector looks like a setter. 13001 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13002 return; 13003 13004 // Try to find a variable that the receiver is strongly owned by. 13005 RetainCycleOwner owner; 13006 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13007 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13008 return; 13009 } else { 13010 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13011 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13012 owner.Loc = msg->getSuperLoc(); 13013 owner.Range = msg->getSuperLoc(); 13014 } 13015 13016 // Check whether the receiver is captured by any of the arguments. 13017 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13018 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13019 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13020 // noescape blocks should not be retained by the method. 13021 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13022 continue; 13023 return diagnoseRetainCycle(*this, capturer, owner); 13024 } 13025 } 13026 } 13027 13028 /// Check a property assign to see if it's likely to cause a retain cycle. 13029 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13030 RetainCycleOwner owner; 13031 if (!findRetainCycleOwner(*this, receiver, owner)) 13032 return; 13033 13034 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13035 diagnoseRetainCycle(*this, capturer, owner); 13036 } 13037 13038 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13039 RetainCycleOwner Owner; 13040 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13041 return; 13042 13043 // Because we don't have an expression for the variable, we have to set the 13044 // location explicitly here. 13045 Owner.Loc = Var->getLocation(); 13046 Owner.Range = Var->getSourceRange(); 13047 13048 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13049 diagnoseRetainCycle(*this, Capturer, Owner); 13050 } 13051 13052 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13053 Expr *RHS, bool isProperty) { 13054 // Check if RHS is an Objective-C object literal, which also can get 13055 // immediately zapped in a weak reference. Note that we explicitly 13056 // allow ObjCStringLiterals, since those are designed to never really die. 13057 RHS = RHS->IgnoreParenImpCasts(); 13058 13059 // This enum needs to match with the 'select' in 13060 // warn_objc_arc_literal_assign (off-by-1). 13061 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13062 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13063 return false; 13064 13065 S.Diag(Loc, diag::warn_arc_literal_assign) 13066 << (unsigned) Kind 13067 << (isProperty ? 0 : 1) 13068 << RHS->getSourceRange(); 13069 13070 return true; 13071 } 13072 13073 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13074 Qualifiers::ObjCLifetime LT, 13075 Expr *RHS, bool isProperty) { 13076 // Strip off any implicit cast added to get to the one ARC-specific. 13077 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13078 if (cast->getCastKind() == CK_ARCConsumeObject) { 13079 S.Diag(Loc, diag::warn_arc_retained_assign) 13080 << (LT == Qualifiers::OCL_ExplicitNone) 13081 << (isProperty ? 0 : 1) 13082 << RHS->getSourceRange(); 13083 return true; 13084 } 13085 RHS = cast->getSubExpr(); 13086 } 13087 13088 if (LT == Qualifiers::OCL_Weak && 13089 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13090 return true; 13091 13092 return false; 13093 } 13094 13095 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13096 QualType LHS, Expr *RHS) { 13097 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13098 13099 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13100 return false; 13101 13102 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13103 return true; 13104 13105 return false; 13106 } 13107 13108 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13109 Expr *LHS, Expr *RHS) { 13110 QualType LHSType; 13111 // PropertyRef on LHS type need be directly obtained from 13112 // its declaration as it has a PseudoType. 13113 ObjCPropertyRefExpr *PRE 13114 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13115 if (PRE && !PRE->isImplicitProperty()) { 13116 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13117 if (PD) 13118 LHSType = PD->getType(); 13119 } 13120 13121 if (LHSType.isNull()) 13122 LHSType = LHS->getType(); 13123 13124 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13125 13126 if (LT == Qualifiers::OCL_Weak) { 13127 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13128 getCurFunction()->markSafeWeakUse(LHS); 13129 } 13130 13131 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13132 return; 13133 13134 // FIXME. Check for other life times. 13135 if (LT != Qualifiers::OCL_None) 13136 return; 13137 13138 if (PRE) { 13139 if (PRE->isImplicitProperty()) 13140 return; 13141 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13142 if (!PD) 13143 return; 13144 13145 unsigned Attributes = PD->getPropertyAttributes(); 13146 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13147 // when 'assign' attribute was not explicitly specified 13148 // by user, ignore it and rely on property type itself 13149 // for lifetime info. 13150 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13151 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13152 LHSType->isObjCRetainableType()) 13153 return; 13154 13155 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13156 if (cast->getCastKind() == CK_ARCConsumeObject) { 13157 Diag(Loc, diag::warn_arc_retained_property_assign) 13158 << RHS->getSourceRange(); 13159 return; 13160 } 13161 RHS = cast->getSubExpr(); 13162 } 13163 } 13164 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13165 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13166 return; 13167 } 13168 } 13169 } 13170 13171 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13172 13173 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13174 SourceLocation StmtLoc, 13175 const NullStmt *Body) { 13176 // Do not warn if the body is a macro that expands to nothing, e.g: 13177 // 13178 // #define CALL(x) 13179 // if (condition) 13180 // CALL(0); 13181 if (Body->hasLeadingEmptyMacro()) 13182 return false; 13183 13184 // Get line numbers of statement and body. 13185 bool StmtLineInvalid; 13186 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13187 &StmtLineInvalid); 13188 if (StmtLineInvalid) 13189 return false; 13190 13191 bool BodyLineInvalid; 13192 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13193 &BodyLineInvalid); 13194 if (BodyLineInvalid) 13195 return false; 13196 13197 // Warn if null statement and body are on the same line. 13198 if (StmtLine != BodyLine) 13199 return false; 13200 13201 return true; 13202 } 13203 13204 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13205 const Stmt *Body, 13206 unsigned DiagID) { 13207 // Since this is a syntactic check, don't emit diagnostic for template 13208 // instantiations, this just adds noise. 13209 if (CurrentInstantiationScope) 13210 return; 13211 13212 // The body should be a null statement. 13213 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13214 if (!NBody) 13215 return; 13216 13217 // Do the usual checks. 13218 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13219 return; 13220 13221 Diag(NBody->getSemiLoc(), DiagID); 13222 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13223 } 13224 13225 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13226 const Stmt *PossibleBody) { 13227 assert(!CurrentInstantiationScope); // Ensured by caller 13228 13229 SourceLocation StmtLoc; 13230 const Stmt *Body; 13231 unsigned DiagID; 13232 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13233 StmtLoc = FS->getRParenLoc(); 13234 Body = FS->getBody(); 13235 DiagID = diag::warn_empty_for_body; 13236 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13237 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13238 Body = WS->getBody(); 13239 DiagID = diag::warn_empty_while_body; 13240 } else 13241 return; // Neither `for' nor `while'. 13242 13243 // The body should be a null statement. 13244 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13245 if (!NBody) 13246 return; 13247 13248 // Skip expensive checks if diagnostic is disabled. 13249 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13250 return; 13251 13252 // Do the usual checks. 13253 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13254 return; 13255 13256 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13257 // noise level low, emit diagnostics only if for/while is followed by a 13258 // CompoundStmt, e.g.: 13259 // for (int i = 0; i < n; i++); 13260 // { 13261 // a(i); 13262 // } 13263 // or if for/while is followed by a statement with more indentation 13264 // than for/while itself: 13265 // for (int i = 0; i < n; i++); 13266 // a(i); 13267 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13268 if (!ProbableTypo) { 13269 bool BodyColInvalid; 13270 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13271 PossibleBody->getBeginLoc(), &BodyColInvalid); 13272 if (BodyColInvalid) 13273 return; 13274 13275 bool StmtColInvalid; 13276 unsigned StmtCol = 13277 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13278 if (StmtColInvalid) 13279 return; 13280 13281 if (BodyCol > StmtCol) 13282 ProbableTypo = true; 13283 } 13284 13285 if (ProbableTypo) { 13286 Diag(NBody->getSemiLoc(), DiagID); 13287 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13288 } 13289 } 13290 13291 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13292 13293 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13294 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13295 SourceLocation OpLoc) { 13296 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13297 return; 13298 13299 if (inTemplateInstantiation()) 13300 return; 13301 13302 // Strip parens and casts away. 13303 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13304 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13305 13306 // Check for a call expression 13307 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13308 if (!CE || CE->getNumArgs() != 1) 13309 return; 13310 13311 // Check for a call to std::move 13312 if (!CE->isCallToStdMove()) 13313 return; 13314 13315 // Get argument from std::move 13316 RHSExpr = CE->getArg(0); 13317 13318 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13319 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13320 13321 // Two DeclRefExpr's, check that the decls are the same. 13322 if (LHSDeclRef && RHSDeclRef) { 13323 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13324 return; 13325 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13326 RHSDeclRef->getDecl()->getCanonicalDecl()) 13327 return; 13328 13329 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13330 << LHSExpr->getSourceRange() 13331 << RHSExpr->getSourceRange(); 13332 return; 13333 } 13334 13335 // Member variables require a different approach to check for self moves. 13336 // MemberExpr's are the same if every nested MemberExpr refers to the same 13337 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13338 // the base Expr's are CXXThisExpr's. 13339 const Expr *LHSBase = LHSExpr; 13340 const Expr *RHSBase = RHSExpr; 13341 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13342 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13343 if (!LHSME || !RHSME) 13344 return; 13345 13346 while (LHSME && RHSME) { 13347 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13348 RHSME->getMemberDecl()->getCanonicalDecl()) 13349 return; 13350 13351 LHSBase = LHSME->getBase(); 13352 RHSBase = RHSME->getBase(); 13353 LHSME = dyn_cast<MemberExpr>(LHSBase); 13354 RHSME = dyn_cast<MemberExpr>(RHSBase); 13355 } 13356 13357 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13358 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13359 if (LHSDeclRef && RHSDeclRef) { 13360 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13361 return; 13362 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13363 RHSDeclRef->getDecl()->getCanonicalDecl()) 13364 return; 13365 13366 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13367 << LHSExpr->getSourceRange() 13368 << RHSExpr->getSourceRange(); 13369 return; 13370 } 13371 13372 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13373 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13374 << LHSExpr->getSourceRange() 13375 << RHSExpr->getSourceRange(); 13376 } 13377 13378 //===--- Layout compatibility ----------------------------------------------// 13379 13380 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13381 13382 /// Check if two enumeration types are layout-compatible. 13383 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13384 // C++11 [dcl.enum] p8: 13385 // Two enumeration types are layout-compatible if they have the same 13386 // underlying type. 13387 return ED1->isComplete() && ED2->isComplete() && 13388 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13389 } 13390 13391 /// Check if two fields are layout-compatible. 13392 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13393 FieldDecl *Field2) { 13394 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13395 return false; 13396 13397 if (Field1->isBitField() != Field2->isBitField()) 13398 return false; 13399 13400 if (Field1->isBitField()) { 13401 // Make sure that the bit-fields are the same length. 13402 unsigned Bits1 = Field1->getBitWidthValue(C); 13403 unsigned Bits2 = Field2->getBitWidthValue(C); 13404 13405 if (Bits1 != Bits2) 13406 return false; 13407 } 13408 13409 return true; 13410 } 13411 13412 /// Check if two standard-layout structs are layout-compatible. 13413 /// (C++11 [class.mem] p17) 13414 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13415 RecordDecl *RD2) { 13416 // If both records are C++ classes, check that base classes match. 13417 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13418 // If one of records is a CXXRecordDecl we are in C++ mode, 13419 // thus the other one is a CXXRecordDecl, too. 13420 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13421 // Check number of base classes. 13422 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13423 return false; 13424 13425 // Check the base classes. 13426 for (CXXRecordDecl::base_class_const_iterator 13427 Base1 = D1CXX->bases_begin(), 13428 BaseEnd1 = D1CXX->bases_end(), 13429 Base2 = D2CXX->bases_begin(); 13430 Base1 != BaseEnd1; 13431 ++Base1, ++Base2) { 13432 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13433 return false; 13434 } 13435 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13436 // If only RD2 is a C++ class, it should have zero base classes. 13437 if (D2CXX->getNumBases() > 0) 13438 return false; 13439 } 13440 13441 // Check the fields. 13442 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13443 Field2End = RD2->field_end(), 13444 Field1 = RD1->field_begin(), 13445 Field1End = RD1->field_end(); 13446 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13447 if (!isLayoutCompatible(C, *Field1, *Field2)) 13448 return false; 13449 } 13450 if (Field1 != Field1End || Field2 != Field2End) 13451 return false; 13452 13453 return true; 13454 } 13455 13456 /// Check if two standard-layout unions are layout-compatible. 13457 /// (C++11 [class.mem] p18) 13458 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13459 RecordDecl *RD2) { 13460 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13461 for (auto *Field2 : RD2->fields()) 13462 UnmatchedFields.insert(Field2); 13463 13464 for (auto *Field1 : RD1->fields()) { 13465 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13466 I = UnmatchedFields.begin(), 13467 E = UnmatchedFields.end(); 13468 13469 for ( ; I != E; ++I) { 13470 if (isLayoutCompatible(C, Field1, *I)) { 13471 bool Result = UnmatchedFields.erase(*I); 13472 (void) Result; 13473 assert(Result); 13474 break; 13475 } 13476 } 13477 if (I == E) 13478 return false; 13479 } 13480 13481 return UnmatchedFields.empty(); 13482 } 13483 13484 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13485 RecordDecl *RD2) { 13486 if (RD1->isUnion() != RD2->isUnion()) 13487 return false; 13488 13489 if (RD1->isUnion()) 13490 return isLayoutCompatibleUnion(C, RD1, RD2); 13491 else 13492 return isLayoutCompatibleStruct(C, RD1, RD2); 13493 } 13494 13495 /// Check if two types are layout-compatible in C++11 sense. 13496 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13497 if (T1.isNull() || T2.isNull()) 13498 return false; 13499 13500 // C++11 [basic.types] p11: 13501 // If two types T1 and T2 are the same type, then T1 and T2 are 13502 // layout-compatible types. 13503 if (C.hasSameType(T1, T2)) 13504 return true; 13505 13506 T1 = T1.getCanonicalType().getUnqualifiedType(); 13507 T2 = T2.getCanonicalType().getUnqualifiedType(); 13508 13509 const Type::TypeClass TC1 = T1->getTypeClass(); 13510 const Type::TypeClass TC2 = T2->getTypeClass(); 13511 13512 if (TC1 != TC2) 13513 return false; 13514 13515 if (TC1 == Type::Enum) { 13516 return isLayoutCompatible(C, 13517 cast<EnumType>(T1)->getDecl(), 13518 cast<EnumType>(T2)->getDecl()); 13519 } else if (TC1 == Type::Record) { 13520 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13521 return false; 13522 13523 return isLayoutCompatible(C, 13524 cast<RecordType>(T1)->getDecl(), 13525 cast<RecordType>(T2)->getDecl()); 13526 } 13527 13528 return false; 13529 } 13530 13531 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13532 13533 /// Given a type tag expression find the type tag itself. 13534 /// 13535 /// \param TypeExpr Type tag expression, as it appears in user's code. 13536 /// 13537 /// \param VD Declaration of an identifier that appears in a type tag. 13538 /// 13539 /// \param MagicValue Type tag magic value. 13540 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13541 const ValueDecl **VD, uint64_t *MagicValue) { 13542 while(true) { 13543 if (!TypeExpr) 13544 return false; 13545 13546 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13547 13548 switch (TypeExpr->getStmtClass()) { 13549 case Stmt::UnaryOperatorClass: { 13550 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13551 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13552 TypeExpr = UO->getSubExpr(); 13553 continue; 13554 } 13555 return false; 13556 } 13557 13558 case Stmt::DeclRefExprClass: { 13559 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 13560 *VD = DRE->getDecl(); 13561 return true; 13562 } 13563 13564 case Stmt::IntegerLiteralClass: { 13565 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 13566 llvm::APInt MagicValueAPInt = IL->getValue(); 13567 if (MagicValueAPInt.getActiveBits() <= 64) { 13568 *MagicValue = MagicValueAPInt.getZExtValue(); 13569 return true; 13570 } else 13571 return false; 13572 } 13573 13574 case Stmt::BinaryConditionalOperatorClass: 13575 case Stmt::ConditionalOperatorClass: { 13576 const AbstractConditionalOperator *ACO = 13577 cast<AbstractConditionalOperator>(TypeExpr); 13578 bool Result; 13579 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 13580 if (Result) 13581 TypeExpr = ACO->getTrueExpr(); 13582 else 13583 TypeExpr = ACO->getFalseExpr(); 13584 continue; 13585 } 13586 return false; 13587 } 13588 13589 case Stmt::BinaryOperatorClass: { 13590 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 13591 if (BO->getOpcode() == BO_Comma) { 13592 TypeExpr = BO->getRHS(); 13593 continue; 13594 } 13595 return false; 13596 } 13597 13598 default: 13599 return false; 13600 } 13601 } 13602 } 13603 13604 /// Retrieve the C type corresponding to type tag TypeExpr. 13605 /// 13606 /// \param TypeExpr Expression that specifies a type tag. 13607 /// 13608 /// \param MagicValues Registered magic values. 13609 /// 13610 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 13611 /// kind. 13612 /// 13613 /// \param TypeInfo Information about the corresponding C type. 13614 /// 13615 /// \returns true if the corresponding C type was found. 13616 static bool GetMatchingCType( 13617 const IdentifierInfo *ArgumentKind, 13618 const Expr *TypeExpr, const ASTContext &Ctx, 13619 const llvm::DenseMap<Sema::TypeTagMagicValue, 13620 Sema::TypeTagData> *MagicValues, 13621 bool &FoundWrongKind, 13622 Sema::TypeTagData &TypeInfo) { 13623 FoundWrongKind = false; 13624 13625 // Variable declaration that has type_tag_for_datatype attribute. 13626 const ValueDecl *VD = nullptr; 13627 13628 uint64_t MagicValue; 13629 13630 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 13631 return false; 13632 13633 if (VD) { 13634 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 13635 if (I->getArgumentKind() != ArgumentKind) { 13636 FoundWrongKind = true; 13637 return false; 13638 } 13639 TypeInfo.Type = I->getMatchingCType(); 13640 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 13641 TypeInfo.MustBeNull = I->getMustBeNull(); 13642 return true; 13643 } 13644 return false; 13645 } 13646 13647 if (!MagicValues) 13648 return false; 13649 13650 llvm::DenseMap<Sema::TypeTagMagicValue, 13651 Sema::TypeTagData>::const_iterator I = 13652 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 13653 if (I == MagicValues->end()) 13654 return false; 13655 13656 TypeInfo = I->second; 13657 return true; 13658 } 13659 13660 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 13661 uint64_t MagicValue, QualType Type, 13662 bool LayoutCompatible, 13663 bool MustBeNull) { 13664 if (!TypeTagForDatatypeMagicValues) 13665 TypeTagForDatatypeMagicValues.reset( 13666 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 13667 13668 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 13669 (*TypeTagForDatatypeMagicValues)[Magic] = 13670 TypeTagData(Type, LayoutCompatible, MustBeNull); 13671 } 13672 13673 static bool IsSameCharType(QualType T1, QualType T2) { 13674 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 13675 if (!BT1) 13676 return false; 13677 13678 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 13679 if (!BT2) 13680 return false; 13681 13682 BuiltinType::Kind T1Kind = BT1->getKind(); 13683 BuiltinType::Kind T2Kind = BT2->getKind(); 13684 13685 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 13686 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 13687 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 13688 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 13689 } 13690 13691 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 13692 const ArrayRef<const Expr *> ExprArgs, 13693 SourceLocation CallSiteLoc) { 13694 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 13695 bool IsPointerAttr = Attr->getIsPointer(); 13696 13697 // Retrieve the argument representing the 'type_tag'. 13698 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 13699 if (TypeTagIdxAST >= ExprArgs.size()) { 13700 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13701 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 13702 return; 13703 } 13704 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 13705 bool FoundWrongKind; 13706 TypeTagData TypeInfo; 13707 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 13708 TypeTagForDatatypeMagicValues.get(), 13709 FoundWrongKind, TypeInfo)) { 13710 if (FoundWrongKind) 13711 Diag(TypeTagExpr->getExprLoc(), 13712 diag::warn_type_tag_for_datatype_wrong_kind) 13713 << TypeTagExpr->getSourceRange(); 13714 return; 13715 } 13716 13717 // Retrieve the argument representing the 'arg_idx'. 13718 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 13719 if (ArgumentIdxAST >= ExprArgs.size()) { 13720 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13721 << 1 << Attr->getArgumentIdx().getSourceIndex(); 13722 return; 13723 } 13724 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 13725 if (IsPointerAttr) { 13726 // Skip implicit cast of pointer to `void *' (as a function argument). 13727 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 13728 if (ICE->getType()->isVoidPointerType() && 13729 ICE->getCastKind() == CK_BitCast) 13730 ArgumentExpr = ICE->getSubExpr(); 13731 } 13732 QualType ArgumentType = ArgumentExpr->getType(); 13733 13734 // Passing a `void*' pointer shouldn't trigger a warning. 13735 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 13736 return; 13737 13738 if (TypeInfo.MustBeNull) { 13739 // Type tag with matching void type requires a null pointer. 13740 if (!ArgumentExpr->isNullPointerConstant(Context, 13741 Expr::NPC_ValueDependentIsNotNull)) { 13742 Diag(ArgumentExpr->getExprLoc(), 13743 diag::warn_type_safety_null_pointer_required) 13744 << ArgumentKind->getName() 13745 << ArgumentExpr->getSourceRange() 13746 << TypeTagExpr->getSourceRange(); 13747 } 13748 return; 13749 } 13750 13751 QualType RequiredType = TypeInfo.Type; 13752 if (IsPointerAttr) 13753 RequiredType = Context.getPointerType(RequiredType); 13754 13755 bool mismatch = false; 13756 if (!TypeInfo.LayoutCompatible) { 13757 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 13758 13759 // C++11 [basic.fundamental] p1: 13760 // Plain char, signed char, and unsigned char are three distinct types. 13761 // 13762 // But we treat plain `char' as equivalent to `signed char' or `unsigned 13763 // char' depending on the current char signedness mode. 13764 if (mismatch) 13765 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 13766 RequiredType->getPointeeType())) || 13767 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 13768 mismatch = false; 13769 } else 13770 if (IsPointerAttr) 13771 mismatch = !isLayoutCompatible(Context, 13772 ArgumentType->getPointeeType(), 13773 RequiredType->getPointeeType()); 13774 else 13775 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 13776 13777 if (mismatch) 13778 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 13779 << ArgumentType << ArgumentKind 13780 << TypeInfo.LayoutCompatible << RequiredType 13781 << ArgumentExpr->getSourceRange() 13782 << TypeTagExpr->getSourceRange(); 13783 } 13784 13785 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 13786 CharUnits Alignment) { 13787 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 13788 } 13789 13790 void Sema::DiagnoseMisalignedMembers() { 13791 for (MisalignedMember &m : MisalignedMembers) { 13792 const NamedDecl *ND = m.RD; 13793 if (ND->getName().empty()) { 13794 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 13795 ND = TD; 13796 } 13797 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 13798 << m.MD << ND << m.E->getSourceRange(); 13799 } 13800 MisalignedMembers.clear(); 13801 } 13802 13803 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 13804 E = E->IgnoreParens(); 13805 if (!T->isPointerType() && !T->isIntegerType()) 13806 return; 13807 if (isa<UnaryOperator>(E) && 13808 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13809 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13810 if (isa<MemberExpr>(Op)) { 13811 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 13812 MisalignedMember(Op)); 13813 if (MA != MisalignedMembers.end() && 13814 (T->isIntegerType() || 13815 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13816 Context.getTypeAlignInChars( 13817 T->getPointeeType()) <= MA->Alignment)))) 13818 MisalignedMembers.erase(MA); 13819 } 13820 } 13821 } 13822 13823 void Sema::RefersToMemberWithReducedAlignment( 13824 Expr *E, 13825 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13826 Action) { 13827 const auto *ME = dyn_cast<MemberExpr>(E); 13828 if (!ME) 13829 return; 13830 13831 // No need to check expressions with an __unaligned-qualified type. 13832 if (E->getType().getQualifiers().hasUnaligned()) 13833 return; 13834 13835 // For a chain of MemberExpr like "a.b.c.d" this list 13836 // will keep FieldDecl's like [d, c, b]. 13837 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13838 const MemberExpr *TopME = nullptr; 13839 bool AnyIsPacked = false; 13840 do { 13841 QualType BaseType = ME->getBase()->getType(); 13842 if (ME->isArrow()) 13843 BaseType = BaseType->getPointeeType(); 13844 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13845 if (RD->isInvalidDecl()) 13846 return; 13847 13848 ValueDecl *MD = ME->getMemberDecl(); 13849 auto *FD = dyn_cast<FieldDecl>(MD); 13850 // We do not care about non-data members. 13851 if (!FD || FD->isInvalidDecl()) 13852 return; 13853 13854 AnyIsPacked = 13855 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13856 ReverseMemberChain.push_back(FD); 13857 13858 TopME = ME; 13859 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13860 } while (ME); 13861 assert(TopME && "We did not compute a topmost MemberExpr!"); 13862 13863 // Not the scope of this diagnostic. 13864 if (!AnyIsPacked) 13865 return; 13866 13867 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13868 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13869 // TODO: The innermost base of the member expression may be too complicated. 13870 // For now, just disregard these cases. This is left for future 13871 // improvement. 13872 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13873 return; 13874 13875 // Alignment expected by the whole expression. 13876 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13877 13878 // No need to do anything else with this case. 13879 if (ExpectedAlignment.isOne()) 13880 return; 13881 13882 // Synthesize offset of the whole access. 13883 CharUnits Offset; 13884 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 13885 I++) { 13886 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 13887 } 13888 13889 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 13890 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 13891 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 13892 13893 // The base expression of the innermost MemberExpr may give 13894 // stronger guarantees than the class containing the member. 13895 if (DRE && !TopME->isArrow()) { 13896 const ValueDecl *VD = DRE->getDecl(); 13897 if (!VD->getType()->isReferenceType()) 13898 CompleteObjectAlignment = 13899 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 13900 } 13901 13902 // Check if the synthesized offset fulfills the alignment. 13903 if (Offset % ExpectedAlignment != 0 || 13904 // It may fulfill the offset it but the effective alignment may still be 13905 // lower than the expected expression alignment. 13906 CompleteObjectAlignment < ExpectedAlignment) { 13907 // If this happens, we want to determine a sensible culprit of this. 13908 // Intuitively, watching the chain of member expressions from right to 13909 // left, we start with the required alignment (as required by the field 13910 // type) but some packed attribute in that chain has reduced the alignment. 13911 // It may happen that another packed structure increases it again. But if 13912 // we are here such increase has not been enough. So pointing the first 13913 // FieldDecl that either is packed or else its RecordDecl is, 13914 // seems reasonable. 13915 FieldDecl *FD = nullptr; 13916 CharUnits Alignment; 13917 for (FieldDecl *FDI : ReverseMemberChain) { 13918 if (FDI->hasAttr<PackedAttr>() || 13919 FDI->getParent()->hasAttr<PackedAttr>()) { 13920 FD = FDI; 13921 Alignment = std::min( 13922 Context.getTypeAlignInChars(FD->getType()), 13923 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 13924 break; 13925 } 13926 } 13927 assert(FD && "We did not find a packed FieldDecl!"); 13928 Action(E, FD->getParent(), FD, Alignment); 13929 } 13930 } 13931 13932 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 13933 using namespace std::placeholders; 13934 13935 RefersToMemberWithReducedAlignment( 13936 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 13937 _2, _3, _4)); 13938 } 13939